@bastani/atomic 0.9.68-alpha.1 → 0.9.69-alpha.1
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/CHANGELOG.md +68 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +20 -0
- package/dist/builtin/workflows/builtin/{chunk-95r61ve5.js → chunk-3gk3k003.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-qbthhjjk.js → chunk-6bgw5p0e.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-rv4xxwd6.js → chunk-k8930apc.js} +101 -37
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +740 -453
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +563 -280
- package/dist/builtin/workflows/src/index.js +549 -266
- package/dist/builtin/workflows/src/local-worker-entry.mjs +563 -280
- package/dist/core/agent-session-boundaries.d.ts.map +1 -1
- package/dist/core/agent-session-boundaries.js +14 -1
- package/dist/core/agent-session-boundaries.js.map +1 -1
- package/dist/core/agent-session-events.d.ts +6 -0
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +99 -20
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-held-input.d.ts +44 -0
- package/dist/core/agent-session-held-input.d.ts.map +1 -0
- package/dist/core/agent-session-held-input.js +76 -0
- package/dist/core/agent-session-held-input.js.map +1 -0
- package/dist/core/agent-session-message-queue.d.ts +6 -2
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +29 -7
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +4 -2
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-persistence-failures.d.ts +19 -0
- package/dist/core/agent-session-persistence-failures.d.ts.map +1 -0
- package/dist/core/agent-session-persistence-failures.js +39 -0
- package/dist/core/agent-session-persistence-failures.js.map +1 -0
- package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.js +3 -0
- package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.js +5 -1
- package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +156 -16
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
- package/dist/core/agent-session-tool-hooks.js +14 -3
- package/dist/core/agent-session-tool-hooks.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +5 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +3 -0
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +10 -2
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +1 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/workflow-run-control.d.ts +6 -0
- package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
- package/dist/core/extensions/workflow-run-control.js.map +1 -1
- package/dist/core/queued-input-admission.d.ts +2 -0
- package/dist/core/queued-input-admission.d.ts.map +1 -1
- package/dist/core/queued-input-admission.js +4 -0
- package/dist/core/queued-input-admission.js.map +1 -1
- package/dist/core/storage/errors.d.ts +2 -0
- package/dist/core/storage/errors.d.ts.map +1 -1
- package/dist/core/storage/errors.js +9 -0
- package/dist/core/storage/errors.js.map +1 -1
- package/dist/core/storage/storage-status.d.ts +2 -2
- package/dist/core/storage/storage-status.d.ts.map +1 -1
- package/dist/core/storage/storage-status.js +2 -10
- package/dist/core/storage/storage-status.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +16 -3
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/conflict-registry.d.ts +17 -0
- package/dist/core/tools/conflict-registry.d.ts.map +1 -1
- package/dist/core/tools/conflict-registry.js +80 -0
- package/dist/core/tools/conflict-registry.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +23 -4
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/history-protocol.d.ts +29 -0
- package/dist/core/tools/history-protocol.d.ts.map +1 -0
- package/dist/core/tools/history-protocol.js +438 -0
- package/dist/core/tools/history-protocol.js.map +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +4 -4
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/resource-selectors.d.ts +28 -0
- package/dist/core/tools/resource-selectors.d.ts.map +1 -1
- package/dist/core/tools/resource-selectors.js +73 -13
- package/dist/core/tools/resource-selectors.js.map +1 -1
- package/dist/core/tools/search-line-ranges.d.ts +5 -0
- package/dist/core/tools/search-line-ranges.d.ts.map +1 -1
- package/dist/core/tools/search-line-ranges.js +7 -3
- package/dist/core/tools/search-line-ranges.js.map +1 -1
- package/dist/core/tools/search.d.ts.map +1 -1
- package/dist/core/tools/search.js +5 -5
- package/dist/core/tools/search.js.map +1 -1
- package/dist/core/tools/shell-plain-words.d.ts +8 -0
- package/dist/core/tools/shell-plain-words.d.ts.map +1 -0
- package/dist/core/tools/shell-plain-words.js +139 -0
- package/dist/core/tools/shell-plain-words.js.map +1 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +8 -45
- package/dist/core/tools/write.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +4 -0
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +4 -0
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-queueing.d.ts +9 -1
- package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-queueing.js +82 -9
- package/dist/modes/interactive/interactive-queueing.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +15 -0
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +5 -1
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts +6 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +16 -1
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +1 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/docs/compaction.md +1 -1
- package/docs/extensions/api-reference.md +3 -1
- package/docs/rpc/protocol.md +1 -1
- package/docs/sdk.md +3 -1
- package/docs/sessions.md +17 -0
- package/docs/storage.md +2 -0
- package/docs/tools.md +8 -4
- package/docs/usage.md +1 -1
- package/npm-shrinkwrap.json +75 -53
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kC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KAAK,QAAQ,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YACvF,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,iCAAiC,GAAG,QAAQ,CAAC;IACpD,iBAAiB,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.js\";\nimport { customMessageExcludesContext } from \"./agent-session-types.js\";\nimport type { PendingRecoveryDelivery } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n\t/** Set when resume recovery declined to replay the card to the model. */\n\trecovery?: \"dropped\";\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nasync function appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<{ readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string }> {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// A retry after a failed flush must complete the already-appended occurrence\n\t// rather than append a second visible card for the same stable key.\n\tconst partial =\n\t\tadmitted.stageAdmissionKey === undefined\n\t\t\t? undefined\n\t\t\t: session.sessionManager\n\t\t\t\t\t.getBranch()\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"custom_message\" &&\n\t\t\t\t\t\t\tentry.stageAdmissionKey === admitted.stageAdmissionKey &&\n\t\t\t\t\t\t\tprotectedDelivery(entry.protectedReconciliation) !== undefined,\n\t\t\t\t\t);\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId =\n\t\tpartial?.id ??\n\t\t(await session.sessionManager.appendCustomMessageEntry(\n\t\t\tcard.customType,\n\t\t\tcard.content,\n\t\t\tcard.display,\n\t\t\tcard.details,\n\t\t\ttrue,\n\t\t\t{ delivery },\n\t\t\tadmitted.stageAdmissionKey,\n\t\t));\n\tsession._entryIdsByMessage.set(card, intentEntryId);\n\tsession._refreshFinalizedContext();\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Durable card intents with neither a persisted hidden completion nor a scheduled one. */\nexport function pendingProtectedStreamingCustomMessages(session: AgentSession): PendingRecoveryDelivery[] {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tconst pending: PendingRecoveryDelivery[] = [];\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tpending.push({\n\t\t\tentryId: entry.id,\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\t...(entry.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: entry.stageAdmissionKey }),\n\t\t\tdelivery,\n\t\t});\n\t}\n\treturn pending;\n}\n\n/** Requeue the hidden model-facing turn of each recovered durable card. */\nexport function recoverProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tpending: readonly PendingRecoveryDelivery[],\n): number {\n\tfor (const entry of pending) {\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst reconciliation: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: false,\n\t\t\tdetails: { protectedReconciliationOf: entry.entryId } satisfies ProtectedReconciliationDetails,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery: entry.delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, entry.delivery);\n\t}\n\treturn pending.length;\n}\n\n/** Close a recovered card without a model turn, so later resumes never offer it again. */\nexport async function dismissProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tpending: PendingRecoveryDelivery,\n): Promise<void> {\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tPROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tpending.content,\n\t\tfalse,\n\t\t{ protectedReconciliationOf: pending.entryId, recovery: \"dropped\" } satisfies ProtectedReconciliationDetails,\n\t\ttrue,\n\t);\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = [];\n\tfor (const message of messages) {\n\t\tconst { card, intentEntryId } = await appendDurableDisplayCard(owner, message, delivery);\n\t\tprepared.push({ card, reconciliation: createProtectedReconciliation(message, intentEntryId) });\n\t}\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n\tpriority = false,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, priority ? \"interrupt\" : delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._isPreparingRun || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\n/**\n * Whether a durable card of this custom type is admitted but its hidden turn is still queued, so the model has not\n * read it yet. Clearing the queue restores protected turns, so a queued entry ends only when it is consumed.\n */\nexport function hasUnreadProtectedCustomMessage(session: AgentSession, customType: string): boolean {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\treturn protectedMessages(owner).some((entry) => {\n\t\tif (entry.phase !== \"queued\") return false;\n\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\tif (intent === undefined) return false;\n\t\tconst card = owner.sessionManager.getEntry(intent);\n\t\treturn card?.type === \"custom_message\" && card.customType === customType;\n\t});\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport async function persistProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): Promise<boolean> {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport async function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport async function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport async function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): Promise<void> {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tawait session.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tawait flushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAOxE,MAAM,CAAC,MAAM,oCAAoC,GAAG,2CAA2C,CAAC;AAchG,SAAS,iBAAiB,CAAC,OAAqB;IAC/C,OAAO,CAAC,iCAAiC,KAAK,EAAE,CAAC;IACjD,OAAO,OAAO,CAAC,iCAAiC,CAAC;AAClD,CAAC;AAED,KAAK,UAAU,wBAAwB,CACtC,OAAqB,EACrB,OAAsB,EACtB,QAA2B;IAE3B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAyD,CAAC;IAC7G,MAAM,QAAQ,GAAG,OAAqC,CAAC;IACvD,6EAA6E;IAC7E,oEAAoE;IACpE,MAAM,OAAO,GACZ,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QACvC,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAAC,cAAc;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AAC,CAAC;IAC9E,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;QAChD,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;YACtE,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC3D,CAAC;IACF,CAAC;AACF,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,wCAAwC,CACvD,MAAoB,EACpB,MAAoB,EACpB,WAA+B;IAE/B,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,QAAQ,EAAE,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1F,MAAM,QAAQ,GAAsC,EAAE,CAAC;IACvD,MAAM,KAAK,GAAsC,EAAE,CAAC;IACpD,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YACvF,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,iCAAiC,GAAG,QAAQ,CAAC;IACpD,iBAAiB,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.js\";\nimport { customMessageExcludesContext } from \"./agent-session-types.js\";\nimport type { PendingRecoveryDelivery } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n\t/** Set when resume recovery declined to replay the card to the model. */\n\trecovery?: \"dropped\";\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nasync function appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<{ readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string }> {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// A retry after a failed flush must complete the already-appended occurrence\n\t// rather than append a second visible card for the same stable key.\n\tconst partial =\n\t\tadmitted.stageAdmissionKey === undefined\n\t\t\t? undefined\n\t\t\t: session.sessionManager\n\t\t\t\t\t.getBranch()\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"custom_message\" &&\n\t\t\t\t\t\t\tentry.stageAdmissionKey === admitted.stageAdmissionKey &&\n\t\t\t\t\t\t\tprotectedDelivery(entry.protectedReconciliation) !== undefined,\n\t\t\t\t\t);\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId =\n\t\tpartial?.id ??\n\t\t(await session.sessionManager.appendCustomMessageEntry(\n\t\t\tcard.customType,\n\t\t\tcard.content,\n\t\t\tcard.display,\n\t\t\tcard.details,\n\t\t\ttrue,\n\t\t\t{ delivery },\n\t\t\tadmitted.stageAdmissionKey,\n\t\t));\n\tsession._entryIdsByMessage.set(card, intentEntryId);\n\tsession._refreshFinalizedContext();\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Durable card intents with neither a persisted hidden completion nor a scheduled one. */\nexport function pendingProtectedStreamingCustomMessages(session: AgentSession): PendingRecoveryDelivery[] {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tconst pending: PendingRecoveryDelivery[] = [];\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tpending.push({\n\t\t\tentryId: entry.id,\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\t...(entry.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: entry.stageAdmissionKey }),\n\t\t\tdelivery,\n\t\t});\n\t}\n\treturn pending;\n}\n\n/** Requeue the hidden model-facing turn of each recovered durable card. */\nexport function recoverProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tpending: readonly PendingRecoveryDelivery[],\n): number {\n\tfor (const entry of pending) {\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst reconciliation: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: false,\n\t\t\tdetails: { protectedReconciliationOf: entry.entryId } satisfies ProtectedReconciliationDetails,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery: entry.delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, entry.delivery);\n\t}\n\treturn pending.length;\n}\n\n/** Close a recovered card without a model turn, so later resumes never offer it again. */\nexport async function dismissProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tpending: PendingRecoveryDelivery,\n): Promise<void> {\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tPROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tpending.content,\n\t\tfalse,\n\t\t{ protectedReconciliationOf: pending.entryId, recovery: \"dropped\" } satisfies ProtectedReconciliationDetails,\n\t\ttrue,\n\t);\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = [];\n\tfor (const message of messages) {\n\t\tconst { card, intentEntryId } = await appendDurableDisplayCard(owner, message, delivery);\n\t\tprepared.push({ card, reconciliation: createProtectedReconciliation(message, intentEntryId) });\n\t}\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n\tpriority = false,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, priority ? \"interrupt\" : delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._isPreparingRun || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\n/**\n * Whether a durable card of this custom type is admitted but its hidden turn is still queued, so the model has not\n * read it yet. Clearing the queue restores protected turns, so a queued entry ends only when it is consumed.\n */\nexport function hasUnreadProtectedCustomMessage(session: AgentSession, customType: string): boolean {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\treturn protectedMessages(owner).some((entry) => {\n\t\tif (entry.phase !== \"queued\") return false;\n\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\tif (intent === undefined) return false;\n\t\tconst card = owner.sessionManager.getEntry(intent);\n\t\treturn card?.type === \"custom_message\" && card.customType === customType;\n\t});\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport async function persistProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): Promise<boolean> {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport async function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\t// #4254: a run stopped on an unsaved message writes nothing more; the next prompt or disposal retries.\n\tif (session._persistenceFailure !== undefined) return;\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport async function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport async function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): Promise<void> {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tawait session.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tawait flushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG9F,OAAO,EAAwC,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAY5G,oFAAoF;AACpF,wBAAsB,yBAAyB,CAC9C,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,YAAY,EAAE,CAAC,CAsHzB;AACD,mFAAmF;AACnF,wBAAgB,kCAAkC,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CAmD/G;AAED,MAAM,WAAW,8BAA8B;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,wBAAwB,CAAC;CACjC;AAED,eAAO,MAAM,qCAAqC;;;CAGjD,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createAutoCompactionCompletion, hasPendingManualCompactionTakeover } from "./agent-session-auto-compaction.js";
|
|
2
2
|
import { emitSessionCompactFailed } from "./agent-session-compaction.js";
|
|
3
3
|
import { authForStream } from "./agent-session-models.js";
|
|
4
|
+
import { rethrowUnlessReportedPersistenceFailure } from "./agent-session-persistence-failures.js";
|
|
4
5
|
import { estimateContextTokens, shouldCompact } from "./compaction/index.js";
|
|
5
6
|
import { scrubPreCompactionAssistantUsage } from "./provider-context-usage.js";
|
|
6
7
|
function postToolFailureMessage(error) {
|
|
@@ -26,7 +27,10 @@ export async function _preflightPostToolContext(messages, signal) {
|
|
|
26
27
|
const overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;
|
|
27
28
|
// Tool-result persistence is ordered on AgentSession's event queue, while Pi
|
|
28
29
|
// may reach its next-turn hook as soon as its own listener barrier settles.
|
|
29
|
-
await this._agentEventQueue;
|
|
30
|
+
await this._agentEventQueue.catch(rethrowUnlessReportedPersistenceFailure);
|
|
31
|
+
// #4226: a run with an unsaved message ends at its request boundary; it compacts nothing first.
|
|
32
|
+
if (this._persistenceFailure !== undefined)
|
|
33
|
+
return messages;
|
|
30
34
|
// Manual compaction owns the next boundary and aborts the active run before
|
|
31
35
|
// planning. Do not append a competing mid-turn boundary in that brief gap.
|
|
32
36
|
if (this._compactionAbortController !== undefined || this._manualCompactionPromise !== undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAE/E,SAAS,sBAAsB,CAAC,KAAc;IAC7C,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAA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ACb,YAAY;YACZ,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACzF,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,KAAK,CAAC;QACV,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,WAAW;QACnB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,IAAI;QACb,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACzF,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC;AAC9B,CAAC;AAOD,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { createAutoCompactionCompletion, hasPendingManualCompactionTakeover } from \"./agent-session-auto-compaction.ts\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings(model);\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue;\n\t// Manual compaction owns the next boundary and aborts the active run before\n\t// planning. Do not append a competing mid-turn boundary in that brief gap.\n\tif (this._compactionAbortController !== undefined || this._manualCompactionPromise !== undefined) {\n\t\treturn messages;\n\t}\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tlet fromExtension = false;\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\t// Ownership publication and the synchronous `compaction_start` emission live\n\t// inside the cleanup scope: `_emit` runs subscribers synchronously, so a\n\t// throwing listener would otherwise leave ownership set with no `finally` to\n\t// clear it. A manual takeover also awaits this settlement before it writes.\n\ttry {\n\t\tthis._autoCompactionAbortController = abortController;\n\t\tthis._autoCompactionCompletion = completion.promise;\n\t\tthis._compactionReason = \"threshold\";\n\t\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate, signal) => {\n\t\t\t\tconst auth = await this._getRequiredRequestAuth(candidate, signal ?? abortController.signal);\n\t\t\t\treturn auth.apiKey || auth.headers ? authForStream(this, auth) : undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// A mid-turn planner failure must reach the fresh rung so the active\n\t\t\t// turn can continue. `_applyVerbatimCompaction` still treats a fitting\n\t\t\t// no-preparation threshold crossing as a safe no-op.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies,\n\t\t// while the getter returns the live internal array. Return a separate array\n\t\t// so the loop and reducer cannot append the next message twice.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason: \"threshold\",\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tif (this._autoCompactionAbortController === abortController) this._autoCompactionAbortController = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tif (this._compactionReason === \"threshold\") this._compactionReason = undefined;\n\t}\n}\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(this: AgentSession, messages: AgentMessage[]): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\t// Mid-turn 0.86 system patches are appended after compaction and before this\n\t// gate. Pre-compaction assistant usage would otherwise keep the old prompt\n\t// size and reject a compacted follow-up that actually fits.\n\tconst projectedTokens = estimateContextTokens(\n\t\tproviderBoundMessages.map((message) => {\n\t\t\tif (message.role !== \"assistant\" || !(\"usage\" in message) || !message.usage) return message;\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tusage: {\n\t\t\t\t\t...message.usage,\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t}),\n\t).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,uCAAuC,EAAE,MAAM,yCAAyC,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MA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AE,CAAC;QAC9C,MAAM,YAAY,GAAG,gBAAgB,CAAC,eAAe,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/E,IAAI,CAAC,iCAAiC,GAAG,YAAY,CAAC;QACtD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;YACb,YAAY;YACZ,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACzF,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,KAAK,CAAC;QACV,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,WAAW;QACnB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,IAAI;QACb,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACzF,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC;AAC9B,CAAC;AAOD,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { createAutoCompactionCompletion, hasPendingManualCompactionTakeover } from \"./agent-session-auto-compaction.ts\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport { rethrowUnlessReportedPersistenceFailure } from \"./agent-session-persistence-failures.ts\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings(model);\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue.catch(rethrowUnlessReportedPersistenceFailure);\n\t// #4226: a run with an unsaved message ends at its request boundary; it compacts nothing first.\n\tif (this._persistenceFailure !== undefined) return messages;\n\t// Manual compaction owns the next boundary and aborts the active run before\n\t// planning. Do not append a competing mid-turn boundary in that brief gap.\n\tif (this._compactionAbortController !== undefined || this._manualCompactionPromise !== undefined) {\n\t\treturn messages;\n\t}\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tlet fromExtension = false;\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\t// Ownership publication and the synchronous `compaction_start` emission live\n\t// inside the cleanup scope: `_emit` runs subscribers synchronously, so a\n\t// throwing listener would otherwise leave ownership set with no `finally` to\n\t// clear it. A manual takeover also awaits this settlement before it writes.\n\ttry {\n\t\tthis._autoCompactionAbortController = abortController;\n\t\tthis._autoCompactionCompletion = completion.promise;\n\t\tthis._compactionReason = \"threshold\";\n\t\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate, signal) => {\n\t\t\t\tconst auth = await this._getRequiredRequestAuth(candidate, signal ?? abortController.signal);\n\t\t\t\treturn auth.apiKey || auth.headers ? authForStream(this, auth) : undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// A mid-turn planner failure must reach the fresh rung so the active\n\t\t\t// turn can continue. `_applyVerbatimCompaction` still treats a fitting\n\t\t\t// no-preparation threshold crossing as a safe no-op.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies,\n\t\t// while the getter returns the live internal array. Return a separate array\n\t\t// so the loop and reducer cannot append the next message twice.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason: \"threshold\",\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tif (this._autoCompactionAbortController === abortController) this._autoCompactionAbortController = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tif (this._compactionReason === \"threshold\") this._compactionReason = undefined;\n\t}\n}\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(this: AgentSession, messages: AgentMessage[]): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\t// Mid-turn 0.86 system patches are appended after compaction and before this\n\t// gate. Pre-compaction assistant usage would otherwise keep the old prompt\n\t// size and reject a compacted follow-up that actually fits.\n\tconst projectedTokens = estimateContextTokens(\n\t\tproviderBoundMessages.map((message) => {\n\t\t\tif (message.role !== \"assistant\" || !(\"usage\" in message) || !message.usage) return message;\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tusage: {\n\t\t\t\t\t...message.usage,\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t}),\n\t).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-prompt.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-prompt.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAYlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAOzG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAgCnD,wBAAsB,+BAA+B,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAE1F;AAED,KAAK,yBAAyB,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,CAAC;AAW7E,KAAK,iCAAiC,GAAG,aAAa,GAAG;IACxD,QAAQ,CAAC,kBAAkB,CAAC,EAAE;QAC7B,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;QACrC,iFAAiF;QACjF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;QACpC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,IAAI,CAAC;KACjE,C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MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,QAAQ,GAAG,uBAAuB,CAAC,GAC/D,OAAO,CAAC,sBAAsB,CAAC,CASjC;AAED;;;;;;;GAOG;AAEH,wBAAsB,QAAQ,CAC7B,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,QAAQ,GAAG,uBAAuB,CAAC,GAC/D,OAAO,CAAC,sBAAsB,CAAC,CASjC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;IACT,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IACjC,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kBAAkB,CAAC,EAAE,iCAAiC,CAAC,oBAAoB,CAAC,CAAC;CAC7E,GACC,OAAO,CAAC,IAAI,CAAC,CAoCf;AAED;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB;;;;;;;;;;CAUrC,CAAC"}
|
|
@@ -2,10 +2,11 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
3
3
|
import { processImage } from "../utils/image-process.js";
|
|
4
4
|
import { resolveWorkflowStageDeliveryTarget } from "./agent-session-delivery-forwarding.js";
|
|
5
|
+
import { earlierHeldInputs, finishHeldInput, hasHeldInput, registerHeldInput, stopWaiting, } from "./agent-session-held-input.js";
|
|
5
6
|
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage, } from "./auth-guidance.js";
|
|
6
7
|
import { runCallback } from "./callback-activity.js";
|
|
7
8
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
8
|
-
import { reserveQueuedInputAdmission, runInputHook, UNORDERED_ADMISSION, } from "./queued-input-admission.js";
|
|
9
|
+
import { isInsideInputHook, reserveQueuedInputAdmission, runInputHook, UNORDERED_ADMISSION, } from "./queued-input-admission.js";
|
|
9
10
|
import { currentResourceAdmission, withOwnResourceAdmission } from "./resource-admission-scope.js";
|
|
10
11
|
import { assertSessionOpen, sessionGenerationClosing, sessionLifetime, sessionQuitSignal, trackSessionWork, } from "./session-lifecycle-work.js";
|
|
11
12
|
import { getSkillCatalog } from "./skill-catalog.js";
|
|
@@ -87,9 +88,58 @@ function queuesDuringAgentSettled(session, options) {
|
|
|
87
88
|
function queuesBehindOpenRun(session, options) {
|
|
88
89
|
return openRuns.has(session) && options?.streamingBehavior !== undefined && options.source !== "extension";
|
|
89
90
|
}
|
|
91
|
+
function compactionSettlement(session) {
|
|
92
|
+
const pending = [
|
|
93
|
+
session._manualCompactionPromise,
|
|
94
|
+
session._autoCompactionCompletion,
|
|
95
|
+
session._branchSummaryCompletion,
|
|
96
|
+
].filter((settlement) => settlement !== undefined);
|
|
97
|
+
return pending.length === 0 ? undefined : Promise.allSettled(pending);
|
|
98
|
+
}
|
|
99
|
+
function untilSessionEnds(work, lifetime) {
|
|
100
|
+
if (lifetime.aborted)
|
|
101
|
+
return Promise.resolve();
|
|
102
|
+
return new Promise((resolve) => {
|
|
103
|
+
const finish = () => {
|
|
104
|
+
lifetime.removeEventListener("abort", finish);
|
|
105
|
+
resolve();
|
|
106
|
+
};
|
|
107
|
+
lifetime.addEventListener("abort", finish, { once: true });
|
|
108
|
+
void work.then(finish, finish);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Hold input that reaches the session while it compacts (#4251): a turn started now would send the transcript
|
|
113
|
+
* that compaction is rewriting. The input is registered on entry, so it keeps its arrival order across senders.
|
|
114
|
+
* Extension commands still run at once and are never registered.
|
|
115
|
+
*/
|
|
116
|
+
function registerInputForCompaction(session, text, options, expandPromptTemplates) {
|
|
117
|
+
if (!session.isCompacting && !hasHeldInput(session))
|
|
118
|
+
return undefined;
|
|
119
|
+
if (expandPromptTemplates && isExtensionCommand(session, text))
|
|
120
|
+
return undefined;
|
|
121
|
+
return registerHeldInput(session, text, options?.streamingBehavior ?? "steer", !isInsideInputHook());
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Wait until every input held before this one has started its turn, queued, or failed, and no compaction runs,
|
|
125
|
+
* or until `clearQueue()` cancels this input or the session ends.
|
|
126
|
+
*/
|
|
127
|
+
async function waitForHeldTurn(session, held, lifetime) {
|
|
128
|
+
const until = (work) => untilSessionEnds(Promise.race([work, held.cancellation.promise]), lifetime);
|
|
129
|
+
const earlier = earlierHeldInputs(session, held);
|
|
130
|
+
if (earlier.length > 0)
|
|
131
|
+
await until(Promise.all(earlier.map((entry) => entry.admitted.promise)));
|
|
132
|
+
for (let settlement = compactionSettlement(session); session.isCompacting && settlement !== undefined && !held.cancelled && !lifetime.aborted; settlement = compactionSettlement(session)) {
|
|
133
|
+
await until(settlement);
|
|
134
|
+
}
|
|
135
|
+
stopWaiting(session, held);
|
|
136
|
+
}
|
|
90
137
|
async function admittedPrompt(text, options) {
|
|
91
|
-
if (this._activePromptCount === 0 && !this.isStreaming)
|
|
138
|
+
if (this._activePromptCount === 0 && !this.isStreaming) {
|
|
92
139
|
this._agentRunAbortRequested = false;
|
|
140
|
+
// #4226: a new prompt saves again after an earlier run stopped on a message it could not save.
|
|
141
|
+
this._persistenceFailure = undefined;
|
|
142
|
+
}
|
|
93
143
|
this._activePromptCount += 1;
|
|
94
144
|
try {
|
|
95
145
|
await promptInternal.call(this, text, options);
|
|
@@ -115,6 +165,9 @@ async function admittedPrompt(text, options) {
|
|
|
115
165
|
this._activePromptCount -= 1;
|
|
116
166
|
}
|
|
117
167
|
}
|
|
168
|
+
function isSessionClosed(error) {
|
|
169
|
+
return typeof error === "object" && error !== null && error.code === "SessionClosed";
|
|
170
|
+
}
|
|
118
171
|
function isExtensionCommand(session, text) {
|
|
119
172
|
if (!text.startsWith("/"))
|
|
120
173
|
return false;
|
|
@@ -141,11 +194,37 @@ async function promptInternal(text, options) {
|
|
|
141
194
|
if (owner !== this)
|
|
142
195
|
return owner.prompt(text, options);
|
|
143
196
|
const expandPromptTemplates = options?.expandPromptTemplates ?? true;
|
|
144
|
-
|
|
197
|
+
let preflightReported = false;
|
|
198
|
+
// Reported once: input held while the session compacts is accepted as queued before it is admitted.
|
|
199
|
+
const preflightResult = (success, disposition) => {
|
|
200
|
+
if (preflightReported)
|
|
201
|
+
return;
|
|
202
|
+
preflightReported = true;
|
|
203
|
+
options?.preflightResult?.(success, disposition);
|
|
204
|
+
};
|
|
145
205
|
const workflowDelivery = options?.__workflowDelivery;
|
|
146
206
|
let messages;
|
|
147
207
|
let preparingRun = false;
|
|
148
208
|
const admission = reserveAdmissionForQueuedPrompt(this, text, options);
|
|
209
|
+
const held = registerInputForCompaction(this, text, options, expandPromptTemplates);
|
|
210
|
+
// The sender learns at once that the session took the input, so an interactive host can stop
|
|
211
|
+
// showing its own copy: the session lists the input as queued from here on.
|
|
212
|
+
const acceptedWhileHeld = held !== undefined && this.isCompacting;
|
|
213
|
+
if (acceptedWhileHeld)
|
|
214
|
+
preflightResult(true, "queued");
|
|
215
|
+
// Input accepted while held must not vanish if a later check fails: it stays queued for the next turn.
|
|
216
|
+
let keptText = text;
|
|
217
|
+
let keptImages = options?.images;
|
|
218
|
+
const keepAcceptedInput = async (error) => {
|
|
219
|
+
if (!acceptedWhileHeld || held.cancelled || isSessionClosed(error))
|
|
220
|
+
return;
|
|
221
|
+
if (this._disposed || lifetime.aborted || sessionGenerationClosing.has(this))
|
|
222
|
+
return;
|
|
223
|
+
if (held.lane === "followUp")
|
|
224
|
+
await this._queueFollowUp(keptText, keptImages);
|
|
225
|
+
else
|
|
226
|
+
await this._queueSteer(keptText, keptImages);
|
|
227
|
+
};
|
|
149
228
|
try {
|
|
150
229
|
// Authorize workflow delivery before commands or input extensions can perform side effects.
|
|
151
230
|
// A later terminal transition cannot retroactively reject input accepted at this boundary.
|
|
@@ -172,6 +251,14 @@ async function promptInternal(text, options) {
|
|
|
172
251
|
if (earlierAdmissions)
|
|
173
252
|
await earlierAdmissions;
|
|
174
253
|
assertCurrent();
|
|
254
|
+
// clearQueue() gave held input back to its sender, so it is not queued again.
|
|
255
|
+
if (held?.cancelled) {
|
|
256
|
+
workflowDelivery?.delivered?.("handled");
|
|
257
|
+
preflightResult?.(true, "handled");
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (held)
|
|
261
|
+
stopWaiting(this, held);
|
|
175
262
|
if (delivery === "followUp")
|
|
176
263
|
await this._queueFollowUp(text, options?.images);
|
|
177
264
|
else
|
|
@@ -202,26 +289,67 @@ async function promptInternal(text, options) {
|
|
|
202
289
|
expandedText = this._expandSkillCommand(expandedText);
|
|
203
290
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
204
291
|
}
|
|
292
|
+
keptText = expandedText;
|
|
293
|
+
keptImages = currentImages;
|
|
205
294
|
const earlierAdmissions = admission.waitForTurn();
|
|
206
295
|
if (earlierAdmissions)
|
|
207
296
|
await earlierAdmissions;
|
|
208
297
|
assertCurrent();
|
|
298
|
+
let delivery = options;
|
|
299
|
+
let waited = false;
|
|
300
|
+
if (held) {
|
|
301
|
+
const startsTurn = !(this.isStreaming || this._isPreparingRun || this._isBeforeSettle) &&
|
|
302
|
+
!queuesDuringAgentSettled(this, options) &&
|
|
303
|
+
!queuesBehindOpenRun(this, options);
|
|
304
|
+
if (earlierHeldInputs(this, held).length > 0 || (this.isCompacting && startsTurn)) {
|
|
305
|
+
await waitForHeldTurn(this, held, lifetime);
|
|
306
|
+
waited = true;
|
|
307
|
+
// The sender found the session idle. If held input ahead of this one started a turn
|
|
308
|
+
// meanwhile, this input queues behind it instead of being refused as a second prompt.
|
|
309
|
+
delivery = { ...options, streamingBehavior: held.lane };
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
stopWaiting(this, held);
|
|
313
|
+
}
|
|
314
|
+
// clearQueue() gave the text back, so the input is not sent.
|
|
315
|
+
if (held.cancelled) {
|
|
316
|
+
workflowDelivery?.delivered?.("handled");
|
|
317
|
+
preflightResult?.(true, "handled");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
assertCurrent();
|
|
321
|
+
// The queue may have been paused while the input waited. Keep it with the paused
|
|
322
|
+
// input instead of letting an abort that followed the pause drop it.
|
|
323
|
+
if (this._queuedMessagesPaused) {
|
|
324
|
+
if (held.lane === "followUp")
|
|
325
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
326
|
+
else
|
|
327
|
+
await this._queueSteer(expandedText, currentImages);
|
|
328
|
+
workflowDelivery?.delivered?.(held.lane);
|
|
329
|
+
preflightResult?.(true, "queued");
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
209
333
|
// If streaming, queue via steer() or followUp() based on option. The run is still
|
|
210
334
|
// open while agent_before_settle handlers decide on its continuation, so input sent
|
|
211
335
|
// from that boundary queues for the continuation instead of starting a second run.
|
|
212
336
|
const busy = this.isStreaming || this._isPreparingRun || this._isBeforeSettle;
|
|
213
|
-
|
|
337
|
+
// Held input from every sender queues behind a run that is still open, as earlier held input
|
|
338
|
+
// with a lane did, so the agent delivers all of it in arrival order.
|
|
339
|
+
const settling = (waited && (this._isEmittingAgentSettled || openRuns.has(this))) ||
|
|
340
|
+
queuesDuringAgentSettled(this, delivery) ||
|
|
341
|
+
(!busy && queuesBehindOpenRun(this, delivery));
|
|
214
342
|
if (busy || settling) {
|
|
215
|
-
if (!
|
|
343
|
+
if (!delivery?.streamingBehavior) {
|
|
216
344
|
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
217
345
|
}
|
|
218
|
-
const queued =
|
|
346
|
+
const queued = delivery.streamingBehavior === "followUp"
|
|
219
347
|
? this._queueFollowUp(expandedText, currentImages)
|
|
220
348
|
: this._queueSteer(expandedText, currentImages);
|
|
221
349
|
if (settling)
|
|
222
350
|
deliverQueuedInputIfIdle(this, { userSubmission: true });
|
|
223
351
|
await queued;
|
|
224
|
-
workflowDelivery?.delivered?.(
|
|
352
|
+
workflowDelivery?.delivered?.(delivery.streamingBehavior);
|
|
225
353
|
preflightResult?.(true, "queued");
|
|
226
354
|
return;
|
|
227
355
|
}
|
|
@@ -322,10 +450,14 @@ async function promptInternal(text, options) {
|
|
|
322
450
|
if (preparingRun)
|
|
323
451
|
this._isPreparingRun = false;
|
|
324
452
|
preflightResult?.(false);
|
|
453
|
+
await keepAcceptedInput(error);
|
|
325
454
|
throw error;
|
|
326
455
|
}
|
|
327
456
|
finally {
|
|
328
457
|
admission.release();
|
|
458
|
+
// A started run is now preparing, so held input admitted next queues behind it.
|
|
459
|
+
if (held)
|
|
460
|
+
finishHeldInput(this, held);
|
|
329
461
|
}
|
|
330
462
|
assertCurrent();
|
|
331
463
|
let dispatched = false;
|
|
@@ -344,6 +476,7 @@ async function promptInternal(text, options) {
|
|
|
344
476
|
if (!dispatched) {
|
|
345
477
|
dispatched = true;
|
|
346
478
|
preflightResult?.(false);
|
|
479
|
+
await keepAcceptedInput(error);
|
|
347
480
|
}
|
|
348
481
|
throw error;
|
|
349
482
|
}
|
|
@@ -367,8 +500,10 @@ export async function _runAgentPrompt(messages, promptStarted, reportDispatch, p
|
|
|
367
500
|
}
|
|
368
501
|
// Any run that starts ends the gap before a fresh stage's first prompt (#3919).
|
|
369
502
|
this._workflowStageAwaitingFirstPrompt = false;
|
|
370
|
-
if (this._activePromptCount === 0 && !this.isStreaming)
|
|
503
|
+
if (this._activePromptCount === 0 && !this.isStreaming) {
|
|
371
504
|
this._agentRunAbortRequested = false;
|
|
505
|
+
this._persistenceFailure = undefined;
|
|
506
|
+
}
|
|
372
507
|
const startingMessages = Array.isArray(messages) ? messages : [messages];
|
|
373
508
|
const customMessage = !prepared
|
|
374
509
|
? (customStarter ?? startingMessages.find((message) => message.role === "custom"))
|
|
@@ -492,7 +627,8 @@ async function settleAgentRun(session) {
|
|
|
492
627
|
session._cacheWarmer?.onAgentSettled();
|
|
493
628
|
try {
|
|
494
629
|
await session._agentEventQueue;
|
|
495
|
-
|
|
630
|
+
// #4254: once the run stopped on an unsaved message, settling neither saves again nor rethrows its error.
|
|
631
|
+
await session._flushPendingCustomMessages(true);
|
|
496
632
|
}
|
|
497
633
|
finally {
|
|
498
634
|
// A failed event or flush must still close and settle the run; otherwise the open-run
|
|
@@ -539,6 +675,9 @@ async function runBeforeSettleContinuations(session) {
|
|
|
539
675
|
return;
|
|
540
676
|
while (!session._agentRunAbortRequested) {
|
|
541
677
|
await session._agentEventQueue?.catch(() => { });
|
|
678
|
+
// #4226: a run that could not save a message is not continued.
|
|
679
|
+
if (session._persistenceFailure !== undefined)
|
|
680
|
+
return;
|
|
542
681
|
if (!(await session._runBeforeSettleBoundary()))
|
|
543
682
|
return;
|
|
544
683
|
// An explicit stop or a paused queue keeps the requested continuation pending.
|
|
@@ -563,7 +702,9 @@ async function settleSubagentMessages(session) {
|
|
|
563
702
|
await session._continueQueuedAgentMessages();
|
|
564
703
|
if (session._stopAfterTurnBlockedContinuation)
|
|
565
704
|
session.pauseQueuedMessages();
|
|
566
|
-
} while (admission.hasPendingDeliveries() ||
|
|
705
|
+
} while (admission.hasPendingDeliveries() ||
|
|
706
|
+
// #4226: a child that could not save a message stops; its queued input waits for its next prompt.
|
|
707
|
+
(!session._queuedMessagesPaused && session._persistenceFailure === undefined && session.agent.hasQueuedMessages()));
|
|
567
708
|
admission.seal();
|
|
568
709
|
}
|
|
569
710
|
export async function _runAgentContinue() {
|
|
@@ -600,6 +741,8 @@ function preparePriorityContinuation(session) {
|
|
|
600
741
|
export async function _continueQueuedAgentMessages() {
|
|
601
742
|
const lifetime = sessionLifetime(this);
|
|
602
743
|
const closing = () => this._disposed || lifetime.aborted || sessionGenerationClosing.has(this);
|
|
744
|
+
// #4226: nothing continues on top of a message the last run could not save.
|
|
745
|
+
const stopped = () => this._stopAfterTurnBlockedContinuation || this._persistenceFailure !== undefined;
|
|
603
746
|
if (closing())
|
|
604
747
|
return;
|
|
605
748
|
await this._agentEventQueue;
|
|
@@ -608,13 +751,10 @@ export async function _continueQueuedAgentMessages() {
|
|
|
608
751
|
await preparePriorityContinuation(this);
|
|
609
752
|
if (closing())
|
|
610
753
|
return;
|
|
611
|
-
if (!this._agentRunAbortRequested &&
|
|
612
|
-
!this._stopAfterTurnBlockedContinuation &&
|
|
613
|
-
!this._queuedMessagesPaused &&
|
|
614
|
-
this.agent.hasQueuedMessages()) {
|
|
754
|
+
if (!this._agentRunAbortRequested && !stopped() && !this._queuedMessagesPaused && this.agent.hasQueuedMessages()) {
|
|
615
755
|
while (!this._agentRunAbortRequested &&
|
|
616
756
|
!closing() &&
|
|
617
|
-
!
|
|
757
|
+
!stopped() &&
|
|
618
758
|
!this._queuedMessagesPaused &&
|
|
619
759
|
this.agent.hasQueuedMessages()) {
|
|
620
760
|
await this.agent.continue();
|
|
@@ -623,7 +763,7 @@ export async function _continueQueuedAgentMessages() {
|
|
|
623
763
|
await preparePriorityContinuation(this);
|
|
624
764
|
}
|
|
625
765
|
}
|
|
626
|
-
if (
|
|
766
|
+
if (stopped())
|
|
627
767
|
return;
|
|
628
768
|
if (closing())
|
|
629
769
|
return;
|