@bastani/atomic 0.9.44-alpha.5 → 0.9.44-alpha.6
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 +15 -0
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/broker/broker.ts +13 -1
- package/dist/builtin/intercom/index.bundle.mjs +9 -1
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/types.ts +7 -0
- package/dist/builtin/intercom/workflow-delivery-states.ts +48 -0
- 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-zjecnjxx.js → chunk-6901nsd6.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-k8d7ehjx.js → chunk-jvna28mq.js} +381 -130
- package/dist/builtin/workflows/builtin/{chunk-qxpymnaf.js → chunk-vwx023ge.js} +1 -1
- 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/durable/journal/internal.d.ts +15 -1
- package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +11 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +2373 -703
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +2245 -697
- package/dist/builtin/workflows/src/index.js +2244 -697
- package/dist/builtin/workflows/src/local-worker-entry.mjs +2245 -697
- package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
- package/dist/core/agent-session-custom-message-commit.js +16 -0
- package/dist/core/agent-session-custom-message-commit.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +130 -13
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/docs/intercom/reference.md +2 -0
- package/docs/workflows/operations.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-custom-message-commit.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAQ9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-custom-message-commit.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAQ9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAgFnD,6EAA6E;AAC7E,wBAAsB,2BAA2B,CAAC,CAAC,EAClD,OAAO,EAAE,YAAY,EACrB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAgHf;AAED,wBAAgB,4BAA4B,CAAC,CAAC,EAC7C,IAAI,EAAE,YAAY,EAClB,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,+EAA+E;AAC/E,wBAAsB,4BAA4B,CAAC,CAAC,EACnD,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CA4Df;AAED,wBAAgB,6BAA6B,CAAC,CAAC,EAC9C,IAAI,EAAE,YAAY,EAClB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAC/B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAEf;AAED,eAAO,MAAM,sCAAsC;;;CAGlD,CAAC"}
|
|
@@ -52,6 +52,20 @@ function queuesBehindFirstStagePrompt(session, options) {
|
|
|
52
52
|
options.deliverAs !== "nextTurn" &&
|
|
53
53
|
options.deliverAs !== "interrupt");
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* A protected delivery accepted while queued input is paused writes its durable card before it queues the hidden
|
|
57
|
+
* turn. A resume during that write releases a hold that does not contain it yet and reports no released work, so
|
|
58
|
+
* nothing would ever start the turn. Start it here, as an idle delivery after the resume would have.
|
|
59
|
+
*/
|
|
60
|
+
function startTurnIfPauseReleasedDuringAdmission(session, starter) {
|
|
61
|
+
if (session._queuedMessagesPaused || session._subagentPolicy?.executionEnded !== undefined)
|
|
62
|
+
return;
|
|
63
|
+
if (session.isStreaming || session._isPreparingRun || session._activePromptCount > 0)
|
|
64
|
+
return;
|
|
65
|
+
const turn = session._runAgentPrompt([], undefined, undefined, false, starter);
|
|
66
|
+
session._workflowStageAdmission?.trackAdmittedWork(turn);
|
|
67
|
+
void turn.catch(() => { });
|
|
68
|
+
}
|
|
55
69
|
/** Commit one delivery whose source generation already granted admission. */
|
|
56
70
|
export async function commitAdmittedCustomMessage(session, appMessage, options) {
|
|
57
71
|
const owner = resolveWorkflowStageDeliveryTarget(session);
|
|
@@ -91,6 +105,7 @@ export async function commitAdmittedCustomMessage(session, appMessage, options)
|
|
|
91
105
|
const delivery = options.deliverAs === "followUp" ? "followUp" : "steer";
|
|
92
106
|
if (useProtectedReconciliation) {
|
|
93
107
|
await queueProtectedStreamingCustomMessage(self, appMessage, delivery);
|
|
108
|
+
startTurnIfPauseReleasedDuringAdmission(self, appMessage);
|
|
94
109
|
}
|
|
95
110
|
else {
|
|
96
111
|
self._queueAgentMessage(appMessage, delivery);
|
|
@@ -197,6 +212,7 @@ export async function commitAdmittedCustomMessages(session, appMessages, options
|
|
|
197
212
|
if (options?.triggerTurn === true) {
|
|
198
213
|
if (useProtectedReconciliation) {
|
|
199
214
|
await queueProtectedStreamingCustomMessages(self, appMessages, delivery);
|
|
215
|
+
startTurnIfPauseReleasedDuringAdmission(self, appMessages[0]);
|
|
200
216
|
}
|
|
201
217
|
else {
|
|
202
218
|
for (const item of appMessages)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-custom-message-commit.js","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAE5F,OAAO,EACN,oCAAoC,EACpC,oCAAoC,EACpC,qCAAqC,EACrC,uCAAuC,GACvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAGrE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAErE,KAAK,UAAU,2BAA2B,CAAI,OAAqB,EAAE,OAAyB;IAC7F,MAAM,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;AAC7C,CAAC;AAED,0FAA0F;AAC1F,KAAK,UAAU,qBAAqB,CAAC,OAAqB,EAAE,OAAsB;IACjF,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IACzC,OAAO,CAAC,+BAA+B,EAAE,CAAC;IAC1C,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAC;QACpC,OAAO,CAAC,UAAU,EAAE,CAAC;QACrB,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;IACD,MAAM,oCAAoC,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE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kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACzE,CAAC;SAAM,IAAI,OAAO,EAAE,WAAW,EAAE,CAAC;QACjC,IAAI,0BAA0B,EAAE,CAAC;YAChC,MAAM,uCAAuC,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;QAC5E,CAAC;aAAM,CAAC;YACP,MAAM,IAAI,GAAG,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;YAC/C,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC3B,CAAC;IACF,CAAC;SAAM,CAAC;QACP,KAAK,MAAM,IAAI,IAAI,WAAW;YAAE,MAAM,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACvE,CAAC;AACF,CAAC;AAED,MAAM,UAAU,6BAA6B,CAE5C,WAA+B,EAC/B,OAA6B;IAE7B,OAAO,4BAA4B,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;AACjE,CAAC;AAED,MAAM,CAAC,MAAM,sCAAsC,GAAG;IACrD,4BAA4B;IAC5B,6BAA6B;CAC7B,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport {\n\tadmitProtectedStreamingCustomMessage,\n\tqueueProtectedStreamingCustomMessage,\n\tqueueProtectedStreamingCustomMessages,\n\ttriggerProtectedStreamingCustomMessages,\n} from \"./agent-session-persistent-custom-messages.ts\";\nimport { deliverQueuedInputIfIdle } from \"./agent-session-prompt.ts\";\nimport type { SendMessageOptions, SendMessagesOptions } from \"./extensions/index.js\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport { TASK_COMPLETION_MESSAGE_TYPE } from \"./tasks/completion.js\";\n\nasync function appendDurableStageAdmission<T>(session: AgentSession, message: CustomMessage<T>): Promise<void> {\n\tawait session._appendCustomMessage(message);\n}\n\n/** Cancel only the receiver's native operation; its original prompt owns continuation. */\nasync function commitPriorityMessage(session: AgentSession, message: CustomMessage): Promise<void> {\n\tsession._priorityInterruptPending = true;\n\tsession._ensureActiveInterruptQueueHold();\n\tif (!session._queuedMessagesPaused) {\n\t\tsession.abortRetry();\n\t\tsession.agent.abort();\n\t}\n\tawait queueProtectedStreamingCustomMessage(session, message, \"steer\", true);\n\tif (\n\t\t!session.isStreaming &&\n\t\tsession._activePromptCount === 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\t!session._subagentMessageAdmission\n\t) {\n\t\t// Idle stage chat has no original prompt awaiter. Start one owned drain,\n\t\t// without replaying the stage task or a completed tool call.\n\t\tconst turn = session._runAgentPrompt([], undefined, undefined, false, message);\n\t\tsession._workflowStageAdmission?.trackAdmittedWork(turn);\n\t\tvoid turn.catch(() => {});\n\t}\n}\n\n/**\n * #3919: before a fresh stage's own prompt is submitted, turn-starting input is that prompt's startup context.\n * Once the prompt is in preflight, a run has started, or queued input is paused, the ordinary admission paths\n * own ordering. The stage's own task completions follow its own work, so they never precede its prompt.\n */\nfunction holdsForFirstStagePrompt<T>(\n\tsession: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions: SendMessageOptions | undefined,\n): boolean {\n\treturn (\n\t\tsession._workflowStageAwaitingFirstPrompt &&\n\t\tsession._activePromptCount === 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\tmessage.customType !== TASK_COMPLETION_MESSAGE_TYPE &&\n\t\toptions?.triggerTurn === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\toptions.deliverAs !== \"nextTurn\"\n\t);\n}\n\n/**\n * #3919: once the stage prompt is submitted but before it owns a run (its input hooks), a turn-starting\n * message must not start a competing turn. It queues behind the pending prompt; interrupts keep their own path.\n */\nfunction queuesBehindFirstStagePrompt(session: AgentSession, options: SendMessageOptions | undefined): boolean {\n\treturn (\n\t\tsession._workflowStageAwaitingFirstPrompt &&\n\t\tsession._activePromptCount > 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\toptions?.triggerTurn === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\toptions.deliverAs !== \"nextTurn\" &&\n\t\toptions.deliverAs !== \"interrupt\"\n\t);\n}\n\n/** Commit one delivery whose source generation already granted admission. */\nexport async function commitAdmittedCustomMessage<T>(\n\tsession: AgentSession,\n\tappMessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return commitAdmittedCustomMessage(owner, appMessage, options);\n\tconst self = session;\n\tif (holdsForFirstStagePrompt(self, appMessage, options)) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t\treturn;\n\t}\n\tconst useProtectedReconciliation =\n\t\toptions?.persistWhenStreaming === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\t(options.triggerTurn === true || options.stageAdmissionKey !== undefined);\n\tif (queuesBehindFirstStagePrompt(self, options)) {\n\t\tconst delivery = options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\t\tif (useProtectedReconciliation) await queueProtectedStreamingCustomMessage(self, appMessage, delivery);\n\t\telse self._queueAgentMessage(appMessage, delivery);\n\t\treturn;\n\t}\n\tif (\n\t\tuseProtectedReconciliation &&\n\t\toptions?.triggerTurn &&\n\t\toptions.deliverAs === \"interrupt\" &&\n\t\t(self._subagentMessageAdmission || self._workflowStageAdmission)\n\t) {\n\t\tawait commitPriorityMessage(self, appMessage);\n\t\treturn;\n\t}\n\tif (options?.deliverAs === \"nextTurn\") {\n\t\tself._pendingNextTurnMessages.push(appMessage);\n\t} else if (\n\t\tself._queuedMessagesPaused ||\n\t\t// A child has one host-owned task prompt, including its asynchronous preflight.\n\t\t// Inbound context joins that execution; an idle SDK gap is not a new task.\n\t\t(self._subagentPolicy?.executionEnded !== undefined && options?.triggerTurn && options.deliverAs !== \"interrupt\")\n\t) {\n\t\tif (options?.triggerTurn === true) {\n\t\t\tconst delivery = options.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\t\t\tif (useProtectedReconciliation) {\n\t\t\t\tawait queueProtectedStreamingCustomMessage(self, appMessage, delivery);\n\t\t\t} else {\n\t\t\t\tself._queueAgentMessage(appMessage, delivery);\n\t\t\t}\n\t\t} else if (self.isStreaming || self._isPreparingRun) {\n\t\t\tself._pendingCustomMessages.push(appMessage);\n\t\t} else {\n\t\t\tawait appendDurableStageAdmission(self, appMessage);\n\t\t}\n\t} else if (options?.deliverAs === \"interrupt\" && options.triggerTurn) {\n\t\tconst interrupt = self._enqueueInterruptCustomMessage(appMessage, options);\n\t\tself._workflowStageAdmission?.trackAdmittedWork(interrupt);\n\t\tvoid interrupt.catch(() => {});\n\t} else if (\n\t\t(self.isStreaming || self._isPreparingRun) &&\n\t\toptions?.excludeFromContext === true &&\n\t\toptions.triggerTurn !== true &&\n\t\toptions.deliverAs === undefined\n\t) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn === false) {\n\t\tself._pendingCustomMessages.push(appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && useProtectedReconciliation) {\n\t\tawait queueProtectedStreamingCustomMessage(\n\t\t\tself,\n\t\t\tappMessage,\n\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t);\n\t\t// The durable card append can yield past the run's last queue drain.\n\t\tif (!self.isStreaming) deliverQueuedInputIfIdle(self);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.persistWhenStreaming === true) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn !== false) {\n\t\tself._queueAgentMessage(appMessage, options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t} else if (useProtectedReconciliation && options?.triggerTurn === true && self._workflowStageAdmission) {\n\t\tawait queueProtectedStreamingCustomMessage(\n\t\t\tself,\n\t\t\tappMessage,\n\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t);\n\t\tconst turn = self._runAgentPrompt([], undefined, undefined, false, appMessage);\n\t\tself._workflowStageAdmission.trackAdmittedWork(turn);\n\t\tvoid turn.catch(() => {});\n\t} else if (options?.triggerTurn) {\n\t\tconst promptMessage = useProtectedReconciliation\n\t\t\t? await admitProtectedStreamingCustomMessage(\n\t\t\t\t\tself,\n\t\t\t\t\tappMessage,\n\t\t\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t\t\t)\n\t\t\t: appMessage;\n\t\t// Durable admission may yield while another turn takes ownership.\n\t\tif (useProtectedReconciliation && (self.isStreaming || self._isPreparingRun)) {\n\t\t\tself._queueAgentMessage(promptMessage, options.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t\t\treturn;\n\t\t}\n\t\tlet resolveAdmission!: () => void;\n\t\tconst admission = new Promise<void>((resolve) => {\n\t\t\tresolveAdmission = resolve;\n\t\t});\n\t\tconst turn = self._runAgentPrompt(promptMessage, resolveAdmission);\n\t\ttry {\n\t\t\tawait Promise.race([admission, turn]);\n\t\t} catch (error) {\n\t\t\tif (!useProtectedReconciliation) throw error;\n\t\t\t// The visible card is already durable. Retry only its hidden turn so\n\t\t\t// lifecycle delivery never appends a second card for this occurrence.\n\t\t\tself._queueAgentMessage(promptMessage, options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t\t\tvoid self._continueQueuedAgentMessages().catch(() => {});\n\t\t}\n\t} else {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t}\n}\n\nexport function _commitAdmittedCustomMessage<T>(\n\tthis: AgentSession,\n\tappMessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\treturn commitAdmittedCustomMessage(this, appMessage, options);\n}\n\n/** Commit a batch whose source generation already granted atomic admission. */\nexport async function commitAdmittedCustomMessages<T>(\n\tsession: AgentSession,\n\tappMessages: CustomMessage<T>[],\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return commitAdmittedCustomMessages(owner, appMessages, options);\n\tconst self = session;\n\tif (appMessages.every((item) => holdsForFirstStagePrompt(self, item, options))) {\n\t\tfor (const item of appMessages) await appendDurableStageAdmission(self, item);\n\t\treturn;\n\t}\n\tconst useProtectedReconciliation =\n\t\toptions?.persistWhenStreaming === true && options.triggerTurn === true && options.excludeFromContext !== true;\n\tconst delivery = options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\tif (queuesBehindFirstStagePrompt(self, options)) {\n\t\tif (useProtectedReconciliation) await queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\telse for (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t\treturn;\n\t}\n\tif (options?.deliverAs === \"nextTurn\") {\n\t\tself._pendingNextTurnMessages.push(...appMessages);\n\t} else if (\n\t\tself._queuedMessagesPaused ||\n\t\t(self._subagentPolicy?.executionEnded !== undefined && options?.triggerTurn)\n\t) {\n\t\tif (options?.triggerTurn === true) {\n\t\t\tif (useProtectedReconciliation) {\n\t\t\t\tawait queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\t\t} else {\n\t\t\t\tfor (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t\t\t}\n\t\t} else if (self.isStreaming || self._isPreparingRun) {\n\t\t\tself._pendingCustomMessages.push(...appMessages);\n\t\t} else {\n\t\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t\t}\n\t} else if (\n\t\t(self.isStreaming || self._isPreparingRun) &&\n\t\toptions?.excludeFromContext === true &&\n\t\toptions.triggerTurn !== true &&\n\t\toptions.deliverAs === undefined\n\t) {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn === false) {\n\t\tself._pendingCustomMessages.push(...appMessages);\n\t} else if ((self.isStreaming || self._isPreparingRun) && useProtectedReconciliation) {\n\t\tawait queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\tif (!self.isStreaming) deliverQueuedInputIfIdle(self);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.persistWhenStreaming === true) {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn !== false) {\n\t\tfor (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t} else if (options?.triggerTurn) {\n\t\tif (useProtectedReconciliation) {\n\t\t\tawait triggerProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\t} else {\n\t\t\tconst turn = self._runAgentPrompt(appMessages);\n\t\t\tvoid turn.catch(() => {});\n\t\t}\n\t} else {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t}\n}\n\nexport function _commitAdmittedCustomMessages<T>(\n\tthis: AgentSession,\n\tappMessages: CustomMessage<T>[],\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\treturn commitAdmittedCustomMessages(this, appMessages, options);\n}\n\nexport const agentSessionCustomMessageCommitMethods = {\n\t_commitAdmittedCustomMessage,\n\t_commitAdmittedCustomMessages,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-custom-message-commit.js","sourceRoot":"","sources":["../../src/core/agent-session-custom-message-commit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAE5F,OAAO,EACN,oCAAoC,EACpC,oCAAoC,EACpC,qCAAqC,EACrC,uCAAuC,GACvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAGrE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAErE,KAAK,UAAU,2BAA2B,CAAI,OAAqB,EAAE,OAAyB;IAC7F,MAAM,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;AAC7C,CAAC;AAED,0FAA0F;AAC1F,KAAK,UAAU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AAC,eAAe,CAAC,WAAW,CAAC,CAAC;YAC/C,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC3B,CAAC;IACF,CAAC;SAAM,CAAC;QACP,KAAK,MAAM,IAAI,IAAI,WAAW;YAAE,MAAM,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACvE,CAAC;AACF,CAAC;AAED,MAAM,UAAU,6BAA6B,CAE5C,WAA+B,EAC/B,OAA6B;IAE7B,OAAO,4BAA4B,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;AACjE,CAAC;AAED,MAAM,CAAC,MAAM,sCAAsC,GAAG;IACrD,4BAA4B;IAC5B,6BAA6B;CAC7B,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport {\n\tadmitProtectedStreamingCustomMessage,\n\tqueueProtectedStreamingCustomMessage,\n\tqueueProtectedStreamingCustomMessages,\n\ttriggerProtectedStreamingCustomMessages,\n} from \"./agent-session-persistent-custom-messages.ts\";\nimport { deliverQueuedInputIfIdle } from \"./agent-session-prompt.ts\";\nimport type { SendMessageOptions, SendMessagesOptions } from \"./extensions/index.js\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport { TASK_COMPLETION_MESSAGE_TYPE } from \"./tasks/completion.js\";\n\nasync function appendDurableStageAdmission<T>(session: AgentSession, message: CustomMessage<T>): Promise<void> {\n\tawait session._appendCustomMessage(message);\n}\n\n/** Cancel only the receiver's native operation; its original prompt owns continuation. */\nasync function commitPriorityMessage(session: AgentSession, message: CustomMessage): Promise<void> {\n\tsession._priorityInterruptPending = true;\n\tsession._ensureActiveInterruptQueueHold();\n\tif (!session._queuedMessagesPaused) {\n\t\tsession.abortRetry();\n\t\tsession.agent.abort();\n\t}\n\tawait queueProtectedStreamingCustomMessage(session, message, \"steer\", true);\n\tif (\n\t\t!session.isStreaming &&\n\t\tsession._activePromptCount === 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\t!session._subagentMessageAdmission\n\t) {\n\t\t// Idle stage chat has no original prompt awaiter. Start one owned drain,\n\t\t// without replaying the stage task or a completed tool call.\n\t\tconst turn = session._runAgentPrompt([], undefined, undefined, false, message);\n\t\tsession._workflowStageAdmission?.trackAdmittedWork(turn);\n\t\tvoid turn.catch(() => {});\n\t}\n}\n\n/**\n * #3919: before a fresh stage's own prompt is submitted, turn-starting input is that prompt's startup context.\n * Once the prompt is in preflight, a run has started, or queued input is paused, the ordinary admission paths\n * own ordering. The stage's own task completions follow its own work, so they never precede its prompt.\n */\nfunction holdsForFirstStagePrompt<T>(\n\tsession: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions: SendMessageOptions | undefined,\n): boolean {\n\treturn (\n\t\tsession._workflowStageAwaitingFirstPrompt &&\n\t\tsession._activePromptCount === 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\tmessage.customType !== TASK_COMPLETION_MESSAGE_TYPE &&\n\t\toptions?.triggerTurn === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\toptions.deliverAs !== \"nextTurn\"\n\t);\n}\n\n/**\n * #3919: once the stage prompt is submitted but before it owns a run (its input hooks), a turn-starting\n * message must not start a competing turn. It queues behind the pending prompt; interrupts keep their own path.\n */\nfunction queuesBehindFirstStagePrompt(session: AgentSession, options: SendMessageOptions | undefined): boolean {\n\treturn (\n\t\tsession._workflowStageAwaitingFirstPrompt &&\n\t\tsession._activePromptCount > 0 &&\n\t\t!session._queuedMessagesPaused &&\n\t\toptions?.triggerTurn === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\toptions.deliverAs !== \"nextTurn\" &&\n\t\toptions.deliverAs !== \"interrupt\"\n\t);\n}\n\n/**\n * A protected delivery accepted while queued input is paused writes its durable card before it queues the hidden\n * turn. A resume during that write releases a hold that does not contain it yet and reports no released work, so\n * nothing would ever start the turn. Start it here, as an idle delivery after the resume would have.\n */\nfunction startTurnIfPauseReleasedDuringAdmission(session: AgentSession, starter: CustomMessage): void {\n\tif (session._queuedMessagesPaused || session._subagentPolicy?.executionEnded !== undefined) return;\n\tif (session.isStreaming || session._isPreparingRun || session._activePromptCount > 0) return;\n\tconst turn = session._runAgentPrompt([], undefined, undefined, false, starter);\n\tsession._workflowStageAdmission?.trackAdmittedWork(turn);\n\tvoid turn.catch(() => {});\n}\n\n/** Commit one delivery whose source generation already granted admission. */\nexport async function commitAdmittedCustomMessage<T>(\n\tsession: AgentSession,\n\tappMessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return commitAdmittedCustomMessage(owner, appMessage, options);\n\tconst self = session;\n\tif (holdsForFirstStagePrompt(self, appMessage, options)) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t\treturn;\n\t}\n\tconst useProtectedReconciliation =\n\t\toptions?.persistWhenStreaming === true &&\n\t\toptions.excludeFromContext !== true &&\n\t\t(options.triggerTurn === true || options.stageAdmissionKey !== undefined);\n\tif (queuesBehindFirstStagePrompt(self, options)) {\n\t\tconst delivery = options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\t\tif (useProtectedReconciliation) await queueProtectedStreamingCustomMessage(self, appMessage, delivery);\n\t\telse self._queueAgentMessage(appMessage, delivery);\n\t\treturn;\n\t}\n\tif (\n\t\tuseProtectedReconciliation &&\n\t\toptions?.triggerTurn &&\n\t\toptions.deliverAs === \"interrupt\" &&\n\t\t(self._subagentMessageAdmission || self._workflowStageAdmission)\n\t) {\n\t\tawait commitPriorityMessage(self, appMessage);\n\t\treturn;\n\t}\n\tif (options?.deliverAs === \"nextTurn\") {\n\t\tself._pendingNextTurnMessages.push(appMessage);\n\t} else if (\n\t\tself._queuedMessagesPaused ||\n\t\t// A child has one host-owned task prompt, including its asynchronous preflight.\n\t\t// Inbound context joins that execution; an idle SDK gap is not a new task.\n\t\t(self._subagentPolicy?.executionEnded !== undefined && options?.triggerTurn && options.deliverAs !== \"interrupt\")\n\t) {\n\t\tif (options?.triggerTurn === true) {\n\t\t\tconst delivery = options.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\t\t\tif (useProtectedReconciliation) {\n\t\t\t\tawait queueProtectedStreamingCustomMessage(self, appMessage, delivery);\n\t\t\t\tstartTurnIfPauseReleasedDuringAdmission(self, appMessage);\n\t\t\t} else {\n\t\t\t\tself._queueAgentMessage(appMessage, delivery);\n\t\t\t}\n\t\t} else if (self.isStreaming || self._isPreparingRun) {\n\t\t\tself._pendingCustomMessages.push(appMessage);\n\t\t} else {\n\t\t\tawait appendDurableStageAdmission(self, appMessage);\n\t\t}\n\t} else if (options?.deliverAs === \"interrupt\" && options.triggerTurn) {\n\t\tconst interrupt = self._enqueueInterruptCustomMessage(appMessage, options);\n\t\tself._workflowStageAdmission?.trackAdmittedWork(interrupt);\n\t\tvoid interrupt.catch(() => {});\n\t} else if (\n\t\t(self.isStreaming || self._isPreparingRun) &&\n\t\toptions?.excludeFromContext === true &&\n\t\toptions.triggerTurn !== true &&\n\t\toptions.deliverAs === undefined\n\t) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn === false) {\n\t\tself._pendingCustomMessages.push(appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && useProtectedReconciliation) {\n\t\tawait queueProtectedStreamingCustomMessage(\n\t\t\tself,\n\t\t\tappMessage,\n\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t);\n\t\t// The durable card append can yield past the run's last queue drain.\n\t\tif (!self.isStreaming) deliverQueuedInputIfIdle(self);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.persistWhenStreaming === true) {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn !== false) {\n\t\tself._queueAgentMessage(appMessage, options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t} else if (useProtectedReconciliation && options?.triggerTurn === true && self._workflowStageAdmission) {\n\t\tawait queueProtectedStreamingCustomMessage(\n\t\t\tself,\n\t\t\tappMessage,\n\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t);\n\t\tconst turn = self._runAgentPrompt([], undefined, undefined, false, appMessage);\n\t\tself._workflowStageAdmission.trackAdmittedWork(turn);\n\t\tvoid turn.catch(() => {});\n\t} else if (options?.triggerTurn) {\n\t\tconst promptMessage = useProtectedReconciliation\n\t\t\t? await admitProtectedStreamingCustomMessage(\n\t\t\t\t\tself,\n\t\t\t\t\tappMessage,\n\t\t\t\t\toptions?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\",\n\t\t\t\t)\n\t\t\t: appMessage;\n\t\t// Durable admission may yield while another turn takes ownership.\n\t\tif (useProtectedReconciliation && (self.isStreaming || self._isPreparingRun)) {\n\t\t\tself._queueAgentMessage(promptMessage, options.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t\t\treturn;\n\t\t}\n\t\tlet resolveAdmission!: () => void;\n\t\tconst admission = new Promise<void>((resolve) => {\n\t\t\tresolveAdmission = resolve;\n\t\t});\n\t\tconst turn = self._runAgentPrompt(promptMessage, resolveAdmission);\n\t\ttry {\n\t\t\tawait Promise.race([admission, turn]);\n\t\t} catch (error) {\n\t\t\tif (!useProtectedReconciliation) throw error;\n\t\t\t// The visible card is already durable. Retry only its hidden turn so\n\t\t\t// lifecycle delivery never appends a second card for this occurrence.\n\t\t\tself._queueAgentMessage(promptMessage, options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\");\n\t\t\tvoid self._continueQueuedAgentMessages().catch(() => {});\n\t\t}\n\t} else {\n\t\tawait appendDurableStageAdmission(self, appMessage);\n\t}\n}\n\nexport function _commitAdmittedCustomMessage<T>(\n\tthis: AgentSession,\n\tappMessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\treturn commitAdmittedCustomMessage(this, appMessage, options);\n}\n\n/** Commit a batch whose source generation already granted atomic admission. */\nexport async function commitAdmittedCustomMessages<T>(\n\tsession: AgentSession,\n\tappMessages: CustomMessage<T>[],\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return commitAdmittedCustomMessages(owner, appMessages, options);\n\tconst self = session;\n\tif (appMessages.every((item) => holdsForFirstStagePrompt(self, item, options))) {\n\t\tfor (const item of appMessages) await appendDurableStageAdmission(self, item);\n\t\treturn;\n\t}\n\tconst useProtectedReconciliation =\n\t\toptions?.persistWhenStreaming === true && options.triggerTurn === true && options.excludeFromContext !== true;\n\tconst delivery = options?.deliverAs === \"followUp\" ? \"followUp\" : \"steer\";\n\tif (queuesBehindFirstStagePrompt(self, options)) {\n\t\tif (useProtectedReconciliation) await queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\telse for (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t\treturn;\n\t}\n\tif (options?.deliverAs === \"nextTurn\") {\n\t\tself._pendingNextTurnMessages.push(...appMessages);\n\t} else if (\n\t\tself._queuedMessagesPaused ||\n\t\t(self._subagentPolicy?.executionEnded !== undefined && options?.triggerTurn)\n\t) {\n\t\tif (options?.triggerTurn === true) {\n\t\t\tif (useProtectedReconciliation) {\n\t\t\t\tawait queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\t\t\tstartTurnIfPauseReleasedDuringAdmission(self, appMessages[0]!);\n\t\t\t} else {\n\t\t\t\tfor (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t\t\t}\n\t\t} else if (self.isStreaming || self._isPreparingRun) {\n\t\t\tself._pendingCustomMessages.push(...appMessages);\n\t\t} else {\n\t\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t\t}\n\t} else if (\n\t\t(self.isStreaming || self._isPreparingRun) &&\n\t\toptions?.excludeFromContext === true &&\n\t\toptions.triggerTurn !== true &&\n\t\toptions.deliverAs === undefined\n\t) {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn === false) {\n\t\tself._pendingCustomMessages.push(...appMessages);\n\t} else if ((self.isStreaming || self._isPreparingRun) && useProtectedReconciliation) {\n\t\tawait queueProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\tif (!self.isStreaming) deliverQueuedInputIfIdle(self);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.persistWhenStreaming === true) {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t} else if ((self.isStreaming || self._isPreparingRun) && options?.triggerTurn !== false) {\n\t\tfor (const item of appMessages) self._queueAgentMessage(item, delivery);\n\t} else if (options?.triggerTurn) {\n\t\tif (useProtectedReconciliation) {\n\t\t\tawait triggerProtectedStreamingCustomMessages(self, appMessages, delivery);\n\t\t} else {\n\t\t\tconst turn = self._runAgentPrompt(appMessages);\n\t\t\tvoid turn.catch(() => {});\n\t\t}\n\t} else {\n\t\tfor (const item of appMessages) await self._appendCustomMessage(item);\n\t}\n}\n\nexport function _commitAdmittedCustomMessages<T>(\n\tthis: AgentSession,\n\tappMessages: CustomMessage<T>[],\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\treturn commitAdmittedCustomMessages(this, appMessages, options);\n}\n\nexport const agentSessionCustomMessageCommitMethods = {\n\t_commitAdmittedCustomMessage,\n\t_commitAdmittedCustomMessages,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAA6D,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAA6D,MAAM,eAAe,CAAC;AA2Z/G,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,MAAM,EACZ,EACC,aAAoB,EACpB,UAA6C,EAC7C,QAAgB,GAChB,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAO,GACzE,OAAO,CAAC,cAAc,CAAC,CA2BzB;AAED,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,YAAY,GAAG,cAAc,CAW/E"}
|
|
@@ -41,6 +41,8 @@ function finalizeReleasedStatements() {
|
|
|
41
41
|
const DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;
|
|
42
42
|
const LOCK_RETRY_BASE_DELAY_MS = 5;
|
|
43
43
|
const LOCK_RETRY_MAX_DELAY_MS = 100;
|
|
44
|
+
/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */
|
|
45
|
+
const MAX_GROUP_COMMIT_TRANSACTIONS = 128;
|
|
44
46
|
/** SQLITE_BUSY, including its extended codes: another connection holds the lock this statement needs. */
|
|
45
47
|
function isSqliteBusy(cause) {
|
|
46
48
|
const code = cause?.errcode;
|
|
@@ -72,6 +74,7 @@ class NodeSqliteDatabase {
|
|
|
72
74
|
descriptor;
|
|
73
75
|
connection;
|
|
74
76
|
tail = Promise.resolve();
|
|
77
|
+
openBatch;
|
|
75
78
|
closing = false;
|
|
76
79
|
closePromise;
|
|
77
80
|
executor;
|
|
@@ -182,43 +185,157 @@ class NodeSqliteDatabase {
|
|
|
182
185
|
this.tail = result.then(() => { }, () => { });
|
|
183
186
|
return result;
|
|
184
187
|
}
|
|
188
|
+
/** A statement queued after open transactions runs after them, so later transactions start a new batch. */
|
|
189
|
+
enqueueStatement(operation) {
|
|
190
|
+
this.openBatch = undefined;
|
|
191
|
+
return this.enqueue(operation);
|
|
192
|
+
}
|
|
185
193
|
exec(sql) {
|
|
186
|
-
return this.
|
|
194
|
+
return this.enqueueStatement(() => this.executor.exec(sql));
|
|
187
195
|
}
|
|
188
196
|
run(sql, ...params) {
|
|
189
197
|
const bound = snapshotParams(params);
|
|
190
|
-
return this.
|
|
198
|
+
return this.enqueueStatement(() => this.executor.run(sql, ...bound));
|
|
191
199
|
}
|
|
192
200
|
get(sql, ...params) {
|
|
193
201
|
const bound = snapshotParams(params);
|
|
194
|
-
return this.
|
|
202
|
+
return this.enqueueStatement(() => this.executor.get(sql, ...bound));
|
|
195
203
|
}
|
|
196
204
|
all(sql, ...params) {
|
|
197
205
|
const bound = snapshotParams(params);
|
|
198
|
-
return this.
|
|
206
|
+
return this.enqueueStatement(() => this.executor.all(sql, ...bound));
|
|
199
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,
|
|
210
|
+
* each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only
|
|
211
|
+
* its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the
|
|
212
|
+
* same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch.
|
|
213
|
+
*/
|
|
200
214
|
transaction(callback) {
|
|
201
|
-
|
|
215
|
+
if (this.closing)
|
|
216
|
+
return Promise.reject(new StoreClosedError(this.descriptor));
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
const queued = { callback, resolve: resolve, reject };
|
|
219
|
+
if (this.openBatch !== undefined && this.openBatch.length < MAX_GROUP_COMMIT_TRANSACTIONS) {
|
|
220
|
+
this.openBatch.push(queued);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
this.startBatch([queued]);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
startBatch(batch) {
|
|
227
|
+
this.openBatch = batch;
|
|
228
|
+
void this.enqueue(() => this.commitBatch(batch));
|
|
229
|
+
}
|
|
230
|
+
commitBatch(batch) {
|
|
231
|
+
if (this.openBatch === batch)
|
|
232
|
+
this.openBatch = undefined;
|
|
233
|
+
return gateTransaction(this.transactionIdentity, () => batch.length === 1 ? this.commitAlone(batch[0]) : this.commitMembers(batch));
|
|
234
|
+
}
|
|
235
|
+
/** A transaction with nobody queued behind it commits on its own, without savepoints. */
|
|
236
|
+
async commitAlone(queued) {
|
|
237
|
+
try {
|
|
202
238
|
await this.begin();
|
|
239
|
+
}
|
|
240
|
+
catch (cause) {
|
|
241
|
+
queued.reject(cause);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
let active = true;
|
|
245
|
+
try {
|
|
246
|
+
const value = await queued.callback(this.createExecutor(() => active));
|
|
247
|
+
active = false;
|
|
248
|
+
await this.executor.exec("COMMIT");
|
|
249
|
+
queued.resolve(value);
|
|
250
|
+
}
|
|
251
|
+
catch (cause) {
|
|
252
|
+
active = false;
|
|
253
|
+
try {
|
|
254
|
+
await this.executor.exec("ROLLBACK");
|
|
255
|
+
}
|
|
256
|
+
catch (rollbackCause) {
|
|
257
|
+
queued.reject(new StorageRollbackError(cause, rollbackCause));
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
queued.reject(cause);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async commitMembers(batch) {
|
|
264
|
+
try {
|
|
265
|
+
await this.begin();
|
|
266
|
+
}
|
|
267
|
+
catch (cause) {
|
|
268
|
+
for (const queued of batch)
|
|
269
|
+
queued.reject(cause);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const outcomes = [];
|
|
273
|
+
for (const queued of batch) {
|
|
274
|
+
const savepoint = `atomic_group_${outcomes.length}`;
|
|
203
275
|
let active = true;
|
|
204
|
-
const transaction = this.createExecutor(() => active);
|
|
205
276
|
try {
|
|
206
|
-
|
|
277
|
+
await this.executor.exec(`SAVEPOINT ${savepoint}`);
|
|
278
|
+
const value = await queued.callback(this.createExecutor(() => active));
|
|
207
279
|
active = false;
|
|
208
|
-
await this.executor.exec(
|
|
209
|
-
|
|
280
|
+
await this.executor.exec(`RELEASE ${savepoint}`);
|
|
281
|
+
outcomes.push({ ok: true, value });
|
|
210
282
|
}
|
|
211
283
|
catch (cause) {
|
|
212
284
|
active = false;
|
|
213
285
|
try {
|
|
214
|
-
await this.executor.exec(
|
|
286
|
+
await this.executor.exec(`ROLLBACK TO ${savepoint}`);
|
|
287
|
+
await this.executor.exec(`RELEASE ${savepoint}`);
|
|
215
288
|
}
|
|
216
289
|
catch (rollbackCause) {
|
|
217
|
-
|
|
290
|
+
await this.abandonMembers(batch, outcomes, cause, rollbackCause);
|
|
291
|
+
return;
|
|
218
292
|
}
|
|
219
|
-
|
|
293
|
+
outcomes.push({ ok: false, error: cause });
|
|
220
294
|
}
|
|
221
|
-
}
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
await this.executor.exec("COMMIT");
|
|
298
|
+
}
|
|
299
|
+
catch (commitCause) {
|
|
300
|
+
await this.rollbackQuietly();
|
|
301
|
+
batch.forEach((queued, index) => {
|
|
302
|
+
const outcome = outcomes[index];
|
|
303
|
+
queued.reject(outcome.ok ? commitCause : outcome.error);
|
|
304
|
+
});
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
batch.forEach((queued, index) => {
|
|
308
|
+
const outcome = outcomes[index];
|
|
309
|
+
if (outcome.ok)
|
|
310
|
+
queued.resolve(outcome.value);
|
|
311
|
+
else
|
|
312
|
+
queued.reject(outcome.error);
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their
|
|
317
|
+
* uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a
|
|
318
|
+
* fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.
|
|
319
|
+
*/
|
|
320
|
+
async abandonMembers(batch, outcomes, cause, rollbackCause) {
|
|
321
|
+
await this.rollbackQuietly();
|
|
322
|
+
const failed = outcomes.length;
|
|
323
|
+
batch.slice(0, failed).forEach((queued, index) => {
|
|
324
|
+
const outcome = outcomes[index];
|
|
325
|
+
queued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);
|
|
326
|
+
});
|
|
327
|
+
batch[failed].reject(new StorageRollbackError(cause, rollbackCause));
|
|
328
|
+
const remaining = batch.slice(failed + 1);
|
|
329
|
+
if (remaining.length > 0)
|
|
330
|
+
await this.commitMembers(remaining);
|
|
331
|
+
}
|
|
332
|
+
async rollbackQuietly() {
|
|
333
|
+
try {
|
|
334
|
+
await this.executor.exec("ROLLBACK");
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
// SQLite already rolled the transaction back; there is nothing left to undo.
|
|
338
|
+
}
|
|
222
339
|
}
|
|
223
340
|
close() {
|
|
224
341
|
if (!this.closePromise) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAOrB,2GAA2G;AAC3G,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;AACvF,MAAM,OAAO,GAAG,UAA8E,CAAC;AAC/F,MAAM,KAAK,GAAqB,OAAO,CAAC,iBAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,WAAW,EAAE,IAAI,OAAO,EAAE,EAAE,CAAC;AAC/G,OAAO,CAAC,iBAAi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F,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC;YACJ,UAAU,EAAE,KAAK,EAAE,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACR,sDAAsD;QACvD,CAAC;QACD,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,UAAwB;IAC9D,MAAM,UAAU,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACpE,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,UAAU,CAAC;QAC1D,UAAU,CAAC,IAAI,CACd,oGAAoG,CACpG,CAAC;QACF,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC","sourcesContent":["import { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/** Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while another connection holds the write lock. */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\nconst LOCK_RETRY_BASE_DELAY_MS = 5;\nconst LOCK_RETRY_MAX_DELAY_MS = 100;\n\n/** SQLITE_BUSY, including its extended codes: another connection holds the lock this statement needs. */\nfunction isSqliteBusy(cause: unknown): boolean {\n\tconst code = (cause as { errcode?: unknown } | null | undefined)?.errcode;\n\treturn typeof code === \"number\" && (code & 0xff) === 5;\n}\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\tprivate readonly lockWaitMs: number;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`\n\t * and the connection's own value is restored before returning or throwing, so single statements outside a\n\t * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs\n\t * on the connection in between.\n\t */\n\tprivate tryBegin(): void {\n\t\tthis.driver(() => {\n\t\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\t\tlet began = false;\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tbegan = true;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t\t} catch (restoreFailure) {\n\t\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\t\tthrow restoreFailure;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried after a jittered timer until `lockWaitMs` has passed; every other\n\t * failure, and a lock still held at the deadline, rejects at once with its cause.\n\t */\n\tprivate async begin(): Promise<void> {\n\t\tconst started = Date.now();\n\t\tfor (let attempt = 0; ; attempt += 1) {\n\t\t\ttry {\n\t\t\t\tthis.tryBegin();\n\t\t\t\treturn;\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\t\tconst remaining = started + this.lockWaitMs - Date.now();\n\t\t\t\tif (remaining <= 0) {\n\t\t\t\t\tthrow unavailable(\n\t\t\t\t\t\tthis.descriptor,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\t`${sqliteFailureDetail(cause)}; gave up after waiting ${Date.now() - started} ms for the write lock`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst backoff = Math.min(LOCK_RETRY_MAX_DELAY_MS, LOCK_RETRY_BASE_DELAY_MS * 2 ** attempt);\n\t\t\t\tawait new Promise((resolve) =>\n\t\t\t\t\tsetTimeout(resolve, Math.min(remaining, backoff * (0.5 + Math.random() / 2))),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueue(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\ttransaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {\n\t\treturn this.enqueue(() =>\n\t\t\tgateTransaction(this.transactionIdentity, async () => {\n\t\t\t\tawait this.begin();\n\t\t\t\tlet active = true;\n\t\t\t\tconst transaction = this.createExecutor(() => active);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await callback(transaction);\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\t\t\treturn result;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\t\tthrow new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause);\n\t\t\t\t\t}\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t}: { busyTimeoutMs?: number; lockWaitMs?: number; readOnly?: boolean } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path, { readOnly });\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) connection.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(\n\t\t\t\"PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\",\n\t\t);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAOrB,2GAA2G;AAC3G,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;AACvF,MAAM,OAAO,GAAG,UAA8E,CAAC;AAC/F,MAAM,KAAK,GAAqB,OAAO,CAAC,iBAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,WAAW,EAAE,IAAI,OAAO,EAAE,EAAE,CAAC;AAC/G,OAAO,CAAC,iBAAiB,CAAC,GAAG,KAAK,CAAC;AAEnC,SAAS,eAAe,CAAI,QAA+B,EAAE,SAA2B;IACvF,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAA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BAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC","sourcesContent":["import { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/** Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while another connection holds the write lock. */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\nconst LOCK_RETRY_BASE_DELAY_MS = 5;\nconst LOCK_RETRY_MAX_DELAY_MS = 100;\n/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */\nconst MAX_GROUP_COMMIT_TRANSACTIONS = 128;\n\ninterface QueuedTransaction {\n\treadonly callback: (transaction: SqliteExecutor) => Promise<unknown>;\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\ntype TransactionOutcome =\n\t| { readonly ok: true; readonly value: unknown }\n\t| { readonly ok: false; readonly error: unknown };\n\n/** SQLITE_BUSY, including its extended codes: another connection holds the lock this statement needs. */\nfunction isSqliteBusy(cause: unknown): boolean {\n\tconst code = (cause as { errcode?: unknown } | null | undefined)?.errcode;\n\treturn typeof code === \"number\" && (code & 0xff) === 5;\n}\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate openBatch?: QueuedTransaction[];\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\tprivate readonly lockWaitMs: number;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`\n\t * and the connection's own value is restored before returning or throwing, so single statements outside a\n\t * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs\n\t * on the connection in between.\n\t */\n\tprivate tryBegin(): void {\n\t\tthis.driver(() => {\n\t\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\t\tlet began = false;\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tbegan = true;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t\t} catch (restoreFailure) {\n\t\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\t\tthrow restoreFailure;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried after a jittered timer until `lockWaitMs` has passed; every other\n\t * failure, and a lock still held at the deadline, rejects at once with its cause.\n\t */\n\tprivate async begin(): Promise<void> {\n\t\tconst started = Date.now();\n\t\tfor (let attempt = 0; ; attempt += 1) {\n\t\t\ttry {\n\t\t\t\tthis.tryBegin();\n\t\t\t\treturn;\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\t\tconst remaining = started + this.lockWaitMs - Date.now();\n\t\t\t\tif (remaining <= 0) {\n\t\t\t\t\tthrow unavailable(\n\t\t\t\t\t\tthis.descriptor,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\t`${sqliteFailureDetail(cause)}; gave up after waiting ${Date.now() - started} ms for the write lock`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst backoff = Math.min(LOCK_RETRY_MAX_DELAY_MS, LOCK_RETRY_BASE_DELAY_MS * 2 ** attempt);\n\t\t\t\tawait new Promise((resolve) =>\n\t\t\t\t\tsetTimeout(resolve, Math.min(remaining, backoff * (0.5 + Math.random() / 2))),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** A statement queued after open transactions runs after them, so later transactions start a new batch. */\n\tprivate enqueueStatement<T>(operation: () => Promise<T>): Promise<T> {\n\t\tthis.openBatch = undefined;\n\t\treturn this.enqueue(operation);\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueueStatement(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\t/**\n\t * Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,\n\t * each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only\n\t * its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the\n\t * same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch.\n\t */\n\ttransaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst queued: QueuedTransaction = { callback, resolve: resolve as (value: unknown) => void, reject };\n\t\t\tif (this.openBatch !== undefined && this.openBatch.length < MAX_GROUP_COMMIT_TRANSACTIONS) {\n\t\t\t\tthis.openBatch.push(queued);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.startBatch([queued]);\n\t\t});\n\t}\n\n\tprivate startBatch(batch: QueuedTransaction[]): void {\n\t\tthis.openBatch = batch;\n\t\tvoid this.enqueue(() => this.commitBatch(batch));\n\t}\n\n\tprivate commitBatch(batch: QueuedTransaction[]): Promise<void> {\n\t\tif (this.openBatch === batch) this.openBatch = undefined;\n\t\treturn gateTransaction(this.transactionIdentity, () =>\n\t\t\tbatch.length === 1 ? this.commitAlone(batch[0]!) : this.commitMembers(batch),\n\t\t);\n\t}\n\n\t/** A transaction with nobody queued behind it commits on its own, without savepoints. */\n\tprivate async commitAlone(queued: QueuedTransaction): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin();\n\t\t} catch (cause) {\n\t\t\tqueued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tlet active = true;\n\t\ttry {\n\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\tactive = false;\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\tqueued.resolve(value);\n\t\t} catch (cause) {\n\t\t\tactive = false;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t} catch (rollbackCause) {\n\t\t\t\tqueued.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tqueued.reject(cause);\n\t\t}\n\t}\n\n\tprivate async commitMembers(batch: QueuedTransaction[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin();\n\t\t} catch (cause) {\n\t\t\tfor (const queued of batch) queued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tconst outcomes: TransactionOutcome[] = [];\n\t\tfor (const queued of batch) {\n\t\t\tconst savepoint = `atomic_group_${outcomes.length}`;\n\t\t\tlet active = true;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(`SAVEPOINT ${savepoint}`);\n\t\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\t\tactive = false;\n\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\toutcomes.push({ ok: true, value });\n\t\t\t} catch (cause) {\n\t\t\t\tactive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.executor.exec(`ROLLBACK TO ${savepoint}`);\n\t\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tawait this.abandonMembers(batch, outcomes, cause, rollbackCause);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.push({ ok: false, error: cause });\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t} catch (commitCause) {\n\t\t\tawait this.rollbackQuietly();\n\t\t\tbatch.forEach((queued, index) => {\n\t\t\t\tconst outcome = outcomes[index]!;\n\t\t\t\tqueued.reject(outcome.ok ? commitCause : outcome.error);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tbatch.forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tif (outcome.ok) queued.resolve(outcome.value);\n\t\t\telse queued.reject(outcome.error);\n\t\t});\n\t}\n\n\t/**\n\t * A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their\n\t * uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a\n\t * fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.\n\t */\n\tprivate async abandonMembers(\n\t\tbatch: QueuedTransaction[],\n\t\toutcomes: TransactionOutcome[],\n\t\tcause: unknown,\n\t\trollbackCause: unknown,\n\t): Promise<void> {\n\t\tawait this.rollbackQuietly();\n\t\tconst failed = outcomes.length;\n\t\tbatch.slice(0, failed).forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tqueued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);\n\t\t});\n\t\tbatch[failed]!.reject(\n\t\t\tnew StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause),\n\t\t);\n\t\tconst remaining = batch.slice(failed + 1);\n\t\tif (remaining.length > 0) await this.commitMembers(remaining);\n\t}\n\n\tprivate async rollbackQuietly(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// SQLite already rolled the transaction back; there is nothing left to undo.\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t}: { busyTimeoutMs?: number; lockWaitMs?: number; readOnly?: boolean } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path, { readOnly });\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) connection.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(\n\t\t\t\"PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\",\n\t\t);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n"]}
|
|
@@ -88,6 +88,8 @@ The `[future]` queued count is the number of retained sticky messages, not the n
|
|
|
88
88
|
|
|
89
89
|
`[delivery]` rows retain per-stage evidence for sticky targets missing from the future-target list, including exact targets after materialization. They do not indicate that a stage is still in the future or currently live. Use the per-stage state to decide what to do; an ended stage without confirmed context admission shows `stage-terminal`, even when transport delivery was acknowledged.
|
|
90
90
|
|
|
91
|
+
Each row in `intercom list`, and each run in `workflow` status, lists at most 5 delivery states. When there are more, the states that still need action come first (`queued`, `receipt-unverified`, `session-replaced`, `delivery-unavailable`, `root-unresolved`, `stage-terminal`), followed by the most recent `delivered` ones. A final line reports how many states were omitted and the total in each state. The `deliveryStateCounts` and `omittedDeliveryStates` fields carry the same totals.
|
|
92
|
+
|
|
91
93
|
| State | What to do |
|
|
92
94
|
| --- | --- |
|
|
93
95
|
| `queued` | Wait for the matching stage to finish startup. |
|
|
@@ -35,7 +35,7 @@ intercom({
|
|
|
35
35
|
|
|
36
36
|
Send material updates through Intercom to every affected workflow stage, including stages that have not started. Name and pattern sends remain sticky for every future matching stage until root termination. When shared scope or acceptance criteria change, broadcast one authoritative update to `workflow:<rootRunId>/**` (or a narrower path pattern) rather than enumerating stages; live matches receive it immediately and future descendants receive it before their first model turn. A syntactically valid path outside the persisted known set queues with a `notInKnownSet` warning and settles undeliverable at terminal only if never delivered; an entry delivered at least once is not reported undeliverable. Use `ask` once the stage session is live and can reply.
|
|
37
37
|
|
|
38
|
-
To verify a sticky update, inspect its per-stage `deliveryStates` in `intercom list` or `workflow({ action: "status", runId: "<rootRunId>" })`. The future target's queued count includes messages retained for stages that have not started yet, even after delivery to earlier stages. It is not an unread count or proof of receipt by every stage. `delivered` confirms admission to stage context, not compliance with the update. A transport-only or older receipt appears as `receipt-unverified`; check the stage transcript before resending. See [pending delivery states](/intercom/reference#deferred-delivery-to-pending-stages) for skip reasons and recovery.
|
|
38
|
+
To verify a sticky update, inspect its per-stage `deliveryStates` in `intercom list` or `workflow({ action: "status", runId: "<rootRunId>" })`. Both list at most 5 states, those still needing action first; `deliveryStateCounts` totals every state. The future target's queued count includes messages retained for stages that have not started yet, even after delivery to earlier stages. It is not an unread count or proof of receipt by every stage. `delivered` confirms admission to stage context, not compliance with the update. A transport-only or older receipt appears as `receipt-unverified`; check the stage transcript before resending. See [pending delivery states](/intercom/reference#deferred-delivery-to-pending-stages) for skip reasons and recovery.
|
|
39
39
|
|
|
40
40
|
### Reading and scrolling the panel
|
|
41
41
|
|