@tangle-network/agent-app 0.60.62 → 0.60.63
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/dist/app-auth/index.js +3 -3
- package/dist/assistant/index.js +7 -7
- package/dist/chat-routes/index.js +12 -12
- package/dist/chat-store/index.js +3 -3
- package/dist/chunk-5UQJ7F3P.js +41 -0
- package/dist/chunk-5UQJ7F3P.js.map +1 -0
- package/dist/{chunk-YXYQ6MJL.js → chunk-5V6VTO5Q.js} +65 -2
- package/dist/chunk-5V6VTO5Q.js.map +1 -0
- package/dist/chunk-J2O76TTS.js +458 -0
- package/dist/chunk-J2O76TTS.js.map +1 -0
- package/dist/{chunk-2YLSWZ5W.js → chunk-JBEFTXDO.js} +4 -4
- package/dist/{chunk-JGZ7WEPL.js → chunk-JC7YSRBR.js} +15 -1
- package/dist/chunk-JC7YSRBR.js.map +1 -0
- package/dist/{chunk-4WJREKXX.js → chunk-O3ZM5QPC.js} +6 -6
- package/dist/{chunk-FWLCPAST.js → chunk-SH56N4PV.js} +3 -3
- package/dist/{chunk-ZGUXI5SI.js → chunk-XNKLQG26.js} +5 -5
- package/dist/chunk-Y6LE5CAW.js +503 -0
- package/dist/chunk-Y6LE5CAW.js.map +1 -0
- package/dist/design-canvas-react/index.js +4 -4
- package/dist/launch-invariants/auth-lookup-cache.d.ts +57 -0
- package/dist/launch-invariants/catalog.d.ts +51 -0
- package/dist/launch-invariants/cli.d.ts +10 -0
- package/dist/launch-invariants/cli.js +88 -0
- package/dist/launch-invariants/cli.js.map +1 -0
- package/dist/launch-invariants/conformance.d.ts +49 -0
- package/dist/launch-invariants/index.d.ts +19 -0
- package/dist/launch-invariants/index.js +253 -0
- package/dist/launch-invariants/index.js.map +1 -0
- package/dist/launch-invariants/limit-alarms.d.ts +66 -0
- package/dist/launch-invariants/schedule.d.ts +114 -0
- package/dist/launch-invariants/settlement.d.ts +90 -0
- package/dist/launch-invariants/sized-reads.d.ts +50 -0
- package/dist/launch-invariants/testing.d.ts +175 -0
- package/dist/launch-invariants/testing.js +45 -0
- package/dist/launch-invariants/testing.js.map +1 -0
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +7 -7
- package/dist/stream/index.d.ts +1 -0
- package/dist/stream/index.js +9 -5
- package/dist/stream/orphaned-turns.d.ts +56 -0
- package/dist/stream/turn-buffer.d.ts +12 -0
- package/dist/teams/invitations-api.js +3 -3
- package/dist/turn-health/index.js +6 -17
- package/dist/turn-health/index.js.map +1 -1
- package/dist/turn-stream/index.js +1 -1
- package/dist/web-react/index.js +13 -13
- package/package.json +13 -2
- package/dist/chunk-JGZ7WEPL.js.map +0 -1
- package/dist/chunk-YXYQ6MJL.js.map +0 -1
- /package/dist/{chunk-2YLSWZ5W.js.map → chunk-JBEFTXDO.js.map} +0 -0
- /package/dist/{chunk-4WJREKXX.js.map → chunk-O3ZM5QPC.js.map} +0 -0
- /package/dist/{chunk-FWLCPAST.js.map → chunk-SH56N4PV.js.map} +0 -0
- /package/dist/{chunk-ZGUXI5SI.js.map → chunk-XNKLQG26.js.map} +0 -0
package/dist/app-auth/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
noticeEmail
|
|
3
|
-
} from "../chunk-WOTWQ2ST.js";
|
|
4
1
|
import {
|
|
5
2
|
createAuthGuard,
|
|
6
3
|
createBetterAuthSessionCookieMinter,
|
|
7
4
|
createTangleSsoHandlers
|
|
8
5
|
} from "../chunk-WN3UK23P.js";
|
|
6
|
+
import {
|
|
7
|
+
noticeEmail
|
|
8
|
+
} from "../chunk-WOTWQ2ST.js";
|
|
9
9
|
import "../chunk-D6UJEOZQ.js";
|
|
10
10
|
import "../chunk-UTAIRVOK.js";
|
|
11
11
|
import "../chunk-RN4WPTBH.js";
|
package/dist/assistant/index.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
chatToolCallPart
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-O3ZM5QPC.js";
|
|
4
4
|
import "../chunk-FAU5FIFD.js";
|
|
5
5
|
import "../chunk-3HUFJ5LO.js";
|
|
6
|
+
import "../chunk-KHCJKVQN.js";
|
|
7
|
+
import "../chunk-XEURJVS5.js";
|
|
8
|
+
import "../chunk-E4AY62T2.js";
|
|
6
9
|
import "../chunk-FBVLEGEG.js";
|
|
7
10
|
import "../chunk-Y6PRDUFJ.js";
|
|
8
11
|
import "../chunk-GEYACSFW.js";
|
|
@@ -10,13 +13,10 @@ import {
|
|
|
10
13
|
ChatComposer
|
|
11
14
|
} from "../chunk-GNA5I5NM.js";
|
|
12
15
|
import "../chunk-L7MB2LLM.js";
|
|
13
|
-
import "../chunk-KHCJKVQN.js";
|
|
14
|
-
import "../chunk-XEURJVS5.js";
|
|
15
16
|
import "../chunk-NJDQ2JCP.js";
|
|
16
17
|
import {
|
|
17
18
|
ModelPicker
|
|
18
19
|
} from "../chunk-HG4OONJA.js";
|
|
19
|
-
import "../chunk-E4AY62T2.js";
|
|
20
20
|
import "../chunk-SJWIZT7B.js";
|
|
21
21
|
import "../chunk-MLG6XKPV.js";
|
|
22
22
|
import {
|
|
@@ -28,13 +28,13 @@ import "../chunk-MCYJON3F.js";
|
|
|
28
28
|
import "../chunk-B7CL7ENS.js";
|
|
29
29
|
import "../chunk-PV33JZKV.js";
|
|
30
30
|
import "../chunk-7YA4QNTU.js";
|
|
31
|
-
import "../chunk-
|
|
31
|
+
import "../chunk-JBEFTXDO.js";
|
|
32
32
|
import "../chunk-ZVEEWGDK.js";
|
|
33
33
|
import "../chunk-6E7LKHYV.js";
|
|
34
34
|
import "../chunk-TXD5HXLE.js";
|
|
35
|
-
import "../chunk-
|
|
36
|
-
import "../chunk-6VQCFJWP.js";
|
|
35
|
+
import "../chunk-XNKLQG26.js";
|
|
37
36
|
import "../chunk-LQYIBL3G.js";
|
|
37
|
+
import "../chunk-6VQCFJWP.js";
|
|
38
38
|
|
|
39
39
|
// src/assistant/sse.ts
|
|
40
40
|
var SSEChunkParser = class {
|
|
@@ -65,16 +65,16 @@ import {
|
|
|
65
65
|
rowIdOf,
|
|
66
66
|
storeSupportsDraftPersistence,
|
|
67
67
|
streamChatRouteAsSandboxEvents
|
|
68
|
-
} from "../chunk-
|
|
69
|
-
import "../chunk-Q7WEEN7P.js";
|
|
68
|
+
} from "../chunk-SH56N4PV.js";
|
|
70
69
|
import "../chunk-UTAIRVOK.js";
|
|
71
70
|
import "../chunk-RN4WPTBH.js";
|
|
71
|
+
import "../chunk-Q7WEEN7P.js";
|
|
72
72
|
import "../chunk-3NCPXNBZ.js";
|
|
73
73
|
import {
|
|
74
74
|
attachmentInputToPart,
|
|
75
75
|
attachmentKindForMime,
|
|
76
76
|
toChatMessageParts
|
|
77
|
-
} from "../chunk-
|
|
77
|
+
} from "../chunk-JBEFTXDO.js";
|
|
78
78
|
import "../chunk-ZVEEWGDK.js";
|
|
79
79
|
import {
|
|
80
80
|
ChatTurnInputError,
|
|
@@ -110,7 +110,7 @@ import {
|
|
|
110
110
|
import {
|
|
111
111
|
isWorkspaceFileExportable
|
|
112
112
|
} from "../chunk-TXD5HXLE.js";
|
|
113
|
-
import "../chunk-
|
|
113
|
+
import "../chunk-5V6VTO5Q.js";
|
|
114
114
|
import "../chunk-YG66IHDU.js";
|
|
115
115
|
import {
|
|
116
116
|
asRecord,
|
|
@@ -124,7 +124,13 @@ import {
|
|
|
124
124
|
normalizePersistedPart,
|
|
125
125
|
normalizeToolEvent,
|
|
126
126
|
terminalizeDanglingAssistantToolUpdates
|
|
127
|
-
} from "../chunk-
|
|
127
|
+
} from "../chunk-XNKLQG26.js";
|
|
128
|
+
import {
|
|
129
|
+
parsePlanSubmittedEvent,
|
|
130
|
+
persistedPartToPlan,
|
|
131
|
+
planFollowUpTurnId,
|
|
132
|
+
planToPersistedPart
|
|
133
|
+
} from "../chunk-LQYIBL3G.js";
|
|
128
134
|
import {
|
|
129
135
|
cancelStatusFor,
|
|
130
136
|
interactionPartKey,
|
|
@@ -135,16 +141,10 @@ import {
|
|
|
135
141
|
parseInteractionCancel,
|
|
136
142
|
parseInteractionRequest
|
|
137
143
|
} from "../chunk-6VQCFJWP.js";
|
|
138
|
-
import {
|
|
139
|
-
parsePlanSubmittedEvent,
|
|
140
|
-
persistedPartToPlan,
|
|
141
|
-
planFollowUpTurnId,
|
|
142
|
-
planToPersistedPart
|
|
143
|
-
} from "../chunk-LQYIBL3G.js";
|
|
144
144
|
import {
|
|
145
145
|
coalesceDeltas,
|
|
146
146
|
createBufferedTurnTap
|
|
147
|
-
} from "../chunk-
|
|
147
|
+
} from "../chunk-JC7YSRBR.js";
|
|
148
148
|
|
|
149
149
|
// src/chat-routes/model-failover-stream.ts
|
|
150
150
|
var TERMINAL_FAILURE_TYPES = /* @__PURE__ */ new Set(["error", "session.run.failed"]);
|
package/dist/chat-store/index.js
CHANGED
|
@@ -14,15 +14,15 @@ import {
|
|
|
14
14
|
mentionInputToPart,
|
|
15
15
|
mentionPartsFromMessageParts,
|
|
16
16
|
toChatMessageParts
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-JBEFTXDO.js";
|
|
18
18
|
import "../chunk-ZVEEWGDK.js";
|
|
19
19
|
import "../chunk-6E7LKHYV.js";
|
|
20
20
|
import "../chunk-TXD5HXLE.js";
|
|
21
21
|
import {
|
|
22
22
|
attachmentPartKey
|
|
23
|
-
} from "../chunk-
|
|
24
|
-
import "../chunk-6VQCFJWP.js";
|
|
23
|
+
} from "../chunk-XNKLQG26.js";
|
|
25
24
|
import "../chunk-LQYIBL3G.js";
|
|
25
|
+
import "../chunk-6VQCFJWP.js";
|
|
26
26
|
|
|
27
27
|
// src/chat-store/core.ts
|
|
28
28
|
var BULK_DELETE_MAX_THREADS = 200;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// src/launch-invariants/sized-reads.ts
|
|
2
|
+
var SIZED_READ_BYTES = 4 * 1024 * 1024;
|
|
3
|
+
var D1_MAX_BOUND_PARAMETERS = 100;
|
|
4
|
+
var SIZED_READ_ROWS = 50;
|
|
5
|
+
var SIZED_READ_COMPOSITE_ROWS = 40;
|
|
6
|
+
function sizedBatches(rows, options = {}) {
|
|
7
|
+
const bytes = options.bytes ?? SIZED_READ_BYTES;
|
|
8
|
+
const maxRows = options.rows ?? SIZED_READ_ROWS;
|
|
9
|
+
if (!(bytes > 0)) throw new RangeError("sized batches need a positive byte budget");
|
|
10
|
+
if (!(maxRows >= 1)) throw new RangeError("sized batches need at least one row per batch");
|
|
11
|
+
const batches = [];
|
|
12
|
+
let batch = [];
|
|
13
|
+
let size = 0;
|
|
14
|
+
for (const row of rows) {
|
|
15
|
+
const rowSize = Math.max(0, Number(row.size ?? 0) || 0);
|
|
16
|
+
if (batch.length > 0 && (size + rowSize > bytes || batch.length >= maxRows)) {
|
|
17
|
+
batches.push(batch);
|
|
18
|
+
batch = [];
|
|
19
|
+
size = 0;
|
|
20
|
+
}
|
|
21
|
+
batch.push(row.key);
|
|
22
|
+
size += rowSize;
|
|
23
|
+
}
|
|
24
|
+
if (batch.length > 0) batches.push(batch);
|
|
25
|
+
return batches;
|
|
26
|
+
}
|
|
27
|
+
async function* readInSizedBatches(rows, read, options = {}) {
|
|
28
|
+
for (const keys of sizedBatches(rows, options)) {
|
|
29
|
+
yield { keys, value: await read(keys) };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export {
|
|
34
|
+
SIZED_READ_BYTES,
|
|
35
|
+
D1_MAX_BOUND_PARAMETERS,
|
|
36
|
+
SIZED_READ_ROWS,
|
|
37
|
+
SIZED_READ_COMPOSITE_ROWS,
|
|
38
|
+
sizedBatches,
|
|
39
|
+
readInSizedBatches
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=chunk-5UQJ7F3P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/launch-invariants/sized-reads.ts"],"sourcesContent":["/**\n * Reads of a large column a bounded batch at a time.\n *\n * On 2026-10-10 GTM's scheduled jobs exceeded the Worker's 128 MB by reading a\n * day of stored turns at once: the outcome sweep held about 93 MB of turn\n * events, the reliability report read 1.63 M events, and turn health read\n * 121.8 MB of message parts in one query. D1 refuses the same read on its side\n * with `D1_ERROR: Memory limit exceeded before EOF`.\n *\n * A caller lists each row's key with the stored size of its large column\n * (SQLite `length(column)`), then reads and handles one batch before it reads\n * the next, keeping only what it concluded (counts, verdicts) rather than the\n * rows. Memory then holds one batch, not the day.\n *\n * Keep what you conclude, not what you read: a value sliced or matched out of a\n * large string can pin the whole parent string in V8 (a regex match kept in a\n * Map held every tool output it came from). Copy a kept substring out, e.g.\n * `new URL(match).href` or `(' ' + text).slice(1)`, before the row goes.\n */\n\n/** Most bytes of a large column one read returns; a single larger row is read alone. */\nexport const SIZED_READ_BYTES = 4 * 1024 * 1024\n\n/** D1 binds at most 100 parameters to one query. */\nexport const D1_MAX_BOUND_PARAMETERS = 100\n\n/** Most single-column keys one read binds, leaving room for the query's own parameters. */\nexport const SIZED_READ_ROWS = 50\n\n/** Most two-column keys, such as (turnId, seq), one read binds: two parameters each. */\nexport const SIZED_READ_COMPOSITE_ROWS = 40\n\n/** A row's key and the stored size of its large column. */\nexport interface SizedRow<K> {\n key: K\n /** `length()` of the large column; null when it is NULL. */\n size: number | null | undefined\n}\n\nexport interface SizedBatchOptions {\n /** Most bytes per batch. Default {@link SIZED_READ_BYTES}. */\n bytes?: number\n /** Most keys per batch. Default {@link SIZED_READ_ROWS}; `Infinity` for a range read (`seq BETWEEN`). */\n rows?: number\n}\n\n/** Consecutive keys whose stored sizes fit one read, in their listed order. */\nexport function sizedBatches<K>(rows: Iterable<SizedRow<K>>, options: SizedBatchOptions = {}): K[][] {\n const bytes = options.bytes ?? SIZED_READ_BYTES\n const maxRows = options.rows ?? SIZED_READ_ROWS\n if (!(bytes > 0)) throw new RangeError('sized batches need a positive byte budget')\n if (!(maxRows >= 1)) throw new RangeError('sized batches need at least one row per batch')\n const batches: K[][] = []\n let batch: K[] = []\n let size = 0\n for (const row of rows) {\n const rowSize = Math.max(0, Number(row.size ?? 0) || 0)\n if (batch.length > 0 && (size + rowSize > bytes || batch.length >= maxRows)) {\n batches.push(batch)\n batch = []\n size = 0\n }\n batch.push(row.key)\n size += rowSize\n }\n if (batch.length > 0) batches.push(batch)\n return batches\n}\n\n/**\n * Read listed rows one sized batch at a time. Each batch is read only after the\n * caller has handled the previous one, so a `for await` loop that keeps its\n * conclusions and drops the rows holds one batch at most.\n */\nexport async function* readInSizedBatches<K, R>(\n rows: Iterable<SizedRow<K>>,\n read: (keys: K[]) => Promise<R>,\n options: SizedBatchOptions = {},\n): AsyncGenerator<{ keys: K[]; value: R }> {\n for (const keys of sizedBatches(rows, options)) {\n yield { keys, value: await read(keys) }\n }\n}\n"],"mappings":";AAqBO,IAAM,mBAAmB,IAAI,OAAO;AAGpC,IAAM,0BAA0B;AAGhC,IAAM,kBAAkB;AAGxB,IAAM,4BAA4B;AAiBlC,SAAS,aAAgB,MAA6B,UAA6B,CAAC,GAAU;AACnG,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,UAAU,QAAQ,QAAQ;AAChC,MAAI,EAAE,QAAQ,GAAI,OAAM,IAAI,WAAW,2CAA2C;AAClF,MAAI,EAAE,WAAW,GAAI,OAAM,IAAI,WAAW,+CAA+C;AACzF,QAAM,UAAiB,CAAC;AACxB,MAAI,QAAa,CAAC;AAClB,MAAI,OAAO;AACX,aAAW,OAAO,MAAM;AACtB,UAAM,UAAU,KAAK,IAAI,GAAG,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC;AACtD,QAAI,MAAM,SAAS,MAAM,OAAO,UAAU,SAAS,MAAM,UAAU,UAAU;AAC3E,cAAQ,KAAK,KAAK;AAClB,cAAQ,CAAC;AACT,aAAO;AAAA,IACT;AACA,UAAM,KAAK,IAAI,GAAG;AAClB,YAAQ;AAAA,EACV;AACA,MAAI,MAAM,SAAS,EAAG,SAAQ,KAAK,KAAK;AACxC,SAAO;AACT;AAOA,gBAAuB,mBACrB,MACA,MACA,UAA6B,CAAC,GACW;AACzC,aAAW,QAAQ,aAAa,MAAM,OAAO,GAAG;AAC9C,UAAM,EAAE,MAAM,OAAO,MAAM,KAAK,IAAI,EAAE;AAAA,EACxC;AACF;","names":[]}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_RUNNING_TURN_LEASE_MS
|
|
3
|
+
} from "./chunk-JC7YSRBR.js";
|
|
4
|
+
|
|
1
5
|
// src/stream/turn-observation.ts
|
|
2
6
|
function parseTurnObservation(value) {
|
|
3
7
|
if (value === void 0) return {
|
|
@@ -88,9 +92,68 @@ async function consumeTurnStream(body, options) {
|
|
|
88
92
|
return state;
|
|
89
93
|
}
|
|
90
94
|
|
|
95
|
+
// src/stream/orphaned-turns.ts
|
|
96
|
+
var ORPHANED_TURN_CODE = "turn.orphaned";
|
|
97
|
+
var TAIL_EVENTS = 50;
|
|
98
|
+
var DEFAULT_LIMIT = 50;
|
|
99
|
+
async function settleOrphanedTurns(options) {
|
|
100
|
+
const { store } = options;
|
|
101
|
+
if (!store.listStaleRunning) throw new Error("settleOrphanedTurns needs a TurnEventStore with listStaleRunning (the D1 and memory stores have it)");
|
|
102
|
+
const now = options.now ?? Date.now();
|
|
103
|
+
const staleAfterMs = options.staleAfterMs ?? DEFAULT_RUNNING_TURN_LEASE_MS;
|
|
104
|
+
const cutoff = now - staleAfterMs;
|
|
105
|
+
const stale = await store.listStaleRunning(cutoff, options.limit ?? DEFAULT_LIMIT);
|
|
106
|
+
const settled = [];
|
|
107
|
+
const owned = [];
|
|
108
|
+
for (const turn of stale) {
|
|
109
|
+
if (options.isOwned && await options.isOwned(turn)) {
|
|
110
|
+
owned.push(turn.turnId);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const tail = await store.readTail?.(turn.turnId, TAIL_EVENTS) ?? [];
|
|
114
|
+
const { seq, at, phase } = describeTail(tail);
|
|
115
|
+
await store.append(turn.turnId, [{
|
|
116
|
+
seq: seq + 1,
|
|
117
|
+
event: JSON.stringify({
|
|
118
|
+
type: "error",
|
|
119
|
+
data: { message: `The turn stopped without finishing during ${phase ?? "the turn"}. Retry to send it again.`, code: ORPHANED_TURN_CODE, orphaned: true, retryable: true },
|
|
120
|
+
_t: at
|
|
121
|
+
})
|
|
122
|
+
}]);
|
|
123
|
+
await store.setStatus(turn.turnId, "error", void 0, { preserveUpdatedAt: true, onlyIfRunningBefore: cutoff });
|
|
124
|
+
settled.push({
|
|
125
|
+
turnId: turn.turnId,
|
|
126
|
+
scopeId: turn.scopeId,
|
|
127
|
+
lastRenewedAt: turn.updatedAt,
|
|
128
|
+
detectionLagMs: Math.max(0, now - (turn.updatedAt + DEFAULT_RUNNING_TURN_LEASE_MS)),
|
|
129
|
+
phase
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return { settled, owned, maxDetectionLagMs: settled.reduce((max, turn) => Math.max(max, turn.detectionLagMs), 0) };
|
|
133
|
+
}
|
|
134
|
+
function describeTail(tail) {
|
|
135
|
+
let seq = 0;
|
|
136
|
+
let at = 0;
|
|
137
|
+
let phase = null;
|
|
138
|
+
for (const row of tail) {
|
|
139
|
+
seq = Math.max(seq, row.seq);
|
|
140
|
+
let event;
|
|
141
|
+
try {
|
|
142
|
+
event = JSON.parse(row.event);
|
|
143
|
+
} catch {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (typeof event?._t === "number") at = Math.max(at, event._t);
|
|
147
|
+
if (phase === null && event?.type === "session.run.phase" && typeof event.data?.phase === "string") phase = event.data.phase;
|
|
148
|
+
}
|
|
149
|
+
return { seq, at, phase };
|
|
150
|
+
}
|
|
151
|
+
|
|
91
152
|
export {
|
|
92
153
|
parseTurnObservation,
|
|
93
154
|
observeTurnEvent,
|
|
94
|
-
consumeTurnStream
|
|
155
|
+
consumeTurnStream,
|
|
156
|
+
ORPHANED_TURN_CODE,
|
|
157
|
+
settleOrphanedTurns
|
|
95
158
|
};
|
|
96
|
-
//# sourceMappingURL=chunk-
|
|
159
|
+
//# sourceMappingURL=chunk-5V6VTO5Q.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stream/turn-observation.ts","../src/stream/orphaned-turns.ts"],"sourcesContent":["/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n","/**\n * Settle turn streams whose owner is gone.\n *\n * A running turn row is a lease: the buffer renews it every 30 s while a\n * producer lives, and a durable observer renews it on each pass. A row nothing\n * renewed past its lease has no producer left; the Worker that streamed it\n * died. Left alone it stays `running` forever: a reconnecting client waits on\n * it, discovery offers it, and reports count it as in flight. On 2026-10-10\n * GTM held 51 such rows, some for hours, and its failure notices arrived 8–11 h\n * after the turns had stopped.\n *\n * {@link settleOrphanedTurns} ends each one the way the buffer ends a failed\n * turn: a terminal `error` event naming the phase it stopped in, then status\n * `error`, written only while the row is still running and still stale, and\n * without moving its update time (reports place a stream by it). It returns\n * each turn's detection lag, the time from its lease expiring to this\n * settlement, so a product can report how late it noticed. Run it from its own\n * scheduled invocation at least every 15 minutes.\n */\nimport { DEFAULT_RUNNING_TURN_LEASE_MS, type BufferedTurnEvent, type StaleRunningTurn, type TurnEventStore } from './turn-buffer'\n\n/** The failure code carried by the terminal event of a settled orphan. */\nexport const ORPHANED_TURN_CODE = 'turn.orphaned'\n\n/** How many tail events are read to name the phase a turn stopped in. */\nconst TAIL_EVENTS = 50\nconst DEFAULT_LIMIT = 50\n\nexport interface SettleOrphanedTurnsOptions {\n store: TurnEventStore\n now?: number\n /** A row older than this since its last renewal is orphaned. Default the running lease, 5 minutes. */\n staleAfterMs?: number\n /** Most rows settled per run; the next run takes the rest. Default 50. */\n limit?: number\n /**\n * Whether something still owns this turn although it stopped renewing the\n * row, such as an open completion admission with a live lease. An owned turn\n * is skipped. A product whose durable owner does not renew the row must\n * answer this, or its live turns are settled as orphans.\n */\n isOwned?: (turn: StaleRunningTurn) => Promise<boolean>\n}\n\nexport interface SettledOrphanedTurn {\n turnId: string\n scopeId: string | null\n /** Unix ms the row was last renewed. */\n lastRenewedAt: number\n /** From its lease expiring to this settlement. */\n detectionLagMs: number\n /** The run phase the stream last reported, when it reported one. */\n phase: string | null\n}\n\nexport interface SettleOrphanedTurnsResult {\n settled: SettledOrphanedTurn[]\n /** Stale rows an owner still held. */\n owned: string[]\n /** Most detection lag among the settled turns, in ms. */\n maxDetectionLagMs: number\n}\n\n/** End every running turn stream nothing has renewed past its lease. */\nexport async function settleOrphanedTurns(options: SettleOrphanedTurnsOptions): Promise<SettleOrphanedTurnsResult> {\n const { store } = options\n if (!store.listStaleRunning) throw new Error('settleOrphanedTurns needs a TurnEventStore with listStaleRunning (the D1 and memory stores have it)')\n const now = options.now ?? Date.now()\n const staleAfterMs = options.staleAfterMs ?? DEFAULT_RUNNING_TURN_LEASE_MS\n const cutoff = now - staleAfterMs\n const stale = await store.listStaleRunning(cutoff, options.limit ?? DEFAULT_LIMIT)\n const settled: SettledOrphanedTurn[] = []\n const owned: string[] = []\n for (const turn of stale) {\n if (options.isOwned && await options.isOwned(turn)) {\n owned.push(turn.turnId)\n continue\n }\n const tail = (await store.readTail?.(turn.turnId, TAIL_EVENTS)) ?? []\n const { seq, at, phase } = describeTail(tail)\n await store.append(turn.turnId, [{\n seq: seq + 1,\n event: JSON.stringify({\n type: 'error',\n data: { message: `The turn stopped without finishing during ${phase ?? 'the turn'}. Retry to send it again.`, code: ORPHANED_TURN_CODE, orphaned: true, retryable: true },\n _t: at,\n }),\n }])\n // Only a row still running and still stale: a producer that came back keeps its stream.\n await store.setStatus(turn.turnId, 'error', undefined, { preserveUpdatedAt: true, onlyIfRunningBefore: cutoff })\n settled.push({\n turnId: turn.turnId,\n scopeId: turn.scopeId,\n lastRenewedAt: turn.updatedAt,\n detectionLagMs: Math.max(0, now - (turn.updatedAt + DEFAULT_RUNNING_TURN_LEASE_MS)),\n phase,\n })\n }\n return { settled, owned, maxDetectionLagMs: settled.reduce((max, turn) => Math.max(max, turn.detectionLagMs), 0) }\n}\n\ninterface TailEvent {\n type?: unknown\n _t?: unknown\n data?: { phase?: unknown }\n}\n\nfunction describeTail(tail: readonly BufferedTurnEvent[]): { seq: number; at: number; phase: string | null } {\n let seq = 0\n let at = 0\n let phase: string | null = null\n for (const row of tail) {\n seq = Math.max(seq, row.seq)\n let event: TailEvent | null\n try {\n event = JSON.parse(row.event) as TailEvent | null\n } catch {\n continue\n }\n if (typeof event?._t === 'number') at = Math.max(at, event._t)\n if (phase === null && event?.type === 'session.run.phase' && typeof event.data?.phase === 'string') phase = event.data.phase\n }\n return { seq, at, phase }\n}\n"],"mappings":";;;;;AAWO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