@tangle-network/agent-app 0.55.7 → 0.56.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.
Files changed (32) hide show
  1. package/dist/assistant/index.js +4 -4
  2. package/dist/chat-routes/completed-sandbox-turn.d.ts +9 -1
  3. package/dist/chat-routes/detached-turn.d.ts +3 -9
  4. package/dist/chat-routes/index.d.ts +2 -1
  5. package/dist/chat-routes/index.js +206 -55
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-routes/plan-follow-up.d.ts +108 -0
  8. package/dist/chat-store/index.js +3 -3
  9. package/dist/{chunk-RSTPXLC3.js → chunk-3LOTQCW7.js} +3 -3
  10. package/dist/{chunk-HXTJXODG.js → chunk-GBOHTAQH.js} +11 -2
  11. package/dist/chunk-GBOHTAQH.js.map +1 -0
  12. package/dist/{chunk-V4JZ5OYC.js → chunk-HTAFI247.js} +2 -2
  13. package/dist/{chunk-YJMCRXQQ.js → chunk-LQYIBL3G.js} +3 -3
  14. package/dist/{chunk-YJMCRXQQ.js.map → chunk-LQYIBL3G.js.map} +1 -1
  15. package/dist/{chunk-UII4YDYS.js → chunk-N56FWDSP.js} +2 -2
  16. package/dist/{chunk-2HEFK764.js → chunk-TNDBW5XG.js} +3 -3
  17. package/dist/peer-floors/cli.js +123 -3
  18. package/dist/peer-floors/cli.js.map +1 -1
  19. package/dist/peer-floors/durability-owners.d.ts +23 -0
  20. package/dist/plans/index.d.ts +6 -2
  21. package/dist/plans/index.js +1 -1
  22. package/dist/public-consultation/index.js +5 -5
  23. package/dist/stream/index.js +5 -3
  24. package/dist/stream/turn-buffer.d.ts +8 -1
  25. package/dist/turn-stream/index.js +1 -1
  26. package/dist/web-react/index.js +4 -4
  27. package/package.json +1 -1
  28. package/dist/chunk-HXTJXODG.js.map +0 -1
  29. /package/dist/{chunk-RSTPXLC3.js.map → chunk-3LOTQCW7.js.map} +0 -0
  30. /package/dist/{chunk-V4JZ5OYC.js.map → chunk-HTAFI247.js.map} +0 -0
  31. /package/dist/{chunk-UII4YDYS.js.map → chunk-N56FWDSP.js.map} +0 -0
  32. /package/dist/{chunk-2HEFK764.js.map → chunk-TNDBW5XG.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-2HEFK764.js";
3
+ } from "../chunk-TNDBW5XG.js";
4
4
  import "../chunk-X374TCDT.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-E4AY62T2.js";
@@ -26,13 +26,13 @@ import "../chunk-FQYAJYPW.js";
26
26
  import "../chunk-NJA6X7JI.js";
27
27
  import "../chunk-MCYJON3F.js";
28
28
  import "../chunk-7YA4QNTU.js";
29
- import "../chunk-V4JZ5OYC.js";
29
+ import "../chunk-HTAFI247.js";
30
30
  import "../chunk-ZVEEWGDK.js";
31
31
  import "../chunk-GYDFGEJ2.js";
32
32
  import "../chunk-TXD5HXLE.js";
33
- import "../chunk-UII4YDYS.js";
33
+ import "../chunk-N56FWDSP.js";
34
34
  import "../chunk-FCON65I2.js";
35
- import "../chunk-YJMCRXQQ.js";
35
+ import "../chunk-LQYIBL3G.js";
36
36
 
37
37
  // src/assistant/sse.ts
38
38
  var SSEChunkParser = class {
@@ -8,7 +8,9 @@
8
8
  * the same `DetachedTurnFinal` shape `runDetachedTurn` already consumes.
9
9
  */
10
10
  import type { SandboxInstance, SessionMessage } from '@tangle-network/sandbox';
11
+ import { type JsonRecord } from '../stream/index';
11
12
  import type { DetachedTurnFinal } from './detached-turn';
13
+ import type { ChatTurnModelAttribution, ChatTurnUsage } from './turn-routes';
12
14
  /** The official Sandbox methods needed for completed-turn recovery. */
13
15
  export type CompletedSandboxTurnSource = Pick<SandboxInstance, 'findCompletedTurn' | 'session'>;
14
16
  /** Options for resolving one exact detached turn. */
@@ -17,6 +19,10 @@ export interface ReadCompletedSandboxTurnOptions {
17
19
  sessionId: string;
18
20
  log?: (message: string, meta?: Record<string, unknown>) => void;
19
21
  }
22
+ /** @internal Shared terminal-result decoder; callers must establish exact turn identity. */
23
+ export declare function usageFromResult(result: JsonRecord | undefined): ChatTurnUsage;
24
+ /** @internal Attribution travels with the same validated result as content and usage. */
25
+ export declare function attributionFromResult(result: Record<string, unknown> | undefined): Pick<ChatTurnModelAttribution, 'servedModel' | 'servedProvider' | 'servedSource'>;
20
26
  /**
21
27
  * Recover the durable content a Sandbox recorder attached to one assistant
22
28
  * message. The caller is responsible for proving that the message belongs to
@@ -28,5 +34,7 @@ export declare function recoverSandboxAssistantMessage(message: SessionMessage):
28
34
  * Read the exact completed turn from its keyed cache and completed message.
29
35
  * Never borrow a session-wide aggregate from a concurrently advancing session.
30
36
  * Observation failure is retryable and distinct from successful absent reads.
37
+ * Model attribution comes from that same identity-checked cache record, never
38
+ * from a second unchecked lookup that could belong to a different turn.
31
39
  */
32
- export declare function readCompletedSandboxTurn(box: CompletedSandboxTurnSource, options: ReadCompletedSandboxTurnOptions): Promise<DetachedTurnFinal | null>;
40
+ export declare function readCompletedSandboxTurn(box: CompletedSandboxTurnSource, options: ReadCompletedSandboxTurnOptions): Promise<(DetachedTurnFinal & Pick<ChatTurnModelAttribution, 'servedModel' | 'servedProvider' | 'servedSource'>) | null>;
@@ -105,13 +105,6 @@ export interface DetachedTurnOptions {
105
105
  * `readCompletedSandboxTurn` so the exact completed session message
106
106
  * restores tool/file parts as well as text. */
107
107
  completedResult?: () => Promise<DetachedTurnFinal | null | undefined>;
108
- /** Clear the prior partial buffer for `turnId` before a genuine re-stream.
109
- * A crash mid-run leaves buffered rows at seqs 1..N with status `running`;
110
- * re-streaming restarts the tap's seq at 0 and would duplicate/interleave
111
- * rows. Wire this (delete `turnId`'s buffered events) so a retry is clean.
112
- * A re-stream over an existing `running` buffer requires this operation to
113
- * succeed. Missing or failed reset leaves the existing stream untouched. */
114
- resetBuffer?: (turnId: string) => Promise<void>;
115
108
  /** Own the durable assistant row for this turn instead of returning the body
116
109
  * for the caller to insert — and keep it in step with the stream.
117
110
  *
@@ -188,8 +181,9 @@ export interface DetachedTurnResult {
188
181
  * re-streaming (a second event sequence would collide with the buffered one).
189
182
  * - Crash-safe: a `running` turn (a prior attempt crashed mid-tap) consults
190
183
  * `completedResult` to detect a run that finished server-side; only a run that
191
- * genuinely did not complete is re-streamed, and then over a `resetBuffer`-
192
- * cleared buffer so seqs don't corrupt.
184
+ * genuinely did not complete is re-streamed, and then over a buffer the
185
+ * store's `resetEvents` cleared so seqs don't corrupt. A store without
186
+ * `resetEvents` refuses that re-stream and leaves the existing buffer intact.
193
187
  * - Marks the turn `running` under `scopeId` so a mid-run browser finds it.
194
188
  * - Settles `complete`/`error` so the client stops tailing and billing/render
195
189
  * can branch on `state`.
@@ -17,8 +17,9 @@ export * from './protected-runtime-producer';
17
17
  export * from './model-failover-stream';
18
18
  export * from './draft-persistence';
19
19
  export * from './detached-turn';
20
- export * from './completed-sandbox-turn';
20
+ export { type CompletedSandboxTurnSource, type ReadCompletedSandboxTurnOptions, readCompletedSandboxTurn, recoverSandboxAssistantMessage, } from './completed-sandbox-turn';
21
21
  export * from './native-completion';
22
+ export * from './plan-follow-up';
22
23
  export * from './durable-projection';
23
24
  export * from './upload';
24
25
  export * from './file-index';
@@ -64,7 +64,7 @@ import {
64
64
  rowIdOf,
65
65
  storeSupportsDraftPersistence,
66
66
  streamChatRouteAsSandboxEvents
67
- } from "../chunk-RSTPXLC3.js";
67
+ } from "../chunk-3LOTQCW7.js";
68
68
  import "../chunk-6VRVRWYN.js";
69
69
  import "../chunk-YNSPVKMS.js";
70
70
  import "../chunk-3NCPXNBZ.js";
@@ -72,7 +72,7 @@ import {
72
72
  attachmentInputToPart,
73
73
  attachmentKindForMime,
74
74
  toChatMessageParts
75
- } from "../chunk-V4JZ5OYC.js";
75
+ } from "../chunk-HTAFI247.js";
76
76
  import "../chunk-ZVEEWGDK.js";
77
77
  import {
78
78
  ChatTurnInputError,
@@ -111,7 +111,7 @@ import {
111
111
  normalizePersistedPart,
112
112
  normalizeToolEvent,
113
113
  terminalizeDanglingAssistantToolUpdates
114
- } from "../chunk-UII4YDYS.js";
114
+ } from "../chunk-N56FWDSP.js";
115
115
  import {
116
116
  cancelStatusFor,
117
117
  interactionPartKey,
@@ -124,12 +124,14 @@ import {
124
124
  } from "../chunk-FCON65I2.js";
125
125
  import {
126
126
  parsePlanSubmittedEvent,
127
+ persistedPartToPlan,
128
+ planFollowUpTurnId,
127
129
  planToPersistedPart
128
- } from "../chunk-YJMCRXQQ.js";
130
+ } from "../chunk-LQYIBL3G.js";
129
131
  import {
130
132
  coalesceDeltas,
131
133
  createBufferedTurnTap
132
- } from "../chunk-HXTJXODG.js";
134
+ } from "../chunk-GBOHTAQH.js";
133
135
 
134
136
  // src/chat-routes/model-failover-stream.ts
135
137
  var TERMINAL_FAILURE_TYPES = /* @__PURE__ */ new Set(["error", "session.run.failed"]);
@@ -1390,12 +1392,12 @@ async function runDetachedTurn(opts) {
1390
1392
  const settleRow = async (base, cachedPersisted) => {
1391
1393
  const persisted = cachedPersisted ?? (!producer ? await persistedRow() : void 0);
1392
1394
  const info = producer?.modelFailover?.();
1393
- const attribution2 = producer?.modelAttribution?.();
1395
+ const attribution = producer?.modelAttribution?.();
1394
1396
  const model = producer?.model ?? persisted?.model ?? opts.model;
1395
- const requestedModel = attribution2?.requestedModel ?? persisted?.requestedModel ?? opts.model;
1396
- const servedModel = attribution2?.servedModel ?? persisted?.servedModel;
1397
- const servedProvider = attribution2?.servedProvider ?? persisted?.servedProvider;
1398
- const servedSource = attribution2?.servedSource ?? (persisted?.servedSource === "request" || persisted?.servedSource === "environment" || persisted?.servedSource === "profile" ? persisted.servedSource : void 0);
1397
+ const requestedModel = attribution?.requestedModel ?? persisted?.requestedModel ?? opts.model;
1398
+ const servedModel = attribution?.servedModel ?? persisted?.servedModel;
1399
+ const servedProvider = attribution?.servedProvider ?? persisted?.servedProvider;
1400
+ const servedSource = attribution?.servedSource ?? (persisted?.servedSource === "request" || persisted?.servedSource === "environment" || persisted?.servedSource === "profile" ? persisted.servedSource : void 0);
1399
1401
  const result = {
1400
1402
  ...base,
1401
1403
  ...model ? { model } : {},
@@ -1455,10 +1457,10 @@ async function runDetachedTurn(opts) {
1455
1457
  const persisted = await persistedRow();
1456
1458
  return await settleRow(cachedResultFrom(final, persisted), persisted);
1457
1459
  }
1458
- if (!opts.resetBuffer) {
1459
- throw new Error("Detached turn recovery requires resetBuffer before replaying an existing stream");
1460
+ if (!store.resetEvents) {
1461
+ throw new Error("Detached turn recovery requires a TurnEventStore with resetEvents before replaying an existing stream");
1460
1462
  }
1461
- await opts.resetBuffer(turnId);
1463
+ await store.resetEvents(turnId);
1462
1464
  }
1463
1465
  const tap = createBufferedTurnTap({
1464
1466
  store,
@@ -1556,6 +1558,23 @@ function usageFromResult(result) {
1556
1558
  ...costUsd !== void 0 ? { costUsd } : {}
1557
1559
  };
1558
1560
  }
1561
+ function nonEmptyString(value) {
1562
+ return typeof value === "string" && value.trim() ? value : void 0;
1563
+ }
1564
+ function attributionFromResult(result) {
1565
+ const metadata = asRecord(result?.metadata);
1566
+ const modelAttribution = asRecord(result?.modelAttribution) ?? asRecord(metadata?.modelAttribution);
1567
+ const backend = asRecord(result?.effectiveBackend) ?? asRecord(metadata?.effectiveBackend);
1568
+ const source = nonEmptyString(result?.servedSource) ?? nonEmptyString(modelAttribution?.servedSource) ?? nonEmptyString(backend?.source);
1569
+ const servedSource = source === "request" || source === "environment" || source === "profile" ? source : void 0;
1570
+ const servedModel = nonEmptyString(result?.servedModel) ?? nonEmptyString(modelAttribution?.servedModel) ?? nonEmptyString(backend?.model);
1571
+ const servedProvider = nonEmptyString(result?.servedProvider) ?? nonEmptyString(modelAttribution?.servedProvider) ?? nonEmptyString(backend?.provider);
1572
+ return {
1573
+ ...servedModel ? { servedModel } : {},
1574
+ ...servedProvider ? { servedProvider } : {},
1575
+ ...servedSource ? { servedSource } : {}
1576
+ };
1577
+ }
1559
1578
  function textFromResult(result) {
1560
1579
  return asString(result?.response) ?? asString(result?.finalText) ?? asString(result?.text) ?? asString(result?.output);
1561
1580
  }
@@ -1664,7 +1683,8 @@ async function readCompletedSandboxTurn(box, options) {
1664
1683
  return {
1665
1684
  ...text !== void 0 ? { text } : {},
1666
1685
  ...hasUsage2(usage) ? { usage } : {},
1667
- ...parts ? { parts } : {}
1686
+ ...parts ? { parts } : {},
1687
+ ...attributionFromResult(result)
1668
1688
  };
1669
1689
  }
1670
1690
 
@@ -1675,9 +1695,6 @@ function timestamp(value) {
1675
1695
  if (value instanceof Date) return value.getTime();
1676
1696
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1677
1697
  }
1678
- function nonEmptyString(value) {
1679
- return typeof value === "string" && value.trim() ? value : void 0;
1680
- }
1681
1698
  function record(value) {
1682
1699
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1683
1700
  }
@@ -1685,39 +1702,11 @@ function isSandboxNotFoundError(value) {
1685
1702
  const error = record(value);
1686
1703
  return error?.name === "NotFoundError" || error?.code === "NOT_FOUND" || error?.status === 404;
1687
1704
  }
1688
- function attribution(result) {
1689
- const metadata = record(result?.metadata);
1690
- const modelAttribution = record(result?.modelAttribution) ?? record(metadata?.modelAttribution);
1691
- const backend = record(result?.effectiveBackend) ?? record(metadata?.effectiveBackend);
1692
- const source = nonEmptyString(result?.servedSource) ?? nonEmptyString(modelAttribution?.servedSource) ?? nonEmptyString(backend?.source);
1693
- const servedSource = source === "request" || source === "environment" || source === "profile" ? source : void 0;
1694
- const servedModel = nonEmptyString(result?.servedModel) ?? nonEmptyString(modelAttribution?.servedModel) ?? nonEmptyString(backend?.model);
1695
- const servedProvider = nonEmptyString(result?.servedProvider) ?? nonEmptyString(modelAttribution?.servedProvider) ?? nonEmptyString(backend?.provider);
1696
- return {
1697
- ...servedModel ? { servedModel } : {},
1698
- ...servedProvider ? { servedProvider } : {},
1699
- ...servedSource ? { servedSource } : {}
1700
- };
1701
- }
1702
- function usageFromResult2(result) {
1703
- const raw = record(result?.usage) ?? record(result?.tokenUsage);
1704
- const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1705
- return {
1706
- ...number(raw?.inputTokens) !== void 0 ? { inputTokens: number(raw?.inputTokens) } : {},
1707
- ...number(raw?.outputTokens) !== void 0 ? { outputTokens: number(raw?.outputTokens) } : {},
1708
- ...number(raw?.cacheReadTokens) !== void 0 ? { cacheReadTokens: number(raw?.cacheReadTokens) } : {},
1709
- ...number(raw?.cacheWriteTokens) !== void 0 ? { cacheWriteTokens: number(raw?.cacheWriteTokens) } : {},
1710
- ...number(result?.costUsd) !== void 0 ? { costUsd: number(result?.costUsd) } : {}
1711
- };
1712
- }
1713
1705
  function interruptedMessages(messages, turnId) {
1714
1706
  return messages.filter(
1715
1707
  (message) => message.role === "assistant" && message.metadata?.turnId === turnId && (message.metadata.interrupted === true || message.metadata.status === "interrupted")
1716
1708
  );
1717
1709
  }
1718
- function mergeUsage(messageUsage, resultUsage) {
1719
- return { ...messageUsage, ...resultUsage };
1720
- }
1721
1710
  function consistent(values) {
1722
1711
  if (values.length === 0 || values.some((value) => value === void 0)) return void 0;
1723
1712
  const first = values[0];
@@ -1805,7 +1794,7 @@ async function observeNativeCompletion(options) {
1805
1794
  return { state: "running" };
1806
1795
  }
1807
1796
  if (admittedTurnIds.some((turnId) => runsByTurnId.get(turnId)?.status === "active")) return { state: "running" };
1808
- const messages = await exactSession.messages({ limit: 1e3 });
1797
+ let messages;
1809
1798
  const recovered = [];
1810
1799
  for (const turnId of admittedTurnIds) {
1811
1800
  const run = runsByTurnId.get(turnId);
@@ -1814,19 +1803,18 @@ async function observeNativeCompletion(options) {
1814
1803
  continue;
1815
1804
  }
1816
1805
  const completed = run.status === "completed" ? await readCompletedSandboxTurn(source, { turnId, sessionId: options.sessionId }) : null;
1817
- const cached = run.status === "completed" ? await source.findCompletedTurn(turnId, { sessionId: options.sessionId }) : null;
1818
1806
  if (run.status === "completed" && completed) {
1819
1807
  recovered.push({
1808
+ ...completed,
1820
1809
  turnId,
1821
1810
  state: "completed",
1822
1811
  text: completed.text ?? "",
1823
1812
  parts: completed.parts ?? [],
1824
- usage: completed.usage ?? {},
1825
- ...attribution(cached?.result)
1813
+ usage: completed.usage ?? {}
1826
1814
  });
1827
1815
  continue;
1828
1816
  }
1829
- const interrupted = interruptedMessages(messages, turnId);
1817
+ const interrupted = run.status === "failed" || run.status === "cancelled" ? interruptedMessages(messages ??= await exactSession.messages({ limit: 1e3 }), turnId) : [];
1830
1818
  if ((run.status === "failed" || run.status === "cancelled") && interrupted.length === 1) {
1831
1819
  const message = recoverSandboxAssistantMessage(interrupted[0]);
1832
1820
  const result = await exactSession.result({ executionId: turnId });
@@ -1835,11 +1823,8 @@ async function observeNativeCompletion(options) {
1835
1823
  state: "failed",
1836
1824
  text: message.text ?? result.response ?? "",
1837
1825
  parts: message.parts ?? [],
1838
- usage: mergeUsage(message.usage ?? {}, {
1839
- ...usageFromResult2(result),
1840
- ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : {}
1841
- }),
1842
- ...attribution(result),
1826
+ usage: { ...message.usage, ...usageFromResult(result) },
1827
+ ...attributionFromResult(result),
1843
1828
  error: result.error ?? interrupted[0].metadata?.interruptReason ?? status.failureReason?.message
1844
1829
  });
1845
1830
  continue;
@@ -1855,6 +1840,166 @@ async function observeNativeCompletion(options) {
1855
1840
  return receipt.state === "completed" ? { state: "completed", receipt } : { state: "failed", receipt };
1856
1841
  }
1857
1842
 
1843
+ // src/chat-routes/plan-follow-up.ts
1844
+ import { createHash, randomUUID } from "crypto";
1845
+ var PLAN_FOLLOW_UP_STALE_AFTER_MS = 60 * 60 * 1e3;
1846
+ var PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS = 12e4;
1847
+ var TERMINAL_SESSION_EVENT_TYPES = /* @__PURE__ */ new Set(["done", "error", "result"]);
1848
+ function planFollowUpExecutionId(sessionId, turnId) {
1849
+ return `plan-followup-${createHash("sha256").update(`${sessionId}\0${turnId}`).digest("hex")}`;
1850
+ }
1851
+ function parsePlanFollowUpAttach(value) {
1852
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1853
+ const record2 = value;
1854
+ const planId = typeof record2.planId === "string" ? record2.planId.trim() : "";
1855
+ const turnId = typeof record2.turnId === "string" ? record2.turnId.trim() : "";
1856
+ const revision = record2.revision;
1857
+ const outcome = record2.outcome;
1858
+ if (!planId || !turnId || outcome !== "approved" && outcome !== "rejected") return null;
1859
+ if (typeof revision !== "number" || !Number.isInteger(revision) || revision < 1) return null;
1860
+ if (turnId !== planFollowUpTurnId(planId, revision, outcome)) return null;
1861
+ return { planId, revision, outcome, turnId };
1862
+ }
1863
+ function resolvePlanFollowUpRequest(input) {
1864
+ const attach = parsePlanFollowUpAttach(input.planFollowUp);
1865
+ if (!attach) {
1866
+ return { ok: false, status: 400, code: "invalid_plan_follow_up", error: "Invalid planFollowUp descriptor" };
1867
+ }
1868
+ const plan = input.messages.filter((message) => message.role === "assistant" && Array.isArray(message.parts)).flatMap((message) => message.parts).map((part) => part && typeof part === "object" && !Array.isArray(part) ? persistedPartToPlan(part) : null).find((candidate) => candidate?.planId === attach.planId && candidate.revision === attach.revision);
1869
+ if (!plan) {
1870
+ return {
1871
+ ok: false,
1872
+ status: 409,
1873
+ code: "plan_follow_up_missing",
1874
+ error: `Plan ${attach.planId} revision ${attach.revision} is not in this session`
1875
+ };
1876
+ }
1877
+ if (plan.status !== attach.outcome) {
1878
+ return {
1879
+ ok: false,
1880
+ status: 409,
1881
+ code: "plan_follow_up_not_decided",
1882
+ error: `Plan ${attach.planId} is ${plan.status}, not ${attach.outcome}`
1883
+ };
1884
+ }
1885
+ return { ok: true, attach, executionId: planFollowUpExecutionId(input.sessionId, attach.turnId) };
1886
+ }
1887
+ function unwrapSessionEventPayload(event) {
1888
+ const data = event.data && typeof event.data === "object" && !Array.isArray(event.data) ? event.data : void 0;
1889
+ const properties = data?.properties && typeof data.properties === "object" && !Array.isArray(data.properties) ? data.properties : void 0;
1890
+ return properties ? { ...event, data: properties } : event;
1891
+ }
1892
+ async function* streamPlanFollowUpEvents(box, sessionId, executionId, options = {}) {
1893
+ const timeoutMs = options.timeoutMs ?? PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS;
1894
+ const abort = new AbortController();
1895
+ const iterator = box.session(sessionId).events({
1896
+ executionId,
1897
+ since: "0",
1898
+ signal: abort.signal
1899
+ })[Symbol.asyncIterator]();
1900
+ let timeout;
1901
+ let sawTerminalEvent = false;
1902
+ const track = (event) => {
1903
+ if (TERMINAL_SESSION_EVENT_TYPES.has(String(event.type ?? ""))) sawTerminalEvent = true;
1904
+ return unwrapSessionEventPayload(event);
1905
+ };
1906
+ try {
1907
+ const first = await Promise.race([
1908
+ iterator.next(),
1909
+ new Promise((_, reject) => {
1910
+ timeout = setTimeout(
1911
+ () => reject(new Error(`Plan follow-up ${executionId} did not start within ${Math.round(timeoutMs / 1e3)} seconds`)),
1912
+ timeoutMs
1913
+ );
1914
+ })
1915
+ ]);
1916
+ if (timeout) clearTimeout(timeout);
1917
+ if (first.done) throw new Error(`Plan follow-up ${executionId} ended before emitting an event`);
1918
+ yield track(first.value);
1919
+ while (true) {
1920
+ const next = await iterator.next();
1921
+ if (next.done) {
1922
+ if (!sawTerminalEvent) {
1923
+ throw new Error(`Plan follow-up ${executionId} stream ended without a terminal event`);
1924
+ }
1925
+ return;
1926
+ }
1927
+ yield track(next.value);
1928
+ }
1929
+ } finally {
1930
+ if (timeout) clearTimeout(timeout);
1931
+ abort.abort();
1932
+ await iterator.return?.(void 0);
1933
+ }
1934
+ }
1935
+ function createD1PlanFollowUpGate(db, options = {}) {
1936
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1937
+ const createLease = options.createLease ?? randomUUID;
1938
+ const staleAfterMs = options.staleAfterMs ?? PLAN_FOLLOW_UP_STALE_AFTER_MS;
1939
+ const readStatus = (executionId) => db.prepare(`
1940
+ SELECT status, leaseToken
1941
+ FROM turn_status
1942
+ WHERE turnId = ?
1943
+ LIMIT 1
1944
+ `).bind(executionId);
1945
+ async function readAfterBatch(write, executionId, operation) {
1946
+ const results = await db.batch([write, readStatus(executionId)]);
1947
+ const rows = results[1]?.results;
1948
+ const row = rows?.[0];
1949
+ if (!row || typeof row.status !== "string") {
1950
+ throw new Error(`Plan follow-up ${executionId} has no status after ${operation}`);
1951
+ }
1952
+ if (row.leaseToken !== null && row.leaseToken !== void 0 && typeof row.leaseToken !== "string") {
1953
+ throw new Error(`Plan follow-up ${executionId} has an invalid lease after ${operation}`);
1954
+ }
1955
+ return { status: row.status, leaseToken: row.leaseToken ?? null };
1956
+ }
1957
+ async function settle(executionId, scopeId, lease, status) {
1958
+ const row = await readAfterBatch(
1959
+ db.prepare(`
1960
+ UPDATE turn_status
1961
+ SET status = ?, scopeId = ?, updatedAt = ?
1962
+ WHERE turnId = ? AND status = 'running' AND leaseToken = ?
1963
+ `).bind(status, scopeId, now().toISOString(), executionId, lease),
1964
+ executionId,
1965
+ `settling ${status}`
1966
+ );
1967
+ if (row.leaseToken !== lease) return { settled: false, reason: "lease_lost" };
1968
+ if (row.status !== status) {
1969
+ throw new Error(`Plan follow-up ${executionId} remained ${row.status} while settling ${status}`);
1970
+ }
1971
+ return { settled: true };
1972
+ }
1973
+ return {
1974
+ async admit(executionId, scopeId) {
1975
+ const claimedAt = now();
1976
+ const lease = createLease();
1977
+ const staleBefore = new Date(claimedAt.getTime() - staleAfterMs).toISOString();
1978
+ const row = await readAfterBatch(
1979
+ db.prepare(`
1980
+ INSERT INTO turn_status (turnId, status, scopeId, updatedAt, leaseToken)
1981
+ VALUES (?, 'running', ?, ?, ?)
1982
+ ON CONFLICT(turnId) DO UPDATE SET
1983
+ status = 'running',
1984
+ scopeId = excluded.scopeId,
1985
+ updatedAt = excluded.updatedAt,
1986
+ leaseToken = excluded.leaseToken
1987
+ WHERE turn_status.status = 'error'
1988
+ OR (turn_status.status = 'running' AND turn_status.updatedAt < ?)
1989
+ `).bind(executionId, scopeId, claimedAt.toISOString(), lease, staleBefore),
1990
+ executionId,
1991
+ "admission"
1992
+ );
1993
+ if (row.status === "running" && row.leaseToken === lease) return { admitted: true, lease };
1994
+ if (row.status === "running") return { admitted: false, reason: "in_flight" };
1995
+ if (row.status === "complete") return { admitted: false, reason: "completed" };
1996
+ throw new Error(`Plan follow-up ${executionId} has unexpected admission status: ${row.status}`);
1997
+ },
1998
+ settle: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, "complete"),
1999
+ abandon: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, "error")
2000
+ };
2001
+ }
2002
+
1858
2003
  // src/chat-routes/durable-projection.ts
1859
2004
  function errorMessage(error) {
1860
2005
  return error instanceof Error ? error.message : String(error);
@@ -3161,6 +3306,7 @@ export {
3161
3306
  createAtomicAttachmentWriter,
3162
3307
  createAttachmentUploadRoute,
3163
3308
  createChatTurnRoutes,
3309
+ createD1PlanFollowUpGate,
3164
3310
  createProtectedRuntimeChatProducer,
3165
3311
  createSandboxChatProducer,
3166
3312
  createSandboxFileIndexRoute,
@@ -3179,6 +3325,8 @@ export {
3179
3325
  observeNativeCompletion,
3180
3326
  parseChatTurnParts,
3181
3327
  parseFileMentions,
3328
+ parsePlanFollowUpAttach,
3329
+ planFollowUpExecutionId,
3182
3330
  produceChatTurnWithIntelligence,
3183
3331
  promoteAgentFilePart,
3184
3332
  promptPartsByteSize,
@@ -3187,6 +3335,7 @@ export {
3187
3335
  recoverSandboxAssistantMessage,
3188
3336
  resolveChatAttachments,
3189
3337
  resolveEmptyTurnRetries,
3338
+ resolvePlanFollowUpRequest,
3190
3339
  rowIdOf,
3191
3340
  runDetachedTurn,
3192
3341
  sanitizeAttachmentFileName,
@@ -3195,8 +3344,10 @@ export {
3195
3344
  sniffMimeFromName,
3196
3345
  storeSupportsDraftPersistence,
3197
3346
  streamChatRouteAsSandboxEvents,
3347
+ streamPlanFollowUpEvents,
3198
3348
  streamWithModelFailover,
3199
3349
  summarizeFailoverReason,
3350
+ unwrapSessionEventPayload,
3200
3351
  validateSandboxMentionPath,
3201
3352
  withDurableChatProjection
3202
3353
  };