@tangle-network/agent-app 0.43.76 → 0.44.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/DesignCanvas-Z362I3R3.js +10 -0
- package/dist/{DesignCanvasEditor-FJIVYOA2.js → DesignCanvasEditor-ZFE2W4OJ.js} +4 -4
- package/dist/assets/index.d.ts +4 -4
- package/dist/assets/index.js +223 -11
- package/dist/assets/index.js.map +1 -1
- package/dist/assistant/index.d.ts +7 -7
- package/dist/assistant/index.js +3 -3
- package/dist/assistant/index.js.map +1 -1
- package/dist/{attachment-validation-Dv1A_Puy.d.ts → attachment-validation-DRuLEjAE.d.ts} +1 -1
- package/dist/{auth-_FU8w01b.d.ts → auth-anc7mv2W.d.ts} +2 -2
- package/dist/chat-routes/index.d.ts +65 -14
- package/dist/chat-routes/index.js +61 -24
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-store/index.d.ts +26 -7
- package/dist/chat-store/index.js +14 -5
- package/dist/chat-store/index.js.map +1 -1
- package/dist/{chunk-ROLFDOMJ.js → chunk-4TI7QWLW.js} +3 -3
- package/dist/{chunk-3JUTOVUH.js → chunk-6KMAM7BL.js} +1 -1
- package/dist/chunk-6KMAM7BL.js.map +1 -0
- package/dist/{chunk-WL7XHLDK.js → chunk-ICOHEZK6.js} +77 -5
- package/dist/chunk-ICOHEZK6.js.map +1 -0
- package/dist/{chunk-22GLESKE.js → chunk-O63WWYET.js} +2 -4
- package/dist/chunk-O63WWYET.js.map +1 -0
- package/dist/{chunk-E7N67FYI.js → chunk-Q3FONVAK.js} +5 -5
- package/dist/{chunk-E7N67FYI.js.map → chunk-Q3FONVAK.js.map} +1 -1
- package/dist/{chunk-RXOTWZ4G.js → chunk-TKRI463Z.js} +4 -4
- package/dist/chunk-TKRI463Z.js.map +1 -0
- package/dist/config/index.d.ts +1 -1
- package/dist/config/index.js +123 -4
- package/dist/config/index.js.map +1 -1
- package/dist/{contract-B3h7peV3.d.ts → contract-CEewO6DI.d.ts} +1 -1
- package/dist/design-canvas/index.d.ts +4 -4
- package/dist/design-canvas-react/index.js +7 -7
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/index.d.ts +1 -1
- package/dist/eval/index.js +22 -8
- package/dist/eval/index.js.map +1 -1
- package/dist/{flow-types-CqomVAUN.d.ts → flow-types-CJxEmaRy.d.ts} +1 -1
- package/dist/integrations/index.js +67 -5
- package/dist/integrations/index.js.map +1 -1
- package/dist/interactions/index.d.ts +6 -4
- package/dist/interactions/index.js +1 -2
- package/dist/knowledge/index.js +63 -4
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge-loop/index.d.ts +1 -1
- package/dist/knowledge-loop/index.js +94 -4
- package/dist/knowledge-loop/index.js.map +1 -1
- package/dist/{mcp-BjPqQ-3C.d.ts → mcp-D3qVzbE1.d.ts} +2 -2
- package/dist/{mcp-rpc-BfUOsalw.d.ts → mcp-rpc-CzU5LWWT.d.ts} +1 -1
- package/dist/missions/index.js +1143 -23
- package/dist/missions/index.js.map +1 -1
- package/dist/{model-DmdkIteM.d.ts → model-CdCDfBA9.d.ts} +1 -1
- package/dist/object-store/index.js +113 -8
- package/dist/object-store/index.js.map +1 -1
- package/dist/{parts-2ymE5cs-.d.ts → parts-Co_lFgLI.d.ts} +3 -3
- package/dist/platform/index.d.ts +1 -1
- package/dist/preflight/cli.d.ts +13 -0
- package/dist/preflight/cli.js +50 -0
- package/dist/preflight/cli.js.map +1 -0
- package/dist/preset-cloudflare/index.d.ts +1 -1
- package/dist/preset-cloudflare/index.js +284 -11
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/{queue-C24V13h9.d.ts → queue-CD5-_VTX.d.ts} +1 -1
- package/dist/redact/index.js +116 -8
- package/dist/redact/index.js.map +1 -1
- package/dist/runtime/index.d.ts +19 -111
- package/dist/runtime/index.js +234 -14
- package/dist/runtime/index.js.map +1 -1
- package/dist/sandbox/index.d.ts +3 -3
- package/dist/sandbox/index.js +2 -3
- package/dist/sequences/index.d.ts +4 -4
- package/dist/stream/index.d.ts +4 -4
- package/dist/{stream-normalizer-QYUl4vnl.d.ts → stream-normalizer-DnuqkZvw.d.ts} +2 -2
- package/dist/tangle/index.js +42 -4
- package/dist/tangle/index.js.map +1 -1
- package/dist/teams/index.js +5 -5
- package/dist/teams/invitations-api.js +4 -4
- package/dist/teams-react/index.js +3 -3
- package/dist/theme/index.js +0 -1
- package/dist/tools/index.d.ts +6 -6
- package/dist/tools/index.js +5 -7
- package/dist/trace/index.d.ts +1 -1
- package/dist/trace/index.js +179 -10
- package/dist/trace/index.js.map +1 -1
- package/dist/{turn-buffer-BaSgxVmK.d.ts → turn-buffer-BcPfhr1_.d.ts} +1 -1
- package/dist/turn-stream/index.d.ts +1 -1
- package/dist/{types-CBRyqijY.d.ts → types-BCxK0wyS.d.ts} +1 -1
- package/dist/{types-CEchbvgz.d.ts → types-XIZqIdX1.d.ts} +1 -1
- package/dist/web-react/index.d.ts +10 -10
- package/dist/web-react/index.js +5 -5
- package/dist/work-product/index.d.ts +4 -4
- package/dist/work-product/index.js +735 -15
- package/dist/work-product/index.js.map +1 -1
- package/dist/work-product-react/index.d.ts +1 -1
- package/dist/work-product-react/index.js.map +1 -1
- package/package.json +4 -19
- package/dist/DesignCanvas-UNL34LS2.js +0 -12
- package/dist/chunk-22GLESKE.js.map +0 -1
- package/dist/chunk-3JUTOVUH.js.map +0 -1
- package/dist/chunk-5EQCITY3.js +0 -20
- package/dist/chunk-5EQCITY3.js.map +0 -1
- package/dist/chunk-5SD6HT2V.js +0 -236
- package/dist/chunk-5SD6HT2V.js.map +0 -1
- package/dist/chunk-5TESA4SN.js +0 -74
- package/dist/chunk-5TESA4SN.js.map +0 -1
- package/dist/chunk-6GQ5DKFK.js +0 -920
- package/dist/chunk-6GQ5DKFK.js.map +0 -1
- package/dist/chunk-7ESQUSAC.js +0 -343
- package/dist/chunk-7ESQUSAC.js.map +0 -1
- package/dist/chunk-7LNGJDNA.js +0 -1
- package/dist/chunk-7LNGJDNA.js.map +0 -1
- package/dist/chunk-AP2UXKUK.js +0 -69
- package/dist/chunk-AP2UXKUK.js.map +0 -1
- package/dist/chunk-FA4XR66Y.js +0 -32
- package/dist/chunk-FA4XR66Y.js.map +0 -1
- package/dist/chunk-FKCB5FTD.js +0 -126
- package/dist/chunk-FKCB5FTD.js.map +0 -1
- package/dist/chunk-GPBRL2XR.js +0 -102
- package/dist/chunk-GPBRL2XR.js.map +0 -1
- package/dist/chunk-HRH7ASAG.js +0 -759
- package/dist/chunk-HRH7ASAG.js.map +0 -1
- package/dist/chunk-HYTIHYNV.js +0 -297
- package/dist/chunk-HYTIHYNV.js.map +0 -1
- package/dist/chunk-LGBO24FL.js +0 -190
- package/dist/chunk-LGBO24FL.js.map +0 -1
- package/dist/chunk-NLSSFLLS.js +0 -1168
- package/dist/chunk-NLSSFLLS.js.map +0 -1
- package/dist/chunk-OSMNYPOG.js +0 -129
- package/dist/chunk-OSMNYPOG.js.map +0 -1
- package/dist/chunk-QYOD3K56.js +0 -124
- package/dist/chunk-QYOD3K56.js.map +0 -1
- package/dist/chunk-RXOTWZ4G.js.map +0 -1
- package/dist/chunk-UAKFCMWK.js +0 -1
- package/dist/chunk-UAKFCMWK.js.map +0 -1
- package/dist/chunk-UKTYKG57.js +0 -48
- package/dist/chunk-UKTYKG57.js.map +0 -1
- package/dist/chunk-UOAYS72M.js +0 -80
- package/dist/chunk-UOAYS72M.js.map +0 -1
- package/dist/chunk-WL7XHLDK.js.map +0 -1
- package/dist/composer/index.d.ts +0 -2
- package/dist/composer/index.js +0 -22
- package/dist/composer/index.js.map +0 -1
- package/dist/core-7qIM7svy.d.ts +0 -21
- package/dist/durable-chat/index.d.ts +0 -464
- package/dist/durable-chat/index.js +0 -59
- package/dist/durable-chat/index.js.map +0 -1
- package/dist/index.d.ts +0 -51
- package/dist/index.js +0 -827
- package/dist/index.js.map +0 -1
- /package/dist/{DesignCanvas-UNL34LS2.js.map → DesignCanvas-Z362I3R3.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-FJIVYOA2.js.map → DesignCanvasEditor-ZFE2W4OJ.js.map} +0 -0
- /package/dist/{chunk-ROLFDOMJ.js.map → chunk-4TI7QWLW.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/durable-chat/errors.ts","../src/durable-chat/types.ts","../src/durable-chat/memory.ts","../src/durable-chat/interactions.ts","../src/durable-chat/adapters.ts","../src/durable-chat/plan-routes.ts"],"sourcesContent":["/** Define error codes representing possible Durable Chat failure scenarios */\nexport type DurableChatErrorCode =\n | 'DURABLE_CHAT_BAD_REQUEST'\n | 'DURABLE_CHAT_UNAUTHORIZED'\n | 'DURABLE_CHAT_CONFLICT'\n | 'DURABLE_CHAT_UNAVAILABLE'\n | 'DURABLE_CHAT_GONE'\n | 'DURABLE_CHAT_NOT_FOUND'\n\n/** Typed, fail-loud errors for adapters and route seams. */\nexport class DurableChatError extends Error {\n readonly code: DurableChatErrorCode\n readonly status: number\n readonly details?: unknown\n\n constructor(code: DurableChatErrorCode, message: string, status: number, details?: unknown) {\n super(message)\n this.name = 'DurableChatError'\n this.code = code\n this.status = status\n this.details = details\n }\n}\n\n/** Represent conflict errors occurring in durable chat state management */\nexport class DurableChatConflictError extends DurableChatError {\n constructor(message = 'durable chat state conflict', details?: unknown) {\n super('DURABLE_CHAT_CONFLICT', message, 409, details)\n this.name = 'DurableChatConflictError'\n }\n}\n\n/** Represent unavailable durable chat authority errors with status code 503 */\nexport class DurableChatUnavailableError extends DurableChatError {\n constructor(message = 'durable chat authority unavailable', details?: unknown) {\n super('DURABLE_CHAT_UNAVAILABLE', message, 503, details)\n this.name = 'DurableChatUnavailableError'\n }\n}\n\n/** Represent durable chat errors indicating the chat plan is no longer available */\nexport class DurableChatGoneError extends DurableChatError {\n constructor(message = 'durable chat plan is gone', details?: unknown) {\n super('DURABLE_CHAT_GONE', message, 410, details)\n this.name = 'DurableChatGoneError'\n }\n}\n","import type {\n ChatInteraction,\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswerValue,\n InteractionAnswers,\n} from '../interactions/contract'\nimport type { ChatPlan, ChatPlanStatus } from '../plans/index'\n\n/** An authorization-derived tenant/thread scope. Consumers should only\n * create this value after authenticating the request; the route never accepts\n * an identity or scope from the request body. */\nexport type DurableChatScope = string & { readonly __durableChatScope: unique symbol }\n\n/** Create a durable chat scope from a non-empty string value */\nexport function createDurableChatScope(value: string): DurableChatScope {\n if (typeof value !== 'string' || value.trim() === '') throw new TypeError('durable chat scope must be a non-empty string')\n return value as DurableChatScope\n}\n\n/** Resolve a valid durable chat scope key from the given scope input */\nexport function durableChatScopeKey(scope: DurableChatScope): string {\n if (typeof scope !== 'string' || scope.length === 0) throw new TypeError('durable chat scope is required')\n return scope\n}\n\n/** Represent durable plan outcomes as either approved or rejected */\nexport type DurablePlanDecision = 'approved' | 'rejected'\n/** Resolve durable plan authority decisions including approval, rejection, or predefined durable decisions */\nexport type DurablePlanAuthorityDecision = DurablePlanDecision | 'approve' | 'reject'\n\n/** Projection retained by a durable store. It is intentionally compatible\n * with the browser `/plans` projection and adds no product-specific fields. */\nexport type DurablePlanProjection = ChatPlan & {\n metadata?: Record<string, unknown>\n decidedBy?: string\n}\n\n/** Represent a unique identifier key for durable plan commands */\nexport type DurablePlanCommandKey = string\n\n/** Define possible states for a durable plan command in its lifecycle */\nexport type DurablePlanCommandState =\n | 'claimed'\n | 'authority_committed'\n | 'finalized'\n | 'conflicted'\n\n/** Define the structure for recording durable plan commands with associated metadata and state information */\nexport interface DurablePlanCommandRecord {\n scope: DurableChatScope\n planId: string\n revision: number\n decision: DurablePlanDecision\n commandKey: DurablePlanCommandKey\n authorityIdempotencyKey: string\n state: DurablePlanCommandState\n claimedAt: string\n authorityResult?: DurablePlanAuthorityResult\n receipt?: DurableFollowUpReceipt\n conflict?: string\n}\n\n/** Represent the current authoritative state and optional receipt of a durable plan authority */\nexport interface DurablePlanAuthorityCurrentResult {\n /** Authoritative state. `null` means the authority has forgotten the plan. */\n plan: DurablePlanProjection | null\n receipt?: DurableFollowUpReceipt\n}\n\n/** Define a durable receipt capturing stable identifiers and state for follow-up decisions */\nexport interface DurableFollowUpReceipt {\n /** Stable for a scope + plan + revision + decision. */\n receiptId: string\n planId: string\n revision: number\n decision: DurablePlanDecision\n turnId: string\n state: string\n /** Authority's stable idempotency key, useful when reconciling. */\n authorityIdempotencyKey: string\n}\n\n/** Describe the outcome of an authority's durable plan decision including follow-up and metadata */\nexport interface DurablePlanAuthorityResult {\n /** Authority's final plan projection. */\n plan: DurablePlanProjection\n /** Sandbox-style follow-up result. */\n followUp: { turnId: string; state: string }\n /** True when the authority served a previously committed decision. */\n idempotent?: boolean\n /** Stable authority operation id, if the provider has one. */\n authorityId?: string\n receipt?: DurableFollowUpReceipt\n}\n\n/** Structural port to Sandbox (or another durable plan authority). */\nexport interface DurablePlanAuthority {\n current(args: {\n scope: DurableChatScope\n planId: string\n revision?: number\n }): Promise<DurablePlanAuthorityCurrentResult | DurablePlanProjection | null>\n decide(args: {\n scope: DurableChatScope\n planId: string\n revision: number\n decision: DurablePlanDecision\n feedback?: string\n idempotencyKey: string\n }): Promise<DurablePlanAuthorityResult>\n}\n\n/** Define the structure for recording the state and metadata of a durable plan effect */\nexport interface DurablePlanEffectRecord {\n effectKey: string\n scope: DurableChatScope\n planId: string\n revision: number\n decision: DurablePlanDecision\n state: 'claimed' | 'completed' | 'error'\n claimedAt: string\n completedAt?: string\n error?: string\n}\n\n/** Manage durable storage and retrieval of plan projections, commands, and effects within a scoped context */\nexport interface DurablePlanStore {\n getPlanProjection(scope: DurableChatScope, planId: string, revision?: number): Promise<DurablePlanProjection | null>\n putPlanProjection(scope: DurableChatScope, projection: DurablePlanProjection): Promise<void>\n listPlanProjections?(scope: DurableChatScope, planId?: string): Promise<DurablePlanProjection[]>\n getPlanCommand(scope: DurableChatScope, commandKey: DurablePlanCommandKey): Promise<DurablePlanCommandRecord | null>\n claimPlanCommand(scope: DurableChatScope, command: DurablePlanCommandRecord): Promise<\n | { status: 'claimed'; record: DurablePlanCommandRecord }\n | { status: 'existing'; record: DurablePlanCommandRecord }\n | { status: 'conflict'; record?: DurablePlanCommandRecord; reason: string }\n >\n recordPlanAuthorityResult(scope: DurableChatScope, commandKey: DurablePlanCommandKey, result: DurablePlanAuthorityResult, receipt: DurableFollowUpReceipt): Promise<void>\n finalizePlanCommand(scope: DurableChatScope, commandKey: DurablePlanCommandKey): Promise<void>\n getPlanEffect(scope: DurableChatScope, effectKey: string): Promise<DurablePlanEffectRecord | null>\n claimPlanEffect(scope: DurableChatScope, effect: DurablePlanEffectRecord): Promise<\n | { status: 'claimed'; record: DurablePlanEffectRecord }\n | { status: 'existing'; record: DurablePlanEffectRecord }\n >\n completePlanEffect(scope: DurableChatScope, effectKey: string): Promise<void>\n failPlanEffect(scope: DurableChatScope, effectKey: string, error: string): Promise<void>\n\n getInteractionProjection(scope: DurableChatScope, interactionId: string): Promise<DurableInteractionProjection | null>\n upsertInteractionProjection(scope: DurableChatScope, projection: DurableInteractionProjection): Promise<DurableInteractionProjection>\n listInteractionProjections?(scope: DurableChatScope): Promise<DurableInteractionProjection[]>\n getAnswerIntent(scope: DurableChatScope, intentKey: string): Promise<DurableAnswerIntentRecord | null>\n claimAnswerIntent(scope: DurableChatScope, intent: DurableAnswerIntentRecord): Promise<\n | { status: 'claimed'; record: DurableAnswerIntentRecord }\n | { status: 'existing'; record: DurableAnswerIntentRecord }\n | { status: 'conflict'; record?: DurableAnswerIntentRecord; reason: string }\n >\n acknowledgeAnswerIntent(scope: DurableChatScope, intentKey: string, acknowledgement: DurableInteractionAcknowledgement): Promise<void>\n /** Atomically settle the interaction projection (including semantic aliases)\n * from the acknowledged intent and mark the intent finalized. */\n finalizeAnswerIntent(scope: DurableChatScope, intentKey: string, guarantee?: DurableInteractionGuarantee): Promise<void>\n abortAnswerIntent(scope: DurableChatScope, intentKey: string, error: string): Promise<void>\n}\n\n/** Alias used by adapters that store all durable chat state in one port. */\nexport type DurableChatStateStore = DurablePlanStore\n/** Represent durable storage for plan state management with persistence and reliability guarantees */\nexport type DurablePlanStateStore = DurablePlanStore\n/** Pick essential methods to manage and record durable plan command operations */\nexport type DurablePlanCommandJournal = Pick<DurablePlanStore, 'getPlanCommand' | 'claimPlanCommand' | 'recordPlanAuthorityResult' | 'finalizePlanCommand'>\n/** Provide durable methods to manage the lifecycle of answer intents in a plan store */\nexport type DurableAnswerIntentJournal = Pick<DurablePlanStore, 'getAnswerIntent' | 'claimAnswerIntent' | 'acknowledgeAnswerIntent' | 'finalizeAnswerIntent' | 'abortAnswerIntent'>\n\n/** Define a durable chat interaction projection with idempotent event tracking and optional tombstone flag */\nexport interface DurableInteractionProjection extends ChatInteraction {\n /** Sequence/event identity used to make ask replays idempotent. */\n eventId?: string\n semanticKey?: string\n /** A cancel-before-ask row is a terminal tombstone. */\n tombstone?: boolean\n updatedAt?: string\n}\n\n/** Define possible states for a durable answer intent lifecycle */\nexport type DurableAnswerIntentState = 'prepared' | 'acknowledged' | 'finalized' | 'aborted'\n\n/** Define the structure for recording durable answer intent details and their states */\nexport interface DurableAnswerIntentRecord {\n scope: DurableChatScope\n interactionId: string\n attemptKey: string\n intentKey: string\n outcome: 'accepted' | 'declined'\n data?: Record<string, InteractionAnswerValue>\n state: DurableAnswerIntentState\n guarantee?: DurableInteractionGuarantee\n acknowledgement?: DurableInteractionAcknowledgement\n createdAt: string\n finalizedAt?: string\n error?: string\n}\n\n/** Represent durable acknowledgement of an interaction with optional authority, status, and timestamp fields */\nexport interface DurableInteractionAcknowledgement {\n acknowledged: true\n authorityId?: string\n status?: string\n at?: string\n}\n\n/** Define interaction durability levels to specify reconciliation or best-effort guarantees */\nexport type DurableInteractionGuarantee = 'reconciled' | 'best-effort'\n\n/** Define options for durable interaction settlement including attempt key, guarantee, and timestamp provider */\nexport interface DurableInteractionSettlementOptions {\n /** Caller-created and stable across retries/reconnects. */\n attemptKey: string\n guarantee?: DurableInteractionGuarantee\n now?: () => string\n}\n\n/** Manage durable interaction lifecycles by preparing, acknowledging, finalizing, aborting, and reconciling intents */\nexport interface DurableInteractionSettlement {\n prepare(scope: DurableChatScope, interactionId: string, outcome: 'accepted' | 'declined', data?: Record<string, InteractionAnswerValue>): Promise<DurableAnswerIntentRecord>\n acknowledge(scope: DurableChatScope, intentKey: string, acknowledgement?: Omit<DurableInteractionAcknowledgement, 'acknowledged'>): Promise<DurableAnswerIntentRecord>\n finalize(scope: DurableChatScope, intentKey: string): Promise<DurableAnswerIntentRecord>\n abort(scope: DurableChatScope, intentKey: string, error: string): Promise<DurableAnswerIntentRecord>\n reconcile(scope: DurableChatScope, intentKey: string): Promise<DurableAnswerIntentRecord | null>\n}\n\n/** Normalize input value to a standardized DurablePlanDecision or return null for invalid inputs */\nexport function normalizePlanDecision(value: unknown): DurablePlanDecision | null {\n if (value === 'approved' || value === 'approve') return 'approved'\n if (value === 'rejected' || value === 'reject') return 'rejected'\n return null\n}\n\n/** Generate a unique key string for a plan command using plan ID, revision, and decision */\nexport function planCommandKey(planId: string, revision: number, decision: DurablePlanDecision): string {\n return `plan:${encodeURIComponent(planId)}:${revision}:${decision}`\n}\n\n/** Generate a unique idempotency key for a plan authority based on scope, plan, revision, and decision */\nexport function planAuthorityIdempotencyKey(scope: DurableChatScope, planId: string, revision: number, decision: DurablePlanDecision): string {\n return `durable-plan:${encodeURIComponent(durableChatScopeKey(scope))}:${encodeURIComponent(planId)}:${revision}:${decision}`\n}\n\n/** Generate a unique string key representing the effect of a plan decision within a given scope and revision */\nexport function planEffectKey(scope: DurableChatScope, planId: string, revision: number, decision: DurablePlanDecision): string {\n return `after-decision:${encodeURIComponent(durableChatScopeKey(scope))}:${encodeURIComponent(planId)}:${revision}:${decision}`\n}\n\n/** Resolve a durable follow-up receipt ensuring idempotency for a given plan decision and revision */\nexport function stablePlanReceipt(\n scope: DurableChatScope,\n planId: string,\n revision: number,\n decision: DurablePlanDecision,\n result: Pick<DurablePlanAuthorityResult, 'followUp'>,\n): DurableFollowUpReceipt {\n const authorityIdempotencyKey = planAuthorityIdempotencyKey(scope, planId, revision, decision)\n return {\n receiptId: `receipt:${authorityIdempotencyKey}`,\n planId,\n revision,\n decision,\n turnId: result.followUp.turnId,\n state: result.followUp.state,\n authorityIdempotencyKey,\n }\n}\n","import {\n durableChatScopeKey,\n type DurableAnswerIntentRecord,\n type DurableChatScope,\n type DurableInteractionProjection,\n type DurablePlanAuthorityResult,\n type DurablePlanCommandRecord,\n type DurablePlanCommandKey,\n type DurablePlanEffectRecord,\n type DurablePlanProjection,\n type DurablePlanStore,\n} from './types'\nimport { DurableChatConflictError } from './errors'\nimport { canTransitionPlanStatus } from '../plans/index'\n\n/**\n * Reference adapter for tests and local development. It is intentionally\n * process-local and non-production: there is no locking across processes,\n * transaction, or crash recovery. Production adapters should implement the\n * same port with a database/Workflow primitive and CAS at every claim.\n */\nexport class InMemoryDurableChatStateStore implements DurablePlanStore {\n private readonly plans = new Map<string, DurablePlanProjection>()\n private readonly currentPlans = new Map<string, string>()\n private readonly commands = new Map<string, DurablePlanCommandRecord>()\n private readonly effects = new Map<string, DurablePlanEffectRecord>()\n private readonly interactions = new Map<string, DurableInteractionProjection>()\n private readonly interactionSemantic = new Map<string, string>()\n /** Duplicate event ids point at the canonical semantic interaction so all\n * duplicate asks settle through one terminal row/attempt. */\n private readonly interactionAliases = new Map<string, string>()\n private readonly answerIntents = new Map<string, DurableAnswerIntentRecord>()\n\n private scopePrefix(scope: DurableChatScope): string {\n return `${encodeURIComponent(durableChatScopeKey(scope))}\\u0000`\n }\n private scopedKey(scope: DurableChatScope, ...parts: Array<string | number>): string {\n return `${this.scopePrefix(scope)}${parts.map((part) => encodeURIComponent(String(part))).join('\\u0000')}`\n }\n private planKey(scope: DurableChatScope, planId: string, revision: number): string {\n return this.scopedKey(scope, planId, revision)\n }\n private currentKey(scope: DurableChatScope, planId: string): string {\n return this.scopedKey(scope, planId)\n }\n private commandKey(scope: DurableChatScope, key: string): string {\n return this.scopedKey(scope, key)\n }\n private interactionKey(scope: DurableChatScope, id: string): string {\n return this.scopedKey(scope, id)\n }\n private intentKey(scope: DurableChatScope, key: string): string {\n return this.scopedKey(scope, key)\n }\n private effectKey(scope: DurableChatScope, key: string): string {\n return this.scopedKey(scope, key)\n }\n\n async getPlanProjection(scope: DurableChatScope, planId: string, revision?: number): Promise<DurablePlanProjection | null> {\n const current = revision === undefined ? this.currentPlans.get(this.currentKey(scope, planId)) : undefined\n const key = revision === undefined\n ? current\n : this.planKey(scope, planId, revision)\n return key ? this.plans.get(key) ?? null : null\n }\n\n async listPlanProjections(scope: DurableChatScope, planId?: string): Promise<DurablePlanProjection[]> {\n const prefix = this.scopePrefix(scope)\n return [...this.plans.entries()]\n .filter(([key, projection]) => key.startsWith(prefix) && (!planId || projection.planId === planId))\n .map(([, projection]) => projection)\n .sort((a, b) => a.revision - b.revision)\n }\n\n async putPlanProjection(scope: DurableChatScope, projection: DurablePlanProjection): Promise<void> {\n if (!projection.planId || !Number.isInteger(projection.revision) || projection.revision < 1) {\n throw new TypeError('plan projection requires planId and positive integer revision')\n }\n const key = this.planKey(scope, projection.planId, projection.revision)\n const prior = this.plans.get(key)\n if (prior && JSON.stringify(prior) !== JSON.stringify(projection)) {\n if (\n prior.body !== projection.body ||\n prior.title !== projection.title ||\n prior.submittedAt !== projection.submittedAt\n ) {\n throw new DurableChatConflictError('plan content changed without a new revision')\n }\n if (prior.status === projection.status && !['preparing', 'pending'].includes(prior.status)) {\n throw new DurableChatConflictError('terminal plan projection cannot be rewritten')\n }\n if (!canTransitionPlanStatus(prior.status, projection.status)) {\n throw new DurableChatConflictError('conflicting plan projection for the same revision')\n }\n }\n this.plans.set(key, projection)\n const currentKey = this.currentKey(scope, projection.planId)\n const currentKeyValue = this.currentPlans.get(currentKey)\n const current = currentKeyValue ? this.plans.get(currentKeyValue) : undefined\n if (!current || projection.revision > current.revision) this.currentPlans.set(currentKey, key)\n }\n\n async getPlanCommand(scope: DurableChatScope, commandKey: DurablePlanCommandKey): Promise<DurablePlanCommandRecord | null> {\n return this.commands.get(this.commandKey(scope, commandKey)) ?? null\n }\n\n async claimPlanCommand(scope: DurableChatScope, command: DurablePlanCommandRecord) {\n const key = this.commandKey(scope, command.commandKey)\n const existing = this.commands.get(key)\n if (!existing) {\n const prefix = this.scopePrefix(scope)\n const competing = [...this.commands.entries()].find(([storedKey, candidate]) =>\n storedKey.startsWith(prefix) && candidate.planId === command.planId &&\n candidate.revision === command.revision && candidate.decision !== command.decision,\n )\n if (competing) {\n return { status: 'conflict' as const, record: competing[1], reason: 'competing decision for plan revision' }\n }\n this.commands.set(key, command)\n return { status: 'claimed' as const, record: command }\n }\n if (\n existing.planId === command.planId && existing.revision === command.revision &&\n existing.decision === command.decision\n ) return { status: 'existing' as const, record: existing }\n return { status: 'conflict' as const, record: existing, reason: 'command key is already used by another decision' }\n }\n\n async recordPlanAuthorityResult(scope: DurableChatScope, commandKey: string, result: DurablePlanAuthorityResult, receipt: DurablePlanCommandRecord['receipt']): Promise<void> {\n const key = this.commandKey(scope, commandKey)\n const command = this.commands.get(key)\n if (!command) throw new DurableChatConflictError('cannot record authority result before claiming command')\n command.authorityResult = result\n command.receipt = receipt\n command.state = 'authority_committed'\n }\n\n async finalizePlanCommand(scope: DurableChatScope, commandKey: string): Promise<void> {\n const command = this.commands.get(this.commandKey(scope, commandKey))\n if (!command) throw new DurableChatConflictError('cannot finalize unknown plan command')\n command.state = 'finalized'\n }\n\n async getPlanEffect(scope: DurableChatScope, effectKey: string): Promise<DurablePlanEffectRecord | null> {\n return this.effects.get(this.effectKey(scope, effectKey)) ?? null\n }\n async claimPlanEffect(scope: DurableChatScope, effect: DurablePlanEffectRecord) {\n const key = this.effectKey(scope, effect.effectKey)\n const existing = this.effects.get(key)\n if (existing) return { status: 'existing' as const, record: existing }\n this.effects.set(key, effect)\n return { status: 'claimed' as const, record: effect }\n }\n async completePlanEffect(scope: DurableChatScope, effectKey: string): Promise<void> {\n const effect = this.effects.get(this.effectKey(scope, effectKey))\n if (!effect) throw new DurableChatConflictError('cannot complete unknown plan effect')\n effect.state = 'completed'\n effect.completedAt = new Date().toISOString()\n }\n async failPlanEffect(scope: DurableChatScope, effectKey: string, error: string): Promise<void> {\n const effect = this.effects.get(this.effectKey(scope, effectKey))\n if (!effect) throw new DurableChatConflictError('cannot fail unknown plan effect')\n effect.state = 'error'\n effect.error = error\n }\n\n async getInteractionProjection(scope: DurableChatScope, interactionId: string): Promise<DurableInteractionProjection | null> {\n const directKey = this.interactionKey(scope, interactionId)\n const alias = this.interactionAliases.get(directKey)\n return this.interactions.get(alias ?? directKey) ?? null\n }\n\n async listInteractionProjections(scope: DurableChatScope): Promise<DurableInteractionProjection[]> {\n const prefix = this.scopePrefix(scope)\n return [...this.interactions.entries()]\n .filter(([key]) => key.startsWith(prefix))\n .map(([, value]) => value)\n }\n\n async upsertInteractionProjection(scope: DurableChatScope, projection: DurableInteractionProjection): Promise<DurableInteractionProjection> {\n if (!projection.id) throw new TypeError('interaction projection requires id')\n const key = this.interactionKey(scope, projection.id)\n const prior = this.interactions.get(key)\n const resolvedPrior = prior ?? (() => {\n const alias = this.interactionAliases.get(key)\n return alias ? this.interactions.get(alias) : undefined\n })()\n if (!prior && resolvedPrior) {\n this.interactionAliases.set(key, this.interactionKey(scope, resolvedPrior.id))\n }\n if (resolvedPrior) {\n if (projection.eventId && resolvedPrior.eventId === projection.eventId) return resolvedPrior\n if (resolvedPrior.status !== 'pending') {\n if (\n resolvedPrior.tombstone && resolvedPrior.kind === 'unknown' &&\n projection.status === resolvedPrior.status\n ) {\n const enriched = {\n ...projection,\n id: resolvedPrior.id,\n status: resolvedPrior.status,\n tombstone: true,\n ...(resolvedPrior.cancelReason ? { cancelReason: resolvedPrior.cancelReason } : {}),\n }\n this.interactions.set(this.interactionKey(scope, resolvedPrior.id), enriched)\n return enriched\n }\n if (resolvedPrior.status === projection.status && JSON.stringify(resolvedPrior.answers) === JSON.stringify(projection.answers)) return resolvedPrior\n throw new DurableChatConflictError('interaction already has a conflicting terminal outcome')\n }\n // A terminal event wins over pending. A second terminal event is caught\n // above; this is the accepted-answer/cancel ordering rule.\n if (projection.status !== 'pending') {\n const canonical = resolvedPrior.id === projection.id ? projection : { ...projection, id: resolvedPrior.id }\n this.interactions.set(this.interactionKey(scope, canonical.id), canonical)\n if (resolvedPrior.semanticKey) {\n this.interactionSemantic.delete(this.scopedKey(scope, resolvedPrior.semanticKey))\n }\n return canonical\n }\n return resolvedPrior\n }\n if (projection.semanticKey) {\n const semantic = this.scopedKey(scope, projection.semanticKey)\n const priorId = this.interactionSemantic.get(semantic)\n if (priorId) {\n const canonicalKey = this.interactionKey(scope, priorId)\n this.interactionAliases.set(this.interactionKey(scope, projection.id), canonicalKey)\n return this.interactions.get(canonicalKey) ?? projection\n }\n this.interactionSemantic.set(semantic, projection.id)\n }\n this.interactions.set(key, projection)\n return projection\n }\n\n async getAnswerIntent(scope: DurableChatScope, intentKey: string): Promise<DurableAnswerIntentRecord | null> {\n return this.answerIntents.get(this.intentKey(scope, intentKey)) ?? null\n }\n async claimAnswerIntent(scope: DurableChatScope, intent: DurableAnswerIntentRecord) {\n const key = this.intentKey(scope, intent.intentKey)\n const existing = this.answerIntents.get(key)\n if (!existing) {\n this.answerIntents.set(key, intent)\n return { status: 'claimed' as const, record: intent }\n }\n if (existing.interactionId === intent.interactionId && existing.attemptKey === intent.attemptKey && existing.outcome === intent.outcome && JSON.stringify(existing.data) === JSON.stringify(intent.data)) {\n return { status: 'existing' as const, record: existing }\n }\n return { status: 'conflict' as const, record: existing, reason: 'answer intent key is already used by another answer' }\n }\n async acknowledgeAnswerIntent(scope: DurableChatScope, intentKey: string, acknowledgement: DurableAnswerIntentRecord['acknowledgement']): Promise<void> {\n const intent = this.answerIntents.get(this.intentKey(scope, intentKey))\n if (!intent) throw new DurableChatConflictError('cannot acknowledge unknown answer intent')\n if (intent.state === 'finalized') return\n intent.acknowledgement = acknowledgement\n intent.state = 'acknowledged'\n }\n async finalizeAnswerIntent(scope: DurableChatScope, intentKey: string, guarantee: DurableAnswerIntentRecord['guarantee'] = 'reconciled'): Promise<void> {\n const intent = this.answerIntents.get(this.intentKey(scope, intentKey))\n if (!intent) throw new DurableChatConflictError('cannot finalize unknown answer intent')\n if (intent.state === 'finalized') return\n if (!intent.acknowledgement?.acknowledged) {\n throw new DurableChatConflictError('cannot finalize an answer before authority acknowledgement')\n }\n const projection = await this.getInteractionProjection(scope, intent.interactionId)\n if (!projection) throw new DurableChatConflictError('cannot finalize an answer before its ask projection')\n const status = intent.outcome === 'accepted' ? 'answered' : 'declined'\n await this.upsertInteractionProjection(scope, {\n ...projection,\n status,\n ...(intent.data ? { answers: intent.data } : {}),\n updatedAt: intent.acknowledgement.at ?? new Date().toISOString(),\n })\n intent.state = 'finalized'\n intent.guarantee = guarantee\n intent.finalizedAt = new Date().toISOString()\n }\n async abortAnswerIntent(scope: DurableChatScope, intentKey: string, error: string): Promise<void> {\n const intent = this.answerIntents.get(this.intentKey(scope, intentKey))\n if (!intent) throw new DurableChatConflictError('cannot abort unknown answer intent')\n if (intent.state === 'finalized') return\n intent.state = 'aborted'\n intent.error = error\n }\n}\n\n/** Short aliases retained for adapter authors who call this a durable chat\n * store rather than a state store. Both names refer to the same non-production\n * reference implementation. */\nexport const InMemoryDurableChatStore = InMemoryDurableChatStateStore\n/** Create an in-memory durable chat state store for managing chat session data efficiently */\nexport function createInMemoryDurableChatStateStore(): InMemoryDurableChatStateStore {\n return new InMemoryDurableChatStateStore()\n}\n","import {\n cancelStatusFor,\n interactionFromWireRequest,\n isSafeInteractionFieldKey,\n parseInteractionAnswers,\n questionInteractionContentSignature,\n type InteractionAnswerValue,\n type InteractionAnswers,\n type InteractionRequestWire,\n} from '../interactions/contract'\nimport { DurableChatConflictError } from './errors'\nimport type {\n DurableAnswerIntentRecord,\n DurableChatScope,\n DurableInteractionAcknowledgement,\n DurableInteractionGuarantee,\n DurableInteractionProjection,\n DurableInteractionSettlement,\n DurableInteractionSettlementOptions,\n DurablePlanStore,\n} from './types'\n\nfunction nowIso(now?: () => string): string {\n return (now ?? (() => new Date().toISOString()))()\n}\n\nfunction intentKey(scope: DurableChatScope, interactionId: string, attemptKey: string): string {\n return `interaction-answer:${encodeURIComponent(scope)}:${encodeURIComponent(interactionId)}:${encodeURIComponent(attemptKey)}`\n}\n\nfunction ensureAttemptKey(attemptKey: string): void {\n if (!attemptKey || typeof attemptKey !== 'string' || attemptKey.length > 512) throw new TypeError('attemptKey must be a non-empty string')\n}\n\nfunction safeAnswers(data: Record<string, InteractionAnswerValue> | undefined): InteractionAnswers | undefined {\n if (data === undefined) return undefined\n for (const key of Object.keys(data)) {\n if (!isSafeInteractionFieldKey(key)) throw new TypeError(`unsafe interaction answer key: ${key}`)\n }\n const parsed = parseInteractionAnswers(data)\n if (!parsed.succeeded) throw new TypeError(parsed.error)\n return parsed.value\n}\n\n/** Apply an ask event. Event ids and semantic signatures make replays safe;\n * a prior cancel creates a tombstone and cannot be resurrected by a late ask. */\nexport async function upsertDurableInteractionAsk(\n store: DurablePlanStore,\n scope: DurableChatScope,\n request: InteractionRequestWire,\n options: { eventId?: string; semanticKey?: string; now?: () => string } = {},\n): Promise<DurableInteractionProjection> {\n const semanticKey = options.semanticKey ?? questionInteractionContentSignature(interactionFromWireRequest(request)) ?? undefined\n const incoming: DurableInteractionProjection = {\n ...interactionFromWireRequest(request),\n ...(options.eventId ? { eventId: options.eventId } : {}),\n ...(semanticKey ? { semanticKey } : {}),\n updatedAt: nowIso(options.now),\n }\n const prior = await store.getInteractionProjection(scope, request.id)\n if (prior?.tombstone) {\n return store.upsertInteractionProjection(scope, {\n ...incoming,\n status: prior.status,\n tombstone: true,\n ...(prior.cancelReason ? { cancelReason: prior.cancelReason } : {}),\n })\n }\n if (prior && prior.status !== 'pending') return prior\n return store.upsertInteractionProjection(scope, incoming)\n}\n\n/** Apply a cancel event. It is valid before the ask arrives and leaves a\n * terminal tombstone so a delayed ask cannot re-open the card. */\nexport async function recordDurableInteractionCancel(\n store: DurablePlanStore,\n scope: DurableChatScope,\n interactionId: string,\n reason?: string,\n options: { eventId?: string; now?: () => string } = {},\n): Promise<DurableInteractionProjection> {\n if (!interactionId) throw new TypeError('interaction id is required')\n const status = cancelStatusFor(reason)\n const prior = await store.getInteractionProjection(scope, interactionId)\n if (prior) {\n if (prior.status === status) return prior\n if (prior.status !== 'pending') throw new DurableChatConflictError('interaction already has a conflicting terminal outcome')\n return store.upsertInteractionProjection(scope, {\n ...prior, status, tombstone: true, ...(reason ? { cancelReason: reason } : {}),\n ...(options.eventId ? { eventId: options.eventId } : {}), updatedAt: nowIso(options.now),\n })\n }\n return store.upsertInteractionProjection(scope, {\n id: interactionId, kind: 'unknown', title: '', fields: [], status,\n tombstone: true, ...(reason ? { cancelReason: reason } : {}),\n ...(options.eventId ? { eventId: options.eventId } : {}), updatedAt: nowIso(options.now),\n })\n}\n\n/** Record an accepted/declined answer in the projection. The terminal\n * transition is intentionally separate from answer-intent acknowledgement so\n * callers can choose reconciled or best-effort delivery. */\nexport async function recordDurableInteractionAnswer(\n store: DurablePlanStore,\n scope: DurableChatScope,\n interactionId: string,\n outcome: 'accepted' | 'declined',\n answers?: Record<string, InteractionAnswerValue>,\n options: { eventId?: string; now?: () => string } = {},\n): Promise<DurableInteractionProjection> {\n const prior = await store.getInteractionProjection(scope, interactionId)\n if (!prior) throw new DurableChatConflictError('cannot answer an interaction before its ask projection')\n const status = outcome === 'accepted' ? 'answered' : 'declined'\n const parsed = safeAnswers(answers)\n if (prior.status === status && JSON.stringify(prior.answers) === JSON.stringify(parsed)) return prior\n if (prior.status !== 'pending') throw new DurableChatConflictError('interaction already has a conflicting terminal outcome')\n return store.upsertInteractionProjection(scope, {\n ...prior, status, ...(parsed ? { answers: parsed } : {}),\n ...(options.eventId ? { eventId: options.eventId } : {}), updatedAt: nowIso(options.now),\n })\n}\n\n/** Define options for creating durable interaction settlement factories including store and optional reconcile authority */\nexport interface DurableInteractionSettlementFactoryOptions extends DurableInteractionSettlementOptions {\n store: DurablePlanStore\n /** Optional authority lookup used by `reconcile`; returning null leaves the\n * intent prepared for a later durable retry. */\n reconcileAuthority?: (args: {\n scope: DurableChatScope\n intent: DurableAnswerIntentRecord\n }) => Promise<DurableInteractionAcknowledgement | null>\n}\n\n/** Additive answer settlement primitive for wiring into `/interactions`.\n * `attemptKey` belongs to the caller and is never generated from user data. */\nexport function createDurableInteractionSettlement(\n options: DurableInteractionSettlementFactoryOptions,\n): DurableInteractionSettlement {\n const now = options.now ?? (() => new Date().toISOString())\n return {\n async prepare(scope, interactionId, outcome, data) {\n ensureAttemptKey(options.attemptKey)\n const parsed = safeAnswers(data)\n const record: DurableAnswerIntentRecord = {\n scope, interactionId, attemptKey: options.attemptKey,\n intentKey: intentKey(scope, interactionId, options.attemptKey),\n outcome, ...(parsed ? { data: parsed } : {}), state: 'prepared',\n guarantee: options.guarantee ?? 'reconciled', createdAt: now(),\n }\n const result = await options.store.claimAnswerIntent(scope, record)\n if (result.status === 'conflict') throw new DurableChatConflictError(result.reason)\n return result.record\n },\n async acknowledge(scope, key, acknowledgement = {}) {\n const existing = await options.store.getAnswerIntent(scope, key)\n if (!existing) throw new DurableChatConflictError('unknown answer intent')\n const value: DurableInteractionAcknowledgement = {\n acknowledged: true,\n ...(acknowledgement.authorityId ? { authorityId: acknowledgement.authorityId } : {}),\n ...(acknowledgement.status ? { status: acknowledgement.status } : {}),\n at: acknowledgement.at ?? now(),\n }\n await options.store.acknowledgeAnswerIntent(scope, key, value)\n return (await options.store.getAnswerIntent(scope, key))!\n },\n async finalize(scope, key) {\n const existing = await options.store.getAnswerIntent(scope, key)\n if (!existing) throw new DurableChatConflictError('unknown answer intent')\n await options.store.finalizeAnswerIntent(scope, key, options.guarantee ?? 'reconciled')\n return (await options.store.getAnswerIntent(scope, key))!\n },\n async abort(scope, key, error) {\n const existing = await options.store.getAnswerIntent(scope, key)\n if (!existing) throw new DurableChatConflictError('unknown answer intent')\n await options.store.abortAnswerIntent(scope, key, error)\n return (await options.store.getAnswerIntent(scope, key))!\n },\n async reconcile(scope, key) {\n const existing = await options.store.getAnswerIntent(scope, key)\n if (!existing || !options.reconcileAuthority) return existing\n if (existing.state === 'finalized') return existing\n const acknowledgement = await options.reconcileAuthority({ scope, intent: existing })\n if (!acknowledgement) return existing\n await options.store.acknowledgeAnswerIntent(scope, key, {\n acknowledged: true,\n ...(acknowledgement.authorityId ? { authorityId: acknowledgement.authorityId } : {}),\n ...(acknowledgement.status ? { status: acknowledgement.status } : {}),\n ...(acknowledgement.at ? { at: acknowledgement.at } : {}),\n })\n await options.store.finalizeAnswerIntent(scope, key, options.guarantee ?? 'reconciled')\n return (await options.store.getAnswerIntent(scope, key))!\n },\n }\n}\n\n/** Stable key helper exported for products implementing their own settlement\n * loop. */\nexport function durableInteractionIntentKey(scope: DurableChatScope, interactionId: string, attemptKey: string): string {\n ensureAttemptKey(attemptKey)\n return intentKey(scope, interactionId, attemptKey)\n}\n\n/** Resolve and upsert a durable interaction ask in the store with optional event and timing parameters */\nexport const applyDurableInteractionAsk = upsertDurableInteractionAsk\n/** Resolve cancellation of a durable interaction with optional reason and event details */\nexport const applyDurableInteractionCancel = recordDurableInteractionCancel\n/** Resolve and record the outcome and answers of a durable interaction within the given store and scope */\nexport const applyDurableInteractionAnswer = recordDurableInteractionAnswer\n","import {\n interactionToPersistedPart,\n parseInteractionCancel,\n parseInteractionRequest,\n type InteractionCancelData,\n type InteractionPersistedPart,\n type InteractionRequestWire,\n} from '../interactions/contract'\nimport { DurableChatConflictError } from './errors'\nimport type {\n DurableInteractionRouteArgs,\n DurableInteractionRoutePersistence,\n} from '../interactions/route'\nimport {\n createDurableInteractionSettlement,\n recordDurableInteractionCancel,\n upsertDurableInteractionAsk,\n} from './interactions'\nimport type {\n DurableAnswerIntentRecord,\n DurableChatScope,\n DurableInteractionAcknowledgement,\n DurableInteractionGuarantee,\n DurableInteractionSettlement,\n DurablePlanStore,\n} from './types'\nimport {\n parsePlanSubmittedEvent,\n persistedPartToPlan,\n planToPersistedPart,\n} from '../plans/index'\n\n/** Define methods to manage durable interaction projections including upsert, cancel, and materialize operations */\nexport interface DurableInteractionProjectionAdapter {\n upsertAsk(request: InteractionRequestWire): Promise<void>\n cancel(cancel: InteractionCancelData): Promise<void>\n materialize(): Promise<InteractionPersistedPart[]>\n}\n\n/** Binds an authorized durable scope/store to interaction lifecycle events. */\nexport function createDurableInteractionProjectionAdapter(options: {\n store: DurablePlanStore\n scope: DurableChatScope\n now?: () => string\n}): DurableInteractionProjectionAdapter {\n const observed = new Set<string>()\n return {\n async upsertAsk(request) {\n observed.add(request.id)\n await upsertDurableInteractionAsk(options.store, options.scope, request, { now: options.now })\n },\n async cancel(cancel) {\n observed.add(cancel.id)\n await recordDurableInteractionCancel(\n options.store,\n options.scope,\n cancel.id,\n cancel.reason,\n { now: options.now },\n )\n },\n async materialize() {\n const projections = await Promise.all(\n [...observed].map((id) => options.store.getInteractionProjection(options.scope, id)),\n )\n const canonical = new Map(projections.filter((item) => item !== null).map((item) => [item.id, item]))\n return [...canonical.values()]\n .filter((projection) => projection.kind !== 'unknown')\n .map((projection) => interactionToPersistedPart(\n {\n id: projection.id,\n kind: projection.kind,\n title: projection.title,\n ...(projection.body ? { body: projection.body } : {}),\n answerSpec: { fields: projection.fields },\n },\n projection.status,\n projection.cancelReason,\n projection.answers,\n ))\n },\n }\n}\n\n/** Resolve chat events and materialize their state into durable records */\nexport interface DurableChatEventProjection {\n observe(event: unknown): void | Promise<void>\n materialize(): Array<Record<string, unknown>> | Promise<Array<Record<string, unknown>>>\n}\n\nfunction eventRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const record = value as Record<string, unknown>\n if (record.kind === 'event' && record.event && typeof record.event === 'object') {\n return record.event as Record<string, unknown>\n }\n return record\n}\n\n/** Event projector usable with any `ChatTurnRouteProducer` through\n * `withDurableChatProjection`. It tracks this turn's identities so older\n * thread state is not copied into every assistant message. */\nexport function createDurableChatEventProjection(options: {\n store: DurablePlanStore\n scope: DurableChatScope\n now?: () => string\n}): DurableChatEventProjection {\n const interactions = createDurableInteractionProjectionAdapter(options)\n const plans = new Set<string>()\n return {\n async observe(value) {\n const event = eventRecord(value)\n if (!event || typeof event.type !== 'string') return\n const data = eventRecord(event.data)\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(data ?? undefined)\n if (parsed.succeeded) await interactions.upsertAsk(parsed.value)\n return\n }\n if (event.type === 'interaction.cancel') {\n const parsed = parseInteractionCancel(data ?? undefined)\n if (parsed.succeeded) {\n try {\n await interactions.cancel(parsed.value)\n } catch (error) {\n if (!(error instanceof DurableChatConflictError)) throw error\n }\n }\n return\n }\n if (!event.type.startsWith('plan.')) return\n const submitted = parsePlanSubmittedEvent(event)\n const planRecord = eventRecord(data?.plan) ?? eventRecord(eventRecord(event.properties)?.plan)\n const plan = submitted.succeeded\n ? submitted.value\n : planRecord ? persistedPartToPlan({ type: 'plan', ...planRecord }) : null\n if (!plan) return\n plans.add(`${plan.planId}\\u0000${plan.revision}`)\n try {\n await options.store.putPlanProjection(options.scope, plan)\n } catch (error) {\n if (!(error instanceof DurableChatConflictError)) throw error\n }\n },\n async materialize() {\n const interactionParts = await interactions.materialize()\n const planParts = await Promise.all([...plans].map(async (key) => {\n const [planId, rawRevision] = key.split('\\u0000')\n const plan = await options.store.getPlanProjection(options.scope, planId!, Number(rawRevision))\n return plan ? planToPersistedPart(plan) : null\n }))\n return [...interactionParts, ...planParts.filter((part) => part !== null)]\n },\n }\n}\n\n/** Define a structured response containing scope, settlement, and intent for durable interactions */\nexport interface PreparedDurableInteractionAnswer {\n scope: DurableChatScope\n settlement: DurableInteractionSettlement\n intent: DurableAnswerIntentRecord\n}\n\ninterface DurableInteractionRoutePersistenceBase {\n store: DurablePlanStore\n scope(args: DurableInteractionRouteArgs): DurableChatScope | Promise<DurableChatScope>\n now?: () => string\n}\n\n/** Define options for durable interaction route persistence with reconciliation guarantees and authority functions */\nexport type CreateDurableInteractionRoutePersistenceOptions =\n | (DurableInteractionRoutePersistenceBase & {\n guarantee: 'reconciled'\n reconcileAuthority(args: {\n scope: DurableChatScope\n intent: DurableAnswerIntentRecord\n route: DurableInteractionRouteArgs\n }): Promise<DurableInteractionAcknowledgement | null>\n })\n | (DurableInteractionRoutePersistenceBase & {\n guarantee: 'best-effort'\n reconcileAuthority?: (args: {\n scope: DurableChatScope\n intent: DurableAnswerIntentRecord\n route: DurableInteractionRouteArgs\n }) => Promise<DurableInteractionAcknowledgement | null>\n })\n\n/** Ready-to-use bridge from `/interactions` to the durable state port. Only\n * the reconciled variant may claim crash-safe behavior; best-effort is\n * explicit in both its type and persisted intent. */\nexport function createDurableInteractionRoutePersistence(\n options: CreateDurableInteractionRoutePersistenceOptions,\n): DurableInteractionRoutePersistence<PreparedDurableInteractionAnswer> {\n const guarantee: DurableInteractionGuarantee = options.guarantee\n return {\n guarantee,\n async prepare(args) {\n const scope = await options.scope(args)\n const settlement = createDurableInteractionSettlement({\n store: options.store,\n attemptKey: args.attemptKey,\n guarantee,\n now: options.now,\n ...(options.reconcileAuthority\n ? { reconcileAuthority: ({ intent }) => options.reconcileAuthority!({ scope, intent, route: args }) }\n : {}),\n })\n const intent = await settlement.prepare(\n scope,\n args.answer.id,\n args.answer.outcome,\n args.answer.data,\n )\n return { scope, settlement, intent }\n },\n async reconcile({ prepared }) {\n let intent = await prepared.settlement.reconcile(prepared.scope, prepared.intent.intentKey)\n if (intent?.state === 'acknowledged') {\n intent = await prepared.settlement.finalize(prepared.scope, prepared.intent.intentKey)\n }\n return { settled: intent?.state === 'finalized' }\n },\n async acknowledge({ prepared }) {\n await prepared.settlement.acknowledge(prepared.scope, prepared.intent.intentKey, {\n status: prepared.intent.outcome,\n })\n },\n async finalize({ prepared }) {\n await prepared.settlement.finalize(prepared.scope, prepared.intent.intentKey)\n },\n async fail({ prepared, error }) {\n await prepared.settlement.abort(\n prepared.scope,\n prepared.intent.intentKey,\n error instanceof Error ? error.message : String(error),\n )\n },\n }\n}\n","import {\n DurableChatConflictError,\n DurableChatGoneError,\n DurableChatUnavailableError,\n} from './errors'\nimport {\n durableChatScopeKey,\n normalizePlanDecision,\n planAuthorityIdempotencyKey,\n planCommandKey,\n planEffectKey,\n stablePlanReceipt,\n type DurableChatScope,\n type DurableFollowUpReceipt,\n type DurablePlanAuthority,\n type DurablePlanAuthorityCurrentResult,\n type DurablePlanAuthorityResult,\n type DurablePlanCommandRecord,\n type DurablePlanProjection,\n type DurablePlanStore,\n} from './types'\nimport { canTransitionPlanStatus, planFollowUpTurnId } from '../plans/index'\n\n/** Resolve authorization status for durable plans using scopes, responses, or nullish values */\nexport type DurablePlanAuthorization =\n | DurableChatScope\n | { scope: DurableChatScope }\n | Response\n | null\n | undefined\n\n/** Define arguments for authorizing durable plan route requests with operation and optional plan ID */\nexport interface DurablePlanRouteAuthorizeArgs {\n request: Request\n operation: 'current' | 'decide'\n planId?: string\n}\n\n/** Define options for durable plan routing including store, authority, authorization, and idempotent side effect handling */\nexport interface DurablePlanRouteOptions {\n store: DurablePlanStore\n authority: DurablePlanAuthority\n /** Authentication and resource authorization. Scope must be derived by the\n * caller from trusted credentials, never from client JSON. */\n authorize: (args: DurablePlanRouteAuthorizeArgs) => Promise<DurablePlanAuthorization> | DurablePlanAuthorization\n /** Required idempotent side effect seam. The route claims `effectKey` before\n * calling it; a product must make the callback safe to retry by that key. */\n afterDecision: (args: {\n scope: DurableChatScope\n plan: DurablePlanProjection\n receipt: DurableFollowUpReceipt\n effectKey: string\n }) => Promise<void> | void\n now?: () => string\n logger?: Pick<Console, 'warn' | 'error'>\n}\n\n/** Define routes handling durable plan requests with current and decide methods */\nexport interface DurablePlanRoutes {\n current(request: Request): Promise<Response>\n decide(request: Request): Promise<Response>\n}\n\ntype ParsedDecision = {\n planId: string\n revision: number\n decision: 'approved' | 'rejected'\n feedback?: string\n}\n\nfunction errorResponse(error: unknown, fallbackCode: string, fallbackStatus: number, fallbackMessage: string): Response {\n if (error instanceof Response) return error\n if (error && typeof error === 'object' && 'status' in error && typeof error.status === 'number') {\n const typed = error as { code?: unknown; message?: unknown; status: number }\n return Response.json(\n { code: typeof typed.code === 'string' ? typed.code : fallbackCode, error: typeof typed.message === 'string' ? typed.message : fallbackMessage },\n { status: typed.status },\n )\n }\n return Response.json({ code: fallbackCode, error: fallbackMessage }, { status: fallbackStatus })\n}\n\nfunction scopeFromAuthorization(value: DurablePlanAuthorization): DurableChatScope | Response {\n if (value instanceof Response) return value\n if (typeof value === 'string' && value) return value\n if (value && typeof value === 'object' && 'scope' in value && value.scope) return value.scope\n return Response.json({ code: 'DURABLE_CHAT_UNAUTHORIZED', error: 'not authorized' }, { status: 401 })\n}\n\nfunction planIdFromUrl(request: Request): string | null {\n const url = new URL(request.url)\n const query = url.searchParams.get('planId') ?? url.searchParams.get('id')\n if (query) return query\n const segments = url.pathname.split('/').filter(Boolean)\n return segments.length > 0 ? decodeURIComponent(segments[segments.length - 1]!) : null\n}\n\nfunction asCurrent(value: DurablePlanAuthorityCurrentResult | DurablePlanProjection | null): DurablePlanAuthorityCurrentResult {\n if (value === null) return { plan: null }\n if ('plan' in value) return value\n return { plan: value }\n}\n\nfunction terminalDecision(plan: DurablePlanProjection | null): 'approved' | 'rejected' | null {\n if (!plan) return null\n return plan.status === 'approved' || plan.status === 'rejected' ? plan.status : null\n}\n\nfunction parseDecisionBody(body: unknown): ParsedDecision | { error: string } {\n if (!body || typeof body !== 'object' || Array.isArray(body)) return { error: 'Invalid JSON body' }\n const record = body as Record<string, unknown>\n const planId = typeof record.planId === 'string' && record.planId\n ? record.planId\n : typeof record.id === 'string' && record.id ? record.id : null\n const revision = record.revision\n const decision = normalizePlanDecision(record.decision ?? record.outcome ?? record.status)\n if (!planId) return { error: 'Missing planId' }\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 1) return { error: 'revision must be a positive integer' }\n if (!decision) return { error: 'decision must be approved or rejected' }\n if (record.feedback !== undefined && typeof record.feedback !== 'string') return { error: 'feedback must be a string' }\n return { planId, revision, decision, ...(typeof record.feedback === 'string' ? { feedback: record.feedback } : {}) }\n}\n\nfunction withReceipt(result: DurablePlanAuthorityResult, scope: DurableChatScope, parsed: ParsedDecision): DurablePlanAuthorityResult & { receipt: DurableFollowUpReceipt } {\n const receipt = result.receipt ?? stablePlanReceipt(scope, parsed.planId, parsed.revision, parsed.decision, result)\n return { ...result, receipt }\n}\n\nfunction recoverReceipt(\n scope: DurableChatScope,\n plan: DurablePlanProjection,\n decision: 'approved' | 'rejected',\n): DurableFollowUpReceipt {\n return stablePlanReceipt(scope, plan.planId, plan.revision, decision, {\n followUp: { turnId: planFollowUpTurnId(plan.planId, decision), state: 'unknown' },\n })\n}\n\n/** Build durable plan routes with authorization and effect handling based on provided options */\nexport function createDurablePlanRoutes(options: DurablePlanRouteOptions): DurablePlanRoutes {\n const now = options.now ?? (() => new Date().toISOString())\n const logger = options.logger ?? console\n\n async function authorize(request: Request, operation: 'current' | 'decide', planId?: string): Promise<DurableChatScope | Response> {\n try {\n return scopeFromAuthorization(await options.authorize({ request, operation, ...(planId ? { planId } : {}) }))\n } catch (error) {\n return errorResponse(error, 'DURABLE_CHAT_UNAUTHORIZED', 401, 'not authorized')\n }\n }\n\n async function runEffect(\n scope: DurableChatScope,\n plan: DurablePlanProjection,\n receipt: DurableFollowUpReceipt,\n ): Promise<boolean> {\n const effectKey = planEffectKey(scope, plan.planId, plan.revision, receipt.decision)\n try {\n const existing = await options.store.getPlanEffect(scope, effectKey)\n if (existing?.state === 'completed') return true\n const claim = await options.store.claimPlanEffect(scope, {\n effectKey, scope, planId: plan.planId, revision: plan.revision,\n decision: receipt.decision, state: 'claimed', claimedAt: now(),\n })\n if (claim.status === 'existing' && claim.record.state === 'completed') return true\n await options.afterDecision({ scope, plan, receipt, effectKey })\n await options.store.completePlanEffect(scope, effectKey)\n return true\n } catch (error) {\n await options.store.failPlanEffect(scope, effectKey, error instanceof Error ? error.message : String(error)).catch(() => undefined)\n logger.warn('[durable-chat] afterDecision failed:', error)\n return false\n }\n }\n\n async function current(request: Request): Promise<Response> {\n const planId = planIdFromUrl(request)\n if (!planId) return Response.json({ code: 'DURABLE_CHAT_BAD_REQUEST', error: 'Missing planId' }, { status: 400 })\n const scope = await authorize(request, 'current', planId)\n if (scope instanceof Response) return scope\n const local = await options.store.getPlanProjection(scope, planId)\n let authoritative: DurablePlanAuthorityCurrentResult\n try {\n authoritative = asCurrent(await options.authority.current({ scope, planId }))\n } catch (error) {\n // A known terminal local record is safe to replay while authority is\n // temporarily down; pending records must not pretend to be committed.\n const decision = terminalDecision(local)\n if (decision) {\n const command = await options.store.getPlanCommand(scope, planCommandKey(planId, local!.revision, decision))\n if (command?.receipt) {\n const effectComplete = await runEffect(scope, command.authorityResult?.plan ?? local!, command.receipt)\n return Response.json({\n plan: command.authorityResult?.plan ?? local,\n receipt: command.receipt,\n replayed: true,\n ...(!effectComplete ? { effectPending: true } : {}),\n })\n }\n }\n return errorResponse(error, 'DURABLE_CHAT_UNAVAILABLE', 503, 'plan authority unavailable')\n }\n if (!authoritative.plan) {\n return Response.json({ code: 'DURABLE_CHAT_GONE', error: 'plan is no longer available' }, { status: 410 })\n }\n const authorityPlan = authoritative.plan\n const localWins = Boolean(local && (\n local.revision > authorityPlan.revision ||\n (local.revision === authorityPlan.revision && !canTransitionPlanStatus(local.status, authorityPlan.status))\n ))\n const plan = localWins ? local! : authorityPlan\n let projectionPending = false\n if (!localWins) {\n try {\n await options.store.putPlanProjection(scope, plan)\n } catch (error) {\n projectionPending = true\n logger.warn('[durable-chat] failed to heal plan projection:', error)\n }\n }\n const decision = terminalDecision(plan)\n let receipt = localWins ? undefined : authoritative.receipt\n if (!receipt && decision) {\n const command = await options.store.getPlanCommand(scope, planCommandKey(plan.planId, plan.revision, decision))\n receipt = command?.receipt\n if (!receipt) receipt = recoverReceipt(scope, plan, decision)\n }\n const effectComplete = decision && receipt ? await runEffect(scope, plan, receipt) : true\n return Response.json({\n plan,\n ...(receipt ? { receipt } : {}),\n ...(projectionPending ? { projectionPending: true } : {}),\n ...(!effectComplete ? { effectPending: true } : {}),\n })\n }\n\n async function decide(request: Request): Promise<Response> {\n const body = await request.json().catch(() => null)\n const parsed = parseDecisionBody(body)\n if ('error' in parsed) return Response.json({ code: 'DURABLE_CHAT_BAD_REQUEST', error: parsed.error }, { status: 400 })\n const scope = await authorize(request, 'decide', parsed.planId)\n if (scope instanceof Response) return scope\n const local = await options.store.getPlanProjection(scope, parsed.planId, parsed.revision)\n const current = await options.store.getPlanProjection(scope, parsed.planId)\n if (!local) {\n return Response.json({ code: 'DURABLE_CHAT_UNAVAILABLE', error: 'submitted plan projection is required before deciding' }, { status: 503 })\n }\n if (current && parsed.revision < current.revision) {\n return Response.json({ code: 'DURABLE_CHAT_CONFLICT', error: 'stale plan revision' }, { status: 409 })\n }\n if (local.status !== 'pending') {\n const existingTerminal = terminalDecision(local)\n if (existingTerminal === parsed.decision) {\n const existing = await options.store.getPlanCommand(scope, planCommandKey(parsed.planId, parsed.revision, parsed.decision))\n const receipt = existing?.receipt ?? recoverReceipt(scope, local, parsed.decision)\n const effectComplete = await runEffect(scope, existing?.authorityResult?.plan ?? local, receipt)\n return Response.json({\n plan: existing?.authorityResult?.plan ?? local,\n receipt,\n replayed: true,\n ...(!effectComplete ? { effectPending: true } : {}),\n })\n }\n return Response.json({\n code: 'DURABLE_CHAT_CONFLICT',\n error: 'plan is not pending',\n plan: local,\n }, { status: 409 })\n }\n const opposite = parsed.decision === 'approved' ? 'rejected' : 'approved'\n const oppositeCommand = await options.store.getPlanCommand(scope, planCommandKey(parsed.planId, parsed.revision, opposite))\n if (oppositeCommand) return Response.json({ code: 'DURABLE_CHAT_CONFLICT', error: 'competing decision for plan revision' }, { status: 409 })\n const commandKey = planCommandKey(parsed.planId, parsed.revision, parsed.decision)\n const authorityIdempotencyKey = planAuthorityIdempotencyKey(scope, parsed.planId, parsed.revision, parsed.decision)\n const command: DurablePlanCommandRecord = {\n scope, planId: parsed.planId, revision: parsed.revision, decision: parsed.decision,\n commandKey, authorityIdempotencyKey, state: 'claimed', claimedAt: now(),\n }\n const claimed = await options.store.claimPlanCommand(scope, command)\n if (claimed.status === 'conflict') return Response.json({ code: 'DURABLE_CHAT_CONFLICT', error: claimed.reason }, { status: 409 })\n if (claimed.status === 'existing' && claimed.record.receipt) {\n // Effect errors are intentionally retried on a known committed command.\n const effectComplete = await runEffect(scope, claimed.record.authorityResult?.plan ?? local, claimed.record.receipt)\n return Response.json({\n plan: claimed.record.authorityResult?.plan ?? local,\n receipt: claimed.record.receipt,\n replayed: true,\n ...(!effectComplete ? { effectPending: true } : {}),\n })\n }\n let authorityResult: DurablePlanAuthorityResult & { receipt: DurableFollowUpReceipt }\n try {\n authorityResult = withReceipt(await options.authority.decide({\n scope, planId: parsed.planId, revision: parsed.revision, decision: parsed.decision,\n ...(parsed.feedback ? { feedback: parsed.feedback } : {}), idempotencyKey: authorityIdempotencyKey,\n }), scope, parsed)\n } catch (error) {\n try {\n const reconciled = asCurrent(await options.authority.current({\n scope,\n planId: parsed.planId,\n revision: parsed.revision,\n }))\n const terminal = terminalDecision(reconciled.plan)\n if (reconciled.plan && terminal === parsed.decision) {\n const receipt = reconciled.receipt ?? recoverReceipt(scope, reconciled.plan, terminal)\n authorityResult = {\n plan: reconciled.plan,\n followUp: { turnId: receipt.turnId, state: receipt.state },\n idempotent: true,\n receipt,\n }\n } else if (reconciled.plan && reconciled.plan.status !== 'pending') {\n // The authority has already moved this revision out of its pending\n // state, but not to the decision this request asked for. Surface the\n // authoritative snapshot so the client can converge instead of\n // retrying an already-lost decision as if the authority were down.\n let projectionPending = false\n try {\n await options.store.putPlanProjection(scope, reconciled.plan)\n } catch (projectionError) {\n projectionPending = true\n logger.warn('[durable-chat] failed to reconcile conflicting plan projection:', projectionError)\n }\n return Response.json({\n code: 'DURABLE_CHAT_CONFLICT',\n error: 'plan is not pending',\n plan: reconciled.plan,\n ...(reconciled.receipt ? { receipt: reconciled.receipt } : {}),\n ...(projectionPending ? { projectionPending: true } : {}),\n }, { status: 409 })\n } else {\n return errorResponse(error, 'DURABLE_CHAT_UNAVAILABLE', 503, 'plan authority unavailable')\n }\n } catch {\n return errorResponse(error, 'DURABLE_CHAT_UNAVAILABLE', 503, 'plan authority unavailable')\n }\n }\n let projectionPending = false\n try {\n await options.store.recordPlanAuthorityResult(scope, commandKey, authorityResult, authorityResult.receipt)\n } catch (error) {\n projectionPending = true\n // The authority has committed; the receipt remains safe to return and\n // GET can reconcile from the authority on the next request.\n logger.warn('[durable-chat] failed to record authority result:', error)\n }\n try {\n await options.store.putPlanProjection(scope, authorityResult.plan)\n await options.store.finalizePlanCommand(scope, commandKey)\n } catch (error) {\n projectionPending = true\n logger.warn('[durable-chat] failed to finalize plan projection:', error)\n }\n const effectComplete = await runEffect(scope, authorityResult.plan, authorityResult.receipt)\n return Response.json({\n plan: authorityResult.plan,\n receipt: authorityResult.receipt,\n ...(projectionPending ? { projectionPending: true } : {}),\n ...(!effectComplete ? { effectPending: true } : {}),\n })\n }\n\n return { current, decide }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAUO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAA4B,SAAiB,QAAgB,SAAmB;AAC1F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AACF;AAGO,IAAM,2BAAN,cAAuC,iBAAiB;AAAA,EAC7D,YAAY,UAAU,+BAA+B,SAAmB;AACtE,UAAM,yBAAyB,SAAS,KAAK,OAAO;AACpD,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,8BAAN,cAA0C,iBAAiB;AAAA,EAChE,YAAY,UAAU,sCAAsC,SAAmB;AAC7E,UAAM,4BAA4B,SAAS,KAAK,OAAO;AACvD,SAAK,OAAO;AAAA,EACd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ACpB,OAAO;AACL,iBAAO,cAAc,OAAO,4BAA4B,KAAK,4BAA4B;AAAA,QAC3F;AAAA,MACF,QAAQ;AACN,eAAO,cAAc,OAAO,4BAA4B,KAAK,4BAA4B;AAAA,MAC3F;AAAA,IACF;AACA,QAAI,oBAAoB;AACxB,QAAI;AACF,YAAM,QAAQ,MAAM,0BAA0B,OAAO,YAAY,iBAAiB,gBAAgB,OAAO;AAAA,IAC3G,SAAS,OAAO;AACd,0BAAoB;AAGpB,aAAO,KAAK,qDAAqD,KAAK;AAAA,IACxE;AACA,QAAI;AACF,YAAM,QAAQ,MAAM,kBAAkB,OAAO,gBAAgB,IAAI;AACjE,YAAM,QAAQ,MAAM,oBAAoB,OAAO,UAAU;AAAA,IAC3D,SAAS,OAAO;AACd,0BAAoB;AACpB,aAAO,KAAK,sDAAsD,KAAK;AAAA,IACzE;AACA,UAAM,iBAAiB,MAAM,UAAU,OAAO,gBAAgB,MAAM,gBAAgB,OAAO;AAC3F,WAAO,SAAS,KAAK;AAAA,MACnB,MAAM,gBAAgB;AAAA,MACtB,SAAS,gBAAgB;AAAA,MACzB,GAAI,oBAAoB,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAAA,MACvD,GAAI,CAAC,iBAAiB,EAAE,eAAe,KAAK,IAAI,CAAC;AAAA,IACnD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,SAAS,OAAO;AAC3B;","names":["intentKey","intent","decision","effectComplete","current","projectionPending"]}
|
package/dist/chunk-7ESQUSAC.js
DELETED
|
@@ -1,343 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
createAppToolRuntimeExecutor
|
|
3
|
-
} from "./chunk-UOAYS72M.js";
|
|
4
|
-
import {
|
|
5
|
-
buildAppToolOpenAITools,
|
|
6
|
-
isAppToolName
|
|
7
|
-
} from "./chunk-YEFFHORB.js";
|
|
8
|
-
|
|
9
|
-
// src/runtime/openai-stream.ts
|
|
10
|
-
async function* toLoopEvents(chunks) {
|
|
11
|
-
const calls = /* @__PURE__ */ new Map();
|
|
12
|
-
for await (const chunk of chunks) {
|
|
13
|
-
if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {
|
|
14
|
-
yield {
|
|
15
|
-
type: "usage",
|
|
16
|
-
usage: {
|
|
17
|
-
promptTokens: chunk.usage.prompt_tokens ?? 0,
|
|
18
|
-
completionTokens: chunk.usage.completion_tokens ?? 0
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
const choice = chunk.choices?.[0];
|
|
23
|
-
if (!choice) continue;
|
|
24
|
-
const content = choice.delta?.content;
|
|
25
|
-
if (content) yield { type: "text", text: content };
|
|
26
|
-
const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking;
|
|
27
|
-
if (reasoning) yield { type: "reasoning", text: reasoning };
|
|
28
|
-
for (const tc of choice.delta?.tool_calls ?? []) {
|
|
29
|
-
const cur = calls.get(tc.index) ?? { name: "", args: "" };
|
|
30
|
-
if (tc.id) cur.id = tc.id;
|
|
31
|
-
if (tc.function?.name) cur.name += tc.function.name;
|
|
32
|
-
if (tc.function?.arguments) cur.args += tc.function.arguments;
|
|
33
|
-
calls.set(tc.index, cur);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {
|
|
37
|
-
if (!c.name) continue;
|
|
38
|
-
yield { type: "tool_call", call: { toolCallId: c.id, toolName: c.name, args: safeParse(c.args) } };
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
function safeParse(s) {
|
|
42
|
-
if (!s.trim()) return {};
|
|
43
|
-
try {
|
|
44
|
-
const v = JSON.parse(s);
|
|
45
|
-
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
46
|
-
} catch {
|
|
47
|
-
return {};
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
function createOpenAICompatStreamTurn(opts) {
|
|
51
|
-
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
52
|
-
const doFetch = opts.fetchImpl ?? fetch;
|
|
53
|
-
return (messages) => toLoopEvents(
|
|
54
|
-
streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {
|
|
55
|
-
model: opts.model,
|
|
56
|
-
messages,
|
|
57
|
-
stream: true,
|
|
58
|
-
stream_options: { include_usage: true },
|
|
59
|
-
...opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {},
|
|
60
|
-
...opts.temperature != null ? { temperature: opts.temperature } : {},
|
|
61
|
-
...opts.extraBody
|
|
62
|
-
})
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
async function* streamChatCompletions(doFetch, url, apiKey, body) {
|
|
66
|
-
const res = await doFetch(url, {
|
|
67
|
-
method: "POST",
|
|
68
|
-
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "text/event-stream" },
|
|
69
|
-
body: JSON.stringify(body)
|
|
70
|
-
});
|
|
71
|
-
if (!res.ok || !res.body) {
|
|
72
|
-
const text = res.body ? await res.text().catch(() => "") : "";
|
|
73
|
-
throw new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
74
|
-
}
|
|
75
|
-
const reader = res.body.getReader();
|
|
76
|
-
const decoder = new TextDecoder();
|
|
77
|
-
let buffer = "";
|
|
78
|
-
for (; ; ) {
|
|
79
|
-
const { done, value } = await reader.read();
|
|
80
|
-
if (done) break;
|
|
81
|
-
buffer += decoder.decode(value, { stream: true });
|
|
82
|
-
const lines = buffer.split("\n");
|
|
83
|
-
buffer = lines.pop() ?? "";
|
|
84
|
-
for (const line of lines) {
|
|
85
|
-
const trimmed = line.trim();
|
|
86
|
-
if (!trimmed.startsWith("data:")) continue;
|
|
87
|
-
const data = trimmed.slice(5).trim();
|
|
88
|
-
if (data === "[DONE]") return;
|
|
89
|
-
try {
|
|
90
|
-
yield JSON.parse(data);
|
|
91
|
-
} catch {
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/runtime/loop.ts
|
|
98
|
-
import {
|
|
99
|
-
runToolLoop,
|
|
100
|
-
streamToolLoop
|
|
101
|
-
} from "@tangle-network/agent-runtime";
|
|
102
|
-
|
|
103
|
-
// src/runtime/agent.ts
|
|
104
|
-
function createAgentRuntime(opts) {
|
|
105
|
-
if (opts.executeOtherTool && !opts.isOtherExecutableTool) {
|
|
106
|
-
throw new Error("createAgentRuntime: isOtherExecutableTool is required when executeOtherTool is set");
|
|
107
|
-
}
|
|
108
|
-
const m = opts.model;
|
|
109
|
-
const buildStreamTurn = (extraTools) => createOpenAICompatStreamTurn({
|
|
110
|
-
baseUrl: m.baseUrl,
|
|
111
|
-
apiKey: m.apiKey,
|
|
112
|
-
model: m.model,
|
|
113
|
-
tools: [...buildAppToolOpenAITools(opts.taxonomy), ...extraTools],
|
|
114
|
-
temperature: m.temperature,
|
|
115
|
-
fetchImpl: m.fetchImpl,
|
|
116
|
-
extraBody: m.extraBody
|
|
117
|
-
});
|
|
118
|
-
const baseExtraTools = opts.extraTools ?? [];
|
|
119
|
-
let activeExtraTools = baseExtraTools;
|
|
120
|
-
let activeStreamTurn = buildStreamTurn(baseExtraTools);
|
|
121
|
-
const streamTurnFor = (extraTools) => {
|
|
122
|
-
if (extraTools !== activeExtraTools) {
|
|
123
|
-
activeExtraTools = extraTools;
|
|
124
|
-
activeStreamTurn = buildStreamTurn(extraTools);
|
|
125
|
-
}
|
|
126
|
-
return activeStreamTurn;
|
|
127
|
-
};
|
|
128
|
-
const resolveProfile = async (turn) => {
|
|
129
|
-
const base = {
|
|
130
|
-
systemPrompt: turn.systemPrompt ?? opts.systemPrompt,
|
|
131
|
-
extraTools: baseExtraTools
|
|
132
|
-
};
|
|
133
|
-
return opts.composeProfile ? opts.composeProfile(base) : base;
|
|
134
|
-
};
|
|
135
|
-
const isExecutableTool = (name) => isAppToolName(name) || (opts.isOtherExecutableTool?.(name) ?? false);
|
|
136
|
-
const buildExecutor = (turn) => {
|
|
137
|
-
const appExecutor = createAppToolRuntimeExecutor({
|
|
138
|
-
handlers: opts.handlers,
|
|
139
|
-
taxonomy: opts.taxonomy,
|
|
140
|
-
ctx: turn.ctx,
|
|
141
|
-
onProduced: turn.onProduced
|
|
142
|
-
});
|
|
143
|
-
return async (call) => {
|
|
144
|
-
if (isAppToolName(call.toolName)) return appExecutor({ toolName: call.toolName, args: call.args });
|
|
145
|
-
if (opts.executeOtherTool && opts.isOtherExecutableTool?.(call.toolName)) {
|
|
146
|
-
return opts.executeOtherTool(call, turn.ctx);
|
|
147
|
-
}
|
|
148
|
-
return { ok: false, code: "unknown_tool", message: `No executor for tool: ${call.toolName}` };
|
|
149
|
-
};
|
|
150
|
-
};
|
|
151
|
-
return {
|
|
152
|
-
async run(userMessage, turn) {
|
|
153
|
-
const profile = await resolveProfile(turn);
|
|
154
|
-
return runToolLoop({
|
|
155
|
-
systemPrompt: profile.systemPrompt,
|
|
156
|
-
userMessage,
|
|
157
|
-
priorMessages: turn.priorMessages,
|
|
158
|
-
// The awaitable loop consumes only text + tool_call; the app's UI-only
|
|
159
|
-
// reasoning/usage events ride the substrate's `other` channel.
|
|
160
|
-
streamTurn: narrowToToolLoopEvents(streamTurnFor(profile.extraTools)),
|
|
161
|
-
executeToolCall: buildExecutor(turn),
|
|
162
|
-
isExecutableTool,
|
|
163
|
-
maxToolTurns: opts.maxToolTurns
|
|
164
|
-
});
|
|
165
|
-
},
|
|
166
|
-
async *stream(userMessage, turn) {
|
|
167
|
-
const profile = await resolveProfile(turn);
|
|
168
|
-
yield* streamToolLoop({
|
|
169
|
-
systemPrompt: profile.systemPrompt,
|
|
170
|
-
userMessage,
|
|
171
|
-
priorMessages: turn.priorMessages,
|
|
172
|
-
streamTurn: streamTurnFor(profile.extraTools),
|
|
173
|
-
extractText: (ev) => ev.type === "text" ? ev.text : "",
|
|
174
|
-
extractToolCall: (ev) => ev.type === "tool_call" ? ev.call : null,
|
|
175
|
-
isExecutableTool,
|
|
176
|
-
executeToolCall: buildExecutor(turn),
|
|
177
|
-
maxToolTurns: opts.maxToolTurns
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
function narrowToToolLoopEvents(streamTurn) {
|
|
183
|
-
return (messages) => (async function* () {
|
|
184
|
-
for await (const ev of streamTurn(messages)) {
|
|
185
|
-
if (ev.type === "text") yield { type: "text", text: ev.text };
|
|
186
|
-
else if (ev.type === "tool_call") yield { type: "tool_call", call: ev.call };
|
|
187
|
-
else yield { type: "other", event: ev };
|
|
188
|
-
}
|
|
189
|
-
})();
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// src/runtime/certified-delivery.ts
|
|
193
|
-
import {
|
|
194
|
-
composeCertifiedPrompt,
|
|
195
|
-
pullCertified
|
|
196
|
-
} from "@tangle-network/agent-runtime/intelligence";
|
|
197
|
-
var defaultRefreshMs = 3e5;
|
|
198
|
-
function createCertifiedDelivery(config) {
|
|
199
|
-
const refreshMs = config.refreshMs ?? defaultRefreshMs;
|
|
200
|
-
let certified = null;
|
|
201
|
-
let lastPullAt = 0;
|
|
202
|
-
let inflight = null;
|
|
203
|
-
async function refresh(force = false) {
|
|
204
|
-
if (!force && Date.now() - lastPullAt < refreshMs) return;
|
|
205
|
-
if (inflight) return inflight;
|
|
206
|
-
inflight = (async () => {
|
|
207
|
-
const outcome = await pullCertified({
|
|
208
|
-
target: config.target,
|
|
209
|
-
apiKey: config.apiKey,
|
|
210
|
-
baseUrl: config.baseUrl,
|
|
211
|
-
fetchImpl: config.fetchImpl
|
|
212
|
-
});
|
|
213
|
-
lastPullAt = Date.now();
|
|
214
|
-
if (outcome.succeeded) certified = outcome.value;
|
|
215
|
-
})();
|
|
216
|
-
try {
|
|
217
|
-
await inflight;
|
|
218
|
-
} finally {
|
|
219
|
-
inflight = null;
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
return {
|
|
223
|
-
async composeProfile(base) {
|
|
224
|
-
await refresh();
|
|
225
|
-
return {
|
|
226
|
-
// prompt-surface + skill fold into the system prompt.
|
|
227
|
-
systemPrompt: composeCertifiedPrompt(base.systemPrompt, certified),
|
|
228
|
-
// Certified `tool` artifacts deliver here once they carry a runnable
|
|
229
|
-
// OpenAI def + the product wires the executor; until then pass through.
|
|
230
|
-
extraTools: base.extraTools
|
|
231
|
-
};
|
|
232
|
-
},
|
|
233
|
-
refresh: () => refresh(true),
|
|
234
|
-
current: () => certified
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// src/runtime/surface-profile.ts
|
|
239
|
-
function defineSurfaceKind(opts) {
|
|
240
|
-
if (typeof opts.kind !== "string" || opts.kind.length === 0 || /\s/.test(opts.kind)) {
|
|
241
|
-
throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`);
|
|
242
|
-
}
|
|
243
|
-
if (typeof opts.build !== "function") {
|
|
244
|
-
throw new Error(`surface kind '${opts.kind}' requires a build function`);
|
|
245
|
-
}
|
|
246
|
-
return { kind: opts.kind, build: opts.build };
|
|
247
|
-
}
|
|
248
|
-
function createSurfaceRegistry(kinds) {
|
|
249
|
-
const byKind = /* @__PURE__ */ new Map();
|
|
250
|
-
for (const definition of kinds) {
|
|
251
|
-
if (byKind.has(definition.kind)) {
|
|
252
|
-
throw new Error(`duplicate surface kind '${definition.kind}' \u2014 each kind must be registered exactly once`);
|
|
253
|
-
}
|
|
254
|
-
byKind.set(definition.kind, definition);
|
|
255
|
-
}
|
|
256
|
-
return {
|
|
257
|
-
async resolve(kind, ctx) {
|
|
258
|
-
const definition = byKind.get(kind);
|
|
259
|
-
if (!definition) {
|
|
260
|
-
const known = [...byKind.keys()].join(", ") || "(none)";
|
|
261
|
-
throw new Error(
|
|
262
|
-
`unknown surface kind '${kind}' \u2014 registered kinds: ${known}. An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.`
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
const overlay = await definition.build(ctx);
|
|
266
|
-
assertSurfaceOverlay(overlay, `surface kind '${kind}'`);
|
|
267
|
-
return overlay;
|
|
268
|
-
}
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
var PERMISSION_SEVERITY = { allow: 0, ask: 1, deny: 2 };
|
|
272
|
-
function mergeSurfaceOverlay(base, overlay) {
|
|
273
|
-
assertSurfaceOverlay(overlay, "surface overlay");
|
|
274
|
-
const merged = { ...base };
|
|
275
|
-
if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {
|
|
276
|
-
const baseMcp = base.mcp ?? {};
|
|
277
|
-
const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp);
|
|
278
|
-
if (collisions.length > 0) {
|
|
279
|
-
throw new Error(
|
|
280
|
-
`surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(", ")} already exist on the base profile. Two servers cannot claim one name \u2014 give the surface server a distinct name.`
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
merged.mcp = { ...baseMcp, ...overlay.mcp };
|
|
284
|
-
}
|
|
285
|
-
if (overlay.promptAddendum !== void 0) {
|
|
286
|
-
merged.systemPromptAddendum = base.systemPromptAddendum ? `${base.systemPromptAddendum}
|
|
287
|
-
|
|
288
|
-
${overlay.promptAddendum}` : overlay.promptAddendum;
|
|
289
|
-
}
|
|
290
|
-
if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {
|
|
291
|
-
const permissions = { ...base.permissions ?? {} };
|
|
292
|
-
for (const [key, value] of Object.entries(overlay.permissions)) {
|
|
293
|
-
const existing = permissions[key];
|
|
294
|
-
permissions[key] = existing === void 0 || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing;
|
|
295
|
-
}
|
|
296
|
-
merged.permissions = permissions;
|
|
297
|
-
}
|
|
298
|
-
return merged;
|
|
299
|
-
}
|
|
300
|
-
function assertSurfaceOverlay(overlay, label) {
|
|
301
|
-
if (overlay.promptAddendum !== void 0) {
|
|
302
|
-
if (typeof overlay.promptAddendum !== "string" || overlay.promptAddendum.trim().length === 0) {
|
|
303
|
-
throw new Error(`${label}: promptAddendum must be a non-blank string when provided`);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
if (overlay.mcp !== void 0) {
|
|
307
|
-
for (const [name, server] of Object.entries(overlay.mcp)) {
|
|
308
|
-
if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`);
|
|
309
|
-
if (server.transport !== "http") {
|
|
310
|
-
throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify(server.transport)})`);
|
|
311
|
-
}
|
|
312
|
-
let parsed;
|
|
313
|
-
try {
|
|
314
|
-
parsed = new URL(server.url);
|
|
315
|
-
} catch {
|
|
316
|
-
throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`);
|
|
317
|
-
}
|
|
318
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
319
|
-
throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`);
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
if (overlay.permissions !== void 0) {
|
|
324
|
-
for (const [key, value] of Object.entries(overlay.permissions)) {
|
|
325
|
-
if (!(value in PERMISSION_SEVERITY)) {
|
|
326
|
-
throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
export {
|
|
333
|
-
toLoopEvents,
|
|
334
|
-
createOpenAICompatStreamTurn,
|
|
335
|
-
runToolLoop,
|
|
336
|
-
streamToolLoop,
|
|
337
|
-
createAgentRuntime,
|
|
338
|
-
createCertifiedDelivery,
|
|
339
|
-
defineSurfaceKind,
|
|
340
|
-
createSurfaceRegistry,
|
|
341
|
-
mergeSurfaceOverlay
|
|
342
|
-
};
|
|
343
|
-
//# sourceMappingURL=chunk-7ESQUSAC.js.map
|