@tangle-network/agent-app 0.55.6 → 0.56.0

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 (36) hide show
  1. package/dist/assistant/index.js +4 -4
  2. package/dist/chat-routes/detached-turn.d.ts +3 -9
  3. package/dist/chat-routes/index.d.ts +1 -0
  4. package/dist/chat-routes/index.js +177 -9
  5. package/dist/chat-routes/index.js.map +1 -1
  6. package/dist/chat-routes/plan-follow-up.d.ts +108 -0
  7. package/dist/chat-store/index.js +3 -3
  8. package/dist/{chunk-RSTPXLC3.js → chunk-3LOTQCW7.js} +3 -3
  9. package/dist/{chunk-OXDA7G4E.js → chunk-73WE4UQG.js} +21 -5
  10. package/dist/chunk-73WE4UQG.js.map +1 -0
  11. package/dist/{chunk-HXTJXODG.js → chunk-GBOHTAQH.js} +11 -2
  12. package/dist/chunk-GBOHTAQH.js.map +1 -0
  13. package/dist/{chunk-V4JZ5OYC.js → chunk-HTAFI247.js} +2 -2
  14. package/dist/{chunk-YJMCRXQQ.js → chunk-LQYIBL3G.js} +3 -3
  15. package/dist/{chunk-YJMCRXQQ.js.map → chunk-LQYIBL3G.js.map} +1 -1
  16. package/dist/{chunk-UII4YDYS.js → chunk-N56FWDSP.js} +2 -2
  17. package/dist/{chunk-2HEFK764.js → chunk-TNDBW5XG.js} +3 -3
  18. package/dist/peer-floors/cli.js +123 -3
  19. package/dist/peer-floors/cli.js.map +1 -1
  20. package/dist/peer-floors/durability-owners.d.ts +23 -0
  21. package/dist/plans/index.d.ts +6 -2
  22. package/dist/plans/index.js +1 -1
  23. package/dist/public-consultation/index.js +5 -5
  24. package/dist/sandbox/index.d.ts +1 -0
  25. package/dist/sandbox/index.js +1 -1
  26. package/dist/stream/index.js +5 -3
  27. package/dist/stream/turn-buffer.d.ts +8 -1
  28. package/dist/turn-stream/index.js +1 -1
  29. package/dist/web-react/index.js +4 -4
  30. package/package.json +1 -1
  31. package/dist/chunk-HXTJXODG.js.map +0 -1
  32. package/dist/chunk-OXDA7G4E.js.map +0 -1
  33. /package/dist/{chunk-RSTPXLC3.js.map → chunk-3LOTQCW7.js.map} +0 -0
  34. /package/dist/{chunk-V4JZ5OYC.js.map → chunk-HTAFI247.js.map} +0 -0
  35. /package/dist/{chunk-UII4YDYS.js.map → chunk-N56FWDSP.js.map} +0 -0
  36. /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 {
@@ -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`.
@@ -19,6 +19,7 @@ export * from './draft-persistence';
19
19
  export * from './detached-turn';
20
20
  export * 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';
@@ -42,7 +42,7 @@ import {
42
42
  flattenHistory,
43
43
  readSandboxBinaryBytes,
44
44
  statSandboxFileSize
45
- } from "../chunk-OXDA7G4E.js";
45
+ } from "../chunk-73WE4UQG.js";
46
46
  import "../chunk-MCYJON3F.js";
47
47
  import "../chunk-LWSJK546.js";
48
48
  import "../chunk-7YLSF33A.js";
@@ -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"]);
@@ -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,
@@ -1855,6 +1857,166 @@ async function observeNativeCompletion(options) {
1855
1857
  return receipt.state === "completed" ? { state: "completed", receipt } : { state: "failed", receipt };
1856
1858
  }
1857
1859
 
1860
+ // src/chat-routes/plan-follow-up.ts
1861
+ import { createHash, randomUUID } from "crypto";
1862
+ var PLAN_FOLLOW_UP_STALE_AFTER_MS = 60 * 60 * 1e3;
1863
+ var PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS = 12e4;
1864
+ var TERMINAL_SESSION_EVENT_TYPES = /* @__PURE__ */ new Set(["done", "error", "result"]);
1865
+ function planFollowUpExecutionId(sessionId, turnId) {
1866
+ return `plan-followup-${createHash("sha256").update(`${sessionId}\0${turnId}`).digest("hex")}`;
1867
+ }
1868
+ function parsePlanFollowUpAttach(value) {
1869
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1870
+ const record2 = value;
1871
+ const planId = typeof record2.planId === "string" ? record2.planId.trim() : "";
1872
+ const turnId = typeof record2.turnId === "string" ? record2.turnId.trim() : "";
1873
+ const revision = record2.revision;
1874
+ const outcome = record2.outcome;
1875
+ if (!planId || !turnId || outcome !== "approved" && outcome !== "rejected") return null;
1876
+ if (typeof revision !== "number" || !Number.isInteger(revision) || revision < 1) return null;
1877
+ if (turnId !== planFollowUpTurnId(planId, revision, outcome)) return null;
1878
+ return { planId, revision, outcome, turnId };
1879
+ }
1880
+ function resolvePlanFollowUpRequest(input) {
1881
+ const attach = parsePlanFollowUpAttach(input.planFollowUp);
1882
+ if (!attach) {
1883
+ return { ok: false, status: 400, code: "invalid_plan_follow_up", error: "Invalid planFollowUp descriptor" };
1884
+ }
1885
+ 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);
1886
+ if (!plan) {
1887
+ return {
1888
+ ok: false,
1889
+ status: 409,
1890
+ code: "plan_follow_up_missing",
1891
+ error: `Plan ${attach.planId} revision ${attach.revision} is not in this session`
1892
+ };
1893
+ }
1894
+ if (plan.status !== attach.outcome) {
1895
+ return {
1896
+ ok: false,
1897
+ status: 409,
1898
+ code: "plan_follow_up_not_decided",
1899
+ error: `Plan ${attach.planId} is ${plan.status}, not ${attach.outcome}`
1900
+ };
1901
+ }
1902
+ return { ok: true, attach, executionId: planFollowUpExecutionId(input.sessionId, attach.turnId) };
1903
+ }
1904
+ function unwrapSessionEventPayload(event) {
1905
+ const data = event.data && typeof event.data === "object" && !Array.isArray(event.data) ? event.data : void 0;
1906
+ const properties = data?.properties && typeof data.properties === "object" && !Array.isArray(data.properties) ? data.properties : void 0;
1907
+ return properties ? { ...event, data: properties } : event;
1908
+ }
1909
+ async function* streamPlanFollowUpEvents(box, sessionId, executionId, options = {}) {
1910
+ const timeoutMs = options.timeoutMs ?? PLAN_FOLLOW_UP_ATTACH_TIMEOUT_MS;
1911
+ const abort = new AbortController();
1912
+ const iterator = box.session(sessionId).events({
1913
+ executionId,
1914
+ since: "0",
1915
+ signal: abort.signal
1916
+ })[Symbol.asyncIterator]();
1917
+ let timeout;
1918
+ let sawTerminalEvent = false;
1919
+ const track = (event) => {
1920
+ if (TERMINAL_SESSION_EVENT_TYPES.has(String(event.type ?? ""))) sawTerminalEvent = true;
1921
+ return unwrapSessionEventPayload(event);
1922
+ };
1923
+ try {
1924
+ const first = await Promise.race([
1925
+ iterator.next(),
1926
+ new Promise((_, reject) => {
1927
+ timeout = setTimeout(
1928
+ () => reject(new Error(`Plan follow-up ${executionId} did not start within ${Math.round(timeoutMs / 1e3)} seconds`)),
1929
+ timeoutMs
1930
+ );
1931
+ })
1932
+ ]);
1933
+ if (timeout) clearTimeout(timeout);
1934
+ if (first.done) throw new Error(`Plan follow-up ${executionId} ended before emitting an event`);
1935
+ yield track(first.value);
1936
+ while (true) {
1937
+ const next = await iterator.next();
1938
+ if (next.done) {
1939
+ if (!sawTerminalEvent) {
1940
+ throw new Error(`Plan follow-up ${executionId} stream ended without a terminal event`);
1941
+ }
1942
+ return;
1943
+ }
1944
+ yield track(next.value);
1945
+ }
1946
+ } finally {
1947
+ if (timeout) clearTimeout(timeout);
1948
+ abort.abort();
1949
+ await iterator.return?.(void 0);
1950
+ }
1951
+ }
1952
+ function createD1PlanFollowUpGate(db, options = {}) {
1953
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1954
+ const createLease = options.createLease ?? randomUUID;
1955
+ const staleAfterMs = options.staleAfterMs ?? PLAN_FOLLOW_UP_STALE_AFTER_MS;
1956
+ const readStatus = (executionId) => db.prepare(`
1957
+ SELECT status, leaseToken
1958
+ FROM turn_status
1959
+ WHERE turnId = ?
1960
+ LIMIT 1
1961
+ `).bind(executionId);
1962
+ async function readAfterBatch(write, executionId, operation) {
1963
+ const results = await db.batch([write, readStatus(executionId)]);
1964
+ const rows = results[1]?.results;
1965
+ const row = rows?.[0];
1966
+ if (!row || typeof row.status !== "string") {
1967
+ throw new Error(`Plan follow-up ${executionId} has no status after ${operation}`);
1968
+ }
1969
+ if (row.leaseToken !== null && row.leaseToken !== void 0 && typeof row.leaseToken !== "string") {
1970
+ throw new Error(`Plan follow-up ${executionId} has an invalid lease after ${operation}`);
1971
+ }
1972
+ return { status: row.status, leaseToken: row.leaseToken ?? null };
1973
+ }
1974
+ async function settle(executionId, scopeId, lease, status) {
1975
+ const row = await readAfterBatch(
1976
+ db.prepare(`
1977
+ UPDATE turn_status
1978
+ SET status = ?, scopeId = ?, updatedAt = ?
1979
+ WHERE turnId = ? AND status = 'running' AND leaseToken = ?
1980
+ `).bind(status, scopeId, now().toISOString(), executionId, lease),
1981
+ executionId,
1982
+ `settling ${status}`
1983
+ );
1984
+ if (row.leaseToken !== lease) return { settled: false, reason: "lease_lost" };
1985
+ if (row.status !== status) {
1986
+ throw new Error(`Plan follow-up ${executionId} remained ${row.status} while settling ${status}`);
1987
+ }
1988
+ return { settled: true };
1989
+ }
1990
+ return {
1991
+ async admit(executionId, scopeId) {
1992
+ const claimedAt = now();
1993
+ const lease = createLease();
1994
+ const staleBefore = new Date(claimedAt.getTime() - staleAfterMs).toISOString();
1995
+ const row = await readAfterBatch(
1996
+ db.prepare(`
1997
+ INSERT INTO turn_status (turnId, status, scopeId, updatedAt, leaseToken)
1998
+ VALUES (?, 'running', ?, ?, ?)
1999
+ ON CONFLICT(turnId) DO UPDATE SET
2000
+ status = 'running',
2001
+ scopeId = excluded.scopeId,
2002
+ updatedAt = excluded.updatedAt,
2003
+ leaseToken = excluded.leaseToken
2004
+ WHERE turn_status.status = 'error'
2005
+ OR (turn_status.status = 'running' AND turn_status.updatedAt < ?)
2006
+ `).bind(executionId, scopeId, claimedAt.toISOString(), lease, staleBefore),
2007
+ executionId,
2008
+ "admission"
2009
+ );
2010
+ if (row.status === "running" && row.leaseToken === lease) return { admitted: true, lease };
2011
+ if (row.status === "running") return { admitted: false, reason: "in_flight" };
2012
+ if (row.status === "complete") return { admitted: false, reason: "completed" };
2013
+ throw new Error(`Plan follow-up ${executionId} has unexpected admission status: ${row.status}`);
2014
+ },
2015
+ settle: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, "complete"),
2016
+ abandon: (executionId, scopeId, lease) => settle(executionId, scopeId, lease, "error")
2017
+ };
2018
+ }
2019
+
1858
2020
  // src/chat-routes/durable-projection.ts
1859
2021
  function errorMessage(error) {
1860
2022
  return error instanceof Error ? error.message : String(error);
@@ -3161,6 +3323,7 @@ export {
3161
3323
  createAtomicAttachmentWriter,
3162
3324
  createAttachmentUploadRoute,
3163
3325
  createChatTurnRoutes,
3326
+ createD1PlanFollowUpGate,
3164
3327
  createProtectedRuntimeChatProducer,
3165
3328
  createSandboxChatProducer,
3166
3329
  createSandboxFileIndexRoute,
@@ -3179,6 +3342,8 @@ export {
3179
3342
  observeNativeCompletion,
3180
3343
  parseChatTurnParts,
3181
3344
  parseFileMentions,
3345
+ parsePlanFollowUpAttach,
3346
+ planFollowUpExecutionId,
3182
3347
  produceChatTurnWithIntelligence,
3183
3348
  promoteAgentFilePart,
3184
3349
  promptPartsByteSize,
@@ -3187,6 +3352,7 @@ export {
3187
3352
  recoverSandboxAssistantMessage,
3188
3353
  resolveChatAttachments,
3189
3354
  resolveEmptyTurnRetries,
3355
+ resolvePlanFollowUpRequest,
3190
3356
  rowIdOf,
3191
3357
  runDetachedTurn,
3192
3358
  sanitizeAttachmentFileName,
@@ -3195,8 +3361,10 @@ export {
3195
3361
  sniffMimeFromName,
3196
3362
  storeSupportsDraftPersistence,
3197
3363
  streamChatRouteAsSandboxEvents,
3364
+ streamPlanFollowUpEvents,
3198
3365
  streamWithModelFailover,
3199
3366
  summarizeFailoverReason,
3367
+ unwrapSessionEventPayload,
3200
3368
  validateSandboxMentionPath,
3201
3369
  withDurableChatProjection
3202
3370
  };