dsh-context 0.70.0 → 0.71.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.
package/lib/index.js CHANGED
@@ -1,3649 +1,16 @@
1
1
  /**
2
- * dsh-context v0.70.0
2
+ * dsh-context v0.71.0
3
3
  * A DeepSeek Harness plugin for context insight and management, with context dashboard and context command, for understanding how the context is made of, and how it evolves.
4
4
  * @author bowenliang123
5
5
  * @license Apache-2.0
6
6
  * @homepage https://github.com/bowenliang123/dsh-context
7
- * @built 2026-10-13T23:50:32+00:00
8
- * @commit 854ce14aad18
9
- * @commit-date 2026-10-14T07:45:49+08:00
7
+ * @built 2026-10-14T18:33:56+00:00
8
+ * @commit afd94fec7b80
9
+ * @commit-date 2026-10-15T02:31:07+08:00
10
10
  */
11
11
 
12
- import { createRequire } from "node:module";
13
- import { z } from "zod";
14
- import { deriveEventMessage, interruptedTurnClosers } from "@deepseek-ai/dsh-session";
15
- import z$1 from "@deepseek-ai/schemastery";
16
- import { copyFile, link, mkdir } from "node:fs/promises";
17
- import { basename, dirname, isAbsolute, join, normalize, relative } from "node:path";
18
- import { getHeapStatistics } from "node:v8";
19
- import { existsSync, readFileSync } from "node:fs";
20
- import { fileURLToPath } from "node:url";
21
- import { performance } from "node:perf_hooks";
22
- import { randomUUID } from "node:crypto";
23
- //#region src/shared/estimate.ts
24
- const CHARS_PER_TOKEN$1 = 4;
25
- const ROLE_OVERHEAD$1 = 4;
26
- const BLOCK_OVERHEAD$1 = 4;
27
- function estimateSystemTokens(text) {
28
- if (typeof text !== "string" || text.length === 0) return 0;
29
- return Math.ceil(text.length / CHARS_PER_TOKEN$1) + ROLE_OVERHEAD$1;
30
- }
31
- function estimateTextTokens(text) {
32
- return Math.ceil(text.length / CHARS_PER_TOKEN$1) + BLOCK_OVERHEAD$1;
33
- }
34
- function estimateSystemContent(blocks) {
35
- if (!Array.isArray(blocks) || blocks.length === 0) return 0;
36
- let characters = 0;
37
- for (const block of blocks) {
38
- const text = block !== null && typeof block === "object" && block.type === "text" ? block.text : void 0;
39
- if (typeof text === "string") {
40
- characters += text.length;
41
- continue;
42
- }
43
- try {
44
- const json = JSON.stringify(block);
45
- if (typeof json === "string") characters += json.length;
46
- } catch {}
47
- }
48
- return Math.ceil(characters / CHARS_PER_TOKEN$1) + ROLE_OVERHEAD$1;
49
- }
50
- //#endregion
51
- //#region src/shared/imageTokens.ts
52
- const PATCH_SIZE = 14;
53
- const DOWNSAMPLE_RATIO = 3;
54
- const MAX_WH_RATIO = 8;
55
- const MIN_PIXELS = 147456;
56
- const floorDiv = (a, b) => Math.floor(a / b);
57
- const ceilDiv = (a, b) => Math.floor((a + b - 1) / b);
58
- function gridTokens(rows, cols) {
59
- let n = rows * (cols + 1) + 2;
60
- if (rows % 2 === 1) n += cols + 1;
61
- n += ceilDiv(rows, 2) * (cols + 1) % 2 * 2;
62
- return n;
63
- }
64
- function solveResizeRatio(height, width, budget) {
65
- const ratio = height / width;
66
- const gridW = Math.sqrt((budget - 2) / ratio + .25) - .5;
67
- const gridH = gridW * ratio;
68
- const unit = 42;
69
- let bestHeight;
70
- let bestWidth;
71
- if (gridW < 1) {
72
- let rows = floorDiv(budget - 2, 2);
73
- if (rows % 2 === 1) rows -= 1;
74
- bestWidth = unit;
75
- bestHeight = rows * unit;
76
- } else if (gridH < 2) {
77
- const cols = floorDiv(budget - 2, 2) - 1;
78
- if (cols <= 1) throw new Error("image tokens: budget too small to solve");
79
- bestHeight = 84;
80
- bestWidth = cols * unit;
81
- } else {
82
- const cols = Math.trunc(gridW);
83
- let rows = Math.trunc(gridH);
84
- if (rows % 2 === 1) rows -= 1;
85
- const scale = Math.min(cols * unit / width, rows * unit / height);
86
- bestWidth = Math.trunc(width * scale / PATCH_SIZE) * PATCH_SIZE;
87
- bestHeight = Math.trunc(height * scale / PATCH_SIZE) * PATCH_SIZE;
88
- }
89
- const nLlmH = ceilDiv(floorDiv(bestHeight, PATCH_SIZE), DOWNSAMPLE_RATIO);
90
- const nLlmW = ceilDiv(floorDiv(bestWidth, PATCH_SIZE), DOWNSAMPLE_RATIO);
91
- return {
92
- nLlmH,
93
- nLlmW,
94
- bestHeight,
95
- bestWidth,
96
- numTokens: gridTokens(nLlmH, nLlmW)
97
- };
98
- }
99
- function safeResize(height, width, paddedHeight, paddedWidth) {
100
- const nLlmH = ceilDiv(floorDiv(paddedHeight, PATCH_SIZE), DOWNSAMPLE_RATIO);
101
- const nLlmW = ceilDiv(floorDiv(paddedWidth, PATCH_SIZE), DOWNSAMPLE_RATIO);
102
- const pad = 3;
103
- const budget = 381;
104
- let result = {
105
- nLlmH,
106
- nLlmW,
107
- bestHeight: paddedHeight,
108
- bestWidth: paddedWidth,
109
- numTokens: gridTokens(nLlmH, nLlmW)
110
- };
111
- if (result.numTokens > budget) {
112
- result = solveResizeRatio(height, width, budget);
113
- let nextBudget = budget;
114
- while (result.numTokens > budget) {
115
- nextBudget -= 1;
116
- result = solveResizeRatio(height, width, nextBudget);
117
- }
118
- }
119
- result.numTokens += pad;
120
- return result;
121
- }
122
- function calcResizeInner(width, height) {
123
- let w = width;
124
- let h = height;
125
- if (w > h * MAX_WH_RATIO) w = h * MAX_WH_RATIO;
126
- const pixels = w * h;
127
- if (pixels < MIN_PIXELS && pixels > 0) {
128
- const scale = Math.sqrt(MIN_PIXELS / pixels);
129
- w = Math.trunc(w * scale);
130
- h = Math.trunc(h * scale);
131
- }
132
- const paddedWidth = ceilDiv(w, PATCH_SIZE) * PATCH_SIZE;
133
- const paddedHeight = ceilDiv(h, PATCH_SIZE) * PATCH_SIZE;
134
- return safeResize(h, w, paddedHeight, paddedWidth);
135
- }
136
- function estimateImageTokens(width, height) {
137
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return null;
138
- try {
139
- let result = calcResizeInner(width, height);
140
- for (let i = 1; i < 10; i++) {
141
- const next = calcResizeInner(result.bestWidth, result.bestHeight);
142
- if (next.nLlmH === result.nLlmH && next.nLlmW === result.nLlmW && next.bestHeight === result.bestHeight && next.bestWidth === result.bestWidth && next.numTokens === result.numTokens) return result.numTokens;
143
- result = next;
144
- }
145
- return null;
146
- } catch {
147
- return null;
148
- }
149
- }
150
- //#endregion
151
- //#region src/host/pricing.ts
152
- const CHARS_PER_TOKEN = 4;
153
- const BLOCK_OVERHEAD = 4;
154
- const ROLE_OVERHEAD = 4;
155
- function estimateToolsTotal(tools) {
156
- return tools.length > 0 ? Math.ceil(JSON.stringify(tools).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD : 0;
157
- }
158
- function estimateBlocks(blocks) {
159
- let tokens = 0;
160
- if (!Array.isArray(blocks)) return 0;
161
- for (const item of blocks) {
162
- if (item === null || typeof item !== "object") {
163
- tokens += BLOCK_OVERHEAD;
164
- continue;
165
- }
166
- const block = item;
167
- switch (block.type) {
168
- case "text":
169
- case "reasoning":
170
- tokens += estimateTextTokens(block.text || "");
171
- break;
172
- case "tool-call":
173
- tokens += Math.ceil((block.name || "").length / CHARS_PER_TOKEN) + Math.ceil((block.arguments || "").length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
174
- break;
175
- case "image": {
176
- const ref = block.attachment;
177
- const priced = ref !== null && typeof ref === "object" && typeof ref.width === "number" && typeof ref.height === "number" ? estimateImageTokens(ref.width, ref.height) : null;
178
- tokens += (priced ?? Math.ceil(JSON.stringify(block).length / CHARS_PER_TOKEN)) + BLOCK_OVERHEAD;
179
- break;
180
- }
181
- default: tokens += BLOCK_OVERHEAD + Math.ceil(JSON.stringify(block).length / CHARS_PER_TOKEN);
182
- }
183
- }
184
- return tokens;
185
- }
186
- function estimateMessage(message, emptyIsZero = false) {
187
- if (emptyIsZero && (message === null || message === void 0 || !Array.isArray(message.content) || message.content.length === 0)) return 0;
188
- return estimateBlocks(message?.content) + ROLE_OVERHEAD;
189
- }
190
- function estimateToolSchema(tool) {
191
- return Math.ceil(JSON.stringify(tool).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
192
- }
193
- function imageCountOf(blocks) {
194
- let count = 0;
195
- if (!Array.isArray(blocks)) return 0;
196
- for (const item of blocks) {
197
- if (item === null || typeof item !== "object") continue;
198
- const block = item;
199
- if (block.type === "image") count++;
200
- else if (Array.isArray(block.content)) count += imageCountOf(block.content);
201
- }
202
- return count;
203
- }
204
- function firstText(blocks) {
205
- if (!Array.isArray(blocks)) return "";
206
- for (const item of blocks) {
207
- if (item === null || typeof item !== "object") continue;
208
- const b = item;
209
- if (b.type === "text" && typeof b.text === "string" && b.text.trim() !== "") return b.text.replace(/\s+/g, " ").trim().slice(0, 80);
210
- }
211
- return "";
212
- }
213
- function toolCallNames(blocks) {
214
- const names = [];
215
- if (!Array.isArray(blocks)) return names;
216
- for (const item of blocks) {
217
- if (item === null || typeof item !== "object") continue;
218
- const b = item;
219
- if (b.type === "tool-call" && typeof b.name === "string") names.push(b.name);
220
- }
221
- return names;
222
- }
223
- function injectionSourceName(source) {
224
- if (source?.kind === "agent-instructions" && Array.isArray(source.changes)) {
225
- const paths = [];
226
- for (const change of source.changes) {
227
- const path = change?.path;
228
- if (typeof path === "string" && path !== "" && !paths.includes(path)) paths.push(path);
229
- }
230
- if (paths.length > 0) return paths.join(", ");
231
- }
232
- const plugin = source?.plugin;
233
- if (typeof plugin === "string" && plugin !== "") return plugin;
234
- const kind = source?.kind;
235
- return typeof kind === "string" && kind !== "" ? kind : "";
236
- }
237
- function isInjection(source) {
238
- return source !== null && source !== void 0 && (typeof source.kind === "string" && source.kind !== "" && source.kind !== "user" || typeof source.form === "string");
239
- }
240
- //#endregion
241
- //#region src/host/logShapes.ts
242
- function isTokenChunk(chunk) {
243
- if (chunk === null || typeof chunk !== "object") return false;
244
- const c = chunk;
245
- switch (c.type) {
246
- case "text-delta":
247
- case "reasoning-delta": return typeof c.text === "string" && c.text !== "";
248
- case "tool-call-delta": return typeof c.argumentsDelta === "string" && c.argumentsDelta !== "" || c.name !== void 0;
249
- default: return false;
250
- }
251
- }
252
- function decodeKindOfBlock(blockType) {
253
- if (blockType === "reasoning") return "reasoning";
254
- if (blockType === "text") return "text";
255
- if (blockType === "tool-call") return "toolarg";
256
- }
257
- function decodeTallyOfStream(stream, endTime) {
258
- const tally = {
259
- spans: {
260
- reasoning: 0,
261
- text: 0,
262
- toolarg: 0
263
- },
264
- blocks: {
265
- reasoning: 0,
266
- text: 0,
267
- toolarg: 0
268
- }
269
- };
270
- if (!Array.isArray(stream) || !Number.isFinite(endTime)) return tally;
271
- let kind;
272
- let since = 0;
273
- for (const record of stream) {
274
- if (record === null || typeof record !== "object") continue;
275
- const r = record;
276
- if (r.type !== "chunk" || r.chunk === null || typeof r.chunk !== "object") continue;
277
- const chunk = r.chunk;
278
- if (chunk.type !== "block-start") continue;
279
- const time = r.time;
280
- if (typeof time !== "number" || !Number.isFinite(time)) continue;
281
- if (kind !== void 0) tally.spans[kind] += Math.max(0, time - since);
282
- kind = decodeKindOfBlock(chunk.blockType);
283
- if (kind !== void 0) tally.blocks[kind] += 1;
284
- since = time;
285
- }
286
- if (kind !== void 0) tally.spans[kind] += Math.max(0, endTime - since);
287
- return tally;
288
- }
289
- function decodeSpansOfStream(stream, endTime) {
290
- const spans = [];
291
- if (!Array.isArray(stream) || !Number.isFinite(endTime)) return spans;
292
- let kind;
293
- let since = 0;
294
- const close = (to) => {
295
- if (kind !== void 0 && to > since) spans.push({
296
- kind,
297
- start: since,
298
- end: to
299
- });
300
- };
301
- for (const record of stream) {
302
- if (record === null || typeof record !== "object") continue;
303
- const r = record;
304
- if (r.type !== "chunk" || r.chunk === null || typeof r.chunk !== "object") continue;
305
- const chunk = r.chunk;
306
- if (chunk.type !== "block-start") continue;
307
- const time = r.time;
308
- if (typeof time !== "number" || !Number.isFinite(time)) continue;
309
- close(time);
310
- kind = decodeKindOfBlock(chunk.blockType);
311
- since = time;
312
- }
313
- close(endTime);
314
- return spans;
315
- }
316
- function runFirstTokenTime(record) {
317
- const time0 = record.time0;
318
- if (typeof time0 !== "number" || !Number.isFinite(time0)) return void 0;
319
- if (record.type === "tool-call-chunks" && record.name !== void 0) return time0;
320
- const fragments = record.type === "tool-call-chunks" ? record.args : record.texts;
321
- if (!Array.isArray(fragments)) return void 0;
322
- const dt = Array.isArray(record.dt) ? record.dt : [];
323
- let time = time0;
324
- for (const [index, fragment] of fragments.entries()) {
325
- if (index > 0) {
326
- const step = dt[index - 1];
327
- if (typeof step !== "number" || !Number.isFinite(step)) return void 0;
328
- time += step;
329
- }
330
- if (typeof fragment === "string" && fragment !== "") return time;
331
- }
332
- }
333
- function firstTokenTimeOfStream(stream) {
334
- if (!Array.isArray(stream)) return void 0;
335
- for (const record of stream) {
336
- if (record === null || typeof record !== "object") continue;
337
- const r = record;
338
- if (r.type === "chunk") {
339
- const time = r.time;
340
- if (typeof time === "number" && Number.isFinite(time) && isTokenChunk(r.chunk)) return time;
341
- continue;
342
- }
343
- const time = runFirstTokenTime(r);
344
- if (time !== void 0) return time;
345
- }
346
- }
347
- function replaceRangeOf(surfaceOp) {
348
- if (surfaceOp === null || typeof surfaceOp !== "object") return null;
349
- const op = surfaceOp;
350
- if (op.op !== "replace") return null;
351
- const { startSeq: start, endSeq: end } = op;
352
- if (typeof start !== "number" || !Number.isFinite(start)) return null;
353
- if (typeof end !== "number" || !Number.isFinite(end)) return null;
354
- return {
355
- start,
356
- end
357
- };
358
- }
359
- //#endregion
360
- //#region src/shared/fileOps.ts
361
- function parseCallArgs(raw) {
362
- if (typeof raw !== "string" || raw === "") return null;
363
- try {
364
- const parsed = JSON.parse(raw);
365
- return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
366
- } catch {
367
- return null;
368
- }
369
- }
370
- const KIND_BY_TOOL = {
371
- read: "read",
372
- read_image: "read",
373
- write: "write",
374
- edit: "write",
375
- grep: "search",
376
- glob: "search"
377
- };
378
- function kindOfTool(tool) {
379
- if (tool === void 0) return null;
380
- return KIND_BY_TOOL[tool] ?? null;
381
- }
382
- function kindOfCall(tool, args) {
383
- if (tool === "str_replace_editor") return args !== null && args.command === "view" ? "read" : "write";
384
- return kindOfTool(tool);
385
- }
386
- function opBearingTool(tool) {
387
- return tool === "str_replace_editor" || kindOfTool(tool) !== null;
388
- }
389
- function rawArgsNeeded(tool) {
390
- return opBearingTool(tool) || tool === "run_code";
391
- }
392
- function pathOfArgs(tool, args) {
393
- if (args === null) return null;
394
- if (tool === "grep" || tool === "glob") {
395
- const p = args.path;
396
- if (typeof p === "string" && p !== "") return p;
397
- const pattern = args.pattern;
398
- return typeof pattern === "string" && pattern !== "" ? pattern : null;
399
- }
400
- for (const k of [
401
- "file_path",
402
- "filePath",
403
- "path"
404
- ]) {
405
- const v = args[k];
406
- if (typeof v === "string" && v !== "") return v;
407
- }
408
- return null;
409
- }
410
- function linesOf(s) {
411
- if (s === "") return 0;
412
- let n = 0;
413
- for (let i = 0; i < s.length; i++) if (s[i] === "\n") n++;
414
- return s.endsWith("\n") ? n : n + 1;
415
- }
416
- function pairOf(added, removed) {
417
- return {
418
- added: typeof added === "string" ? linesOf(added) : 0,
419
- removed: typeof removed === "string" ? linesOf(removed) : 0
420
- };
421
- }
422
- function deltaOf(tool, args) {
423
- if (tool === "edit") return pairOf(args.new_string, args.old_string);
424
- if (tool === "write") return pairOf(args.content, void 0);
425
- if (tool === "str_replace_editor") {
426
- if (args.command === "str_replace") return pairOf(args.new_str, args.old_str);
427
- if (args.command === "insert") return pairOf(args.new_str, void 0);
428
- if (args.command === "create") return pairOf(args.file_text, void 0);
429
- }
430
- return {
431
- added: 0,
432
- removed: 0
433
- };
434
- }
435
- function readWindowOf(meta) {
436
- if (meta === null || typeof meta !== "object") return null;
437
- const m = meta;
438
- if (typeof m.path !== "string" || m.path === "") return null;
439
- if (typeof m.offset !== "number" || !Number.isFinite(m.offset) || m.offset < 1) return null;
440
- if (!Array.isArray(m.lines) || m.lines.length === 0) return null;
441
- return {
442
- start: m.offset,
443
- count: m.lines.length
444
- };
445
- }
446
- function readEstimateOf(args) {
447
- const limit = args.limit;
448
- return typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? {
449
- count: Math.floor(limit),
450
- est: true
451
- } : void 0;
452
- }
453
- function readOf(meta, args) {
454
- const win = readWindowOf(meta);
455
- if (win !== null) return {
456
- start: win.start,
457
- count: win.count
458
- };
459
- return readEstimateOf(args);
460
- }
461
- function searchDetailOf(args) {
462
- const pattern = args?.pattern;
463
- if (typeof pattern !== "string" || pattern === "") return void 0;
464
- const include = args?.include;
465
- return typeof include === "string" && include !== "" ? `${pattern} (${include})` : pattern;
466
- }
467
- function searchFilesOf(meta) {
468
- if (meta === null || typeof meta !== "object") return null;
469
- const m = meta;
470
- if (m.truncated !== false) return null;
471
- const files = [];
472
- if (m.shape === "matches" && Array.isArray(m.files)) for (const f of m.files) {
473
- if (f === null || typeof f !== "object") continue;
474
- const group = f;
475
- if (typeof group.path === "string" && group.path !== "" && Array.isArray(group.matches)) files.push({
476
- path: group.path,
477
- hits: group.matches.length
478
- });
479
- }
480
- else if (m.shape === "paths" && Array.isArray(m.paths)) {
481
- for (const p of m.paths) if (typeof p === "string" && p !== "") files.push({
482
- path: p,
483
- hits: 0
484
- });
485
- }
486
- return files.length > 0 ? files : null;
487
- }
488
- function opsOfCall(input) {
489
- const args = opBearingTool(input.tool) ? parseCallArgs(input.argsRaw) : null;
490
- const kind = kindOfCall(input.tool, args);
491
- if (kind === null) return [];
492
- const stamp = {
493
- seq: input.seq,
494
- kind,
495
- tool: input.tool,
496
- err: input.err === true,
497
- added: 0,
498
- removed: 0,
499
- path: "",
500
- ...input.time !== void 0 ? { time: input.time } : {},
501
- ...input.gone !== void 0 ? { gone: input.gone } : {},
502
- ...input.parent !== void 0 ? { parent: input.parent } : {},
503
- ...input.program !== void 0 ? { program: input.program } : {}
504
- };
505
- if (kind === "search") {
506
- const files = searchFilesOf(input.meta);
507
- if (files !== null) {
508
- const detail = searchDetailOf(args);
509
- const target = args !== null ? pathOfArgs(input.tool, args) : null;
510
- const narrowed = args !== null && typeof args.path === "string" && args.path !== "";
511
- return [...target !== null && !files.some((f) => f.path === target) ? [{
512
- ...stamp,
513
- path: target,
514
- ...narrowed && detail !== void 0 ? { detail } : {},
515
- ...narrowed ? {} : { pattern: true }
516
- }] : [], ...files.map((f) => ({
517
- ...stamp,
518
- path: f.path,
519
- ...detail !== void 0 ? { detail } : {},
520
- ...f.hits > 0 ? { hits: f.hits } : {}
521
- }))];
522
- }
523
- }
524
- if (args === null) return [];
525
- const path = pathOfArgs(input.tool, args);
526
- if (path === null) return [];
527
- const { added, removed } = deltaOf(input.tool, args);
528
- const narrowed = typeof args.path === "string" && args.path !== "";
529
- const detail = kind === "search" && narrowed ? searchDetailOf(args) : void 0;
530
- const read = kind === "read" ? readOf(input.meta, args) : void 0;
531
- return [{
532
- ...stamp,
533
- path,
534
- added,
535
- removed,
536
- ...detail !== void 0 ? { detail } : {},
537
- ...read !== void 0 ? { read } : {},
538
- ...kind === "search" && !narrowed ? { pattern: true } : {}
539
- }];
540
- }
541
- //#endregion
542
- //#region src/host/foldState.ts
543
- function trimToLastTurns(requests, maxTurns) {
544
- let runs = 0;
545
- let start = requests.length;
546
- let prevTurn;
547
- for (let i = requests.length - 1; i >= 0; i--) {
548
- const turn = requests[i].turn;
549
- if (turn !== prevTurn) {
550
- if (runs >= maxTurns) break;
551
- runs++;
552
- prevTurn = turn;
553
- }
554
- start = i;
555
- }
556
- return requests.slice(start);
557
- }
558
- function countTurnRuns(requests) {
559
- let runs = 0;
560
- let prevTurn;
561
- for (const r of requests) if (r.turn !== prevTurn) {
562
- runs++;
563
- prevTurn = r.turn;
564
- }
565
- return runs;
566
- }
567
- function trimState(st, bounds) {
568
- st.turnRuns = st.turnRuns ?? countTurnRuns(st.requests);
569
- if (st.turnRuns > bounds.maxKeptTurns) {
570
- st.requests = trimToLastTurns(st.requests, bounds.maxKeptTurns);
571
- st.turnRuns = countTurnRuns(st.requests);
572
- }
573
- if (st.requests.length > bounds.maxRequestSteps) {
574
- st.requests = st.requests.slice(-bounds.maxRequestSteps);
575
- st.turnRuns = countTurnRuns(st.requests);
576
- }
577
- if (st.events.length > bounds.maxEvents) st.events = st.events.slice(-bounds.maxEvents);
578
- if (st.spans.length > TIMING_SPANS_MAX) st.spans = st.spans.slice(-TIMING_SPANS_MAX);
579
- if (st.fileOps.length > bounds.maxFileOps) {
580
- const drop = st.fileOps.length - bounds.maxFileOps;
581
- st.fileOpsFloor = Math.max(st.fileOpsFloor ?? 0, st.fileOps[drop - 1].seq);
582
- st.fileOps = st.fileOps.slice(drop);
583
- }
584
- if (st.archived.length > 0) {
585
- let drop = 0;
586
- const oldestReq = st.requests.length > 0 ? st.requests[0].seq : void 0;
587
- if (oldestReq !== void 0) while (drop < st.archived.length && (st.archived[drop].gone ?? Infinity) <= oldestReq) drop++;
588
- if (st.archived.length - drop > bounds.maxArchiveNodes) drop = st.archived.length - bounds.maxArchiveNodes;
589
- if (drop > 0) {
590
- const floor = st.archived[drop - 1].gone;
591
- if (floor !== void 0) st.archiveFloor = Math.max(st.archiveFloor ?? 0, floor);
592
- st.archived = st.archived.slice(drop);
593
- }
594
- }
595
- }
596
- const TIMING_SPANS_MAX = 2e3;
597
- function createTimelineState() {
598
- return {
599
- surface: [],
600
- sums: {
601
- user: 0,
602
- inject: 0,
603
- skill: 0,
604
- assistant: 0,
605
- tool: 0
606
- },
607
- systemTokens: 0,
608
- toolsTokens: 0,
609
- requests: [],
610
- turnRuns: 0,
611
- events: [],
612
- archived: [],
613
- callNames: {},
614
- fileOps: [],
615
- spans: []
616
- };
617
- }
618
- //#endregion
619
- //#region src/shared/providers.ts
620
- const MODELS_DEV_PROVIDER_IDS = {
621
- "deepseek-official": "deepseek",
622
- "deepseek-account": "deepseek",
623
- "kimi-coding": "moonshotai",
624
- "minimax-cn": "minimax",
625
- "zai-coding-cn": "zhipuai"
626
- };
627
- function modelsDevProviderOf(dshProviderId) {
628
- return MODELS_DEV_PROVIDER_IDS[dshProviderId] ?? dshProviderId;
629
- }
630
- function isDeepSeekProvider(dshProviderId) {
631
- return modelsDevProviderOf(dshProviderId) === "deepseek";
632
- }
633
- //#endregion
634
- //#region src/host/foldMetering.ts
635
- function tokenCountOf(value) {
636
- if (typeof value === "number") return Number.isFinite(value) ? Math.max(0, Math.round(value)) : null;
637
- if (typeof value === "string" && value.trim() !== "") {
638
- const parsed = Number(value);
639
- return Number.isFinite(parsed) ? Math.max(0, Math.round(parsed)) : null;
640
- }
641
- return null;
642
- }
643
- function isPeakUtc(time) {
644
- const at = new Date(time);
645
- const day = at.getUTCDay();
646
- if (day === 0 || day === 6) return false;
647
- const h = at.getUTCHours();
648
- return h >= 1 && h < 4 || h >= 6 && h < 10;
649
- }
650
- function addBilledUsage(prev, provider, model, time, usage) {
651
- const period = isDeepSeekProvider(provider) && !isPeakUtc(time) ? "off" : "peak";
652
- const models = prev?.[provider] ?? {};
653
- const periods = models[model] ?? {};
654
- const b = periods[period] ?? {
655
- uncached: 0,
656
- cacheRead: 0,
657
- cacheWrite: 0,
658
- output: 0
659
- };
660
- const nextPeriods = { ...periods };
661
- nextPeriods[period] = {
662
- uncached: b.uncached + usage.uncached,
663
- cacheRead: b.cacheRead + usage.cacheRead,
664
- cacheWrite: b.cacheWrite + usage.cacheWrite,
665
- output: b.output + usage.output
666
- };
667
- const nextModels = {
668
- ...models,
669
- [model]: nextPeriods
670
- };
671
- return {
672
- ...prev ?? {},
673
- [provider]: nextModels
674
- };
675
- }
676
- function copyCostUsage(cost) {
677
- const copy = {};
678
- for (const provider in cost) {
679
- const models = {};
680
- for (const model in cost[provider]) {
681
- const periods = cost[provider][model];
682
- const modelCopy = {};
683
- if (periods.peak !== void 0) modelCopy.peak = { ...periods.peak };
684
- if (periods.off !== void 0) modelCopy.off = { ...periods.off };
685
- models[model] = modelCopy;
686
- }
687
- copy[provider] = models;
688
- }
689
- return copy;
690
- }
691
- function accumulateCost(st, time, usage) {
692
- const model = st.model;
693
- if (model === void 0) return;
694
- st.cost = addBilledUsage(st.cost, st.provider ?? "", model, time, usage);
695
- }
696
- const TOOL_TIMING_CAP = 16;
697
- const DECODE_KINDS = [
698
- "reasoning",
699
- "text",
700
- "toolarg"
701
- ];
702
- function durOf(from, to) {
703
- if (!Number.isFinite(from) || !Number.isFinite(to)) return 0;
704
- return Math.max(0, to - from);
705
- }
706
- function ensureTiming(st) {
707
- if (st.timing === void 0) st.timing = {
708
- wallMs: 0,
709
- ttftMs: 0,
710
- genMs: 0,
711
- calls: 0,
712
- toolsMs: 0,
713
- toolCalls: 0,
714
- tools: {}
715
- };
716
- return st.timing;
717
- }
718
- const DECODE_FIELDS = {
719
- reasoning: {
720
- ms: "reasoningMs",
721
- n: "reasoningBlocks"
722
- },
723
- text: {
724
- ms: "textMs",
725
- n: "textBlocks"
726
- },
727
- toolarg: {
728
- ms: "toolArgMs",
729
- n: "toolArgBlocks"
730
- }
731
- };
732
- function addDecode(timing, kind, ms, blocks) {
733
- const field = DECODE_FIELDS[kind];
734
- if (ms > 0) timing[field.ms] = (timing[field.ms] ?? 0) + ms;
735
- if (blocks > 0) timing[field.n] = (timing[field.n] ?? 0) + blocks;
736
- }
737
- function bumpToolTotals(timing, name, ms) {
738
- if (name === "__proto__") return;
739
- if (!Object.hasOwn(timing.tools, name)) {
740
- if (Object.keys(timing.tools).length >= TOOL_TIMING_CAP) {
741
- let minKey = "";
742
- let minMs = Infinity;
743
- for (const k in timing.tools) if (timing.tools[k].ms < minMs) {
744
- minMs = timing.tools[k].ms;
745
- minKey = k;
746
- }
747
- const kept = {};
748
- for (const k in timing.tools) if (k !== minKey) kept[k] = timing.tools[k];
749
- timing.tools = kept;
750
- }
751
- timing.tools[name] = {
752
- calls: 1,
753
- ms
754
- };
755
- return;
756
- }
757
- const cur = timing.tools[name];
758
- timing.tools[name] = {
759
- calls: cur.calls + 1,
760
- ms: cur.ms + ms
761
- };
762
- }
763
- //#endregion
764
- //#region src/host/foldWire.ts
765
- function headFieldsOf(state) {
766
- const surfaceTotal = state.sums.user + state.sums.inject + state.sums.skill + state.sums.assistant + state.sums.tool;
767
- const result = {
768
- ok: true,
769
- ...state.model !== void 0 ? { model: state.model } : {},
770
- ...state.provider !== void 0 ? { provider: state.provider } : {},
771
- ...state.contextWindow !== void 0 ? { contextWindow: state.contextWindow } : {},
772
- ...state.maxOutputTokens !== void 0 ? { maxOutputTokens: state.maxOutputTokens } : {},
773
- current: {
774
- system: state.systemTokens,
775
- tools: state.toolsTokens,
776
- user: state.sums.user,
777
- inject: state.sums.inject,
778
- skill: state.sums.skill,
779
- assistant: state.sums.assistant,
780
- tool: state.sums.tool,
781
- total: surfaceTotal + state.systemTokens + state.toolsTokens
782
- },
783
- images: state.surface.reduce((n, node) => n + (node.imgs ?? 0), 0),
784
- toolCalls: state.surface.reduce((n, node) => node.cat === "tool" || node.cat === "skill" && node.tool !== void 0 ? n + 1 : n, 0),
785
- humanInputs: state.humanInputs ?? 0,
786
- answers: state.answers ?? 0,
787
- ...state.lastUser !== void 0 ? { lastUser: state.lastUser } : {},
788
- requests: [],
789
- events: [],
790
- nodes: [],
791
- droppedNodes: 0,
792
- archive: []
793
- };
794
- if (state.cost !== void 0) result.cost = copyCostUsage(state.cost);
795
- if (state.timing !== void 0) {
796
- const tools = {};
797
- for (const k in state.timing.tools) tools[k] = { ...state.timing.tools[k] };
798
- result.timing = {
799
- ...state.timing,
800
- tools
801
- };
802
- }
803
- if (state.systems !== void 0 && state.systems.length > 0) result.systems = state.systems.map((n) => ({ ...n }));
804
- return result;
805
- }
806
- function detailCollectionsOf(state, bounds) {
807
- const result = {
808
- requests: state.requests.map((r) => ({ ...r })),
809
- events: state.events.map((e) => ({ ...e })),
810
- nodes: [],
811
- droppedNodes: 0,
812
- archive: state.archived.map((n) => ({ ...n })),
813
- fileOps: state.fileOps.map((o) => ({ ...o })),
814
- ...state.fileOpsFloor !== void 0 ? { fileOpsFloor: state.fileOpsFloor } : {},
815
- spans: state.spans.map((s) => ({ ...s }))
816
- };
817
- const overflowCount = Math.max(0, state.surface.length - bounds.maxNodes);
818
- const overflow = state.surface.slice(0, overflowCount);
819
- const tail = state.surface.slice(overflowCount);
820
- const pinned = overflow.filter((n) => n.cat === "inject" || n.cat === "skill");
821
- result.nodes = pinned.length > 0 ? [...pinned, ...tail] : tail;
822
- result.droppedNodes = overflowCount - pinned.length;
823
- if (result.droppedNodes > 0) {
824
- let floor = 0;
825
- for (const n of overflow) if (n.cat !== "inject" && n.cat !== "skill") floor = Math.max(floor, n.seq);
826
- result.surfaceFloor = floor;
827
- }
828
- if (state.archiveFloor !== void 0) result.archiveFloor = state.archiveFloor;
829
- const requests = result.requests;
830
- const events = result.events;
831
- let ri = 0;
832
- for (const ev of events) {
833
- while (ri < requests.length && requests[ri].seq <= ev.seq) ri++;
834
- const next = requests.at(ri);
835
- const prev = ri > 0 ? requests.at(ri - 1) : void 0;
836
- if (next !== void 0 && typeof next.turn === "number" && typeof next.step === "number") {
837
- ev.turn = next.turn;
838
- ev.step = next.step;
839
- }
840
- if (prev !== void 0 && typeof prev.turn === "number" && typeof prev.step === "number") {
841
- ev.fromTurn = prev.turn;
842
- ev.fromStep = prev.step;
843
- }
844
- }
845
- return result;
846
- }
847
- function buildTimelineHead(state) {
848
- const result = headFieldsOf(state);
849
- const turns = new Set();
850
- for (const r of state.requests) turns.add(r.turn ?? 0);
851
- let injects = 0;
852
- let compactions = 0;
853
- let prunes = 0;
854
- const skills = new Set();
855
- for (const e of state.events) {
856
- if (e.kind === "inject") injects++;
857
- else if (e.kind === "compaction") compactions++;
858
- else if (e.kind === "prune") prunes++;
859
- if (e.sub === "skill" && typeof e.name === "string" && e.name !== "") skills.add(e.name);
860
- }
861
- result.counts = {
862
- turns: turns.size,
863
- steps: state.requests.length,
864
- injects,
865
- compactions,
866
- prunes,
867
- skills: skills.size
868
- };
869
- const last = state.requests.at(-1);
870
- if (last !== void 0) result.last = {
871
- seq: last.seq,
872
- total: last.total,
873
- ...typeof last.prompt === "number" ? { prompt: last.prompt } : {}
874
- };
875
- result.detailRev = state.detailRev ?? 0;
876
- return result;
877
- }
878
- function buildTimelineDetail(state, bounds) {
879
- return {
880
- rev: state.detailRev ?? 0,
881
- head: buildTimelineHead(state),
882
- ...detailCollectionsOf(state, bounds)
883
- };
884
- }
885
- function buildTimelineView(state, bounds) {
886
- return {
887
- ...headFieldsOf(state),
888
- ...detailCollectionsOf(state, bounds)
889
- };
890
- }
891
- //#endregion
892
- //#region src/host/fold.ts
893
- function categoryOf(type, message) {
894
- if (type === "assistant/message") return "assistant";
895
- if (type === "tool/result") return "tool";
896
- if (type === "developer/message") return "inject";
897
- const kind = message?.source?.kind;
898
- if (kind === "skill-invocation" || kind === "skill-catalog") return "skill";
899
- if (isInjection(message?.source)) return "inject";
900
- return "user";
901
- }
902
- function bumpDetailRev(st) {
903
- st.detailRev = (st.detailRev ?? 0) + 1;
904
- }
905
- const SYSTEM_NODES_MAX = 8;
906
- function systemTokensOf(systems) {
907
- for (let i = systems.length - 1; i >= 0; i--) if (systems[i].tokens > 0) return systems[i].tokens;
908
- return 0;
909
- }
910
- function pushSystem(st, node) {
911
- const systems = [...st.systems ?? [], node];
912
- st.systems = systems.length > SYSTEM_NODES_MAX ? systems.slice(-8) : systems;
913
- st.systemTokens = systemTokensOf(st.systems);
914
- }
915
- const PENDING_CODE_OPS_MAX = 200;
916
- function argsRawOf(value) {
917
- if (typeof value === "string") return value;
918
- if (value === void 0 || value === null) return void 0;
919
- try {
920
- return JSON.stringify(value);
921
- } catch {
922
- return;
923
- }
924
- }
925
- function pushFileOps(st, ops) {
926
- for (const op of ops) st.fileOps.push(op);
927
- }
928
- function bufferCodeOps(st, rootCallId, ops) {
929
- const pending = st.pendingCodeOps ?? {};
930
- let total = 0;
931
- for (const k in pending) total += pending[k].length;
932
- if (total + ops.length > PENDING_CODE_OPS_MAX) return;
933
- st.pendingCodeOps = {
934
- ...pending,
935
- [rootCallId]: [...pending[rootCallId] ?? [], ...ops]
936
- };
937
- }
938
- function archiveRemoved(st, removed, goneSeq) {
939
- for (const n of removed) st.archived.push({
940
- ...n,
941
- gone: goneSeq
942
- });
943
- }
944
- function removeSurfaceSeqs(st, claimed, goneSeq) {
945
- if (claimed.size === 0) return [];
946
- const kept = [];
947
- const removed = [];
948
- for (const n of st.surface) if (claimed.has(n.seq)) {
949
- st.sums[n.cat] -= n.tokens;
950
- removed.push(n);
951
- } else kept.push(n);
952
- archiveRemoved(st, removed, goneSeq);
953
- st.surface = kept;
954
- return removed;
955
- }
956
- function messageOf$2(data) {
957
- const message = data?.message;
958
- return message !== null && typeof message === "object" ? message : null;
959
- }
960
- function firstFullText(blocks) {
961
- if (!Array.isArray(blocks)) return "";
962
- for (const item of blocks) {
963
- if (item === null || typeof item !== "object") continue;
964
- const block = item;
965
- if (block.type === "text" && typeof block.text === "string" && block.text !== "") return block.text;
966
- }
967
- return "";
968
- }
969
- function skillNameOf(msg) {
970
- const match = firstFullText(msg !== null && typeof msg === "object" ? msg.content : void 0).match(/<skill_content\s+name="([^"]+)"/);
971
- return match === null ? "" : match[1];
972
- }
973
- function applySurface(st, ev, type, message) {
974
- const cat = categoryOf(type, message ?? void 0);
975
- const node = {
976
- seq: ev.seq,
977
- time: ev.time,
978
- cat,
979
- tokens: estimateMessage(message, type === "assistant/message" || type === "developer/message")
980
- };
981
- const imgs = imageCountOf(message?.content);
982
- if (imgs > 0) node.imgs = imgs;
983
- const source = message?.source;
984
- const form = source?.form;
985
- if (typeof form === "string") node.form = form;
986
- if (type === "assistant/message") {
987
- const text = firstText(message?.content);
988
- if (text !== "") node.text = text;
989
- else {
990
- const names = toolCallNames(message?.content);
991
- if (names.length > 0) node.calls = names.slice(0, 3);
992
- }
993
- } else if (type === "tool/result") {
994
- const srcId = source?.callId;
995
- const toolEntry = typeof srcId === "string" ? st.callNames[srcId] : void 0;
996
- if (toolEntry !== void 0) {
997
- node.tool = toolEntry.name;
998
- const timing = ensureTiming(st);
999
- const dur = durOf(toolEntry.start, ev.time);
1000
- timing.toolsMs += dur;
1001
- timing.toolCalls += 1;
1002
- bumpToolTotals(timing, toolEntry.name, dur);
1003
- if (st.stepStart !== void 0) st.stepSpans = [...st.stepSpans ?? [], {
1004
- kind: "tools",
1005
- start: toolEntry.start,
1006
- end: ev.time
1007
- }];
1008
- }
1009
- if (typeof srcId === "string") {
1010
- const kept = {};
1011
- for (const k in st.callNames) if (k !== srcId) kept[k] = st.callNames[k];
1012
- st.callNames = kept;
1013
- }
1014
- if (message?.isError === true) node.err = true;
1015
- } else if (source?.kind === "skill-invocation") node.skill = typeof source.name === "string" ? source.name : "?";
1016
- else if (source?.kind === "plugin") {
1017
- if (source.form === "notice" && typeof source.summary === "string") node.text = source.summary;
1018
- else if (source.form === "snapshot" && Array.isArray(source.sections)) node.text = source.sections.map((s) => s?.name).filter(Boolean).join(", ").slice(0, 80);
1019
- else {
1020
- const ptext = firstText(message?.content);
1021
- if (ptext !== "") node.text = ptext;
1022
- }
1023
- } else {
1024
- const utext = firstText(message?.content);
1025
- if (utext !== "") node.text = utext;
1026
- }
1027
- const shadowedSeqs = st.pendingShadowedSeqs;
1028
- const shadowEventSeq = st.pendingShadowEventSeq;
1029
- delete st.pendingShadowedSeqs;
1030
- delete st.pendingShadowEventSeq;
1031
- const op = replaceRangeOf(ev.surfaceOp);
1032
- if (op !== null) {
1033
- if (Array.isArray(shadowedSeqs) && shadowedSeqs.length > 0) {
1034
- const removed = removeSurfaceSeqs(st, new Set(shadowedSeqs), ev.seq);
1035
- st.sums[cat] += node.tokens;
1036
- st.surface.push(node);
1037
- if (shadowEventSeq !== void 0) {
1038
- const removedSum = removed.reduce((sum, n) => sum + n.tokens, 0);
1039
- const i = st.events.findIndex((e) => e.seq === shadowEventSeq);
1040
- if (i >= 0) st.events[i] = {
1041
- ...st.events[i],
1042
- tokens: Math.max(0, removedSum - node.tokens)
1043
- };
1044
- }
1045
- return node;
1046
- }
1047
- let si = -1;
1048
- let ei = -1;
1049
- for (let i = 0; i < st.surface.length; i++) {
1050
- if (si < 0 && st.surface[i].seq === op.start) si = i;
1051
- if (st.surface[i].seq === op.end) {
1052
- ei = i;
1053
- break;
1054
- }
1055
- }
1056
- if (si >= 0 && ei >= si) {
1057
- const removed = st.surface.splice(si, ei - si + 1, node);
1058
- archiveRemoved(st, removed, ev.seq);
1059
- for (const r of removed) st.sums[r.cat] -= r.tokens;
1060
- st.sums[cat] += node.tokens;
1061
- return node;
1062
- }
1063
- }
1064
- st.surface.push(node);
1065
- st.sums[cat] += node.tokens;
1066
- return node;
1067
- }
1068
- const ASK_USER_TOOL = "ask_user_question";
1069
- const CLONE_ALL = [
1070
- "surface",
1071
- "sums",
1072
- "requests",
1073
- "events",
1074
- "archived",
1075
- "callNames",
1076
- "fileOps",
1077
- "timing"
1078
- ];
1079
- function applyTimeline(state, event, bounds) {
1080
- let st;
1081
- const ensure = (keys = CLONE_ALL) => {
1082
- st = { ...state };
1083
- for (const key of keys) if (key === "surface") st.surface = [...state.surface];
1084
- else if (key === "sums") st.sums = { ...state.sums };
1085
- else if (key === "requests") st.requests = [...state.requests];
1086
- else if (key === "events") st.events = [...state.events];
1087
- else if (key === "archived") st.archived = [...state.archived];
1088
- else if (key === "callNames") st.callNames = { ...state.callNames };
1089
- else if (key === "fileOps") st.fileOps = [...state.fileOps];
1090
- else if (state.timing !== void 0) st.timing = {
1091
- ...state.timing,
1092
- tools: { ...state.timing.tools }
1093
- };
1094
- return st;
1095
- };
1096
- const data = event.data;
1097
- try {
1098
- switch (event.type) {
1099
- case "request/header": {
1100
- const header = data?.header ?? {};
1101
- const tools = Array.isArray(header.tools) ? header.tools : [];
1102
- const s = ensure(["events"]);
1103
- s.toolsTokens = estimateToolsTotal(tools);
1104
- if (header.config && typeof header.config.model === "string") s.model = header.config.model;
1105
- if (header.config && typeof header.config.provider === "string") s.provider = header.config.provider;
1106
- const maxOutputTokens = header.config?.maxTokens;
1107
- if (typeof maxOutputTokens === "number" && Number.isFinite(maxOutputTokens) && maxOutputTokens > 0) s.maxOutputTokens = maxOutputTokens;
1108
- else delete s.maxOutputTokens;
1109
- if ((data?.reason === "change" || data?.reason === "resume") && s.model && s.lastModel && s.model !== s.lastModel) {
1110
- s.events.push({
1111
- seq: event.seq,
1112
- time: event.time,
1113
- kind: "model",
1114
- from: s.lastModel,
1115
- to: s.model
1116
- });
1117
- bumpDetailRev(s);
1118
- }
1119
- if (s.model) s.lastModel = s.model;
1120
- break;
1121
- }
1122
- case "system/message": {
1123
- const s = ensure([
1124
- "surface",
1125
- "sums",
1126
- "archived"
1127
- ]);
1128
- delete s.pendingShadowedSeqs;
1129
- delete s.pendingShadowEventSeq;
1130
- const op = replaceRangeOf(event.surfaceOp);
1131
- if (op !== null) {
1132
- s.systems = (s.systems ?? []).filter((n) => n.seq < op.start || n.seq > op.end);
1133
- const claimed = new Set();
1134
- for (const n of s.surface) if (n.seq >= op.start && n.seq <= op.end) claimed.add(n.seq);
1135
- if (removeSurfaceSeqs(s, claimed, event.seq).length > 0) bumpDetailRev(s);
1136
- }
1137
- pushSystem(s, {
1138
- seq: event.seq,
1139
- time: event.time,
1140
- tokens: estimateSystemContent(messageOf$2(data)?.content)
1141
- });
1142
- break;
1143
- }
1144
- case "request/context": {
1145
- const s = ensure([]);
1146
- if (data && typeof data.contextWindow === "number") s.contextWindow = data.contextWindow;
1147
- if (data && typeof data.model === "string") s.model = data.model;
1148
- if (data && typeof data.provider === "string") s.provider = data.provider;
1149
- break;
1150
- }
1151
- case "tool/call":
1152
- if (data && typeof data.callId === "string" && typeof data.name === "string") {
1153
- const s = ensure(["callNames"]);
1154
- const argsRaw = rawArgsNeeded(data.name) ? argsRawOf(data.arguments) : void 0;
1155
- s.callNames[data.callId] = {
1156
- name: data.name,
1157
- start: event.time,
1158
- ...argsRaw !== void 0 ? { argsRaw } : {}
1159
- };
1160
- }
1161
- break;
1162
- case "tool/ptc-dispatch": {
1163
- const rootCallId = data?.rootCallId;
1164
- const name = data?.name;
1165
- if (typeof rootCallId === "string" && typeof name === "string") {
1166
- const argsRaw = opBearingTool(name) ? argsRawOf(data?.arguments) : void 0;
1167
- const ops = opsOfCall({
1168
- seq: event.seq,
1169
- time: event.time,
1170
- tool: name,
1171
- argsRaw,
1172
- err: data?.isError === true
1173
- });
1174
- if (ops.length > 0) bufferCodeOps(ensure([]), rootCallId, ops);
1175
- }
1176
- break;
1177
- }
1178
- case "assistant/attempt": {
1179
- const start = state.stepStart;
1180
- if (start === void 0 || start.firstToken !== void 0) return state;
1181
- const first = firstTokenTimeOfStream(data?.stream);
1182
- if (first === void 0) return state;
1183
- const s = ensure([]);
1184
- s.stepStart = {
1185
- time: start.time,
1186
- firstToken: first
1187
- };
1188
- break;
1189
- }
1190
- case "step/start": {
1191
- const s = ensure([]);
1192
- s.stepStart = { time: event.time };
1193
- delete s.stepSpans;
1194
- delete s.stepWaits;
1195
- delete s.stepApprovals;
1196
- delete s.stepRequestSeq;
1197
- break;
1198
- }
1199
- case "step/end": {
1200
- const start = state.stepStart;
1201
- if (start === void 0) return state;
1202
- const s = ensure(state.stepRequestSeq !== void 0 ? ["timing", "requests"] : ["timing"]);
1203
- ensureTiming(s).wallMs += durOf(start.time, event.time);
1204
- const waits = [...state.stepWaits ?? []];
1205
- for (const id in state.stepApprovals) waits.push({
1206
- start: state.stepApprovals[id],
1207
- end: event.time
1208
- });
1209
- waits.sort((a, b) => a.start - b.start || a.end - b.end);
1210
- let waitMs = 0;
1211
- let waitCursor = start.time;
1212
- for (const wait of waits) {
1213
- const from = Math.max(waitCursor, wait.start);
1214
- const to = Math.min(wait.end, event.time);
1215
- if (to > from) {
1216
- waitMs += to - from;
1217
- waitCursor = to;
1218
- }
1219
- }
1220
- const activeMs = durOf(start.time, event.time) - waitMs;
1221
- const last = state.requests.at(-1);
1222
- if (last !== void 0 && last.seq === state.stepRequestSeq) s.requests[s.requests.length - 1] = {
1223
- ...last,
1224
- activeMs
1225
- };
1226
- const painted = [];
1227
- for (const span of state.stepSpans ?? []) {
1228
- const from = Math.max(start.time, span.start);
1229
- const to = Math.min(event.time, span.end);
1230
- if (to > from) painted.push({
1231
- kind: span.kind,
1232
- start: from,
1233
- end: to
1234
- });
1235
- }
1236
- painted.sort((a, b) => a.start - b.start || a.end - b.end);
1237
- const flushed = [];
1238
- let cursor = start.time;
1239
- for (const span of painted) {
1240
- const from = Math.max(cursor, span.start);
1241
- if (span.end <= from) continue;
1242
- if (from > cursor) flushed.push({
1243
- kind: "other",
1244
- start: cursor,
1245
- end: from
1246
- });
1247
- flushed.push({
1248
- kind: span.kind,
1249
- start: from,
1250
- end: span.end
1251
- });
1252
- cursor = span.end;
1253
- }
1254
- if (event.time > cursor) flushed.push({
1255
- kind: "other",
1256
- start: cursor,
1257
- end: event.time
1258
- });
1259
- s.spans = [...state.spans, ...flushed];
1260
- delete s.stepStart;
1261
- delete s.stepSpans;
1262
- delete s.stepWaits;
1263
- delete s.stepApprovals;
1264
- delete s.stepRequestSeq;
1265
- bumpDetailRev(s);
1266
- break;
1267
- }
1268
- case "approval/asked": {
1269
- const id = data?.id;
1270
- if (state.stepStart === void 0 || typeof id !== "string") return state;
1271
- const s = ensure([]);
1272
- s.stepApprovals = {
1273
- ...state.stepApprovals,
1274
- [id]: event.time
1275
- };
1276
- break;
1277
- }
1278
- case "approval/decided": {
1279
- const id = data?.id;
1280
- const open = state.stepApprovals;
1281
- const askedAt = typeof id === "string" ? open?.[id] : void 0;
1282
- if (open === void 0 || askedAt === void 0) return state;
1283
- const s = ensure([]);
1284
- s.stepWaits = [...state.stepWaits ?? [], {
1285
- start: askedAt,
1286
- end: event.time
1287
- }];
1288
- const kept = {};
1289
- for (const k in open) if (k !== id) kept[k] = open[k];
1290
- if (Object.keys(kept).length > 0) s.stepApprovals = kept;
1291
- else delete s.stepApprovals;
1292
- break;
1293
- }
1294
- case "user/message":
1295
- case "developer/message": {
1296
- const developer = event.type === "developer/message";
1297
- const msg = developer ? messageOf$2(data) : deriveEventMessage(event);
1298
- if (developer && (msg === null || !Array.isArray(msg.content))) return state;
1299
- const s = ensure([
1300
- "surface",
1301
- "sums",
1302
- "archived",
1303
- "events"
1304
- ]);
1305
- bumpDetailRev(s);
1306
- const node = applySurface(s, event, event.type, msg);
1307
- const source = msg?.source;
1308
- if (developer || isInjection(source)) {
1309
- const rec = {
1310
- seq: event.seq,
1311
- time: event.time,
1312
- kind: "inject",
1313
- form: typeof source?.form === "string" && source.form !== "" ? source.form : "context",
1314
- tokens: node.tokens
1315
- };
1316
- if (source?.kind === "skill-invocation") {
1317
- rec.sub = "skill";
1318
- rec.name = typeof source.name === "string" ? source.name : "?";
1319
- } else {
1320
- const label = injectionSourceName(source);
1321
- if (label !== "") {
1322
- rec.name = label;
1323
- node.name = label;
1324
- }
1325
- if (source?.form === "notice" && typeof source.summary === "string" && source.summary !== "") rec.detail = source.summary;
1326
- }
1327
- s.events.push(rec);
1328
- } else {
1329
- s.humanInputs = (s.humanInputs ?? 0) + 1;
1330
- if (node.text !== void 0 && node.text !== "") s.lastUser = node.text;
1331
- }
1332
- break;
1333
- }
1334
- case "tool/result": {
1335
- const toolMsg = deriveEventMessage(event);
1336
- const srcId = (toolMsg?.source)?.callId;
1337
- const pendingEntry = typeof srcId === "string" ? state.callNames[srcId] : void 0;
1338
- const buffered = typeof srcId === "string" ? state.pendingCodeOps?.[srcId] : void 0;
1339
- const s = ensure([
1340
- "surface",
1341
- "sums",
1342
- "archived",
1343
- "events",
1344
- "fileOps",
1345
- "timing"
1346
- ]);
1347
- bumpDetailRev(s);
1348
- const node = applySurface(s, event, event.type, toolMsg);
1349
- if (node.tool === ASK_USER_TOOL) s.humanInputs = (s.humanInputs ?? 0) + 1;
1350
- if (pendingEntry !== void 0 && pendingEntry.name === ASK_USER_TOOL && state.stepStart !== void 0) s.stepWaits = [...state.stepWaits ?? [], {
1351
- start: pendingEntry.start,
1352
- end: event.time
1353
- }];
1354
- if (pendingEntry !== void 0) pushFileOps(s, opsOfCall({
1355
- seq: event.seq,
1356
- time: event.time,
1357
- tool: pendingEntry.name,
1358
- argsRaw: pendingEntry.argsRaw,
1359
- meta: data?.meta,
1360
- err: toolMsg?.isError === true
1361
- }));
1362
- if (buffered !== void 0 && buffered.length > 0) {
1363
- const program = parseCallArgs(pendingEntry?.argsRaw)?.description;
1364
- pushFileOps(s, buffered.map((op) => ({
1365
- ...op,
1366
- parent: event.seq,
1367
- ...typeof program === "string" && program !== "" ? { program } : {}
1368
- })));
1369
- const kept = {};
1370
- for (const k in s.pendingCodeOps) if (k !== srcId) kept[k] = s.pendingCodeOps[k];
1371
- if (Object.keys(kept).length > 0) s.pendingCodeOps = kept;
1372
- else delete s.pendingCodeOps;
1373
- }
1374
- if (node.tool === "skill" || node.tool === void 0) {
1375
- const name = skillNameOf(toolMsg);
1376
- if (name !== "") {
1377
- node.skill = name;
1378
- if (node.tool === void 0) node.tool = "skill";
1379
- s.sums.tool -= node.tokens;
1380
- node.cat = "skill";
1381
- s.sums.skill += node.tokens;
1382
- s.events.push({
1383
- seq: event.seq,
1384
- time: event.time,
1385
- kind: "inject",
1386
- form: "instructions",
1387
- sub: "skill",
1388
- name,
1389
- tokens: node.tokens
1390
- });
1391
- }
1392
- }
1393
- break;
1394
- }
1395
- case "assistant/message": {
1396
- const usage = data?.usage;
1397
- const s = ensure([
1398
- "surface",
1399
- "sums",
1400
- "archived",
1401
- "events",
1402
- "requests",
1403
- "timing"
1404
- ]);
1405
- bumpDetailRev(s);
1406
- const total = s.systemTokens + s.toolsTokens + s.sums.user + s.sums.inject + s.sums.skill + s.sums.assistant + s.sums.tool;
1407
- const record = {
1408
- time: event.time,
1409
- seq: event.seq,
1410
- system: s.systemTokens,
1411
- tools: s.toolsTokens,
1412
- user: s.sums.user,
1413
- inject: s.sums.inject,
1414
- skill: s.sums.skill,
1415
- assistant: s.sums.assistant,
1416
- tool: s.sums.tool,
1417
- total
1418
- };
1419
- if (data && typeof data.turn === "number") record.turn = data.turn;
1420
- if (data && typeof data.step === "number") record.step = data.step;
1421
- if (state.stepStart !== void 0) s.stepRequestSeq = record.seq;
1422
- let output = null;
1423
- if (usage !== null && typeof usage === "object") {
1424
- const input = tokenCountOf(usage.inputTokens);
1425
- const cacheRead = tokenCountOf(usage.cacheReadTokens);
1426
- const cacheWrite = tokenCountOf(usage.cacheWriteTokens);
1427
- output = tokenCountOf(usage.outputTokens);
1428
- if (input !== null || cacheRead !== null || cacheWrite !== null || output !== null) {
1429
- record.prompt = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
1430
- if (cacheRead !== null) record.cacheRead = cacheRead;
1431
- if (output !== null) record.output = output;
1432
- accumulateCost(s, event.time, {
1433
- uncached: input ?? 0,
1434
- cacheRead: cacheRead ?? 0,
1435
- cacheWrite: cacheWrite ?? 0,
1436
- output: output ?? 0
1437
- });
1438
- }
1439
- }
1440
- s.requests.push(record);
1441
- const prevLast = state.requests.at(-1);
1442
- s.turnRuns = (state.turnRuns ?? countTurnRuns(state.requests)) + (prevLast === void 0 ? record.turn !== void 0 ? 1 : 0 : record.turn === prevLast.turn ? 0 : 1);
1443
- const timing = ensureTiming(s);
1444
- timing.calls += 1;
1445
- const stepStart = state.stepStart;
1446
- if (stepStart !== void 0) {
1447
- const firstToken = stepStart.firstToken ?? firstTokenTimeOfStream(data?.stream);
1448
- if (firstToken !== void 0) {
1449
- const decodeBlocks = decodeSpansOfStream(data?.stream, event.time);
1450
- let decodeStart = firstToken;
1451
- for (const block of decodeBlocks) decodeStart = Math.min(decodeStart, block.start);
1452
- timing.ttftMs += durOf(stepStart.time, decodeStart);
1453
- timing.genMs += durOf(decodeStart, event.time);
1454
- const modelSpans = [{
1455
- kind: "ttft",
1456
- start: stepStart.time,
1457
- end: decodeStart
1458
- }];
1459
- for (const block of decodeBlocks) {
1460
- const to = Math.min(event.time, block.end);
1461
- if (to <= block.start) continue;
1462
- modelSpans.push({
1463
- kind: block.kind,
1464
- start: modelSpans.length === 1 ? decodeStart : block.start,
1465
- end: to
1466
- });
1467
- }
1468
- s.stepSpans = [...s.stepSpans ?? [], ...modelSpans];
1469
- if (output !== null) {
1470
- timing.speedMs = (timing.speedMs ?? 0) + durOf(firstToken, event.time);
1471
- timing.speedTokens = (timing.speedTokens ?? 0) + output;
1472
- }
1473
- const tally = decodeTallyOfStream(data?.stream, event.time);
1474
- for (const kind of DECODE_KINDS) addDecode(timing, kind, tally.spans[kind], tally.blocks[kind]);
1475
- }
1476
- }
1477
- const asstMsg = deriveEventMessage(event);
1478
- if (applySurface(s, event, event.type, asstMsg).text !== void 0) s.answers = (s.answers ?? 0) + 1;
1479
- break;
1480
- }
1481
- case "session/end-seed": {
1482
- if (data?.inherited !== true) break;
1483
- const s = ensure([]);
1484
- s.cost = {};
1485
- break;
1486
- }
1487
- case "plan/mode":
1488
- if (data && typeof data.active === "boolean") {
1489
- const s = ensure(["events"]);
1490
- s.events.push({
1491
- seq: event.seq,
1492
- time: event.time,
1493
- kind: "mode",
1494
- name: data.active ? "plan.on" : "plan.off"
1495
- });
1496
- bumpDetailRev(s);
1497
- }
1498
- break;
1499
- case "compaction/summary":
1500
- case "compaction/prune": {
1501
- const s = ensure(["events"]);
1502
- bumpDetailRev(s);
1503
- if (data && Array.isArray(data.shadowedSeqs)) {
1504
- s.pendingShadowedSeqs = data.shadowedSeqs.filter((x) => typeof x === "number");
1505
- s.pendingShadowEventSeq = event.seq;
1506
- }
1507
- s.events.push({
1508
- seq: event.seq,
1509
- time: event.time,
1510
- kind: event.type === "compaction/summary" ? "compaction" : "prune",
1511
- tokens: data && typeof data.shadowedTokenCount === "number" ? data.shadowedTokenCount : 0,
1512
- ...event.type === "compaction/summary" && data && Array.isArray(data.shadowedSeqs) ? { count: data.shadowedSeqs.length } : {}
1513
- });
1514
- break;
1515
- }
1516
- default: return state;
1517
- }
1518
- } catch {
1519
- st = void 0;
1520
- }
1521
- if (st !== void 0) {
1522
- trimState(st, bounds);
1523
- return st;
1524
- }
1525
- return state;
1526
- }
1527
- //#endregion
1528
- //#region src/host/config.ts
1529
- const DEFAULT_BOUNDS = {
1530
- maxRequestSteps: 1500,
1531
- maxKeptTurns: 300,
1532
- maxEvents: 400,
1533
- maxNodes: 2e3,
1534
- maxArchiveNodes: 400,
1535
- maxFileOps: 400
1536
- };
1537
- function volatileField(field) {
1538
- const volatile = field.volatile;
1539
- return typeof volatile === "function" ? volatile.call(field) : field;
1540
- }
1541
- function count(defaultValue) {
1542
- return z$1.number().min(1).step(1).default(defaultValue);
1543
- }
1544
- const Config = z$1.object({
1545
- maxRequestSteps: count(DEFAULT_BOUNDS.maxRequestSteps),
1546
- maxKeptTurns: count(DEFAULT_BOUNDS.maxKeptTurns),
1547
- maxEvents: count(DEFAULT_BOUNDS.maxEvents),
1548
- maxNodes: count(DEFAULT_BOUNDS.maxNodes),
1549
- maxArchiveNodes: count(DEFAULT_BOUNDS.maxArchiveNodes),
1550
- maxFileOps: count(DEFAULT_BOUNDS.maxFileOps),
1551
- defaultPlacement: volatileField(z$1.union([
1552
- "all",
1553
- "tab",
1554
- "sidebar"
1555
- ]).default("all").loose()),
1556
- defaultGranularity: volatileField(z$1.union(["step", "turn"]).default("step").loose()),
1557
- defaultTrendMode: volatileField(z$1.union(["total", "delta"]).default("total").loose()),
1558
- defaultDeltaBase: volatileField(z$1.union(["step", "turn"]).default("step").loose()),
1559
- defaultToolSort: volatileField(z$1.union([
1560
- "size",
1561
- "count",
1562
- "name"
1563
- ]).default("count").loose()),
1564
- defaultFileSort: volatileField(z$1.union([
1565
- "count",
1566
- "latest",
1567
- "path"
1568
- ]).default("count").loose()),
1569
- insightsEntry: volatileField(z$1.union(["show", "hide"]).default("show").loose()),
1570
- defaultDurationCurve: volatileField(z$1.union(["show", "hide"]).default("show").loose()),
1571
- fleetTab: volatileField(z$1.union(["show", "hide"]).default("show").loose()),
1572
- promptPrefix: volatileField(z$1.string().default("").loose()),
1573
- promptSuffix: volatileField(z$1.string().default("").loose())
1574
- });
1575
- function resolveBounds(config) {
1576
- const resolved = Config(config ?? {});
1577
- return {
1578
- maxRequestSteps: resolved.maxRequestSteps,
1579
- maxKeptTurns: resolved.maxKeptTurns,
1580
- maxEvents: resolved.maxEvents,
1581
- maxNodes: resolved.maxNodes,
1582
- maxArchiveNodes: resolved.maxArchiveNodes,
1583
- maxFileOps: resolved.maxFileOps
1584
- };
1585
- }
1586
- //#endregion
1587
- //#region src/host/timeline.ts
1588
- const surfaceNodeSchema = z.object({
1589
- seq: z.number().int().nonnegative(),
1590
- time: z.number().optional(),
1591
- cat: z.enum([
1592
- "user",
1593
- "inject",
1594
- "skill",
1595
- "assistant",
1596
- "tool"
1597
- ]),
1598
- tokens: z.number().int().nonnegative(),
1599
- imgs: z.number().int().nonnegative().optional(),
1600
- gone: z.number().int().nonnegative().optional(),
1601
- form: z.string().optional(),
1602
- name: z.string().optional(),
1603
- text: z.string().optional(),
1604
- tool: z.string().optional(),
1605
- err: z.boolean().optional(),
1606
- skill: z.string().optional(),
1607
- calls: z.array(z.string()).optional()
1608
- }).strict();
1609
- const systemPromptNodeSchema = z.object({
1610
- seq: z.number().int().nonnegative(),
1611
- time: z.number(),
1612
- tokens: z.number().int().nonnegative()
1613
- }).strict();
1614
- const requestRecordSchema = z.object({
1615
- turn: z.number().optional(),
1616
- step: z.number().optional(),
1617
- time: z.number(),
1618
- seq: z.number(),
1619
- system: z.number().int().nonnegative(),
1620
- tools: z.number().int().nonnegative(),
1621
- user: z.number().int().nonnegative(),
1622
- inject: z.number().int().nonnegative(),
1623
- assistant: z.number().int().nonnegative(),
1624
- tool: z.number().int().nonnegative(),
1625
- total: z.number().int().nonnegative(),
1626
- prompt: z.number().int().nonnegative().optional(),
1627
- skill: z.number().int().nonnegative().optional(),
1628
- cacheRead: z.number().int().nonnegative().optional(),
1629
- output: z.number().int().nonnegative().optional(),
1630
- activeMs: z.number().nonnegative().optional(),
1631
- stepCount: z.number().int().positive().optional()
1632
- }).strict();
1633
- const contextEventSchema = z.object({
1634
- seq: z.number(),
1635
- time: z.number(),
1636
- kind: z.enum([
1637
- "compaction",
1638
- "prune",
1639
- "inject",
1640
- "model",
1641
- "mode"
1642
- ]),
1643
- form: z.string().optional(),
1644
- tokens: z.number().optional(),
1645
- count: z.number().optional(),
1646
- sub: z.string().optional(),
1647
- name: z.string().optional(),
1648
- detail: z.string().optional(),
1649
- from: z.string().optional(),
1650
- to: z.string().optional(),
1651
- fromTurn: z.number().optional(),
1652
- fromStep: z.number().optional(),
1653
- turn: z.number().optional(),
1654
- step: z.number().optional()
1655
- }).strict();
1656
- const fileOpSchema = z.object({
1657
- seq: z.number().int().nonnegative(),
1658
- path: z.string(),
1659
- kind: z.enum([
1660
- "read",
1661
- "write",
1662
- "search"
1663
- ]),
1664
- tool: z.string(),
1665
- time: z.number().optional(),
1666
- err: z.boolean(),
1667
- added: z.number().int().nonnegative(),
1668
- removed: z.number().int().nonnegative(),
1669
- detail: z.string().optional(),
1670
- hits: z.number().int().positive().optional(),
1671
- read: z.union([z.object({
1672
- start: z.number().int().positive(),
1673
- count: z.number().int().nonnegative()
1674
- }).strict(), z.object({
1675
- count: z.number().int().positive(),
1676
- est: z.literal(true)
1677
- }).strict()]).optional(),
1678
- parent: z.number().int().nonnegative().optional(),
1679
- program: z.string().optional(),
1680
- pattern: z.literal(true).optional(),
1681
- gone: z.number().int().nonnegative().optional()
1682
- }).strict();
1683
- const timingSpanSchema = z.object({
1684
- kind: z.enum([
1685
- "ttft",
1686
- "reasoning",
1687
- "text",
1688
- "toolarg",
1689
- "tools",
1690
- "other"
1691
- ]),
1692
- start: z.number(),
1693
- end: z.number()
1694
- }).strict();
1695
- const currentSchema = z.object({
1696
- system: z.number().int().nonnegative(),
1697
- tools: z.number().int().nonnegative(),
1698
- user: z.number().int().nonnegative(),
1699
- inject: z.number().int().nonnegative(),
1700
- skill: z.number().int().nonnegative(),
1701
- assistant: z.number().int().nonnegative(),
1702
- tool: z.number().int().nonnegative(),
1703
- total: z.number().int().nonnegative()
1704
- }).strict();
1705
- const costBucketsSchema = z.object({
1706
- uncached: z.number().int().nonnegative(),
1707
- cacheRead: z.number().int().nonnegative(),
1708
- cacheWrite: z.number().int().nonnegative(),
1709
- output: z.number().int().nonnegative()
1710
- }).strict();
1711
- const costModelSchema = z.object({
1712
- peak: costBucketsSchema.optional(),
1713
- off: costBucketsSchema.optional()
1714
- }).strict();
1715
- const costModelsSchema = z.record(z.string(), costModelSchema);
1716
- const costUsageSchema = z.record(z.string(), costModelsSchema);
1717
- const toolTimingSchema = z.object({
1718
- calls: z.number().int().nonnegative(),
1719
- ms: z.number().nonnegative()
1720
- }).strict();
1721
- const timingTotalsSchema = z.object({
1722
- wallMs: z.number().nonnegative(),
1723
- ttftMs: z.number().nonnegative(),
1724
- genMs: z.number().nonnegative(),
1725
- reasoningMs: z.number().nonnegative().optional(),
1726
- reasoningBlocks: z.number().int().nonnegative().optional(),
1727
- textMs: z.number().nonnegative().optional(),
1728
- textBlocks: z.number().int().nonnegative().optional(),
1729
- toolArgMs: z.number().nonnegative().optional(),
1730
- toolArgBlocks: z.number().int().nonnegative().optional(),
1731
- speedTokens: z.number().nonnegative().optional(),
1732
- speedMs: z.number().nonnegative().optional(),
1733
- calls: z.number().int().nonnegative(),
1734
- toolsMs: z.number().nonnegative(),
1735
- toolCalls: z.number().int().nonnegative(),
1736
- tools: z.record(z.string(), toolTimingSchema)
1737
- }).strict();
1738
- const unsupportedSchema = z.object({
1739
- current: z.string(),
1740
- minimum: z.string()
1741
- }).strict();
1742
- const countsSchema = z.object({
1743
- turns: z.number().int().nonnegative(),
1744
- steps: z.number().int().nonnegative(),
1745
- injects: z.number().int().nonnegative(),
1746
- compactions: z.number().int().nonnegative(),
1747
- prunes: z.number().int().nonnegative(),
1748
- skills: z.number().int().nonnegative().optional()
1749
- }).strict();
1750
- const lastSchema = z.object({
1751
- seq: z.number(),
1752
- total: z.number().int().nonnegative(),
1753
- prompt: z.number().int().nonnegative().optional()
1754
- }).strict();
1755
- const contextTimelineSchema = z.object({
1756
- ok: z.literal(true),
1757
- unsupported: unsupportedSchema.optional(),
1758
- model: z.string().optional(),
1759
- provider: z.string().optional(),
1760
- contextWindow: z.number().optional(),
1761
- maxOutputTokens: z.number().positive().optional(),
1762
- current: currentSchema,
1763
- images: z.number().int().nonnegative().optional(),
1764
- toolCalls: z.number().int().nonnegative().optional(),
1765
- humanInputs: z.number().int().nonnegative().optional(),
1766
- answers: z.number().int().nonnegative().optional(),
1767
- lastUser: z.string().optional(),
1768
- counts: countsSchema.optional(),
1769
- last: lastSchema.optional(),
1770
- detailRev: z.number().int().nonnegative().optional(),
1771
- requests: z.array(requestRecordSchema).optional(),
1772
- events: z.array(contextEventSchema).optional(),
1773
- cost: costUsageSchema.optional(),
1774
- timing: timingTotalsSchema.optional(),
1775
- systems: z.array(systemPromptNodeSchema).optional(),
1776
- nodes: z.array(surfaceNodeSchema).optional(),
1777
- droppedNodes: z.number().int().nonnegative().optional(),
1778
- archive: z.array(surfaceNodeSchema).optional(),
1779
- surfaceFloor: z.number().int().nonnegative().optional(),
1780
- archiveFloor: z.number().int().nonnegative().optional(),
1781
- fileOps: z.array(fileOpSchema).optional(),
1782
- fileOpsFloor: z.number().int().nonnegative().optional(),
1783
- spans: z.array(timingSpanSchema).optional()
1784
- }).strict();
1785
- const timelineStateSchema = z.object({
1786
- surface: z.array(surfaceNodeSchema),
1787
- sums: z.object({
1788
- user: z.number().int().nonnegative(),
1789
- inject: z.number().int().nonnegative(),
1790
- skill: z.number().int().nonnegative(),
1791
- assistant: z.number().int().nonnegative(),
1792
- tool: z.number().int().nonnegative()
1793
- }).strict(),
1794
- systemTokens: z.number().int().nonnegative(),
1795
- systems: z.array(systemPromptNodeSchema).optional(),
1796
- toolsTokens: z.number().int().nonnegative(),
1797
- model: z.string().optional(),
1798
- provider: z.string().optional(),
1799
- lastModel: z.string().optional(),
1800
- contextWindow: z.number().optional(),
1801
- maxOutputTokens: z.number().positive().optional(),
1802
- requests: z.array(requestRecordSchema),
1803
- turnRuns: z.number().int().nonnegative().optional(),
1804
- events: z.array(contextEventSchema),
1805
- archived: z.array(surfaceNodeSchema),
1806
- cost: costUsageSchema.optional(),
1807
- archiveFloor: z.number().optional(),
1808
- timing: timingTotalsSchema.optional(),
1809
- humanInputs: z.number().int().nonnegative().optional(),
1810
- answers: z.number().int().nonnegative().optional(),
1811
- lastUser: z.string().optional(),
1812
- stepStart: z.object({
1813
- time: z.number(),
1814
- firstToken: z.number().optional()
1815
- }).strict().optional(),
1816
- stepWaits: z.array(z.object({
1817
- start: z.number(),
1818
- end: z.number()
1819
- }).strict()).optional(),
1820
- stepApprovals: z.record(z.string(), z.number()).optional(),
1821
- stepRequestSeq: z.number().optional(),
1822
- callNames: z.record(z.string(), z.object({
1823
- name: z.string(),
1824
- start: z.number(),
1825
- argsRaw: z.string().optional()
1826
- }).strict()),
1827
- pendingShadowedSeqs: z.array(z.number()).optional(),
1828
- pendingShadowEventSeq: z.number().optional(),
1829
- detailRev: z.number().int().nonnegative().optional(),
1830
- fileOps: z.array(fileOpSchema),
1831
- fileOpsFloor: z.number().int().nonnegative().optional(),
1832
- spans: z.array(timingSpanSchema),
1833
- stepSpans: z.array(timingSpanSchema).optional(),
1834
- pendingCodeOps: z.record(z.string(), z.array(fileOpSchema)).optional()
1835
- });
1836
- function createContextTimelineDefinition(config, slim) {
1837
- const bounds = resolveBounds(config);
1838
- const view = (state) => slim() ? buildTimelineHead(state) : buildTimelineView(state, bounds);
1839
- return {
1840
- key: "contextTimeline",
1841
- stateSchema: timelineStateSchema,
1842
- wire: {
1843
- viewSchema: contextTimelineSchema,
1844
- view
1845
- },
1846
- init: () => createTimelineState(),
1847
- apply: (state, event) => applyTimeline(state, event, bounds),
1848
- stateVersion: 28
1849
- };
1850
- }
1851
- //#endregion
1852
- //#region src/shared/days.ts
1853
- function dayKeyOf(time) {
1854
- if (!Number.isFinite(time)) return null;
1855
- const d = new Date(time);
1856
- const y = d.getFullYear();
1857
- if (!Number.isFinite(y) || y < 1970 || y > 9999) return null;
1858
- return `${String(y).padStart(4, "0")}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
1859
- }
1860
- //#endregion
1861
- //#region src/host/activity.ts
1862
- const MAX_KEPT_DAYS = 400;
1863
- const MAX_SKILLS_PER_DAY = 100;
1864
- const activitySkillSchema = z.object({
1865
- n: z.number().int().nonnegative(),
1866
- last: z.number()
1867
- }).strict();
1868
- const activityDaySchema = z.object({
1869
- tokens: z.number().int().nonnegative(),
1870
- requests: z.number().int().nonnegative(),
1871
- cost: costUsageSchema.optional(),
1872
- skills: z.record(z.string(), activitySkillSchema).optional()
1873
- }).strict();
1874
- const contextActivitySchema = z.object({ days: z.record(z.string(), activityDaySchema) }).strict();
1875
- const activityStateSchema = z.object({
1876
- days: z.record(z.string(), activityDaySchema),
1877
- model: z.string().optional(),
1878
- provider: z.string().optional(),
1879
- stepStart: z.number().optional(),
1880
- skillCalls: z.array(z.string()).optional()
1881
- });
1882
- function billedBucketsOf(value) {
1883
- if (value === null || typeof value !== "object") return null;
1884
- const usage = value;
1885
- const input = tokenCountOf(usage.inputTokens);
1886
- const cacheRead = tokenCountOf(usage.cacheReadTokens);
1887
- const cacheWrite = tokenCountOf(usage.cacheWriteTokens);
1888
- const output = tokenCountOf(usage.outputTokens);
1889
- if (input === null && cacheRead === null && cacheWrite === null && output === null) return null;
1890
- return {
1891
- uncached: input ?? 0,
1892
- cacheRead: cacheRead ?? 0,
1893
- cacheWrite: cacheWrite ?? 0,
1894
- output: output ?? 0
1895
- };
1896
- }
1897
- function withDayEntry(state, key, entry) {
1898
- let days = {
1899
- ...state.days,
1900
- [key]: entry
1901
- };
1902
- const keys = Object.keys(days);
1903
- if (keys.length > MAX_KEPT_DAYS) {
1904
- keys.sort();
1905
- const drop = new Set(keys.slice(0, keys.length - MAX_KEPT_DAYS));
1906
- days = Object.fromEntries(Object.entries(days).filter(([k]) => !drop.has(k)));
1907
- }
1908
- return {
1909
- ...state,
1910
- days
1911
- };
1912
- }
1913
- function bookSkillLoad(state, name, time) {
1914
- const key = dayKeyOf(time);
1915
- if (key === null) return state;
1916
- const prev = state.days[key];
1917
- const existing = prev?.skills?.[name];
1918
- if (existing === void 0 && prev?.skills !== void 0 && Object.keys(prev.skills).length >= MAX_SKILLS_PER_DAY) return state;
1919
- const skills = {
1920
- ...prev?.skills,
1921
- [name]: {
1922
- n: (existing?.n ?? 0) + 1,
1923
- last: existing === void 0 ? time : Math.max(existing.last, time)
1924
- }
1925
- };
1926
- return withDayEntry(state, key, {
1927
- tokens: prev?.tokens ?? 0,
1928
- requests: prev?.requests ?? 0,
1929
- ...prev?.cost !== void 0 ? { cost: prev.cost } : {},
1930
- skills
1931
- });
1932
- }
1933
- function invokedSkillOf(event) {
1934
- const data = event.data;
1935
- const carrier = event.type === "developer/message" ? data?.message : data;
1936
- const source = carrier !== null && typeof carrier === "object" ? carrier.source : void 0;
1937
- if (source === null || typeof source !== "object") return "";
1938
- const rec = source;
1939
- return rec.kind === "skill-invocation" && typeof rec.name === "string" ? rec.name : "";
1940
- }
1941
- function toolResultCallIdOf(message) {
1942
- if (message === null || typeof message !== "object") return null;
1943
- const rec = message;
1944
- if (typeof rec.toolCallId === "string" && rec.toolCallId !== "") return rec.toolCallId;
1945
- const source = rec.source;
1946
- if (source === null || typeof source !== "object") return null;
1947
- const callId = source.callId;
1948
- return typeof callId === "string" && callId !== "" ? callId : null;
1949
- }
1950
- function applyActivity(state, event) {
1951
- if (event.type === "request/header") {
1952
- const config = event.data?.header?.config;
1953
- if (config === null || typeof config !== "object") return state;
1954
- const model = typeof config.model === "string" ? config.model : void 0;
1955
- const provider = typeof config.provider === "string" ? config.provider : void 0;
1956
- const nextModel = model !== void 0 ? model : state.model;
1957
- const nextProvider = provider !== void 0 ? provider : state.provider;
1958
- if (nextModel === state.model && nextProvider === state.provider) return state;
1959
- return {
1960
- ...state,
1961
- ...nextModel !== void 0 ? { model: nextModel } : {},
1962
- ...nextProvider !== void 0 ? { provider: nextProvider } : {}
1963
- };
1964
- }
1965
- if (event.type === "step/start") {
1966
- if (!Number.isFinite(event.time)) return state;
1967
- return state.stepStart === event.time ? state : {
1968
- ...state,
1969
- stepStart: event.time
1970
- };
1971
- }
1972
- if (event.type === "step/end") {
1973
- if (state.stepStart === void 0) return state;
1974
- const next = { ...state };
1975
- delete next.stepStart;
1976
- return next;
1977
- }
1978
- if (event.type === "session/end-seed") {
1979
- if (event.data?.inherited !== true) return state;
1980
- return { days: {} };
1981
- }
1982
- if (event.type === "user/message" || event.type === "developer/message") {
1983
- const name = invokedSkillOf(event);
1984
- return name === "" ? state : bookSkillLoad(state, name, event.time);
1985
- }
1986
- if (event.type === "tool/call") {
1987
- const data = event.data;
1988
- const callId = data?.callId;
1989
- if (data?.name !== "skill" || typeof callId !== "string" || callId === "") return state;
1990
- const pending = state.skillCalls ?? [];
1991
- if (pending.includes(callId)) return state;
1992
- return {
1993
- ...state,
1994
- skillCalls: [...pending, callId].slice(-100)
1995
- };
1996
- }
1997
- if (event.type === "tool/result") {
1998
- const message = event.data?.message;
1999
- const callId = toolResultCallIdOf(message);
2000
- const pending = state.skillCalls;
2001
- if (callId === null || pending === void 0 || !pending.includes(callId)) return state;
2002
- const skillCalls = pending.filter((id) => id !== callId);
2003
- const next = { ...state };
2004
- if (skillCalls.length > 0) next.skillCalls = skillCalls;
2005
- else delete next.skillCalls;
2006
- const name = skillNameOf(message);
2007
- return name === "" ? next : bookSkillLoad(next, name, event.time);
2008
- }
2009
- if (event.type !== "assistant/message") return state;
2010
- const initiated = state.stepStart !== void 0 ? state.stepStart : event.time;
2011
- const key = dayKeyOf(initiated);
2012
- if (key === null) return state;
2013
- const data = event.data;
2014
- const buckets = billedBucketsOf(data?.usage);
2015
- const prev = state.days[key];
2016
- let cost = prev?.cost;
2017
- if (buckets !== null && state.model !== void 0) cost = addBilledUsage(cost, state.provider ?? "", state.model, initiated, buckets);
2018
- return withDayEntry(state, key, {
2019
- tokens: (prev === void 0 ? 0 : prev.tokens) + (buckets === null ? 0 : buckets.uncached + buckets.cacheRead + buckets.cacheWrite + buckets.output),
2020
- requests: (prev === void 0 ? 0 : prev.requests) + 1,
2021
- ...cost !== void 0 ? { cost } : {},
2022
- ...prev?.skills !== void 0 ? { skills: prev.skills } : {}
2023
- });
2024
- }
2025
- function createContextActivityDefinition() {
2026
- return {
2027
- key: "contextActivity",
2028
- stateSchema: activityStateSchema,
2029
- init: () => ({ days: {} }),
2030
- apply: (state, event) => applyActivity(state, event),
2031
- wire: {
2032
- viewSchema: contextActivitySchema,
2033
- view: (state) => ({ days: Object.fromEntries(Object.entries(state.days).map(([k, v]) => [k, {
2034
- ...v,
2035
- ...v.cost !== void 0 ? { cost: copyCostUsage(v.cost) } : {},
2036
- ...v.skills !== void 0 ? { skills: Object.fromEntries(Object.entries(v.skills).map(([n, t]) => [n, { ...t }])) } : {}
2037
- }])) })
2038
- },
2039
- stateVersion: 4
2040
- };
2041
- }
2042
- //#endregion
2043
- //#region src/shared/attachment.ts
2044
- const EXTENSION_IMAGE = new Set([
2045
- "png",
2046
- "jpg",
2047
- "jpeg",
2048
- "gif",
2049
- "webp",
2050
- "bmp",
2051
- "ico",
2052
- "svg"
2053
- ]);
2054
- function leafNameOf(name) {
2055
- return name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1);
2056
- }
2057
- function attachmentExtension(name) {
2058
- const base = leafNameOf(name);
2059
- const dot = base.lastIndexOf(".");
2060
- return dot < 0 ? "" : base.slice(dot + 1).toLowerCase();
2061
- }
2062
- function isImageName(name) {
2063
- return EXTENSION_IMAGE.has(attachmentExtension(name));
2064
- }
2065
- function numOf(value) {
2066
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
2067
- }
2068
- function dimensionsOf(value) {
2069
- if (value === null || typeof value !== "object") return void 0;
2070
- const dims = value;
2071
- const width = numOf(dims.width);
2072
- const height = numOf(dims.height);
2073
- return width !== void 0 && height !== void 0 ? {
2074
- width,
2075
- height
2076
- } : void 0;
2077
- }
2078
- function attachmentOf(block) {
2079
- if (block === null || typeof block !== "object") return null;
2080
- const b = block;
2081
- const spelling = typeof b.type === "string" ? b.type : b.kind;
2082
- if (spelling !== "image" && spelling !== "file") return null;
2083
- if (b.attachment === null || typeof b.attachment !== "object") return null;
2084
- const a = b.attachment;
2085
- if (typeof a.attachmentId !== "string" || a.attachmentId === "") return null;
2086
- const name = typeof a.name === "string" && a.name !== "" ? a.name : void 0;
2087
- const bytes = numOf(a.bytes);
2088
- if (spelling === "file") return {
2089
- kind: "file",
2090
- attachmentId: a.attachmentId,
2091
- ...name !== void 0 ? { name } : {},
2092
- ...bytes !== void 0 ? { bytes } : {}
2093
- };
2094
- const origDims = dimensionsOf(a.originalDimensions);
2095
- const width = numOf(a.width);
2096
- const height = numOf(a.height);
2097
- const mediaType = typeof a.mediaType === "string" && a.mediaType !== "" ? a.mediaType : void 0;
2098
- return {
2099
- kind: "image",
2100
- attachmentId: a.attachmentId,
2101
- ...name !== void 0 ? { name } : {},
2102
- ...mediaType !== void 0 ? { mediaType } : {},
2103
- ...bytes !== void 0 ? { bytes } : {},
2104
- ...width !== void 0 ? { width } : {},
2105
- ...height !== void 0 ? { height } : {},
2106
- ...origDims !== void 0 ? { originalDimensions: origDims } : {}
2107
- };
2108
- }
2109
- //#endregion
2110
- //#region src/host/coldRead.ts
2111
- const HIGH_WATER = 2 / 3;
2112
- function v8Reading() {
2113
- const stats = getHeapStatistics();
2114
- return {
2115
- used: stats.used_heap_size,
2116
- limit: stats.heap_size_limit
2117
- };
2118
- }
2119
- const noop = () => {};
2120
- function makeColdReadGate(reading = v8Reading) {
2121
- const clear = () => {
2122
- try {
2123
- const { used, limit } = reading();
2124
- if (!Number.isFinite(used) || !Number.isFinite(limit) || limit <= 0) return true;
2125
- return used < limit * HIGH_WATER;
2126
- } catch {
2127
- return true;
2128
- }
2129
- };
2130
- let tail = Promise.resolve();
2131
- return { admit(read) {
2132
- const run = tail.then(() => clear() ? read() : void 0);
2133
- tail = run.then(noop, noop);
2134
- return run;
2135
- } };
2136
- }
2137
- //#endregion
2138
- //#region src/host/connection.ts
2139
- function fetchRouteRegistrar(connection) {
2140
- return typeof connection?.fetch?.register === "function" ? connection.fetch.register.bind(connection.fetch) : void 0;
2141
- }
2142
- function registerPostRoute(c, connection, path, fetch, label) {
2143
- const register = fetchRouteRegistrar(connection);
2144
- if (register === void 0) return false;
2145
- try {
2146
- c.effect(() => register({
2147
- path,
2148
- methods: ["POST"],
2149
- requestBody: "buffered",
2150
- fetch
2151
- }), label);
2152
- } catch {
2153
- return false;
2154
- }
2155
- return true;
2156
- }
2157
- //#endregion
2158
- //#region src/host/attachment.ts
2159
- const ATTACHMENT_ROUTE = "/api/dsh-context/attachment";
2160
- const IMAGE_MEDIA_EXTENSION = {
2161
- "image/png": "png",
2162
- "image/jpeg": "jpg",
2163
- "image/webp": "webp",
2164
- "image/gif": "gif"
2165
- };
2166
- function reply$2(value) {
2167
- return Response.json(value, { headers: { "cache-control": "no-store" } });
2168
- }
2169
- function failure$2(code, message) {
2170
- return reply$2({
2171
- ok: false,
2172
- error: {
2173
- code,
2174
- message
2175
- }
2176
- });
2177
- }
2178
- function asRecord$2(value) {
2179
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
2180
- }
2181
- const WALK_MAX_DEPTH = 8;
2182
- function attachmentIn(value, id, depth) {
2183
- if (depth > WALK_MAX_DEPTH) return null;
2184
- if (Array.isArray(value)) {
2185
- for (const item of value) {
2186
- const hit = attachmentIn(item, id, depth + 1);
2187
- if (hit !== null) return hit;
2188
- }
2189
- return null;
2190
- }
2191
- if (value === null || typeof value !== "object") return null;
2192
- const ref = attachmentOf(value);
2193
- if (ref !== null && ref.attachmentId === id) return ref;
2194
- for (const child of Object.values(value)) {
2195
- const hit = attachmentIn(child, id, depth + 1);
2196
- if (hit !== null) return hit;
2197
- }
2198
- return null;
2199
- }
2200
- function referencedAttachmentOf(events, attachmentId) {
2201
- for (const entry of events) try {
2202
- const hit = attachmentIn(entry, attachmentId, 0);
2203
- if (hit !== null) return hit;
2204
- } catch {}
2205
- return null;
2206
- }
2207
- function imagePreviewNameOf(ref) {
2208
- const leaf = leafNameOf(ref.name ?? "");
2209
- if (leaf !== "" && isImageName(leaf)) return leaf;
2210
- const extension = ref.mediaType !== void 0 ? IMAGE_MEDIA_EXTENSION[ref.mediaType] : void 0;
2211
- return extension === void 0 ? null : `attachment.${extension}`;
2212
- }
2213
- function previewAliasDirOf(objectPath) {
2214
- const root = dirname(dirname(dirname(objectPath)));
2215
- if (basename(root) !== "v1" || basename(dirname(root)) !== "attachments") return null;
2216
- return join(dirname(dirname(root)), "cache", "dsh-context", "previews");
2217
- }
2218
- function filePathOf(store, ref) {
2219
- if (typeof store?.fileHostPath !== "function") return null;
2220
- try {
2221
- const path = store.fileHostPath({
2222
- attachmentId: ref.attachmentId,
2223
- name: ref.name ?? "",
2224
- bytes: ref.bytes ?? 0
2225
- });
2226
- return typeof path === "string" && path !== "" ? path : null;
2227
- } catch {
2228
- return null;
2229
- }
2230
- }
2231
- async function imageAliasOf(store, ref) {
2232
- if (typeof store?.imageHostPath !== "function") return null;
2233
- let objectPath;
2234
- try {
2235
- objectPath = store.imageHostPath({
2236
- attachmentId: ref.attachmentId,
2237
- ...ref.mediaType !== void 0 ? { mediaType: ref.mediaType } : {},
2238
- ...ref.bytes !== void 0 ? { bytes: ref.bytes } : {},
2239
- ...ref.width !== void 0 ? { width: ref.width } : {},
2240
- ...ref.height !== void 0 ? { height: ref.height } : {},
2241
- ...ref.name !== void 0 ? { name: ref.name } : {}
2242
- });
2243
- } catch {
2244
- return null;
2245
- }
2246
- if (typeof objectPath !== "string" || objectPath === "") return null;
2247
- const name = imagePreviewNameOf(ref);
2248
- if (name === null) return null;
2249
- const directory = previewAliasDirOf(objectPath);
2250
- if (directory === null) return null;
2251
- const alias = join(directory, basename(dirname(objectPath)), basename(objectPath), name);
2252
- try {
2253
- await mkdir(dirname(alias), { recursive: true });
2254
- try {
2255
- await link(objectPath, alias);
2256
- } catch (err) {
2257
- if (!(err instanceof Error && "code" in err && err.code === "EEXIST")) await copyFile(objectPath, alias);
2258
- }
2259
- return alias;
2260
- } catch {
2261
- return null;
2262
- }
2263
- }
2264
- async function previewPathOf(store, ref) {
2265
- return ref.kind === "file" ? filePathOf(store, ref) : await imageAliasOf(store, ref);
2266
- }
2267
- function watchAttachmentChannel(ctx, coldReads = makeColdReadGate()) {
2268
- ctx.inject(["connection"], (c) => {
2269
- const handler = async (request) => {
2270
- let sessionId;
2271
- let attachmentId;
2272
- try {
2273
- const body = asRecord$2(await request.json());
2274
- sessionId = body?.sessionId;
2275
- attachmentId = body?.attachmentId;
2276
- } catch {
2277
- return failure$2("dsh-context/bad-request", "body is not JSON");
2278
- }
2279
- if (typeof sessionId !== "string" || sessionId === "") return failure$2("dsh-context/bad-request", "missing sessionId");
2280
- if (typeof attachmentId !== "string" || attachmentId === "") return failure$2("dsh-context/bad-request", "missing attachmentId");
2281
- try {
2282
- const query = ctx.get("sessionQuery");
2283
- const observe = typeof query?.observeSession === "function" ? query.observeSession.bind(query) : void 0;
2284
- if (observe === void 0) return reply$2({
2285
- ok: true,
2286
- value: null
2287
- });
2288
- const store = ctx.get("attachments");
2289
- return reply$2({
2290
- ok: true,
2291
- value: await coldReads.admit(async () => {
2292
- const observation = await observe(sessionId, { projectionMode: "none" });
2293
- try {
2294
- const events = observation?.events;
2295
- if (!Array.isArray(events)) return null;
2296
- const ref = referencedAttachmentOf(events, attachmentId);
2297
- if (ref === null) return null;
2298
- const path = await previewPathOf(store, ref);
2299
- return path === null ? null : { path };
2300
- } finally {
2301
- const dispose = observation?.[Symbol.dispose];
2302
- if (typeof dispose === "function") dispose.call(observation);
2303
- }
2304
- }) ?? null
2305
- });
2306
- } catch (err) {
2307
- return failure$2("gateway/internal", err instanceof Error ? err.message : String(err));
2308
- }
2309
- };
2310
- registerPostRoute(c, c.get("connection"), ATTACHMENT_ROUTE, handler, "dsh-context: attachment route");
2311
- });
2312
- }
2313
- function mcpServerOf(name) {
2314
- if (!name.startsWith("mcp__")) return void 0;
2315
- const cut = name.lastIndexOf("__");
2316
- if (cut < 5) return void 0;
2317
- const server = name.slice(5, cut);
2318
- return server.length > 0 ? server : void 0;
2319
- }
2320
- function mcpSourceOf(name) {
2321
- const server = mcpServerOf(name);
2322
- return server !== void 0 ? `mcp:${server}` : void 0;
2323
- }
2324
- function pinnedSourceOf(name) {
2325
- return FIRST_PARTY_SOURCES[name];
2326
- }
2327
- const FIRST_PARTY_SOURCES = Object.freeze({
2328
- read: "@deepseek-ai/dsh-tool-fs",
2329
- write: "@deepseek-ai/dsh-tool-fs",
2330
- edit: "@deepseek-ai/dsh-tool-fs",
2331
- read_image: "@deepseek-ai/dsh-tool-fs",
2332
- glob: "@deepseek-ai/dsh-tool-fs-search",
2333
- grep: "@deepseek-ai/dsh-tool-fs-search",
2334
- str_replace_editor: "@deepseek-ai/dsh-tool-str-replace-editor",
2335
- bash: "@deepseek-ai/dsh-tool-bash",
2336
- pwsh: "@deepseek-ai/dsh-tool-pwsh",
2337
- web_search: "@deepseek-ai/dsh-tool-web",
2338
- web_fetch: "@deepseek-ai/dsh-tool-web",
2339
- job_output: "@deepseek-ai/dsh-tool-jobs",
2340
- job_list: "@deepseek-ai/dsh-tool-jobs",
2341
- job_kill: "@deepseek-ai/dsh-tool-jobs",
2342
- ask_user_question: "@deepseek-ai/dsh-tool-ask-user",
2343
- plan: "@deepseek-ai/dsh-plan-mode",
2344
- exit_plan_mode: "@deepseek-ai/dsh-plan-mode",
2345
- skill: "@deepseek-ai/dsh-tool-skill",
2346
- todo_write: "@deepseek-ai/dsh-tool-todo",
2347
- subagent: "@deepseek-ai/dsh-tool-subagent",
2348
- subagent_fork: "@deepseek-ai/dsh-tool-subagent",
2349
- send_message: "@deepseek-ai/dsh-tool-subagent-control",
2350
- interrupt_agent: "@deepseek-ai/dsh-tool-subagent-control",
2351
- list_agents: "@deepseek-ai/dsh-tool-subagent-control",
2352
- ralph: "@deepseek-ai/dsh-tool-ralph",
2353
- workflow: "@deepseek-ai/dsh-tool-workflow",
2354
- run_code: "@deepseek-ai/dsh-tools",
2355
- schedule_create: "@deepseek-ai/dsh-schedule",
2356
- schedule_list: "@deepseek-ai/dsh-schedule",
2357
- schedule_delete: "@deepseek-ai/dsh-schedule",
2358
- create_goal: "@deepseek-ai/dsh-tool-goal",
2359
- get_goal: "@deepseek-ai/dsh-tool-goal",
2360
- update_goal: "@deepseek-ai/dsh-tool-goal",
2361
- lsp: "@deepseek-ai/dsh-tool-lsp"
2362
- });
2363
- //#endregion
2364
- //#region src/host/attribution.ts
2365
- const selfUrl = normalize(fileURLToPath(import.meta.url));
2366
- const packageCache = new Map();
2367
- function packageNameFrom(file) {
2368
- let dir = dirname(file);
2369
- for (let depth = 0; depth < 12; depth++) {
2370
- const cached = packageCache.get(dir);
2371
- if (cached !== void 0) return cached;
2372
- const packageFile = join(dir, "package.json");
2373
- if (existsSync(packageFile)) try {
2374
- const name = JSON.parse(readFileSync(packageFile, "utf8")).name;
2375
- if (typeof name === "string" && name) {
2376
- packageCache.set(dir, name);
2377
- return name;
2378
- }
2379
- } catch {}
2380
- const parent = dirname(dir);
2381
- packageCache.set(dir, void 0);
2382
- if (parent === dir) return void 0;
2383
- dir = parent;
2384
- }
2385
- }
2386
- const FRAME_POSITION = /:\d+:\d+$/;
2387
- const CORDIS_ORIGINAL = Symbol.for("cordis.original");
2388
- function rawInstanceOf(tools) {
2389
- return tools?.[CORDIS_ORIGINAL] ?? tools;
2390
- }
2391
- const selfPackage = packageNameFrom(selfUrl);
2392
- function callerPackageFrom(stack) {
2393
- if (!stack) return void 0;
2394
- for (const raw of stack.split("\n").slice(1)) {
2395
- let line = raw.trim();
2396
- if (!line.startsWith("at ")) continue;
2397
- line = line.slice(3);
2398
- if (line.startsWith("async ")) line = line.slice(6);
2399
- line = line.replace(/\)\s*$/, "");
2400
- const position = FRAME_POSITION.exec(line);
2401
- if (!position) continue;
2402
- let target = line.slice(0, -position[0].length);
2403
- if (target.includes("(")) target = target.slice(target.lastIndexOf("(") + 1);
2404
- if (target.startsWith("file://")) try {
2405
- target = normalize(fileURLToPath(target));
2406
- } catch {
2407
- continue;
2408
- }
2409
- else if (!/^[A-Za-z]:[\\/]/.test(target) && !target.startsWith("/") && !target.startsWith("\\\\")) continue;
2410
- else target = normalize(target);
2411
- if (target === selfUrl) continue;
2412
- const name = packageNameFrom(target);
2413
- if (name !== void 0 && name !== selfPackage) return name;
2414
- }
2415
- }
2416
- function createToolAttribution(ctx) {
2417
- const live = new Map();
2418
- const wrapped = new WeakSet();
2419
- const self = ctx.fiber.name;
2420
- let lastReader;
2421
- const patched = [];
2422
- const wrapInstance = (tools) => {
2423
- if (!tools || typeof tools !== "object" || wrapped.has(tools)) return;
2424
- const register = tools.register;
2425
- if (typeof register !== "function") return;
2426
- wrapped.add(tools);
2427
- const original = register.attributedOriginal ?? register;
2428
- if (typeof original !== "function") return;
2429
- const instance = tools;
2430
- const wrappedRegister = function(definition) {
2431
- const toolName = definition?.name;
2432
- let owner = lastReader;
2433
- if (!owner || owner === "root" || owner === self) owner = callerPackageFrom(new Error().stack);
2434
- const dispose = original.call(this, definition);
2435
- if (typeof toolName === "string" && owner && owner !== "root" && owner !== self && owner !== selfPackage) {
2436
- live.set(toolName, owner);
2437
- if (typeof dispose === "function") return () => {
2438
- try {
2439
- return dispose();
2440
- } finally {
2441
- live.delete(toolName);
2442
- }
2443
- };
2444
- }
2445
- return dispose;
2446
- };
2447
- wrappedRegister.attributedOriginal = original;
2448
- instance.register = wrappedRegister;
2449
- patched.push(() => {
2450
- if (instance.register === wrappedRegister) instance.register = original;
2451
- });
2452
- };
2453
- ctx.on("internal/get", (reader, name, _error, next) => {
2454
- if (name !== "tools") return next();
2455
- const tools = next();
2456
- lastReader = reader.fiber.name;
2457
- wrapInstance(rawInstanceOf(tools));
2458
- return tools;
2459
- });
2460
- ctx.effect(() => () => {
2461
- for (const restore of patched.splice(0)) restore();
2462
- }, "tools.register attribution");
2463
- const toolsService = rawInstanceOf(ctx.get("tools", false));
2464
- wrapInstance(toolsService);
2465
- const boot = new Set();
2466
- try {
2467
- const toolEntries = toolsService?.layers?.global?.tools;
2468
- if (toolEntries !== void 0 && typeof toolEntries.entries === "function") for (const [name] of toolEntries.entries()) boot.add(name);
2469
- } catch {}
2470
- return { ownerOf: (name) => mcpSourceOf(name) ?? live.get(name) ?? pinnedSourceOf(name) ?? (boot.has(name) ? "<unknown-plugin>" : void 0) };
2471
- }
2472
- //#endregion
2473
- //#region src/host/record.ts
2474
- function asRecord$1(value) {
2475
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
2476
- }
2477
- //#endregion
2478
- //#region src/host/balance.ts
2479
- const BALANCE_ROUTE = "/api/dsh-context/balance";
2480
- const DEEPSEEK_SETTINGS_NS = "llm-deepseek";
2481
- const PUBLIC_BASE_URL = "https://api.deepseek.com";
2482
- const FETCH_TIMEOUT_MS = 1e4;
2483
- function amountOf(value) {
2484
- const n = typeof value === "string" ? Number(value) : value;
2485
- return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : null;
2486
- }
2487
- function deepseekSectionOf(ctx) {
2488
- const settings = ctx.get("settings");
2489
- if (typeof settings?.describe !== "function") return null;
2490
- try {
2491
- const rows = settings.describe();
2492
- if (!Array.isArray(rows)) return null;
2493
- let shaped = null;
2494
- for (const row of rows) try {
2495
- const record = asRecord$1(row);
2496
- if (record === null) continue;
2497
- const value = asRecord$1(record.value);
2498
- if (value === null || typeof value.apiKeyEnv !== "string" || value.apiKeyEnv === "") continue;
2499
- if (record.ns === DEEPSEEK_SETTINGS_NS || record.ns === "llm-deepseek-api-key") return value;
2500
- shaped ??= value;
2501
- } catch {
2502
- continue;
2503
- }
2504
- return shaped;
2505
- } catch {
2506
- return null;
2507
- }
2508
- }
2509
- async function resolveFacts(ctx) {
2510
- const section = deepseekSectionOf(ctx);
2511
- if (section === null) return null;
2512
- const apiKeyEnv = section.apiKeyEnv;
2513
- const baseUrl = typeof section.baseURL === "string" && section.baseURL !== "" ? section.baseURL : PUBLIC_BASE_URL;
2514
- const credentials = ctx.get("credentials");
2515
- const resolve = typeof credentials?.resolve === "function" ? credentials.resolve.bind(credentials) : void 0;
2516
- if (resolve === void 0) return null;
2517
- let hit;
2518
- try {
2519
- hit = await resolve(apiKeyEnv);
2520
- } catch {
2521
- return null;
2522
- }
2523
- const apiKey = typeof hit?.value === "string" ? hit.value : "";
2524
- return apiKey === "" ? null : {
2525
- baseUrl,
2526
- apiKey
2527
- };
2528
- }
2529
- function balanceOfPayload(value) {
2530
- const data = asRecord$1(value);
2531
- if (data === null) return null;
2532
- const infos = Array.isArray(data.balance_infos) ? data.balance_infos : [];
2533
- const balances = [];
2534
- for (const info of infos) try {
2535
- const entry = asRecord$1(info);
2536
- if (entry === null) continue;
2537
- const currency = entry.currency;
2538
- const granted = amountOf(entry.granted_balance);
2539
- const toppedUp = amountOf(entry.topped_up_balance);
2540
- if (typeof currency !== "string" || currency === "" || granted === null || toppedUp === null) continue;
2541
- balances.push({
2542
- currency,
2543
- total: granted + toppedUp,
2544
- granted,
2545
- toppedUp
2546
- });
2547
- } catch {
2548
- continue;
2549
- }
2550
- return balances.length > 0 ? {
2551
- isAvailable: data.is_available === true,
2552
- balances
2553
- } : null;
2554
- }
2555
- const defaultFetcher = (url, init) => fetch(url, init);
2556
- let fetcher = defaultFetcher;
2557
- let inFlight = null;
2558
- async function readBalance(facts) {
2559
- if (inFlight !== null) return inFlight;
2560
- inFlight = (async () => {
2561
- let value = null;
2562
- try {
2563
- const response = await fetcher(facts.baseUrl.replace(/\/+$/, "") + "/user/balance", {
2564
- headers: {
2565
- accept: "application/json",
2566
- authorization: "Bearer " + facts.apiKey
2567
- },
2568
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
2569
- });
2570
- if (response.ok) value = balanceOfPayload(await response.json());
2571
- } catch {}
2572
- return value;
2573
- })();
2574
- const settled = inFlight;
2575
- try {
2576
- return await settled;
2577
- } finally {
2578
- inFlight = null;
2579
- }
2580
- }
2581
- function watchBalanceChannel(ctx) {
2582
- ctx.inject(["connection"], (c) => {
2583
- const handler = async () => {
2584
- const facts = await resolveFacts(ctx);
2585
- const value = facts !== null ? await readBalance(facts) : null;
2586
- return Response.json({
2587
- ok: true,
2588
- value
2589
- }, { headers: { "cache-control": "no-store" } });
2590
- };
2591
- registerPostRoute(c, c.get("connection"), BALANCE_ROUTE, handler, "dsh-context: balance route");
2592
- });
2593
- }
2594
- //#endregion
2595
- //#region src/host/backfill.ts
2596
- const BACKFILL_ROUTE = "/api/dsh-context/backfill";
2597
- const MIN_REST_MS = 25;
2598
- const SLICE_EVENTS = 2e3;
2599
- const DEFAULT_PACING = {
2600
- now: () => performance.now(),
2601
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
2602
- minRestMs: MIN_REST_MS,
2603
- workBudgetMs: 8e3,
2604
- roundPauseMs: 2e3
2605
- };
2606
- const UNSUPPORTED_FORMAT = "SessionFormatUnsupported";
2607
- function headerOf(record) {
2608
- const header = asRecord$1(asRecord$1(record)?.header);
2609
- if (header === null) return null;
2610
- if (typeof header.id !== "string" || header.id === "") return null;
2611
- return header;
2612
- }
2613
- const PROBE_KEYS = ["contextActivity", "contextTimeline"];
2614
- function servesRows(cache, header) {
2615
- try {
2616
- const values = asRecord$1(asRecord$1(cache.cachedSnapshot(header, PROBE_KEYS))?.values);
2617
- return values !== null && values.contextActivity !== void 0 && values.contextTimeline !== void 0;
2618
- } catch {
2619
- return false;
2620
- }
2621
- }
2622
- async function readColdLog(persistence, id, signal) {
2623
- const handle = await persistence.open(id, "read", { signal });
2624
- let events;
2625
- try {
2626
- const result = asRecord$1(await handle.read(0, void 0, { signal }))?.events;
2627
- events = Array.isArray(result) ? result : [];
2628
- } catch (error) {
2629
- try {
2630
- await handle.close();
2631
- } catch {}
2632
- throw error;
2633
- }
2634
- await handle.close();
2635
- return {
2636
- header: handle.header,
2637
- inheritedEventCount: handle.inheritedEventCount,
2638
- events: [...events, ...interruptedTurnClosers(events)]
2639
- };
2640
- }
2641
- function isLive(sessions, id) {
2642
- if (sessions === null || typeof sessions.get !== "function") return false;
2643
- try {
2644
- return sessions.get(id) !== void 0;
2645
- } catch {
2646
- return true;
2647
- }
2648
- }
2649
- async function coldSnapshotSliced(ctx, faces, sessions, log, signal, rest, now) {
2650
- const { header, inheritedEventCount, events } = log;
2651
- let rows = {};
2652
- let workMs = 0;
2653
- for (let end = SLICE_EVENTS;; end += SLICE_EVENTS) {
2654
- const last = end >= events.length;
2655
- const started = now();
2656
- rows = asRecord$1(faces.restore(rows, last ? events : events.slice(0, end), 0, header, inheritedEventCount))?.checkpoint ?? {};
2657
- const sliceCost = now() - started;
2658
- workMs += sliceCost;
2659
- if (last) break;
2660
- await rest(sliceCost);
2661
- if (signal.aborted) return {
2662
- outcome: "aborted",
2663
- workMs
2664
- };
2665
- }
2666
- let prepared;
2667
- try {
2668
- prepared = faces.prepare(header.id, {
2669
- seed: events,
2670
- meta: structuredClone(header),
2671
- inheritedEventCount,
2672
- eventState: "shared-frozen"
2673
- });
2674
- } catch (error) {
2675
- if (isLive(sessions, header.id)) return {
2676
- outcome: "live",
2677
- workMs
2678
- };
2679
- throw error;
2680
- }
2681
- faces.hydrate(prepared, rows, events, 0);
2682
- try {
2683
- await faces.write(prepared);
2684
- } catch (error) {
2685
- ctx.logger.warn(`dsh-context: projection backfill write-back for "${header.id}" failed (cache stays stale): ${messageOf$1(error)}`);
2686
- }
2687
- return {
2688
- outcome: "done",
2689
- workMs
2690
- };
2691
- }
2692
- function isUnsupportedFormat(error) {
2693
- try {
2694
- return String(asRecord$1(error)?.name).startsWith(UNSUPPORTED_FORMAT);
2695
- } catch {
2696
- return false;
2697
- }
2698
- }
2699
- function messageOf$1(error) {
2700
- try {
2701
- return String(error);
2702
- } catch {
2703
- return "unprintable error";
2704
- }
2705
- }
2706
- function watchActivityBackfill(ctx, coldReads = makeColdReadGate(), pacing = DEFAULT_PACING) {
2707
- let requested = false;
2708
- let started = false;
2709
- let launch = null;
2710
- const tryLaunch = () => {
2711
- if (!requested || started || launch === null) return;
2712
- started = true;
2713
- launch();
2714
- };
2715
- const routeFiber = ctx.inject(["connection"], (c) => {
2716
- const handler = () => {
2717
- requested = true;
2718
- tryLaunch();
2719
- return Response.json({ ok: true }, { headers: { "cache-control": "no-store" } });
2720
- };
2721
- registerPostRoute(c, c.get("connection"), BACKFILL_ROUTE, handler, "dsh-context: backfill route");
2722
- });
2723
- const runnerFiber = ctx.inject([
2724
- "sessionQuery",
2725
- "sessionProjectionCache",
2726
- "sessionPersistence",
2727
- "sessions"
2728
- ], (raw) => {
2729
- const injected = raw;
2730
- const query = asRecord$1(injected.sessionQuery);
2731
- const cache = asRecord$1(injected.sessionProjectionCache);
2732
- const persistence = asRecord$1(injected.sessionPersistence);
2733
- if (query === null || typeof query.listSessions !== "function") return;
2734
- if (cache === null || typeof cache.cachedSnapshot !== "function" || typeof cache.coldSnapshot !== "function") return;
2735
- if (persistence === null || typeof persistence.open !== "function") return;
2736
- const sessions = asRecord$1(injected.sessions);
2737
- const registry = asRecord$1(ctx.sessionProjections);
2738
- const sliceFaces = registry !== null && typeof registry.restore === "function" && typeof registry.hydrate === "function" && sessions !== null && typeof sessions.prepare === "function" && typeof cache.write === "function" ? {
2739
- restore: registry.restore.bind(registry),
2740
- hydrate: registry.hydrate.bind(registry),
2741
- prepare: sessions.prepare.bind(sessions),
2742
- write: cache.write.bind(cache)
2743
- } : null;
2744
- const abort = new AbortController();
2745
- const run = async () => {
2746
- const listed = await query.listSessions(abort.signal);
2747
- if (!Array.isArray(listed)) return;
2748
- let folded = 0;
2749
- let refused = 0;
2750
- let paused = false;
2751
- let roundWork = 0;
2752
- const sleep = async (ms) => {
2753
- if (abort.signal.aborted) return;
2754
- let onAbort;
2755
- try {
2756
- await Promise.race([pacing.sleep(ms), new Promise((resolve) => {
2757
- onAbort = () => {
2758
- resolve();
2759
- };
2760
- abort.signal.addEventListener("abort", onAbort, { once: true });
2761
- })]);
2762
- } finally {
2763
- abort.signal.removeEventListener("abort", onAbort);
2764
- }
2765
- };
2766
- const rest = async (costMs) => {
2767
- roundWork += costMs;
2768
- if (roundWork >= pacing.workBudgetMs) {
2769
- roundWork = 0;
2770
- ctx.logger.info(`dsh-context: projection backfill pausing after ${Math.round(pacing.workBudgetMs / 1e3)}s of fold work; resuming in ${Math.round(pacing.roundPauseMs / 1e3)}s`);
2771
- await sleep(pacing.roundPauseMs);
2772
- return;
2773
- }
2774
- await sleep(Math.max(pacing.minRestMs, costMs));
2775
- };
2776
- for (const record of listed) {
2777
- if (abort.signal.aborted) return;
2778
- const header = headerOf(record);
2779
- if (header === null || typeof header.cwd !== "string") continue;
2780
- if (isLive(sessions, header.id)) continue;
2781
- if (servesRows(cache, header)) continue;
2782
- const started = pacing.now();
2783
- let slicedWorkMs = 0;
2784
- try {
2785
- const admitted = await coldReads.admit(async () => {
2786
- const log = await readColdLog(persistence, header.id, abort.signal);
2787
- if (sliceFaces !== null && log.events.length > SLICE_EVENTS) {
2788
- const sliced = await coldSnapshotSliced(ctx, sliceFaces, sessions, log, abort.signal, rest, pacing.now);
2789
- slicedWorkMs = sliced.workMs;
2790
- return sliced.outcome;
2791
- }
2792
- cache.coldSnapshot(log.header, log.inheritedEventCount, log.events);
2793
- return "done";
2794
- });
2795
- if (admitted === void 0) {
2796
- paused = true;
2797
- break;
2798
- }
2799
- if (admitted === "aborted") return;
2800
- if (admitted === "done") folded++;
2801
- } catch (error) {
2802
- if (isUnsupportedFormat(error)) {
2803
- refused++;
2804
- ctx.logger.debug(`dsh-context: projection backfill skipped "${header.id}" (${messageOf$1(error)})`);
2805
- } else ctx.logger.warn(`dsh-context: projection backfill skipped "${header.id}" (${messageOf$1(error)})`);
2806
- }
2807
- await rest(Math.max(0, pacing.now() - started - slicedWorkMs));
2808
- }
2809
- if (folded > 0) ctx.logger.info(`dsh-context: projection rows backfilled for ${folded} session(s)`);
2810
- if (paused) ctx.logger.info("dsh-context: projection backfill stopped early under heap pressure (remaining sessions refold on their next live activity)");
2811
- if (refused > 0) ctx.logger.info(`dsh-context: projection backfill skipped ${refused} session(s) (legacy log format is not migratable; sources left unchanged)`);
2812
- };
2813
- launch = () => {
2814
- run().catch((error) => {
2815
- if (!abort.signal.aborted) ctx.logger.warn(`dsh-context: projection backfill stopped early (${messageOf$1(error)})`);
2816
- });
2817
- };
2818
- tryLaunch();
2819
- return () => {
2820
- abort.abort();
2821
- };
2822
- });
2823
- return () => {
2824
- for (const fiber of [routeFiber, runnerFiber]) fiber?.dispose?.();
2825
- };
2826
- }
2827
- const FOLD_YIELD_EVENTS = 1e3;
2828
- const PAYLOAD_CACHE_MAX = 4;
2829
- function revisionOf(observation) {
2830
- const revision = observation?.revision;
2831
- return typeof revision === "string" && revision !== "" ? revision : void 0;
2832
- }
2833
- function reply$1(value) {
2834
- return Response.json(value, { headers: { "cache-control": "no-store" } });
2835
- }
2836
- function failure$1(code, message) {
2837
- return reply$1({
2838
- ok: false,
2839
- error: {
2840
- code,
2841
- message
2842
- }
2843
- });
2844
- }
2845
- function watchDetailChannel(ctx, bounds, coldReads = makeColdReadGate()) {
2846
- const gate = { live: false };
2847
- const payloads = new Map();
2848
- ctx.inject(["connection", "sessions"], (c) => {
2849
- const sessions = c.get("sessions");
2850
- const getSession = typeof sessions?.get === "function" ? sessions.get.bind(sessions) : void 0;
2851
- if (getSession === void 0) return;
2852
- const projections = ctx.sessionProjections;
2853
- const handler = async (request) => {
2854
- let sessionId;
2855
- try {
2856
- const body = await request.json();
2857
- sessionId = body !== null && typeof body === "object" ? body.sessionId : void 0;
2858
- } catch {
2859
- return failure$1("dsh-context/bad-request", "body is not JSON");
2860
- }
2861
- if (typeof sessionId !== "string" || sessionId === "") return failure$1("dsh-context/bad-request", "missing sessionId");
2862
- try {
2863
- const session = getSession(sessionId);
2864
- if (session !== void 0 && session !== null) {
2865
- const state = projections.stateOf(session, "contextTimeline");
2866
- if (state === void 0) return reply$1({
2867
- ok: true,
2868
- value: null
2869
- });
2870
- return reply$1({
2871
- ok: true,
2872
- value: buildTimelineDetail(state, bounds)
2873
- });
2874
- }
2875
- const query = ctx.get("sessionQuery");
2876
- const observe = typeof query?.observeSession === "function" ? query.observeSession.bind(query) : void 0;
2877
- if (observe === void 0) return reply$1({
2878
- ok: true,
2879
- value: null
2880
- });
2881
- return reply$1({
2882
- ok: true,
2883
- value: await coldReads.admit(async () => {
2884
- const observation = await observe(sessionId, { projectionMode: "none" });
2885
- try {
2886
- const persistence = ctx.get("sessionPersistence");
2887
- const revision = revisionOf(observation);
2888
- if (revision !== void 0) {
2889
- const hit = payloads.get(sessionId);
2890
- if (hit !== void 0 && hit.revision === revision && hit.persistence === persistence) {
2891
- payloads.delete(sessionId);
2892
- payloads.set(sessionId, hit);
2893
- return hit.value;
2894
- }
2895
- }
2896
- const events = observation?.events;
2897
- if (!Array.isArray(events)) return null;
2898
- let state = createTimelineState();
2899
- let folded = 0;
2900
- for (const ev of events) {
2901
- state = applyTimeline(state, ev, bounds);
2902
- if (++folded % FOLD_YIELD_EVENTS === 0) await new Promise((resolve) => setTimeout(resolve, 0));
2903
- }
2904
- const detail = buildTimelineDetail(state, bounds);
2905
- if (revision !== void 0) {
2906
- payloads.delete(sessionId);
2907
- payloads.set(sessionId, {
2908
- persistence,
2909
- revision,
2910
- value: detail
2911
- });
2912
- for (const oldest of payloads.keys()) {
2913
- if (payloads.size <= PAYLOAD_CACHE_MAX) break;
2914
- payloads.delete(oldest);
2915
- }
2916
- }
2917
- return detail;
2918
- } finally {
2919
- const dispose = observation?.[Symbol.dispose];
2920
- if (typeof dispose === "function") dispose.call(observation);
2921
- }
2922
- }) ?? null
2923
- });
2924
- } catch (err) {
2925
- return failure$1("gateway/internal", err instanceof Error ? err.message : String(err));
2926
- }
2927
- };
2928
- if (!registerPostRoute(c, c.get("connection"), "/api/dsh-context/detail", handler, "dsh-context: detail route")) return;
2929
- gate.live = true;
2930
- return () => {
2931
- gate.live = false;
2932
- };
2933
- });
2934
- return gate;
2935
- }
2936
- //#endregion
2937
- //#region src/shared/version.ts
2938
- const BASELINE_DSH_VERSION = "0.1.7-rc.2";
2939
- function channelRank(channel) {
2940
- return channel === "rc" ? 3 : channel === "beta" ? 2 : 1;
2941
- }
2942
- const RELEASE_RANK = 4;
2943
- function parseVersion(version) {
2944
- const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-(alpha|beta|rc)(?:\.(\d+))?)?(?:\+[0-9a-z.-]+)?$/i.exec(version.trim());
2945
- if (match === null) return null;
2946
- const channel = match[4]?.toLowerCase();
2947
- return {
2948
- major: Number(match[1]),
2949
- minor: Number(match[2]),
2950
- patch: Number(match[3]),
2951
- rank: channel === void 0 ? RELEASE_RANK : channelRank(channel),
2952
- serial: match[5] ? Number(match[5]) : 0
2953
- };
2954
- }
2955
- function compareParsed(a, b) {
2956
- if (a.major !== b.major) return a.major - b.major;
2957
- if (a.minor !== b.minor) return a.minor - b.minor;
2958
- if (a.patch !== b.patch) return a.patch - b.patch;
2959
- if (a.rank !== b.rank) return a.rank - b.rank;
2960
- return a.serial - b.serial;
2961
- }
2962
- function meetsBaseline(version, baseline = BASELINE_DSH_VERSION) {
2963
- const v = parseVersion(version);
2964
- const b = parseVersion(baseline);
2965
- if (v === null || b === null) return true;
2966
- return compareParsed(v, b) >= 0;
2967
- }
2968
- //#endregion
2969
- //#region src/host/headers.ts
2970
- const HEADERS_MAX = 50;
2971
- const storedToolSchema = z.object({
2972
- name: z.string(),
2973
- tokens: z.number().int().nonnegative(),
2974
- description: z.string().optional(),
2975
- plugin: z.string().optional(),
2976
- schema: z.unknown().optional()
2977
- }).strict();
2978
- const storedEpochSchema = z.object({
2979
- seq: z.number(),
2980
- time: z.number(),
2981
- system: z.string().optional(),
2982
- systemTokens: z.number().int().nonnegative().optional(),
2983
- tools: z.array(storedToolSchema)
2984
- }).strict();
2985
- const contextHeadersStateSchema = z.object({ headers: z.array(storedEpochSchema) }).strict();
2986
- const headerToolWireSchema = z.object({
2987
- name: z.string(),
2988
- tokens: z.number().int().nonnegative(),
2989
- plugin: z.string().optional()
2990
- }).strict();
2991
- const contextHeadersSchema = z.object({ headers: z.array(z.object({
2992
- seq: z.number(),
2993
- time: z.number(),
2994
- systemTokens: z.number().int().nonnegative().optional(),
2995
- tools: z.array(headerToolWireSchema)
2996
- }).strict()) }).strict();
2997
- function recordOf(event) {
2998
- if (event.type !== "request/header") return null;
2999
- const rawHeader = event.data?.header;
3000
- if (rawHeader === null || rawHeader === void 0 || typeof rawHeader !== "object") return null;
3001
- const header = rawHeader;
3002
- const tools = Array.isArray(header.tools) ? header.tools : [];
3003
- return {
3004
- seq: event.seq,
3005
- time: event.time,
3006
- tools: tools.map((t) => {
3007
- const tool = t !== null && typeof t === "object" ? t : {};
3008
- const entry = {
3009
- name: typeof tool.name === "string" ? tool.name : "?",
3010
- tokens: estimateToolSchema(t)
3011
- };
3012
- if (typeof tool.plugin === "string" && tool.plugin !== "") entry.plugin = tool.plugin;
3013
- return entry;
3014
- })
3015
- };
3016
- }
3017
- function createContextHeadersDefinition(resolve) {
3018
- const view = (state) => ({ headers: state.headers.map((h) => {
3019
- const record = {
3020
- seq: h.seq,
3021
- time: h.time,
3022
- tools: h.tools.map((t) => {
3023
- const entry = {
3024
- name: t.name,
3025
- tokens: t.tokens
3026
- };
3027
- const plugin = t.plugin ?? (resolve !== void 0 ? resolve(t.name) : void 0);
3028
- if (plugin !== void 0) entry.plugin = plugin;
3029
- return entry;
3030
- })
3031
- };
3032
- const systemTokens = h.systemTokens ?? (typeof h.system === "string" && h.system !== "" ? estimateSystemTokens(h.system) : void 0);
3033
- if (systemTokens !== void 0) record.systemTokens = systemTokens;
3034
- return record;
3035
- }) });
3036
- return {
3037
- key: "contextHeaders",
3038
- stateSchema: contextHeadersStateSchema,
3039
- wire: {
3040
- viewSchema: contextHeadersSchema,
3041
- view
3042
- },
3043
- init: () => ({ headers: [] }),
3044
- apply: (state, event) => {
3045
- const record = recordOf(event);
3046
- if (record === null) return state;
3047
- const last = state.headers.at(-1);
3048
- if (last !== void 0 && last.seq === record.seq) return state;
3049
- const headers = [...state.headers, record];
3050
- return { headers: headers.length > HEADERS_MAX ? headers.slice(-50) : headers };
3051
- },
3052
- stateVersion: 1
3053
- };
3054
- }
3055
- //#endregion
3056
- //#region src/host/fallback.ts
3057
- const fallbackStateSchema = z.object({});
3058
- function fallbackDefinition(key, wireSchema, value) {
3059
- const view = () => value;
3060
- return {
3061
- key,
3062
- stateSchema: fallbackStateSchema,
3063
- init: () => ({}),
3064
- apply: (state) => state,
3065
- wire: {
3066
- viewSchema: wireSchema,
3067
- view
3068
- },
3069
- schema: wireSchema,
3070
- view,
3071
- stateVersion: 1
3072
- };
3073
- }
3074
- function createFallbackTimelineDefinition(current) {
3075
- return fallbackDefinition("contextTimeline", contextTimelineSchema, {
3076
- ok: true,
3077
- unsupported: {
3078
- current,
3079
- minimum: BASELINE_DSH_VERSION
3080
- },
3081
- current: {
3082
- system: 0,
3083
- tools: 0,
3084
- user: 0,
3085
- inject: 0,
3086
- skill: 0,
3087
- assistant: 0,
3088
- tool: 0,
3089
- total: 0
3090
- },
3091
- requests: [],
3092
- events: [],
3093
- nodes: [],
3094
- droppedNodes: 0,
3095
- archive: []
3096
- });
3097
- }
3098
- function createFallbackHeadersDefinition() {
3099
- return fallbackDefinition("contextHeaders", contextHeadersSchema, { headers: [] });
3100
- }
3101
- function createFallbackActivityDefinition() {
3102
- return fallbackDefinition("contextActivity", contextActivitySchema, { days: {} });
3103
- }
3104
- //#endregion
3105
- //#region src/host/fleet.ts
3106
- const FLEET_ROUTE = "/api/dsh-context/fleet";
3107
- const MESSAGES_MAX = 40;
3108
- const MESSAGE_TEXT_MAX = 400;
3109
- const PROMPT_TEXT_MAX = 1600;
3110
- const REPLY_TEXT_MAX = 300;
3111
- function reply(value) {
3112
- return Response.json(value, { headers: { "cache-control": "no-store" } });
3113
- }
3114
- function failure(code, message) {
3115
- return reply({
3116
- ok: false,
3117
- error: {
3118
- code,
3119
- message
3120
- }
3121
- });
3122
- }
3123
- function asRecord(value) {
3124
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
3125
- }
3126
- function textOfContent(content) {
3127
- if (!Array.isArray(content)) return "";
3128
- let out = "";
3129
- for (const block of content) {
3130
- const text = asRecord(block)?.text;
3131
- if (typeof text === "string") out += text;
3132
- }
3133
- return out;
3134
- }
3135
- const REMINDER_PREFIX = /^\s*<system-reminder>[\s\S]*?<\/system-reminder>\s*/;
3136
- function clip(text, max) {
3137
- return text.length > max ? {
3138
- text: text.slice(0, max) + "…",
3139
- cut: true
3140
- } : {
3141
- text,
3142
- cut: false
3143
- };
3144
- }
3145
- function descriptorOf(data) {
3146
- const mode = data.mode;
3147
- if (mode !== "one-shot" && mode !== "continuable") return null;
3148
- const out = { mode };
3149
- for (const key of [
3150
- "label",
3151
- "provider",
3152
- "agentProvider",
3153
- "agentModel",
3154
- "persona"
3155
- ]) {
3156
- const value = data[key];
3157
- if (typeof value === "string" && value !== "") out[key] = value;
3158
- }
3159
- return out;
3160
- }
3161
- const MAILBOX_PREFIX = /^Team message \S+ from [^:]{1,64}:\s*/;
3162
- const RELAY_PREFIX = /^(?:Agent \S+ sent a message: |Team message from [^:\n]{1,64}:\s*)/;
3163
- function messageOf(seq, time, data) {
3164
- const source = asRecord(data.source);
3165
- const kind = source?.kind;
3166
- let message = null;
3167
- if (kind === "agent-message" || kind === "team-message") {
3168
- let text = textOfContent(data.content);
3169
- text = text.replace(kind === "team-message" ? MAILBOX_PREFIX : RELAY_PREFIX, "");
3170
- if (text.trim() === "") return null;
3171
- message = {
3172
- seq,
3173
- time,
3174
- kind: kind === "agent-message" ? "relay" : "mailbox",
3175
- text
3176
- };
3177
- const from = kind === "agent-message" ? source?.senderSessionId : source?.senderId;
3178
- if (typeof from === "string" && from !== "") message.from = from;
3179
- const fromName = source?.senderName;
3180
- if (typeof fromName === "string" && fromName !== "") message.fromName = fromName;
3181
- } else if (kind === "subagent-settled") {
3182
- const summary = source?.summary;
3183
- const text = typeof summary === "string" && summary.trim() !== "" ? summary : textOfContent(data.content);
3184
- if (text.trim() === "") return null;
3185
- message = {
3186
- seq,
3187
- time,
3188
- kind: "settled",
3189
- text
3190
- };
3191
- const from = source?.senderSessionId;
3192
- if (typeof from === "string" && from !== "") message.from = from;
3193
- }
3194
- if (message === null) return null;
3195
- const cut = clip(message.text, MESSAGE_TEXT_MAX);
3196
- message.text = cut.text;
3197
- return message;
3198
- }
3199
- function isPlainPrompt(source) {
3200
- if (source === null) return true;
3201
- return source.kind === "user";
3202
- }
3203
- function rosterMemberOf(data) {
3204
- const member = asRecord(data.member);
3205
- if (member === null) return null;
3206
- if (typeof member.name !== "string" || member.name === "") return null;
3207
- const out = {
3208
- name: member.name,
3209
- description: typeof member.description === "string" ? member.description : ""
3210
- };
3211
- if (typeof member.provider === "string" && member.provider !== "") out.provider = member.provider;
3212
- if (member.context === "fresh" || member.context === "fork") out.context = member.context;
3213
- return out;
3214
- }
3215
- function lastReplyOf(events) {
3216
- for (let i = events.length - 1; i >= 0; i--) {
3217
- const ev = asRecord(events[i]);
3218
- if (ev === null || ev.type !== "assistant/message") continue;
3219
- const content = asRecord(asRecord(ev.data)?.message)?.content;
3220
- if (!Array.isArray(content)) continue;
3221
- let text = "";
3222
- for (const block of content) {
3223
- const b = asRecord(block);
3224
- if (b?.type === "text" && typeof b.text === "string") text += b.text;
3225
- }
3226
- if (text.trim() === "") continue;
3227
- const time = typeof ev.time === "number" && Number.isFinite(ev.time) ? ev.time : 0;
3228
- const cut = clip(text, REPLY_TEXT_MAX);
3229
- return {
3230
- time,
3231
- text: cut.text,
3232
- cut: cut.cut
3233
- };
3234
- }
3235
- return null;
3236
- }
3237
- function fleetDetailOfEvents(events) {
3238
- let descriptor;
3239
- let initialPrompt;
3240
- let truncated = false;
3241
- const messages = [];
3242
- const roster = new Map();
3243
- for (const entry of events) {
3244
- const ev = asRecord(entry);
3245
- if (ev === null) continue;
3246
- const type = ev.type;
3247
- if (typeof type !== "string") continue;
3248
- const seq = typeof ev.seq === "number" && Number.isFinite(ev.seq) ? ev.seq : 0;
3249
- const time = typeof ev.time === "number" && Number.isFinite(ev.time) ? ev.time : 0;
3250
- const data = asRecord(ev.data);
3251
- if (data === null) continue;
3252
- if (type === "subagent/descriptor") {
3253
- const next = descriptorOf(data);
3254
- if (next !== null) descriptor = next;
3255
- continue;
3256
- }
3257
- if (type === "team/member") {
3258
- const member = rosterMemberOf(data);
3259
- if (member !== null) roster.set(member.name, member);
3260
- continue;
3261
- }
3262
- if (type !== "user/message") continue;
3263
- const message = messageOf(seq, time, data);
3264
- if (message !== null) {
3265
- if (message.text.endsWith("…")) truncated = true;
3266
- messages.push(message);
3267
- continue;
3268
- }
3269
- if (initialPrompt === void 0 && isPlainPrompt(asRecord(data.source))) {
3270
- const text = textOfContent(data.content).replace(REMINDER_PREFIX, "");
3271
- if (text.trim() !== "") {
3272
- const cut = clip(text, PROMPT_TEXT_MAX);
3273
- initialPrompt = cut.text;
3274
- if (cut.cut) truncated = true;
3275
- }
3276
- }
3277
- }
3278
- messages.sort((a, b) => b.seq - a.seq);
3279
- if (messages.length > MESSAGES_MAX) {
3280
- messages.length = MESSAGES_MAX;
3281
- truncated = true;
3282
- }
3283
- const reply = lastReplyOf(events);
3284
- if (reply !== null && reply.cut) truncated = true;
3285
- return {
3286
- ...descriptor !== void 0 ? { descriptor } : {},
3287
- ...initialPrompt !== void 0 ? { initialPrompt } : {},
3288
- ...reply !== null ? { lastReply: {
3289
- time: reply.time,
3290
- text: reply.text
3291
- } } : {},
3292
- ...roster.size > 0 ? { roster: [...roster.values()] } : {},
3293
- messages,
3294
- truncated
3295
- };
3296
- }
3297
- function watchFleetChannel(ctx, coldReads = makeColdReadGate()) {
3298
- ctx.inject(["connection"], (c) => {
3299
- const handler = async (request) => {
3300
- let sessionId;
3301
- try {
3302
- sessionId = asRecord(await request.json())?.sessionId;
3303
- } catch {
3304
- return failure("dsh-context/bad-request", "body is not JSON");
3305
- }
3306
- if (typeof sessionId !== "string" || sessionId === "") return failure("dsh-context/bad-request", "missing sessionId");
3307
- try {
3308
- const query = ctx.get("sessionQuery");
3309
- const observe = typeof query?.observeSession === "function" ? query.observeSession.bind(query) : void 0;
3310
- if (observe === void 0) return reply({
3311
- ok: true,
3312
- value: null
3313
- });
3314
- return reply({
3315
- ok: true,
3316
- value: await coldReads.admit(async () => {
3317
- const observation = await observe(sessionId, { projectionMode: "none" });
3318
- const events = observation?.events;
3319
- if (!Array.isArray(events)) return null;
3320
- try {
3321
- return fleetDetailOfEvents(events);
3322
- } finally {
3323
- const dispose = observation?.[Symbol.dispose];
3324
- if (typeof dispose === "function") dispose.call(observation);
3325
- }
3326
- }) ?? null
3327
- });
3328
- } catch (err) {
3329
- return failure("gateway/internal", err instanceof Error ? err.message : String(err));
3330
- }
3331
- };
3332
- registerPostRoute(c, c.get("connection"), FLEET_ROUTE, handler, "dsh-context: fleet route");
3333
- });
3334
- }
3335
- //#endregion
3336
- //#region src/host/promptInjection.ts
3337
- function liveText(value) {
3338
- if (value !== null && typeof value === "object" && typeof value.get === "function") {
3339
- const get = value.get;
3340
- return () => {
3341
- const text = get();
3342
- return typeof text === "string" ? text : "";
3343
- };
3344
- }
3345
- const text = typeof value === "string" ? value : "";
3346
- return () => text;
3347
- }
3348
- function sectionText(read) {
3349
- return () => {
3350
- const text = read();
3351
- return text.trim().length === 0 ? "" : text;
3352
- };
3353
- }
3354
- const ORDER_CLEARANCE = 1e3;
3355
- function watchPromptInjection(ctx, config) {
3356
- ctx.inject(["systemPrompt"], (inner) => {
3357
- const systemPrompt = inner.systemPrompt;
3358
- if (systemPrompt === null || systemPrompt === void 0 || typeof systemPrompt.section !== "function" || typeof systemPrompt.getSectionOrder !== "function") return;
3359
- systemPrompt.section({
3360
- name: "dsh-context:prompt-prefix",
3361
- order: systemPrompt.getSectionOrder("HARNESS_IDENTITY") - ORDER_CLEARANCE,
3362
- text: sectionText(liveText(config.promptPrefix)),
3363
- interpolate: false
3364
- });
3365
- systemPrompt.section({
3366
- name: "dsh-context:prompt-suffix",
3367
- order: systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_SUFFIX") + ORDER_CLEARANCE,
3368
- text: sectionText(liveText(config.promptSuffix)),
3369
- interpolate: false
3370
- });
3371
- });
3372
- }
3373
- //#endregion
3374
- //#region src/host/stepIdentity.ts
3375
- const MINTED_ID_PREFIX = "dshctx-";
3376
- function lacksId(message) {
3377
- if (typeof message !== "object" || message === null) return false;
3378
- const id = message.id;
3379
- return typeof id !== "string" || id === "";
3380
- }
3381
- function identifiedMessages(messages) {
3382
- let copy;
3383
- for (const [index, message] of messages.entries()) {
3384
- if (!lacksId(message)) {
3385
- copy?.push(message);
3386
- continue;
3387
- }
3388
- copy ??= messages.slice(0, index);
3389
- copy.push({
3390
- ...message,
3391
- id: MINTED_ID_PREFIX + randomUUID()
3392
- });
3393
- }
3394
- return copy;
3395
- }
3396
- function watchStepIdentity(ctx) {
3397
- ctx.on("agent/pre-step", async (_input, next) => {
3398
- const decision = await next();
3399
- try {
3400
- if (decision.kind !== "enter" || !Array.isArray(decision.messages)) return decision;
3401
- const identified = identifiedMessages(decision.messages);
3402
- return identified === void 0 ? decision : {
3403
- ...decision,
3404
- messages: identified
3405
- };
3406
- } catch {
3407
- return decision;
3408
- }
3409
- }, { prepend: true });
3410
- }
3411
- //#endregion
3412
- //#region src/host/skills.ts
3413
- const SKILLS_ROUTE = "/api/dsh-context/skills";
3414
- const MAX_SKILLS = 500;
3415
- function stringOf(value) {
3416
- return typeof value === "string" && value !== "" ? value : void 0;
3417
- }
3418
- async function disposeOf(resource) {
3419
- if (resource === null || typeof resource !== "object" && typeof resource !== "function") return;
3420
- try {
3421
- const asyncDispose = resource[Symbol.asyncDispose];
3422
- if (typeof asyncDispose === "function") {
3423
- await asyncDispose.call(resource);
3424
- return;
3425
- }
3426
- const syncDispose = resource[Symbol.dispose];
3427
- if (typeof syncDispose === "function") syncDispose.call(resource);
3428
- } catch {}
3429
- }
3430
- function skillInfoOf(value) {
3431
- const record = asRecord$1(value);
3432
- if (record === null || typeof record.name !== "string" || record.name === "") return null;
3433
- return {
3434
- name: record.name,
3435
- description: typeof record.description === "string" ? record.description : "",
3436
- ...typeof record.path === "string" && record.path !== "" ? { path: record.path } : {},
3437
- ...typeof record.source === "string" && record.source !== "" ? { source: record.source } : {}
3438
- };
3439
- }
3440
- async function sessionViewOf(ctx, sessionId) {
3441
- if (sessionId === void 0) return {};
3442
- const query = asRecord$1(ctx.get("sessionQuery"));
3443
- if (typeof query?.observeSession !== "function") return {};
3444
- let observation;
3445
- try {
3446
- observation = await query.observeSession.call(query, sessionId);
3447
- } catch {
3448
- return {};
3449
- }
3450
- try {
3451
- const obs = asRecord$1(observation);
3452
- const cwd = stringOf(asRecord$1(obs?.header)?.cwd);
3453
- const agentPreset = stringOf(asRecord$1(asRecord$1(obs?.projections)?.values)?.agentPreset);
3454
- return {
3455
- ...cwd === void 0 ? {} : { cwd },
3456
- ...agentPreset === void 0 ? {} : { agentPreset }
3457
- };
3458
- } finally {
3459
- await disposeOf(observation);
3460
- }
3461
- }
3462
- async function resolveRegistry(ctx, sessionId, agentPreset) {
3463
- const presets = asRecord$1(ctx.get("agentPresets"));
3464
- let live;
3465
- if (sessionId !== void 0) {
3466
- const agents = asRecord$1(ctx.get("agents"));
3467
- if (typeof agents?.get === "function") try {
3468
- live = agents.get.call(agents, sessionId);
3469
- } catch {
3470
- live = void 0;
3471
- }
3472
- }
3473
- if (live !== void 0 && live !== null && typeof presets?.serviceFor === "function") {
3474
- const scoped = asRecord$1(presets.serviceFor.call(presets, live, "skills"));
3475
- if (scoped !== null && typeof scoped.list === "function") return {
3476
- registry: scoped,
3477
- scope: live,
3478
- lease: void 0
3479
- };
3480
- }
3481
- const registry = asRecord$1(ctx.get("skills"));
3482
- if (registry === null || typeof registry.list !== "function") return null;
3483
- let scope;
3484
- let lease;
3485
- if (typeof presets?.acquireScope === "function") try {
3486
- lease = await presets.acquireScope.call(presets, agentPreset);
3487
- scope = asRecord$1(lease)?.key;
3488
- } catch {
3489
- lease = void 0;
3490
- }
3491
- return {
3492
- registry,
3493
- scope,
3494
- lease
3495
- };
3496
- }
3497
- function watchSkillCatalog(ctx) {
3498
- ctx.inject(["connection"], (c) => {
3499
- const handler = async (request) => {
3500
- let value = null;
3501
- let lease;
3502
- try {
3503
- const body = asRecord$1(await request.json());
3504
- const sessionId = stringOf(body?.sessionId);
3505
- const view = await sessionViewOf(ctx, sessionId);
3506
- const cwd = view.cwd ?? stringOf(body?.cwd);
3507
- const resolved = await resolveRegistry(ctx, sessionId, view.agentPreset);
3508
- if (resolved !== null) {
3509
- lease = resolved.lease;
3510
- const listed = await resolved.registry.list({
3511
- ...cwd === void 0 ? {} : { cwd },
3512
- ...resolved.scope === void 0 ? {} : { scope: resolved.scope }
3513
- });
3514
- const rows = Array.isArray(listed) ? listed : [];
3515
- const skills = [];
3516
- for (const row of rows) {
3517
- const info = skillInfoOf(row);
3518
- if (info !== null) skills.push(info);
3519
- if (skills.length >= MAX_SKILLS) break;
3520
- }
3521
- value = { skills };
3522
- }
3523
- } catch {} finally {
3524
- await disposeOf(lease);
3525
- }
3526
- return Response.json({
3527
- ok: true,
3528
- value
3529
- }, { headers: { "cache-control": "no-store" } });
3530
- };
3531
- registerPostRoute(c, c.get("connection"), SKILLS_ROUTE, handler, "dsh-context: skills route");
3532
- });
3533
- }
3534
- //#endregion
3535
- //#region src/host/version.ts
3536
- const LIBRARY_PROBE_PACKAGES = ["@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session"];
3537
- const RUNNING_PROBE_PACKAGES = ["@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-projection"];
3538
- const HOME_PROBE_PACKAGES = ["@deepseek-ai/dsh", ...LIBRARY_PROBE_PACKAGES];
3539
- function ownPackageRoot() {
3540
- try {
3541
- return dirname(fileURLToPath(import.meta.resolve("dsh-context/package.json")));
3542
- } catch {
3543
- return dirname(fileURLToPath(import.meta.url));
3544
- }
3545
- }
3546
- const PLUGIN_ROOT = ownPackageRoot();
3547
- function versionOfManifest(manifestPath, expectedName) {
3548
- try {
3549
- const parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
3550
- if (parsed === null || typeof parsed !== "object") return void 0;
3551
- const record = parsed;
3552
- if (expectedName !== void 0 && record.name !== expectedName) return void 0;
3553
- return typeof record.version === "string" && record.version !== "" ? record.version : void 0;
3554
- } catch {
3555
- return;
3556
- }
3557
- }
3558
- function versionViaManifest(resolve, packageName) {
3559
- try {
3560
- return versionOfManifest(resolve(packageName + "/package.json"));
3561
- } catch {
3562
- return;
3563
- }
3564
- }
3565
- function versionViaEntry(resolve, packageName) {
3566
- let dir;
3567
- try {
3568
- dir = dirname(resolve(packageName));
3569
- } catch {
3570
- return;
3571
- }
3572
- for (;;) {
3573
- const version = versionOfManifest(join(dir, "package.json"), packageName);
3574
- if (version !== void 0) return version;
3575
- const parent = dirname(dir);
3576
- if (parent === dir) return void 0;
3577
- dir = parent;
3578
- }
3579
- }
3580
- function probeAnchor(resolve, packageNames) {
3581
- for (const packageName of packageNames) {
3582
- const version = versionViaManifest(resolve, packageName) ?? versionViaEntry(resolve, packageName);
3583
- if (version !== void 0) return version;
3584
- }
3585
- }
3586
- function isInside(root, candidate) {
3587
- const rel = relative(root, candidate);
3588
- return !rel.startsWith("..") && !isAbsolute(rel);
3589
- }
3590
- function probeRunningTree(resolve, pluginRoot) {
3591
- for (const packageName of RUNNING_PROBE_PACKAGES) {
3592
- let witness;
3593
- try {
3594
- witness = resolve(packageName);
3595
- } catch {
3596
- continue;
3597
- }
3598
- if (isInside(pluginRoot, witness)) continue;
3599
- const version = versionViaManifest(resolve, packageName) ?? versionViaEntry(resolve, packageName);
3600
- if (version !== void 0) return version;
3601
- }
3602
- }
3603
- function resolveRunningModule(specifier) {
3604
- return import.meta.resolve(specifier);
3605
- }
3606
- function detectHarnessVersion(ctx, resolveUrl = resolveRunningModule, pluginRoot = PLUGIN_ROOT) {
3607
- const running = probeRunningTree((specifier) => {
3608
- const url = resolveUrl(specifier);
3609
- if (!url.startsWith("file:")) throw new Error(`dsh-context: non-file module URL for ${specifier}`);
3610
- return fileURLToPath(url);
3611
- }, pluginRoot);
3612
- if (running !== void 0) return running;
3613
- try {
3614
- const homePath = ctx.get("dshHomePath");
3615
- if (typeof homePath === "function") {
3616
- const req = createRequire(homePath("profiles", "dsh-context-version-probe.cjs"));
3617
- const home = probeAnchor((specifier) => req.resolve(specifier), HOME_PROBE_PACKAGES);
3618
- if (home !== void 0) return home;
3619
- }
3620
- } catch {}
3621
- }
3622
- //#endregion
3623
- //#region src/host/index.ts
3624
- const name = "dsh-context";
3625
- const inject = ["sessionProjections"];
3626
- function apply(ctx, config) {
3627
- const coldReads = makeColdReadGate();
3628
- watchBalanceChannel(ctx);
3629
- watchSkillCatalog(ctx);
3630
- watchFleetChannel(ctx, coldReads);
3631
- watchAttachmentChannel(ctx, coldReads);
3632
- const harnessVersion = detectHarnessVersion(ctx);
3633
- if (harnessVersion !== void 0 && !meetsBaseline(harnessVersion)) {
3634
- ctx.sessionProjections.register(createFallbackTimelineDefinition(harnessVersion));
3635
- ctx.sessionProjections.register(createFallbackHeadersDefinition());
3636
- ctx.sessionProjections.register(createFallbackActivityDefinition());
3637
- return;
3638
- }
3639
- const attribution = createToolAttribution(ctx);
3640
- watchStepIdentity(ctx);
3641
- const gate = watchDetailChannel(ctx, resolveBounds(config), coldReads);
3642
- ctx.sessionProjections.register(createContextTimelineDefinition(config, () => gate.live));
3643
- ctx.sessionProjections.register(createContextHeadersDefinition((name) => attribution.ownerOf(name)));
3644
- ctx.sessionProjections.register(createContextActivityDefinition());
3645
- watchActivityBackfill(ctx, coldReads);
3646
- watchPromptInjection(ctx, config);
3647
- }
3648
- //#endregion
3649
- export { Config, apply, inject, name };
12
+ import{createRequire as e}from"node:module";import{z as t}from"zod";import{deriveEventMessage as n,interruptedTurnClosers as r}from"@deepseek-ai/dsh-session";import i from"@deepseek-ai/schemastery";import{copyFile as a,link as o,mkdir as s}from"node:fs/promises";import{basename as c,dirname as l,isAbsolute as u,join as d,normalize as f,relative as p}from"node:path";import{getHeapStatistics as m}from"node:v8";import{existsSync as h,readFileSync as ee}from"node:fs";import{fileURLToPath as g}from"node:url";import{performance as te}from"node:perf_hooks";import{randomUUID as ne}from"node:crypto";function re(e){return typeof e!=`string`||e.length===0?0:Math.ceil(e.length/4)+4}function ie(e){return Math.ceil(e.length/4)+4}function ae(e){if(!Array.isArray(e)||e.length===0)return 0;let t=0;for(let n of e){let e=typeof n==`object`&&n&&n.type===`text`?n.text:void 0;if(typeof e==`string`){t+=e.length;continue}try{let e=JSON.stringify(n);typeof e==`string`&&(t+=e.length)}catch{}}return Math.ceil(t/4)+4}const oe=147456,_=(e,t)=>Math.floor(e/t),v=(e,t)=>Math.floor((e+t-1)/t);function se(e,t){let n=e*(t+1)+2;return e%2==1&&(n+=t+1),n+=v(e,2)*(t+1)%2*2,n}function ce(e,t,n){let r=e/t,i=Math.sqrt((n-2)/r+.25)-.5,a=i*r,o,s;if(i<1){let e=_(n-2,2);e%2==1&&--e,s=42,o=e*42}else if(a<2){let e=_(n-2,2)-1;if(e<=1)throw Error(`image tokens: budget too small to solve`);o=84,s=e*42}else{let n=Math.trunc(i),r=Math.trunc(a);r%2==1&&--r;let c=Math.min(n*42/t,r*42/e);s=Math.trunc(t*c/14)*14,o=Math.trunc(e*c/14)*14}let c=v(_(o,14),3),l=v(_(s,14),3);return{nLlmH:c,nLlmW:l,bestHeight:o,bestWidth:s,numTokens:se(c,l)}}function le(e,t,n,r){let i=v(_(n,14),3),a=v(_(r,14),3),o={nLlmH:i,nLlmW:a,bestHeight:n,bestWidth:r,numTokens:se(i,a)};if(o.numTokens>381){o=ce(e,t,381);let n=381;for(;o.numTokens>381;)--n,o=ce(e,t,n)}return o.numTokens+=3,o}function ue(e,t){let n=e,r=t;n>r*8&&(n=r*8);let i=n*r;if(i<oe&&i>0){let e=Math.sqrt(oe/i);n=Math.trunc(n*e),r=Math.trunc(r*e)}let a=v(n,14)*14,o=v(r,14)*14;return le(r,n,o,a)}function de(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return null;try{let n=ue(e,t);for(let e=1;e<10;e++){let e=ue(n.bestWidth,n.bestHeight);if(e.nLlmH===n.nLlmH&&e.nLlmW===n.nLlmW&&e.bestHeight===n.bestHeight&&e.bestWidth===n.bestWidth&&e.numTokens===n.numTokens)return n.numTokens;n=e}return null}catch{return null}}function fe(e){return e.length>0?Math.ceil(JSON.stringify(e).length/4)+4:0}function pe(e){let t=0;if(!Array.isArray(e))return 0;for(let n of e){if(typeof n!=`object`||!n){t+=4;continue}let e=n;switch(e.type){case`text`:case`reasoning`:t+=ie(e.text||``);break;case`tool-call`:t+=Math.ceil((e.name||``).length/4)+Math.ceil((e.arguments||``).length/4)+4;break;case`image`:{let n=e.attachment,r=typeof n==`object`&&n&&typeof n.width==`number`&&typeof n.height==`number`?de(n.width,n.height):null;t+=(r??Math.ceil(JSON.stringify(e).length/4))+4;break}default:t+=4+Math.ceil(JSON.stringify(e).length/4)}}return t}function me(e,t=!1){return t&&(e==null||!Array.isArray(e.content)||e.content.length===0)?0:pe(e?.content)+4}function he(e){return Math.ceil(JSON.stringify(e).length/4)+4}function ge(e){let t=0;if(!Array.isArray(e))return 0;for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;e.type===`image`?t++:Array.isArray(e.content)&&(t+=ge(e.content))}return t}function y(e){if(!Array.isArray(e))return``;for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type===`text`&&typeof e.text==`string`&&e.text.trim()!==``)return e.text.replace(/\s+/g,` `).trim().slice(0,80)}return``}function _e(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;e.type===`tool-call`&&typeof e.name==`string`&&t.push(e.name)}return t}function ve(e){if(e?.kind===`agent-instructions`&&Array.isArray(e.changes)){let t=[];for(let n of e.changes){let e=n?.path;typeof e==`string`&&e!==``&&!t.includes(e)&&t.push(e)}if(t.length>0)return t.join(`, `)}let t=e?.plugin;if(typeof t==`string`&&t!==``)return t;let n=e?.kind;return typeof n==`string`&&n!==``?n:``}function ye(e){return e!=null&&(typeof e.kind==`string`&&e.kind!==``&&e.kind!==`user`||typeof e.form==`string`)}function be(e){if(typeof e!=`object`||!e)return!1;let t=e;switch(t.type){case`text-delta`:case`reasoning-delta`:return typeof t.text==`string`&&t.text!==``;case`tool-call-delta`:return typeof t.argumentsDelta==`string`&&t.argumentsDelta!==``||t.name!==void 0;default:return!1}}function xe(e){if(e===`reasoning`)return`reasoning`;if(e===`text`)return`text`;if(e===`tool-call`)return`toolarg`}function Se(e,t){let n={spans:{reasoning:0,text:0,toolarg:0},blocks:{reasoning:0,text:0,toolarg:0}};if(!Array.isArray(e)||!Number.isFinite(t))return n;let r,i=0;for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type!==`chunk`||e.chunk===null||typeof e.chunk!=`object`)continue;let a=e.chunk;if(a.type!==`block-start`)continue;let o=e.time;typeof o==`number`&&Number.isFinite(o)&&(r!==void 0&&(n.spans[r]+=Math.max(0,o-i)),r=xe(a.blockType),r!==void 0&&(n.blocks[r]+=1),i=o)}return r!==void 0&&(n.spans[r]+=Math.max(0,t-i)),n}function Ce(e,t){let n=[];if(!Array.isArray(e)||!Number.isFinite(t))return n;let r,i=0,a=e=>{r!==void 0&&e>i&&n.push({kind:r,start:i,end:e})};for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type!==`chunk`||e.chunk===null||typeof e.chunk!=`object`)continue;let n=e.chunk;if(n.type!==`block-start`)continue;let o=e.time;typeof o==`number`&&Number.isFinite(o)&&(a(o),r=xe(n.blockType),i=o)}return a(t),n}function we(e){let t=e.time0;if(typeof t!=`number`||!Number.isFinite(t))return;if(e.type===`tool-call-chunks`&&e.name!==void 0)return t;let n=e.type===`tool-call-chunks`?e.args:e.texts;if(!Array.isArray(n))return;let r=Array.isArray(e.dt)?e.dt:[],i=t;for(let[e,t]of n.entries()){if(e>0){let t=r[e-1];if(typeof t!=`number`||!Number.isFinite(t))return;i+=t}if(typeof t==`string`&&t!==``)return i}}function Te(e){if(Array.isArray(e))for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type===`chunk`){let t=e.time;if(typeof t==`number`&&Number.isFinite(t)&&be(e.chunk))return t;continue}let n=we(e);if(n!==void 0)return n}}function Ee(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`replace`)return null;let{startSeq:n,endSeq:r}=t;return typeof n!=`number`||!Number.isFinite(n)||typeof r!=`number`||!Number.isFinite(r)?null:{start:n,end:r}}function De(e){if(typeof e!=`string`||e===``)return null;try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}const Oe={read:`read`,read_image:`read`,write:`write`,edit:`write`,grep:`search`,glob:`search`};function ke(e){return e===void 0?null:Oe[e]??null}function Ae(e,t){return e===`str_replace_editor`?t!==null&&t.command===`view`?`read`:`write`:ke(e)}function b(e){return e===`str_replace_editor`||ke(e)!==null}function je(e){return b(e)||e===`run_code`}function Me(e,t){if(t===null)return null;if(e===`grep`||e===`glob`){let e=t.path;if(typeof e==`string`&&e!==``)return e;let n=t.pattern;return typeof n==`string`&&n!==``?n:null}for(let e of[`file_path`,`filePath`,`path`]){let n=t[e];if(typeof n==`string`&&n!==``)return n}return null}function Ne(e){if(e===``)return 0;let t=0;for(let n=0;n<e.length;n++)e[n]===`
13
+ `&&t++;return e.endsWith(`
14
+ `)?t:t+1}function x(e,t){return{added:typeof e==`string`?Ne(e):0,removed:typeof t==`string`?Ne(t):0}}function Pe(e,t){if(e===`edit`)return x(t.new_string,t.old_string);if(e===`write`)return x(t.content,void 0);if(e===`str_replace_editor`){if(t.command===`str_replace`)return x(t.new_str,t.old_str);if(t.command===`insert`)return x(t.new_str,void 0);if(t.command===`create`)return x(t.file_text,void 0)}return{added:0,removed:0}}function Fe(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.path!=`string`||t.path===``||typeof t.offset!=`number`||!Number.isFinite(t.offset)||t.offset<1||!Array.isArray(t.lines)||t.lines.length===0?null:{start:t.offset,count:t.lines.length}}function Ie(e){let t=e.limit;return typeof t==`number`&&Number.isFinite(t)&&t>0?{count:Math.floor(t),est:!0}:void 0}function Le(e,t){let n=Fe(e);return n===null?Ie(t):{start:n.start,count:n.count}}function Re(e){let t=e?.pattern;if(typeof t!=`string`||t===``)return;let n=e?.include;return typeof n==`string`&&n!==``?`${t} (${n})`:t}function ze(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.truncated!==!1)return null;let n=[];if(t.shape===`matches`&&Array.isArray(t.files))for(let e of t.files){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&t.path!==``&&Array.isArray(t.matches)&&n.push({path:t.path,hits:t.matches.length})}else if(t.shape===`paths`&&Array.isArray(t.paths))for(let e of t.paths)typeof e==`string`&&e!==``&&n.push({path:e,hits:0});return n.length>0?n:null}function Be(e){let t=b(e.tool)?De(e.argsRaw):null,n=Ae(e.tool,t);if(n===null)return[];let r={seq:e.seq,kind:n,tool:e.tool,err:e.err===!0,added:0,removed:0,path:``,...e.time===void 0?{}:{time:e.time},...e.gone===void 0?{}:{gone:e.gone},...e.parent===void 0?{}:{parent:e.parent},...e.program===void 0?{}:{program:e.program}};if(n===`search`){let n=ze(e.meta);if(n!==null){let i=Re(t),a=t===null?null:Me(e.tool,t),o=t!==null&&typeof t.path==`string`&&t.path!==``;return[...a!==null&&!n.some(e=>e.path===a)?[{...r,path:a,...o&&i!==void 0?{detail:i}:{},...o?{}:{pattern:!0}}]:[],...n.map(e=>({...r,path:e.path,...i===void 0?{}:{detail:i},...e.hits>0?{hits:e.hits}:{}}))]}}if(t===null)return[];let i=Me(e.tool,t);if(i===null)return[];let{added:a,removed:o}=Pe(e.tool,t),s=typeof t.path==`string`&&t.path!==``,c=n===`search`&&s?Re(t):void 0,l=n===`read`?Le(e.meta,t):void 0;return[{...r,path:i,added:a,removed:o,...c===void 0?{}:{detail:c},...l===void 0?{}:{read:l},...n===`search`&&!s?{pattern:!0}:{}}]}function Ve(e,t){let n=0,r=e.length,i;for(let a=e.length-1;a>=0;a--){let o=e[a].turn;if(o!==i){if(n>=t)break;n++,i=o}r=a}return e.slice(r)}function S(e){let t=0,n;for(let r of e)r.turn!==n&&(t++,n=r.turn);return t}function He(e,t){if(e.turnRuns=e.turnRuns??S(e.requests),e.turnRuns>t.maxKeptTurns&&(e.requests=Ve(e.requests,t.maxKeptTurns),e.turnRuns=S(e.requests)),e.requests.length>t.maxRequestSteps&&(e.requests=e.requests.slice(-t.maxRequestSteps),e.turnRuns=S(e.requests)),e.events.length>t.maxEvents&&(e.events=e.events.slice(-t.maxEvents)),e.spans.length>Ue&&(e.spans=e.spans.slice(-Ue)),e.fileOps.length>t.maxFileOps){let n=e.fileOps.length-t.maxFileOps;e.fileOpsFloor=Math.max(e.fileOpsFloor??0,e.fileOps[n-1].seq),e.fileOps=e.fileOps.slice(n)}if(e.archived.length>0){let n=0,r=e.requests.length>0?e.requests[0].seq:void 0;if(r!==void 0)for(;n<e.archived.length&&(e.archived[n].gone??1/0)<=r;)n++;if(e.archived.length-n>t.maxArchiveNodes&&(n=e.archived.length-t.maxArchiveNodes),n>0){let t=e.archived[n-1].gone;t!==void 0&&(e.archiveFloor=Math.max(e.archiveFloor??0,t)),e.archived=e.archived.slice(n)}}}const Ue=2e3;function We(){return{surface:[],sums:{user:0,inject:0,skill:0,assistant:0,tool:0},systemTokens:0,toolsTokens:0,requests:[],turnRuns:0,events:[],archived:[],callNames:{},fileOps:[],spans:[]}}const Ge={"deepseek-official":`deepseek`,"deepseek-account":`deepseek`,"kimi-coding":`moonshotai`,"minimax-cn":`minimax`,"zai-coding-cn":`zhipuai`};function Ke(e){return Ge[e]??e}function qe(e){return Ke(e)===`deepseek`}function C(e){if(typeof e==`number`)return Number.isFinite(e)?Math.max(0,Math.round(e)):null;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?Math.max(0,Math.round(t)):null}return null}function Je(e){let t=new Date(e),n=t.getUTCDay();if(n===0||n===6)return!1;let r=t.getUTCHours();return r>=1&&r<4||r>=6&&r<10}function Ye(e,t,n,r,i){let a=qe(t)&&!Je(r)?`off`:`peak`,o=e?.[t]??{},s=o[n]??{},c=s[a]??{uncached:0,cacheRead:0,cacheWrite:0,output:0},l={...s};l[a]={uncached:c.uncached+i.uncached,cacheRead:c.cacheRead+i.cacheRead,cacheWrite:c.cacheWrite+i.cacheWrite,output:c.output+i.output};let u={...o,[n]:l};return{...e??{},[t]:u}}function Xe(e){let t={};for(let n in e){let r={};for(let t in e[n]){let i=e[n][t],a={};i.peak!==void 0&&(a.peak={...i.peak}),i.off!==void 0&&(a.off={...i.off}),r[t]=a}t[n]=r}return t}function Ze(e,t,n){let r=e.model;r!==void 0&&(e.cost=Ye(e.cost,e.provider??``,r,t,n))}const Qe=[`reasoning`,`text`,`toolarg`];function w(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?0:Math.max(0,t-e)}function T(e){return e.timing===void 0&&(e.timing={wallMs:0,ttftMs:0,genMs:0,calls:0,toolsMs:0,toolCalls:0,tools:{}}),e.timing}const $e={reasoning:{ms:`reasoningMs`,n:`reasoningBlocks`},text:{ms:`textMs`,n:`textBlocks`},toolarg:{ms:`toolArgMs`,n:`toolArgBlocks`}};function et(e,t,n,r){let i=$e[t];n>0&&(e[i.ms]=(e[i.ms]??0)+n),r>0&&(e[i.n]=(e[i.n]??0)+r)}function tt(e,t,n){if(t===`__proto__`)return;if(!Object.hasOwn(e.tools,t)){if(Object.keys(e.tools).length>=16){let t=``,n=1/0;for(let r in e.tools)e.tools[r].ms<n&&(n=e.tools[r].ms,t=r);let r={};for(let n in e.tools)n!==t&&(r[n]=e.tools[n]);e.tools=r}e.tools[t]={calls:1,ms:n};return}let r=e.tools[t];e.tools[t]={calls:r.calls+1,ms:r.ms+n}}function nt(e){let t=e.sums.user+e.sums.inject+e.sums.skill+e.sums.assistant+e.sums.tool,n={ok:!0,...e.model===void 0?{}:{model:e.model},...e.provider===void 0?{}:{provider:e.provider},...e.contextWindow===void 0?{}:{contextWindow:e.contextWindow},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},current:{system:e.systemTokens,tools:e.toolsTokens,user:e.sums.user,inject:e.sums.inject,skill:e.sums.skill,assistant:e.sums.assistant,tool:e.sums.tool,total:t+e.systemTokens+e.toolsTokens},images:e.surface.reduce((e,t)=>e+(t.imgs??0),0),toolCalls:e.surface.reduce((e,t)=>t.cat===`tool`||t.cat===`skill`&&t.tool!==void 0?e+1:e,0),humanInputs:e.humanInputs??0,answers:e.answers??0,...e.lastUser===void 0?{}:{lastUser:e.lastUser},requests:[],events:[],nodes:[],droppedNodes:0,archive:[]};if(e.cost!==void 0&&(n.cost=Xe(e.cost)),e.timing!==void 0){let t={};for(let n in e.timing.tools)t[n]={...e.timing.tools[n]};n.timing={...e.timing,tools:t}}return e.systems!==void 0&&e.systems.length>0&&(n.systems=e.systems.map(e=>({...e}))),n}function rt(e,t){let n={requests:e.requests.map(e=>({...e})),events:e.events.map(e=>({...e})),nodes:[],droppedNodes:0,archive:e.archived.map(e=>({...e})),fileOps:e.fileOps.map(e=>({...e})),...e.fileOpsFloor===void 0?{}:{fileOpsFloor:e.fileOpsFloor},spans:e.spans.map(e=>({...e}))},r=Math.max(0,e.surface.length-t.maxNodes),i=e.surface.slice(0,r),a=e.surface.slice(r),o=i.filter(e=>e.cat===`inject`||e.cat===`skill`);if(n.nodes=o.length>0?[...o,...a]:a,n.droppedNodes=r-o.length,n.droppedNodes>0){let e=0;for(let t of i)t.cat!==`inject`&&t.cat!==`skill`&&(e=Math.max(e,t.seq));n.surfaceFloor=e}e.archiveFloor!==void 0&&(n.archiveFloor=e.archiveFloor);let s=n.requests,c=n.events,l=0;for(let e of c){for(;l<s.length&&s[l].seq<=e.seq;)l++;let t=s.at(l),n=l>0?s.at(l-1):void 0;t!==void 0&&typeof t.turn==`number`&&typeof t.step==`number`&&(e.turn=t.turn,e.step=t.step),n!==void 0&&typeof n.turn==`number`&&typeof n.step==`number`&&(e.fromTurn=n.turn,e.fromStep=n.step)}return n}function it(e){let t=nt(e),n=new Set;for(let t of e.requests)n.add(t.turn??0);let r=0,i=0,a=0,o=new Set;for(let t of e.events)t.kind===`inject`?r++:t.kind===`compaction`?i++:t.kind===`prune`&&a++,t.sub===`skill`&&typeof t.name==`string`&&t.name!==``&&o.add(t.name);t.counts={turns:n.size,steps:e.requests.length,injects:r,compactions:i,prunes:a,skills:o.size};let s=e.requests.at(-1);return s!==void 0&&(t.last={seq:s.seq,total:s.total,...typeof s.prompt==`number`?{prompt:s.prompt}:{}}),t.detailRev=e.detailRev??0,t}function at(e,t){return{rev:e.detailRev??0,head:it(e),...rt(e,t)}}function ot(e,t){return{...nt(e),...rt(e,t)}}function st(e,t){if(e===`assistant/message`)return`assistant`;if(e===`tool/result`)return`tool`;if(e===`developer/message`)return`inject`;let n=t?.source?.kind;return n===`skill-invocation`||n===`skill-catalog`?`skill`:ye(t?.source)?`inject`:`user`}function E(e){e.detailRev=(e.detailRev??0)+1}function ct(e){for(let t=e.length-1;t>=0;t--)if(e[t].tokens>0)return e[t].tokens;return 0}function lt(e,t){let n=[...e.systems??[],t];e.systems=n.length>8?n.slice(-8):n,e.systemTokens=ct(e.systems)}function ut(e){if(typeof e==`string`)return e;if(e!=null)try{return JSON.stringify(e)}catch{return}}function dt(e,t){for(let n of t)e.fileOps.push(n)}function ft(e,t,n){let r=e.pendingCodeOps??{},i=0;for(let e in r)i+=r[e].length;i+n.length>200||(e.pendingCodeOps={...r,[t]:[...r[t]??[],...n]})}function pt(e,t,n){for(let r of t)e.archived.push({...r,gone:n})}function mt(e,t,n){if(t.size===0)return[];let r=[],i=[];for(let n of e.surface)t.has(n.seq)?(e.sums[n.cat]-=n.tokens,i.push(n)):r.push(n);return pt(e,i,n),e.surface=r,i}function ht(e){let t=e?.message;return typeof t==`object`&&t?t:null}function gt(e){if(!Array.isArray(e))return``;for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type===`text`&&typeof e.text==`string`&&e.text!==``)return e.text}return``}function _t(e){let t=gt(typeof e==`object`&&e?e.content:void 0).match(/<skill_content\s+name="([^"]+)"/);return t===null?``:t[1]}function D(e,t,n,r){let i=st(n,r??void 0),a={seq:t.seq,time:t.time,cat:i,tokens:me(r,n===`assistant/message`||n===`developer/message`)},o=ge(r?.content);o>0&&(a.imgs=o);let s=r?.source,c=s?.form;if(typeof c==`string`&&(a.form=c),n===`assistant/message`){let e=y(r?.content);if(e!==``)a.text=e;else{let e=_e(r?.content);e.length>0&&(a.calls=e.slice(0,3))}}else if(n===`tool/result`){let n=s?.callId,i=typeof n==`string`?e.callNames[n]:void 0;if(i!==void 0){a.tool=i.name;let n=T(e),r=w(i.start,t.time);n.toolsMs+=r,n.toolCalls+=1,tt(n,i.name,r),e.stepStart!==void 0&&(e.stepSpans=[...e.stepSpans??[],{kind:`tools`,start:i.start,end:t.time}])}if(typeof n==`string`){let t={};for(let r in e.callNames)r!==n&&(t[r]=e.callNames[r]);e.callNames=t}r?.isError===!0&&(a.err=!0)}else if(s?.kind===`skill-invocation`)a.skill=typeof s.name==`string`?s.name:`?`;else if(s?.kind===`plugin`){if(s.form===`notice`&&typeof s.summary==`string`)a.text=s.summary;else if(s.form===`snapshot`&&Array.isArray(s.sections))a.text=s.sections.map(e=>e?.name).filter(Boolean).join(`, `).slice(0,80);else{let e=y(r?.content);e!==``&&(a.text=e)}}else{let e=y(r?.content);e!==``&&(a.text=e)}let l=e.pendingShadowedSeqs,u=e.pendingShadowEventSeq;delete e.pendingShadowedSeqs,delete e.pendingShadowEventSeq;let d=Ee(t.surfaceOp);if(d!==null){if(Array.isArray(l)&&l.length>0){let n=mt(e,new Set(l),t.seq);if(e.sums[i]+=a.tokens,e.surface.push(a),u!==void 0){let t=n.reduce((e,t)=>e+t.tokens,0),r=e.events.findIndex(e=>e.seq===u);r>=0&&(e.events[r]={...e.events[r],tokens:Math.max(0,t-a.tokens)})}return a}let n=-1,r=-1;for(let t=0;t<e.surface.length;t++)if(n<0&&e.surface[t].seq===d.start&&(n=t),e.surface[t].seq===d.end){r=t;break}if(n>=0&&r>=n){let o=e.surface.splice(n,r-n+1,a);pt(e,o,t.seq);for(let t of o)e.sums[t.cat]-=t.tokens;return e.sums[i]+=a.tokens,a}}return e.surface.push(a),e.sums[i]+=a.tokens,a}const vt=`ask_user_question`,yt=[`surface`,`sums`,`requests`,`events`,`archived`,`callNames`,`fileOps`,`timing`];function bt(e,t,r){let i,a=(t=yt)=>{i={...e};for(let n of t)n===`surface`?i.surface=[...e.surface]:n===`sums`?i.sums={...e.sums}:n===`requests`?i.requests=[...e.requests]:n===`events`?i.events=[...e.events]:n===`archived`?i.archived=[...e.archived]:n===`callNames`?i.callNames={...e.callNames}:n===`fileOps`?i.fileOps=[...e.fileOps]:e.timing!==void 0&&(i.timing={...e.timing,tools:{...e.timing.tools}});return i},o=t.data;try{switch(t.type){case`request/header`:{let e=o?.header??{},n=Array.isArray(e.tools)?e.tools:[],r=a([`events`]);r.toolsTokens=fe(n),e.config&&typeof e.config.model==`string`&&(r.model=e.config.model),e.config&&typeof e.config.provider==`string`&&(r.provider=e.config.provider);let i=e.config?.maxTokens;typeof i==`number`&&Number.isFinite(i)&&i>0?r.maxOutputTokens=i:delete r.maxOutputTokens,(o?.reason===`change`||o?.reason===`resume`)&&r.model&&r.lastModel&&r.model!==r.lastModel&&(r.events.push({seq:t.seq,time:t.time,kind:`model`,from:r.lastModel,to:r.model}),E(r)),r.model&&(r.lastModel=r.model);break}case`system/message`:{let e=a([`surface`,`sums`,`archived`]);delete e.pendingShadowedSeqs,delete e.pendingShadowEventSeq;let n=Ee(t.surfaceOp);if(n!==null){e.systems=(e.systems??[]).filter(e=>e.seq<n.start||e.seq>n.end);let r=new Set;for(let t of e.surface)t.seq>=n.start&&t.seq<=n.end&&r.add(t.seq);mt(e,r,t.seq).length>0&&E(e)}lt(e,{seq:t.seq,time:t.time,tokens:ae(ht(o)?.content)});break}case`request/context`:{let e=a([]);o&&typeof o.contextWindow==`number`&&(e.contextWindow=o.contextWindow),o&&typeof o.model==`string`&&(e.model=o.model),o&&typeof o.provider==`string`&&(e.provider=o.provider);break}case`tool/call`:if(o&&typeof o.callId==`string`&&typeof o.name==`string`){let e=a([`callNames`]),n=je(o.name)?ut(o.arguments):void 0;e.callNames[o.callId]={name:o.name,start:t.time,...n===void 0?{}:{argsRaw:n}}}break;case`tool/ptc-dispatch`:{let e=o?.rootCallId,n=o?.name;if(typeof e==`string`&&typeof n==`string`){let r=b(n)?ut(o?.arguments):void 0,i=Be({seq:t.seq,time:t.time,tool:n,argsRaw:r,err:o?.isError===!0});i.length>0&&ft(a([]),e,i)}break}case`assistant/attempt`:{let t=e.stepStart;if(t===void 0||t.firstToken!==void 0)return e;let n=Te(o?.stream);if(n===void 0)return e;let r=a([]);r.stepStart={time:t.time,firstToken:n};break}case`step/start`:{let e=a([]);e.stepStart={time:t.time},delete e.stepSpans,delete e.stepWaits,delete e.stepApprovals,delete e.stepRequestSeq;break}case`step/end`:{let n=e.stepStart;if(n===void 0)return e;let r=a(e.stepRequestSeq===void 0?[`timing`]:[`timing`,`requests`]);T(r).wallMs+=w(n.time,t.time);let i=[...e.stepWaits??[]];for(let n in e.stepApprovals)i.push({start:e.stepApprovals[n],end:t.time});i.sort((e,t)=>e.start-t.start||e.end-t.end);let o=0,s=n.time;for(let e of i){let n=Math.max(s,e.start),r=Math.min(e.end,t.time);r>n&&(o+=r-n,s=r)}let c=w(n.time,t.time)-o,l=e.requests.at(-1);l!==void 0&&l.seq===e.stepRequestSeq&&(r.requests[r.requests.length-1]={...l,activeMs:c});let u=[];for(let r of e.stepSpans??[]){let e=Math.max(n.time,r.start),i=Math.min(t.time,r.end);i>e&&u.push({kind:r.kind,start:e,end:i})}u.sort((e,t)=>e.start-t.start||e.end-t.end);let d=[],f=n.time;for(let e of u){let t=Math.max(f,e.start);e.end<=t||(t>f&&d.push({kind:`other`,start:f,end:t}),d.push({kind:e.kind,start:t,end:e.end}),f=e.end)}t.time>f&&d.push({kind:`other`,start:f,end:t.time}),r.spans=[...e.spans,...d],delete r.stepStart,delete r.stepSpans,delete r.stepWaits,delete r.stepApprovals,delete r.stepRequestSeq,E(r);break}case`approval/asked`:{let n=o?.id;if(e.stepStart===void 0||typeof n!=`string`)return e;let r=a([]);r.stepApprovals={...e.stepApprovals,[n]:t.time};break}case`approval/decided`:{let n=o?.id,r=e.stepApprovals,i=typeof n==`string`?r?.[n]:void 0;if(r===void 0||i===void 0)return e;let s=a([]);s.stepWaits=[...e.stepWaits??[],{start:i,end:t.time}];let c={};for(let e in r)e!==n&&(c[e]=r[e]);Object.keys(c).length>0?s.stepApprovals=c:delete s.stepApprovals;break}case`user/message`:case`developer/message`:{let r=t.type===`developer/message`,i=r?ht(o):n(t);if(r&&(i===null||!Array.isArray(i.content)))return e;let s=a([`surface`,`sums`,`archived`,`events`]);E(s);let c=D(s,t,t.type,i),l=i?.source;if(r||ye(l)){let e={seq:t.seq,time:t.time,kind:`inject`,form:typeof l?.form==`string`&&l.form!==``?l.form:`context`,tokens:c.tokens};if(l?.kind===`skill-invocation`)e.sub=`skill`,e.name=typeof l.name==`string`?l.name:`?`;else{let t=ve(l);t!==``&&(e.name=t,c.name=t),l?.form===`notice`&&typeof l.summary==`string`&&l.summary!==``&&(e.detail=l.summary)}s.events.push(e)}else s.humanInputs=(s.humanInputs??0)+1,c.text!==void 0&&c.text!==``&&(s.lastUser=c.text);break}case`tool/result`:{let r=n(t),i=r?.source?.callId,s=typeof i==`string`?e.callNames[i]:void 0,c=typeof i==`string`?e.pendingCodeOps?.[i]:void 0,l=a([`surface`,`sums`,`archived`,`events`,`fileOps`,`timing`]);E(l);let u=D(l,t,t.type,r);if(u.tool===vt&&(l.humanInputs=(l.humanInputs??0)+1),s!==void 0&&s.name===vt&&e.stepStart!==void 0&&(l.stepWaits=[...e.stepWaits??[],{start:s.start,end:t.time}]),s!==void 0&&dt(l,Be({seq:t.seq,time:t.time,tool:s.name,argsRaw:s.argsRaw,meta:o?.meta,err:r?.isError===!0})),c!==void 0&&c.length>0){let e=De(s?.argsRaw)?.description;dt(l,c.map(n=>({...n,parent:t.seq,...typeof e==`string`&&e!==``?{program:e}:{}})));let n={};for(let e in l.pendingCodeOps)e!==i&&(n[e]=l.pendingCodeOps[e]);Object.keys(n).length>0?l.pendingCodeOps=n:delete l.pendingCodeOps}if(u.tool===`skill`||u.tool===void 0){let e=_t(r);e!==``&&(u.skill=e,u.tool===void 0&&(u.tool=`skill`),l.sums.tool-=u.tokens,u.cat=`skill`,l.sums.skill+=u.tokens,l.events.push({seq:t.seq,time:t.time,kind:`inject`,form:`instructions`,sub:`skill`,name:e,tokens:u.tokens}))}break}case`assistant/message`:{let r=o?.usage,i=a([`surface`,`sums`,`archived`,`events`,`requests`,`timing`]);E(i);let s=i.systemTokens+i.toolsTokens+i.sums.user+i.sums.inject+i.sums.skill+i.sums.assistant+i.sums.tool,c={time:t.time,seq:t.seq,system:i.systemTokens,tools:i.toolsTokens,user:i.sums.user,inject:i.sums.inject,skill:i.sums.skill,assistant:i.sums.assistant,tool:i.sums.tool,total:s};o&&typeof o.turn==`number`&&(c.turn=o.turn),o&&typeof o.step==`number`&&(c.step=o.step),e.stepStart!==void 0&&(i.stepRequestSeq=c.seq);let l=null;if(typeof r==`object`&&r){let e=C(r.inputTokens),n=C(r.cacheReadTokens),a=C(r.cacheWriteTokens);l=C(r.outputTokens),(e!==null||n!==null||a!==null||l!==null)&&(c.prompt=(e??0)+(n??0)+(a??0),n!==null&&(c.cacheRead=n),l!==null&&(c.output=l),Ze(i,t.time,{uncached:e??0,cacheRead:n??0,cacheWrite:a??0,output:l??0}))}i.requests.push(c);let u=e.requests.at(-1);i.turnRuns=(e.turnRuns??S(e.requests))+(u===void 0?c.turn===void 0?0:1:c.turn===u.turn?0:1);let d=T(i);d.calls+=1;let f=e.stepStart;if(f!==void 0){let e=f.firstToken??Te(o?.stream);if(e!==void 0){let n=Ce(o?.stream,t.time),r=e;for(let e of n)r=Math.min(r,e.start);d.ttftMs+=w(f.time,r),d.genMs+=w(r,t.time);let a=[{kind:`ttft`,start:f.time,end:r}];for(let e of n){let n=Math.min(t.time,e.end);n<=e.start||a.push({kind:e.kind,start:a.length===1?r:e.start,end:n})}i.stepSpans=[...i.stepSpans??[],...a],l!==null&&(d.speedMs=(d.speedMs??0)+w(e,t.time),d.speedTokens=(d.speedTokens??0)+l);let s=Se(o?.stream,t.time);for(let e of Qe)et(d,e,s.spans[e],s.blocks[e])}}let p=n(t);D(i,t,t.type,p).text!==void 0&&(i.answers=(i.answers??0)+1);break}case`session/end-seed`:{if(o?.inherited!==!0)break;let e=a([]);e.cost={};break}case`plan/mode`:if(o&&typeof o.active==`boolean`){let e=a([`events`]);e.events.push({seq:t.seq,time:t.time,kind:`mode`,name:o.active?`plan.on`:`plan.off`}),E(e)}break;case`compaction/summary`:case`compaction/prune`:{let e=a([`events`]);E(e),o&&Array.isArray(o.shadowedSeqs)&&(e.pendingShadowedSeqs=o.shadowedSeqs.filter(e=>typeof e==`number`),e.pendingShadowEventSeq=t.seq),e.events.push({seq:t.seq,time:t.time,kind:t.type===`compaction/summary`?`compaction`:`prune`,tokens:o&&typeof o.shadowedTokenCount==`number`?o.shadowedTokenCount:0,...t.type===`compaction/summary`&&o&&Array.isArray(o.shadowedSeqs)?{count:o.shadowedSeqs.length}:{}});break}default:return e}}catch{i=void 0}return i===void 0?e:(He(i,r),i)}const O={maxRequestSteps:1500,maxKeptTurns:300,maxEvents:400,maxNodes:2e3,maxArchiveNodes:400,maxFileOps:400};function k(e){let t=e.volatile;return typeof t==`function`?t.call(e):e}function A(e){return i.number().min(1).step(1).default(e)}const xt=i.object({maxRequestSteps:A(O.maxRequestSteps),maxKeptTurns:A(O.maxKeptTurns),maxEvents:A(O.maxEvents),maxNodes:A(O.maxNodes),maxArchiveNodes:A(O.maxArchiveNodes),maxFileOps:A(O.maxFileOps),defaultPlacement:k(i.union([`all`,`tab`,`sidebar`]).default(`all`).loose()),defaultGranularity:k(i.union([`step`,`turn`]).default(`step`).loose()),defaultTrendMode:k(i.union([`total`,`delta`]).default(`total`).loose()),defaultDeltaBase:k(i.union([`step`,`turn`]).default(`step`).loose()),defaultToolSort:k(i.union([`size`,`count`,`name`]).default(`count`).loose()),defaultFileSort:k(i.union([`count`,`latest`,`path`]).default(`count`).loose()),insightsEntry:k(i.union([`show`,`hide`]).default(`show`).loose()),defaultDurationCurve:k(i.union([`show`,`hide`]).default(`show`).loose()),fleetTab:k(i.union([`show`,`hide`]).default(`show`).loose()),promptPrefix:k(i.string().default(``).loose()),promptSuffix:k(i.string().default(``).loose())});function St(e){let t=xt(e??{});return{maxRequestSteps:t.maxRequestSteps,maxKeptTurns:t.maxKeptTurns,maxEvents:t.maxEvents,maxNodes:t.maxNodes,maxArchiveNodes:t.maxArchiveNodes,maxFileOps:t.maxFileOps}}const j=t.object({seq:t.number().int().nonnegative(),time:t.number().optional(),cat:t.enum([`user`,`inject`,`skill`,`assistant`,`tool`]),tokens:t.number().int().nonnegative(),imgs:t.number().int().nonnegative().optional(),gone:t.number().int().nonnegative().optional(),form:t.string().optional(),name:t.string().optional(),text:t.string().optional(),tool:t.string().optional(),err:t.boolean().optional(),skill:t.string().optional(),calls:t.array(t.string()).optional()}).strict(),Ct=t.object({seq:t.number().int().nonnegative(),time:t.number(),tokens:t.number().int().nonnegative()}).strict(),wt=t.object({turn:t.number().optional(),step:t.number().optional(),time:t.number(),seq:t.number(),system:t.number().int().nonnegative(),tools:t.number().int().nonnegative(),user:t.number().int().nonnegative(),inject:t.number().int().nonnegative(),assistant:t.number().int().nonnegative(),tool:t.number().int().nonnegative(),total:t.number().int().nonnegative(),prompt:t.number().int().nonnegative().optional(),skill:t.number().int().nonnegative().optional(),cacheRead:t.number().int().nonnegative().optional(),output:t.number().int().nonnegative().optional(),activeMs:t.number().nonnegative().optional(),stepCount:t.number().int().positive().optional()}).strict(),Tt=t.object({seq:t.number(),time:t.number(),kind:t.enum([`compaction`,`prune`,`inject`,`model`,`mode`]),form:t.string().optional(),tokens:t.number().optional(),count:t.number().optional(),sub:t.string().optional(),name:t.string().optional(),detail:t.string().optional(),from:t.string().optional(),to:t.string().optional(),fromTurn:t.number().optional(),fromStep:t.number().optional(),turn:t.number().optional(),step:t.number().optional()}).strict(),M=t.object({seq:t.number().int().nonnegative(),path:t.string(),kind:t.enum([`read`,`write`,`search`]),tool:t.string(),time:t.number().optional(),err:t.boolean(),added:t.number().int().nonnegative(),removed:t.number().int().nonnegative(),detail:t.string().optional(),hits:t.number().int().positive().optional(),read:t.union([t.object({start:t.number().int().positive(),count:t.number().int().nonnegative()}).strict(),t.object({count:t.number().int().positive(),est:t.literal(!0)}).strict()]).optional(),parent:t.number().int().nonnegative().optional(),program:t.string().optional(),pattern:t.literal(!0).optional(),gone:t.number().int().nonnegative().optional()}).strict(),N=t.object({kind:t.enum([`ttft`,`reasoning`,`text`,`toolarg`,`tools`,`other`]),start:t.number(),end:t.number()}).strict(),Et=t.object({system:t.number().int().nonnegative(),tools:t.number().int().nonnegative(),user:t.number().int().nonnegative(),inject:t.number().int().nonnegative(),skill:t.number().int().nonnegative(),assistant:t.number().int().nonnegative(),tool:t.number().int().nonnegative(),total:t.number().int().nonnegative()}).strict(),Dt=t.object({uncached:t.number().int().nonnegative(),cacheRead:t.number().int().nonnegative(),cacheWrite:t.number().int().nonnegative(),output:t.number().int().nonnegative()}).strict(),Ot=t.object({peak:Dt.optional(),off:Dt.optional()}).strict(),kt=t.record(t.string(),Ot),P=t.record(t.string(),kt),At=t.object({calls:t.number().int().nonnegative(),ms:t.number().nonnegative()}).strict(),jt=t.object({wallMs:t.number().nonnegative(),ttftMs:t.number().nonnegative(),genMs:t.number().nonnegative(),reasoningMs:t.number().nonnegative().optional(),reasoningBlocks:t.number().int().nonnegative().optional(),textMs:t.number().nonnegative().optional(),textBlocks:t.number().int().nonnegative().optional(),toolArgMs:t.number().nonnegative().optional(),toolArgBlocks:t.number().int().nonnegative().optional(),speedTokens:t.number().nonnegative().optional(),speedMs:t.number().nonnegative().optional(),calls:t.number().int().nonnegative(),toolsMs:t.number().nonnegative(),toolCalls:t.number().int().nonnegative(),tools:t.record(t.string(),At)}).strict(),Mt=t.object({current:t.string(),minimum:t.string()}).strict(),Nt=t.object({turns:t.number().int().nonnegative(),steps:t.number().int().nonnegative(),injects:t.number().int().nonnegative(),compactions:t.number().int().nonnegative(),prunes:t.number().int().nonnegative(),skills:t.number().int().nonnegative().optional()}).strict(),Pt=t.object({seq:t.number(),total:t.number().int().nonnegative(),prompt:t.number().int().nonnegative().optional()}).strict(),Ft=t.object({ok:t.literal(!0),unsupported:Mt.optional(),model:t.string().optional(),provider:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),current:Et,images:t.number().int().nonnegative().optional(),toolCalls:t.number().int().nonnegative().optional(),humanInputs:t.number().int().nonnegative().optional(),answers:t.number().int().nonnegative().optional(),lastUser:t.string().optional(),counts:Nt.optional(),last:Pt.optional(),detailRev:t.number().int().nonnegative().optional(),requests:t.array(wt).optional(),events:t.array(Tt).optional(),cost:P.optional(),timing:jt.optional(),systems:t.array(Ct).optional(),nodes:t.array(j).optional(),droppedNodes:t.number().int().nonnegative().optional(),archive:t.array(j).optional(),surfaceFloor:t.number().int().nonnegative().optional(),archiveFloor:t.number().int().nonnegative().optional(),fileOps:t.array(M).optional(),fileOpsFloor:t.number().int().nonnegative().optional(),spans:t.array(N).optional()}).strict(),It=t.object({surface:t.array(j),sums:t.object({user:t.number().int().nonnegative(),inject:t.number().int().nonnegative(),skill:t.number().int().nonnegative(),assistant:t.number().int().nonnegative(),tool:t.number().int().nonnegative()}).strict(),systemTokens:t.number().int().nonnegative(),systems:t.array(Ct).optional(),toolsTokens:t.number().int().nonnegative(),model:t.string().optional(),provider:t.string().optional(),lastModel:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),requests:t.array(wt),turnRuns:t.number().int().nonnegative().optional(),events:t.array(Tt),archived:t.array(j),cost:P.optional(),archiveFloor:t.number().optional(),timing:jt.optional(),humanInputs:t.number().int().nonnegative().optional(),answers:t.number().int().nonnegative().optional(),lastUser:t.string().optional(),stepStart:t.object({time:t.number(),firstToken:t.number().optional()}).strict().optional(),stepWaits:t.array(t.object({start:t.number(),end:t.number()}).strict()).optional(),stepApprovals:t.record(t.string(),t.number()).optional(),stepRequestSeq:t.number().optional(),callNames:t.record(t.string(),t.object({name:t.string(),start:t.number(),argsRaw:t.string().optional()}).strict()),pendingShadowedSeqs:t.array(t.number()).optional(),pendingShadowEventSeq:t.number().optional(),detailRev:t.number().int().nonnegative().optional(),fileOps:t.array(M),fileOpsFloor:t.number().int().nonnegative().optional(),spans:t.array(N),stepSpans:t.array(N).optional(),pendingCodeOps:t.record(t.string(),t.array(M)).optional()});function Lt(e,t){let n=St(e);return{key:`contextTimeline`,stateSchema:It,wire:{viewSchema:Ft,view:e=>t()?it(e):ot(e,n)},init:()=>We(),apply:(e,t)=>bt(e,t,n),stateVersion:28}}function Rt(e){if(!Number.isFinite(e))return null;let t=new Date(e),n=t.getFullYear();return!Number.isFinite(n)||n<1970||n>9999?null:`${String(n).padStart(4,`0`)}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}const zt=t.object({n:t.number().int().nonnegative(),last:t.number()}).strict(),Bt=t.object({tokens:t.number().int().nonnegative(),requests:t.number().int().nonnegative(),cost:P.optional(),skills:t.record(t.string(),zt).optional()}).strict(),Vt=t.object({days:t.record(t.string(),Bt)}).strict(),Ht=t.object({days:t.record(t.string(),Bt),model:t.string().optional(),provider:t.string().optional(),stepStart:t.number().optional(),skillCalls:t.array(t.string()).optional()});function Ut(e){if(typeof e!=`object`||!e)return null;let t=e,n=C(t.inputTokens),r=C(t.cacheReadTokens),i=C(t.cacheWriteTokens),a=C(t.outputTokens);return n===null&&r===null&&i===null&&a===null?null:{uncached:n??0,cacheRead:r??0,cacheWrite:i??0,output:a??0}}function Wt(e,t,n){let r={...e.days,[t]:n},i=Object.keys(r);if(i.length>400){i.sort();let e=new Set(i.slice(0,i.length-400));r=Object.fromEntries(Object.entries(r).filter(([t])=>!e.has(t)))}return{...e,days:r}}function Gt(e,t,n){let r=Rt(n);if(r===null)return e;let i=e.days[r],a=i?.skills?.[t];if(a===void 0&&i?.skills!==void 0&&Object.keys(i.skills).length>=100)return e;let o={...i?.skills,[t]:{n:(a?.n??0)+1,last:a===void 0?n:Math.max(a.last,n)}};return Wt(e,r,{tokens:i?.tokens??0,requests:i?.requests??0,...i?.cost===void 0?{}:{cost:i.cost},skills:o})}function Kt(e){let t=e.data,n=e.type===`developer/message`?t?.message:t,r=typeof n==`object`&&n?n.source:void 0;if(typeof r!=`object`||!r)return``;let i=r;return i.kind===`skill-invocation`&&typeof i.name==`string`?i.name:``}function qt(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.toolCallId==`string`&&t.toolCallId!==``)return t.toolCallId;let n=t.source;if(typeof n!=`object`||!n)return null;let r=n.callId;return typeof r==`string`&&r!==``?r:null}function Jt(e,t){if(t.type===`request/header`){let n=t.data?.header?.config;if(typeof n!=`object`||!n)return e;let r=typeof n.model==`string`?n.model:void 0,i=typeof n.provider==`string`?n.provider:void 0,a=r===void 0?e.model:r,o=i===void 0?e.provider:i;return a===e.model&&o===e.provider?e:{...e,...a===void 0?{}:{model:a},...o===void 0?{}:{provider:o}}}if(t.type===`step/start`)return Number.isFinite(t.time)?e.stepStart===t.time?e:{...e,stepStart:t.time}:e;if(t.type===`step/end`){if(e.stepStart===void 0)return e;let t={...e};return delete t.stepStart,t}if(t.type===`session/end-seed`)return t.data?.inherited===!0?{days:{}}:e;if(t.type===`user/message`||t.type===`developer/message`){let n=Kt(t);return n===``?e:Gt(e,n,t.time)}if(t.type===`tool/call`){let n=t.data,r=n?.callId;if(n?.name!==`skill`||typeof r!=`string`||r===``)return e;let i=e.skillCalls??[];return i.includes(r)?e:{...e,skillCalls:[...i,r].slice(-100)}}if(t.type===`tool/result`){let n=t.data?.message,r=qt(n),i=e.skillCalls;if(r===null||i===void 0||!i.includes(r))return e;let a=i.filter(e=>e!==r),o={...e};a.length>0?o.skillCalls=a:delete o.skillCalls;let s=_t(n);return s===``?o:Gt(o,s,t.time)}if(t.type!==`assistant/message`)return e;let n=e.stepStart===void 0?t.time:e.stepStart,r=Rt(n);if(r===null)return e;let i=t.data,a=Ut(i?.usage),o=e.days[r],s=o?.cost;return a!==null&&e.model!==void 0&&(s=Ye(s,e.provider??``,e.model,n,a)),Wt(e,r,{tokens:(o===void 0?0:o.tokens)+(a===null?0:a.uncached+a.cacheRead+a.cacheWrite+a.output),requests:(o===void 0?0:o.requests)+1,...s===void 0?{}:{cost:s},...o?.skills===void 0?{}:{skills:o.skills}})}function Yt(){return{key:`contextActivity`,stateSchema:Ht,init:()=>({days:{}}),apply:(e,t)=>Jt(e,t),wire:{viewSchema:Vt,view:e=>({days:Object.fromEntries(Object.entries(e.days).map(([e,t])=>[e,{...t,...t.cost===void 0?{}:{cost:Xe(t.cost)},...t.skills===void 0?{}:{skills:Object.fromEntries(Object.entries(t.skills).map(([e,t])=>[e,{...t}]))}}]))})},stateVersion:4}}const Xt=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]);function Zt(e){return e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1)}function Qt(e){let t=Zt(e),n=t.lastIndexOf(`.`);return n<0?``:t.slice(n+1).toLowerCase()}function $t(e){return Xt.has(Qt(e))}function F(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function en(e){if(typeof e!=`object`||!e)return;let t=e,n=F(t.width),r=F(t.height);return n!==void 0&&r!==void 0?{width:n,height:r}:void 0}function tn(e){if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.type==`string`?t.type:t.kind;if(n!==`image`&&n!==`file`||t.attachment===null||typeof t.attachment!=`object`)return null;let r=t.attachment;if(typeof r.attachmentId!=`string`||r.attachmentId===``)return null;let i=typeof r.name==`string`&&r.name!==``?r.name:void 0,a=F(r.bytes);if(n===`file`)return{kind:`file`,attachmentId:r.attachmentId,...i===void 0?{}:{name:i},...a===void 0?{}:{bytes:a}};let o=en(r.originalDimensions),s=F(r.width),c=F(r.height),l=typeof r.mediaType==`string`&&r.mediaType!==``?r.mediaType:void 0;return{kind:`image`,attachmentId:r.attachmentId,...i===void 0?{}:{name:i},...l===void 0?{}:{mediaType:l},...a===void 0?{}:{bytes:a},...s===void 0?{}:{width:s},...c===void 0?{}:{height:c},...o===void 0?{}:{originalDimensions:o}}}function nn(){let e=m();return{used:e.used_heap_size,limit:e.heap_size_limit}}const rn=()=>{};function I(e=nn){let t=()=>{try{let{used:t,limit:n}=e();return!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<n*.6666666666666666}catch{return!0}},n=Promise.resolve();return{admit(e){let r=n.then(()=>t()?e():void 0);return n=r.then(rn,rn),r}}}function an(e){return typeof e?.fetch?.register==`function`?e.fetch.register.bind(e.fetch):void 0}function L(e,t,n,r,i){let a=an(t);if(a===void 0)return!1;try{e.effect(()=>a({path:n,methods:[`POST`],requestBody:`buffered`,fetch:r}),i)}catch{return!1}return!0}const on={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`};function R(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function z(e,t){return R({ok:!1,error:{code:e,message:t}})}function sn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function B(e,t,n){if(n>8)return null;if(Array.isArray(e)){for(let r of e){let e=B(r,t,n+1);if(e!==null)return e}return null}if(typeof e!=`object`||!e)return null;let r=tn(e);if(r!==null&&r.attachmentId===t)return r;for(let r of Object.values(e)){let e=B(r,t,n+1);if(e!==null)return e}return null}function cn(e,t){for(let n of e)try{let e=B(n,t,0);if(e!==null)return e}catch{}return null}function ln(e){let t=Zt(e.name??``);if(t!==``&&$t(t))return t;let n=e.mediaType===void 0?void 0:on[e.mediaType];return n===void 0?null:`attachment.${n}`}function un(e){let t=l(l(l(e)));return c(t)!==`v1`||c(l(t))!==`attachments`?null:d(l(l(t)),`cache`,`dsh-context`,`previews`)}function dn(e,t){if(typeof e?.fileHostPath!=`function`)return null;try{let n=e.fileHostPath({attachmentId:t.attachmentId,name:t.name??``,bytes:t.bytes??0});return typeof n==`string`&&n!==``?n:null}catch{return null}}async function fn(e,t){if(typeof e?.imageHostPath!=`function`)return null;let n;try{n=e.imageHostPath({attachmentId:t.attachmentId,...t.mediaType===void 0?{}:{mediaType:t.mediaType},...t.bytes===void 0?{}:{bytes:t.bytes},...t.width===void 0?{}:{width:t.width},...t.height===void 0?{}:{height:t.height},...t.name===void 0?{}:{name:t.name}})}catch{return null}if(typeof n!=`string`||n===``)return null;let r=ln(t);if(r===null)return null;let i=un(n);if(i===null)return null;let u=d(i,c(l(n)),c(n),r);try{await s(l(u),{recursive:!0});try{await o(n,u)}catch(e){e instanceof Error&&`code`in e&&e.code===`EEXIST`||await a(n,u)}return u}catch{return null}}async function pn(e,t){return t.kind===`file`?dn(e,t):await fn(e,t)}function mn(e,t=I()){e.inject([`connection`],n=>{L(n,n.get(`connection`),`/api/dsh-context/attachment`,async n=>{let r,i;try{let e=sn(await n.json());r=e?.sessionId,i=e?.attachmentId}catch{return z(`dsh-context/bad-request`,`body is not JSON`)}if(typeof r!=`string`||r===``)return z(`dsh-context/bad-request`,`missing sessionId`);if(typeof i!=`string`||i===``)return z(`dsh-context/bad-request`,`missing attachmentId`);try{let n=e.get(`sessionQuery`),a=typeof n?.observeSession==`function`?n.observeSession.bind(n):void 0;if(a===void 0)return R({ok:!0,value:null});let o=e.get(`attachments`);return R({ok:!0,value:await t.admit(async()=>{let e=await a(r,{projectionMode:`none`});try{let t=e?.events;if(!Array.isArray(t))return null;let n=cn(t,i);if(n===null)return null;let r=await pn(o,n);return r===null?null:{path:r}}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return z(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: attachment route`)})}function hn(e){if(!e.startsWith(`mcp__`))return;let t=e.lastIndexOf(`__`);if(t<5)return;let n=e.slice(5,t);return n.length>0?n:void 0}function gn(e){let t=hn(e);return t===void 0?void 0:`mcp:${t}`}function _n(e){return vn[e]}const vn=Object.freeze({read:`@deepseek-ai/dsh-tool-fs`,write:`@deepseek-ai/dsh-tool-fs`,edit:`@deepseek-ai/dsh-tool-fs`,read_image:`@deepseek-ai/dsh-tool-fs`,glob:`@deepseek-ai/dsh-tool-fs-search`,grep:`@deepseek-ai/dsh-tool-fs-search`,str_replace_editor:`@deepseek-ai/dsh-tool-str-replace-editor`,bash:`@deepseek-ai/dsh-tool-bash`,pwsh:`@deepseek-ai/dsh-tool-pwsh`,web_search:`@deepseek-ai/dsh-tool-web`,web_fetch:`@deepseek-ai/dsh-tool-web`,job_output:`@deepseek-ai/dsh-tool-jobs`,job_list:`@deepseek-ai/dsh-tool-jobs`,job_kill:`@deepseek-ai/dsh-tool-jobs`,ask_user_question:`@deepseek-ai/dsh-tool-ask-user`,plan:`@deepseek-ai/dsh-plan-mode`,exit_plan_mode:`@deepseek-ai/dsh-plan-mode`,skill:`@deepseek-ai/dsh-tool-skill`,todo_write:`@deepseek-ai/dsh-tool-todo`,subagent:`@deepseek-ai/dsh-tool-subagent`,subagent_fork:`@deepseek-ai/dsh-tool-subagent`,send_message:`@deepseek-ai/dsh-tool-subagent-control`,interrupt_agent:`@deepseek-ai/dsh-tool-subagent-control`,list_agents:`@deepseek-ai/dsh-tool-subagent-control`,ralph:`@deepseek-ai/dsh-tool-ralph`,workflow:`@deepseek-ai/dsh-tool-workflow`,run_code:`@deepseek-ai/dsh-tools`,schedule_create:`@deepseek-ai/dsh-schedule`,schedule_list:`@deepseek-ai/dsh-schedule`,schedule_delete:`@deepseek-ai/dsh-schedule`,create_goal:`@deepseek-ai/dsh-tool-goal`,get_goal:`@deepseek-ai/dsh-tool-goal`,update_goal:`@deepseek-ai/dsh-tool-goal`,lsp:`@deepseek-ai/dsh-tool-lsp`}),yn=f(g(import.meta.url)),V=new Map;function bn(e){let t=l(e);for(let e=0;e<12;e++){let e=V.get(t);if(e!==void 0)return e;let n=d(t,`package.json`);if(h(n))try{let e=JSON.parse(ee(n,`utf8`)).name;if(typeof e==`string`&&e)return V.set(t,e),e}catch{}let r=l(t);if(V.set(t,void 0),r===t)return;t=r}}const xn=/:\d+:\d+$/,Sn=Symbol.for(`cordis.original`);function Cn(e){return e?.[Sn]??e}const wn=bn(yn);function Tn(e){if(e)for(let t of e.split(`
15
+ `).slice(1)){let e=t.trim();if(!e.startsWith(`at `))continue;e=e.slice(3),e.startsWith(`async `)&&(e=e.slice(6)),e=e.replace(/\)\s*$/,``);let n=xn.exec(e);if(!n)continue;let r=e.slice(0,-n[0].length);if(r.includes(`(`)&&(r=r.slice(r.lastIndexOf(`(`)+1)),r.startsWith(`file://`))try{r=f(g(r))}catch{continue}else if(!/^[A-Za-z]:[\\/]/.test(r)&&!r.startsWith(`/`)&&!r.startsWith(`\\\\`))continue;else r=f(r);if(r===yn)continue;let i=bn(r);if(i!==void 0&&i!==wn)return i}}function En(e){let t=new Map,n=new WeakSet,r=e.fiber.name,i,a=[],o=e=>{if(!e||typeof e!=`object`||n.has(e))return;let o=e.register;if(typeof o!=`function`)return;n.add(e);let s=o.attributedOriginal??o;if(typeof s!=`function`)return;let c=e,l=function(e){let n=e?.name,a=i;(!a||a===`root`||a===r)&&(a=Tn(Error().stack));let o=s.call(this,e);return typeof n==`string`&&a&&a!==`root`&&a!==r&&a!==wn&&(t.set(n,a),typeof o==`function`)?()=>{try{return o()}finally{t.delete(n)}}:o};l.attributedOriginal=s,c.register=l,a.push(()=>{c.register===l&&(c.register=s)})};e.on(`internal/get`,(e,t,n,r)=>{if(t!==`tools`)return r();let a=r();return i=e.fiber.name,o(Cn(a)),a}),e.effect(()=>()=>{for(let e of a.splice(0))e()},`tools.register attribution`);let s=Cn(e.get(`tools`,!1));o(s);let c=new Set;try{let e=s?.layers?.global?.tools;if(e!==void 0&&typeof e.entries==`function`)for(let[t]of e.entries())c.add(t)}catch{}return{ownerOf:e=>gn(e)??t.get(e)??_n(e)??(c.has(e)?`<unknown-plugin>`:void 0)}}function H(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Dn(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function On(e){let t=e.get(`settings`);if(typeof t?.describe!=`function`)return null;try{let e=t.describe();if(!Array.isArray(e))return null;let n=null;for(let t of e)try{let e=H(t);if(e===null)continue;let r=H(e.value);if(r===null||typeof r.apiKeyEnv!=`string`||r.apiKeyEnv===``)continue;if(e.ns===`llm-deepseek`||e.ns===`llm-deepseek-api-key`)return r;n??=r}catch{continue}return n}catch{return null}}async function kn(e){let t=On(e);if(t===null)return null;let n=t.apiKeyEnv,r=typeof t.baseURL==`string`&&t.baseURL!==``?t.baseURL:`https://api.deepseek.com`,i=e.get(`credentials`),a=typeof i?.resolve==`function`?i.resolve.bind(i):void 0;if(a===void 0)return null;let o;try{o=await a(n)}catch{return null}let s=typeof o?.value==`string`?o.value:``;return s===``?null:{baseUrl:r,apiKey:s}}function An(e){let t=H(e);if(t===null)return null;let n=Array.isArray(t.balance_infos)?t.balance_infos:[],r=[];for(let e of n)try{let t=H(e);if(t===null)continue;let n=t.currency,i=Dn(t.granted_balance),a=Dn(t.topped_up_balance);if(typeof n!=`string`||n===``||i===null||a===null)continue;r.push({currency:n,total:i+a,granted:i,toppedUp:a})}catch{continue}return r.length>0?{isAvailable:t.is_available===!0,balances:r}:null}let jn=(e,t)=>fetch(e,t),U=null;async function Mn(e){if(U!==null)return U;U=(async()=>{let t=null;try{let n=await jn(e.baseUrl.replace(/\/+$/,``)+`/user/balance`,{headers:{accept:`application/json`,authorization:`Bearer `+e.apiKey},signal:AbortSignal.timeout(1e4)});n.ok&&(t=An(await n.json()))}catch{}return t})();let t=U;try{return await t}finally{U=null}}function Nn(e){e.inject([`connection`],t=>{L(t,t.get(`connection`),`/api/dsh-context/balance`,async()=>{let t=await kn(e),n=t===null?null:await Mn(t);return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: balance route`)})}const W=2e3,Pn={now:()=>te.now(),sleep:e=>new Promise(t=>setTimeout(t,e)),minRestMs:25,workBudgetMs:8e3,roundPauseMs:2e3};function Fn(e){let t=H(H(e)?.header);return t===null||typeof t.id!=`string`||t.id===``?null:t}const In=[`contextActivity`,`contextTimeline`];function Ln(e,t){try{let n=H(H(e.cachedSnapshot(t,In))?.values);return n!==null&&n.contextActivity!==void 0&&n.contextTimeline!==void 0}catch{return!1}}async function Rn(e,t,n){let i=await e.open(t,`read`,{signal:n}),a;try{let e=H(await i.read(0,void 0,{signal:n}))?.events;a=Array.isArray(e)?e:[]}catch(e){try{await i.close()}catch{}throw e}return await i.close(),{header:i.header,inheritedEventCount:i.inheritedEventCount,events:[...a,...r(a)]}}function zn(e,t){if(e===null||typeof e.get!=`function`)return!1;try{return e.get(t)!==void 0}catch{return!0}}async function Bn(e,t,n,r,i,a,o){let{header:s,inheritedEventCount:c,events:l}=r,u={},d=0;for(let e=W;;e+=W){let n=e>=l.length,r=o();u=H(t.restore(u,n?l:l.slice(0,e),0,s,c))?.checkpoint??{};let f=o()-r;if(d+=f,n)break;if(await a(f),i.aborted)return{outcome:`aborted`,workMs:d}}let f;try{f=t.prepare(s.id,{seed:l,meta:structuredClone(s),inheritedEventCount:c,eventState:`shared-frozen`})}catch(e){if(zn(n,s.id))return{outcome:`live`,workMs:d};throw e}t.hydrate(f,u,l,0);try{await t.write(f)}catch(t){e.logger.warn(`dsh-context: projection backfill write-back for "${s.id}" failed (cache stays stale): ${G(t)}`)}return{outcome:`done`,workMs:d}}function Vn(e){try{return String(H(e)?.name).startsWith(`SessionFormatUnsupported`)}catch{return!1}}function G(e){try{return String(e)}catch{return`unprintable error`}}function Hn(e,t=I(),n=Pn){let r=!1,i=!1,a=null,o=()=>{r&&!i&&a!==null&&(i=!0,a())},s=e.inject([`connection`],e=>{L(e,e.get(`connection`),`/api/dsh-context/backfill`,()=>(r=!0,o(),Response.json({ok:!0},{headers:{"cache-control":`no-store`}})),`dsh-context: backfill route`)}),c=e.inject([`sessionQuery`,`sessionProjectionCache`,`sessionPersistence`,`sessions`],r=>{let i=r,s=H(i.sessionQuery),c=H(i.sessionProjectionCache),l=H(i.sessionPersistence);if(s===null||typeof s.listSessions!=`function`||c===null||typeof c.cachedSnapshot!=`function`||typeof c.coldSnapshot!=`function`||l===null||typeof l.open!=`function`)return;let u=H(i.sessions),d=H(e.sessionProjections),f=d!==null&&typeof d.restore==`function`&&typeof d.hydrate==`function`&&u!==null&&typeof u.prepare==`function`&&typeof c.write==`function`?{restore:d.restore.bind(d),hydrate:d.hydrate.bind(d),prepare:u.prepare.bind(u),write:c.write.bind(c)}:null,p=new AbortController,m=async()=>{let r=await s.listSessions(p.signal);if(!Array.isArray(r))return;let i=0,a=0,o=!1,d=0,m=async e=>{if(p.signal.aborted)return;let t;try{await Promise.race([n.sleep(e),new Promise(e=>{t=()=>{e()},p.signal.addEventListener(`abort`,t,{once:!0})})])}finally{p.signal.removeEventListener(`abort`,t)}},h=async t=>{if(d+=t,d>=n.workBudgetMs){d=0,e.logger.info(`dsh-context: projection backfill pausing after ${Math.round(n.workBudgetMs/1e3)}s of fold work; resuming in ${Math.round(n.roundPauseMs/1e3)}s`),await m(n.roundPauseMs);return}await m(Math.max(n.minRestMs,t))};for(let s of r){if(p.signal.aborted)return;let r=Fn(s);if(r===null||typeof r.cwd!=`string`||zn(u,r.id)||Ln(c,r))continue;let d=n.now(),m=0;try{let a=await t.admit(async()=>{let t=await Rn(l,r.id,p.signal);if(f!==null&&t.events.length>W){let r=await Bn(e,f,u,t,p.signal,h,n.now);return m=r.workMs,r.outcome}return c.coldSnapshot(t.header,t.inheritedEventCount,t.events),`done`});if(a===void 0){o=!0;break}if(a===`aborted`)return;a===`done`&&i++}catch(t){Vn(t)?(a++,e.logger.debug(`dsh-context: projection backfill skipped "${r.id}" (${G(t)})`)):e.logger.warn(`dsh-context: projection backfill skipped "${r.id}" (${G(t)})`)}await h(Math.max(0,n.now()-d-m))}i>0&&e.logger.info(`dsh-context: projection rows backfilled for ${i} session(s)`),o&&e.logger.info(`dsh-context: projection backfill stopped early under heap pressure (remaining sessions refold on their next live activity)`),a>0&&e.logger.info(`dsh-context: projection backfill skipped ${a} session(s) (legacy log format is not migratable; sources left unchanged)`)};return a=()=>{m().catch(t=>{p.signal.aborted||e.logger.warn(`dsh-context: projection backfill stopped early (${G(t)})`)})},o(),()=>{p.abort()}});return()=>{for(let e of[s,c])e?.dispose?.()}}function Un(e){let t=e?.revision;return typeof t==`string`&&t!==``?t:void 0}function K(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function q(e,t){return K({ok:!1,error:{code:e,message:t}})}function Wn(e,t,n=I()){let r={live:!1},i=new Map;return e.inject([`connection`,`sessions`],a=>{let o=a.get(`sessions`),s=typeof o?.get==`function`?o.get.bind(o):void 0;if(s===void 0)return;let c=e.sessionProjections;if(L(a,a.get(`connection`),`/api/dsh-context/detail`,async r=>{let a;try{let e=await r.json();a=typeof e==`object`&&e?e.sessionId:void 0}catch{return q(`dsh-context/bad-request`,`body is not JSON`)}if(typeof a!=`string`||a===``)return q(`dsh-context/bad-request`,`missing sessionId`);try{let r=s(a);if(r!=null){let e=c.stateOf(r,`contextTimeline`);return K(e===void 0?{ok:!0,value:null}:{ok:!0,value:at(e,t)})}let o=e.get(`sessionQuery`),l=typeof o?.observeSession==`function`?o.observeSession.bind(o):void 0;return K(l===void 0?{ok:!0,value:null}:{ok:!0,value:await n.admit(async()=>{let n=await l(a,{projectionMode:`none`});try{let r=e.get(`sessionPersistence`),o=Un(n);if(o!==void 0){let e=i.get(a);if(e!==void 0&&e.revision===o&&e.persistence===r)return i.delete(a),i.set(a,e),e.value}let s=n?.events;if(!Array.isArray(s))return null;let c=We(),l=0;for(let e of s)c=bt(c,e,t),++l%1e3==0&&await new Promise(e=>setTimeout(e,0));let u=at(c,t);if(o!==void 0){i.delete(a),i.set(a,{persistence:r,revision:o,value:u});for(let e of i.keys()){if(i.size<=4)break;i.delete(e)}}return u}finally{let e=n?.[Symbol.dispose];typeof e==`function`&&e.call(n)}})??null})}catch(e){return q(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: detail route`))return r.live=!0,()=>{r.live=!1}}),r}const Gn=`0.1.7-rc.2`;function Kn(e){return e===`rc`?3:e===`beta`?2:1}function qn(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-(alpha|beta|rc)(?:\.(\d+))?)?(?:\+[0-9a-z.-]+)?$/i.exec(e.trim());if(t===null)return null;let n=t[4]?.toLowerCase();return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),rank:n===void 0?4:Kn(n),serial:t[5]?Number(t[5]):0}}function Jn(e,t){return e.major===t.major?e.minor===t.minor?e.patch===t.patch?e.rank===t.rank?e.serial-t.serial:e.rank-t.rank:e.patch-t.patch:e.minor-t.minor:e.major-t.major}function Yn(e,t=Gn){let n=qn(e),r=qn(t);return n===null||r===null||Jn(n,r)>=0}const Xn=t.object({name:t.string(),tokens:t.number().int().nonnegative(),description:t.string().optional(),plugin:t.string().optional(),schema:t.unknown().optional()}).strict(),Zn=t.object({seq:t.number(),time:t.number(),system:t.string().optional(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array(Xn)}).strict(),Qn=t.object({headers:t.array(Zn)}).strict(),$n=t.object({name:t.string(),tokens:t.number().int().nonnegative(),plugin:t.string().optional()}).strict(),er=t.object({headers:t.array(t.object({seq:t.number(),time:t.number(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array($n)}).strict())}).strict();function tr(e){if(e.type!==`request/header`)return null;let t=e.data?.header;if(typeof t!=`object`||!t)return null;let n=t,r=Array.isArray(n.tools)?n.tools:[];return{seq:e.seq,time:e.time,tools:r.map(e=>{let t=typeof e==`object`&&e?e:{},n={name:typeof t.name==`string`?t.name:`?`,tokens:he(e)};return typeof t.plugin==`string`&&t.plugin!==``&&(n.plugin=t.plugin),n})}}function nr(e){return{key:`contextHeaders`,stateSchema:Qn,wire:{viewSchema:er,view:t=>({headers:t.headers.map(t=>{let n={seq:t.seq,time:t.time,tools:t.tools.map(t=>{let n={name:t.name,tokens:t.tokens},r=t.plugin??(e===void 0?void 0:e(t.name));return r!==void 0&&(n.plugin=r),n})},r=t.systemTokens??(typeof t.system==`string`&&t.system!==``?re(t.system):void 0);return r!==void 0&&(n.systemTokens=r),n})})},init:()=>({headers:[]}),apply:(e,t)=>{let n=tr(t);if(n===null)return e;let r=e.headers.at(-1);if(r!==void 0&&r.seq===n.seq)return e;let i=[...e.headers,n];return{headers:i.length>50?i.slice(-50):i}},stateVersion:1}}const rr=t.object({});function J(e,t,n){let r=()=>n;return{key:e,stateSchema:rr,init:()=>({}),apply:e=>e,wire:{viewSchema:t,view:r},schema:t,view:r,stateVersion:1}}function ir(e){return J(`contextTimeline`,Ft,{ok:!0,unsupported:{current:e,minimum:Gn},current:{system:0,tools:0,user:0,inject:0,skill:0,assistant:0,tool:0,total:0},requests:[],events:[],nodes:[],droppedNodes:0,archive:[]})}function ar(){return J(`contextHeaders`,er,{headers:[]})}function or(){return J(`contextActivity`,Vt,{days:{}})}const sr=1e5;function cr(e){return X(e)?.full===!0}function lr(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function Y(e,t){return lr({ok:!1,error:{code:e,message:t}})}function X(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Z(e){if(!Array.isArray(e))return``;let t=``;for(let n of e){let e=X(n)?.text;typeof e==`string`&&(t+=e)}return t}const ur=/^\s*<system-reminder>[\s\S]*?<\/system-reminder>\s*/;function Q(e,t){return e.length>t?{text:e.slice(0,t)+`…`,cut:!0}:{text:e,cut:!1}}function dr(e){let t=e.mode;if(t!==`one-shot`&&t!==`continuable`)return null;let n={mode:t};for(let t of[`label`,`provider`,`agentProvider`,`agentModel`,`persona`]){let r=e[t];typeof r==`string`&&r!==``&&(n[t]=r)}return n}const fr=/^Team message \S+ from [^:]{1,64}:\s*/,pr=/^(?:Agent \S+ sent a message: |Team message from [^:\n]{1,64}:\s*)/;function mr(e,t,n){let r=X(n.source),i=r?.kind,a=null;if(i===`agent-message`||i===`team-message`){let o=Z(n.content);if(o=o.replace(i===`team-message`?fr:pr,``),o.trim()===``)return null;a={seq:e,time:t,kind:i===`agent-message`?`relay`:`mailbox`,text:o};let s=i===`agent-message`?r?.senderSessionId:r?.senderId;typeof s==`string`&&s!==``&&(a.from=s);let c=r?.senderName;typeof c==`string`&&c!==``&&(a.fromName=c)}else if(i===`subagent-settled`){let i=r?.summary,o=typeof i==`string`&&i.trim()!==``?i:Z(n.content);if(o.trim()===``)return null;a={seq:e,time:t,kind:`settled`,text:o};let s=r?.senderSessionId;typeof s==`string`&&s!==``&&(a.from=s)}if(a===null)return null;let o=Q(a.text,400);return a.text=o.text,a}function hr(e){return e===null||e.kind===`user`}function gr(e){let t=X(e.member);if(t===null||typeof t.name!=`string`||t.name===``)return null;let n={name:t.name,description:typeof t.description==`string`?t.description:``};return typeof t.provider==`string`&&t.provider!==``&&(n.provider=t.provider),(t.context===`fresh`||t.context===`fork`)&&(n.context=t.context),n}function _r(e,t){for(let n=e.length-1;n>=0;n--){let r=X(e[n]);if(r===null||r.type!==`assistant/message`)continue;let i=X(X(r.data)?.message)?.content;if(!Array.isArray(i))continue;let a=``;for(let e of i){let t=X(e);t?.type===`text`&&typeof t.text==`string`&&(a+=t.text)}if(a.trim()===``)continue;let o=typeof r.time==`number`&&Number.isFinite(r.time)?r.time:0,s=Q(a,t);return{time:o,text:s.text,cut:s.cut}}return null}function vr(e,t=!1){let n=t?sr:1600,r=t?sr:300,i,a,o=!1,s=[],c=new Map;for(let t of e){let e=X(t);if(e===null)continue;let r=e.type;if(typeof r!=`string`)continue;let l=typeof e.seq==`number`&&Number.isFinite(e.seq)?e.seq:0,u=typeof e.time==`number`&&Number.isFinite(e.time)?e.time:0,d=X(e.data);if(d===null)continue;if(r===`subagent/descriptor`){let e=dr(d);e!==null&&(i=e);continue}if(r===`team/member`){let e=gr(d);e!==null&&c.set(e.name,e);continue}if(r!==`user/message`)continue;let f=mr(l,u,d);if(f!==null){f.text.endsWith(`…`)&&(o=!0),s.push(f);continue}if(a===void 0&&hr(X(d.source))){let e=Z(d.content).replace(ur,``);if(e.trim()!==``){let t=Q(e,n);a=t.text,t.cut&&(o=!0)}}}s.sort((e,t)=>t.seq-e.seq),s.length>40&&(s.length=40,o=!0);let l=_r(e,r);return l!==null&&l.cut&&(o=!0),{...i===void 0?{}:{descriptor:i},...a===void 0?{}:{initialPrompt:a},...l===null?{}:{lastReply:{time:l.time,text:l.text}},...c.size>0?{roster:[...c.values()]}:{},messages:s,truncated:o}}function yr(e,t=I()){e.inject([`connection`],n=>{L(n,n.get(`connection`),`/api/dsh-context/fleet`,async n=>{let r,i=!1;try{let e=await n.json();r=X(e)?.sessionId,i=cr(e)}catch{return Y(`dsh-context/bad-request`,`body is not JSON`)}if(typeof r!=`string`||r===``)return Y(`dsh-context/bad-request`,`missing sessionId`);try{let n=e.get(`sessionQuery`),a=typeof n?.observeSession==`function`?n.observeSession.bind(n):void 0;return lr(a===void 0?{ok:!0,value:null}:{ok:!0,value:await t.admit(async()=>{let e=await a(r,{projectionMode:`none`}),t=e?.events;if(!Array.isArray(t))return null;try{return vr(t,i)}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return Y(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: fleet route`)})}function br(e){if(typeof e==`object`&&e&&typeof e.get==`function`){let t=e.get;return()=>{let e=t();return typeof e==`string`?e:``}}let t=typeof e==`string`?e:``;return()=>t}function xr(e){return()=>{let t=e();return t.trim().length===0?``:t}}const Sr=1e3;function Cr(e,t){e.inject([`systemPrompt`],e=>{let n=e.systemPrompt;n!=null&&typeof n.section==`function`&&typeof n.getSectionOrder==`function`&&(n.section({name:`dsh-context:prompt-prefix`,order:n.getSectionOrder(`HARNESS_IDENTITY`)-Sr,text:xr(br(t.promptPrefix)),interpolate:!1}),n.section({name:`dsh-context:prompt-suffix`,order:n.getSectionOrder(`DEPLOYMENT_PERSONA_SUFFIX`)+Sr,text:xr(br(t.promptSuffix)),interpolate:!1}))})}function wr(e){if(typeof e!=`object`||!e)return!1;let t=e.id;return typeof t!=`string`||t===``}function Tr(e){let t;for(let[n,r]of e.entries()){if(!wr(r)){t?.push(r);continue}t??=e.slice(0,n),t.push({...r,id:`dshctx-`+ne()})}return t}function Er(e){e.on(`agent/pre-step`,async(e,t)=>{let n=await t();try{if(n.kind!==`enter`||!Array.isArray(n.messages))return n;let e=Tr(n.messages);return e===void 0?n:{...n,messages:e}}catch{return n}},{prepend:!0})}function $(e){return typeof e==`string`&&e!==``?e:void 0}async function Dr(e){if(!(e===null||typeof e!=`object`&&typeof e!=`function`))try{let t=e[Symbol.asyncDispose];if(typeof t==`function`){await t.call(e);return}let n=e[Symbol.dispose];typeof n==`function`&&n.call(e)}catch{}}function Or(e){let t=H(e);return t===null||typeof t.name!=`string`||t.name===``?null:{name:t.name,description:typeof t.description==`string`?t.description:``,...typeof t.path==`string`&&t.path!==``?{path:t.path}:{},...typeof t.source==`string`&&t.source!==``?{source:t.source}:{}}}async function kr(e,t){if(t===void 0)return{};let n=H(e.get(`sessionQuery`));if(typeof n?.observeSession!=`function`)return{};let r;try{r=await n.observeSession.call(n,t)}catch{return{}}try{let e=H(r),t=$(H(e?.header)?.cwd),n=$(H(H(e?.projections)?.values)?.agentPreset);return{...t===void 0?{}:{cwd:t},...n===void 0?{}:{agentPreset:n}}}finally{await Dr(r)}}async function Ar(e,t,n){let r=H(e.get(`agentPresets`)),i;if(t!==void 0){let n=H(e.get(`agents`));if(typeof n?.get==`function`)try{i=n.get.call(n,t)}catch{i=void 0}}if(i!=null&&typeof r?.serviceFor==`function`){let e=H(r.serviceFor.call(r,i,`skills`));if(e!==null&&typeof e.list==`function`)return{registry:e,scope:i,lease:void 0}}let a=H(e.get(`skills`));if(a===null||typeof a.list!=`function`)return null;let o,s;if(typeof r?.acquireScope==`function`)try{s=await r.acquireScope.call(r,n),o=H(s)?.key}catch{s=void 0}return{registry:a,scope:o,lease:s}}function jr(e){e.inject([`connection`],t=>{L(t,t.get(`connection`),`/api/dsh-context/skills`,async t=>{let n=null,r;try{let i=H(await t.json()),a=$(i?.sessionId),o=await kr(e,a),s=o.cwd??$(i?.cwd),c=await Ar(e,a,o.agentPreset);if(c!==null){r=c.lease;let e=await c.registry.list({...s===void 0?{}:{cwd:s},...c.scope===void 0?{}:{scope:c.scope}}),t=Array.isArray(e)?e:[],i=[];for(let e of t){let t=Or(e);if(t!==null&&i.push(t),i.length>=500)break}n={skills:i}}}catch{}finally{await Dr(r)}return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: skills route`)})}const Mr=[`@deepseek-ai/dsh-session-projection`,`@deepseek-ai/dsh-session`],Nr=[`@deepseek-ai/dsh-session`,`@deepseek-ai/dsh-session-projection`],Pr=[`@deepseek-ai/dsh`,...Mr];function Fr(){try{return l(g(import.meta.resolve(`dsh-context/package.json`)))}catch{return l(g(import.meta.url))}}const Ir=Fr();function Lr(e,t){try{let n=JSON.parse(ee(e,`utf8`));if(typeof n!=`object`||!n)return;let r=n;return t!==void 0&&r.name!==t?void 0:typeof r.version==`string`&&r.version!==``?r.version:void 0}catch{return}}function Rr(e,t){try{return Lr(e(t+`/package.json`))}catch{return}}function zr(e,t){let n;try{n=l(e(t))}catch{return}for(;;){let e=Lr(d(n,`package.json`),t);if(e!==void 0)return e;let r=l(n);if(r===n)return;n=r}}function Br(e,t){for(let n of t){let t=Rr(e,n)??zr(e,n);if(t!==void 0)return t}}function Vr(e,t){let n=p(e,t);return!n.startsWith(`..`)&&!u(n)}function Hr(e,t){for(let n of Nr){let r;try{r=e(n)}catch{continue}if(Vr(t,r))continue;let i=Rr(e,n)??zr(e,n);if(i!==void 0)return i}}function Ur(e){return import.meta.resolve(e)}function Wr(t,n=Ur,r=Ir){let i=Hr(e=>{let t=n(e);if(!t.startsWith(`file:`))throw Error(`dsh-context: non-file module URL for ${e}`);return g(t)},r);if(i!==void 0)return i;try{let n=t.get(`dshHomePath`);if(typeof n==`function`){let t=e(n(`profiles`,`dsh-context-version-probe.cjs`)),r=Br(e=>t.resolve(e),Pr);if(r!==void 0)return r}}catch{}}const Gr=`dsh-context`,Kr=[`sessionProjections`];function qr(e,t){let n=I();Nn(e),jr(e),yr(e,n),mn(e,n);let r=Wr(e);if(r!==void 0&&!Yn(r)){e.sessionProjections.register(ir(r)),e.sessionProjections.register(ar()),e.sessionProjections.register(or());return}let i=En(e);Er(e);let a=Wn(e,St(t),n);e.sessionProjections.register(Lt(t,()=>a.live)),e.sessionProjections.register(nr(e=>i.ownerOf(e))),e.sessionProjections.register(Yt()),Hn(e,n),Cr(e,t)}export{xt as Config,qr as apply,Kr as inject,Gr as name};
16
+ //# sourceMappingURL=index.js.map