mirror of
https://github.com/openclaw/openclaw.git
synced 2026-06-06 05:51:15 +08:00
chore: stop tracking package dist output
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -42,6 +42,7 @@ apps/macos-mlx-tts/.build/
|
|||||||
apps/shared/MoltbotKit/.build/
|
apps/shared/MoltbotKit/.build/
|
||||||
apps/shared/OpenClawKit/.build/
|
apps/shared/OpenClawKit/.build/
|
||||||
apps/shared/*/.build/
|
apps/shared/*/.build/
|
||||||
|
packages/*/dist/
|
||||||
apps/shared/OpenClawKit/Package.resolved
|
apps/shared/OpenClawKit/Package.resolved
|
||||||
**/ModuleCache/
|
**/ModuleCache/
|
||||||
bin/
|
bin/
|
||||||
|
|||||||
10
packages/acp-core/dist/error-format.d.mts
vendored
10
packages/acp-core/dist/error-format.d.mts
vendored
@@ -1,10 +0,0 @@
|
|||||||
//#region src/error-format.d.ts
|
|
||||||
declare function configureAcpErrorRedactor(redactor: ((value: string) => string) | undefined): void;
|
|
||||||
declare function redactSensitiveText(value: string): string;
|
|
||||||
/**
|
|
||||||
* Render a non-Error `cause` value without leaking `[object Object]` or throwing
|
|
||||||
* while formatting nested ACP runtime failures.
|
|
||||||
*/
|
|
||||||
declare function stringifyNonErrorCause(value: unknown): string;
|
|
||||||
//#endregion
|
|
||||||
export { configureAcpErrorRedactor, redactSensitiveText, stringifyNonErrorCause };
|
|
||||||
64
packages/acp-core/dist/error-format.mjs
vendored
64
packages/acp-core/dist/error-format.mjs
vendored
@@ -1,64 +0,0 @@
|
|||||||
//#region src/error-format.ts
|
|
||||||
const SECRET_PATTERNS = [
|
|
||||||
/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN)\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g,
|
|
||||||
/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN)\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g,
|
|
||||||
/[?&](?:access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|api[-_]?key|client[-_]?secret|token|key|secret|password|pass|passwd|auth|signature|card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token)=([^&\s"'<>]+)/gi,
|
|
||||||
/"(?:apiKey|token|secret|password|passwd|accessToken|refreshToken|cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token)"\s*:\s*"([^"]+)"/g,
|
|
||||||
/(^|[\s,{])["']?(?:api[-_]key|access[-_]token|refresh[-_]token|authToken|auth[-_]token|clientSecret|client[-_]secret|appSecret|app[-_]secret)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2/gi,
|
|
||||||
/(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2/gi,
|
|
||||||
/--(?:api[-_]?key|hook[-_]?token|token|secret|password|passwd|card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token)\s+(["']?)([^\s"']+)\1/gi,
|
|
||||||
/Authorization\s*[:=]\s*Bearer\s+([A-Za-z0-9._\-+=]+)/gi,
|
|
||||||
/Authorization\s*[:=]\s*Basic\s+([A-Za-z0-9+/=]+)/gi,
|
|
||||||
/(?:X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token)\s*[:=]\s*([^\s"',;]+)/gi,
|
|
||||||
/\bBearer\s+([A-Za-z0-9._\-+=]{18,})\b/g,
|
|
||||||
/(^|[\s,;])(?:access_token|refresh_token|auth[-_]?token|api[-_]?key|client[-_]?secret|app[-_]?secret|token|secret|password|passwd|card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token)=([^\s&#]+)/gi,
|
|
||||||
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
||||||
/\b(sk-[A-Za-z0-9_-]{8,})\b/g,
|
|
||||||
/(ghp_[A-Za-z0-9]{20,})/g,
|
|
||||||
/(github_pat_[A-Za-z0-9_]{20,})/g,
|
|
||||||
/(xox[baprs]-[A-Za-z0-9-]{10,})/g,
|
|
||||||
/(xapp-[A-Za-z0-9-]{10,})/g,
|
|
||||||
/(gsk_[A-Za-z0-9_-]{10,})/g,
|
|
||||||
/(AIza[0-9A-Za-z\-_]{20,})/g,
|
|
||||||
/(ya29\.[0-9A-Za-z_\-./+=]{10,})/g,
|
|
||||||
/(1\/\/0[0-9A-Za-z_\-./+=]{10,})/g,
|
|
||||||
/(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})/g,
|
|
||||||
/(pplx-[A-Za-z0-9_-]{10,})/g,
|
|
||||||
/(npm_[A-Za-z0-9]{10,})/g,
|
|
||||||
/(AKID[A-Za-z0-9]{10,})/g,
|
|
||||||
/(LTAI[A-Za-z0-9]{10,})/g,
|
|
||||||
/(hf_[A-Za-z0-9]{10,})/g,
|
|
||||||
/(r8_[A-Za-z0-9]{10,})/g,
|
|
||||||
/\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b/g,
|
|
||||||
/\b(\d{6,}:[A-Za-z0-9_-]{20,})\b/g
|
|
||||||
];
|
|
||||||
let configuredRedactor;
|
|
||||||
function configureAcpErrorRedactor(redactor) {
|
|
||||||
configuredRedactor = redactor;
|
|
||||||
}
|
|
||||||
function redactSensitiveText(value) {
|
|
||||||
if (configuredRedactor) return configuredRedactor(value);
|
|
||||||
let redacted = value;
|
|
||||||
for (const pattern of SECRET_PATTERNS) redacted = redacted.replace(pattern, (match, ...args) => {
|
|
||||||
if (match.includes("PRIVATE KEY-----")) return "[REDACTED_PRIVATE_KEY]";
|
|
||||||
const token = args.slice(0, -2).findLast((group) => typeof group === "string" && group.length > 0);
|
|
||||||
return token ? match.replace(token, "[REDACTED]") : "[REDACTED]";
|
|
||||||
});
|
|
||||||
return redacted;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Render a non-Error `cause` value without leaking `[object Object]` or throwing
|
|
||||||
* while formatting nested ACP runtime failures.
|
|
||||||
*/
|
|
||||||
function stringifyNonErrorCause(value) {
|
|
||||||
if (value === null) return "null";
|
|
||||||
if (typeof value === "string") return value;
|
|
||||||
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
||||||
try {
|
|
||||||
return JSON.stringify(value);
|
|
||||||
} catch {
|
|
||||||
return Object.prototype.toString.call(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { configureAcpErrorRedactor, redactSensitiveText, stringifyNonErrorCause };
|
|
||||||
15
packages/acp-core/dist/index.d.mts
vendored
15
packages/acp-core/dist/index.d.mts
vendored
@@ -1,15 +0,0 @@
|
|||||||
import { configureAcpErrorRedactor, redactSensitiveText, stringifyNonErrorCause } from "./error-format.mjs";
|
|
||||||
import { readBool, readNonNegativeInteger, readNumber, readString } from "./meta.mjs";
|
|
||||||
import { normalizeText } from "./normalize-text.mjs";
|
|
||||||
import { resolveIntegerOption } from "./numeric-options.mjs";
|
|
||||||
import { asRecord } from "./record-shared.mjs";
|
|
||||||
import { isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession } from "./session-interaction-mode.mjs";
|
|
||||||
import { AcpSessionLineageMeta, AcpSessionLineageRow, toAcpSessionLineageMeta } from "./session-lineage-meta.mjs";
|
|
||||||
import { AcpProvenanceMode, AcpServerOptions, AcpSession, AcpSessionRuntimeOptions, SessionAcpIdentity, SessionAcpIdentitySource, SessionAcpIdentityState, SessionAcpMeta, SessionId, normalizeAcpProvenanceMode } from "./types.mjs";
|
|
||||||
import { AcpSessionStore, createInMemorySessionStore, defaultAcpSessionStore } from "./session.mjs";
|
|
||||||
import { ACP_ERROR_CODES, AcpRuntimeError, AcpRuntimeErrorCode, formatAcpErrorChain, isAcpRuntimeError, toAcpRuntimeError, withAcpRuntimeErrorBoundary } from "./runtime/errors.mjs";
|
|
||||||
import { formatAcpRuntimeErrorText, toAcpRuntimeErrorText } from "./runtime/error-text.mjs";
|
|
||||||
import { ACP_SESSION_IDENTITY_RENDERER_VERSION, AcpSessionIdentifierRenderMode, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines } from "./runtime/session-identifiers.mjs";
|
|
||||||
import { AcpRuntime, AcpRuntimeCapabilities, AcpRuntimeControl, AcpRuntimeDoctorReport, AcpRuntimeEnsureInput, AcpRuntimeEvent, AcpRuntimeHandle, AcpRuntimePromptMode, AcpRuntimeSessionMode, AcpRuntimeStatus, AcpRuntimeTurn, AcpRuntimeTurnAttachment, AcpRuntimeTurnInput, AcpRuntimeTurnResult, AcpRuntimeTurnResultError, AcpSessionUpdateTag } from "./runtime/types.mjs";
|
|
||||||
import { createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, identityEquals, identityHasStableSessionId, isSessionIdentityPending, mergeSessionIdentity, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta } from "./runtime/session-identity.mjs";
|
|
||||||
export { ACP_ERROR_CODES, ACP_SESSION_IDENTITY_RENDERER_VERSION, AcpProvenanceMode, AcpRuntime, AcpRuntimeCapabilities, AcpRuntimeControl, AcpRuntimeDoctorReport, AcpRuntimeEnsureInput, AcpRuntimeError, AcpRuntimeErrorCode, AcpRuntimeEvent, AcpRuntimeHandle, AcpRuntimePromptMode, AcpRuntimeSessionMode, AcpRuntimeStatus, AcpRuntimeTurn, AcpRuntimeTurnAttachment, AcpRuntimeTurnInput, AcpRuntimeTurnResult, AcpRuntimeTurnResultError, AcpServerOptions, AcpSession, AcpSessionIdentifierRenderMode, AcpSessionLineageMeta, AcpSessionLineageRow, AcpSessionRuntimeOptions, AcpSessionStore, AcpSessionUpdateTag, SessionAcpIdentity, SessionAcpIdentitySource, SessionAcpIdentityState, SessionAcpMeta, SessionId, asRecord, configureAcpErrorRedactor, createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, createInMemorySessionStore, defaultAcpSessionStore, formatAcpErrorChain, formatAcpRuntimeErrorText, identityEquals, identityHasStableSessionId, isAcpRuntimeError, isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession, isSessionIdentityPending, mergeSessionIdentity, normalizeAcpProvenanceMode, normalizeText, readBool, readNonNegativeInteger, readNumber, readString, redactSensitiveText, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines, resolveIntegerOption, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta, stringifyNonErrorCause, toAcpRuntimeError, toAcpRuntimeErrorText, toAcpSessionLineageMeta, withAcpRuntimeErrorBoundary };
|
|
||||||
15
packages/acp-core/dist/index.mjs
vendored
15
packages/acp-core/dist/index.mjs
vendored
@@ -1,15 +0,0 @@
|
|||||||
import { configureAcpErrorRedactor, redactSensitiveText, stringifyNonErrorCause } from "./error-format.mjs";
|
|
||||||
import { readBool, readNonNegativeInteger, readNumber, readString } from "./meta.mjs";
|
|
||||||
import { normalizeText } from "./normalize-text.mjs";
|
|
||||||
import { resolveIntegerOption } from "./numeric-options.mjs";
|
|
||||||
import { asRecord } from "./record-shared.mjs";
|
|
||||||
import { isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession } from "./session-interaction-mode.mjs";
|
|
||||||
import { toAcpSessionLineageMeta } from "./session-lineage-meta.mjs";
|
|
||||||
import { createInMemorySessionStore, defaultAcpSessionStore } from "./session.mjs";
|
|
||||||
import { normalizeAcpProvenanceMode } from "./types.mjs";
|
|
||||||
import { ACP_ERROR_CODES, AcpRuntimeError, formatAcpErrorChain, isAcpRuntimeError, toAcpRuntimeError, withAcpRuntimeErrorBoundary } from "./runtime/errors.mjs";
|
|
||||||
import { formatAcpRuntimeErrorText, toAcpRuntimeErrorText } from "./runtime/error-text.mjs";
|
|
||||||
import { createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, identityEquals, identityHasStableSessionId, isSessionIdentityPending, mergeSessionIdentity, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta } from "./runtime/session-identity.mjs";
|
|
||||||
import { ACP_SESSION_IDENTITY_RENDERER_VERSION, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines } from "./runtime/session-identifiers.mjs";
|
|
||||||
import "./runtime/types.mjs";
|
|
||||||
export { ACP_ERROR_CODES, ACP_SESSION_IDENTITY_RENDERER_VERSION, AcpRuntimeError, asRecord, configureAcpErrorRedactor, createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, createInMemorySessionStore, defaultAcpSessionStore, formatAcpErrorChain, formatAcpRuntimeErrorText, identityEquals, identityHasStableSessionId, isAcpRuntimeError, isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession, isSessionIdentityPending, mergeSessionIdentity, normalizeAcpProvenanceMode, normalizeText, readBool, readNonNegativeInteger, readNumber, readString, redactSensitiveText, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines, resolveIntegerOption, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta, stringifyNonErrorCause, toAcpRuntimeError, toAcpRuntimeErrorText, toAcpSessionLineageMeta, withAcpRuntimeErrorBoundary };
|
|
||||||
7
packages/acp-core/dist/meta.d.mts
vendored
7
packages/acp-core/dist/meta.d.mts
vendored
@@ -1,7 +0,0 @@
|
|||||||
//#region src/meta.d.ts
|
|
||||||
declare function readString(meta: Record<string, unknown> | null | undefined, keys: string[]): string | undefined;
|
|
||||||
declare function readBool(meta: Record<string, unknown> | null | undefined, keys: string[]): boolean | undefined;
|
|
||||||
declare function readNumber(meta: Record<string, unknown> | null | undefined, keys: string[]): number | undefined;
|
|
||||||
declare function readNonNegativeInteger(meta: Record<string, unknown> | null | undefined, keys: string[]): number | undefined;
|
|
||||||
//#endregion
|
|
||||||
export { readBool, readNonNegativeInteger, readNumber, readString };
|
|
||||||
23
packages/acp-core/dist/meta.mjs
vendored
23
packages/acp-core/dist/meta.mjs
vendored
@@ -1,23 +0,0 @@
|
|||||||
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
//#region src/meta.ts
|
|
||||||
function readMetaValue(meta, keys, normalize) {
|
|
||||||
if (!meta) return;
|
|
||||||
for (const key of keys) {
|
|
||||||
const normalized = normalize(meta[key]);
|
|
||||||
if (normalized !== void 0) return normalized;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function readString(meta, keys) {
|
|
||||||
return readMetaValue(meta, keys, normalizeOptionalString);
|
|
||||||
}
|
|
||||||
function readBool(meta, keys) {
|
|
||||||
return readMetaValue(meta, keys, (value) => typeof value === "boolean" ? value : void 0);
|
|
||||||
}
|
|
||||||
function readNumber(meta, keys) {
|
|
||||||
return readMetaValue(meta, keys, (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0);
|
|
||||||
}
|
|
||||||
function readNonNegativeInteger(meta, keys) {
|
|
||||||
return readMetaValue(meta, keys, (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { readBool, readNonNegativeInteger, readNumber, readString };
|
|
||||||
2
packages/acp-core/dist/normalize-text.d.mts
vendored
2
packages/acp-core/dist/normalize-text.d.mts
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { normalizeOptionalString as normalizeText } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
export { normalizeText };
|
|
||||||
2
packages/acp-core/dist/normalize-text.mjs
vendored
2
packages/acp-core/dist/normalize-text.mjs
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { normalizeOptionalString as normalizeText } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
export { normalizeText };
|
|
||||||
6
packages/acp-core/dist/numeric-options.d.mts
vendored
6
packages/acp-core/dist/numeric-options.d.mts
vendored
@@ -1,6 +0,0 @@
|
|||||||
//#region src/numeric-options.d.ts
|
|
||||||
declare function resolveIntegerOption(value: number | undefined, fallback: number, params: {
|
|
||||||
min: number;
|
|
||||||
}): number;
|
|
||||||
//#endregion
|
|
||||||
export { resolveIntegerOption };
|
|
||||||
7
packages/acp-core/dist/numeric-options.mjs
vendored
7
packages/acp-core/dist/numeric-options.mjs
vendored
@@ -1,7 +0,0 @@
|
|||||||
import { resolveIntegerOption as resolveIntegerOption$1 } from "@openclaw/normalization-core/number-coercion";
|
|
||||||
//#region src/numeric-options.ts
|
|
||||||
function resolveIntegerOption(value, fallback, params) {
|
|
||||||
return resolveIntegerOption$1(value, fallback, params);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { resolveIntegerOption };
|
|
||||||
2
packages/acp-core/dist/record-shared.d.mts
vendored
2
packages/acp-core/dist/record-shared.d.mts
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { asOptionalRecord as asRecord } from "@openclaw/normalization-core/record-coerce";
|
|
||||||
export { asRecord };
|
|
||||||
2
packages/acp-core/dist/record-shared.mjs
vendored
2
packages/acp-core/dist/record-shared.mjs
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { asOptionalRecord as asRecord } from "@openclaw/normalization-core/record-coerce";
|
|
||||||
export { asRecord };
|
|
||||||
11
packages/acp-core/dist/runtime/error-text.d.mts
vendored
11
packages/acp-core/dist/runtime/error-text.d.mts
vendored
@@ -1,11 +0,0 @@
|
|||||||
import { AcpRuntimeError, AcpRuntimeErrorCode } from "./errors.mjs";
|
|
||||||
|
|
||||||
//#region src/runtime/error-text.d.ts
|
|
||||||
declare function formatAcpRuntimeErrorText(error: AcpRuntimeError): string;
|
|
||||||
declare function toAcpRuntimeErrorText(params: {
|
|
||||||
error: unknown;
|
|
||||||
fallbackCode: AcpRuntimeErrorCode;
|
|
||||||
fallbackMessage: string;
|
|
||||||
}): string;
|
|
||||||
//#endregion
|
|
||||||
export { formatAcpRuntimeErrorText, toAcpRuntimeErrorText };
|
|
||||||
24
packages/acp-core/dist/runtime/error-text.mjs
vendored
24
packages/acp-core/dist/runtime/error-text.mjs
vendored
@@ -1,24 +0,0 @@
|
|||||||
import { toAcpRuntimeError } from "./errors.mjs";
|
|
||||||
//#region src/runtime/error-text.ts
|
|
||||||
function resolveAcpRuntimeErrorNextStep(error) {
|
|
||||||
if (error.code === "ACP_BACKEND_MISSING" || error.code === "ACP_BACKEND_UNAVAILABLE") return "Run `/acp doctor`, install/enable the backend plugin, then retry.";
|
|
||||||
if (error.code === "ACP_DISPATCH_DISABLED") return "Enable `acp.dispatch.enabled=true` to allow thread-message ACP turns.";
|
|
||||||
if (error.code === "ACP_SESSION_INIT_FAILED") return "If this session is stale, recreate it with `/acp spawn` and rebind the thread.";
|
|
||||||
if (error.code === "ACP_INVALID_RUNTIME_OPTION") return "Use `/acp status` to inspect options and pass valid values.";
|
|
||||||
if (error.code === "ACP_BACKEND_UNSUPPORTED_CONTROL") return "This backend does not support that control; use a supported command.";
|
|
||||||
if (error.code === "ACP_TURN_FAILED") return "Retry, or use `/acp cancel` and send the message again.";
|
|
||||||
}
|
|
||||||
function formatAcpRuntimeErrorText(error) {
|
|
||||||
const next = resolveAcpRuntimeErrorNextStep(error);
|
|
||||||
if (!next) return `ACP error (${error.code}): ${error.message}`;
|
|
||||||
return `ACP error (${error.code}): ${error.message}\nnext: ${next}`;
|
|
||||||
}
|
|
||||||
function toAcpRuntimeErrorText(params) {
|
|
||||||
return formatAcpRuntimeErrorText(toAcpRuntimeError({
|
|
||||||
error: params.error,
|
|
||||||
fallbackCode: params.fallbackCode,
|
|
||||||
fallbackMessage: params.fallbackMessage
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { formatAcpRuntimeErrorText, toAcpRuntimeErrorText };
|
|
||||||
33
packages/acp-core/dist/runtime/errors.d.mts
vendored
33
packages/acp-core/dist/runtime/errors.d.mts
vendored
@@ -1,33 +0,0 @@
|
|||||||
//#region src/runtime/errors.d.ts
|
|
||||||
declare const ACP_ERROR_CODES: readonly ["ACP_BACKEND_MISSING", "ACP_BACKEND_UNAVAILABLE", "ACP_BACKEND_UNSUPPORTED_CONTROL", "ACP_DISPATCH_DISABLED", "ACP_INVALID_RUNTIME_OPTION", "ACP_SESSION_INIT_FAILED", "ACP_TURN_FAILED"];
|
|
||||||
type AcpRuntimeErrorCode = (typeof ACP_ERROR_CODES)[number];
|
|
||||||
declare class AcpRuntimeError extends Error {
|
|
||||||
readonly code: AcpRuntimeErrorCode;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
constructor(code: AcpRuntimeErrorCode, message: string, options?: {
|
|
||||||
cause?: unknown;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
declare function isAcpRuntimeError(value: unknown): value is AcpRuntimeError;
|
|
||||||
declare function toAcpRuntimeError(params: {
|
|
||||||
error: unknown;
|
|
||||||
fallbackCode: AcpRuntimeErrorCode;
|
|
||||||
fallbackMessage: string;
|
|
||||||
}): AcpRuntimeError;
|
|
||||||
/**
|
|
||||||
* Render an error and its `.cause` chain as a single human-readable line for
|
|
||||||
* logs, lifecycle events, and tool results. Format is
|
|
||||||
* `Name [code]: message <- Name [code]: message <- ...`. Number codes also
|
|
||||||
* appear, so JSON-RPC error codes like `-32603` survive into surfaces that
|
|
||||||
* downstream consumers see (gateway logs, telegram replies, tool_result text).
|
|
||||||
*
|
|
||||||
* Depth is capped to defend against self-referential `.cause` cycles.
|
|
||||||
*/
|
|
||||||
declare function formatAcpErrorChain(error: unknown): string;
|
|
||||||
declare function withAcpRuntimeErrorBoundary<T>(params: {
|
|
||||||
run: () => Promise<T>;
|
|
||||||
fallbackCode: AcpRuntimeErrorCode;
|
|
||||||
fallbackMessage: string;
|
|
||||||
}): Promise<T>;
|
|
||||||
//#endregion
|
|
||||||
export { ACP_ERROR_CODES, AcpRuntimeError, AcpRuntimeErrorCode, formatAcpErrorChain, isAcpRuntimeError, toAcpRuntimeError, withAcpRuntimeErrorBoundary };
|
|
||||||
97
packages/acp-core/dist/runtime/errors.mjs
vendored
97
packages/acp-core/dist/runtime/errors.mjs
vendored
@@ -1,97 +0,0 @@
|
|||||||
import { redactSensitiveText, stringifyNonErrorCause } from "../error-format.mjs";
|
|
||||||
//#region src/runtime/errors.ts
|
|
||||||
const ACP_ERROR_CODES = [
|
|
||||||
"ACP_BACKEND_MISSING",
|
|
||||||
"ACP_BACKEND_UNAVAILABLE",
|
|
||||||
"ACP_BACKEND_UNSUPPORTED_CONTROL",
|
|
||||||
"ACP_DISPATCH_DISABLED",
|
|
||||||
"ACP_INVALID_RUNTIME_OPTION",
|
|
||||||
"ACP_SESSION_INIT_FAILED",
|
|
||||||
"ACP_TURN_FAILED"
|
|
||||||
];
|
|
||||||
const ACP_ERROR_CODE_SET = new Set(ACP_ERROR_CODES);
|
|
||||||
var AcpRuntimeError = class extends Error {
|
|
||||||
constructor(code, message, options) {
|
|
||||||
super(message);
|
|
||||||
this.name = "AcpRuntimeError";
|
|
||||||
this.code = code;
|
|
||||||
this.cause = options?.cause;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
function getForeignAcpRuntimeError(value) {
|
|
||||||
if (!(value instanceof Error)) return null;
|
|
||||||
const code = value.code;
|
|
||||||
if (typeof code !== "string" || !ACP_ERROR_CODE_SET.has(code)) return null;
|
|
||||||
return {
|
|
||||||
code,
|
|
||||||
message: value.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function readAcpRequestErrorDetails(value) {
|
|
||||||
if (typeof value.code !== "number") return;
|
|
||||||
const data = value.data;
|
|
||||||
if (!data || typeof data !== "object") return;
|
|
||||||
const details = data.details;
|
|
||||||
if (details === void 0 || details === null) return;
|
|
||||||
const rendered = redactSensitiveText(stringifyNonErrorCause(details)).trim();
|
|
||||||
return rendered.length > 0 ? rendered : void 0;
|
|
||||||
}
|
|
||||||
function messageWithAcpRequestErrorDetails(error) {
|
|
||||||
const details = readAcpRequestErrorDetails(error);
|
|
||||||
if (!details || error.message.includes(details)) return error.message;
|
|
||||||
return `${error.message}: ${details}`;
|
|
||||||
}
|
|
||||||
function isAcpRuntimeError(value) {
|
|
||||||
return value instanceof AcpRuntimeError || getForeignAcpRuntimeError(value) !== null;
|
|
||||||
}
|
|
||||||
function toAcpRuntimeError(params) {
|
|
||||||
if (params.error instanceof AcpRuntimeError) return params.error;
|
|
||||||
const foreignAcpRuntimeError = getForeignAcpRuntimeError(params.error);
|
|
||||||
if (foreignAcpRuntimeError) return new AcpRuntimeError(foreignAcpRuntimeError.code, foreignAcpRuntimeError.message, { cause: params.error });
|
|
||||||
if (params.error instanceof Error) return new AcpRuntimeError(params.fallbackCode, messageWithAcpRequestErrorDetails(params.error), { cause: params.error });
|
|
||||||
return new AcpRuntimeError(params.fallbackCode, params.fallbackMessage, { cause: params.error });
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Render an error and its `.cause` chain as a single human-readable line for
|
|
||||||
* logs, lifecycle events, and tool results. Format is
|
|
||||||
* `Name [code]: message <- Name [code]: message <- ...`. Number codes also
|
|
||||||
* appear, so JSON-RPC error codes like `-32603` survive into surfaces that
|
|
||||||
* downstream consumers see (gateway logs, telegram replies, tool_result text).
|
|
||||||
*
|
|
||||||
* Depth is capped to defend against self-referential `.cause` cycles.
|
|
||||||
*/
|
|
||||||
function formatAcpErrorChain(error) {
|
|
||||||
if (!(error instanceof Error)) return redactSensitiveText(String(error));
|
|
||||||
const segments = [renderSingleError(error)];
|
|
||||||
let current = error.cause;
|
|
||||||
let depth = 0;
|
|
||||||
while (current !== void 0 && current !== null && depth < 8) {
|
|
||||||
if (current instanceof Error) {
|
|
||||||
segments.push(renderSingleError(current));
|
|
||||||
current = current.cause;
|
|
||||||
} else {
|
|
||||||
segments.push(stringifyNonErrorCause(current));
|
|
||||||
current = void 0;
|
|
||||||
}
|
|
||||||
depth += 1;
|
|
||||||
}
|
|
||||||
return redactSensitiveText(segments.join(" <- "));
|
|
||||||
}
|
|
||||||
function renderSingleError(error) {
|
|
||||||
const codeValue = error.code;
|
|
||||||
const codeSuffix = typeof codeValue === "string" || typeof codeValue === "number" ? ` [${codeValue}]` : "";
|
|
||||||
return `${error.name}${codeSuffix}: ${error.message}`;
|
|
||||||
}
|
|
||||||
async function withAcpRuntimeErrorBoundary(params) {
|
|
||||||
try {
|
|
||||||
return await params.run();
|
|
||||||
} catch (error) {
|
|
||||||
throw toAcpRuntimeError({
|
|
||||||
error,
|
|
||||||
fallbackCode: params.fallbackCode,
|
|
||||||
fallbackMessage: params.fallbackMessage
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { ACP_ERROR_CODES, AcpRuntimeError, formatAcpErrorChain, isAcpRuntimeError, toAcpRuntimeError, withAcpRuntimeErrorBoundary };
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { SessionAcpIdentity, SessionAcpMeta } from "../types.mjs";
|
|
||||||
|
|
||||||
//#region src/runtime/session-identifiers.d.ts
|
|
||||||
declare const ACP_SESSION_IDENTITY_RENDERER_VERSION = "v1";
|
|
||||||
type AcpSessionIdentifierRenderMode = "status" | "thread";
|
|
||||||
declare function resolveAcpSessionIdentifierLines(params: {
|
|
||||||
sessionKey: string;
|
|
||||||
meta?: SessionAcpMeta;
|
|
||||||
}): string[];
|
|
||||||
declare function resolveAcpSessionIdentifierLinesFromIdentity(params: {
|
|
||||||
backend: string;
|
|
||||||
identity?: SessionAcpIdentity;
|
|
||||||
mode?: AcpSessionIdentifierRenderMode;
|
|
||||||
}): string[];
|
|
||||||
declare function resolveAcpSessionCwd(meta?: SessionAcpMeta): string | undefined;
|
|
||||||
declare function resolveAcpThreadSessionDetailLines(params: {
|
|
||||||
sessionKey: string;
|
|
||||||
meta?: SessionAcpMeta;
|
|
||||||
}): string[];
|
|
||||||
//#endregion
|
|
||||||
export { ACP_SESSION_IDENTITY_RENDERER_VERSION, AcpSessionIdentifierRenderMode, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines };
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { normalizeText } from "../normalize-text.mjs";
|
|
||||||
import { isSessionIdentityPending, resolveSessionIdentityFromMeta } from "./session-identity.mjs";
|
|
||||||
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
//#region src/runtime/session-identifiers.ts
|
|
||||||
const ACP_SESSION_IDENTITY_RENDERER_VERSION = "v1";
|
|
||||||
const ACP_AGENT_RESUME_HINT_BY_KEY = new Map([
|
|
||||||
["codex", ({ agentSessionId }) => `resume in Codex CLI: \`codex resume ${agentSessionId}\` (continues this conversation).`],
|
|
||||||
["openai", ({ agentSessionId }) => `resume in Codex CLI: \`codex resume ${agentSessionId}\` (continues this conversation).`],
|
|
||||||
["codex-cli", ({ agentSessionId }) => `resume in Codex CLI: \`codex resume ${agentSessionId}\` (continues this conversation).`],
|
|
||||||
["kimi", ({ agentSessionId }) => `resume in Kimi CLI: \`kimi resume ${agentSessionId}\` (continues this conversation).`],
|
|
||||||
["moonshot-kimi", ({ agentSessionId }) => `resume in Kimi CLI: \`kimi resume ${agentSessionId}\` (continues this conversation).`]
|
|
||||||
]);
|
|
||||||
function normalizeAgentHintKey(value) {
|
|
||||||
const normalized = normalizeText(value);
|
|
||||||
if (!normalized) return;
|
|
||||||
return normalizeLowercaseStringOrEmpty(normalized).replace(/[\s_]+/g, "-");
|
|
||||||
}
|
|
||||||
function resolveAcpAgentResumeHintLine(params) {
|
|
||||||
const agentSessionId = normalizeText(params.agentSessionId);
|
|
||||||
const agentKey = normalizeAgentHintKey(params.agentId);
|
|
||||||
if (!agentSessionId || !agentKey) return;
|
|
||||||
const resolver = ACP_AGENT_RESUME_HINT_BY_KEY.get(agentKey);
|
|
||||||
return resolver ? resolver({ agentSessionId }) : void 0;
|
|
||||||
}
|
|
||||||
function resolveAcpSessionIdentifierLines(params) {
|
|
||||||
return resolveAcpSessionIdentifierLinesFromIdentity({
|
|
||||||
backend: normalizeText(params.meta?.backend) ?? "backend",
|
|
||||||
identity: resolveSessionIdentityFromMeta(params.meta),
|
|
||||||
mode: "status"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function resolveAcpSessionIdentifierLinesFromIdentity(params) {
|
|
||||||
const backend = normalizeText(params.backend) ?? "backend";
|
|
||||||
const mode = params.mode ?? "status";
|
|
||||||
const identity = params.identity;
|
|
||||||
const agentSessionId = normalizeText(identity?.agentSessionId);
|
|
||||||
const acpxSessionId = normalizeText(identity?.acpxSessionId);
|
|
||||||
const acpxRecordId = normalizeText(identity?.acpxRecordId);
|
|
||||||
const hasIdentifier = Boolean(agentSessionId || acpxSessionId || acpxRecordId);
|
|
||||||
if (isSessionIdentityPending(identity) && hasIdentifier) {
|
|
||||||
if (mode === "status") return ["session ids: pending (available after the first reply)"];
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const lines = [];
|
|
||||||
if (agentSessionId) lines.push(`agent session id: ${agentSessionId}`);
|
|
||||||
if (acpxSessionId) lines.push(`${backend} session id: ${acpxSessionId}`);
|
|
||||||
if (acpxRecordId) lines.push(`${backend} record id: ${acpxRecordId}`);
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
function resolveAcpSessionCwd(meta) {
|
|
||||||
const runtimeCwd = normalizeText(meta?.runtimeOptions?.cwd);
|
|
||||||
if (runtimeCwd) return runtimeCwd;
|
|
||||||
return normalizeText(meta?.cwd);
|
|
||||||
}
|
|
||||||
function resolveAcpThreadSessionDetailLines(params) {
|
|
||||||
const meta = params.meta;
|
|
||||||
const identity = resolveSessionIdentityFromMeta(meta);
|
|
||||||
const lines = resolveAcpSessionIdentifierLinesFromIdentity({
|
|
||||||
backend: normalizeText(meta?.backend) ?? "backend",
|
|
||||||
identity,
|
|
||||||
mode: "thread"
|
|
||||||
});
|
|
||||||
if (lines.length === 0) return lines;
|
|
||||||
const hint = resolveAcpAgentResumeHintLine({
|
|
||||||
agentId: meta?.agent,
|
|
||||||
agentSessionId: identity?.agentSessionId
|
|
||||||
});
|
|
||||||
if (hint) lines.push(hint);
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { ACP_SESSION_IDENTITY_RENDERER_VERSION, resolveAcpSessionCwd, resolveAcpSessionIdentifierLines, resolveAcpSessionIdentifierLinesFromIdentity, resolveAcpThreadSessionDetailLines };
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { SessionAcpIdentity, SessionAcpMeta } from "../types.mjs";
|
|
||||||
import { AcpRuntimeHandle, AcpRuntimeStatus } from "./types.mjs";
|
|
||||||
|
|
||||||
//#region src/runtime/session-identity.d.ts
|
|
||||||
declare function resolveSessionIdentityFromMeta(meta: SessionAcpMeta | undefined): SessionAcpIdentity | undefined;
|
|
||||||
declare function identityHasStableSessionId(identity: SessionAcpIdentity | undefined): boolean;
|
|
||||||
declare function resolveRuntimeResumeSessionId(identity: SessionAcpIdentity | undefined): string | undefined;
|
|
||||||
declare function isSessionIdentityPending(identity: SessionAcpIdentity | undefined): boolean;
|
|
||||||
declare function identityEquals(left: SessionAcpIdentity | undefined, right: SessionAcpIdentity | undefined): boolean;
|
|
||||||
declare function mergeSessionIdentity(params: {
|
|
||||||
current: SessionAcpIdentity | undefined;
|
|
||||||
incoming: SessionAcpIdentity | undefined;
|
|
||||||
now: number;
|
|
||||||
}): SessionAcpIdentity | undefined;
|
|
||||||
declare function createIdentityFromEnsure(params: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
now: number;
|
|
||||||
}): SessionAcpIdentity | undefined;
|
|
||||||
declare function createIdentityFromHandleEvent(params: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
now: number;
|
|
||||||
}): SessionAcpIdentity | undefined;
|
|
||||||
declare function createIdentityFromStatus(params: {
|
|
||||||
status: AcpRuntimeStatus | undefined;
|
|
||||||
now: number;
|
|
||||||
}): SessionAcpIdentity | undefined;
|
|
||||||
declare function resolveRuntimeHandleIdentifiersFromIdentity(identity: SessionAcpIdentity | undefined): {
|
|
||||||
backendSessionId?: string;
|
|
||||||
agentSessionId?: string;
|
|
||||||
};
|
|
||||||
//#endregion
|
|
||||||
export { createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, identityEquals, identityHasStableSessionId, isSessionIdentityPending, mergeSessionIdentity, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta };
|
|
||||||
139
packages/acp-core/dist/runtime/session-identity.mjs
vendored
139
packages/acp-core/dist/runtime/session-identity.mjs
vendored
@@ -1,139 +0,0 @@
|
|||||||
import { normalizeText } from "../normalize-text.mjs";
|
|
||||||
//#region src/runtime/session-identity.ts
|
|
||||||
function normalizeIdentityState(value) {
|
|
||||||
if (value !== "pending" && value !== "resolved") return;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function normalizeIdentitySource(value) {
|
|
||||||
if (value !== "ensure" && value !== "status" && value !== "event") return;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function normalizeIdentity(identity) {
|
|
||||||
if (!identity) return;
|
|
||||||
const state = normalizeIdentityState(identity.state);
|
|
||||||
const source = normalizeIdentitySource(identity.source);
|
|
||||||
const acpxRecordId = normalizeText(identity.acpxRecordId);
|
|
||||||
const acpxSessionId = normalizeText(identity.acpxSessionId);
|
|
||||||
const agentSessionId = normalizeText(identity.agentSessionId);
|
|
||||||
const lastUpdatedAt = typeof identity.lastUpdatedAt === "number" && Number.isFinite(identity.lastUpdatedAt) ? identity.lastUpdatedAt : void 0;
|
|
||||||
if (!state && !source && !Boolean(acpxRecordId || acpxSessionId || agentSessionId) && lastUpdatedAt === void 0) return;
|
|
||||||
return {
|
|
||||||
state: state ?? (Boolean(acpxSessionId || agentSessionId) ? "resolved" : "pending"),
|
|
||||||
...acpxRecordId ? { acpxRecordId } : {},
|
|
||||||
...acpxSessionId ? { acpxSessionId } : {},
|
|
||||||
...agentSessionId ? { agentSessionId } : {},
|
|
||||||
source: source ?? "status",
|
|
||||||
lastUpdatedAt: lastUpdatedAt ?? Date.now()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function readIdentityIdsFromHandle(handle) {
|
|
||||||
return {
|
|
||||||
acpxRecordId: normalizeText(handle.acpxRecordId),
|
|
||||||
acpxSessionId: normalizeText(handle.backendSessionId),
|
|
||||||
agentSessionId: normalizeText(handle.agentSessionId)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function buildSessionIdentity(params) {
|
|
||||||
const { acpxRecordId, acpxSessionId, agentSessionId } = params.ids;
|
|
||||||
if (!acpxRecordId && !acpxSessionId && !agentSessionId) return;
|
|
||||||
return {
|
|
||||||
state: params.state,
|
|
||||||
...acpxRecordId ? { acpxRecordId } : {},
|
|
||||||
...acpxSessionId ? { acpxSessionId } : {},
|
|
||||||
...agentSessionId ? { agentSessionId } : {},
|
|
||||||
source: params.source,
|
|
||||||
lastUpdatedAt: params.now
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function resolveSessionIdentityFromMeta(meta) {
|
|
||||||
if (!meta) return;
|
|
||||||
return normalizeIdentity(meta.identity);
|
|
||||||
}
|
|
||||||
function identityHasStableSessionId(identity) {
|
|
||||||
return Boolean(identity?.acpxSessionId || identity?.agentSessionId);
|
|
||||||
}
|
|
||||||
function resolveRuntimeResumeSessionId(identity) {
|
|
||||||
if (!identity) return;
|
|
||||||
return normalizeText(identity.agentSessionId) ?? normalizeText(identity.acpxSessionId);
|
|
||||||
}
|
|
||||||
function isSessionIdentityPending(identity) {
|
|
||||||
if (!identity) return true;
|
|
||||||
return identity.state === "pending";
|
|
||||||
}
|
|
||||||
function identityEquals(left, right) {
|
|
||||||
const a = normalizeIdentity(left);
|
|
||||||
const b = normalizeIdentity(right);
|
|
||||||
if (!a && !b) return true;
|
|
||||||
if (!a || !b) return false;
|
|
||||||
return a.state === b.state && a.acpxRecordId === b.acpxRecordId && a.acpxSessionId === b.acpxSessionId && a.agentSessionId === b.agentSessionId && a.source === b.source;
|
|
||||||
}
|
|
||||||
function mergeSessionIdentity(params) {
|
|
||||||
const current = normalizeIdentity(params.current);
|
|
||||||
const incoming = normalizeIdentity(params.incoming);
|
|
||||||
if (!current) {
|
|
||||||
if (!incoming) return;
|
|
||||||
return {
|
|
||||||
...incoming,
|
|
||||||
lastUpdatedAt: params.now
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (!incoming) return current;
|
|
||||||
const currentResolved = current.state === "resolved";
|
|
||||||
const incomingResolved = incoming.state === "resolved";
|
|
||||||
const allowIncomingValue = !currentResolved || incomingResolved;
|
|
||||||
const nextRecordId = allowIncomingValue && incoming.acpxRecordId ? incoming.acpxRecordId : current.acpxRecordId;
|
|
||||||
const nextAcpxSessionId = allowIncomingValue && incoming.acpxSessionId ? incoming.acpxSessionId : current.acpxSessionId;
|
|
||||||
const nextAgentSessionId = allowIncomingValue && incoming.agentSessionId ? incoming.agentSessionId : current.agentSessionId;
|
|
||||||
const nextState = Boolean(nextAcpxSessionId || nextAgentSessionId) ? "resolved" : currentResolved ? "resolved" : incoming.state;
|
|
||||||
const nextSource = allowIncomingValue ? incoming.source : current.source;
|
|
||||||
return {
|
|
||||||
state: nextState,
|
|
||||||
...nextRecordId ? { acpxRecordId: nextRecordId } : {},
|
|
||||||
...nextAcpxSessionId ? { acpxSessionId: nextAcpxSessionId } : {},
|
|
||||||
...nextAgentSessionId ? { agentSessionId: nextAgentSessionId } : {},
|
|
||||||
source: nextSource,
|
|
||||||
lastUpdatedAt: params.now
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function createIdentityFromEnsure(params) {
|
|
||||||
return buildSessionIdentity({
|
|
||||||
ids: readIdentityIdsFromHandle(params.handle),
|
|
||||||
state: "pending",
|
|
||||||
source: "ensure",
|
|
||||||
now: params.now
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function createIdentityFromHandleEvent(params) {
|
|
||||||
const ids = readIdentityIdsFromHandle(params.handle);
|
|
||||||
return buildSessionIdentity({
|
|
||||||
ids,
|
|
||||||
state: ids.agentSessionId ? "resolved" : "pending",
|
|
||||||
source: "event",
|
|
||||||
now: params.now
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function createIdentityFromStatus(params) {
|
|
||||||
if (!params.status) return;
|
|
||||||
const details = params.status.details;
|
|
||||||
const acpxRecordId = normalizeText(params.status.acpxRecordId) ?? normalizeText(details?.acpxRecordId);
|
|
||||||
const acpxSessionId = normalizeText(params.status.backendSessionId) ?? normalizeText(details?.backendSessionId) ?? normalizeText(details?.acpxSessionId);
|
|
||||||
const agentSessionId = normalizeText(params.status.agentSessionId) ?? normalizeText(details?.agentSessionId);
|
|
||||||
if (!acpxRecordId && !acpxSessionId && !agentSessionId) return;
|
|
||||||
return {
|
|
||||||
state: Boolean(acpxSessionId || agentSessionId) ? "resolved" : "pending",
|
|
||||||
...acpxRecordId ? { acpxRecordId } : {},
|
|
||||||
...acpxSessionId ? { acpxSessionId } : {},
|
|
||||||
...agentSessionId ? { agentSessionId } : {},
|
|
||||||
source: "status",
|
|
||||||
lastUpdatedAt: params.now
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function resolveRuntimeHandleIdentifiersFromIdentity(identity) {
|
|
||||||
if (!identity) return {};
|
|
||||||
return {
|
|
||||||
...identity.acpxSessionId ? { backendSessionId: identity.acpxSessionId } : {},
|
|
||||||
...identity.agentSessionId ? { agentSessionId: identity.agentSessionId } : {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { createIdentityFromEnsure, createIdentityFromHandleEvent, createIdentityFromStatus, identityEquals, identityHasStableSessionId, isSessionIdentityPending, mergeSessionIdentity, resolveRuntimeHandleIdentifiersFromIdentity, resolveRuntimeResumeSessionId, resolveSessionIdentityFromMeta };
|
|
||||||
162
packages/acp-core/dist/runtime/types.d.mts
vendored
162
packages/acp-core/dist/runtime/types.d.mts
vendored
@@ -1,162 +0,0 @@
|
|||||||
//#region src/runtime/types.d.ts
|
|
||||||
type AcpRuntimePromptMode = "prompt" | "steer";
|
|
||||||
type AcpRuntimeSessionMode = "persistent" | "oneshot";
|
|
||||||
type AcpSessionUpdateTag = "agent_message_chunk" | "agent_thought_chunk" | "tool_call" | "tool_call_update" | "usage_update" | "available_commands_update" | "current_mode_update" | "config_option_update" | "session_info_update" | "plan" | (string & {});
|
|
||||||
type AcpRuntimeControl = "session/set_mode" | "session/set_config_option" | "session/status";
|
|
||||||
type AcpRuntimeHandle = {
|
|
||||||
sessionKey: string;
|
|
||||||
backend: string;
|
|
||||||
runtimeSessionName: string; /** Effective runtime working directory for this ACP session, if exposed by adapter/runtime. */
|
|
||||||
cwd?: string; /** Backend-local record identifier, if exposed by adapter/runtime (for example acpx record id). */
|
|
||||||
acpxRecordId?: string; /** Backend-level ACP session identifier, if exposed by adapter/runtime. */
|
|
||||||
backendSessionId?: string; /** Upstream harness session identifier, if exposed by adapter/runtime. */
|
|
||||||
agentSessionId?: string;
|
|
||||||
};
|
|
||||||
type AcpRuntimeEnsureInput = {
|
|
||||||
sessionKey: string;
|
|
||||||
agent: string;
|
|
||||||
mode: AcpRuntimeSessionMode;
|
|
||||||
resumeSessionId?: string; /** Optional runtime model override that must be available during session creation. */
|
|
||||||
model?: string; /** Optional runtime thinking/reasoning override that must be available during session creation. */
|
|
||||||
thinking?: string;
|
|
||||||
cwd?: string;
|
|
||||||
env?: Record<string, string>;
|
|
||||||
};
|
|
||||||
type AcpRuntimeTurnAttachment = {
|
|
||||||
mediaType: string;
|
|
||||||
data: string;
|
|
||||||
};
|
|
||||||
type AcpRuntimeTurnInput = {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
text: string;
|
|
||||||
attachments?: AcpRuntimeTurnAttachment[];
|
|
||||||
mode: AcpRuntimePromptMode;
|
|
||||||
requestId: string;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
};
|
|
||||||
type AcpRuntimeCapabilities = {
|
|
||||||
controls: AcpRuntimeControl[];
|
|
||||||
/**
|
|
||||||
* Optional backend-advertised option keys for session/set_config_option.
|
|
||||||
* Empty/undefined means "backend accepts keys, but did not advertise a strict list".
|
|
||||||
*/
|
|
||||||
configOptionKeys?: string[];
|
|
||||||
};
|
|
||||||
type AcpRuntimeStatus = {
|
|
||||||
summary?: string; /** Backend-local record identifier, if exposed by adapter/runtime. */
|
|
||||||
acpxRecordId?: string; /** Backend-level ACP session identifier, if known at status time. */
|
|
||||||
backendSessionId?: string; /** Upstream harness session identifier, if known at status time. */
|
|
||||||
agentSessionId?: string;
|
|
||||||
details?: Record<string, unknown>;
|
|
||||||
};
|
|
||||||
type AcpRuntimeDoctorReport = {
|
|
||||||
ok: boolean;
|
|
||||||
code?: string;
|
|
||||||
message: string;
|
|
||||||
installCommand?: string;
|
|
||||||
details?: string[];
|
|
||||||
};
|
|
||||||
type AcpRuntimeEvent = {
|
|
||||||
type: "text_delta";
|
|
||||||
text: string;
|
|
||||||
stream?: "output" | "thought";
|
|
||||||
tag?: AcpSessionUpdateTag;
|
|
||||||
} | {
|
|
||||||
type: "status";
|
|
||||||
text: string;
|
|
||||||
tag?: AcpSessionUpdateTag;
|
|
||||||
used?: number;
|
|
||||||
size?: number;
|
|
||||||
} | {
|
|
||||||
type: "tool_call";
|
|
||||||
text: string;
|
|
||||||
tag?: AcpSessionUpdateTag;
|
|
||||||
toolCallId?: string;
|
|
||||||
status?: string;
|
|
||||||
title?: string;
|
|
||||||
} | {
|
|
||||||
type: "done";
|
|
||||||
stopReason?: string;
|
|
||||||
} | {
|
|
||||||
type: "error";
|
|
||||||
message: string;
|
|
||||||
code?: string;
|
|
||||||
detailCode?: string;
|
|
||||||
retryable?: boolean;
|
|
||||||
};
|
|
||||||
type AcpRuntimeTurnResultError = {
|
|
||||||
message: string;
|
|
||||||
code?: string;
|
|
||||||
detailCode?: string;
|
|
||||||
retryable?: boolean;
|
|
||||||
};
|
|
||||||
type AcpRuntimeTurnResult = {
|
|
||||||
status: "completed";
|
|
||||||
stopReason?: string;
|
|
||||||
} | {
|
|
||||||
status: "cancelled";
|
|
||||||
stopReason?: string;
|
|
||||||
} | {
|
|
||||||
status: "failed";
|
|
||||||
error: AcpRuntimeTurnResultError;
|
|
||||||
};
|
|
||||||
interface AcpRuntimeTurn {
|
|
||||||
readonly requestId: string;
|
|
||||||
readonly events: AsyncIterable<AcpRuntimeEvent>;
|
|
||||||
readonly result: Promise<AcpRuntimeTurnResult>;
|
|
||||||
cancel(input?: {
|
|
||||||
reason?: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
closeStream(input?: {
|
|
||||||
reason?: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
}
|
|
||||||
interface AcpRuntime {
|
|
||||||
ensureSession(input: AcpRuntimeEnsureInput): Promise<AcpRuntimeHandle>;
|
|
||||||
/**
|
|
||||||
* Preferred turn API. Live events are streamed separately from the terminal
|
|
||||||
* result so adapters can report failures without relying on legacy done/error
|
|
||||||
* events in the stream.
|
|
||||||
*/
|
|
||||||
startTurn?(input: AcpRuntimeTurnInput): AcpRuntimeTurn;
|
|
||||||
runTurn(input: AcpRuntimeTurnInput): AsyncIterable<AcpRuntimeEvent>;
|
|
||||||
getCapabilities?(input: {
|
|
||||||
handle?: AcpRuntimeHandle;
|
|
||||||
}): Promise<AcpRuntimeCapabilities> | AcpRuntimeCapabilities;
|
|
||||||
getStatus?(input: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
signal?: AbortSignal;
|
|
||||||
}): Promise<AcpRuntimeStatus>;
|
|
||||||
setMode?(input: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
mode: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
setConfigOption?(input: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
key: string;
|
|
||||||
value: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
doctor?(): Promise<AcpRuntimeDoctorReport>;
|
|
||||||
/**
|
|
||||||
* Prepare the next ensureSession for this session key to start fresh instead
|
|
||||||
* of reopening backend-owned persistent state.
|
|
||||||
*/
|
|
||||||
prepareFreshSession?(input: {
|
|
||||||
sessionKey: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
cancel(input: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
reason?: string;
|
|
||||||
}): Promise<void>;
|
|
||||||
close(input: {
|
|
||||||
handle: AcpRuntimeHandle;
|
|
||||||
reason: string;
|
|
||||||
/**
|
|
||||||
* Discard backend-owned persistent session state so the next ensureSession
|
|
||||||
* starts fresh instead of reopening the same conversation.
|
|
||||||
*/
|
|
||||||
discardPersistentState?: boolean;
|
|
||||||
}): Promise<void>;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { AcpRuntime, AcpRuntimeCapabilities, AcpRuntimeControl, AcpRuntimeDoctorReport, AcpRuntimeEnsureInput, AcpRuntimeEvent, AcpRuntimeHandle, AcpRuntimePromptMode, AcpRuntimeSessionMode, AcpRuntimeStatus, AcpRuntimeTurn, AcpRuntimeTurnAttachment, AcpRuntimeTurnInput, AcpRuntimeTurnResult, AcpRuntimeTurnResultError, AcpSessionUpdateTag };
|
|
||||||
1
packages/acp-core/dist/runtime/types.mjs
vendored
1
packages/acp-core/dist/runtime/types.mjs
vendored
@@ -1 +0,0 @@
|
|||||||
export {};
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
//#region src/session-interaction-mode.d.ts
|
|
||||||
type SessionInteractionEntry = {
|
|
||||||
spawnedBy?: string;
|
|
||||||
parentSessionKey?: string;
|
|
||||||
acp?: unknown;
|
|
||||||
};
|
|
||||||
declare function isParentOwnedBackgroundAcpSession(entry?: SessionInteractionEntry | null): boolean;
|
|
||||||
/**
|
|
||||||
* Returns true when `entry` is a parent-owned background ACP session AND the
|
|
||||||
* given `requesterSessionKey` is the session that spawned/owns it. This is a
|
|
||||||
* strictly narrower check than {@link isParentOwnedBackgroundAcpSession}: the
|
|
||||||
* target must match *and* the caller must be the parent.
|
|
||||||
*
|
|
||||||
* Used to gate behaviors that only make sense for the parent↔own-child pair
|
|
||||||
* (e.g. skipping the A2A ping-pong flow in `sessions_send`), so that an
|
|
||||||
* unrelated session with broad visibility (e.g. `tools.sessions.visibility=all`)
|
|
||||||
* sending to the same target is still routed through the normal A2A path.
|
|
||||||
*/
|
|
||||||
declare function isRequesterParentOfBackgroundAcpSession(entry: SessionInteractionEntry | null | undefined, requesterSessionKey: string | null | undefined): boolean;
|
|
||||||
//#endregion
|
|
||||||
export { isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession };
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
//#region src/session-interaction-mode.ts
|
|
||||||
function resolveAcpSessionInteractionMode(entry) {
|
|
||||||
if (!entry?.acp) return "interactive";
|
|
||||||
if (normalizeOptionalString(entry.spawnedBy) || normalizeOptionalString(entry.parentSessionKey)) return "parent-owned-background";
|
|
||||||
return "interactive";
|
|
||||||
}
|
|
||||||
function isParentOwnedBackgroundAcpSession(entry) {
|
|
||||||
return resolveAcpSessionInteractionMode(entry) === "parent-owned-background";
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Returns true when `entry` is a parent-owned background ACP session AND the
|
|
||||||
* given `requesterSessionKey` is the session that spawned/owns it. This is a
|
|
||||||
* strictly narrower check than {@link isParentOwnedBackgroundAcpSession}: the
|
|
||||||
* target must match *and* the caller must be the parent.
|
|
||||||
*
|
|
||||||
* Used to gate behaviors that only make sense for the parent↔own-child pair
|
|
||||||
* (e.g. skipping the A2A ping-pong flow in `sessions_send`), so that an
|
|
||||||
* unrelated session with broad visibility (e.g. `tools.sessions.visibility=all`)
|
|
||||||
* sending to the same target is still routed through the normal A2A path.
|
|
||||||
*/
|
|
||||||
function isRequesterParentOfBackgroundAcpSession(entry, requesterSessionKey) {
|
|
||||||
if (!isParentOwnedBackgroundAcpSession(entry)) return false;
|
|
||||||
const requester = normalizeOptionalString(requesterSessionKey);
|
|
||||||
if (!requester) return false;
|
|
||||||
const spawnedBy = normalizeOptionalString(entry?.spawnedBy);
|
|
||||||
const parentSessionKey = normalizeOptionalString(entry?.parentSessionKey);
|
|
||||||
return requester === spawnedBy || requester === parentSessionKey;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { isParentOwnedBackgroundAcpSession, isRequesterParentOfBackgroundAcpSession };
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
//#region src/session-lineage-meta.d.ts
|
|
||||||
declare const SUBAGENT_ROLES: readonly ["orchestrator", "leaf"];
|
|
||||||
declare const SUBAGENT_CONTROL_SCOPES: readonly ["children", "none"];
|
|
||||||
type SubagentRole = (typeof SUBAGENT_ROLES)[number];
|
|
||||||
type SubagentControlScope = (typeof SUBAGENT_CONTROL_SCOPES)[number];
|
|
||||||
type AcpSessionLineageMeta = {
|
|
||||||
sessionKey: string;
|
|
||||||
kind?: string;
|
|
||||||
channel?: string;
|
|
||||||
parentSessionId?: string;
|
|
||||||
spawnedBy?: string;
|
|
||||||
spawnDepth?: number;
|
|
||||||
subagentRole?: SubagentRole;
|
|
||||||
subagentControlScope?: SubagentControlScope;
|
|
||||||
spawnedWorkspaceDir?: string;
|
|
||||||
spawnedCwd?: string;
|
|
||||||
};
|
|
||||||
type AcpSessionLineageRow = {
|
|
||||||
key: string;
|
|
||||||
kind?: string;
|
|
||||||
channel?: string;
|
|
||||||
parentSessionKey?: string;
|
|
||||||
spawnedBy?: string;
|
|
||||||
spawnDepth?: number;
|
|
||||||
subagentRole?: string;
|
|
||||||
subagentControlScope?: string;
|
|
||||||
spawnedWorkspaceDir?: string;
|
|
||||||
spawnedCwd?: string;
|
|
||||||
};
|
|
||||||
declare function toAcpSessionLineageMeta(row: AcpSessionLineageRow): AcpSessionLineageMeta;
|
|
||||||
//#endregion
|
|
||||||
export { AcpSessionLineageMeta, AcpSessionLineageRow, toAcpSessionLineageMeta };
|
|
||||||
38
packages/acp-core/dist/session-lineage-meta.mjs
vendored
38
packages/acp-core/dist/session-lineage-meta.mjs
vendored
@@ -1,38 +0,0 @@
|
|||||||
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
//#region src/session-lineage-meta.ts
|
|
||||||
const SUBAGENT_ROLES = ["orchestrator", "leaf"];
|
|
||||||
const SUBAGENT_CONTROL_SCOPES = ["children", "none"];
|
|
||||||
function readInteger(value) {
|
|
||||||
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) return;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function readEnum(value, allowed) {
|
|
||||||
const normalized = normalizeOptionalString(value);
|
|
||||||
return allowed.find((candidate) => candidate === normalized);
|
|
||||||
}
|
|
||||||
function toAcpSessionLineageMeta(row) {
|
|
||||||
const sessionKey = normalizeOptionalString(row.key) ?? row.key;
|
|
||||||
const kind = normalizeOptionalString(row.kind);
|
|
||||||
const channel = normalizeOptionalString(row.channel);
|
|
||||||
const parentSessionId = normalizeOptionalString(row.parentSessionKey) ?? normalizeOptionalString(row.spawnedBy);
|
|
||||||
const spawnedBy = normalizeOptionalString(row.spawnedBy);
|
|
||||||
const spawnDepth = readInteger(row.spawnDepth);
|
|
||||||
const subagentRole = readEnum(row.subagentRole, SUBAGENT_ROLES);
|
|
||||||
const subagentControlScope = readEnum(row.subagentControlScope, SUBAGENT_CONTROL_SCOPES);
|
|
||||||
const spawnedWorkspaceDir = normalizeOptionalString(row.spawnedWorkspaceDir);
|
|
||||||
const spawnedCwd = normalizeOptionalString(row.spawnedCwd);
|
|
||||||
return {
|
|
||||||
sessionKey,
|
|
||||||
...kind ? { kind } : {},
|
|
||||||
...channel ? { channel } : {},
|
|
||||||
...parentSessionId ? { parentSessionId } : {},
|
|
||||||
...spawnedBy ? { spawnedBy } : {},
|
|
||||||
...spawnDepth !== void 0 ? { spawnDepth } : {},
|
|
||||||
...subagentRole ? { subagentRole } : {},
|
|
||||||
...subagentControlScope ? { subagentControlScope } : {},
|
|
||||||
...spawnedWorkspaceDir ? { spawnedWorkspaceDir } : {},
|
|
||||||
...spawnedCwd ? { spawnedCwd } : {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { toAcpSessionLineageMeta };
|
|
||||||
28
packages/acp-core/dist/session.d.mts
vendored
28
packages/acp-core/dist/session.d.mts
vendored
@@ -1,28 +0,0 @@
|
|||||||
import { AcpSession } from "./types.mjs";
|
|
||||||
|
|
||||||
//#region src/session.d.ts
|
|
||||||
type AcpSessionStore = {
|
|
||||||
createSession: (params: {
|
|
||||||
sessionKey: string;
|
|
||||||
cwd: string;
|
|
||||||
sessionId?: string;
|
|
||||||
ledgerSessionId?: string;
|
|
||||||
}) => AcpSession;
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
getSession: (sessionId: string) => AcpSession | undefined;
|
|
||||||
getSessionByRunId: (runId: string) => AcpSession | undefined;
|
|
||||||
setActiveRun: (sessionId: string, runId: string, abortController: AbortController) => void;
|
|
||||||
clearActiveRun: (sessionId: string) => void;
|
|
||||||
cancelActiveRun: (sessionId: string) => boolean;
|
|
||||||
deleteSession: (sessionId: string) => boolean;
|
|
||||||
clearAllSessionsForTest: () => void;
|
|
||||||
};
|
|
||||||
type AcpSessionStoreOptions = {
|
|
||||||
maxSessions?: number;
|
|
||||||
idleTtlMs?: number;
|
|
||||||
now?: () => number;
|
|
||||||
};
|
|
||||||
declare function createInMemorySessionStore(options?: AcpSessionStoreOptions): AcpSessionStore;
|
|
||||||
declare const defaultAcpSessionStore: AcpSessionStore;
|
|
||||||
//#endregion
|
|
||||||
export { AcpSessionStore, createInMemorySessionStore, defaultAcpSessionStore };
|
|
||||||
128
packages/acp-core/dist/session.mjs
vendored
128
packages/acp-core/dist/session.mjs
vendored
@@ -1,128 +0,0 @@
|
|||||||
import { resolveIntegerOption } from "./numeric-options.mjs";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
//#region src/session.ts
|
|
||||||
const DEFAULT_MAX_SESSIONS = 5e3;
|
|
||||||
const DEFAULT_IDLE_TTL_MS = 1440 * 60 * 1e3;
|
|
||||||
function createInMemorySessionStore(options = {}) {
|
|
||||||
const maxSessions = resolveIntegerOption(options.maxSessions, DEFAULT_MAX_SESSIONS, { min: 1 });
|
|
||||||
const idleTtlMs = resolveIntegerOption(options.idleTtlMs, DEFAULT_IDLE_TTL_MS, { min: 1e3 });
|
|
||||||
const now = options.now ?? Date.now;
|
|
||||||
const sessions = /* @__PURE__ */ new Map();
|
|
||||||
const runIdToSessionId = /* @__PURE__ */ new Map();
|
|
||||||
const touchSession = (session, nowMs) => {
|
|
||||||
session.lastTouchedAt = nowMs;
|
|
||||||
};
|
|
||||||
const removeSession = (sessionId) => {
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (!session) return false;
|
|
||||||
if (session.activeRunId) runIdToSessionId.delete(session.activeRunId);
|
|
||||||
session.abortController?.abort();
|
|
||||||
sessions.delete(sessionId);
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
const reapIdleSessions = (nowMs) => {
|
|
||||||
const idleBefore = nowMs - idleTtlMs;
|
|
||||||
for (const [sessionId, session] of sessions.entries()) {
|
|
||||||
if (session.activeRunId || session.abortController) continue;
|
|
||||||
if (session.lastTouchedAt > idleBefore) continue;
|
|
||||||
removeSession(sessionId);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const evictOldestIdleSession = () => {
|
|
||||||
let oldestSessionId = null;
|
|
||||||
let oldestLastTouchedAt = Number.POSITIVE_INFINITY;
|
|
||||||
for (const [sessionId, session] of sessions.entries()) {
|
|
||||||
if (session.activeRunId || session.abortController) continue;
|
|
||||||
if (session.lastTouchedAt >= oldestLastTouchedAt) continue;
|
|
||||||
oldestLastTouchedAt = session.lastTouchedAt;
|
|
||||||
oldestSessionId = sessionId;
|
|
||||||
}
|
|
||||||
if (!oldestSessionId) return false;
|
|
||||||
return removeSession(oldestSessionId);
|
|
||||||
};
|
|
||||||
const createSession = (params) => {
|
|
||||||
const nowMs = now();
|
|
||||||
const sessionId = params.sessionId ?? randomUUID();
|
|
||||||
const existingSession = sessions.get(sessionId);
|
|
||||||
if (existingSession) {
|
|
||||||
existingSession.sessionKey = params.sessionKey;
|
|
||||||
if ("ledgerSessionId" in params) existingSession.ledgerSessionId = params.ledgerSessionId;
|
|
||||||
existingSession.cwd = params.cwd;
|
|
||||||
touchSession(existingSession, nowMs);
|
|
||||||
return existingSession;
|
|
||||||
}
|
|
||||||
reapIdleSessions(nowMs);
|
|
||||||
if (sessions.size >= maxSessions && !evictOldestIdleSession()) throw new Error(`ACP session limit reached (max ${maxSessions}). Close idle ACP clients and retry.`);
|
|
||||||
const session = {
|
|
||||||
sessionId,
|
|
||||||
sessionKey: params.sessionKey,
|
|
||||||
...params.ledgerSessionId ? { ledgerSessionId: params.ledgerSessionId } : {},
|
|
||||||
cwd: params.cwd,
|
|
||||||
createdAt: nowMs,
|
|
||||||
lastTouchedAt: nowMs,
|
|
||||||
abortController: null,
|
|
||||||
activeRunId: null
|
|
||||||
};
|
|
||||||
sessions.set(sessionId, session);
|
|
||||||
return session;
|
|
||||||
};
|
|
||||||
const hasSession = (sessionId) => sessions.has(sessionId);
|
|
||||||
const getSession = (sessionId) => {
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (session) touchSession(session, now());
|
|
||||||
return session;
|
|
||||||
};
|
|
||||||
const getSessionByRunId = (runId) => {
|
|
||||||
const sessionId = runIdToSessionId.get(runId);
|
|
||||||
if (!sessionId) return;
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (session) touchSession(session, now());
|
|
||||||
return session;
|
|
||||||
};
|
|
||||||
const setActiveRun = (sessionId, runId, abortController) => {
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (!session) return;
|
|
||||||
session.activeRunId = runId;
|
|
||||||
session.abortController = abortController;
|
|
||||||
runIdToSessionId.set(runId, sessionId);
|
|
||||||
touchSession(session, now());
|
|
||||||
};
|
|
||||||
const clearActiveRun = (sessionId) => {
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (!session) return;
|
|
||||||
if (session.activeRunId) runIdToSessionId.delete(session.activeRunId);
|
|
||||||
session.activeRunId = null;
|
|
||||||
session.abortController = null;
|
|
||||||
touchSession(session, now());
|
|
||||||
};
|
|
||||||
const cancelActiveRun = (sessionId) => {
|
|
||||||
const session = sessions.get(sessionId);
|
|
||||||
if (!session?.abortController) return false;
|
|
||||||
session.abortController.abort();
|
|
||||||
if (session.activeRunId) runIdToSessionId.delete(session.activeRunId);
|
|
||||||
session.abortController = null;
|
|
||||||
session.activeRunId = null;
|
|
||||||
touchSession(session, now());
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
const deleteSession = (sessionId) => removeSession(sessionId);
|
|
||||||
const clearAllSessionsForTest = () => {
|
|
||||||
for (const session of sessions.values()) session.abortController?.abort();
|
|
||||||
sessions.clear();
|
|
||||||
runIdToSessionId.clear();
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
createSession,
|
|
||||||
hasSession,
|
|
||||||
getSession,
|
|
||||||
getSessionByRunId,
|
|
||||||
setActiveRun,
|
|
||||||
clearActiveRun,
|
|
||||||
cancelActiveRun,
|
|
||||||
deleteSession,
|
|
||||||
clearAllSessionsForTest
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const defaultAcpSessionStore = createInMemorySessionStore();
|
|
||||||
//#endregion
|
|
||||||
export { createInMemorySessionStore, defaultAcpSessionStore };
|
|
||||||
67
packages/acp-core/dist/types.d.mts
vendored
67
packages/acp-core/dist/types.d.mts
vendored
@@ -1,67 +0,0 @@
|
|||||||
//#region src/types.d.ts
|
|
||||||
declare const ACP_PROVENANCE_MODE_VALUES: readonly ["off", "meta", "meta+receipt"];
|
|
||||||
type SessionId = string;
|
|
||||||
type AcpProvenanceMode = (typeof ACP_PROVENANCE_MODE_VALUES)[number];
|
|
||||||
declare function normalizeAcpProvenanceMode(value: string | undefined): AcpProvenanceMode | undefined;
|
|
||||||
type AcpSession = {
|
|
||||||
sessionId: SessionId;
|
|
||||||
sessionKey: string;
|
|
||||||
ledgerSessionId?: string;
|
|
||||||
cwd: string;
|
|
||||||
createdAt: number;
|
|
||||||
lastTouchedAt: number;
|
|
||||||
abortController: AbortController | null;
|
|
||||||
activeRunId: string | null;
|
|
||||||
};
|
|
||||||
type AcpServerOptions = {
|
|
||||||
gatewayUrl?: string;
|
|
||||||
gatewayToken?: string;
|
|
||||||
gatewayPassword?: string;
|
|
||||||
defaultSessionKey?: string;
|
|
||||||
defaultSessionLabel?: string;
|
|
||||||
requireExistingSession?: boolean;
|
|
||||||
resetSession?: boolean;
|
|
||||||
prefixCwd?: boolean;
|
|
||||||
provenanceMode?: AcpProvenanceMode;
|
|
||||||
sessionCreateRateLimit?: {
|
|
||||||
maxRequests?: number;
|
|
||||||
windowMs?: number;
|
|
||||||
};
|
|
||||||
verbose?: boolean;
|
|
||||||
};
|
|
||||||
type SessionAcpIdentitySource = "ensure" | "status" | "event";
|
|
||||||
type SessionAcpIdentityState = "pending" | "resolved";
|
|
||||||
type SessionAcpIdentity = {
|
|
||||||
state: SessionAcpIdentityState;
|
|
||||||
acpxRecordId?: string;
|
|
||||||
acpxSessionId?: string;
|
|
||||||
agentSessionId?: string;
|
|
||||||
source: SessionAcpIdentitySource;
|
|
||||||
lastUpdatedAt: number;
|
|
||||||
};
|
|
||||||
type AcpSessionRuntimeOptions = {
|
|
||||||
/**
|
|
||||||
* ACP runtime mode set via session/set_mode (for example: "plan", "normal", "auto").
|
|
||||||
*/
|
|
||||||
runtimeMode?: string; /** ACP runtime config option: model id. */
|
|
||||||
model?: string; /** ACP runtime config option: thinking/reasoning effort. */
|
|
||||||
thinking?: string; /** Working directory override for ACP session turns. */
|
|
||||||
cwd?: string; /** ACP runtime config option: permission profile id. */
|
|
||||||
permissionProfile?: string; /** ACP runtime config option: per-turn timeout in seconds. */
|
|
||||||
timeoutSeconds?: number; /** Backend-specific option bag mapped through session/set_config_option. */
|
|
||||||
backendExtras?: Record<string, string>;
|
|
||||||
};
|
|
||||||
type SessionAcpMeta = {
|
|
||||||
backend: string;
|
|
||||||
agent: string;
|
|
||||||
runtimeSessionName: string;
|
|
||||||
identity?: SessionAcpIdentity;
|
|
||||||
mode: "persistent" | "oneshot";
|
|
||||||
runtimeOptions?: AcpSessionRuntimeOptions;
|
|
||||||
cwd?: string;
|
|
||||||
state: "idle" | "running" | "error";
|
|
||||||
lastActivityAt: number;
|
|
||||||
lastError?: string;
|
|
||||||
};
|
|
||||||
//#endregion
|
|
||||||
export { AcpProvenanceMode, AcpServerOptions, AcpSession, AcpSessionRuntimeOptions, SessionAcpIdentity, SessionAcpIdentitySource, SessionAcpIdentityState, SessionAcpMeta, SessionId, normalizeAcpProvenanceMode };
|
|
||||||
14
packages/acp-core/dist/types.mjs
vendored
14
packages/acp-core/dist/types.mjs
vendored
@@ -1,14 +0,0 @@
|
|||||||
import { normalizeOptionalLowercaseString } from "@openclaw/normalization-core/string-coerce";
|
|
||||||
//#region src/types.ts
|
|
||||||
const ACP_PROVENANCE_MODE_VALUES = [
|
|
||||||
"off",
|
|
||||||
"meta",
|
|
||||||
"meta+receipt"
|
|
||||||
];
|
|
||||||
function normalizeAcpProvenanceMode(value) {
|
|
||||||
const normalized = normalizeOptionalLowercaseString(value);
|
|
||||||
if (!normalized) return;
|
|
||||||
return ACP_PROVENANCE_MODE_VALUES.includes(normalized) ? normalized : void 0;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { normalizeAcpProvenanceMode };
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/active-model.d.ts
|
|
||||||
type ActiveMediaModel = {
|
|
||||||
provider: string;
|
|
||||||
model?: string;
|
|
||||||
};
|
|
||||||
//#endregion
|
|
||||||
export { ActiveMediaModel };
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export {};
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { MediaUnderstandingCapability } from "./types.mjs";
|
|
||||||
|
|
||||||
//#region packages/media-understanding-common/src/defaults.d.ts
|
|
||||||
declare const DEFAULT_MAX_CHARS = 500;
|
|
||||||
declare const DEFAULT_MAX_CHARS_BY_CAPABILITY: Record<MediaUnderstandingCapability, number | undefined>;
|
|
||||||
declare const DEFAULT_MAX_BYTES: Record<MediaUnderstandingCapability, number>;
|
|
||||||
declare const DEFAULT_TIMEOUT_SECONDS: Record<MediaUnderstandingCapability, number>;
|
|
||||||
declare const DEFAULT_PROMPT: Record<MediaUnderstandingCapability, string>;
|
|
||||||
declare const DEFAULT_VIDEO_MAX_BASE64_BYTES: number;
|
|
||||||
declare const CLI_OUTPUT_MAX_BUFFER: number;
|
|
||||||
declare const DEFAULT_MEDIA_CONCURRENCY = 2;
|
|
||||||
declare const MIN_AUDIO_FILE_BYTES = 1024;
|
|
||||||
//#endregion
|
|
||||||
export { CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES };
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/defaults.ts
|
|
||||||
const MB = 1024 * 1024;
|
|
||||||
const DEFAULT_MAX_CHARS = 500;
|
|
||||||
const DEFAULT_MAX_CHARS_BY_CAPABILITY = {
|
|
||||||
image: 500,
|
|
||||||
audio: void 0,
|
|
||||||
video: 500
|
|
||||||
};
|
|
||||||
const DEFAULT_MAX_BYTES = {
|
|
||||||
image: 10 * MB,
|
|
||||||
audio: 20 * MB,
|
|
||||||
video: 50 * MB
|
|
||||||
};
|
|
||||||
const DEFAULT_TIMEOUT_SECONDS = {
|
|
||||||
image: 60,
|
|
||||||
audio: 60,
|
|
||||||
video: 120
|
|
||||||
};
|
|
||||||
const DEFAULT_PROMPT = {
|
|
||||||
image: "Describe the image.",
|
|
||||||
audio: "Transcribe the audio.",
|
|
||||||
video: "Describe the video."
|
|
||||||
};
|
|
||||||
const DEFAULT_VIDEO_MAX_BASE64_BYTES = 70 * MB;
|
|
||||||
const CLI_OUTPUT_MAX_BUFFER = 5 * MB;
|
|
||||||
const DEFAULT_MEDIA_CONCURRENCY = 2;
|
|
||||||
const MIN_AUDIO_FILE_BYTES = 1024;
|
|
||||||
//#endregion
|
|
||||||
export { CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES };
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/errors.d.ts
|
|
||||||
type MediaUnderstandingSkipReason = "maxBytes" | "timeout" | "unsupported" | "empty" | "blocked" | "tooSmall";
|
|
||||||
declare class MediaUnderstandingSkipError extends Error {
|
|
||||||
readonly reason: MediaUnderstandingSkipReason;
|
|
||||||
constructor(reason: MediaUnderstandingSkipReason, message: string);
|
|
||||||
}
|
|
||||||
declare function isMediaUnderstandingSkipError(err: unknown): err is MediaUnderstandingSkipError;
|
|
||||||
//#endregion
|
|
||||||
export { MediaUnderstandingSkipError, isMediaUnderstandingSkipError };
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/errors.ts
|
|
||||||
var MediaUnderstandingSkipError = class extends Error {
|
|
||||||
constructor(reason, message) {
|
|
||||||
super(message);
|
|
||||||
this.reason = reason;
|
|
||||||
this.name = "MediaUnderstandingSkipError";
|
|
||||||
}
|
|
||||||
};
|
|
||||||
function isMediaUnderstandingSkipError(err) {
|
|
||||||
return err instanceof MediaUnderstandingSkipError;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { MediaUnderstandingSkipError, isMediaUnderstandingSkipError };
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { MediaUnderstandingOutput } from "./types.mjs";
|
|
||||||
|
|
||||||
//#region packages/media-understanding-common/src/format.d.ts
|
|
||||||
declare function extractMediaUserText(body?: string): string | undefined;
|
|
||||||
declare function formatMediaUnderstandingBody(params: {
|
|
||||||
body?: string;
|
|
||||||
outputs: MediaUnderstandingOutput[];
|
|
||||||
}): string;
|
|
||||||
declare function formatAudioTranscripts(outputs: MediaUnderstandingOutput[]): string;
|
|
||||||
//#endregion
|
|
||||||
export { extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody };
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/format.ts
|
|
||||||
const MEDIA_PLACEHOLDER_RE = /^<media:[^>]+>(\s*\([^)]*\))?$/i;
|
|
||||||
const MEDIA_PLACEHOLDER_TOKEN_RE = /^<media:[^>]+>(\s*\([^)]*\))?\s*/i;
|
|
||||||
function extractMediaUserText(body) {
|
|
||||||
const trimmed = body?.trim() ?? "";
|
|
||||||
if (!trimmed) return;
|
|
||||||
if (MEDIA_PLACEHOLDER_RE.test(trimmed)) return;
|
|
||||||
return trimmed.replace(MEDIA_PLACEHOLDER_TOKEN_RE, "").trim() || void 0;
|
|
||||||
}
|
|
||||||
function formatSection(title, kind, text, userText) {
|
|
||||||
const lines = [`[${title}]`];
|
|
||||||
if (userText) lines.push(`User text:\n${userText}`);
|
|
||||||
lines.push(`${kind}:\n${text}`);
|
|
||||||
return lines.join("\n");
|
|
||||||
}
|
|
||||||
function formatMediaUnderstandingBody(params) {
|
|
||||||
const outputs = params.outputs.filter((output) => output.text.trim());
|
|
||||||
if (outputs.length === 0) return params.body ?? "";
|
|
||||||
const userText = extractMediaUserText(params.body);
|
|
||||||
const sections = [];
|
|
||||||
if (userText && outputs.length > 1) sections.push(`User text:\n${userText}`);
|
|
||||||
const counts = /* @__PURE__ */ new Map();
|
|
||||||
for (const output of outputs) counts.set(output.kind, (counts.get(output.kind) ?? 0) + 1);
|
|
||||||
const seen = /* @__PURE__ */ new Map();
|
|
||||||
for (const output of outputs) {
|
|
||||||
const count = counts.get(output.kind) ?? 1;
|
|
||||||
const next = (seen.get(output.kind) ?? 0) + 1;
|
|
||||||
seen.set(output.kind, next);
|
|
||||||
const suffix = count > 1 ? ` ${next}/${count}` : "";
|
|
||||||
if (output.kind === "audio.transcription") {
|
|
||||||
sections.push(formatSection(`Audio${suffix}`, "Transcript", output.text, outputs.length === 1 ? userText : void 0));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (output.kind === "image.description") {
|
|
||||||
sections.push(formatSection(`Image${suffix}`, "Description", output.text, outputs.length === 1 ? userText : void 0));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
sections.push(formatSection(`Video${suffix}`, "Description", output.text, outputs.length === 1 ? userText : void 0));
|
|
||||||
}
|
|
||||||
return sections.join("\n\n").trim();
|
|
||||||
}
|
|
||||||
function formatAudioTranscripts(outputs) {
|
|
||||||
if (outputs.length === 1) return outputs[0].text;
|
|
||||||
return outputs.map((output, index) => `Audio ${index + 1}:\n${output.text}`).join("\n\n");
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody };
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { ActiveMediaModel } from "./active-model.mjs";
|
|
||||||
import { MediaAttachment, MediaUnderstandingCapability, MediaUnderstandingCapabilityRegistry, MediaUnderstandingKind, MediaUnderstandingOutput, MediaUnderstandingProvider } from "./types.mjs";
|
|
||||||
import { CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES } from "./defaults.mjs";
|
|
||||||
import { MediaUnderstandingSkipError, isMediaUnderstandingSkipError } from "./errors.mjs";
|
|
||||||
import { extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody } from "./format.mjs";
|
|
||||||
import { OpenAiCompatibleVideoPayload, buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, resolveMediaUnderstandingString } from "./openai-compatible-video.mjs";
|
|
||||||
import { extractGeminiResponse } from "./output-extract.mjs";
|
|
||||||
import { normalizeMediaExecutionProviderId, normalizeMediaProviderId } from "./provider-id.mjs";
|
|
||||||
import { providerSupportsCapability } from "./provider-supports.mjs";
|
|
||||||
import { estimateBase64Size, resolveVideoMaxBase64Bytes } from "./video.mjs";
|
|
||||||
export { ActiveMediaModel, CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES, MediaAttachment, MediaUnderstandingCapability, MediaUnderstandingCapabilityRegistry, MediaUnderstandingKind, MediaUnderstandingOutput, MediaUnderstandingProvider, MediaUnderstandingSkipError, OpenAiCompatibleVideoPayload, buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, estimateBase64Size, extractGeminiResponse, extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody, isMediaUnderstandingSkipError, normalizeMediaExecutionProviderId, normalizeMediaProviderId, providerSupportsCapability, resolveMediaUnderstandingString, resolveVideoMaxBase64Bytes };
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import "./active-model.mjs";
|
|
||||||
import { CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES } from "./defaults.mjs";
|
|
||||||
import { MediaUnderstandingSkipError, isMediaUnderstandingSkipError } from "./errors.mjs";
|
|
||||||
import { extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody } from "./format.mjs";
|
|
||||||
import { buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, resolveMediaUnderstandingString } from "./openai-compatible-video.mjs";
|
|
||||||
import { extractGeminiResponse } from "./output-extract.mjs";
|
|
||||||
import { normalizeMediaExecutionProviderId, normalizeMediaProviderId } from "./provider-id.mjs";
|
|
||||||
import { providerSupportsCapability } from "./provider-supports.mjs";
|
|
||||||
import "./types.mjs";
|
|
||||||
import { estimateBase64Size, resolveVideoMaxBase64Bytes } from "./video.mjs";
|
|
||||||
export { CLI_OUTPUT_MAX_BUFFER, DEFAULT_MAX_BYTES, DEFAULT_MAX_CHARS, DEFAULT_MAX_CHARS_BY_CAPABILITY, DEFAULT_MEDIA_CONCURRENCY, DEFAULT_PROMPT, DEFAULT_TIMEOUT_SECONDS, DEFAULT_VIDEO_MAX_BASE64_BYTES, MIN_AUDIO_FILE_BYTES, MediaUnderstandingSkipError, buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, estimateBase64Size, extractGeminiResponse, extractMediaUserText, formatAudioTranscripts, formatMediaUnderstandingBody, isMediaUnderstandingSkipError, normalizeMediaExecutionProviderId, normalizeMediaProviderId, providerSupportsCapability, resolveMediaUnderstandingString, resolveVideoMaxBase64Bytes };
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/openai-compatible-video.d.ts
|
|
||||||
type OpenAiCompatibleVideoPayload = {
|
|
||||||
choices?: Array<{
|
|
||||||
message?: {
|
|
||||||
content?: string | Array<{
|
|
||||||
text?: string;
|
|
||||||
}>;
|
|
||||||
reasoning_content?: string;
|
|
||||||
};
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
declare function resolveMediaUnderstandingString(value: string | undefined, fallback: string): string;
|
|
||||||
declare function coerceOpenAiCompatibleVideoText(payload: OpenAiCompatibleVideoPayload): string | null;
|
|
||||||
declare function buildOpenAiCompatibleVideoRequestBody(params: {
|
|
||||||
model: string;
|
|
||||||
prompt: string;
|
|
||||||
mime: string;
|
|
||||||
buffer: Buffer;
|
|
||||||
}): {
|
|
||||||
model: string;
|
|
||||||
messages: {
|
|
||||||
role: string;
|
|
||||||
content: ({
|
|
||||||
type: string;
|
|
||||||
text: string;
|
|
||||||
video_url?: undefined;
|
|
||||||
} | {
|
|
||||||
type: string;
|
|
||||||
video_url: {
|
|
||||||
url: string;
|
|
||||||
};
|
|
||||||
text?: undefined;
|
|
||||||
})[];
|
|
||||||
}[];
|
|
||||||
};
|
|
||||||
//#endregion
|
|
||||||
export { OpenAiCompatibleVideoPayload, buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, resolveMediaUnderstandingString };
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/openai-compatible-video.ts
|
|
||||||
function resolveMediaUnderstandingString(value, fallback) {
|
|
||||||
return value?.trim() || fallback;
|
|
||||||
}
|
|
||||||
function coerceOpenAiCompatibleVideoText(payload) {
|
|
||||||
const message = payload.choices?.[0]?.message;
|
|
||||||
if (!message) return null;
|
|
||||||
if (typeof message.content === "string" && message.content.trim()) return message.content.trim();
|
|
||||||
if (Array.isArray(message.content)) {
|
|
||||||
const text = message.content.map((part) => part.text?.trim() ?? "").filter(Boolean).join("\n");
|
|
||||||
if (text) return text;
|
|
||||||
}
|
|
||||||
if (typeof message.reasoning_content === "string" && message.reasoning_content.trim()) return message.reasoning_content.trim();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
function buildOpenAiCompatibleVideoRequestBody(params) {
|
|
||||||
return {
|
|
||||||
model: params.model,
|
|
||||||
messages: [{
|
|
||||||
role: "user",
|
|
||||||
content: [{
|
|
||||||
type: "text",
|
|
||||||
text: params.prompt
|
|
||||||
}, {
|
|
||||||
type: "video_url",
|
|
||||||
video_url: { url: `data:${params.mime};base64,${params.buffer.toString("base64")}` }
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { buildOpenAiCompatibleVideoRequestBody, coerceOpenAiCompatibleVideoText, resolveMediaUnderstandingString };
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/output-extract.d.ts
|
|
||||||
declare function extractGeminiResponse(raw: string): string | null;
|
|
||||||
//#endregion
|
|
||||||
export { extractGeminiResponse };
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/output-extract.ts
|
|
||||||
function extractLastJsonObject(raw) {
|
|
||||||
const trimmed = raw.trim();
|
|
||||||
const start = trimmed.lastIndexOf("{");
|
|
||||||
if (start === -1) return null;
|
|
||||||
const slice = trimmed.slice(start);
|
|
||||||
try {
|
|
||||||
return JSON.parse(slice);
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function extractGeminiResponse(raw) {
|
|
||||||
const payload = extractLastJsonObject(raw);
|
|
||||||
if (!payload || typeof payload !== "object") return null;
|
|
||||||
const response = payload.response;
|
|
||||||
if (typeof response !== "string") return null;
|
|
||||||
return response.trim() || null;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { extractGeminiResponse };
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/provider-id.d.ts
|
|
||||||
declare function normalizeMediaProviderId(id: string): string;
|
|
||||||
declare function normalizeMediaExecutionProviderId(id: string): string;
|
|
||||||
//#endregion
|
|
||||||
export { normalizeMediaExecutionProviderId, normalizeMediaProviderId };
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/provider-id.ts
|
|
||||||
function normalizeProviderId(provider) {
|
|
||||||
return provider.trim().toLowerCase();
|
|
||||||
}
|
|
||||||
function normalizeMediaProviderId(id) {
|
|
||||||
const normalized = normalizeProviderId(id);
|
|
||||||
if (normalized === "gemini") return "google";
|
|
||||||
if (normalized === "minimax-cn") return "minimax";
|
|
||||||
if (normalized === "minimax-portal-cn") return "minimax-portal";
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
function normalizeMediaExecutionProviderId(id) {
|
|
||||||
const normalized = normalizeProviderId(id);
|
|
||||||
if (normalized === "minimax-cn" || normalized === "minimax-portal-cn") return normalized;
|
|
||||||
return normalizeMediaProviderId(normalized);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { normalizeMediaExecutionProviderId, normalizeMediaProviderId };
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { MediaUnderstandingCapability, MediaUnderstandingProvider } from "./types.mjs";
|
|
||||||
|
|
||||||
//#region packages/media-understanding-common/src/provider-supports.d.ts
|
|
||||||
declare function providerSupportsCapability(provider: MediaUnderstandingProvider | undefined, capability: MediaUnderstandingCapability): boolean;
|
|
||||||
//#endregion
|
|
||||||
export { providerSupportsCapability };
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/provider-supports.ts
|
|
||||||
function providerSupportsCapability(provider, capability) {
|
|
||||||
if (!provider) return false;
|
|
||||||
if (capability === "audio") return Boolean(provider.transcribeAudio);
|
|
||||||
if (capability === "image") return Boolean(provider.describeImage);
|
|
||||||
return Boolean(provider.describeVideo);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { providerSupportsCapability };
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/types.d.ts
|
|
||||||
type MediaUnderstandingKind = "audio.transcription" | "video.description" | "image.description";
|
|
||||||
type MediaUnderstandingCapability = "image" | "audio" | "video";
|
|
||||||
type MediaUnderstandingCapabilityRegistry = Map<string, {
|
|
||||||
capabilities?: MediaUnderstandingCapability[];
|
|
||||||
}>;
|
|
||||||
type MediaAttachment = {
|
|
||||||
path?: string;
|
|
||||||
url?: string;
|
|
||||||
mime?: string;
|
|
||||||
index: number;
|
|
||||||
alreadyTranscribed?: boolean;
|
|
||||||
};
|
|
||||||
type MediaUnderstandingOutput = {
|
|
||||||
kind: MediaUnderstandingKind;
|
|
||||||
attachmentIndex: number;
|
|
||||||
text: string;
|
|
||||||
provider: string;
|
|
||||||
model?: string;
|
|
||||||
};
|
|
||||||
type MediaUnderstandingProvider = {
|
|
||||||
id: string;
|
|
||||||
capabilities?: MediaUnderstandingCapability[];
|
|
||||||
transcribeAudio?: unknown;
|
|
||||||
describeVideo?: unknown;
|
|
||||||
describeImage?: unknown;
|
|
||||||
describeImages?: unknown;
|
|
||||||
extractStructured?: unknown;
|
|
||||||
};
|
|
||||||
//#endregion
|
|
||||||
export { MediaAttachment, MediaUnderstandingCapability, MediaUnderstandingCapabilityRegistry, MediaUnderstandingKind, MediaUnderstandingOutput, MediaUnderstandingProvider };
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export {};
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
//#region packages/media-understanding-common/src/video.d.ts
|
|
||||||
declare function estimateBase64Size(bytes: number): number;
|
|
||||||
declare function resolveVideoMaxBase64Bytes(maxBytes: number): number;
|
|
||||||
//#endregion
|
|
||||||
export { estimateBase64Size, resolveVideoMaxBase64Bytes };
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { DEFAULT_VIDEO_MAX_BASE64_BYTES } from "./defaults.mjs";
|
|
||||||
//#region packages/media-understanding-common/src/video.ts
|
|
||||||
function estimateBase64Size(bytes) {
|
|
||||||
return Math.ceil(bytes / 3) * 4;
|
|
||||||
}
|
|
||||||
function resolveVideoMaxBase64Bytes(maxBytes) {
|
|
||||||
const expanded = Math.floor(maxBytes * (4 / 3));
|
|
||||||
return Math.min(expanded, DEFAULT_VIDEO_MAX_BASE64_BYTES);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { estimateBase64Size, resolveVideoMaxBase64Bytes };
|
|
||||||
5
packages/normalization-core/dist/index.d.mts
vendored
5
packages/normalization-core/dist/index.d.mts
vendored
@@ -1,5 +0,0 @@
|
|||||||
import { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asPositiveSafeInteger, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, isFutureDateTimestampMs, nonNegativeSecondsToSafeMilliseconds, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, timestampMsToIsoFileStamp, timestampMsToIsoString } from "./number-coercion.mjs";
|
|
||||||
import { asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asRecord, isRecord, readStringField } from "./record-coerce.mjs";
|
|
||||||
import { hasNonEmptyString, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, normalizeFastMode, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeStringifiedEntries, normalizeStringifiedOptionalString, readStringValue, resolvePrimaryStringValue } from "./string-coerce.mjs";
|
|
||||||
import { normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeHyphenSlug, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, sortUniqueStrings, uniqueStrings, uniqueValues } from "./string-normalization.mjs";
|
|
||||||
export { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asPositiveSafeInteger, asRecord, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, hasNonEmptyString, isFutureDateTimestampMs, isRecord, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, nonNegativeSecondsToSafeMilliseconds, normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeFastMode, normalizeHyphenSlug, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeStringifiedEntries, normalizeStringifiedOptionalString, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, readStringField, readStringValue, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolvePrimaryStringValue, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, sortUniqueStrings, timestampMsToIsoFileStamp, timestampMsToIsoString, uniqueStrings, uniqueValues };
|
|
||||||
5
packages/normalization-core/dist/index.mjs
vendored
5
packages/normalization-core/dist/index.mjs
vendored
@@ -1,5 +0,0 @@
|
|||||||
import { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asPositiveSafeInteger, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, isFutureDateTimestampMs, nonNegativeSecondsToSafeMilliseconds, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, timestampMsToIsoFileStamp, timestampMsToIsoString } from "./number-coercion.mjs";
|
|
||||||
import { asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asRecord, isRecord, readStringField } from "./record-coerce.mjs";
|
|
||||||
import { hasNonEmptyString, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, normalizeFastMode, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeStringifiedEntries, normalizeStringifiedOptionalString, readStringValue, resolvePrimaryStringValue } from "./string-coerce.mjs";
|
|
||||||
import { normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeHyphenSlug, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, sortUniqueStrings, uniqueStrings, uniqueValues } from "./string-normalization.mjs";
|
|
||||||
export { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asPositiveSafeInteger, asRecord, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, hasNonEmptyString, isFutureDateTimestampMs, isRecord, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, nonNegativeSecondsToSafeMilliseconds, normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeFastMode, normalizeHyphenSlug, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeStringifiedEntries, normalizeStringifiedOptionalString, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, readStringField, readStringValue, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolvePrimaryStringValue, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, sortUniqueStrings, timestampMsToIsoFileStamp, timestampMsToIsoString, uniqueStrings, uniqueValues };
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/number-coercion.d.ts
|
|
||||||
declare function asFiniteNumber(value: unknown): number | undefined;
|
|
||||||
declare function asFiniteNumberInRange(value: unknown, range: {
|
|
||||||
min?: number;
|
|
||||||
max?: number;
|
|
||||||
minExclusive?: boolean;
|
|
||||||
maxExclusive?: boolean;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function asSafeIntegerInRange(value: unknown, range: {
|
|
||||||
min?: number;
|
|
||||||
max?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function parseFiniteNumber(value: unknown): number | undefined;
|
|
||||||
declare function parseStrictInteger(value: unknown): number | undefined;
|
|
||||||
declare function parseStrictFiniteNumber(value: unknown): number | undefined;
|
|
||||||
declare function asPositiveSafeInteger(value: unknown): number | undefined;
|
|
||||||
declare const MAX_TIMER_TIMEOUT_MS = 2147000000;
|
|
||||||
declare const MAX_TIMER_TIMEOUT_SECONDS: number;
|
|
||||||
declare const MAX_DATE_TIMESTAMP_MS = 8640000000000000;
|
|
||||||
declare const UNIX_EPOCH_ISO_STRING = "1970-01-01T00:00:00.000Z";
|
|
||||||
declare function asDateTimestampMs(value: unknown): number | undefined;
|
|
||||||
declare function isFutureDateTimestampMs(value: unknown, opts?: {
|
|
||||||
nowMs?: number;
|
|
||||||
}): value is number;
|
|
||||||
declare function timestampMsToIsoString(value: unknown): string | undefined;
|
|
||||||
declare function resolveDateTimestampMs(value: unknown, fallbackValue?: unknown): number;
|
|
||||||
declare function resolveTimestampMsToIsoString(value: unknown, fallbackValue?: unknown): string;
|
|
||||||
declare function timestampMsToIsoFileStamp(value: unknown, fallbackValue?: unknown): string;
|
|
||||||
declare function clampTimerTimeoutMs(valueMs: unknown, minMs?: number): number | undefined;
|
|
||||||
declare function clampPositiveTimerTimeoutMs(valueMs: unknown): number | undefined;
|
|
||||||
declare function resolvePositiveTimerTimeoutMs(valueMs: unknown, fallbackMs: number): number;
|
|
||||||
declare function resolveTimerTimeoutMs(valueMs: unknown, fallbackMs: number, minMs?: number): number;
|
|
||||||
declare function addTimerTimeoutGraceMs(timeoutMs: unknown, graceMs?: number): number | undefined;
|
|
||||||
declare function finiteSecondsToTimerSafeMilliseconds(value: unknown, opts?: {
|
|
||||||
floorSeconds?: boolean;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function resolveIntegerOption(value: unknown, fallback: number, range?: {
|
|
||||||
min?: number;
|
|
||||||
max?: number;
|
|
||||||
}): number;
|
|
||||||
declare function resolveOptionalIntegerOption(value: unknown, range?: {
|
|
||||||
min?: number;
|
|
||||||
max?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function resolveNonNegativeIntegerOption(value: unknown, fallback: number): number;
|
|
||||||
declare function parseStrictPositiveInteger(value: unknown): number | undefined;
|
|
||||||
declare function parseStrictNonNegativeInteger(value: unknown): number | undefined;
|
|
||||||
declare function positiveSecondsToSafeMilliseconds(value: unknown): number | undefined;
|
|
||||||
declare function nonNegativeSecondsToSafeMilliseconds(value: unknown): number | undefined;
|
|
||||||
declare function resolveExpiresAtMsFromDurationMs(value: unknown, opts?: {
|
|
||||||
nowMs?: number;
|
|
||||||
bufferMs?: number;
|
|
||||||
minRemainingMs?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function resolveExpiresAtMsFromDurationSeconds(value: unknown, opts?: {
|
|
||||||
nowMs?: number;
|
|
||||||
bufferMs?: number;
|
|
||||||
minRemainingMs?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function resolveExpiresAtMsFromEpochSeconds(value: unknown, opts?: {
|
|
||||||
bufferMs?: number;
|
|
||||||
maxMs?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
declare function resolveExpiresAtMsFromDurationOrEpoch(value: unknown, opts?: {
|
|
||||||
nowMs?: number;
|
|
||||||
relativeSecondsThreshold?: number;
|
|
||||||
absoluteMillisecondsThreshold?: number;
|
|
||||||
}): number | undefined;
|
|
||||||
//#endregion
|
|
||||||
export { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asPositiveSafeInteger, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, isFutureDateTimestampMs, nonNegativeSecondsToSafeMilliseconds, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, timestampMsToIsoFileStamp, timestampMsToIsoString };
|
|
||||||
178
packages/normalization-core/dist/number-coercion.mjs
vendored
178
packages/normalization-core/dist/number-coercion.mjs
vendored
@@ -1,178 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/number-coercion.ts
|
|
||||||
function asFiniteNumber(value) {
|
|
||||||
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
||||||
}
|
|
||||||
function asFiniteNumberInRange(value, range) {
|
|
||||||
const number = asFiniteNumber(value);
|
|
||||||
if (number === void 0) return;
|
|
||||||
if (range.min !== void 0) {
|
|
||||||
if (range.minExclusive ? number <= range.min : number < range.min) return;
|
|
||||||
}
|
|
||||||
if (range.max !== void 0) {
|
|
||||||
if (range.maxExclusive ? number >= range.max : number > range.max) return;
|
|
||||||
}
|
|
||||||
return number;
|
|
||||||
}
|
|
||||||
function asSafeIntegerInRange(value, range) {
|
|
||||||
if (typeof value !== "number" || !Number.isSafeInteger(value)) return;
|
|
||||||
if (range.min !== void 0 && value < range.min) return;
|
|
||||||
if (range.max !== void 0 && value > range.max) return;
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function normalizeNumericString(value) {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
return trimmed ? trimmed : void 0;
|
|
||||||
}
|
|
||||||
function parseFiniteNumber(value) {
|
|
||||||
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
||||||
return parseStrictFiniteNumber(value);
|
|
||||||
}
|
|
||||||
function parseStrictInteger(value) {
|
|
||||||
if (typeof value === "number") return Number.isSafeInteger(value) ? value : void 0;
|
|
||||||
if (typeof value !== "string") return;
|
|
||||||
const normalized = normalizeNumericString(value);
|
|
||||||
if (!normalized || !/^[+-]?\d+$/.test(normalized)) return;
|
|
||||||
const parsed = Number(normalized);
|
|
||||||
return Number.isSafeInteger(parsed) ? parsed : void 0;
|
|
||||||
}
|
|
||||||
function parseStrictFiniteNumber(value) {
|
|
||||||
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
||||||
if (typeof value !== "string") return;
|
|
||||||
const normalized = normalizeNumericString(value);
|
|
||||||
if (!normalized || !/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:e[+-]?\d+)?$/i.test(normalized)) return;
|
|
||||||
const parsed = Number(normalized);
|
|
||||||
return Number.isFinite(parsed) ? parsed : void 0;
|
|
||||||
}
|
|
||||||
function asPositiveSafeInteger(value) {
|
|
||||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
||||||
}
|
|
||||||
const MAX_TIMER_TIMEOUT_MS = 2147e6;
|
|
||||||
const MAX_TIMER_TIMEOUT_SECONDS = Math.floor(MAX_TIMER_TIMEOUT_MS / 1e3);
|
|
||||||
const MAX_DATE_TIMESTAMP_MS = 864e13;
|
|
||||||
const UNIX_EPOCH_ISO_STRING = "1970-01-01T00:00:00.000Z";
|
|
||||||
function asDateTimestampMs(value) {
|
|
||||||
return asFiniteNumberInRange(value, {
|
|
||||||
min: -864e13,
|
|
||||||
max: MAX_DATE_TIMESTAMP_MS
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function isFutureDateTimestampMs(value, opts = {}) {
|
|
||||||
const timestampMs = asDateTimestampMs(value);
|
|
||||||
const nowMs = asDateTimestampMs(opts.nowMs ?? Date.now());
|
|
||||||
return timestampMs !== void 0 && nowMs !== void 0 && timestampMs > nowMs;
|
|
||||||
}
|
|
||||||
function timestampMsToIsoString(value) {
|
|
||||||
const timestampMs = asDateTimestampMs(value);
|
|
||||||
return timestampMs === void 0 ? void 0 : new Date(timestampMs).toISOString();
|
|
||||||
}
|
|
||||||
function resolveDateTimestampMs(value, fallbackValue = Date.now()) {
|
|
||||||
return asDateTimestampMs(value) ?? asDateTimestampMs(fallbackValue) ?? 0;
|
|
||||||
}
|
|
||||||
function resolveTimestampMsToIsoString(value, fallbackValue = Date.now()) {
|
|
||||||
return timestampMsToIsoString(value) ?? timestampMsToIsoString(fallbackValue) ?? "1970-01-01T00:00:00.000Z";
|
|
||||||
}
|
|
||||||
function timestampMsToIsoFileStamp(value, fallbackValue = Date.now()) {
|
|
||||||
return resolveTimestampMsToIsoString(value, fallbackValue).replaceAll(":", "-");
|
|
||||||
}
|
|
||||||
function clampTimerTimeoutMs(valueMs, minMs = 1) {
|
|
||||||
const value = asFiniteNumber(valueMs);
|
|
||||||
if (value === void 0) return;
|
|
||||||
return Math.min(Math.max(Math.floor(value), Math.max(1, Math.floor(minMs))), MAX_TIMER_TIMEOUT_MS);
|
|
||||||
}
|
|
||||||
function clampPositiveTimerTimeoutMs(valueMs) {
|
|
||||||
const value = asFiniteNumber(valueMs);
|
|
||||||
if (value === void 0 || value <= 0) return;
|
|
||||||
return clampTimerTimeoutMs(value);
|
|
||||||
}
|
|
||||||
function resolvePositiveTimerTimeoutMs(valueMs, fallbackMs) {
|
|
||||||
return clampPositiveTimerTimeoutMs(valueMs) ?? resolveTimerTimeoutMs(fallbackMs, 1);
|
|
||||||
}
|
|
||||||
function resolveTimerTimeoutMs(valueMs, fallbackMs, minMs = 1) {
|
|
||||||
const value = asFiniteNumber(valueMs) ?? asFiniteNumber(fallbackMs);
|
|
||||||
const min = Math.max(0, Math.floor(minMs));
|
|
||||||
if (value === void 0) return min;
|
|
||||||
return Math.min(Math.max(Math.floor(value), min), MAX_TIMER_TIMEOUT_MS);
|
|
||||||
}
|
|
||||||
function addTimerTimeoutGraceMs(timeoutMs, graceMs = 5e3) {
|
|
||||||
const timeout = asFiniteNumber(timeoutMs);
|
|
||||||
const grace = asFiniteNumber(graceMs);
|
|
||||||
if (timeout === void 0 || grace === void 0) return;
|
|
||||||
const withGrace = timeout + grace;
|
|
||||||
return Number.isFinite(withGrace) ? clampTimerTimeoutMs(withGrace) : MAX_TIMER_TIMEOUT_MS;
|
|
||||||
}
|
|
||||||
function finiteSecondsToTimerSafeMilliseconds(value, opts = {}) {
|
|
||||||
const seconds = asFiniteNumber(value);
|
|
||||||
if (seconds === void 0 || seconds <= 0) return;
|
|
||||||
const boundedSeconds = opts.floorSeconds ? Math.floor(seconds) : seconds;
|
|
||||||
const milliseconds = Math.floor(boundedSeconds * 1e3);
|
|
||||||
if (!Number.isFinite(milliseconds) || milliseconds <= 0) return;
|
|
||||||
return Math.min(milliseconds, MAX_TIMER_TIMEOUT_MS);
|
|
||||||
}
|
|
||||||
function resolveIntegerOption(value, fallback, range = {}) {
|
|
||||||
const floored = Math.floor(typeof value === "number" && Number.isFinite(value) ? value : fallback);
|
|
||||||
const minBounded = range.min === void 0 ? floored : Math.max(range.min, floored);
|
|
||||||
return range.max === void 0 ? minBounded : Math.min(range.max, minBounded);
|
|
||||||
}
|
|
||||||
function resolveOptionalIntegerOption(value, range = {}) {
|
|
||||||
if (typeof value !== "number" || !Number.isFinite(value)) return;
|
|
||||||
return resolveIntegerOption(value, value, range);
|
|
||||||
}
|
|
||||||
function resolveNonNegativeIntegerOption(value, fallback) {
|
|
||||||
return resolveIntegerOption(value, fallback, { min: 0 });
|
|
||||||
}
|
|
||||||
function parseStrictPositiveInteger(value) {
|
|
||||||
const parsed = parseStrictInteger(value);
|
|
||||||
return parsed !== void 0 && parsed > 0 ? parsed : void 0;
|
|
||||||
}
|
|
||||||
function parseStrictNonNegativeInteger(value) {
|
|
||||||
const parsed = parseStrictInteger(value);
|
|
||||||
return parsed !== void 0 && parsed >= 0 ? parsed : void 0;
|
|
||||||
}
|
|
||||||
function positiveSecondsToSafeMilliseconds(value) {
|
|
||||||
const seconds = parseStrictPositiveInteger(value);
|
|
||||||
if (seconds === void 0) return;
|
|
||||||
const milliseconds = seconds * 1e3;
|
|
||||||
return Number.isSafeInteger(milliseconds) ? milliseconds : void 0;
|
|
||||||
}
|
|
||||||
function nonNegativeSecondsToSafeMilliseconds(value) {
|
|
||||||
const seconds = parseStrictNonNegativeInteger(value);
|
|
||||||
if (seconds === void 0) return;
|
|
||||||
const milliseconds = seconds * 1e3;
|
|
||||||
return Number.isSafeInteger(milliseconds) ? milliseconds : void 0;
|
|
||||||
}
|
|
||||||
function resolveExpiresAtMsFromDurationMs(value, opts = {}) {
|
|
||||||
const durationMs = asPositiveSafeInteger(value);
|
|
||||||
if (durationMs === void 0) return;
|
|
||||||
const nowMs = asDateTimestampMs(opts.nowMs ?? Date.now());
|
|
||||||
const bufferMs = asFiniteNumber(opts.bufferMs ?? 0);
|
|
||||||
if (nowMs === void 0 || bufferMs === void 0) return;
|
|
||||||
const expiresAt = nowMs + durationMs - bufferMs;
|
|
||||||
if (!Number.isSafeInteger(expiresAt) || timestampMsToIsoString(expiresAt) === void 0) return;
|
|
||||||
const minRemainingMs = opts.minRemainingMs;
|
|
||||||
if (minRemainingMs === void 0) return expiresAt;
|
|
||||||
const minExpiresAt = nowMs + minRemainingMs;
|
|
||||||
if (!Number.isSafeInteger(minExpiresAt) || timestampMsToIsoString(minExpiresAt) === void 0) return expiresAt;
|
|
||||||
return Math.max(expiresAt, minExpiresAt);
|
|
||||||
}
|
|
||||||
function resolveExpiresAtMsFromDurationSeconds(value, opts = {}) {
|
|
||||||
const durationMs = positiveSecondsToSafeMilliseconds(value);
|
|
||||||
return durationMs === void 0 ? void 0 : resolveExpiresAtMsFromDurationMs(durationMs, opts);
|
|
||||||
}
|
|
||||||
function resolveExpiresAtMsFromEpochSeconds(value, opts = {}) {
|
|
||||||
const epochMs = typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) * 1e3 : positiveSecondsToSafeMilliseconds(value);
|
|
||||||
if (epochMs === void 0) return;
|
|
||||||
const expiresAt = epochMs - (opts.bufferMs ?? 0);
|
|
||||||
if (!Number.isSafeInteger(expiresAt)) return;
|
|
||||||
if (timestampMsToIsoString(expiresAt) === void 0) return;
|
|
||||||
const maxMs = opts.maxMs;
|
|
||||||
return maxMs === void 0 || expiresAt <= maxMs ? expiresAt : void 0;
|
|
||||||
}
|
|
||||||
function resolveExpiresAtMsFromDurationOrEpoch(value, opts = {}) {
|
|
||||||
const parsed = parseStrictPositiveInteger(value);
|
|
||||||
if (parsed === void 0) return;
|
|
||||||
if (parsed < (opts.relativeSecondsThreshold ?? 1e9)) return resolveExpiresAtMsFromDurationSeconds(parsed, { nowMs: opts.nowMs });
|
|
||||||
if (parsed < (opts.absoluteMillisecondsThreshold ?? 0xe8d4a51000)) return resolveExpiresAtMsFromEpochSeconds(parsed);
|
|
||||||
return asDateTimestampMs(parsed);
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { MAX_DATE_TIMESTAMP_MS, MAX_TIMER_TIMEOUT_MS, MAX_TIMER_TIMEOUT_SECONDS, UNIX_EPOCH_ISO_STRING, addTimerTimeoutGraceMs, asDateTimestampMs, asFiniteNumber, asFiniteNumberInRange, asPositiveSafeInteger, asSafeIntegerInRange, clampPositiveTimerTimeoutMs, clampTimerTimeoutMs, finiteSecondsToTimerSafeMilliseconds, isFutureDateTimestampMs, nonNegativeSecondsToSafeMilliseconds, parseFiniteNumber, parseStrictFiniteNumber, parseStrictInteger, parseStrictNonNegativeInteger, parseStrictPositiveInteger, positiveSecondsToSafeMilliseconds, resolveDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveExpiresAtMsFromDurationOrEpoch, resolveExpiresAtMsFromDurationSeconds, resolveExpiresAtMsFromEpochSeconds, resolveIntegerOption, resolveNonNegativeIntegerOption, resolveOptionalIntegerOption, resolvePositiveTimerTimeoutMs, resolveTimerTimeoutMs, resolveTimestampMsToIsoString, timestampMsToIsoFileStamp, timestampMsToIsoString };
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/record-coerce.d.ts
|
|
||||||
declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
||||||
declare function asRecord(value: unknown): Record<string, unknown>;
|
|
||||||
declare function readStringField(record: Record<string, unknown> | null | undefined, key: string): string | undefined;
|
|
||||||
declare function asOptionalRecord(value: unknown): Record<string, unknown> | undefined;
|
|
||||||
declare function asNullableRecord(value: unknown): Record<string, unknown> | null;
|
|
||||||
declare function asOptionalObjectRecord(value: unknown): Record<string, unknown> | undefined;
|
|
||||||
declare function asNullableObjectRecord(value: unknown): Record<string, unknown> | null;
|
|
||||||
//#endregion
|
|
||||||
export { asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asRecord, isRecord, readStringField };
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/record-coerce.ts
|
|
||||||
function isRecord(value) {
|
|
||||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
||||||
}
|
|
||||||
function asRecord(value) {
|
|
||||||
return typeof value === "object" && value !== null ? value : {};
|
|
||||||
}
|
|
||||||
function readStringField(record, key) {
|
|
||||||
const value = record?.[key];
|
|
||||||
return typeof value === "string" ? value : void 0;
|
|
||||||
}
|
|
||||||
function asOptionalRecord(value) {
|
|
||||||
return isRecord(value) ? value : void 0;
|
|
||||||
}
|
|
||||||
function asNullableRecord(value) {
|
|
||||||
return isRecord(value) ? value : null;
|
|
||||||
}
|
|
||||||
function asOptionalObjectRecord(value) {
|
|
||||||
return value && typeof value === "object" ? value : void 0;
|
|
||||||
}
|
|
||||||
function asNullableObjectRecord(value) {
|
|
||||||
return value && typeof value === "object" ? value : null;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { asNullableObjectRecord, asNullableRecord, asOptionalObjectRecord, asOptionalRecord, asRecord, isRecord, readStringField };
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/string-coerce.d.ts
|
|
||||||
declare function readStringValue(value: unknown): string | undefined;
|
|
||||||
declare function normalizeNullableString(value: unknown): string | null;
|
|
||||||
declare function normalizeOptionalString(value: unknown): string | undefined;
|
|
||||||
declare function normalizeStringifiedOptionalString(value: unknown): string | undefined;
|
|
||||||
declare function normalizeStringifiedEntries(values?: ReadonlyArray<unknown>): string[];
|
|
||||||
declare function normalizeOptionalLowercaseString(value: unknown): string | undefined;
|
|
||||||
declare function normalizeLowercaseStringOrEmpty(value: unknown): string;
|
|
||||||
declare function normalizeFastMode(raw?: string | boolean | null): boolean | undefined;
|
|
||||||
declare function lowercasePreservingWhitespace(value: string): string;
|
|
||||||
declare function localeLowercasePreservingWhitespace(value: string): string;
|
|
||||||
declare function resolvePrimaryStringValue(value: unknown): string | undefined;
|
|
||||||
declare function normalizeOptionalThreadValue(value: unknown): string | number | undefined;
|
|
||||||
declare function normalizeOptionalStringifiedId(value: unknown): string | undefined;
|
|
||||||
declare function hasNonEmptyString(value: unknown): value is string;
|
|
||||||
//#endregion
|
|
||||||
export { hasNonEmptyString, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, normalizeFastMode, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeStringifiedEntries, normalizeStringifiedOptionalString, readStringValue, resolvePrimaryStringValue };
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/string-coerce.ts
|
|
||||||
function readStringValue(value) {
|
|
||||||
return typeof value === "string" ? value : void 0;
|
|
||||||
}
|
|
||||||
function normalizeNullableString(value) {
|
|
||||||
if (typeof value !== "string") return null;
|
|
||||||
const trimmed = value.trim();
|
|
||||||
return trimmed ? trimmed : null;
|
|
||||||
}
|
|
||||||
function normalizeOptionalString(value) {
|
|
||||||
return normalizeNullableString(value) ?? void 0;
|
|
||||||
}
|
|
||||||
function normalizeStringifiedOptionalString(value) {
|
|
||||||
if (typeof value === "string") return normalizeOptionalString(value);
|
|
||||||
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return normalizeOptionalString(String(value));
|
|
||||||
}
|
|
||||||
function normalizeStringifiedEntries(values) {
|
|
||||||
return (values ?? []).map((entry) => normalizeStringifiedOptionalString(entry)).filter((entry) => Boolean(entry));
|
|
||||||
}
|
|
||||||
function normalizeOptionalLowercaseString(value) {
|
|
||||||
return normalizeOptionalString(value)?.toLowerCase();
|
|
||||||
}
|
|
||||||
function normalizeLowercaseStringOrEmpty(value) {
|
|
||||||
return normalizeOptionalLowercaseString(value) ?? "";
|
|
||||||
}
|
|
||||||
function normalizeFastMode(raw) {
|
|
||||||
if (typeof raw === "boolean") return raw;
|
|
||||||
if (!raw) return;
|
|
||||||
const key = normalizeLowercaseStringOrEmpty(raw);
|
|
||||||
if ([
|
|
||||||
"off",
|
|
||||||
"false",
|
|
||||||
"no",
|
|
||||||
"0",
|
|
||||||
"disable",
|
|
||||||
"disabled",
|
|
||||||
"normal"
|
|
||||||
].includes(key)) return false;
|
|
||||||
if ([
|
|
||||||
"on",
|
|
||||||
"true",
|
|
||||||
"yes",
|
|
||||||
"1",
|
|
||||||
"enable",
|
|
||||||
"enabled",
|
|
||||||
"fast"
|
|
||||||
].includes(key)) return true;
|
|
||||||
}
|
|
||||||
function lowercasePreservingWhitespace(value) {
|
|
||||||
return value.toLowerCase();
|
|
||||||
}
|
|
||||||
function localeLowercasePreservingWhitespace(value) {
|
|
||||||
return value.toLocaleLowerCase();
|
|
||||||
}
|
|
||||||
function resolvePrimaryStringValue(value) {
|
|
||||||
if (typeof value === "string") return normalizeOptionalString(value);
|
|
||||||
if (!value || typeof value !== "object") return;
|
|
||||||
return normalizeOptionalString(value.primary);
|
|
||||||
}
|
|
||||||
function normalizeOptionalThreadValue(value) {
|
|
||||||
if (typeof value === "number") return Number.isFinite(value) ? Math.trunc(value) : void 0;
|
|
||||||
return normalizeOptionalString(value);
|
|
||||||
}
|
|
||||||
function normalizeOptionalStringifiedId(value) {
|
|
||||||
const normalized = normalizeOptionalThreadValue(value);
|
|
||||||
return normalized == null ? void 0 : String(normalized);
|
|
||||||
}
|
|
||||||
function hasNonEmptyString(value) {
|
|
||||||
return normalizeOptionalString(value) !== void 0;
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { hasNonEmptyString, localeLowercasePreservingWhitespace, lowercasePreservingWhitespace, normalizeFastMode, normalizeLowercaseStringOrEmpty, normalizeNullableString, normalizeOptionalLowercaseString, normalizeOptionalString, normalizeOptionalStringifiedId, normalizeOptionalThreadValue, normalizeStringifiedEntries, normalizeStringifiedOptionalString, readStringValue, resolvePrimaryStringValue };
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
//#region packages/normalization-core/src/string-normalization.d.ts
|
|
||||||
declare function normalizeStringEntries(list?: ReadonlyArray<unknown>): string[];
|
|
||||||
declare function normalizeStringEntriesLower(list?: ReadonlyArray<unknown>): string[];
|
|
||||||
declare function uniqueValues<T>(values: Iterable<T>): T[];
|
|
||||||
declare function uniqueStrings(values: Iterable<string>): string[];
|
|
||||||
declare function sortUniqueStrings(values: Iterable<string>): string[];
|
|
||||||
declare function normalizeUniqueStringEntries(values?: Iterable<unknown>): string[];
|
|
||||||
declare function normalizeUniqueStringEntriesLower(values?: Iterable<unknown>): string[];
|
|
||||||
declare function normalizeSortedUniqueStringEntries(values?: Iterable<unknown>): string[];
|
|
||||||
declare function normalizeTrimmedStringList(value: unknown): string[];
|
|
||||||
declare function normalizeUniqueTrimmedStringList(value: unknown): string[];
|
|
||||||
declare function normalizeSortedUniqueTrimmedStringList(value: unknown): string[];
|
|
||||||
declare function normalizeOptionalTrimmedStringList(value: unknown): string[] | undefined;
|
|
||||||
declare function normalizeArrayBackedTrimmedStringList(value: unknown): string[] | undefined;
|
|
||||||
declare function normalizeSingleOrTrimmedStringList(value: unknown): string[];
|
|
||||||
declare function normalizeUniqueSingleOrTrimmedStringList(value: unknown): string[];
|
|
||||||
declare function normalizeCsvOrLooseStringList(value: unknown): string[];
|
|
||||||
declare function normalizeHyphenSlug(raw?: string | null): string;
|
|
||||||
declare function normalizeAtHashSlug(raw?: string | null): string;
|
|
||||||
//#endregion
|
|
||||||
export { normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeHyphenSlug, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, sortUniqueStrings, uniqueStrings, uniqueValues };
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
import { normalizeOptionalLowercaseString, normalizeOptionalString } from "./string-coerce.mjs";
|
|
||||||
//#region packages/normalization-core/src/string-normalization.ts
|
|
||||||
function normalizeStringEntries(list) {
|
|
||||||
return (list ?? []).map((entry) => normalizeOptionalString(String(entry)) ?? "").filter(Boolean);
|
|
||||||
}
|
|
||||||
function normalizeStringEntriesLower(list) {
|
|
||||||
return normalizeStringEntries(list).map((entry) => normalizeOptionalLowercaseString(entry) ?? "");
|
|
||||||
}
|
|
||||||
function uniqueValues(values) {
|
|
||||||
return [...new Set(values)];
|
|
||||||
}
|
|
||||||
function uniqueStrings(values) {
|
|
||||||
return uniqueValues(values);
|
|
||||||
}
|
|
||||||
function sortUniqueStrings(values) {
|
|
||||||
return uniqueStrings(values).toSorted((left, right) => left < right ? -1 : left > right ? 1 : 0);
|
|
||||||
}
|
|
||||||
function normalizeUniqueStringEntries(values) {
|
|
||||||
return uniqueStrings(normalizeStringEntries(values ? [...values] : void 0));
|
|
||||||
}
|
|
||||||
function normalizeUniqueStringEntriesLower(values) {
|
|
||||||
return uniqueStrings(normalizeStringEntriesLower(values ? [...values] : void 0).filter(Boolean));
|
|
||||||
}
|
|
||||||
function normalizeSortedUniqueStringEntries(values) {
|
|
||||||
return sortUniqueStrings(normalizeUniqueStringEntries(values));
|
|
||||||
}
|
|
||||||
function normalizeTrimmedStringList(value) {
|
|
||||||
if (!Array.isArray(value)) return [];
|
|
||||||
return value.flatMap((entry) => {
|
|
||||||
const normalized = normalizeOptionalString(entry);
|
|
||||||
return normalized ? [normalized] : [];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function normalizeUniqueTrimmedStringList(value) {
|
|
||||||
return uniqueStrings(normalizeTrimmedStringList(value));
|
|
||||||
}
|
|
||||||
function normalizeSortedUniqueTrimmedStringList(value) {
|
|
||||||
return sortUniqueStrings(normalizeTrimmedStringList(value));
|
|
||||||
}
|
|
||||||
function normalizeOptionalTrimmedStringList(value) {
|
|
||||||
const normalized = normalizeTrimmedStringList(value);
|
|
||||||
return normalized.length > 0 ? normalized : void 0;
|
|
||||||
}
|
|
||||||
function normalizeArrayBackedTrimmedStringList(value) {
|
|
||||||
if (!Array.isArray(value)) return;
|
|
||||||
return normalizeTrimmedStringList(value);
|
|
||||||
}
|
|
||||||
function normalizeSingleOrTrimmedStringList(value) {
|
|
||||||
if (Array.isArray(value)) return normalizeTrimmedStringList(value);
|
|
||||||
const normalized = normalizeOptionalString(value);
|
|
||||||
return normalized ? [normalized] : [];
|
|
||||||
}
|
|
||||||
function normalizeUniqueSingleOrTrimmedStringList(value) {
|
|
||||||
return uniqueStrings(normalizeSingleOrTrimmedStringList(value));
|
|
||||||
}
|
|
||||||
function normalizeCsvOrLooseStringList(value) {
|
|
||||||
if (Array.isArray(value)) return normalizeStringEntries(value);
|
|
||||||
if (typeof value === "string") return value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
function normalizeSlugInput(raw) {
|
|
||||||
return (normalizeOptionalLowercaseString(raw) ?? "").normalize("NFC");
|
|
||||||
}
|
|
||||||
function normalizeHyphenSlug(raw) {
|
|
||||||
const trimmed = normalizeSlugInput(raw);
|
|
||||||
if (!trimmed) return "";
|
|
||||||
return trimmed.replace(/\s+/g, "-").replace(/[^\p{L}\p{M}\p{N}#@._+-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
|
|
||||||
}
|
|
||||||
function normalizeAtHashSlug(raw) {
|
|
||||||
const trimmed = normalizeSlugInput(raw);
|
|
||||||
if (!trimmed) return "";
|
|
||||||
return trimmed.replace(/^[@#]+/, "").replace(/[\s_]+/g, "-").replace(/[^\p{L}\p{M}\p{N}-]+/gu, "-").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { normalizeArrayBackedTrimmedStringList, normalizeAtHashSlug, normalizeCsvOrLooseStringList, normalizeHyphenSlug, normalizeOptionalTrimmedStringList, normalizeSingleOrTrimmedStringList, normalizeSortedUniqueStringEntries, normalizeSortedUniqueTrimmedStringList, normalizeStringEntries, normalizeStringEntriesLower, normalizeTrimmedStringList, normalizeUniqueSingleOrTrimmedStringList, normalizeUniqueStringEntries, normalizeUniqueStringEntriesLower, normalizeUniqueTrimmedStringList, sortUniqueStrings, uniqueStrings, uniqueValues };
|
|
||||||
2
packages/web-content-core/dist/index.d.mts
vendored
2
packages/web-content-core/dist/index.d.mts
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { WebProviderConfigSource, hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition } from "./provider-runtime-shared.mjs";
|
|
||||||
export { WebProviderConfigSource, hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition };
|
|
||||||
2
packages/web-content-core/dist/index.mjs
vendored
2
packages/web-content-core/dist/index.mjs
vendored
@@ -1,2 +0,0 @@
|
|||||||
import { hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition } from "./provider-runtime-shared.mjs";
|
|
||||||
export { hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition };
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
//#region packages/web-content-core/src/provider-runtime-shared.d.ts
|
|
||||||
type WebProviderConfigSource = {
|
|
||||||
tools?: {
|
|
||||||
web?: {
|
|
||||||
search?: unknown;
|
|
||||||
fetch?: unknown;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
type RuntimeWebProviderMetadata = {
|
|
||||||
providerConfigured?: string;
|
|
||||||
selectedProvider?: string;
|
|
||||||
};
|
|
||||||
type ProviderWithCredential = {
|
|
||||||
envVars: string[];
|
|
||||||
authProviderId?: string;
|
|
||||||
requiresCredential?: boolean;
|
|
||||||
};
|
|
||||||
type WebContentProcessEnv = Record<string, string | undefined>;
|
|
||||||
declare function resolveWebProviderConfig(cfg: WebProviderConfigSource | undefined, kind: "search" | "fetch"): Record<string, unknown> | undefined;
|
|
||||||
declare function readWebProviderEnvValue(envVars: string[], processEnv?: WebContentProcessEnv): string | undefined;
|
|
||||||
declare function providerRequiresCredential(provider: Pick<ProviderWithCredential, "requiresCredential">): boolean;
|
|
||||||
declare function hasWebProviderEntryCredential<TProvider extends ProviderWithCredential, TConfigSource extends WebProviderConfigSource, TConfig extends Record<string, unknown> | undefined>(params: {
|
|
||||||
provider: TProvider;
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
resolveRawValue: (params: {
|
|
||||||
provider: TProvider;
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
}) => unknown;
|
|
||||||
resolveFallbackRawValue?: (params: {
|
|
||||||
provider: TProvider;
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
}) => unknown;
|
|
||||||
resolveEnvValue: (params: {
|
|
||||||
provider: TProvider;
|
|
||||||
configuredEnvVarId?: string;
|
|
||||||
}) => string | undefined;
|
|
||||||
resolveProviderAuthValue?: (providerId: string) => boolean;
|
|
||||||
}): boolean;
|
|
||||||
declare function resolveWebProviderDefinition<TProvider extends {
|
|
||||||
id: string;
|
|
||||||
}, TConfigSource extends WebProviderConfigSource, TConfig extends Record<string, unknown> | undefined, TRuntimeMetadata extends RuntimeWebProviderMetadata, TDefinition>(params: {
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
runtimeMetadata: TRuntimeMetadata | undefined;
|
|
||||||
sandboxed?: boolean;
|
|
||||||
providerId?: string;
|
|
||||||
providers: TProvider[];
|
|
||||||
resolveEnabled: (params: {
|
|
||||||
toolConfig: TConfig;
|
|
||||||
sandboxed?: boolean;
|
|
||||||
}) => boolean;
|
|
||||||
resolveAutoProviderId: (params: {
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
providers: TProvider[];
|
|
||||||
}) => string;
|
|
||||||
resolveFallbackProviderId?: (params: {
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
providers: TProvider[];
|
|
||||||
providerId: string;
|
|
||||||
}) => string | undefined;
|
|
||||||
createTool: (params: {
|
|
||||||
provider: TProvider;
|
|
||||||
config: TConfigSource | undefined;
|
|
||||||
toolConfig: TConfig;
|
|
||||||
runtimeMetadata: TRuntimeMetadata | undefined;
|
|
||||||
}) => TDefinition | null;
|
|
||||||
}): {
|
|
||||||
provider: TProvider;
|
|
||||||
definition: TDefinition;
|
|
||||||
} | null;
|
|
||||||
//#endregion
|
|
||||||
export { WebProviderConfigSource, hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition };
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
//#region packages/web-content-core/src/provider-runtime-shared.ts
|
|
||||||
const DEFAULT_SECRET_PROVIDER_ALIAS = "default";
|
|
||||||
const ENV_SECRET_REF_ID_RE = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
||||||
const LEGACY_SECRETREF_ENV_MARKER_PREFIX = "secretref-env:";
|
|
||||||
const LEGACY_DOUBLE_UNDERSCORE_ENV_MARKER_PREFIX = "__env__:";
|
|
||||||
const ENV_SECRET_TEMPLATE_RE = /^\$\{([A-Z][A-Z0-9_]{0,127})\}$/;
|
|
||||||
const ENV_SECRET_SHORTHAND_RE = /^\$([A-Z][A-Z0-9_]{0,127})$/;
|
|
||||||
function isRecord(value) {
|
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
||||||
}
|
|
||||||
function normalizeSecretInputString(value) {
|
|
||||||
if (typeof value !== "string") return;
|
|
||||||
const trimmed = value.trim();
|
|
||||||
return trimmed.length > 0 ? trimmed : void 0;
|
|
||||||
}
|
|
||||||
function normalizeSecretInput(value) {
|
|
||||||
if (typeof value !== "string") return "";
|
|
||||||
const collapsed = value.replace(/[\r\n\u2028\u2029]+/g, "");
|
|
||||||
let latin1Only = "";
|
|
||||||
for (const char of collapsed) {
|
|
||||||
const codePoint = char.codePointAt(0);
|
|
||||||
if (typeof codePoint === "number" && codePoint <= 255) latin1Only += char;
|
|
||||||
}
|
|
||||||
return latin1Only.trim();
|
|
||||||
}
|
|
||||||
function isSecretRef(value) {
|
|
||||||
if (!isRecord(value)) return false;
|
|
||||||
if (Object.keys(value).length !== 3) return false;
|
|
||||||
return (value.source === "env" || value.source === "file" || value.source === "exec") && typeof value.provider === "string" && value.provider.trim().length > 0 && typeof value.id === "string" && value.id.trim().length > 0;
|
|
||||||
}
|
|
||||||
function coerceSecretRef(value) {
|
|
||||||
if (isSecretRef(value)) return value;
|
|
||||||
if (typeof value === "string") {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
const legacyPrefix = trimmed.startsWith(LEGACY_SECRETREF_ENV_MARKER_PREFIX) ? LEGACY_SECRETREF_ENV_MARKER_PREFIX : trimmed.startsWith(LEGACY_DOUBLE_UNDERSCORE_ENV_MARKER_PREFIX) ? LEGACY_DOUBLE_UNDERSCORE_ENV_MARKER_PREFIX : void 0;
|
|
||||||
if (legacyPrefix) {
|
|
||||||
const id = trimmed.slice(legacyPrefix.length);
|
|
||||||
return ENV_SECRET_REF_ID_RE.test(id) ? {
|
|
||||||
source: "env",
|
|
||||||
provider: DEFAULT_SECRET_PROVIDER_ALIAS,
|
|
||||||
id
|
|
||||||
} : null;
|
|
||||||
}
|
|
||||||
const match = ENV_SECRET_TEMPLATE_RE.exec(trimmed) ?? ENV_SECRET_SHORTHAND_RE.exec(trimmed);
|
|
||||||
return match ? {
|
|
||||||
source: "env",
|
|
||||||
provider: DEFAULT_SECRET_PROVIDER_ALIAS,
|
|
||||||
id: match[1]
|
|
||||||
} : null;
|
|
||||||
}
|
|
||||||
if (isRecord(value) && (value.source === "env" || value.source === "file" || value.source === "exec") && typeof value.id === "string" && value.id.trim().length > 0 && value.provider === void 0) return {
|
|
||||||
source: value.source,
|
|
||||||
provider: DEFAULT_SECRET_PROVIDER_ALIAS,
|
|
||||||
id: value.id
|
|
||||||
};
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
function resolveWebProviderConfig(cfg, kind) {
|
|
||||||
const webConfig = cfg?.tools?.web;
|
|
||||||
if (!webConfig || typeof webConfig !== "object") return;
|
|
||||||
const toolConfig = webConfig[kind];
|
|
||||||
if (!toolConfig || typeof toolConfig !== "object") return;
|
|
||||||
return toolConfig;
|
|
||||||
}
|
|
||||||
function readWebProviderEnvValue(envVars, processEnv = process.env) {
|
|
||||||
for (const envVar of envVars) {
|
|
||||||
const value = normalizeSecretInput(processEnv[envVar]);
|
|
||||||
if (value) return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function providerRequiresCredential(provider) {
|
|
||||||
return provider.requiresCredential !== false;
|
|
||||||
}
|
|
||||||
function hasWebProviderEntryCredential(params) {
|
|
||||||
if (!providerRequiresCredential(params.provider)) return true;
|
|
||||||
const rawValue = params.resolveRawValue({
|
|
||||||
provider: params.provider,
|
|
||||||
config: params.config,
|
|
||||||
toolConfig: params.toolConfig
|
|
||||||
});
|
|
||||||
const configuredRef = coerceSecretRef(rawValue);
|
|
||||||
if (configuredRef && configuredRef.source !== "env") return true;
|
|
||||||
if (normalizeSecretInput(normalizeSecretInputString(rawValue))) return true;
|
|
||||||
if (params.provider.authProviderId && params.resolveProviderAuthValue?.(params.provider.authProviderId)) return true;
|
|
||||||
if (params.resolveEnvValue({
|
|
||||||
provider: params.provider,
|
|
||||||
configuredEnvVarId: configuredRef?.source === "env" ? configuredRef.id : void 0
|
|
||||||
})) return true;
|
|
||||||
const fallbackRawValue = params.resolveFallbackRawValue?.({
|
|
||||||
provider: params.provider,
|
|
||||||
config: params.config,
|
|
||||||
toolConfig: params.toolConfig
|
|
||||||
});
|
|
||||||
const fallbackRef = coerceSecretRef(fallbackRawValue);
|
|
||||||
if (fallbackRef && fallbackRef.source !== "env") return true;
|
|
||||||
if (normalizeSecretInput(normalizeSecretInputString(fallbackRawValue))) return true;
|
|
||||||
return Boolean(fallbackRef?.source === "env" ? params.resolveEnvValue({
|
|
||||||
provider: params.provider,
|
|
||||||
configuredEnvVarId: fallbackRef.id
|
|
||||||
}) : void 0);
|
|
||||||
}
|
|
||||||
function resolveWebProviderDefinition(params) {
|
|
||||||
if (!params.resolveEnabled({
|
|
||||||
toolConfig: params.toolConfig,
|
|
||||||
sandboxed: params.sandboxed
|
|
||||||
})) return null;
|
|
||||||
const providers = params.providers.filter(Boolean);
|
|
||||||
if (providers.length === 0) return null;
|
|
||||||
const autoProviderId = params.resolveAutoProviderId({
|
|
||||||
config: params.config,
|
|
||||||
toolConfig: params.toolConfig,
|
|
||||||
providers
|
|
||||||
});
|
|
||||||
const providerId = params.providerId ?? params.runtimeMetadata?.selectedProvider ?? autoProviderId;
|
|
||||||
if (!providerId) return null;
|
|
||||||
const provider = providers.find((entry) => entry.id === providerId) ?? providers.find((entry) => entry.id === params.resolveFallbackProviderId?.({
|
|
||||||
config: params.config,
|
|
||||||
toolConfig: params.toolConfig,
|
|
||||||
providers,
|
|
||||||
providerId
|
|
||||||
}));
|
|
||||||
if (!provider) return null;
|
|
||||||
const definition = params.createTool({
|
|
||||||
provider,
|
|
||||||
config: params.config,
|
|
||||||
toolConfig: params.toolConfig,
|
|
||||||
runtimeMetadata: params.runtimeMetadata
|
|
||||||
});
|
|
||||||
if (!definition) return null;
|
|
||||||
return {
|
|
||||||
provider,
|
|
||||||
definition
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//#endregion
|
|
||||||
export { hasWebProviderEntryCredential, providerRequiresCredential, readWebProviderEnvValue, resolveWebProviderConfig, resolveWebProviderDefinition };
|
|
||||||
Reference in New Issue
Block a user