dsh-context 0.77.0 → 0.78.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,9 +1,18 @@
1
+ /**
2
+ * dsh-context v0.78.1
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
+ * @author bowenliang123
5
+ * @license Apache-2.0
6
+ * @homepage https://github.com/bowenliang123/dsh-context
7
+ * @built 2026-10-29T09:32:07+00:00
8
+ * @commit 4e60c910842c
9
+ * @commit-date 2026-10-29T17:28:47+08:00
10
+ */
1
11
 
2
12
  import { z } from "zod";
3
13
  import "@deepseek-ai/dsh-session";
4
14
  import z$1 from "@deepseek-ai/schemastery";
5
15
  import { Context } from "@deepseek-ai/cordis";
6
- //#region src/host/activity.d.ts
7
16
  interface ToolStart {
8
17
  start: number;
9
18
  day: string;
@@ -20,8 +29,6 @@ interface ActivityState {
20
29
  /** Pending `skill`-tool call ids: the wrapper match alone is not trusted, or a `read` quoting it would book a load. */
21
30
  skillCalls?: string[];
22
31
  }
23
- //#endregion
24
- //#region src/host/headers.d.ts
25
32
  /** v1 rows carried the producer description and raw schema; later folds append metadata-only. */
26
33
  interface StoredHeaderTool {
27
34
  name: string;
@@ -41,8 +48,6 @@ interface StoredHeaderRecord {
41
48
  interface HeadersState {
42
49
  headers: StoredHeaderRecord[];
43
50
  }
44
- //#endregion
45
- //#region src/host/foldState.d.ts
46
51
  /** The state's command record: the wire record plus the callId the fold pairs result/job events on. Never served —
47
52
  * `foldWire` strips it (optional precisely so the strip is a plain `delete`). */
48
53
  interface CommandStateRecord extends CommandRecord {
@@ -52,6 +57,12 @@ interface TimelineState {
52
57
  /** Model-visible surface, newest last. */
53
58
  surface: SurfaceNode[];
54
59
  sums: Record<Category, number>;
60
+ /** Live assistant-node reasoning price — a running subset of `sums.assistant` (the thinking split's prompt-side share). */
61
+ assistantReasoning: number;
62
+ /** Live assistant-node text price — a running subset of `sums.assistant` (the answers split's prompt-side share). */
63
+ assistantAnswerTokens: number;
64
+ /** Live assistant-node tool-call price — a running subset of `sums.assistant` (the tool-call split's prompt-side share). */
65
+ assistantCallTokens: number;
55
66
  systemTokens: number;
56
67
  /** The live system-prompt nodes, oldest first; `systemTokens` is the LAST nonempty one (the harness rule), so an empty dormant node
57
68
  * keeps its position. Absent rows fall back to the header epoch's envelope figure. */
@@ -78,6 +89,12 @@ interface TimelineState {
78
89
  archived: SurfaceNode[];
79
90
  /** Cumulative billed-token totals per (provider, model, period); never trimmed, so the estimate covers the COMPLETE log. */
80
91
  cost?: SessionCostUsage;
92
+ /** Cumulative generated reasoning price over the COMPLETE log (the thinking split's output side); never trimmed. */
93
+ generatedReasoning?: number;
94
+ /** Cumulative generated text price over the COMPLETE log (the answers split's output side); never trimmed. */
95
+ generatedAnswerTokens?: number;
96
+ /** Cumulative generated tool-call price over the COMPLETE log (the tool-call split's output side); never trimmed. */
97
+ generatedCallTokens?: number;
81
98
  humanInputs?: number;
82
99
  answers?: number;
83
100
  /** The user's newest own message as a bounded one-line preview. Last-wins: a text-less input keeps the previous line. */
@@ -139,8 +156,6 @@ interface TimelineState {
139
156
  * Bounded by PENDING_CODE_OPS_MAX, so a hostile log that never settles a run_code cannot grow it. */
140
157
  pendingCodeOps?: Record<string, FileOpRecord[]>;
141
158
  }
142
- //#endregion
143
- //#region src/shared/types.d.ts
144
159
  declare module '@deepseek-ai/dsh-session-projection/types' {
145
160
  interface SessionProjectionMap {
146
161
  /** Slim head on the split generation, inline value on channel-less hosts; key absence = no host half. */
@@ -272,11 +287,27 @@ interface Snapshot {
272
287
  inject: number;
273
288
  skill: number;
274
289
  assistant: number;
290
+ /** Heuristic reasoning tokens INSIDE the live assistant nodes — a subset of `assistant` (the thinking split's prompt-side share).
291
+ * Absent on rows folded before the field existed, and on foreign hosts. */
292
+ assistantReasoning?: number;
293
+ /** Heuristic text-block tokens INSIDE the live assistant nodes — a subset of `assistant` (the answers split's prompt-side share).
294
+ * Absent on rows folded before the field existed, and on foreign hosts. */
295
+ assistantAnswerTokens?: number;
296
+ /** Heuristic tool-call tokens INSIDE the live assistant nodes — a subset of `assistant` (the tool-call split's prompt-side share).
297
+ * Absent on rows folded before the field existed, and on foreign hosts. */
298
+ assistantCallTokens?: number;
275
299
  tool: number;
276
300
  total: number;
277
301
  };
278
302
  /** Image blocks in the CURRENT context (uploads plus nested tool-result images). Absent = 0. */
279
303
  images?: number;
304
+ /** Heuristic reasoning tokens GENERATED across the complete log (the thinking split's output side; a provider `reasoningTokens` count
305
+ * wins when reported). Absent = none. */
306
+ generatedReasoning?: number;
307
+ /** Heuristic text-block tokens GENERATED across the complete log (the answers split's output side). Absent = none. */
308
+ generatedAnswerTokens?: number;
309
+ /** Heuristic tool-call tokens GENERATED across the complete log (the tool-call split's output side). Absent = none. */
310
+ generatedCallTokens?: number;
280
311
  /** Tool calls whose result is live (a `skill`-tool node keeps counting). Absent = 0. */
281
312
  toolCalls?: number;
282
313
  /** Whole-session tally of non-injection `user/message` plus answered `ask_user_question` over the COMPLETE log. Absent = 0. */
@@ -466,8 +497,9 @@ interface ToolTimingTotals {
466
497
  ms: number;
467
498
  }
468
499
  /** Whole-session totals over the COMPLETE log: `wallMs` whole steps, `ttftMs` step-start → decode-start, `genMs`
469
- * decode-start → assistant-message, `toolsMs` per-call. The decode window opens at the first OBSERVABLE instant, so
470
- * marker-tiled windows never double-count; speed* keep the first-token anchor; `calls`/`toolCalls` count messages/pairs. */
500
+ * decode-start → assistant-message, `toolsMs` per-call and `toolBusyMs` per-step union. The decode window opens at the
501
+ * first OBSERVABLE instant, so marker-tiled windows never double-count; speed* keep the first-token anchor;
502
+ * `calls`/`toolCalls` count messages/pairs. */
471
503
  interface TimingTotals {
472
504
  wallMs: number;
473
505
  ttftMs: number;
@@ -482,6 +514,9 @@ interface TimingTotals {
482
514
  speedMs?: number;
483
515
  calls: number;
484
516
  toolsMs: number;
517
+ /** Wall time with at least one tool running: parallel runs overlap once, and runs outside every step window price
518
+ * nothing. Absent on rows folded before the field existed (the card attributes the clamped per-call sum instead). */
519
+ toolBusyMs?: number;
485
520
  toolCalls: number;
486
521
  /** Per-tool-name tallies behind the timing card's ranking (bounded). */
487
522
  tools: Record<string, ToolTimingTotals>;
@@ -504,6 +539,12 @@ interface SurfaceNode {
504
539
  time?: number;
505
540
  cat: Category;
506
541
  tokens: number;
542
+ /** Reasoning-block price inside an assistant node (absent when zero); a subset of `tokens`. */
543
+ reasoning?: number;
544
+ /** Text-block price inside an assistant node (absent when zero); a subset of `tokens`. */
545
+ answerTokens?: number;
546
+ /** Tool-call price inside an assistant node (absent when zero); a subset of `tokens`. */
547
+ callTokens?: number;
507
548
  /** Image blocks inside this node's message (absent when zero). */
508
549
  imgs?: number;
509
550
  /** Set only on `archive` entries: the seq of the replacement event that shadowed this node. */
@@ -599,8 +640,6 @@ interface PlatformBalance {
599
640
  /** One entry per currency the account holds; at least one. */
600
641
  balances: PlatformBalanceEntry[];
601
642
  }
602
- //#endregion
603
- //#region src/host/config.d.ts
604
643
  declare const DEFAULT_BOUNDS: {
605
644
  maxRequestSteps: number;
606
645
  /** Newest whole-turn window kept; trimming crosses whole turns, never mid-turn. */
@@ -662,11 +701,7 @@ export declare const Config: z$1<Schemastery.ObjectS<NoInfer<{
662
701
  promptPrefix: z$1<string, string, "defined">;
663
702
  promptSuffix: z$1<string, string, "defined">;
664
703
  }>>, "plain">;
665
- //#endregion
666
- //#region src/host/index.d.ts
667
704
  export declare const name = "dsh-context";
668
705
  export declare const inject: string[];
669
706
  export declare function apply(ctx: Context, config: Config): void;
670
- //#endregion
671
- export type { ActivityDay, ActivityState, Category, ContextActivity, ContextEventRecord, ContextHeaders, ContextTimeline, ContextTimelineDetail, HeaderRecord, HeaderTool, HeadersState, PlatformBalance, PlatformBalanceEntry, RequestRecord, SkillInfo, Snapshot, SurfaceNode, TimelineCounts, TimelineLast, TimelineState };
672
- //# sourceMappingURL=index.d.ts.map
707
+ export type { ActivityDay, ActivityState, Category, ContextActivity, ContextEventRecord, ContextHeaders, ContextTimeline, ContextTimelineDetail, HeaderRecord, HeaderTool, HeadersState, PlatformBalance, PlatformBalanceEntry, RequestRecord, SkillInfo, Snapshot, SurfaceNode, TimelineCounts, TimelineLast, TimelineState };
package/lib/index.js CHANGED
@@ -1,16 +1,15 @@
1
1
  /**
2
- * dsh-context v0.77.0
2
+ * dsh-context v0.78.1
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-25T16:52:54+00:00
8
- * @commit 8e6555a84099
9
- * @commit-date 2026-10-26T00:50:12+08:00
7
+ * @built 2026-10-29T09:32:07+00:00
8
+ * @commit 4e60c910842c
9
+ * @commit-date 2026-10-29T17:28:47+08:00
10
10
  */
11
11
 
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 ee,readFileSync as te}from"node:fs";import{fileURLToPath as h}from"node:url";import{performance as ne}from"node:perf_hooks";import{randomUUID as re}from"node:crypto";function ie(e){return typeof e!=`string`||e.length===0?0:Math.ceil(e.length/4)+4}function ae(e){return Math.ceil(e.length/4)+4}function oe(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 se=147456,g=(e,t)=>Math.floor(e/t),_=(e,t)=>Math.floor((e+t-1)/t);function ce(e,t){let n=e*(t+1)+2;return e%2==1&&(n+=t+1),n+=_(e,2)*(t+1)%2*2,n}function le(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=g(n-2,2);e%2==1&&--e,s=42,o=e*42}else if(a<2){let e=g(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=_(g(o,14),3),l=_(g(s,14),3);return{nLlmH:c,nLlmW:l,bestHeight:o,bestWidth:s,numTokens:ce(c,l)}}function ue(e,t,n,r){let i=_(g(n,14),3),a=_(g(r,14),3),o={nLlmH:i,nLlmW:a,bestHeight:n,bestWidth:r,numTokens:ce(i,a)};if(o.numTokens>381){o=le(e,t,381);let n=381;for(;o.numTokens>381;)--n,o=le(e,t,n)}return o.numTokens+=3,o}function de(e,t){let n=e,r=t;n>r*8&&(n=r*8);let i=n*r;if(i<se&&i>0){let e=Math.sqrt(se/i);n=Math.trunc(n*e),r=Math.trunc(r*e)}let a=_(n,14)*14,o=_(r,14)*14;return ue(r,n,o,a)}function fe(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return null;try{let n=de(e,t);for(let e=1;e<10;e++){let e=de(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 pe(e){return e.length>0?Math.ceil(JSON.stringify(e).length/4)+4:0}function me(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+=ae(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`?fe(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 he(e,t=!1){return t&&(e==null||!Array.isArray(e.content)||e.content.length===0)?0:me(e?.content)+4}function ge(e){return Math.ceil(JSON.stringify(e).length/4)+4}function _e(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+=_e(e.content))}return t}function v(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 ve(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 ye(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 be(e){return e!=null&&(typeof e.kind==`string`&&e.kind!==``&&e.kind!==`user`||typeof e.form==`string`)}function xe(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 Se(e){if(e===`reasoning`)return`reasoning`;if(e===`text`)return`text`;if(e===`tool-call`)return`toolarg`}function Ce(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 we(e){return Te(e,NaN).firstToken}function Te(e,t){let n={spans:{reasoning:0,text:0,toolarg:0},blocks:{reasoning:0,text:0,toolarg:0}},r=[],i={spans:r,tally:n};if(!Array.isArray(e))return i;let a=Number.isFinite(t),o,s,c=0,l=e=>{s===void 0||e<=c||(r.push({kind:s,start:c,end:e}),n.spans[s]+=e-c)};for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type===`chunk`){let t=e.chunk!==null&&typeof e.chunk==`object`?e.chunk:null,r=e.time;if(!Number.isFinite(r))continue;if(a&&t!==null&&t.type===`block-start`?(l(r),s=Se(t.blockType),s!==void 0&&(n.blocks[s]+=1),c=r):o===void 0&&xe(t)&&(o=r),!a&&o!==void 0)break;continue}if(o===void 0&&(o=Ce(e)),!a&&o!==void 0)break}return a&&l(t),o!==void 0&&(i.firstToken=o),i}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 y(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 De={read:`read`,read_image:`read`,write:`write`,edit:`write`,grep:`search`,glob:`search`};function Oe(e){return e===void 0?null:De[e]??null}function ke(e,t){return e===`str_replace_editor`?t!==null&&t.command===`view`?`read`:`write`:Oe(e)}function Ae(e){return e===`str_replace_editor`||Oe(e)!==null}function je(e){return Ae(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]===`
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 g}from"node:fs";import{fileURLToPath as _}from"node:url";import{performance as v}from"node:perf_hooks";import{randomUUID as ee}from"node:crypto";function te(e){return typeof e!=`string`||e.length===0?0:Math.ceil(e.length/4)+4}function ne(e){return Math.ceil(e.length/4)+4}function re(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;else try{let e=JSON.stringify(n);typeof e==`string`&&(t+=e.length)}catch{}}return Math.ceil(t/4)+4}const ie=147456,y=(e,t)=>Math.floor(e/t),b=(e,t)=>Math.floor((e+t-1)/t);function ae(e,t){let n=e*(t+1)+2;return e%2==1&&(n+=t+1),n+=b(e,2)*(t+1)%2*2,n}function oe(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=y(n-2,2);e%2==1&&--e,s=42,o=e*42}else if(a<2){let e=y(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=b(y(o,14),3),l=b(y(s,14),3);return{nLlmH:c,nLlmW:l,bestHeight:o,bestWidth:s,numTokens:ae(c,l)}}function se(e,t,n,r){let i=b(y(n,14),3),a=b(y(r,14),3),o={nLlmH:i,nLlmW:a,bestHeight:n,bestWidth:r,numTokens:ae(i,a)};if(o.numTokens>381){o=oe(e,t,381);let n=381;for(;o.numTokens>381;)--n,o=oe(e,t,n)}return o.numTokens+=3,o}function ce(e,t){let n=e,r=t;n>r*8&&(n=r*8);let i=n*r;if(i<ie&&i>0){let e=Math.sqrt(ie/i);n=Math.trunc(n*e),r=Math.trunc(r*e)}let a=b(n,14)*14,o=b(r,14)*14;return se(r,n,o,a)}function le(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return null;try{let n=ce(e,t);for(let e=1;e<10;e++){let e=ce(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 ue(e){return e.length>0?Math.ceil(JSON.stringify(e).length/4)+4:0}const x=e=>ne(e.text||``),de=e=>Math.ceil((e.name||``).length/4)+Math.ceil((e.arguments||``).length/4)+4;function fe(e,t,n){let r=0;if(!Array.isArray(e))return r;for(let i of e){if(typeof i!=`object`||!i)continue;let e=i;e.type===t&&(r+=n(e))}return r}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+=x(e);break;case`tool-call`:t+=de(e);break;case`image`:{let n=e.attachment,r=typeof n==`object`&&n&&typeof n.width==`number`&&typeof n.height==`number`?le(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){return fe(e,`reasoning`,x)}function he(e){return fe(e,`tool-call`,de)}function ge(e){return fe(e,`text`,x)}function _e(e,t=!1){return t&&(e==null||!Array.isArray(e.content)||e.content.length===0)?0:pe(e?.content)+4}function ve(e){return Math.ceil(JSON.stringify(e).length/4)+4}function ye(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+=ye(e.content))}return t}function S(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 be(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 xe(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 Se(e){return e!=null&&(typeof e.kind==`string`&&e.kind!==``&&e.kind!==`user`||typeof e.form==`string`)}function Ce(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 we(e){if(e===`reasoning`)return`reasoning`;if(e===`text`)return`text`;if(e===`tool-call`)return`toolarg`}function Te(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 Ee(e){return De(e,NaN).firstToken}function De(e,t){let n={spans:{reasoning:0,text:0,toolarg:0},blocks:{reasoning:0,text:0,toolarg:0}},r=[],i={spans:r,tally:n};if(!Array.isArray(e))return i;let a=Number.isFinite(t),o,s,c=0,l=e=>{s===void 0||e<=c||(r.push({kind:s,start:c,end:e}),n.spans[s]+=e-c)};for(let t of e){if(typeof t!=`object`||!t)continue;let e=t;if(e.type===`chunk`){let t=e.chunk!==null&&typeof e.chunk==`object`?e.chunk:null,r=e.time;if(!Number.isFinite(r))continue;if(a&&t!==null&&t.type===`block-start`?(l(r),s=we(t.blockType),s!==void 0&&(n.blocks[s]+=1),c=r):o===void 0&&Ce(t)&&(o=r),!a&&o!==void 0)break}else if(o===void 0&&(o=Te(e)),!a&&o!==void 0)break}return a&&l(t),o!==void 0&&(i.firstToken=o),i}function Oe(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 ke(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 Ae={read:`read`,read_image:`read`,write:`write`,edit:`write`,grep:`search`,glob:`search`};function je(e){return e===void 0?null:Ae[e]??null}function Me(e,t){return e===`str_replace_editor`?t!==null&&t.command===`view`?`read`:`write`:je(e)}function Ne(e){return e===`str_replace_editor`||je(e)!==null}function Pe(e){return Ne(e)||e===`run_code`}function Fe(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 Ie(e){if(e===``)return 0;let t=0;for(let n=0;n<e.length;n++)e[n]===`
13
13
  `&&t++;return e.endsWith(`
14
- `)?t:t+1}function b(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 b(t.new_string,t.old_string);if(e===`write`)return b(t.content,void 0);if(e===`str_replace_editor`){if(t.command===`str_replace`)return b(t.new_str,t.old_str);if(t.command===`insert`)return b(t.new_str,void 0);if(t.command===`create`)return b(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=Ae(e.tool)?y(e.argsRaw):null,n=ke(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){return e===`bash`||e===`pwsh`||e===`run_code`?e:null}function x(e){return typeof e==`string`&&e!==``?e:void 0}function He(e){return typeof e==`string`?y(e):typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Ue(e,t,n){let r=He(t),i=x(e===`run_code`?r?.code:r?.command);if(i===void 0)return null;let a={cmd:i.length>n?i.slice(0,n):i,...i.length>n?{truncated:!0}:{}},o=x(r?.description);o!==void 0&&(a.description=o);let s=x(r?.workdir);s!==void 0&&(a.cwd=s);let c=r?.timeoutMs;typeof c==`number`&&Number.isFinite(c)&&c>0&&(a.timeoutMs=c),r?.run_in_background===!0&&(a.background=!0);let l=x(r?.sandbox_permissions);return l!==void 0&&(a.sandbox=l),a}const We=RegExp(`(?:^|\\n)\\[still running after \\d+ms; moved to background job [^\\]\\n]+\\](?:\\nThe command keeps running in the background\\.[^\\n]*)?\\s*$`);function Ge(e){let t={};if(/(?:^|\n)started background job \S+\s*$/.test(e)||We.test(e))return t.backgroundAck=!0,t;let n=/(?:^|\n)\[killed by signal: ([^\]\n]+)\]\s*$/.exec(e)??/(?:^|\n)\[shell killed by signal: ([^\]\n]+)\](?=\n|$)/.exec(e);if(n?.[1]!==void 0)t.signal=n[1];else{let n=/(?:^|\n)\[exit code: (\d+)\]\s*$/.exec(e)??/(?:^|\n)\[Command finished with exit code (\d+)\]\s*$/.exec(e)??/(?:^|\n)\[shell exited: code (\d+)\](?=\n|$)/.exec(e);n?.[1]===void 0?/(?:^|\n)\[shell exited\](?=\n|$)/.test(e)&&(t.stopped=!0):t.exit=Number(n[1])}return/(?:^|\n)\[timed out after \d+ms\](?=\n|$)/.test(e)&&(t.timedOut=!0),/(?:^|\n)\[Command timed out or OOM\](?=\n|$)/.test(e)&&(t.timedOut=!0),/(?:^|\n)\[stopped: [^\]\n]+\](?=\n|$)/.test(e)&&(t.stopped=!0),/(?:^|\n)\[sandbox: file access denied under [^\]\n]+\](?=\n|$)/.test(e)&&(t.denied=!0),/(?:^|\n)\[output truncated; /.test(e)&&(t.truncated=!0),/(?:^|\n)\[stderr\]\n/.test(e)&&(t.stderr=!0),t}function Ke(e){if(typeof e!=`string`)return;let t=/(?:^|;\s*)exit code: (\d+)\b/.exec(e);return t?.[1]===void 0?void 0:Number(t[1])}function qe(e){if(typeof e==`string`)return/(?:^|;\s*)signal: ([^;]+)/.exec(e)?.[1]?.trim()||void 0}function Je(e,t){return e.signal!==void 0||e.stopped===!0?{status:`killed`}:e.exit===void 0?e.denied===!0||e.timedOut===!0||t?{status:`failed`}:{status:`completed`,exit:0,exitInferred:!0}:e.exit===0?{status:`completed`,exit:0}:{status:`failed`,exit:e.exit}}function S(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].call===t)return n;return-1}function Ye(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n.text;typeof e==`string`&&t.push(e)}return t}function Xe(e,t){let n={...e.commandStats??{runs:0,failed:0,ms:0,bg:0}};n.runs+=1,(t.status===`failed`||t.status===`killed`)&&(n.failed+=1),t.end!==void 0&&(n.ms+=Math.max(0,t.end-t.start)),e.commandStats=n}function C(e){e.commandStats={...e.commandStats??{runs:0,failed:0,ms:0,bg:0},bg:(e.commandStats?.bg??0)+1}}function Ze(e,t,n){e.commands[t].status===`running`&&n.status!==`running`&&Xe(e,n),e.commands[t]=n}function Qe(e,t){return{...e.length>0?{outChars:e.reduce((e,t)=>e+t.length,0)}:{},...t.truncated===!0?{outTruncated:!0}:{},...t.stderr===!0?{stderr:!0}:{},...t.timedOut===!0?{timedOut:!0}:{},...t.stopped===!0?{stopped:!0}:{},...t.denied===!0?{denied:!0}:{},...t.signal===void 0?{}:{signal:t.signal},...t.exit===void 0?{}:{exit:t.exit}}}function $e(e){let{parsed:t}=e;return{seq:e.seq,time:e.time,tool:e.tool,cmd:t.cmd,...t.truncated===!0?{cmdTruncated:!0}:{},...t.description===void 0?{}:{description:t.description},...t.cwd===void 0?{}:{cwd:t.cwd},...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.background===!0?{background:!0}:{},...t.sandbox===void 0?{}:{sandbox:t.sandbox},...typeof e.turn==`number`?{turn:e.turn}:{},...typeof e.step==`number`?{step:e.step}:{},...e.codeMode===!0?{codeMode:!0}:{},start:e.time,status:`running`,err:!1,call:e.call}}function et(e){let t=e?.toolCall;if(typeof t!=`object`||!t)return;let n=t.callId;return typeof n==`string`?n:void 0}function tt(e,t,n,r){let i=Ke(r),a=qe(r),o={...e,end:n,status:t===`completed`?i!==void 0&&i!==0?`failed`:`completed`:t,...i===void 0?{}:{exit:i},...a===void 0?{}:{signal:a}};return delete o.derived,delete o.exitInferred,o}function nt(e,t,n,r){for(let i in t){let a=t[i].findIndex(e=>e.call===n);if(a<0)continue;let o=[...t[i]];return o[a]=r(o[a]),e.pendingCodeCmds={...t,[i]:o},!0}return!1}function rt(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 w(e){let t=0,n;for(let r of e)r.turn!==n&&(t++,n=r.turn);return t}function it(e,t){if(e.turnRuns=e.turnRuns??w(e.requests),e.turnRuns>t.maxKeptTurns&&(e.requests=rt(e.requests,t.maxKeptTurns),e.turnRuns=w(e.requests)),e.requests.length>t.maxRequestSteps&&(e.requests=e.requests.slice(-t.maxRequestSteps),e.turnRuns=w(e.requests)),e.events.length>t.maxEvents&&(e.events=e.events.slice(-t.maxEvents)),e.spans.length>at&&(e.spans=e.spans.slice(-at)),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.commands.length>t.maxCommands){let n=e.commands.length-t.maxCommands,r=0,i=[];for(let t of e.commands){if(n>0&&t.status!==`running`){n--,r=Math.max(r,t.seq);continue}i.push(t)}if(i.length>t.maxCommands){let e=i.length-t.maxCommands;for(let t of i.slice(0,e))r=Math.max(r,t.seq);i.splice(0,e)}e.commandsFloor=Math.max(e.commandsFloor??0,r),e.commands=i}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 at=2e3;function ot(){return{surface:[],sums:{user:0,inject:0,skill:0,assistant:0,tool:0},systemTokens:0,toolsTokens:0,requests:[],turnRuns:0,events:[],archived:[],callNames:{},fileOps:[],commands:[],spans:[]}}const st={"deepseek-official":`deepseek`,"deepseek-account":`deepseek`,"kimi-coding":`moonshotai`,"minimax-cn":`minimax`,"zai-coding-cn":`zhipuai`,claude:`anthropic`,codex:`openai`,fireworks:`fireworks-ai`,together:`togetherai`,"vercel-ai-gateway":`vercel`,"kimi-code-plan-global":`moonshotai`,"kimi-code-plan-cn":`moonshotai-cn`,"zai-coding-plan":`zai`,"zhipuai-coding-plan":`zhipuai`,"xiaomi-token-plan-ams":`xiaomi`,"xiaomi-token-plan-cn":`xiaomi`,"xiaomi-token-plan-sgp":`xiaomi`,"minimax-coding-plan":`minimax`,"minimax-cn-coding-plan":`minimax-cn`};function ct(e){return st[e]??e}function lt(e){return ct(e)===`deepseek`}function T(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 ut(e){let t=new Date(e+288e5),n=t.getUTCDay();if(n===0||n===6)return!1;let r=t.getUTCHours();return r>=9&&r<12||r>=14&&r<18}function dt(e,t,n,r,i){let a=lt(t)&&!ut(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 ft(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 pt(e,t,n){let r=e.model;r!==void 0&&(e.cost=dt(e.cost,e.provider??``,r,t,n))}const mt=[`reasoning`,`text`,`toolarg`];function E(e,t){return!Number.isFinite(e)||!Number.isFinite(t)?0:Math.max(0,t-e)}function D(e){return e.timing===void 0&&(e.timing={wallMs:0,ttftMs:0,genMs:0,calls:0,toolsMs:0,toolCalls:0,tools:{}}),e.timing}const ht={reasoning:{ms:`reasoningMs`,n:`reasoningBlocks`},text:{ms:`textMs`,n:`textBlocks`},toolarg:{ms:`toolArgMs`,n:`toolArgBlocks`}};function gt(e,t,n,r){let i=ht[t];n>0&&(e[i.ms]=(e[i.ms]??0)+n),r>0&&(e[i.n]=(e[i.n]??0)+r)}function _t(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 vt(e){let t={...e};return delete t.call,t}function yt(e){let t=e.sums.user+e.sums.inject+e.sums.skill+e.sums.assistant+e.sums.tool,n=0,r=0;for(let t of e.surface)t.imgs!==void 0&&(n+=t.imgs),(t.cat===`tool`||t.cat===`skill`&&t.tool!==void 0)&&r++;let i={ok:!0,...e.model===void 0?{}:{model:e.model},...e.provider===void 0?{}:{provider:e.provider},...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort},...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:n,toolCalls:r,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&&(i.cost=ft(e.cost)),e.timing!==void 0){let t={};for(let n in e.timing.tools)t[n]={...e.timing.tools[n]};i.timing={...e.timing,tools:t}}return e.systems!==void 0&&e.systems.length>0&&(i.systems=e.systems.map(e=>({...e}))),i}function bt(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},commands:e.commands.map(vt),...e.commandsFloor===void 0?{}:{commandsFloor:e.commandsFloor},...e.commandStats===void 0?{}:{commandStats:{...e.commandStats}},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 O(e){let t=yt(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 k(e,t){return{rev:e.detailRev??0,head:O(e),...bt(e,t)}}function xt(e,t){return{...yt(e),...bt(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`:be(t?.source)?`inject`:`user`}function A(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 wt(e,t){let n=[...e.systems??[],t];e.systems=n.length>8?n.slice(-8):n,e.systemTokens=Ct(e.systems)}function Tt(e){if(typeof e==`string`)return e;if(e!=null)try{return JSON.stringify(e)}catch{return}}function Et(e,t){for(let n of t)e.fileOps.push(n)}function Dt(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 Ot(e,t,n){for(let r of t)e.archived.push({...r,gone:n})}function kt(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 Ot(e,i,n),e.surface=r,i}function At(e){let t=e?.message;return typeof t==`object`&&t?t:null}function jt(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 Mt(e){let t=jt(typeof e==`object`&&e?e.content:void 0).match(/<skill_content\s+name="([^"]+)"/);return t===null?``:t[1]}function j(e,t,n,r){let i=St(n,r??void 0),a={seq:t.seq,time:t.time,cat:i,tokens:he(r,n===`assistant/message`||n===`developer/message`)},o=_e(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=v(r?.content);if(e!==``)a.text=e;else{let e=ve(r?.content);e.length>0&&(a.calls=e.slice(0,3))}}else if(n===`tool/result`){let n=s?.callId,i=typeof n==`string`&&Object.hasOwn(e.callNames,n)?e.callNames[n]:void 0;if(i!==void 0){a.tool=i.name;let n=D(e),r=E(i.start,t.time);n.toolsMs+=r,n.toolCalls+=1,_t(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=v(r?.content);e!==``&&(a.text=e)}}else{let e=v(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=kt(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);Ot(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 Nt=`ask_user_question`,Pt=[`surface`,`sums`,`requests`,`events`,`archived`,`callNames`,`fileOps`,`timing`,`commands`];function Ft(e,t,r){let i,a=(t=Pt)=>{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]:n===`commands`?i.commands=[...e.commands]: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=pe(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),e.config&&typeof e.config.reasoningEffort==`string`&&e.config.reasoningEffort!==``?r.reasoningEffort=e.config.reasoningEffort:delete r.reasoningEffort;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}),A(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);kt(e,r,t.seq).length>0&&A(e)}wt(e,{seq:t.seq,time:t.time,tokens:oe(At(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=Ve(o.name),n=a(e===null?[`callNames`]:[`callNames`,`commands`]),i=je(o.name)?Tt(o.arguments):void 0;if(o.callId!==`__proto__`&&(n.callNames[o.callId]={name:o.name,start:t.time,...i===void 0?{}:{argsRaw:i}}),e!==null){let i=Ue(e,o.arguments,r.maxCommandChars);i!==null&&(n.commands.push($e({seq:t.seq,time:t.time,tool:e,parsed:i,turn:o.turn,step:o.step,call:o.callId})),i.background===!0&&C(n),A(n))}}break;case`job/registered`:{let t=et(o),n=o?.startedAt;if(t===void 0||typeof n!=`number`||!Number.isFinite(n))return e;let r=S(e.commands,t);if(r>=0){let e=a([`commands`]);e.commands[r]={...e.commands[r],start:n},A(e);break}if(e.pendingCodeCmds===void 0||!nt(a([]),e.pendingCodeCmds,t,e=>({...e,start:n})))return e;break}case`job/settled`:{let t=et(o),n=o?.finishedAt,r=o?.status;if(t===void 0||typeof n!=`number`||!Number.isFinite(n)||r!==`completed`&&r!==`killed`&&r!==`failed`)return e;let i=S(e.commands,t);if(i>=0){let e=a([`commands`]);Ze(e,i,tt(e.commands[i],r,n,o?.detail)),A(e);break}let s=e.pendingCodeCmds;if(s===void 0||!nt(a([]),s,t,e=>tt(e,r,n,o?.detail)))return e;break}case`tool/ptc-dispatch-start`:{let n=o?.rootCallId,i=o?.subCallId,s=Ve(typeof o?.name==`string`?o.name:void 0);if(typeof n!=`string`||typeof i!=`string`||s===null)return e;let c=Ue(s,o?.arguments,r.maxCommandChars);if(c===null)return e;let l=e.pendingCodeCmds??{},u=0;for(let e in l)u+=l[e].length;if(u+1>200)return e;let d=$e({seq:t.seq,time:t.time,tool:s,parsed:c,codeMode:!0,call:i}),f=a([]);c.background===!0&&C(f),f.pendingCodeCmds={...l,[n]:[...l[n]??[],d]};break}case`tool/ptc-dispatch`:{let n=o?.rootCallId,r=o?.name;if(typeof n==`string`&&typeof r==`string`){let i=o?.subCallId,s=typeof i==`string`?e.pendingCodeCmds?.[n]:void 0,c=s?.findIndex(e=>e.call===i)??-1,l=Ae(r)?Tt(o?.arguments):void 0,u=Be({seq:t.seq,time:t.time,tool:r,argsRaw:l,err:o?.isError===!0});if(u.length>0||s!==void 0&&c>=0){let r=a([]);if(u.length>0&&Dt(r,n,u),s!==void 0&&c>=0){let i=s[c],a=Ye(o?.content),l=Ge(a.at(-1)??``),u=o?.isError===!0,d={...i,...Qe(a,l),err:u};if(l.backgroundAck===!0)d.background=!0,i.background!==!0&&C(r);else{let e=Je(l,u);d.status=e.status,e.exit!==void 0&&(d.exit=e.exit),e.exitInferred===!0&&(d.exitInferred=!0),d.end=t.time,d.derived=!0}let f=[...s];f[c]=d,r.pendingCodeCmds={...e.pendingCodeCmds,[n]:f}}}}break}case`assistant/attempt`:{let t=e.stepStart;if(t===void 0||t.firstToken!==void 0)return e;let n=we(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`]);D(r).wallMs+=E(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=E(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,A(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?At(o):n(t);if(r&&(i===null||!Array.isArray(i.content)))return e;let s=a([`surface`,`sums`,`archived`,`events`]);A(s);let c=j(s,t,t.type,i),l=i?.source;if(r||be(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=ye(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`&&Object.hasOwn(e.callNames,i)?e.callNames[i]:void 0,c=typeof i==`string`?e.pendingCodeOps?.[i]:void 0,l=typeof i==`string`?e.pendingCodeCmds?.[i]:void 0,u=a([`surface`,`sums`,`archived`,`events`,`fileOps`,`timing`,`commands`]);A(u);let d=j(u,t,t.type,r);if(d.tool===Nt&&(u.humanInputs=(u.humanInputs??0)+1),s!==void 0&&s.name===Nt&&e.stepStart!==void 0&&(u.stepWaits=[...e.stepWaits??[],{start:s.start,end:t.time}]),s!==void 0&&(Et(u,Be({seq:t.seq,time:t.time,tool:s.name,argsRaw:s.argsRaw,meta:o?.meta,err:r?.isError===!0})),typeof i==`string`&&Ve(s.name)!==null)){let e=S(u.commands,i);if(e>=0){let n=u.commands[e],i=Ye(r?.content),a=Ge(i.at(-1)??``),s=r?.isError===!0,c={...n,...Qe(i,a),resultSeq:t.seq,err:s};a.exit!==void 0&&delete c.exitInferred;let l=o?.meta?.cwd;if(typeof l==`string`&&l!==``&&(c.cwd=l),a.backgroundAck===!0)c.background=!0,n.background!==!0&&C(u);else if(n.status===`running`){let e=Je(a,s);c.status=e.status,n.tool!==`run_code`&&(e.exit!==void 0&&(c.exit=e.exit),e.exitInferred===!0&&(c.exitInferred=!0)),c.end=t.time,c.derived=!0}Ze(u,e,c)}}if(c!==void 0&&c.length>0){let e=y(s?.argsRaw)?.description;Et(u,c.map(n=>({...n,parent:t.seq,...typeof e==`string`&&e!==``?{program:e}:{}})));let n={};for(let e in u.pendingCodeOps)e!==i&&(n[e]=u.pendingCodeOps[e]);Object.keys(n).length>0?u.pendingCodeOps=n:delete u.pendingCodeOps}if(l!==void 0&&l.length>0){for(let e of l){let n={...e,parent:t.seq};u.commands.push(n),n.status!==`running`&&Xe(u,n)}let e={};for(let t in u.pendingCodeCmds)t!==i&&(e[t]=u.pendingCodeCmds[t]);Object.keys(e).length>0?u.pendingCodeCmds=e:delete u.pendingCodeCmds}if(d.tool===`skill`||d.tool===void 0){let e=Mt(r);e!==``&&(d.skill=e,d.tool===void 0&&(d.tool=`skill`),u.sums.tool-=d.tokens,d.cat=`skill`,u.sums.skill+=d.tokens,u.events.push({seq:t.seq,time:t.time,kind:`inject`,form:`instructions`,sub:`skill`,name:e,tokens:d.tokens}))}break}case`assistant/message`:{let r=o?.usage,i=a([`surface`,`sums`,`archived`,`events`,`requests`,`timing`]);A(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=T(r.inputTokens),n=T(r.cacheReadTokens),a=T(r.cacheWriteTokens);l=T(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),pt(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??w(e.requests))+(u===void 0?c.turn===void 0?0:1:c.turn===u.turn?0:1);let d=D(i);d.calls+=1;let f=e.stepStart;if(f!==void 0){let e=Te(o?.stream,t.time),n=f.firstToken??e.firstToken;if(n!==void 0){let r=e.spans,a=n;for(let e of r)a=Math.min(a,e.start);d.ttftMs+=E(f.time,a),d.genMs+=E(a,t.time);let o=[{kind:`ttft`,start:f.time,end:a}];for(let e of r){let n=Math.min(t.time,e.end);n<=e.start||o.push({kind:e.kind,start:o.length===1?a:e.start,end:n})}i.stepSpans=[...i.stepSpans??[],...o],l!==null&&(d.speedMs=(d.speedMs??0)+E(n,t.time),d.speedTokens=(d.speedTokens??0)+l);let s=e.tally;for(let e of mt)gt(d,e,s.spans[e],s.blocks[e])}}let p=n(t);j(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`}),A(e)}break;case`compaction/summary`:case`compaction/prune`:{let e=a([`events`]);A(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:(it(i,r),i)}const M={maxRequestSteps:1500,maxKeptTurns:300,maxEvents:400,maxNodes:2e3,maxArchiveNodes:400,maxFileOps:400,maxCommands:400,maxCommandChars:4096};function N(e){let t=e.volatile;return typeof t==`function`?t.call(e):e}function P(e){return i.number().min(1).step(1).default(e)}const It=i.object({maxRequestSteps:P(M.maxRequestSteps),maxKeptTurns:P(M.maxKeptTurns),maxEvents:P(M.maxEvents),maxNodes:P(M.maxNodes),maxArchiveNodes:P(M.maxArchiveNodes),maxFileOps:P(M.maxFileOps),maxCommands:P(M.maxCommands),maxCommandChars:P(M.maxCommandChars),defaultPlacement:N(i.union([`all`,`tab`,`sidebar`,`hide`]).default(`all`).loose()),defaultGranularity:N(i.union([`step`,`turn`]).default(`step`).loose()),defaultTrendMode:N(i.union([`total`,`delta`]).default(`total`).loose()),defaultDeltaBase:N(i.union([`step`,`turn`]).default(`step`).loose()),defaultToolSort:N(i.union([`size`,`count`,`name`]).default(`count`).loose()),defaultFileSort:N(i.union([`count`,`lines`,`latest`,`path`,`name`]).default(`lines`).loose()),insightsEntry:N(i.union([`show`,`hide`]).default(`show`).loose()),defaultDurationCurve:N(i.union([`show`,`hide`]).default(`show`).loose()),overviewAutoSteps:N(i.union([`100`,`200`,`300`,`off`]).default(`200`).loose()),defaultOverviewRange:N(i.union([`today`,`7d`,`30d`,`all`]).default(`30d`).loose()),fleetTab:N(i.union([`show`,`hide`]).default(`show`).loose()),promptPrefix:N(i.string().default(``).loose()),promptSuffix:N(i.string().default(``).loose())});function Lt(e){let t=It(e??{});return{maxRequestSteps:t.maxRequestSteps,maxKeptTurns:t.maxKeptTurns,maxEvents:t.maxEvents,maxNodes:t.maxNodes,maxArchiveNodes:t.maxArchiveNodes,maxFileOps:t.maxFileOps,maxCommands:t.maxCommands,maxCommandChars:t.maxCommandChars}}const F=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(),Rt=t.object({seq:t.number().int().nonnegative(),time:t.number(),tokens:t.number().int().nonnegative()}).strict(),zt=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(),Bt=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(),Vt=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(),Ht=t.object({seq:t.number().int().nonnegative(),resultSeq:t.number().int().nonnegative().optional(),time:t.number(),tool:t.string(),cmd:t.string(),cmdTruncated:t.literal(!0).optional(),description:t.string().optional(),cwd:t.string().optional(),timeoutMs:t.number().positive().optional(),background:t.literal(!0).optional(),sandbox:t.string().optional(),codeMode:t.literal(!0).optional(),parent:t.number().int().nonnegative().optional(),turn:t.number().optional(),step:t.number().optional(),start:t.number(),end:t.number().optional(),status:t.enum([`running`,`completed`,`failed`,`killed`]),exit:t.number().int().optional(),exitInferred:t.literal(!0).optional(),signal:t.string().optional(),timedOut:t.literal(!0).optional(),stopped:t.literal(!0).optional(),denied:t.literal(!0).optional(),err:t.boolean(),outChars:t.number().int().nonnegative().optional(),outTruncated:t.literal(!0).optional(),stderr:t.literal(!0).optional(),derived:t.literal(!0).optional(),gone:t.number().int().nonnegative().optional()}).strict(),Ut=Ht.extend({call:t.string().optional()}).strict(),Wt=t.object({runs:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),ms:t.number().nonnegative(),bg:t.number().int().nonnegative()}).strict(),Gt=t.object({kind:t.enum([`ttft`,`reasoning`,`text`,`toolarg`,`tools`,`other`]),start:t.number(),end:t.number()}).strict(),Kt=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(),qt=t.object({uncached:t.number().int().nonnegative(),cacheRead:t.number().int().nonnegative(),cacheWrite:t.number().int().nonnegative(),output:t.number().int().nonnegative()}).strict(),Jt=t.object({peak:qt.optional(),off:qt.optional()}).strict(),Yt=t.record(t.string(),Jt),Xt=t.record(t.string(),Yt),Zt=t.object({calls:t.number().int().nonnegative(),ms:t.number().nonnegative()}).strict(),Qt=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(),Zt)}).strict(),$t=t.object({current:t.string(),minimum:t.string()}).strict(),en=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(),tn=t.object({seq:t.number(),total:t.number().int().nonnegative(),prompt:t.number().int().nonnegative().optional()}).strict(),nn=t.object({ok:t.literal(!0),unsupported:$t.optional(),model:t.string().optional(),provider:t.string().optional(),reasoningEffort:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),current:Kt,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:en.optional(),last:tn.optional(),detailRev:t.number().int().nonnegative().optional(),requests:t.array(zt).optional(),events:t.array(Bt).optional(),cost:Xt.optional(),timing:Qt.optional(),systems:t.array(Rt).optional(),nodes:t.array(F).optional(),droppedNodes:t.number().int().nonnegative().optional(),archive:t.array(F).optional(),surfaceFloor:t.number().int().nonnegative().optional(),archiveFloor:t.number().int().nonnegative().optional(),fileOps:t.array(Vt).optional(),fileOpsFloor:t.number().int().nonnegative().optional(),commands:t.array(Ht).optional(),commandsFloor:t.number().int().nonnegative().optional(),commandStats:Wt.optional(),spans:t.array(Gt).optional()}).strict(),rn=t.object({surface:t.array(F),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(Rt).optional(),toolsTokens:t.number().int().nonnegative(),model:t.string().optional(),provider:t.string().optional(),reasoningEffort:t.string().optional(),lastModel:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),requests:t.array(zt),turnRuns:t.number().int().nonnegative().optional(),events:t.array(Bt),archived:t.array(F),cost:Xt.optional(),archiveFloor:t.number().optional(),timing:Qt.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(Vt),fileOpsFloor:t.number().int().nonnegative().optional(),commands:t.array(Ut),commandsFloor:t.number().int().nonnegative().optional(),commandStats:Wt.optional(),pendingCodeCmds:t.record(t.string(),t.array(Ut)).optional(),spans:t.array(Gt),stepSpans:t.array(Gt).optional(),pendingCodeOps:t.record(t.string(),t.array(Vt)).optional()});function an(e,t){let n=Lt(e);return{key:`contextTimeline`,stateSchema:rn,wire:{viewSchema:nn,view:e=>t()?O(e):xt(e,n)},init:()=>ot(),apply:(e,t)=>Ft(e,t,n),stateVersion:31}}function I(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 on=t.object({n:t.number().int().nonnegative(),last:t.number()}).strict(),sn=t.object({start:t.number().nonnegative(),day:t.string()}).strict(),cn=t.object({tokens:t.number().int().nonnegative(),requests:t.number().int().nonnegative(),cost:Xt.optional(),turns:t.number().int().nonnegative().optional(),toolCalls:t.number().int().nonnegative().optional(),toolsMs:t.number().nonnegative().optional(),wallMs:t.number().nonnegative().optional(),skills:t.record(t.string(),on).optional()}).strict(),ln=t.object({days:t.record(t.string(),cn)}).strict(),un=t.object({days:t.record(t.string(),cn),model:t.string().optional(),provider:t.string().optional(),stepStart:t.number().optional(),lastTurn:t.number().optional(),toolStarts:t.record(t.string(),sn).optional(),skillCalls:t.array(t.string()).optional()});function dn(e){if(typeof e!=`object`||!e)return null;let t=e,n=T(t.inputTokens),r=T(t.cacheReadTokens),i=T(t.cacheWriteTokens),a=T(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 L(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 fn(e){return{tokens:e?.tokens??0,requests:e?.requests??0,...e?.cost===void 0?{}:{cost:e.cost},...e?.turns===void 0?{}:{turns:e.turns},...e?.toolCalls===void 0?{}:{toolCalls:e.toolCalls},...e?.toolsMs===void 0?{}:{toolsMs:e.toolsMs},...e?.wallMs===void 0?{}:{wallMs:e.wallMs},...e?.skills===void 0?{}:{skills:e.skills}}}function pn(e,t,n){return L(e,t,{...fn(e.days[t]),...n})}function mn(e,t,n){if(!Number.isFinite(n)||n<0)return e;let r=I(e.stepStart??n);if(r===null)return e;let i=e.toolStarts?.[t];if(i!==void 0&&i.start===n&&i.day===r)return e;let a={...e.toolStarts,[t]:{start:n,day:r}},o=Object.entries(a),s=o.length>100?Object.fromEntries(o.slice(o.length-100)):a;return{...e,toolStarts:s}}function hn(e,t,n){let r=e.toolStarts,i=r?.[t];if(r===void 0||i===void 0)return e;let a=e.days[i.day],o=pn(e,i.day,{toolCalls:(a?.toolCalls??0)+1,toolsMs:(a?.toolsMs??0)+E(i.start,n)}),s=Object.fromEntries(Object.entries(r).filter(([e])=>e!==t)),c={...o};return Object.keys(s).length>0?c.toolStarts=s:delete c.toolStarts,c}function gn(e,t,n){let r=I(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 L(e,r,{...fn(i),skills:o})}function _n(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 vn(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 yn(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`){let n=e.stepStart;if(n===void 0)return e;let r=I(n),i=E(n,t.time),a={...r===null||i<=0?e:pn(e,r,{wallMs:(e.days[r]?.wallMs??0)+i})};return delete a.stepStart,a}if(t.type===`session/end-seed`)return t.data?.inherited===!0?{days:{}}:e;if(t.type===`user/message`||t.type===`developer/message`){let n=_n(t);return n===``?e:gn(e,n,t.time)}if(t.type===`tool/call`){let n=t.data,r=n?.callId;if(typeof r!=`string`||r===``)return e;let i=mn(e,r,t.time);if(n?.name!==`skill`)return i;let a=i.skillCalls??[];return a.includes(r)?i:{...i,skillCalls:[...a,r].slice(-100)}}if(t.type===`tool/result`){let n=t.data?.message,r=vn(n),i=r===null?e:hn(e,r,t.time),a=i.skillCalls;if(r===null||a===void 0||!a.includes(r))return i;let o=a.filter(e=>e!==r),s={...i};o.length>0?s.skillCalls=o:delete s.skillCalls;let c=Mt(n);return c===``?s:gn(s,c,t.time)}if(t.type!==`assistant/message`)return e;let n=e.stepStart===void 0?t.time:e.stepStart,r=I(n);if(r===null)return e;let i=t.data,a=dn(i?.usage),o=e.days[r],s=o?.cost;a!==null&&e.model!==void 0&&(s=dt(s,e.provider??``,e.model,n,a));let c=typeof i?.turn==`number`&&Number.isFinite(i.turn)?i.turn:void 0,l=c!==void 0&&c!==e.lastTurn,u=(o?.turns??0)+ +!!l,d=L(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},...u>0?{turns:u}:{},...o?.toolCalls===void 0?{}:{toolCalls:o.toolCalls},...o?.toolsMs===void 0?{}:{toolsMs:o.toolsMs},...o?.wallMs===void 0?{}:{wallMs:o.wallMs},...o?.skills===void 0?{}:{skills:o.skills}});return l?{...d,lastTurn:c}:d}function bn(){return{key:`contextActivity`,stateSchema:un,init:()=>({days:{}}),apply:(e,t)=>yn(e,t),wire:{viewSchema:ln,view:e=>({days:Object.fromEntries(Object.entries(e.days).map(([e,t])=>[e,{...t,...t.cost===void 0?{}:{cost:ft(t.cost)},...t.skills===void 0?{}:{skills:Object.fromEntries(Object.entries(t.skills).map(([e,t])=>[e,{...t}]))}}]))})},stateVersion:5}}const xn=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]);function Sn(e){return e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1)}function Cn(e){let t=Sn(e),n=t.lastIndexOf(`.`);return n<0?``:t.slice(n+1).toLowerCase()}function wn(e){return xn.has(Cn(e))}function R(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Tn(e){if(typeof e!=`object`||!e)return;let t=e,n=R(t.width),r=R(t.height);return n!==void 0&&r!==void 0?{width:n,height:r}:void 0}function En(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=R(r.bytes);if(n===`file`)return{kind:`file`,attachmentId:r.attachmentId,...i===void 0?{}:{name:i},...a===void 0?{}:{bytes:a}};let o=Tn(r.originalDimensions),s=R(r.width),c=R(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 Dn(){let e=m();return{used:e.used_heap_size,limit:e.heap_size_limit}}const On=()=>{};function z(e=Dn){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(On,On),r}}}function kn(e){return typeof e?.fetch?.register==`function`?e.fetch.register.bind(e.fetch):void 0}function B(e,t,n,r,i){let a=kn(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 An={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`};function V(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function H(e,t){return V({ok:!1,error:{code:e,message:t}})}function jn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function U(e,t,n){if(n>8)return null;if(Array.isArray(e)){for(let r of e){let e=U(r,t,n+1);if(e!==null)return e}return null}if(typeof e!=`object`||!e)return null;let r=En(e);if(r!==null&&r.attachmentId===t)return r;for(let r of Object.values(e)){let e=U(r,t,n+1);if(e!==null)return e}return null}function Mn(e,t){for(let n of e)try{let e=U(n,t,0);if(e!==null)return e}catch{}return null}function Nn(e){let t=Sn(e.name??``);if(t!==``&&wn(t))return t;let n=e.mediaType===void 0?void 0:An[e.mediaType];return n===void 0?null:`attachment.${n}`}function Pn(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 Fn(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 In(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=Nn(t);if(r===null)return null;let i=Pn(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 Ln(e,t){return t.kind===`file`?Fn(e,t):await In(e,t)}function Rn(e,t=z()){e.inject([`connection`],n=>{B(n,n.get(`connection`),`/api/dsh-context/attachment`,async n=>{let r,i;try{let e=jn(await n.json());r=e?.sessionId,i=e?.attachmentId}catch{return H(`dsh-context/bad-request`,`body is not JSON`)}if(typeof r!=`string`||r===``)return H(`dsh-context/bad-request`,`missing sessionId`);if(typeof i!=`string`||i===``)return H(`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 V({ok:!0,value:null});let o=e.get(`attachments`);return V({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=Mn(t,i);if(n===null)return null;let r=await Ln(o,n);return r===null?null:{path:r}}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return H(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: attachment route`)})}function zn(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 Bn(e){let t=zn(e);return t===void 0?void 0:`mcp:${t}`}function Vn(e){return Hn[e]}const Hn=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`}),Un=f(h(import.meta.url)),W=new Map;function Wn(e){let t=l(e);for(let e=0;e<12;e++){let e=W.get(t);if(e!==void 0)return e;let n=d(t,`package.json`);if(ee(n))try{let e=JSON.parse(te(n,`utf8`)).name;if(typeof e==`string`&&e)return W.set(t,e),e}catch{}let r=l(t);if(W.set(t,void 0),r===t)return;t=r}}const Gn=/:\d+:\d+$/,Kn=Symbol.for(`cordis.original`);function qn(e){return e?.[Kn]??e}const Jn=Wn(Un);function Yn(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=Gn.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(h(r))}catch{continue}else if(!/^[A-Za-z]:[\\/]/.test(r)&&!r.startsWith(`/`)&&!r.startsWith(`\\\\`))continue;else r=f(r);if(r===Un)continue;let i=Wn(r);if(i!==void 0&&i!==Jn)return i}}function Xn(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=Yn(Error().stack));let o=s.call(this,e);return typeof n==`string`&&a&&a!==`root`&&a!==r&&a!==Jn&&(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(qn(a)),a}),e.effect(()=>()=>{for(let e of a.splice(0))e()},`tools.register attribution`);let s=qn(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=>Bn(e)??t.get(e)??Vn(e)??(c.has(e)?`<unknown-plugin>`:void 0)}}function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}const Zn=[`llm-deepseek`,`web-deepseek-api`,`web-search-deepseek`],K=`https://api.deepseek.com`;function Qn(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function $n(e){let t=[],n=e.get(`llm`);if(typeof n?.listConfigurableProviders==`function`)try{let e=n.listConfigurableProviders();if(Array.isArray(e))for(let n of e)try{let e=G(n);if(e===null||e.provider!==`deepseek-official`)continue;let r=e.settingsNs;typeof r==`string`&&r!==``&&!t.includes(r)&&t.push(r)}catch{continue}}catch{}for(let e of Zn)t.includes(e)||t.push(e);return t}function er(e){let t=e.get(`settings`);if(typeof t?.describe!=`function`)return[];let n;try{n=t.describe({redactSecrets:!0})}catch{return[]}if(!Array.isArray(n))return[];let r=new Map;for(let e of n)try{let t=G(e);if(t===null)continue;let n=t.ns,i=G(t.value);if(typeof n!=`string`||i===null||r.has(n))continue;r.set(n,i)}catch{continue}let i=[];for(let t of $n(e)){let e=r.get(t);if(e===void 0)continue;let n=e.apiKeyEnv;if(typeof n!=`string`||n===``)continue;let a=e.baseURL;i.push({apiKeyEnv:n,baseURL:typeof a==`string`&&a!==``?a:void 0})}return i}function tr(e){if(e===void 0)return K;try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?K:t.origin}catch{return K}}async function nr(e){let t=e.get(`credentials`),n=typeof t?.resolve==`function`?t.resolve.bind(t):void 0;if(n===void 0)return null;let r=new Set;for(let t of er(e)){if(r.has(t.apiKeyEnv))continue;r.add(t.apiKeyEnv);let e;try{e=await n(t.apiKeyEnv)}catch{continue}let i=typeof e?.value==`string`?e.value:``;if(i!==``)return{baseUrl:tr(t.baseURL),apiKey:i}}return null}function rr(e){let t=G(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=G(e);if(t===null)continue;let n=t.currency,i=Qn(t.granted_balance),a=Qn(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 ir=(e,t)=>fetch(e,t),q=null;async function ar(e){if(q!==null)return q;q=(async()=>{let t=null;try{let n=await ir(e.baseUrl+`/user/balance`,{headers:{accept:`application/json`,authorization:`Bearer `+e.apiKey},signal:AbortSignal.timeout(1e4)});n.ok&&(t=rr(await n.json()))}catch{}return t})();let t=q;try{return await t}finally{q=null}}function or(e){e.inject([`connection`],t=>{B(t,t.get(`connection`),`/api/dsh-context/balance`,async()=>{let t=await nr(e),n=t===null?null:await ar(t);return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: balance route`)})}const J=2e3,sr={now:()=>ne.now(),sleep:e=>new Promise(t=>setTimeout(t,e)),minRestMs:25,workBudgetMs:8e3,roundPauseMs:2e3};function cr(e){let t=G(G(e)?.header);return t===null||typeof t.id!=`string`||t.id===``?null:t}const lr=[`contextActivity`,`contextTimeline`];function ur(e,t){try{let n=G(G(e.cachedSnapshot(t,lr))?.values);return n!==null&&n.contextActivity!==void 0&&n.contextTimeline!==void 0}catch{return!1}}async function dr(e,t,n){let i=await e.open(t,`read`,{signal:n}),a;try{let e=G(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 fr(e,t){if(e===null||typeof e.get!=`function`)return!1;try{return e.get(t)!==void 0}catch{return!0}}async function pr(e,t,n,r,i,a,o){let{header:s,inheritedEventCount:c,events:l}=r,u={},d=0;for(let e=J;;e+=J){let n=e>=l.length,r=o();u=G(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(fr(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): ${Y(t)}`)}return{outcome:`done`,workMs:d}}function mr(e){try{return String(G(e)?.name).startsWith(`SessionFormatUnsupported`)}catch{return!1}}function Y(e){try{return String(e)}catch{return`unprintable error`}}function hr(e,t=z(),n=sr){let r=!1,i=!1,a=null,o=()=>{r&&!i&&a!==null&&(i=!0,a())},s=e.inject([`connection`],e=>{B(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=G(i.sessionQuery),c=G(i.sessionProjectionCache),l=G(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=G(i.sessions),d=G(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)}},ee=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=cr(s);if(r===null||typeof r.cwd!=`string`||fr(u,r.id)||ur(c,r))continue;let d=n.now(),m=0;try{let a=await t.admit(async()=>{let t=await dr(l,r.id,p.signal);if(f!==null&&t.events.length>J){let r=await pr(e,f,u,t,p.signal,ee,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){mr(t)?(a++,e.logger.debug(`dsh-context: projection backfill skipped "${r.id}" (${Y(t)})`)):e.logger.warn(`dsh-context: projection backfill skipped "${r.id}" (${Y(t)})`)}await ee(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 (${Y(t)})`)})},o(),()=>{p.abort()}});return()=>{for(let e of[s,c])e?.dispose?.()}}function gr(e){let t=e?.revision;return typeof t==`string`&&t!==``?t:void 0}function _r(e){return{rev:e.rev,head:e.head}}function vr(e){return{rev:e.detailRev??0,head:O(e)}}function yr(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function br(e,t){return yr({ok:!1,error:{code:e,message:t}})}function xr(e,t,n=z()){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(B(a,a.get(`connection`),`/api/dsh-context/detail`,async r=>{let a,o=!1;try{let e=await r.json();a=typeof e==`object`&&e?e.sessionId:void 0,o=typeof e==`object`&&!!e&&e.head===!0}catch{return br(`dsh-context/bad-request`,`body is not JSON`)}if(typeof a!=`string`||a===``)return br(`dsh-context/bad-request`,`missing sessionId`);try{let r=s(a);if(r!=null){let e=c.stateOf(r,`contextTimeline`);return yr(e===void 0?{ok:!0,value:null}:{ok:!0,value:o?vr(e):k(e,t)})}let l=e.get(`sessionQuery`),u=typeof l?.observeSession==`function`?l.observeSession.bind(l):void 0;return yr(u===void 0?{ok:!0,value:null}:{ok:!0,value:await n.admit(async()=>{let n=await u(a,{projectionMode:`none`});try{let r=e.get(`sessionPersistence`),s=gr(n);if(s!==void 0){let e=i.get(a);if(e!==void 0&&e.revision===s&&e.persistence===r)return i.delete(a),i.set(a,e),o?_r(e.value):e.value}let c=n?.events;if(!Array.isArray(c))return null;let l=ot(),u=0;for(let e of c)l=Ft(l,e,t),++u%1e3==0&&await new Promise(e=>setTimeout(e,0));if(s!==void 0){let e=k(l,t);i.delete(a),i.set(a,{persistence:r,revision:s,value:e});for(let e of i.keys()){if(i.size<=4)break;i.delete(e)}return o?_r(e):e}return o?vr(l):k(l,t)}finally{let e=n?.[Symbol.dispose];typeof e==`function`&&e.call(n)}})??null})}catch(e){return br(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: detail route`))return r.live=!0,()=>{r.live=!1}}),r}const Sr=`0.2.0-rc.2`;function Cr(e){return e===`rc`?3:e===`beta`?2:1}function wr(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:Cr(n),serial:t[5]?Number(t[5]):0}}function Tr(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 Er(e,t=Sr){let n=wr(e),r=wr(t);return n===null||r===null||Tr(n,r)>=0}const Dr=t.object({name:t.string(),tokens:t.number().int().nonnegative(),description:t.string().optional(),plugin:t.string().optional(),schema:t.unknown().optional()}).strict(),Or=t.object({seq:t.number(),time:t.number(),system:t.string().optional(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array(Dr)}).strict(),kr=t.object({headers:t.array(Or)}).strict(),Ar=t.object({name:t.string(),tokens:t.number().int().nonnegative(),plugin:t.string().optional()}).strict(),jr=t.object({headers:t.array(t.object({seq:t.number(),time:t.number(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array(Ar)}).strict())}).strict();function Mr(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:ge(e)};return typeof t.plugin==`string`&&t.plugin!==``&&(n.plugin=t.plugin),n})}}function Nr(e){return{key:`contextHeaders`,stateSchema:kr,wire:{viewSchema:jr,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!==``?ie(t.system):void 0);return r!==void 0&&(n.systemTokens=r),n})})},init:()=>({headers:[]}),apply:(e,t)=>{let n=Mr(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 Pr=t.object({});function Fr(e,t,n){let r=()=>n;return{key:e,stateSchema:Pr,init:()=>({}),apply:e=>e,wire:{viewSchema:t,view:r},schema:t,view:r,stateVersion:1}}function Ir(e){return Fr(`contextTimeline`,nn,{ok:!0,unsupported:{current:e,minimum:Sr},current:{system:0,tools:0,user:0,inject:0,skill:0,assistant:0,tool:0,total:0},requests:[],events:[],nodes:[],droppedNodes:0,archive:[]})}function Lr(){return Fr(`contextHeaders`,jr,{headers:[]})}function Rr(){return Fr(`contextActivity`,ln,{days:{}})}const zr=1e5;function Br(e){return X(e)?.full===!0}function Vr(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function Hr(e,t){return Vr({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 Wr(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`,`agentReasoningEffort`,`persona`]){let r=e[t];typeof r==`string`&&r!==``&&(n[t]=r)}return n}const Gr=/^Team message \S+ from ([^:]{1,64}):\s*/,Kr=/^(?:Agent \S+ sent a message: |Team message from ([^:\n]{1,64}):\s*)/;function qr(e){let t=e[0];if(t!==`{`&&t!==`[`)return 0;let n=0,r=!1,i=!1;for(let t=0;t<e.length;t++){let a=e[t];if(r){i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1);continue}if(a===`"`)r=!0;else if(a===`{`||a===`[`)n++;else if((a===`}`||a===`]`)&&(n--,n===0))return t+1}return e.length}function Jr(e,t,n){let r=!1,i=e=>{let t=e.trim();if(t===``)return;let i=Q(t,n);return i.cut&&(r=!0),i.text},a=t.slice(e.length).trim(),o=a.indexOf(`Structured result: `),s=o>=0?a.slice(0,o).trim():a;s===`It left no closing message.`||s===`It sent you a message just before finishing, so its closing message is omitted.`?s=``:s.startsWith(`Its closing message:`)&&(s=s.slice(20).trim());let c,l;if(o>=0){let e=a.slice(o+19).trim(),t=qr(e);c=i(t>0?e.slice(0,t):e),t>0&&(l=i(e.slice(t)))}let u=Q(e,n);u.cut&&(r=!0);let d=i(s),f={summary:u.text,clipped:r};return d!==void 0&&(f.report=d),c!==void 0&&(f.structured=c),l!==void 0&&(f.diagnostic=l),f}function Yr(e,t,n,r){let i=X(n.source),a=i?.kind,o=null;if(a===`agent-message`||a===`team-message`){let r=Z(n.content),s=a===`team-message`?Gr:Kr,c=s.exec(r),l=r.replace(s,``);if(l.trim()===``)return null;o={seq:e,time:t,kind:a===`agent-message`?`relay`:`mailbox`,text:l};let u=a===`agent-message`?i?.senderSessionId:i?.senderId;typeof u==`string`&&u!==``&&(o.from=u);let d=typeof i?.senderName==`string`&&i.senderName!==``?i.senderName:c?.[1];d!==void 0&&d!==``&&(o.fromName=d)}else if(a===`subagent-settled`){let a=typeof i?.summary==`string`?i.summary.trim():``,s=Z(n.content).trim(),c=a!==``&&!s.startsWith(a)||s===``?a:s;if(c.trim()===``)return null;o={seq:e,time:t,kind:`settled`,text:c};let l=i?.senderSessionId;if(typeof l==`string`&&l!==``&&(o.from=l),a!==``){let e=Jr(a,c,r);o.summary=e.summary,e.clipped&&(o.clipped=!0),e.report!==void 0&&(o.report=e.report),e.structured!==void 0&&(o.structured=e.structured),e.diagnostic!==void 0&&(o.diagnostic=e.diagnostic)}}if(o===null)return null;let s=Q(o.text,r);return o.text=s.text,s.cut&&(o.clipped=!0),o}function Xr(e){return e===null||e.kind===`user`}function Zr(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 Qr(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 $r(e,t=!1){let n=t?zr:1600,r=t?zr:300,i=t?24e3:400,a=t?120:80,o,s,c=!1,l=0,u=[],d=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 a=typeof e.seq==`number`&&Number.isFinite(e.seq)?e.seq:0,f=typeof e.time==`number`&&Number.isFinite(e.time)?e.time:0,p=X(e.data);if(p===null)continue;if(r===`subagent/descriptor`){let e=Wr(p);e!==null&&(o=e);continue}if(r===`team/member`){let e=Zr(p);e!==null&&d.set(e.name,e);continue}if(r!==`user/message`)continue;let m=Yr(a,f,p,i);if(m!==null){l+=1,m.clipped===!0&&(c=!0),u.push(m);continue}if(s===void 0&&Xr(X(p.source))){let e=Z(p.content).replace(Ur,``);if(e.trim()!==``){let t=Q(e,n);s=t.text,t.cut&&(c=!0)}}}u.sort((e,t)=>t.seq-e.seq),u.length>a&&(u.length=a,c=!0);let f=Qr(e,r);return f!==null&&f.cut&&(c=!0),{...o===void 0?{}:{descriptor:o},...s===void 0?{}:{initialPrompt:s},...f===null?{}:{lastReply:{time:f.time,text:f.text}},...d.size>0?{roster:[...d.values()]}:{},messages:u,...l>u.length?{messagesTotal:l}:{},truncated:c}}function ei(e,t=z()){e.inject([`connection`],n=>{B(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=Br(e)}catch{return Hr(`dsh-context/bad-request`,`body is not JSON`)}if(typeof r!=`string`||r===``)return Hr(`dsh-context/bad-request`,`missing sessionId`);try{let n=e.get(`sessionQuery`),a=typeof n?.observeSession==`function`?n.observeSession.bind(n):void 0;return Vr(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 $r(t,i)}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return Hr(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: fleet route`)})}function ti(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 ni(e){return()=>{let t=e();return t.trim().length===0?``:t}}const ri=1e3;function ii(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`)-ri,text:ni(ti(t.promptPrefix)),interpolate:!1}),n.section({name:`dsh-context:prompt-suffix`,order:n.getSectionOrder(`DEPLOYMENT_PERSONA_SUFFIX`)+ri,text:ni(ti(t.promptSuffix)),interpolate:!1}))})}function ai(e){if(typeof e!=`object`||!e)return!1;let t=e.id;return typeof t!=`string`||t===``}function oi(e){let t;for(let[n,r]of e.entries()){if(!ai(r)){t?.push(r);continue}t??=e.slice(0,n),t.push({...r,id:`dshctx-`+re()})}return t}function si(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=oi(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 ci(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 li(e){let t=G(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 ui(e,t){if(t===void 0)return{};let n=G(e.get(`sessionQuery`));if(typeof n?.observeSession!=`function`)return{};let r;try{r=await n.observeSession.call(n,t)}catch{return{}}try{let e=G(r),t=$(G(e?.header)?.cwd),n=$(G(G(e?.projections)?.values)?.agentPreset);return{...t===void 0?{}:{cwd:t},...n===void 0?{}:{agentPreset:n}}}finally{await ci(r)}}async function di(e,t,n){let r=G(e.get(`agentPresets`)),i;if(t!==void 0){let n=G(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=G(r.serviceFor.call(r,i,`skills`));if(e!==null&&typeof e.list==`function`)return{registry:e,scope:i,lease:void 0}}let a=G(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=G(s)?.key}catch{s=void 0}return{registry:a,scope:o,lease:s}}function fi(e){e.inject([`connection`],t=>{B(t,t.get(`connection`),`/api/dsh-context/skills`,async t=>{let n=null,r;try{let i=G(await t.json()),a=$(i?.sessionId),o=await ui(e,a),s=o.cwd??$(i?.cwd),c=await di(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=li(e);if(t!==null&&i.push(t),i.length>=500)break}n={skills:i}}}catch{}finally{await ci(r)}return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: skills route`)})}const pi=[`@deepseek-ai/dsh-session-projection`,`@deepseek-ai/dsh-session`],mi=[`@deepseek-ai/dsh-session`,`@deepseek-ai/dsh-session-projection`],hi=[`@deepseek-ai/dsh`,...pi];function gi(){try{return l(h(import.meta.resolve(`dsh-context/package.json`)))}catch{return l(h(import.meta.url))}}const _i=gi();function vi(e,t){try{let n=JSON.parse(te(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 yi(e,t){try{return vi(e(t+`/package.json`))}catch{return}}function bi(e,t){let n;try{n=l(e(t))}catch{return}for(;;){let e=vi(d(n,`package.json`),t);if(e!==void 0)return e;let r=l(n);if(r===n)return;n=r}}function xi(e,t){for(let n of t){let t=yi(e,n)??bi(e,n);if(t!==void 0)return t}}function Si(e,t){let n=p(e,t);return!n.startsWith(`..`)&&!u(n)}function Ci(e,t){for(let n of mi){let r;try{r=e(n)}catch{continue}if(Si(t,r))continue;let i=yi(e,n)??bi(e,n);if(i!==void 0)return i}}function wi(e){return import.meta.resolve(e)}function Ti(t,n=wi,r=_i){let i=Ci(e=>{let t=n(e);if(!t.startsWith(`file:`))throw Error(`dsh-context: non-file module URL for ${e}`);return h(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=xi(e=>t.resolve(e),hi);if(r!==void 0)return r}}catch{}}const Ei=`dsh-context`,Di=[`sessionProjections`];function Oi(e,t){let n=z();or(e),fi(e),ei(e,n),Rn(e,n);let r=Ti(e);if(r!==void 0&&!Er(r)){e.sessionProjections.register(Ir(r)),e.sessionProjections.register(Lr()),e.sessionProjections.register(Rr());return}let i=Xn(e);si(e);let a=xr(e,Lt(t),n);e.sessionProjections.register(an(t,()=>a.live)),e.sessionProjections.register(Nr(e=>i.ownerOf(e))),e.sessionProjections.register(bn()),hr(e,n),ii(e,t)}export{It as Config,Oi as apply,Di as inject,Ei as name};
16
- //# sourceMappingURL=index.js.map
14
+ `)?t:t+1}function C(e,t){return{added:typeof e==`string`?Ie(e):0,removed:typeof t==`string`?Ie(t):0}}function Le(e,t){if(e===`edit`)return C(t.new_string,t.old_string);if(e===`write`)return C(t.content,void 0);if(e===`str_replace_editor`){if(t.command===`str_replace`)return C(t.new_str,t.old_str);if(t.command===`insert`)return C(t.new_str,void 0);if(t.command===`create`)return C(t.file_text,void 0)}return{added:0,removed:0}}function Re(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 ze(e){let t=e.limit;return typeof t==`number`&&Number.isFinite(t)&&t>0?{count:Math.floor(t),est:!0}:void 0}function Be(e,t){let n=Re(e);return n===null?ze(t):{start:n.start,count:n.count}}function Ve(e){let t=e?.pattern;if(typeof t!=`string`||t===``)return;let n=e?.include;return typeof n==`string`&&n!==``?`${t} (${n})`:t}function He(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 Ue(e){let t=Ne(e.tool)?ke(e.argsRaw):null,n=Me(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=He(e.meta);if(n!==null){let i=Ve(t),a=t===null?null:Fe(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=Fe(e.tool,t);if(i===null)return[];let{added:a,removed:o}=Le(e.tool,t),s=typeof t.path==`string`&&t.path!==``,c=n===`search`&&s?Ve(t):void 0,l=n===`read`?Be(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 w(e){return e===`bash`||e===`pwsh`||e===`run_code`?e:null}function T(e){return typeof e==`string`&&e!==``?e:void 0}function We(e){return typeof e==`string`?ke(e):typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Ge(e,t,n){let r=We(t),i=T(e===`run_code`?r?.code:r?.command);if(i===void 0)return null;let a={cmd:i.length>n?i.slice(0,n):i,...i.length>n?{truncated:!0}:{}},o=T(r?.description);o!==void 0&&(a.description=o);let s=T(r?.workdir);s!==void 0&&(a.cwd=s);let c=r?.timeoutMs;typeof c==`number`&&Number.isFinite(c)&&c>0&&(a.timeoutMs=c),r?.run_in_background===!0&&(a.background=!0);let l=T(r?.sandbox_permissions);return l!==void 0&&(a.sandbox=l),a}const Ke=RegExp(`(?:^|\\n)\\[still running after \\d+ms; moved to background job [^\\]\\n]+\\](?:\\nThe command keeps running in the background\\.[^\\n]*)?\\s*$`);function qe(e){let t={};if(/(?:^|\n)started background job \S+\s*$/.test(e)||Ke.test(e))return t.backgroundAck=!0,t;let n=/(?:^|\n)\[killed by signal: ([^\]\n]+)\]\s*$/.exec(e)??/(?:^|\n)\[shell killed by signal: ([^\]\n]+)\](?=\n|$)/.exec(e);if(n?.[1]!==void 0)t.signal=n[1];else{let n=/(?:^|\n)\[exit code: (\d+)\]\s*$/.exec(e)??/(?:^|\n)\[Command finished with exit code (\d+)\]\s*$/.exec(e)??/(?:^|\n)\[shell exited: code (\d+)\](?=\n|$)/.exec(e);n?.[1]===void 0?/(?:^|\n)\[shell exited\](?=\n|$)/.test(e)&&(t.stopped=!0):t.exit=Number(n[1])}return/(?:^|\n)\[timed out after \d+ms\](?=\n|$)/.test(e)&&(t.timedOut=!0),/(?:^|\n)\[Command timed out or OOM\](?=\n|$)/.test(e)&&(t.timedOut=!0),/(?:^|\n)\[stopped: [^\]\n]+\](?=\n|$)/.test(e)&&(t.stopped=!0),/(?:^|\n)\[sandbox: file access denied under [^\]\n]+\](?=\n|$)/.test(e)&&(t.denied=!0),/(?:^|\n)\[output truncated; /.test(e)&&(t.truncated=!0),/(?:^|\n)\[stderr\]\n/.test(e)&&(t.stderr=!0),t}function Je(e){if(typeof e!=`string`)return;let t=/(?:^|;\s*)exit code: (\d+)\b/.exec(e);return t?.[1]===void 0?void 0:Number(t[1])}function Ye(e){if(typeof e==`string`)return/(?:^|;\s*)signal: ([^;]+)/.exec(e)?.[1]?.trim()||void 0}function Xe(e,t){return e.signal!==void 0||e.stopped===!0?{status:`killed`}:e.exit===void 0?e.denied===!0||e.timedOut===!0||t?{status:`failed`}:{status:`completed`,exit:0,exitInferred:!0}:e.exit===0?{status:`completed`,exit:0}:{status:`failed`,exit:e.exit}}function E(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].call===t)return n;return-1}function Ze(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n.text;typeof e==`string`&&t.push(e)}return t}function Qe(e,t){let n={...e.commandStats??{runs:0,failed:0,ms:0,bg:0}};n.runs+=1,(t.status===`failed`||t.status===`killed`)&&(n.failed+=1),t.end!==void 0&&(n.ms+=Math.max(0,t.end-t.start)),e.commandStats=n}function D(e){e.commandStats={...e.commandStats??{runs:0,failed:0,ms:0,bg:0},bg:(e.commandStats?.bg??0)+1}}function $e(e,t,n){e.commands[t].status===`running`&&n.status!==`running`&&Qe(e,n),e.commands[t]=n}function et(e,t){return{...e.length>0?{outChars:e.reduce((e,t)=>e+t.length,0)}:{},...t.truncated===!0?{outTruncated:!0}:{},...t.stderr===!0?{stderr:!0}:{},...t.timedOut===!0?{timedOut:!0}:{},...t.stopped===!0?{stopped:!0}:{},...t.denied===!0?{denied:!0}:{},...t.signal===void 0?{}:{signal:t.signal},...t.exit===void 0?{}:{exit:t.exit}}}function tt(e){let{parsed:t}=e;return{seq:e.seq,time:e.time,tool:e.tool,cmd:t.cmd,...t.truncated===!0?{cmdTruncated:!0}:{},...t.description===void 0?{}:{description:t.description},...t.cwd===void 0?{}:{cwd:t.cwd},...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.background===!0?{background:!0}:{},...t.sandbox===void 0?{}:{sandbox:t.sandbox},...typeof e.turn==`number`?{turn:e.turn}:{},...typeof e.step==`number`?{step:e.step}:{},...e.codeMode===!0?{codeMode:!0}:{},start:e.time,status:`running`,err:!1,call:e.call}}function nt(e){let t=e?.toolCall;if(typeof t!=`object`||!t)return;let n=t.callId;return typeof n==`string`?n:void 0}function rt(e,t,n,r){let i=Je(r),a=Ye(r),o={...e,end:n,status:t===`completed`?i!==void 0&&i!==0?`failed`:`completed`:t,...i===void 0?{}:{exit:i},...a===void 0?{}:{signal:a}};return delete o.derived,delete o.exitInferred,o}function it(e,t,n,r){for(let i in t){let a=t[i].findIndex(e=>e.call===n);if(a<0)continue;let o=[...t[i]];return o[a]=r(o[a]),e.pendingCodeCmds={...t,[i]:o},!0}return!1}function at(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 O(e){let t=0,n;for(let r of e)r.turn!==n&&(t++,n=r.turn);return t}function ot(e,t){if(e.turnRuns=e.turnRuns??O(e.requests),e.turnRuns>t.maxKeptTurns&&(e.requests=at(e.requests,t.maxKeptTurns),e.turnRuns=O(e.requests)),e.requests.length>t.maxRequestSteps&&(e.requests=e.requests.slice(-t.maxRequestSteps),e.turnRuns=O(e.requests)),e.events.length>t.maxEvents&&(e.events=e.events.slice(-t.maxEvents)),e.spans.length>st&&(e.spans=e.spans.slice(-st)),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.commands.length>t.maxCommands){let n=e.commands.length-t.maxCommands,r=0,i=[];for(let t of e.commands)n>0&&t.status!==`running`?(n--,r=Math.max(r,t.seq)):i.push(t);if(i.length>t.maxCommands){let e=i.length-t.maxCommands;for(let t of i.slice(0,e))r=Math.max(r,t.seq);i.splice(0,e)}e.commandsFloor=Math.max(e.commandsFloor??0,r),e.commands=i}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 st=2e3;function ct(){return{surface:[],sums:{user:0,inject:0,skill:0,assistant:0,tool:0},assistantReasoning:0,assistantAnswerTokens:0,assistantCallTokens:0,systemTokens:0,toolsTokens:0,requests:[],turnRuns:0,events:[],archived:[],callNames:{},fileOps:[],commands:[],spans:[]}}const lt={"deepseek-official":`deepseek`,"deepseek-account":`deepseek`,"kimi-coding":`moonshotai`,"minimax-cn":`minimax`,"zai-coding-cn":`zhipuai`,claude:`anthropic`,codex:`openai`,fireworks:`fireworks-ai`,together:`togetherai`,"vercel-ai-gateway":`vercel`,"kimi-code-plan-global":`moonshotai`,"kimi-code-plan-cn":`moonshotai-cn`,"zai-coding-plan":`zai`,"zhipuai-coding-plan":`zhipuai`,"xiaomi-token-plan-ams":`xiaomi`,"xiaomi-token-plan-cn":`xiaomi`,"xiaomi-token-plan-sgp":`xiaomi`,"minimax-coding-plan":`minimax`,"minimax-cn-coding-plan":`minimax-cn`};function ut(e){return lt[e]??e}function dt(e){return ut(e)===`deepseek`}function k(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 ft(e){let t=new Date(e+288e5),n=t.getUTCDay();if(n===0||n===6)return!1;let r=t.getUTCHours();return r>=9&&r<12||r>=14&&r<18}function pt(e,t,n,r,i){let a=dt(t)&&!ft(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 mt(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 ht(e,t,n){let r=e.model;r!==void 0&&(e.cost=pt(e.cost,e.provider??``,r,t,n))}const gt=[`reasoning`,`text`,`toolarg`];function A(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,toolBusyMs:0,toolCalls:0,tools:{}}),e.timing}const vt={reasoning:{ms:`reasoningMs`,n:`reasoningBlocks`},text:{ms:`textMs`,n:`textBlocks`},toolarg:{ms:`toolArgMs`,n:`toolArgBlocks`}};function yt(e,t,n,r){let i=vt[t];n>0&&(e[i.ms]=(e[i.ms]??0)+n),r>0&&(e[i.n]=(e[i.n]??0)+r)}function bt(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 xt(e){let t={...e};return delete t.call,t}function St(e){let t=e.sums.user+e.sums.inject+e.sums.skill+e.sums.assistant+e.sums.tool,n=0,r=0;for(let t of e.surface)t.imgs!==void 0&&(n+=t.imgs),(t.cat===`tool`||t.cat===`skill`&&t.tool!==void 0)&&r++;let i={ok:!0,...e.model===void 0?{}:{model:e.model},...e.provider===void 0?{}:{provider:e.provider},...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort},...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,assistantReasoning:e.assistantReasoning,assistantAnswerTokens:e.assistantAnswerTokens,assistantCallTokens:e.assistantCallTokens,tool:e.sums.tool,total:t+e.systemTokens+e.toolsTokens},images:n,toolCalls:r,humanInputs:e.humanInputs??0,answers:e.answers??0,...e.lastUser===void 0?{}:{lastUser:e.lastUser},...e.generatedReasoning===void 0?{}:{generatedReasoning:e.generatedReasoning},...e.generatedAnswerTokens===void 0?{}:{generatedAnswerTokens:e.generatedAnswerTokens},...e.generatedCallTokens===void 0?{}:{generatedCallTokens:e.generatedCallTokens},requests:[],events:[],nodes:[],droppedNodes:0,archive:[]};if(e.cost!==void 0&&(i.cost=mt(e.cost)),e.timing!==void 0){let t={};for(let n in e.timing.tools)t[n]={...e.timing.tools[n]};i.timing={...e.timing,tools:t}}return e.systems!==void 0&&e.systems.length>0&&(i.systems=e.systems.map(e=>({...e}))),i}function Ct(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},commands:e.commands.map(xt),...e.commandsFloor===void 0?{}:{commandsFloor:e.commandsFloor},...e.commandStats===void 0?{}:{commandStats:{...e.commandStats}},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 wt(e){let t=St(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 j(e,t){return{rev:e.detailRev??0,head:wt(e),...Ct(e,t)}}function Tt(e,t){return{...St(e),...Ct(e,t)}}function Et(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`:Se(t?.source)?`inject`:`user`}function M(e){e.detailRev=(e.detailRev??0)+1}function Dt(e){for(let t=e.length-1;t>=0;t--)if(e[t].tokens>0)return e[t].tokens;return 0}function Ot(e,t){let n=[...e.systems??[],t];e.systems=n.length>8?n.slice(-8):n,e.systemTokens=Dt(e.systems)}function kt(e){if(typeof e==`string`)return e;if(e!=null)try{return JSON.stringify(e)}catch{return}}function At(e,t){for(let n of t)e.fileOps.push(n)}function jt(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 Mt(e,t,n){for(let r of t)e.archived.push({...r,gone:n})}function N(e,t,n){t.reasoning!==void 0&&(e.assistantReasoning+=n*t.reasoning),t.answerTokens!==void 0&&(e.assistantAnswerTokens+=n*t.answerTokens),t.callTokens!==void 0&&(e.assistantCallTokens+=n*t.callTokens)}function Nt(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,N(e,n,-1),i.push(n)):r.push(n);return Mt(e,i,n),e.surface=r,i}function Pt(e){let t=e?.message;return typeof t==`object`&&t?t:null}function Ft(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 It(e){let t=Ft(typeof e==`object`&&e?e.content:void 0).match(/<skill_content\s+name="([^"]+)"/);return t===null?``:t[1]}function P(e,t,n,r){let i=Et(n,r??void 0),a={seq:t.seq,time:t.time,cat:i,tokens:_e(r,n===`assistant/message`||n===`developer/message`)};if(i===`assistant`){let e=me(r?.content);e>0&&(a.reasoning=e);let t=ge(r?.content);t>0&&(a.answerTokens=t);let n=he(r?.content);n>0&&(a.callTokens=n)}let o=ye(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=S(r?.content);if(e!==``)a.text=e;else{let e=be(r?.content);e.length>0&&(a.calls=e.slice(0,3))}}else if(n===`tool/result`){let n=s?.callId,i=typeof n==`string`&&Object.hasOwn(e.callNames,n)?e.callNames[n]:void 0;if(i!==void 0){a.tool=i.name;let n=_t(e),r=A(i.start,t.time);n.toolsMs+=r,n.toolCalls+=1,bt(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=S(r?.content);e!==``&&(a.text=e)}}else{let e=S(r?.content);e!==``&&(a.text=e)}let l=e.pendingShadowedSeqs,u=e.pendingShadowEventSeq;delete e.pendingShadowedSeqs,delete e.pendingShadowEventSeq;let d=Oe(t.surfaceOp);if(d!==null){if(Array.isArray(l)&&l.length>0){let n=Nt(e,new Set(l),t.seq);if(e.sums[i]+=a.tokens,N(e,a,1),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);Mt(e,o,t.seq);for(let t of o)e.sums[t.cat]-=t.tokens,N(e,t,-1);return e.sums[i]+=a.tokens,N(e,a,1),a}}return e.surface.push(a),e.sums[i]+=a.tokens,N(e,a,1),a}const Lt=`ask_user_question`,Rt=[`surface`,`sums`,`requests`,`events`,`archived`,`callNames`,`fileOps`,`timing`,`commands`];function F(e,t,r){let i,a=(t=Rt)=>{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]:n===`commands`?i.commands=[...e.commands]: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=ue(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),e.config&&typeof e.config.reasoningEffort==`string`&&e.config.reasoningEffort!==``?r.reasoningEffort=e.config.reasoningEffort:delete r.reasoningEffort;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}),M(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=Oe(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);Nt(e,r,t.seq).length>0&&M(e)}Ot(e,{seq:t.seq,time:t.time,tokens:re(Pt(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=w(o.name),n=a(e===null?[`callNames`]:[`callNames`,`commands`]),i=Pe(o.name)?kt(o.arguments):void 0;if(o.callId!==`__proto__`&&(n.callNames[o.callId]={name:o.name,start:t.time,...i===void 0?{}:{argsRaw:i}}),e!==null){let i=Ge(e,o.arguments,r.maxCommandChars);i!==null&&(n.commands.push(tt({seq:t.seq,time:t.time,tool:e,parsed:i,turn:o.turn,step:o.step,call:o.callId})),i.background===!0&&D(n),M(n))}}break;case`job/registered`:{let t=nt(o),n=o?.startedAt;if(t===void 0||typeof n!=`number`||!Number.isFinite(n))return e;let r=E(e.commands,t);if(r>=0){let e=a([`commands`]);e.commands[r]={...e.commands[r],start:n},M(e);break}if(e.pendingCodeCmds===void 0||!it(a([]),e.pendingCodeCmds,t,e=>({...e,start:n})))return e;break}case`job/settled`:{let t=nt(o),n=o?.finishedAt,r=o?.status;if(t===void 0||typeof n!=`number`||!Number.isFinite(n)||r!==`completed`&&r!==`killed`&&r!==`failed`)return e;let i=E(e.commands,t);if(i>=0){let e=a([`commands`]);$e(e,i,rt(e.commands[i],r,n,o?.detail)),M(e);break}let s=e.pendingCodeCmds;if(s===void 0||!it(a([]),s,t,e=>rt(e,r,n,o?.detail)))return e;break}case`tool/ptc-dispatch-start`:{let n=o?.rootCallId,i=o?.subCallId,s=w(typeof o?.name==`string`?o.name:void 0);if(typeof n!=`string`||typeof i!=`string`||s===null)return e;let c=Ge(s,o?.arguments,r.maxCommandChars);if(c===null)return e;let l=e.pendingCodeCmds??{},u=0;for(let e in l)u+=l[e].length;if(u+1>200)return e;let d=tt({seq:t.seq,time:t.time,tool:s,parsed:c,codeMode:!0,call:i}),f=a([]);c.background===!0&&D(f),f.pendingCodeCmds={...l,[n]:[...l[n]??[],d]};break}case`tool/ptc-dispatch`:{let n=o?.rootCallId,r=o?.name;if(typeof n==`string`&&typeof r==`string`){let i=o?.subCallId,s=typeof i==`string`?e.pendingCodeCmds?.[n]:void 0,c=s?.findIndex(e=>e.call===i)??-1,l=Ne(r)?kt(o?.arguments):void 0,u=Ue({seq:t.seq,time:t.time,tool:r,argsRaw:l,err:o?.isError===!0});if(u.length>0||s!==void 0&&c>=0){let r=a([]);if(u.length>0&&jt(r,n,u),s!==void 0&&c>=0){let i=s[c],a=Ze(o?.content),l=qe(a.at(-1)??``),u=o?.isError===!0,d={...i,...et(a,l),err:u};if(l.backgroundAck===!0)d.background=!0,i.background!==!0&&D(r);else{let e=Xe(l,u);d.status=e.status,e.exit!==void 0&&(d.exit=e.exit),e.exitInferred===!0&&(d.exitInferred=!0),d.end=t.time,d.derived=!0}let f=[...s];f[c]=d,r.pendingCodeCmds={...e.pendingCodeCmds,[n]:f}}}}break}case`assistant/attempt`:{let t=e.stepStart;if(t===void 0||t.firstToken!==void 0)return e;let n=Ee(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`]),i=_t(r);i.wallMs+=A(n.time,t.time);let o=[...e.stepWaits??[]];for(let n in e.stepApprovals)o.push({start:e.stepApprovals[n],end:t.time});o.sort((e,t)=>e.start-t.start||e.end-t.end);let s=0,c=n.time;for(let e of o){let n=Math.max(c,e.start),r=Math.min(e.end,t.time);r>n&&(s+=r-n,c=r)}let l=A(n.time,t.time)-s,u=e.requests.at(-1);u!==void 0&&u.seq===e.stepRequestSeq&&(r.requests[r.requests.length-1]={...u,activeMs:l});let d=[];for(let r of e.stepSpans??[]){let e=Math.max(n.time,r.start),i=Math.min(t.time,r.end);i>e&&d.push({kind:r.kind,start:e,end:i})}d.sort((e,t)=>e.start-t.start||e.end-t.end);let f=[],p=n.time,m=0;for(let e of d){let t=Math.max(p,e.start);e.end<=t||(t>p&&f.push({kind:`other`,start:p,end:t}),f.push({kind:e.kind,start:t,end:e.end}),e.kind===`tools`&&(m+=e.end-t),p=e.end)}t.time>p&&f.push({kind:`other`,start:p,end:t.time}),r.spans=[...e.spans,...f],i.toolBusyMs!==void 0&&(i.toolBusyMs+=m),delete r.stepStart,delete r.stepSpans,delete r.stepWaits,delete r.stepApprovals,delete r.stepRequestSeq,M(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?Pt(o):n(t);if(r&&(i===null||!Array.isArray(i.content)))return e;let s=a([`surface`,`sums`,`archived`,`events`]);M(s);let c=P(s,t,t.type,i),l=i?.source;if(r||Se(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=xe(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`&&Object.hasOwn(e.callNames,i)?e.callNames[i]:void 0,c=typeof i==`string`?e.pendingCodeOps?.[i]:void 0,l=typeof i==`string`?e.pendingCodeCmds?.[i]:void 0,u=s!==void 0&&w(s.name)!==null,d=a([`surface`,`sums`,`archived`,`events`,`fileOps`,`timing`,...(l?.length??0)>0||u?[`commands`]:[]]);M(d);let f=P(d,t,t.type,r);if(f.tool===Lt&&(d.humanInputs=(d.humanInputs??0)+1),s!==void 0&&s.name===Lt&&e.stepStart!==void 0&&(d.stepWaits=[...e.stepWaits??[],{start:s.start,end:t.time}]),s!==void 0&&(At(d,Ue({seq:t.seq,time:t.time,tool:s.name,argsRaw:s.argsRaw,meta:o?.meta,err:r?.isError===!0})),typeof i==`string`&&w(s.name)!==null)){let e=E(d.commands,i);if(e>=0){let n=d.commands[e],i=Ze(r?.content),a=qe(i.at(-1)??``),s=r?.isError===!0,c={...n,...et(i,a),resultSeq:t.seq,err:s};a.exit!==void 0&&delete c.exitInferred;let l=o?.meta?.cwd;if(typeof l==`string`&&l!==``&&(c.cwd=l),a.backgroundAck===!0)c.background=!0,n.background!==!0&&D(d);else if(n.status===`running`){let e=Xe(a,s);c.status=e.status,n.tool!==`run_code`&&(e.exit!==void 0&&(c.exit=e.exit),e.exitInferred===!0&&(c.exitInferred=!0)),c.end=t.time,c.derived=!0}$e(d,e,c)}}if(c!==void 0&&c.length>0){let e=ke(s?.argsRaw)?.description;At(d,c.map(n=>({...n,parent:t.seq,...typeof e==`string`&&e!==``?{program:e}:{}})));let n={};for(let e in d.pendingCodeOps)e!==i&&(n[e]=d.pendingCodeOps[e]);Object.keys(n).length>0?d.pendingCodeOps=n:delete d.pendingCodeOps}if(l!==void 0&&l.length>0){for(let e of l){let n={...e,parent:t.seq};d.commands.push(n),n.status!==`running`&&Qe(d,n)}let e={};for(let t in d.pendingCodeCmds)t!==i&&(e[t]=d.pendingCodeCmds[t]);Object.keys(e).length>0?d.pendingCodeCmds=e:delete d.pendingCodeCmds}if(f.tool===`skill`||f.tool===void 0){let e=It(r);e!==``&&(f.skill=e,f.tool===void 0&&(f.tool=`skill`),d.sums.tool-=f.tokens,f.cat=`skill`,d.sums.skill+=f.tokens,d.events.push({seq:t.seq,time:t.time,kind:`inject`,form:`instructions`,sub:`skill`,name:e,tokens:f.tokens}))}break}case`assistant/message`:{let r=o?.usage,i=a([`surface`,`sums`,`archived`,`events`,`requests`,`timing`]);M(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=k(r.inputTokens),n=k(r.cacheReadTokens),a=k(r.cacheWriteTokens);l=k(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),ht(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??O(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=De(o?.stream,t.time),n=f.firstToken??e.firstToken;if(n!==void 0){let r=e.spans,a=n;for(let e of r)a=Math.min(a,e.start);d.ttftMs+=A(f.time,a),d.genMs+=A(a,t.time);let o=[{kind:`ttft`,start:f.time,end:a}];for(let e of r){let n=Math.min(t.time,e.end);n<=e.start||o.push({kind:e.kind,start:o.length===1?a:e.start,end:n})}i.stepSpans=[...i.stepSpans??[],...o],l!==null&&(d.speedMs=(d.speedMs??0)+A(n,t.time),d.speedTokens=(d.speedTokens??0)+l);let s=e.tally;for(let e of gt)yt(d,e,s.spans[e],s.blocks[e])}}let p=n(t),m=P(i,t,t.type,p);m.text!==void 0&&(i.answers=(i.answers??0)+1);let h=typeof r==`object`&&r?k(r.reasoningTokens):null,g=h===null?m.reasoning??0:l===null?h:Math.min(h,l);g>0&&(i.generatedReasoning=(i.generatedReasoning??0)+g);let _=m.answerTokens??0;_>0&&(i.generatedAnswerTokens=(i.generatedAnswerTokens??0)+_);let v=m.callTokens??0;v>0&&(i.generatedCallTokens=(i.generatedCallTokens??0)+v);break}case`session/end-seed`:{if(o?.inherited!==!0)break;let e=a([]);e.cost={},delete e.generatedReasoning,delete e.generatedAnswerTokens,delete e.generatedCallTokens;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`}),M(e)}break;case`compaction/summary`:case`compaction/prune`:{let e=a([`events`]);M(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:(ot(i,r),i)}const I={maxRequestSteps:1500,maxKeptTurns:300,maxEvents:400,maxNodes:2e3,maxArchiveNodes:400,maxFileOps:400,maxCommands:400,maxCommandChars:4096};function L(e){let t=e.volatile;return typeof t==`function`?t.call(e):e}function R(e){return i.number().min(1).step(1).default(e)}const zt=i.object({maxRequestSteps:R(I.maxRequestSteps),maxKeptTurns:R(I.maxKeptTurns),maxEvents:R(I.maxEvents),maxNodes:R(I.maxNodes),maxArchiveNodes:R(I.maxArchiveNodes),maxFileOps:R(I.maxFileOps),maxCommands:R(I.maxCommands),maxCommandChars:R(I.maxCommandChars),defaultPlacement:L(i.union([`all`,`tab`,`sidebar`,`hide`]).default(`all`).loose()),defaultGranularity:L(i.union([`step`,`turn`]).default(`step`).loose()),defaultTrendMode:L(i.union([`total`,`delta`]).default(`total`).loose()),defaultDeltaBase:L(i.union([`step`,`turn`]).default(`step`).loose()),defaultToolSort:L(i.union([`size`,`count`,`name`]).default(`count`).loose()),defaultFileSort:L(i.union([`count`,`lines`,`latest`,`path`,`name`]).default(`lines`).loose()),insightsEntry:L(i.union([`show`,`hide`]).default(`show`).loose()),defaultDurationCurve:L(i.union([`show`,`hide`]).default(`show`).loose()),overviewAutoSteps:L(i.union([`100`,`200`,`300`,`off`]).default(`100`).loose()),defaultOverviewRange:L(i.union([`today`,`7d`,`30d`,`all`]).default(`30d`).loose()),fleetTab:L(i.union([`show`,`hide`]).default(`show`).loose()),promptPrefix:L(i.string().default(``).loose()),promptSuffix:L(i.string().default(``).loose())});function z(e){let t=zt(e??{});return{maxRequestSteps:t.maxRequestSteps,maxKeptTurns:t.maxKeptTurns,maxEvents:t.maxEvents,maxNodes:t.maxNodes,maxArchiveNodes:t.maxArchiveNodes,maxFileOps:t.maxFileOps,maxCommands:t.maxCommands,maxCommandChars:t.maxCommandChars}}const B=t.object({seq:t.number().int().nonnegative(),time:t.number().optional(),cat:t.enum([`user`,`inject`,`skill`,`assistant`,`tool`]),tokens:t.number().int().nonnegative(),reasoning:t.number().int().nonnegative().optional(),answerTokens:t.number().int().nonnegative().optional(),callTokens:t.number().int().nonnegative().optional(),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(),Bt=t.object({seq:t.number().int().nonnegative(),time:t.number(),tokens:t.number().int().nonnegative()}).strict(),Vt=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(),Ht=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(),V=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(),Ut=t.object({seq:t.number().int().nonnegative(),resultSeq:t.number().int().nonnegative().optional(),time:t.number(),tool:t.string(),cmd:t.string(),cmdTruncated:t.literal(!0).optional(),description:t.string().optional(),cwd:t.string().optional(),timeoutMs:t.number().positive().optional(),background:t.literal(!0).optional(),sandbox:t.string().optional(),codeMode:t.literal(!0).optional(),parent:t.number().int().nonnegative().optional(),turn:t.number().optional(),step:t.number().optional(),start:t.number(),end:t.number().optional(),status:t.enum([`running`,`completed`,`failed`,`killed`]),exit:t.number().int().optional(),exitInferred:t.literal(!0).optional(),signal:t.string().optional(),timedOut:t.literal(!0).optional(),stopped:t.literal(!0).optional(),denied:t.literal(!0).optional(),err:t.boolean(),outChars:t.number().int().nonnegative().optional(),outTruncated:t.literal(!0).optional(),stderr:t.literal(!0).optional(),derived:t.literal(!0).optional(),gone:t.number().int().nonnegative().optional()}).strict(),Wt=Ut.extend({call:t.string().optional()}).strict(),Gt=t.object({runs:t.number().int().nonnegative(),failed:t.number().int().nonnegative(),ms:t.number().nonnegative(),bg:t.number().int().nonnegative()}).strict(),Kt=t.object({kind:t.enum([`ttft`,`reasoning`,`text`,`toolarg`,`tools`,`other`]),start:t.number(),end:t.number()}).strict(),qt=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(),assistantReasoning:t.number().int().nonnegative().optional(),assistantAnswerTokens:t.number().int().nonnegative().optional(),assistantCallTokens:t.number().int().nonnegative().optional(),tool:t.number().int().nonnegative(),total:t.number().int().nonnegative()}).strict(),Jt=t.object({uncached:t.number().int().nonnegative(),cacheRead:t.number().int().nonnegative(),cacheWrite:t.number().int().nonnegative(),output:t.number().int().nonnegative()}).strict(),Yt=t.object({peak:Jt.optional(),off:Jt.optional()}).strict(),Xt=t.record(t.string(),Yt),Zt=t.record(t.string(),Xt),Qt=t.object({calls:t.number().int().nonnegative(),ms:t.number().nonnegative()}).strict(),$t=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(),toolBusyMs:t.number().nonnegative().optional(),toolCalls:t.number().int().nonnegative(),tools:t.record(t.string(),Qt)}).strict(),en=t.object({current:t.string(),minimum:t.string()}).strict(),tn=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(),nn=t.object({seq:t.number(),total:t.number().int().nonnegative(),prompt:t.number().int().nonnegative().optional()}).strict(),rn=t.object({ok:t.literal(!0),unsupported:en.optional(),model:t.string().optional(),provider:t.string().optional(),reasoningEffort:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),current:qt,images:t.number().int().nonnegative().optional(),generatedReasoning:t.number().int().nonnegative().optional(),generatedAnswerTokens:t.number().int().nonnegative().optional(),generatedCallTokens: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:tn.optional(),last:nn.optional(),detailRev:t.number().int().nonnegative().optional(),requests:t.array(Vt).optional(),events:t.array(Ht).optional(),cost:Zt.optional(),timing:$t.optional(),systems:t.array(Bt).optional(),nodes:t.array(B).optional(),droppedNodes:t.number().int().nonnegative().optional(),archive:t.array(B).optional(),surfaceFloor:t.number().int().nonnegative().optional(),archiveFloor:t.number().int().nonnegative().optional(),fileOps:t.array(V).optional(),fileOpsFloor:t.number().int().nonnegative().optional(),commands:t.array(Ut).optional(),commandsFloor:t.number().int().nonnegative().optional(),commandStats:Gt.optional(),spans:t.array(Kt).optional()}).strict(),an=t.object({surface:t.array(B),assistantReasoning:t.number().int().nonnegative(),assistantAnswerTokens:t.number().int().nonnegative(),assistantCallTokens:t.number().int().nonnegative(),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(Bt).optional(),toolsTokens:t.number().int().nonnegative(),model:t.string().optional(),provider:t.string().optional(),reasoningEffort:t.string().optional(),lastModel:t.string().optional(),contextWindow:t.number().optional(),maxOutputTokens:t.number().positive().optional(),requests:t.array(Vt),turnRuns:t.number().int().nonnegative().optional(),events:t.array(Ht),archived:t.array(B),cost:Zt.optional(),generatedReasoning:t.number().int().nonnegative().optional(),generatedAnswerTokens:t.number().int().nonnegative().optional(),generatedCallTokens:t.number().int().nonnegative().optional(),archiveFloor:t.number().optional(),timing:$t.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(V),fileOpsFloor:t.number().int().nonnegative().optional(),commands:t.array(Wt),commandsFloor:t.number().int().nonnegative().optional(),commandStats:Gt.optional(),pendingCodeCmds:t.record(t.string(),t.array(Wt)).optional(),spans:t.array(Kt),stepSpans:t.array(Kt).optional(),pendingCodeOps:t.record(t.string(),t.array(V)).optional()});function on(e,t){let n=z(e);return{key:`contextTimeline`,stateSchema:an,wire:{viewSchema:rn,view:e=>t()?wt(e):Tt(e,n)},init:()=>ct(),apply:(e,t)=>F(e,t,n),stateVersion:35}}function H(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 sn=t.object({n:t.number().int().nonnegative(),last:t.number()}).strict(),cn=t.object({start:t.number().nonnegative(),day:t.string()}).strict(),ln=t.object({tokens:t.number().int().nonnegative(),requests:t.number().int().nonnegative(),cost:Zt.optional(),turns:t.number().int().nonnegative().optional(),toolCalls:t.number().int().nonnegative().optional(),toolsMs:t.number().nonnegative().optional(),wallMs:t.number().nonnegative().optional(),skills:t.record(t.string(),sn).optional()}).strict(),un=t.object({days:t.record(t.string(),ln)}).strict(),dn=t.object({days:t.record(t.string(),ln),model:t.string().optional(),provider:t.string().optional(),stepStart:t.number().optional(),lastTurn:t.number().optional(),toolStarts:t.record(t.string(),cn).optional(),skillCalls:t.array(t.string()).optional()});function fn(e){if(typeof e!=`object`||!e)return null;let t=e,n=k(t.inputTokens),r=k(t.cacheReadTokens),i=k(t.cacheWriteTokens),a=k(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 pn(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 mn(e){return{tokens:e?.tokens??0,requests:e?.requests??0,...e?.cost===void 0?{}:{cost:e.cost},...e?.turns===void 0?{}:{turns:e.turns},...e?.toolCalls===void 0?{}:{toolCalls:e.toolCalls},...e?.toolsMs===void 0?{}:{toolsMs:e.toolsMs},...e?.wallMs===void 0?{}:{wallMs:e.wallMs},...e?.skills===void 0?{}:{skills:e.skills}}}function hn(e,t,n){return pn(e,t,{...mn(e.days[t]),...n})}function gn(e,t,n){if(!Number.isFinite(n)||n<0)return e;let r=H(e.stepStart??n);if(r===null)return e;let i=e.toolStarts?.[t];if(i!==void 0&&i.start===n&&i.day===r)return e;let a={...e.toolStarts,[t]:{start:n,day:r}},o=Object.entries(a),s=o.length>100?Object.fromEntries(o.slice(o.length-100)):a;return{...e,toolStarts:s}}function _n(e,t,n){let r=e.toolStarts,i=r?.[t];if(r===void 0||i===void 0)return e;let a=e.days[i.day],o=hn(e,i.day,{toolCalls:(a?.toolCalls??0)+1,toolsMs:(a?.toolsMs??0)+A(i.start,n)}),s=Object.fromEntries(Object.entries(r).filter(([e])=>e!==t)),c={...o};return Object.keys(s).length>0?c.toolStarts=s:delete c.toolStarts,c}function vn(e,t,n){let r=H(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 pn(e,r,{...mn(i),skills:o})}function yn(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 bn(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 xn(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`){let n=e.stepStart;if(n===void 0)return e;let r=H(n),i=A(n,t.time),a={...r===null||i<=0?e:hn(e,r,{wallMs:(e.days[r]?.wallMs??0)+i})};return delete a.stepStart,a}if(t.type===`session/end-seed`)return t.data?.inherited===!0?{days:{}}:e;if(t.type===`user/message`||t.type===`developer/message`){let n=yn(t);return n===``?e:vn(e,n,t.time)}if(t.type===`tool/call`){let n=t.data,r=n?.callId;if(typeof r!=`string`||r===``)return e;let i=gn(e,r,t.time);if(n?.name!==`skill`)return i;let a=i.skillCalls??[];return a.includes(r)?i:{...i,skillCalls:[...a,r].slice(-100)}}if(t.type===`tool/result`){let n=t.data?.message,r=bn(n),i=r===null?e:_n(e,r,t.time),a=i.skillCalls;if(r===null||a===void 0||!a.includes(r))return i;let o=a.filter(e=>e!==r),s={...i};o.length>0?s.skillCalls=o:delete s.skillCalls;let c=It(n);return c===``?s:vn(s,c,t.time)}if(t.type!==`assistant/message`)return e;let n=e.stepStart===void 0?t.time:e.stepStart,r=H(n);if(r===null)return e;let i=t.data,a=fn(i?.usage),o=e.days[r],s=o?.cost;a!==null&&e.model!==void 0&&(s=pt(s,e.provider??``,e.model,n,a));let c=typeof i?.turn==`number`&&Number.isFinite(i.turn)?i.turn:void 0,l=c!==void 0&&c!==e.lastTurn,u=(o?.turns??0)+ +!!l,d=pn(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},...u>0?{turns:u}:{},...o?.toolCalls===void 0?{}:{toolCalls:o.toolCalls},...o?.toolsMs===void 0?{}:{toolsMs:o.toolsMs},...o?.wallMs===void 0?{}:{wallMs:o.wallMs},...o?.skills===void 0?{}:{skills:o.skills}});return l?{...d,lastTurn:c}:d}function Sn(){return{key:`contextActivity`,stateSchema:dn,init:()=>({days:{}}),apply:(e,t)=>xn(e,t),wire:{viewSchema:un,view:e=>({days:Object.fromEntries(Object.entries(e.days).map(([e,t])=>[e,{...t,...t.cost===void 0?{}:{cost:mt(t.cost)},...t.skills===void 0?{}:{skills:Object.fromEntries(Object.entries(t.skills).map(([e,t])=>[e,{...t}]))}}]))})},stateVersion:5}}const Cn=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]);function wn(e){return e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1)}function Tn(e){let t=wn(e),n=t.lastIndexOf(`.`);return n<0?``:t.slice(n+1).toLowerCase()}function En(e){return Cn.has(Tn(e))}function U(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Dn(e){if(typeof e!=`object`||!e)return;let t=e,n=U(t.width),r=U(t.height);return n!==void 0&&r!==void 0?{width:n,height:r}:void 0}function On(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=U(r.bytes);if(n===`file`)return{kind:`file`,attachmentId:r.attachmentId,...i===void 0?{}:{name:i},...a===void 0?{}:{bytes:a}};let o=Dn(r.originalDimensions),s=U(r.width),c=U(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 kn(){let e=m();return{used:e.used_heap_size,limit:e.heap_size_limit}}const An=()=>{};function W(e=kn){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(An,An),r}}}function jn(e){return typeof e?.fetch?.register==`function`?e.fetch.register.bind(e.fetch):void 0}function G(e,t,n,r,i){let a=jn(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 Mn={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`};function Nn(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function K(e,t){return Nn({ok:!1,error:{code:e,message:t}})}function Pn(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Fn(e,t,n){if(n>8)return null;if(Array.isArray(e)){for(let r of e){let e=Fn(r,t,n+1);if(e!==null)return e}return null}if(typeof e!=`object`||!e)return null;let r=On(e);if(r!==null&&r.attachmentId===t)return r;for(let r of Object.values(e)){let e=Fn(r,t,n+1);if(e!==null)return e}return null}function In(e,t){for(let n of e)try{let e=Fn(n,t,0);if(e!==null)return e}catch{}return null}function Ln(e){let t=wn(e.name??``);if(t!==``&&En(t))return t;let n=e.mediaType===void 0?void 0:Mn[e.mediaType];return n===void 0?null:`attachment.${n}`}function Rn(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 zn(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 Bn(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=Rn(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 Vn(e,t){return t.kind===`file`?zn(e,t):await Bn(e,t)}function Hn(e,t=W()){e.inject([`connection`],n=>{G(n,n.get(`connection`),`/api/dsh-context/attachment`,async n=>{let r,i;try{let e=Pn(await n.json());r=e?.sessionId,i=e?.attachmentId}catch{return K(`dsh-context/bad-request`,`body is not JSON`)}if(typeof r!=`string`||r===``)return K(`dsh-context/bad-request`,`missing sessionId`);if(typeof i!=`string`||i===``)return K(`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 Nn({ok:!0,value:null});let o=e.get(`attachments`);return Nn({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=In(t,i);if(n===null)return null;let r=await Vn(o,n);return r===null?null:{path:r}}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return K(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: attachment route`)})}function Un(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 Wn(e){let t=Un(e);return t===void 0?void 0:`mcp:${t}`}function Gn(e){return Kn[e]}const Kn=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`}),qn=f(_(import.meta.url)),Jn=new Map;function Yn(e){let t=l(e);for(let e=0;e<12;e++){let e=Jn.get(t);if(e!==void 0)return e;let n=d(t,`package.json`);if(h(n))try{let e=JSON.parse(g(n,`utf8`)).name;if(typeof e==`string`&&e)return Jn.set(t,e),e}catch{}let r=l(t);if(Jn.set(t,void 0),r===t)return;t=r}}const Xn=/:\d+:\d+$/,Zn=Symbol.for(`cordis.original`);function Qn(e){return e?.[Zn]??e}const $n=Yn(qn);function er(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(_(r))}catch{continue}else if(!/^[A-Za-z]:[\\/]/.test(r)&&!r.startsWith(`/`)&&!r.startsWith(`\\\\`))continue;else r=f(r);if(r===qn)continue;let i=Yn(r);if(i!==void 0&&i!==$n)return i}}function tr(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=er(Error().stack));let o=s.call(this,e);return typeof n==`string`&&a&&a!==`root`&&a!==r&&a!==$n&&(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(Qn(a)),a}),e.effect(()=>()=>{for(let e of a.splice(0))e()},`tools.register attribution`);let s=Qn(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=>Wn(e)??t.get(e)??Gn(e)??(c.has(e)?`<unknown-plugin>`:void 0)}}function q(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}const nr=[`llm-deepseek`,`web-deepseek-api`,`web-search-deepseek`],rr=`https://api.deepseek.com`;function ir(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null}function ar(e){let t=[],n=e.get(`llm`);if(typeof n?.listConfigurableProviders==`function`)try{let e=n.listConfigurableProviders();if(Array.isArray(e))for(let n of e)try{let e=q(n);if(e===null||e.provider!==`deepseek-official`)continue;let r=e.settingsNs;typeof r==`string`&&r!==``&&!t.includes(r)&&t.push(r)}catch{continue}}catch{}for(let e of nr)t.includes(e)||t.push(e);return t}function or(e){let t=e.get(`settings`);if(typeof t?.describe!=`function`)return[];let n;try{n=t.describe({redactSecrets:!0})}catch{return[]}if(!Array.isArray(n))return[];let r=new Map;for(let e of n)try{let t=q(e);if(t===null)continue;let n=t.ns,i=q(t.value);if(typeof n!=`string`||i===null||r.has(n))continue;r.set(n,i)}catch{continue}let i=[];for(let t of ar(e)){let e=r.get(t);if(e===void 0)continue;let n=e.apiKeyEnv;if(typeof n!=`string`||n===``)continue;let a=e.baseURL;i.push({apiKeyEnv:n,baseURL:typeof a==`string`&&a!==``?a:void 0})}return i}function sr(e){if(e===void 0)return rr;try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?rr:t.origin}catch{return rr}}async function cr(e){let t=e.get(`credentials`),n=typeof t?.resolve==`function`?t.resolve.bind(t):void 0;if(n===void 0)return null;let r=new Set;for(let t of or(e)){if(r.has(t.apiKeyEnv))continue;r.add(t.apiKeyEnv);let e;try{e=await n(t.apiKeyEnv)}catch{continue}let i=typeof e?.value==`string`?e.value:``;if(i!==``)return{baseUrl:sr(t.baseURL),apiKey:i}}return null}function lr(e){let t=q(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=q(e);if(t===null)continue;let n=t.currency,i=ir(t.granted_balance),a=ir(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 ur=(e,t)=>fetch(e,t),J=null;async function dr(e){if(J!==null)return J;J=(async()=>{let t=null;try{let n=await ur(e.baseUrl+`/user/balance`,{headers:{accept:`application/json`,authorization:`Bearer `+e.apiKey},signal:AbortSignal.timeout(1e4)});n.ok&&(t=lr(await n.json()))}catch{}return t})();let t=J;try{return await t}finally{J=null}}function fr(e){e.inject([`connection`],t=>{G(t,t.get(`connection`),`/api/dsh-context/balance`,async()=>{let t=await cr(e),n=t===null?null:await dr(t);return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: balance route`)})}const pr=2e3,mr={now:()=>v.now(),sleep:e=>new Promise(t=>setTimeout(t,e)),minRestMs:25,workBudgetMs:8e3,roundPauseMs:2e3};function hr(e){let t=q(q(e)?.header);return t===null||typeof t.id!=`string`||t.id===``?null:t}const gr=[`contextActivity`,`contextTimeline`];function _r(e,t){try{let n=q(q(e.cachedSnapshot(t,gr))?.values);return n!==null&&n.contextActivity!==void 0&&n.contextTimeline!==void 0}catch{return!1}}async function vr(e,t,n){let i=await e.open(t,`read`,{signal:n}),a;try{let e=q(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 yr(e,t){if(e===null||typeof e.get!=`function`)return!1;try{return e.get(t)!==void 0}catch{return!0}}async function br(e,t,n,r,i,a,o){let{header:s,inheritedEventCount:c,events:l}=r,u={},d=0;for(let e=pr;;e+=pr){let n=e>=l.length,r=o();u=q(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(yr(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): ${Y(t)}`)}return{outcome:`done`,workMs:d}}function xr(e){try{return String(q(e)?.name).startsWith(`SessionFormatUnsupported`)}catch{return!1}}function Y(e){try{return String(e)}catch{return`unprintable error`}}function Sr(e,t=W(),n=mr){let r=!1,i=!1,a=null,o=()=>{r&&!i&&a!==null&&(i=!0,a())},s=e.inject([`connection`],e=>{G(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=q(i.sessionQuery),c=q(i.sessionProjectionCache),l=q(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=q(i.sessions),d=q(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=>{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)):await m(Math.max(n.minRestMs,t))};for(let s of r){if(p.signal.aborted)return;let r=hr(s);if(r===null||typeof r.cwd!=`string`||yr(u,r.id)||_r(c,r))continue;let d=n.now(),m=0;try{let a=await t.admit(async()=>{let t=await vr(l,r.id,p.signal);if(f!==null&&t.events.length>pr){let r=await br(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){xr(t)?(a++,e.logger.debug(`dsh-context: projection backfill skipped "${r.id}" (${Y(t)})`)):e.logger.warn(`dsh-context: projection backfill skipped "${r.id}" (${Y(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 (${Y(t)})`)})},o(),()=>{p.abort()}});return()=>{for(let e of[s,c])e?.dispose?.()}}function Cr(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function X(e,t){return Cr({ok:!1,error:{code:e,message:t}})}function wr(e){let t=e.revision;return typeof t==`string`&&t!==``?t:void 0}function Tr(e){let t=e.cursor;return typeof t==`number`&&Number.isFinite(t)?t:-1}function Er(e,t,n,r,i){return e===void 0||e.live!==t||e.cursor>r?!1:t||e.revision===n&&e.persistence===i}function Dr(e,t,n){let r=[];for(let n of e.commands)(t===void 0||n.seq<t)&&r.push(n);return r.sort((e,t)=>e.seq-t.seq),{commands:(r.length>n?r.slice(r.length-n):r).map(xt),atStart:r.length<=n,total:e.commands.length}}async function Or(e,t,n,r,i,a,o){let s=e.source===`live`,c=s?void 0:wr(e),l=Tr(e),u=s||c!==void 0,d=i.get(a),f=u&&Er(d,s,c,l,o),p=f&&d!==void 0?d.state:ct(),m=f&&d!==void 0?d.cursor:-1;if(m<l){if(!Array.isArray(e.events))return null;let t={...r,maxCommands:2**53-1},n=0;for(let r=m+1;r<e.events.length&&r<=l;r++)p=F(p,e.events[r],t),m=r,++n%1e3==0&&await new Promise(e=>setTimeout(e,0))}if(u){i.delete(a),i.set(a,{live:s,persistence:o,...c===void 0?{}:{revision:c},cursor:m,state:p});for(let e of i.keys()){if(i.size<=2)break;i.delete(e)}}return Dr(p,t,n)}function kr(e,t,n=W()){let r=new Map;e.inject([`connection`,`sessionQuery`],e=>{let i=e.get(`sessionQuery`),a=typeof i?.observeSession==`function`?i.observeSession.bind(i):void 0;a!==void 0&&G(e,e.get(`connection`),`/api/dsh-context/commands`,async i=>{let o,s,c;try{let e=await i.json();typeof e==`object`&&e&&(o=e.sessionId,s=e.beforeSeq,c=e.limit)}catch{return X(`dsh-context/bad-request`,`body is not JSON`)}if(typeof o!=`string`||o===``)return X(`dsh-context/bad-request`,`missing sessionId`);if(s!==void 0&&(typeof s!=`number`||!Number.isFinite(s)||s<0))return X(`dsh-context/bad-request`,`beforeSeq must be a non-negative number`);let l=typeof c==`number`&&Number.isFinite(c)?Math.min(1e3,Math.max(1,Math.floor(c))):400;try{let i=e.get(`sessionPersistence`);return Cr({ok:!0,value:await n.admit(async()=>{let e=await a(o,{projectionMode:`none`});if(typeof e!=`object`||!e)return null;try{return await Or(e,s,l,t,r,o,i)}finally{let t=e[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return X(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: command page route`)})}function Ar(e){let t=e?.revision;return typeof t==`string`&&t!==``?t:void 0}function jr(e){return{rev:e.rev,head:e.head}}function Mr(e){return{rev:e.detailRev??0,head:wt(e)}}function Nr(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function Pr(e,t){return Nr({ok:!1,error:{code:e,message:t}})}function Fr(e,t,n=W()){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(G(a,a.get(`connection`),`/api/dsh-context/detail`,async r=>{let a,o=!1;try{let e=await r.json();a=typeof e==`object`&&e?e.sessionId:void 0,o=typeof e==`object`&&!!e&&e.head===!0}catch{return Pr(`dsh-context/bad-request`,`body is not JSON`)}if(typeof a!=`string`||a===``)return Pr(`dsh-context/bad-request`,`missing sessionId`);try{let r=s(a);if(r!=null){let e=c.stateOf(r,`contextTimeline`);return Nr(e===void 0?{ok:!0,value:null}:{ok:!0,value:o?Mr(e):j(e,t)})}let l=e.get(`sessionQuery`),u=typeof l?.observeSession==`function`?l.observeSession.bind(l):void 0;return Nr(u===void 0?{ok:!0,value:null}:{ok:!0,value:await n.admit(async()=>{let n=await u(a,{projectionMode:`none`});try{let r=e.get(`sessionPersistence`),s=Ar(n);if(s!==void 0){let e=i.get(a);if(e!==void 0&&e.revision===s&&e.persistence===r)return i.delete(a),i.set(a,e),o?jr(e.value):e.value}let c=n?.events;if(!Array.isArray(c))return null;let l=ct(),u=0;for(let e of c)l=F(l,e,t),++u%1e3==0&&await new Promise(e=>setTimeout(e,0));if(s!==void 0){let e=j(l,t);i.delete(a),i.set(a,{persistence:r,revision:s,value:e});for(let e of i.keys()){if(i.size<=4)break;i.delete(e)}return o?jr(e):e}return o?Mr(l):j(l,t)}finally{let e=n?.[Symbol.dispose];typeof e==`function`&&e.call(n)}})??null})}catch(e){return Pr(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: detail route`))return r.live=!0,()=>{r.live=!1}}),r}const Ir=`0.2.0-rc.2`;function Lr(e){return e===`rc`?3:e===`beta`?2:1}function Rr(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:Lr(n),serial:t[5]?Number(t[5]):0}}function zr(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 Br(e,t=Ir){let n=Rr(e),r=Rr(t);return n===null||r===null||zr(n,r)>=0}const Vr=t.object({name:t.string(),tokens:t.number().int().nonnegative(),description:t.string().optional(),plugin:t.string().optional(),schema:t.unknown().optional()}).strict(),Hr=t.object({seq:t.number(),time:t.number(),system:t.string().optional(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array(Vr)}).strict(),Ur=t.object({headers:t.array(Hr)}).strict(),Wr=t.object({name:t.string(),tokens:t.number().int().nonnegative(),plugin:t.string().optional()}).strict(),Gr=t.object({headers:t.array(t.object({seq:t.number(),time:t.number(),systemTokens:t.number().int().nonnegative().optional(),tools:t.array(Wr)}).strict())}).strict();function Kr(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:ve(e)};return typeof t.plugin==`string`&&t.plugin!==``&&(n.plugin=t.plugin),n})}}function qr(e){return{key:`contextHeaders`,stateSchema:Ur,wire:{viewSchema:Gr,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!==``?te(t.system):void 0);return r!==void 0&&(n.systemTokens=r),n})})},init:()=>({headers:[]}),apply:(e,t)=>{let n=Kr(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 Jr=t.object({});function Yr(e,t,n){let r=()=>n;return{key:e,stateSchema:Jr,init:()=>({}),apply:e=>e,wire:{viewSchema:t,view:r},schema:t,view:r,stateVersion:1}}function Xr(e){return Yr(`contextTimeline`,rn,{ok:!0,unsupported:{current:e,minimum:Ir},current:{system:0,tools:0,user:0,inject:0,skill:0,assistant:0,tool:0,total:0},requests:[],events:[],nodes:[],droppedNodes:0,archive:[]})}function Zr(){return Yr(`contextHeaders`,Gr,{headers:[]})}function Qr(){return Yr(`contextActivity`,un,{days:{}})}const $r=1e5;function ei(e){return Z(e)?.full===!0}function ti(e){return Response.json(e,{headers:{"cache-control":`no-store`}})}function ni(e,t){return ti({ok:!1,error:{code:e,message:t}})}function Z(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function ri(e){if(!Array.isArray(e))return``;let t=``;for(let n of e){let e=Z(n)?.text;typeof e==`string`&&(t+=e)}return t}const ii=/^\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 ai(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`,`agentReasoningEffort`,`persona`]){let r=e[t];typeof r==`string`&&r!==``&&(n[t]=r)}return n}const oi=/^Team message \S+ from ([^:]{1,64}):\s*/,si=/^(?:Agent \S+ sent a message: |Team message from ([^:\n]{1,64}):\s*)/;function ci(e){let t=e[0];if(t!==`{`&&t!==`[`)return 0;let n=0,r=!1,i=!1;for(let t=0;t<e.length;t++){let a=e[t];if(r)i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1);else if(a===`"`)r=!0;else if(a===`{`||a===`[`)n++;else if((a===`}`||a===`]`)&&(n--,n===0))return t+1}return e.length}function li(e,t,n){let r=!1,i=e=>{let t=e.trim();if(t===``)return;let i=Q(t,n);return i.cut&&(r=!0),i.text},a=t.slice(e.length).trim(),o=a.indexOf(`Structured result: `),s=o>=0?a.slice(0,o).trim():a;s===`It left no closing message.`||s===`It sent you a message just before finishing, so its closing message is omitted.`?s=``:s.startsWith(`Its closing message:`)&&(s=s.slice(20).trim());let c,l;if(o>=0){let e=a.slice(o+19).trim(),t=ci(e);c=i(t>0?e.slice(0,t):e),t>0&&(l=i(e.slice(t)))}let u=Q(e,n);u.cut&&(r=!0);let d=i(s),f={summary:u.text,clipped:r};return d!==void 0&&(f.report=d),c!==void 0&&(f.structured=c),l!==void 0&&(f.diagnostic=l),f}function ui(e,t,n,r){let i=Z(n.source),a=i?.kind,o=null;if(a===`agent-message`||a===`team-message`){let r=ri(n.content),s=a===`team-message`?oi:si,c=s.exec(r),l=r.replace(s,``);if(l.trim()===``)return null;o={seq:e,time:t,kind:a===`agent-message`?`relay`:`mailbox`,text:l};let u=a===`agent-message`?i?.senderSessionId:i?.senderId;typeof u==`string`&&u!==``&&(o.from=u);let d=typeof i?.senderName==`string`&&i.senderName!==``?i.senderName:c?.[1];d!==void 0&&d!==``&&(o.fromName=d)}else if(a===`subagent-settled`){let a=typeof i?.summary==`string`?i.summary.trim():``,s=ri(n.content).trim(),c=a!==``&&!s.startsWith(a)||s===``?a:s;if(c.trim()===``)return null;o={seq:e,time:t,kind:`settled`,text:c};let l=i?.senderSessionId;if(typeof l==`string`&&l!==``&&(o.from=l),a!==``){let e=li(a,c,r);o.summary=e.summary,e.clipped&&(o.clipped=!0),e.report!==void 0&&(o.report=e.report),e.structured!==void 0&&(o.structured=e.structured),e.diagnostic!==void 0&&(o.diagnostic=e.diagnostic)}}if(o===null)return null;let s=Q(o.text,r);return o.text=s.text,s.cut&&(o.clipped=!0),o}function di(e){return e===null||e.kind===`user`}function fi(e){let t=Z(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 pi(e){return e?{promptMax:$r,replyMax:$r,messageMax:24e3,listMax:120}:{promptMax:1600,replyMax:300,messageMax:400,listMax:80}}var mi=class{caps;descriptor;initialPrompt;truncated=!1;total=0;messages=[];roster=new Map;lastReply=null;constructor(e){this.caps=e}apply(e){for(let t of e)this.applyEvent(t)}applyEvent(e){let t=Z(e);if(t===null)return;let n=t.type;if(typeof n!=`string`)return;let r=typeof t.seq==`number`&&Number.isFinite(t.seq)?t.seq:0,i=typeof t.time==`number`&&Number.isFinite(t.time)?t.time:0,a=Z(t.data);if(a===null)return;if(n===`subagent/descriptor`){let e=ai(a);e!==null&&(this.descriptor=e);return}if(n===`team/member`){let e=fi(a);e!==null&&this.roster.set(e.name,e);return}if(n===`assistant/message`){this.replyOf(r,i,a);return}if(n!==`user/message`)return;let o=ui(r,i,a,this.caps.messageMax);if(o!==null){this.total+=1,this.insert(o);return}if(this.initialPrompt!==void 0||!di(Z(a.source)))return;let s=ri(a.content).replace(ii,``);if(s.trim()===``)return;let c=Q(s,this.caps.promptMax);this.initialPrompt=c.text,c.cut&&(this.truncated=!0)}replyOf(e,t,n){let r=Z(n.message)?.content;if(!Array.isArray(r))return;let i=``;for(let e of r){let t=Z(e);t?.type===`text`&&typeof t.text==`string`&&(i+=t.text)}if(i.trim()===``)return;let a=Q(i,this.caps.replyMax);this.lastReply={time:t,text:a.text},a.cut&&(this.truncated=!0)}insert(e){let t=0;for(;t<this.messages.length&&this.messages[t].seq>=e.seq;)t++;this.messages.splice(t,0,e),this.messages.length>this.caps.listMax&&(this.messages.pop(),this.truncated=!0),e.clipped===!0&&(this.truncated=!0)}serve(){let e=this.messages.slice();return{...this.descriptor===void 0?{}:{descriptor:this.descriptor},...this.initialPrompt===void 0?{}:{initialPrompt:this.initialPrompt},...this.lastReply===null?{}:{lastReply:this.lastReply},...this.roster.size>0?{roster:[...this.roster.values()]}:{},messages:e,...this.total>e.length?{messagesTotal:this.total}:{},truncated:this.truncated}}};function hi(e,t=!1){let n=new mi(pi(t));return n.apply(e),n.serve()}function gi(e){let t=e?.revision;return typeof t==`string`&&t!==``?t:void 0}function _i(e,t,n,r,i,a){return t?!e.live||i.length<e.count?!1:e.count===0||i[e.count-1]?.seq===e.cursor:!e.live&&e.revision===n&&e.persistence===r&&e.cursor<=a}function vi(e,t,n,r,i,a,o){let s=e.get(t);if(s!==void 0&&_i(s,r,i,a,n,o)){let i=r?s.count:n.length;return i<n.length&&s.fold.apply(n.slice(i)),s.count=n.length,s.cursor=o,e.delete(t),e.set(t,s),s.fold}let c=new mi(pi(!1));if(c.apply(n),!r&&i===void 0)return c;e.set(t,{live:r,...i===void 0?{}:{revision:i},...a===void 0?{}:{persistence:a},cursor:o,count:n.length,fold:c});for(let t of e.keys()){if(e.size<=8)break;e.delete(t)}return c}function yi(e,t=W()){let n=new Map;e.inject([`connection`],r=>{G(r,r.get(`connection`),`/api/dsh-context/fleet`,async i=>{let a,o=!1;try{let e=await i.json();a=Z(e)?.sessionId,o=ei(e)}catch{return ni(`dsh-context/bad-request`,`body is not JSON`)}if(typeof a!=`string`||a===``)return ni(`dsh-context/bad-request`,`missing sessionId`);try{let i=e.get(`sessionQuery`),s=typeof i?.observeSession==`function`?i.observeSession.bind(i):void 0;if(s===void 0)return ti({ok:!0,value:null});let c=r.get(`sessionPersistence`);return ti({ok:!0,value:await t.admit(async()=>{let e=await s(a,{projectionMode:`none`}),t=e?.events;if(!Array.isArray(t))return null;try{if(o)return hi(t,!0);let r=e?.source===`live`;return vi(n,a,t,r,r?void 0:gi(e),c,bi(t)).serve()}finally{let t=e?.[Symbol.dispose];typeof t==`function`&&t.call(e)}})??null})}catch(e){return ni(`gateway/internal`,e instanceof Error?e.message:String(e))}},`dsh-context: fleet route`)})}function bi(e){for(let t=e.length-1;t>=0;t--){let n=e[t]?.seq;if(typeof n==`number`&&Number.isFinite(n))return n}return-1}function xi(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 Si(e){return()=>{let t=e();return t.trim().length===0?``:t}}const Ci=1e3;function wi(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`)-Ci,text:Si(xi(t.promptPrefix)),interpolate:!1}),n.section({name:`dsh-context:prompt-suffix`,order:n.getSectionOrder(`DEPLOYMENT_PERSONA_SUFFIX`)+Ci,text:Si(xi(t.promptSuffix)),interpolate:!1}))})}function Ti(e){if(typeof e!=`object`||!e)return!1;let t=e.id;return typeof t!=`string`||t===``}function Ei(e){let t;for(let[n,r]of e.entries())Ti(r)?(t??=e.slice(0,n),t.push({...r,id:`dshctx-`+ee()})):t?.push(r);return t}function Di(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=Ei(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 Oi(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 ki(e){let t=q(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 Ai(e,t){if(t===void 0)return{};let n=q(e.get(`sessionQuery`));if(typeof n?.observeSession!=`function`)return{};let r;try{r=await n.observeSession.call(n,t)}catch{return{}}try{let e=q(r),t=$(q(e?.header)?.cwd),n=$(q(q(e?.projections)?.values)?.agentPreset);return{...t===void 0?{}:{cwd:t},...n===void 0?{}:{agentPreset:n}}}finally{await Oi(r)}}async function ji(e,t,n){let r=q(e.get(`agentPresets`)),i;if(t!==void 0){let n=q(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=q(r.serviceFor.call(r,i,`skills`));if(e!==null&&typeof e.list==`function`)return{registry:e,scope:i,lease:void 0}}let a=q(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=q(s)?.key}catch{s=void 0}return{registry:a,scope:o,lease:s}}function Mi(e){e.inject([`connection`],t=>{G(t,t.get(`connection`),`/api/dsh-context/skills`,async t=>{let n=null,r;try{let i=q(await t.json()),a=$(i?.sessionId),o=await Ai(e,a),s=o.cwd??$(i?.cwd),c=await ji(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=ki(e);if(t!==null&&i.push(t),i.length>=500)break}n={skills:i}}}catch{}finally{await Oi(r)}return Response.json({ok:!0,value:n},{headers:{"cache-control":`no-store`}})},`dsh-context: skills route`)})}const Ni=[`@deepseek-ai/dsh-session-projection`,`@deepseek-ai/dsh-session`],Pi=[`@deepseek-ai/dsh-session`,`@deepseek-ai/dsh-session-projection`],Fi=[`@deepseek-ai/dsh`,...Ni];function Ii(){try{return l(_(import.meta.resolve(`dsh-context/package.json`)))}catch{return l(_(import.meta.url))}}const Li=Ii();function Ri(e,t){try{let n=JSON.parse(g(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 zi(e,t){try{return Ri(e(t+`/package.json`))}catch{return}}function Bi(e,t){let n;try{n=l(e(t))}catch{return}for(;;){let e=Ri(d(n,`package.json`),t);if(e!==void 0)return e;let r=l(n);if(r===n)return;n=r}}function Vi(e,t){for(let n of t){let t=zi(e,n)??Bi(e,n);if(t!==void 0)return t}}function Hi(e,t){let n=p(e,t);return!n.startsWith(`..`)&&!u(n)}function Ui(e,t){for(let n of Pi){let r;try{r=e(n)}catch{continue}if(Hi(t,r))continue;let i=zi(e,n)??Bi(e,n);if(i!==void 0)return i}}function Wi(e){return import.meta.resolve(e)}function Gi(t,n=Wi,r=Li){let i=Ui(e=>{let t=n(e);if(!t.startsWith(`file:`))throw Error(`dsh-context: non-file module URL for ${e}`);return _(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=Vi(e=>t.resolve(e),Fi);if(r!==void 0)return r}}catch{}}const Ki=`dsh-context`,qi=[`sessionProjections`];function Ji(e,t){let n=W();fr(e),Mi(e),yi(e,n),Hn(e,n);let r=Gi(e);if(r!==void 0&&!Br(r)){e.sessionProjections.register(Xr(r)),e.sessionProjections.register(Zr()),e.sessionProjections.register(Qr());return}let i=tr(e);Di(e);let a=Fr(e,z(t),n);kr(e,z(t),n),e.sessionProjections.register(on(t,()=>a.live)),e.sessionProjections.register(qr(e=>i.ownerOf(e))),e.sessionProjections.register(Sn()),Sr(e,n),wi(e,t)}export{zt as Config,Ji as apply,qi as inject,Ki as name};