dsh-context 0.11.2 → 0.12.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.js CHANGED
@@ -4,7 +4,8 @@ var DEFAULT_BOUNDS = {
4
4
  maxRequestSteps: 1500,
5
5
  maxKeptTurns: 300,
6
6
  maxEvents: 400,
7
- maxNodes: 200
7
+ maxNodes: 2e3,
8
+ maxArchiveNodes: 400
8
9
  };
9
10
  var Config = z.preprocess(
10
11
  (v) => v ?? {},
@@ -12,7 +13,8 @@ var Config = z.preprocess(
12
13
  maxRequestSteps: z.number().int().min(1).default(DEFAULT_BOUNDS.maxRequestSteps),
13
14
  maxKeptTurns: z.number().int().min(1).default(DEFAULT_BOUNDS.maxKeptTurns),
14
15
  maxEvents: z.number().int().min(1).default(DEFAULT_BOUNDS.maxEvents),
15
- maxNodes: z.number().int().min(1).default(DEFAULT_BOUNDS.maxNodes)
16
+ maxNodes: z.number().int().min(1).default(DEFAULT_BOUNDS.maxNodes),
17
+ maxArchiveNodes: z.number().int().min(1).default(DEFAULT_BOUNDS.maxArchiveNodes)
16
18
  }).strict()
17
19
  );
18
20
  function resolveBounds(config) {
@@ -21,11 +23,12 @@ function resolveBounds(config) {
21
23
  maxRequestSteps: parsed.maxRequestSteps,
22
24
  maxKeptTurns: parsed.maxKeptTurns,
23
25
  maxEvents: parsed.maxEvents,
24
- maxNodes: parsed.maxNodes
26
+ maxNodes: parsed.maxNodes,
27
+ maxArchiveNodes: parsed.maxArchiveNodes
25
28
  };
26
29
  }
27
30
 
28
- // src/host/timeline.ts
31
+ // src/host/headers.ts
29
32
  import { z as z2 } from "zod";
30
33
 
31
34
  // src/host/pricing.ts
@@ -91,6 +94,914 @@ function isInjection(source) {
91
94
  return source !== null && typeof source === "object" && (source.kind === "plugin" || source.kind === "skill-invocation" || typeof source.form === "string");
92
95
  }
93
96
 
97
+ // src/host/headers.ts
98
+ var HEADERS_MAX = 50;
99
+ var headerToolSchema = z2.object({
100
+ name: z2.string(),
101
+ tokens: z2.number().int().nonnegative(),
102
+ description: z2.string().optional(),
103
+ schema: z2.unknown().optional()
104
+ }).strict();
105
+ var contextHeadersSchema = z2.object({
106
+ headers: z2.array(z2.object({
107
+ seq: z2.number(),
108
+ time: z2.number(),
109
+ system: z2.string().optional(),
110
+ tools: z2.array(headerToolSchema)
111
+ }).strict())
112
+ }).strict();
113
+ function recordOf(event) {
114
+ if (event.type !== "request/header") return null;
115
+ const header = event.data.header;
116
+ if (header === null || typeof header !== "object") return null;
117
+ const tools = Array.isArray(header.tools) ? header.tools : [];
118
+ const record = {
119
+ seq: event.seq,
120
+ time: event.time,
121
+ tools: tools.map((t) => {
122
+ const tool = t;
123
+ const entry = {
124
+ name: typeof tool.name === "string" ? tool.name : "?",
125
+ tokens: estimateToolSchema(t),
126
+ schema: t
127
+ };
128
+ if (typeof tool.description === "string" && tool.description !== "") {
129
+ entry.description = tool.description;
130
+ }
131
+ return entry;
132
+ })
133
+ };
134
+ if (typeof header.system === "string" && header.system.length > 0) {
135
+ record.system = header.system;
136
+ }
137
+ return record;
138
+ }
139
+ function createContextHeadersDefinition() {
140
+ return {
141
+ key: "contextHeaders",
142
+ schema: contextHeadersSchema,
143
+ init: () => ({ headers: [] }),
144
+ apply: (state, event) => {
145
+ const record = recordOf(event);
146
+ if (record === null) return state;
147
+ const last = state.headers[state.headers.length - 1];
148
+ if (last !== void 0 && last.seq === record.seq) return state;
149
+ const headers = [...state.headers, record];
150
+ return { headers: headers.length > HEADERS_MAX ? headers.slice(-HEADERS_MAX) : headers };
151
+ },
152
+ view: (state) => ({
153
+ headers: state.headers.map((h) => ({ ...h, tools: h.tools.map((t) => ({ ...t })) }))
154
+ }),
155
+ stateVersion: 1
156
+ };
157
+ }
158
+
159
+ // src/host/timeline.ts
160
+ import { z as z3 } from "zod";
161
+
162
+ // node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.2/node_modules/@deepseek-ai/cosmokit/lib/index.js
163
+ function isNullable(value) {
164
+ return value === null || value === void 0;
165
+ }
166
+ function isPlainObject(data) {
167
+ return data && typeof data === "object" && !Array.isArray(data);
168
+ }
169
+ function filterKeys(object, filter) {
170
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
171
+ }
172
+ function mapValues(object, transform) {
173
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
174
+ }
175
+ function pick(source, keys, forced) {
176
+ if (!keys) return { ...source };
177
+ const result = {};
178
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
179
+ return result;
180
+ }
181
+ function is(type, value) {
182
+ if (arguments.length === 1) return (value2) => is(type, value2);
183
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
184
+ }
185
+ function isArrayBufferLike(value) {
186
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
187
+ }
188
+ function isArrayBufferSource(value) {
189
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
190
+ }
191
+ var Binary;
192
+ (function(Binary2) {
193
+ Binary2.is = isArrayBufferLike;
194
+ Binary2.isSource = isArrayBufferSource;
195
+ function fromSource(source) {
196
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
197
+ else return source;
198
+ }
199
+ Binary2.fromSource = fromSource;
200
+ function toBase64(source) {
201
+ source = fromSource(source);
202
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
203
+ let binary = "";
204
+ const bytes = new Uint8Array(source);
205
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
206
+ return btoa(binary);
207
+ }
208
+ Binary2.toBase64 = toBase64;
209
+ function fromBase64(source) {
210
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
211
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
212
+ }
213
+ Binary2.fromBase64 = fromBase64;
214
+ function toHex(source) {
215
+ source = fromSource(source);
216
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
217
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
218
+ }
219
+ Binary2.toHex = toHex;
220
+ function fromHex(source) {
221
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
222
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
223
+ const buffer = [];
224
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
225
+ return Uint8Array.from(buffer).buffer;
226
+ }
227
+ Binary2.fromHex = fromHex;
228
+ })(Binary || (Binary = {}));
229
+ var base64ToArrayBuffer = Binary.fromBase64;
230
+ var arrayBufferToBase64 = Binary.toBase64;
231
+ var hexToArrayBuffer = Binary.fromHex;
232
+ var arrayBufferToHex = Binary.toHex;
233
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
234
+ if (!source || typeof source !== "object") return source;
235
+ if (is("Date", source)) return new Date(source.valueOf());
236
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
237
+ if (isArrayBufferLike(source)) return source.slice(0);
238
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
239
+ const cached = refs.get(source);
240
+ if (cached) return cached;
241
+ if (Array.isArray(source)) {
242
+ const result2 = [];
243
+ refs.set(source, result2);
244
+ source.forEach((value, index) => {
245
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
246
+ });
247
+ return result2;
248
+ }
249
+ const result = Object.create(Object.getPrototypeOf(source));
250
+ refs.set(source, result);
251
+ for (const key of Reflect.ownKeys(source)) {
252
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
253
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
254
+ Reflect.defineProperty(result, key, descriptor);
255
+ }
256
+ return result;
257
+ }
258
+ function deepEqual(a, b, strict) {
259
+ if (a === b) return true;
260
+ if (!strict && isNullable(a) && isNullable(b)) return true;
261
+ if (typeof a !== typeof b) return false;
262
+ if (typeof a !== "object") return false;
263
+ if (!a || !b) return false;
264
+ function check(test, then) {
265
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
266
+ }
267
+ return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
268
+ if (a2.byteLength !== b2.byteLength) return false;
269
+ const viewA = new Uint8Array(a2);
270
+ const viewB = new Uint8Array(b2);
271
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
272
+ return true;
273
+ }) ?? Object.keys({
274
+ ...a,
275
+ ...b
276
+ }).every((key) => deepEqual(a[key], b[key], strict));
277
+ }
278
+ var Time;
279
+ (function(Time2) {
280
+ Time2.millisecond = 1;
281
+ Time2.second = 1e3;
282
+ Time2.minute = Time2.second * 60;
283
+ Time2.hour = Time2.minute * 60;
284
+ Time2.day = Time2.hour * 24;
285
+ Time2.week = Time2.day * 7;
286
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
287
+ function setTimezoneOffset(offset) {
288
+ timezoneOffset = offset;
289
+ }
290
+ Time2.setTimezoneOffset = setTimezoneOffset;
291
+ function getTimezoneOffset() {
292
+ return timezoneOffset;
293
+ }
294
+ Time2.getTimezoneOffset = getTimezoneOffset;
295
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
296
+ if (typeof date2 === "number") date2 = new Date(date2);
297
+ if (offset === void 0) offset = timezoneOffset;
298
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
299
+ }
300
+ Time2.getDateNumber = getDateNumber;
301
+ function fromDateNumber(value, offset) {
302
+ const date2 = new Date(value * Time2.day);
303
+ if (offset === void 0) offset = timezoneOffset;
304
+ return new Date(+date2 + offset * Time2.minute);
305
+ }
306
+ Time2.fromDateNumber = fromDateNumber;
307
+ const numeric = /\d+(?:\.\d+)?/.source;
308
+ const timeRegExp = new RegExp(`^${[
309
+ "w(?:eek(?:s)?)?",
310
+ "d(?:ay(?:s)?)?",
311
+ "h(?:our(?:s)?)?",
312
+ "m(?:in(?:ute)?(?:s)?)?",
313
+ "s(?:ec(?:ond)?(?:s)?)?"
314
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
315
+ function parseTime(source) {
316
+ const capture = timeRegExp.exec(source);
317
+ if (!capture) return 0;
318
+ return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
319
+ }
320
+ Time2.parseTime = parseTime;
321
+ function parseDate(date2) {
322
+ const parsed = parseTime(date2);
323
+ if (parsed) date2 = Date.now() + parsed;
324
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
325
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
326
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
327
+ }
328
+ Time2.parseDate = parseDate;
329
+ function format(ms) {
330
+ const abs = Math.abs(ms);
331
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
332
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
333
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
334
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
335
+ return ms + "ms";
336
+ }
337
+ Time2.format = format;
338
+ function toDigits(source, length = 2) {
339
+ return source.toString().padStart(length, "0");
340
+ }
341
+ Time2.toDigits = toDigits;
342
+ function template(template2, time = /* @__PURE__ */ new Date()) {
343
+ return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
344
+ }
345
+ Time2.template = template;
346
+ })(Time || (Time = {}));
347
+
348
+ // node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-attachment@0_4ed4e5c71eb965b0bd6912871e829940/node_modules/@deepseek-ai/dsh-llm/lib/index.js
349
+ import { createRequire } from "node:module";
350
+
351
+ // node_modules/.pnpm/@deepseek-ai+schemastery@3.18.1/node_modules/@deepseek-ai/schemastery/lib/index.mjs
352
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
353
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
354
+ globalThis.__schemastery_index__ ??= 0;
355
+ globalThis.__schemastery_refs__ = void 0;
356
+ var ValidationError = class extends TypeError {
357
+ options;
358
+ name = "ValidationError";
359
+ constructor(message, options) {
360
+ let prefix = "$";
361
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
362
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
363
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
364
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
365
+ super((prefix === "$" ? "" : `${prefix} `) + message);
366
+ this.options = options;
367
+ }
368
+ static is(error) {
369
+ return !!error?.[kValidationError];
370
+ }
371
+ };
372
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
373
+ var Schema = function(options) {
374
+ const schema = function(data, options2 = {}) {
375
+ return Schema.resolve(data, schema, options2)[0];
376
+ };
377
+ if (options.refs) {
378
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
379
+ const getRef = (uid) => refs[uid];
380
+ for (const key in refs) {
381
+ const options2 = refs[key];
382
+ options2.sKey = getRef(options2.sKey);
383
+ options2.inner = getRef(options2.inner);
384
+ options2.list = options2.list && options2.list.map(getRef);
385
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
386
+ }
387
+ return refs[options.uid];
388
+ }
389
+ Object.assign(schema, options);
390
+ if (typeof schema.callback === "string") try {
391
+ schema.callback = new Function("return " + schema.callback)();
392
+ } catch {
393
+ }
394
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
395
+ Object.setPrototypeOf(schema, Schema.prototype);
396
+ schema.meta ||= {};
397
+ schema.toString = schema.toString.bind(schema);
398
+ return schema;
399
+ };
400
+ Schema.prototype = Object.create(Function.prototype);
401
+ Schema.prototype[kSchema] = true;
402
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
403
+ return {
404
+ version: 1,
405
+ vendor: "schemastery",
406
+ validate: (value) => {
407
+ try {
408
+ return { value: Schema.resolve(value, this, {})[0] };
409
+ } catch (error) {
410
+ if (ValidationError.is(error)) return { issues: [{
411
+ message: error.message,
412
+ path: error.options.path
413
+ }] };
414
+ throw error;
415
+ }
416
+ }
417
+ };
418
+ } });
419
+ Schema.ValidationError = ValidationError;
420
+ Schema.prototype.toJSON = function toJSON() {
421
+ if (globalThis.__schemastery_refs__) {
422
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
423
+ return this.uid;
424
+ }
425
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
426
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
427
+ const result = {
428
+ uid: this.uid,
429
+ refs: globalThis.__schemastery_refs__
430
+ };
431
+ globalThis.__schemastery_refs__ = void 0;
432
+ return result;
433
+ };
434
+ Schema.prototype.set = function set(key, value) {
435
+ this.dict[key] = value;
436
+ return this;
437
+ };
438
+ Schema.prototype.push = function push(value) {
439
+ this.list.push(value);
440
+ return this;
441
+ };
442
+ function mergeDesc(original, messages) {
443
+ const result = typeof original === "string" ? { "": original } : { ...original };
444
+ for (const locale in messages) {
445
+ const value = messages[locale];
446
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
447
+ else if (typeof value === "string") result[locale] = value;
448
+ }
449
+ return result;
450
+ }
451
+ function getInner(value) {
452
+ return value?.$value ?? value?.$inner;
453
+ }
454
+ function extractKeys(data) {
455
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
456
+ }
457
+ Schema.prototype.i18n = function i18n(messages) {
458
+ const schema = Schema(this);
459
+ const desc = mergeDesc(schema.meta.description, messages);
460
+ if (Object.keys(desc).length) schema.meta.description = desc;
461
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
462
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
463
+ });
464
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
465
+ return inner.i18n(mapValues(messages, (data = {}) => {
466
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
467
+ if (Array.isArray(data)) return data[index];
468
+ return extractKeys(data);
469
+ }));
470
+ });
471
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
472
+ if (getInner(data)) return getInner(data);
473
+ return extractKeys(data);
474
+ }));
475
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
476
+ return schema;
477
+ };
478
+ Schema.prototype.extra = function extra(key, value) {
479
+ const schema = Schema(this);
480
+ schema.meta = {
481
+ ...schema.meta,
482
+ [key]: value
483
+ };
484
+ return schema;
485
+ };
486
+ for (const key of [
487
+ "required",
488
+ "disabled",
489
+ "collapse",
490
+ "hidden",
491
+ "loose"
492
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
493
+ const schema = Schema(this);
494
+ schema.meta = {
495
+ ...schema.meta,
496
+ [key]: value
497
+ };
498
+ return schema;
499
+ } });
500
+ Schema.prototype.deprecated = function deprecated() {
501
+ const schema = Schema(this);
502
+ schema.meta.badges ||= [];
503
+ schema.meta.badges.push({
504
+ text: "deprecated",
505
+ type: "danger"
506
+ });
507
+ return schema;
508
+ };
509
+ Schema.prototype.experimental = function experimental() {
510
+ const schema = Schema(this);
511
+ schema.meta.badges ||= [];
512
+ schema.meta.badges.push({
513
+ text: "experimental",
514
+ type: "warning"
515
+ });
516
+ return schema;
517
+ };
518
+ Schema.prototype.pattern = function pattern(regexp) {
519
+ const schema = Schema(this);
520
+ const pattern2 = pick(regexp, ["source", "flags"]);
521
+ schema.meta = {
522
+ ...schema.meta,
523
+ pattern: pattern2
524
+ };
525
+ return schema;
526
+ };
527
+ Schema.prototype.simplify = function simplify(value) {
528
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
529
+ if (isNullable(value)) return value;
530
+ if (this.type === "object" || this.type === "dict") {
531
+ const result = {};
532
+ for (const key in value) {
533
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
534
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
535
+ }
536
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
537
+ return result;
538
+ } else if (this.type === "array" || this.type === "tuple") {
539
+ const result = [];
540
+ value.forEach((value2, index) => {
541
+ const schema = this.type === "array" ? this.inner : this.list[index];
542
+ const item = schema ? schema.simplify(value2) : value2;
543
+ result.push(item);
544
+ });
545
+ return result;
546
+ } else if (this.type === "intersect") {
547
+ const result = {};
548
+ for (const item of this.list) Object.assign(result, item.simplify(value));
549
+ return result;
550
+ } else if (this.type === "union") for (const schema of this.list) try {
551
+ Schema.resolve(value, schema, {});
552
+ return schema.simplify(value);
553
+ } catch {
554
+ }
555
+ return value;
556
+ };
557
+ Schema.prototype.toString = function toString(inline) {
558
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
559
+ };
560
+ Schema.prototype.role = function role(role, extra2) {
561
+ const schema = Schema(this);
562
+ schema.meta = {
563
+ ...schema.meta,
564
+ role,
565
+ extra: extra2
566
+ };
567
+ return schema;
568
+ };
569
+ for (const key of [
570
+ "default",
571
+ "link",
572
+ "comment",
573
+ "description",
574
+ "max",
575
+ "min",
576
+ "step"
577
+ ]) Object.assign(Schema.prototype, { [key](value) {
578
+ const schema = Schema(this);
579
+ schema.meta = {
580
+ ...schema.meta,
581
+ [key]: value
582
+ };
583
+ return schema;
584
+ } });
585
+ var resolvers = {};
586
+ Schema.extend = function extend(type, resolve2) {
587
+ resolvers[type] = resolve2;
588
+ };
589
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
590
+ if (!schema) return [data];
591
+ if (options.ignore?.(data, schema)) return [data];
592
+ if (isNullable(data) && schema.type !== "lazy") {
593
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
594
+ let current = schema;
595
+ let fallback = schema.meta.default;
596
+ while (current?.type === "intersect" && isNullable(fallback)) {
597
+ current = current.list[0];
598
+ fallback = current?.meta.default;
599
+ }
600
+ if (isNullable(fallback)) return [data];
601
+ data = clone(fallback);
602
+ }
603
+ const callback = resolvers[schema.type];
604
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
605
+ try {
606
+ return callback(data, schema, options, strict);
607
+ } catch (error) {
608
+ if (!schema.meta.loose) throw error;
609
+ return [schema.meta.default];
610
+ }
611
+ };
612
+ Schema.from = function from(source) {
613
+ if (isNullable(source)) return Schema.any();
614
+ else if ([
615
+ "string",
616
+ "number",
617
+ "boolean"
618
+ ].includes(typeof source)) return Schema.const(source).required();
619
+ else if (source[kSchema]) return source;
620
+ else if (typeof source === "function") switch (source) {
621
+ case String:
622
+ return Schema.string().required();
623
+ case Number:
624
+ return Schema.number().required();
625
+ case Boolean:
626
+ return Schema.boolean().required();
627
+ case Function:
628
+ return Schema.function().required();
629
+ default:
630
+ return Schema.is(source).required();
631
+ }
632
+ else throw new TypeError(`cannot infer schema from ${source}`);
633
+ };
634
+ Schema.lazy = function lazy(builder) {
635
+ const toJSON2 = () => {
636
+ if (!schema.inner[kSchema]) {
637
+ schema.inner = schema.builder();
638
+ schema.inner.meta = {
639
+ ...schema.meta,
640
+ ...schema.inner.meta
641
+ };
642
+ }
643
+ return schema.inner.toJSON();
644
+ };
645
+ const schema = new Schema({
646
+ type: "lazy",
647
+ builder,
648
+ inner: { toJSON: toJSON2 }
649
+ });
650
+ return schema;
651
+ };
652
+ Schema.natural = function natural() {
653
+ return Schema.number().step(1).min(0);
654
+ };
655
+ Schema.percent = function percent() {
656
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
657
+ };
658
+ Schema.date = function date() {
659
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
660
+ const date2 = new Date(value);
661
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
662
+ return date2;
663
+ }, true)]);
664
+ };
665
+ Schema.regExp = function regExp(flag = "") {
666
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
667
+ try {
668
+ return new RegExp(value, flag);
669
+ } catch (e) {
670
+ throw new ValidationError(e.message, options);
671
+ }
672
+ }, true)]);
673
+ };
674
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
675
+ return Schema.union([
676
+ Schema.is(ArrayBuffer),
677
+ Schema.is(SharedArrayBuffer),
678
+ Schema.transform(Schema.any(), (value, options) => {
679
+ if (Binary.isSource(value)) return Binary.fromSource(value);
680
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
681
+ }, true),
682
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
683
+ try {
684
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
685
+ } catch (e) {
686
+ throw new ValidationError(e.message, options);
687
+ }
688
+ }, true)] : []
689
+ ]);
690
+ };
691
+ Schema.extend("lazy", (data, schema, options, strict) => {
692
+ if (!schema.inner[kSchema]) {
693
+ schema.inner = schema.builder();
694
+ schema.inner.meta = {
695
+ ...schema.meta,
696
+ ...schema.inner.meta
697
+ };
698
+ }
699
+ return Schema.resolve(data, schema.inner, options, strict);
700
+ });
701
+ Schema.extend("any", (data) => {
702
+ return [data];
703
+ });
704
+ Schema.extend("never", (data, _, options) => {
705
+ throw new ValidationError(`expected nullable but got ${data}`, options);
706
+ });
707
+ Schema.extend("const", (data, { value }, options) => {
708
+ if (deepEqual(data, value)) return [value];
709
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
710
+ });
711
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
712
+ const { max = Infinity, min = -Infinity } = meta;
713
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
714
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
715
+ }
716
+ Schema.extend("string", (data, { meta }, options) => {
717
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
718
+ if (meta.pattern) {
719
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
720
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
721
+ }
722
+ checkWithinRange(data.length, meta, "string length", options);
723
+ return [data];
724
+ });
725
+ function decimalShift(data, digits) {
726
+ const str = data.toString();
727
+ if (str.includes("e")) return data * Math.pow(10, digits);
728
+ const index = str.indexOf(".");
729
+ if (index === -1) return data * Math.pow(10, digits);
730
+ const frac = str.slice(index + 1);
731
+ const integer = str.slice(0, index);
732
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
733
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
734
+ }
735
+ function isMultipleOf(data, min, step) {
736
+ step = Math.abs(step);
737
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
738
+ const index = step.toString().indexOf(".");
739
+ const digits = step.toString().slice(index + 1).length;
740
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
741
+ }
742
+ Schema.extend("number", (data, { meta }, options) => {
743
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
744
+ checkWithinRange(data, meta, "number", options);
745
+ const { step } = meta;
746
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
747
+ return [data];
748
+ });
749
+ Schema.extend("boolean", (data, _, options) => {
750
+ if (typeof data === "boolean") return [data];
751
+ throw new ValidationError(`expected boolean but got ${data}`, options);
752
+ });
753
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
754
+ let value = 0, keys = [];
755
+ if (typeof data === "number") {
756
+ value = data;
757
+ for (const key in bits) if (data & bits[key]) keys.push(key);
758
+ } else if (Array.isArray(data)) {
759
+ keys = data;
760
+ for (const key of keys) {
761
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
762
+ if (key in bits) value |= bits[key];
763
+ }
764
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
765
+ if (value === meta.default) return [value];
766
+ return [value, keys];
767
+ });
768
+ Schema.extend("function", (data, _, options) => {
769
+ if (typeof data === "function") return [data];
770
+ throw new ValidationError(`expected function but got ${data}`, options);
771
+ });
772
+ Schema.extend("is", (data, { constructor }, options) => {
773
+ if (typeof constructor === "function") {
774
+ if (data instanceof constructor) return [data];
775
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
776
+ } else {
777
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
778
+ let prototype = Object.getPrototypeOf(data);
779
+ while (prototype) {
780
+ if (prototype.constructor?.name === constructor) return [data];
781
+ prototype = Object.getPrototypeOf(prototype);
782
+ }
783
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
784
+ }
785
+ });
786
+ function property(data, key, schema, options) {
787
+ try {
788
+ const [value, adapted] = Schema.resolve(data[key], schema, {
789
+ ...options,
790
+ path: [...options.path || [], key]
791
+ });
792
+ if (adapted !== void 0) data[key] = adapted;
793
+ return value;
794
+ } catch (e) {
795
+ if (!options?.autofix) throw e;
796
+ delete data[key];
797
+ return schema.meta.default;
798
+ }
799
+ }
800
+ Schema.extend("array", (data, { inner, meta }, options) => {
801
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
802
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
803
+ return [data.map((_, index) => property(data, index, inner, options))];
804
+ });
805
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
806
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
807
+ const result = {};
808
+ for (const key in data) {
809
+ let rKey;
810
+ try {
811
+ rKey = Schema.resolve(key, sKey, options)[0];
812
+ } catch (error) {
813
+ if (strict) continue;
814
+ throw error;
815
+ }
816
+ result[rKey] = property(data, key, inner, options);
817
+ data[rKey] = data[key];
818
+ if (key !== rKey) delete data[key];
819
+ }
820
+ return [result];
821
+ });
822
+ Schema.extend("tuple", (data, { list }, options, strict) => {
823
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
824
+ const result = list.map((inner, index) => property(data, index, inner, options));
825
+ if (strict) return [result];
826
+ result.push(...data.slice(list.length));
827
+ return [result];
828
+ });
829
+ function merge(result, data) {
830
+ for (const key in data) {
831
+ if (key in result) continue;
832
+ result[key] = data[key];
833
+ }
834
+ }
835
+ Schema.extend("object", (data, { dict }, options, strict) => {
836
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
837
+ const result = {};
838
+ for (const key in dict) {
839
+ const value = property(data, key, dict[key], options);
840
+ if (!isNullable(value) || key in data) result[key] = value;
841
+ }
842
+ if (!strict) merge(result, data);
843
+ return [result];
844
+ });
845
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
846
+ const messages = [];
847
+ for (const inner of list) try {
848
+ return Schema.resolve(data, inner, options, strict);
849
+ } catch (error) {
850
+ messages.push(error);
851
+ }
852
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
853
+ });
854
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
855
+ if (!list.length) return [data];
856
+ let result;
857
+ for (const inner of list) {
858
+ const value = Schema.resolve(data, inner, options, true)[0];
859
+ if (isNullable(value)) continue;
860
+ if (isNullable(result)) result = value;
861
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
862
+ else if (typeof value === "object") merge(result ??= {}, value);
863
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
864
+ }
865
+ if (!strict && isPlainObject(data)) merge(result, data);
866
+ return [result];
867
+ });
868
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
869
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
870
+ if (preserve) return [callback(result)];
871
+ else return [callback(result), callback(adapted)];
872
+ });
873
+ var formatters = {};
874
+ function defineMethod(name2, keys, format) {
875
+ formatters[name2] = format;
876
+ Object.assign(Schema, { [name2](...args) {
877
+ const schema = new Schema({ type: name2 });
878
+ keys.forEach((key, index) => {
879
+ switch (key) {
880
+ case "sKey":
881
+ schema.sKey = args[index] ?? Schema.string();
882
+ break;
883
+ case "inner":
884
+ schema.inner = Schema.from(args[index]);
885
+ break;
886
+ case "list":
887
+ schema.list = args[index].map(Schema.from);
888
+ break;
889
+ case "dict":
890
+ schema.dict = mapValues(args[index], Schema.from);
891
+ break;
892
+ case "bits":
893
+ schema.bits = {};
894
+ for (const key2 in args[index]) {
895
+ if (typeof args[index][key2] !== "number") continue;
896
+ schema.bits[key2] = args[index][key2];
897
+ }
898
+ break;
899
+ case "callback": {
900
+ const callback = schema.callback = args[index];
901
+ callback["toJSON"] ||= () => callback.toString();
902
+ break;
903
+ }
904
+ case "constructor": {
905
+ const constructor = schema.constructor = args[index];
906
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
907
+ break;
908
+ }
909
+ default:
910
+ schema[key] = args[index];
911
+ }
912
+ });
913
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
914
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
915
+ else if (name2 === "bitset") schema.meta.default = 0;
916
+ return schema;
917
+ } });
918
+ }
919
+ defineMethod("is", ["constructor"], ({ constructor }) => {
920
+ if (typeof constructor === "function") return constructor.name;
921
+ else return constructor;
922
+ });
923
+ defineMethod("any", [], () => "any");
924
+ defineMethod("never", [], () => "never");
925
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
926
+ defineMethod("string", [], () => "string");
927
+ defineMethod("number", [], () => "number");
928
+ defineMethod("boolean", [], () => "boolean");
929
+ defineMethod("bitset", ["bits"], () => "bitset");
930
+ defineMethod("function", [], () => "function");
931
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
932
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
933
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
934
+ defineMethod("object", ["dict"], ({ dict }) => {
935
+ if (Object.keys(dict).length === 0) return "{}";
936
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
937
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
938
+ }).join(", ")} }`;
939
+ });
940
+ defineMethod("union", ["list"], ({ list }, inline) => {
941
+ const result = list.map(({ toString: format }) => format()).join(" | ");
942
+ return inline ? `(${result})` : result;
943
+ });
944
+ defineMethod("intersect", ["list"], ({ list }) => {
945
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
946
+ });
947
+ defineMethod("transform", [
948
+ "inner",
949
+ "callback",
950
+ "preserve"
951
+ ], ({ inner }, isInner) => inner.toString(isInner));
952
+
953
+ // node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-invarian_8c173ab999b05cf1db05d479dd44e888/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
954
+ var MAX_TIMER_DELAY_MS = 2147483647;
955
+
956
+ // node_modules/.pnpm/@deepseek-ai+dsh-llm@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-attachment@0_4ed4e5c71eb965b0bd6912871e829940/node_modules/@deepseek-ai/dsh-llm/lib/index.js
957
+ var EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
958
+ var STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`, "i");
959
+ var TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
960
+ var EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
961
+ var DEFAULT_MAX_RETRIES = 2;
962
+ var DEFAULT_INITIAL_DELAY_MS = 500;
963
+ var DEFAULT_MAX_DELAY_MS = 1e4;
964
+ var DEFAULT_JITTER_RATIO = 0.1;
965
+ var DEFAULT_RETRYABLE_CODES = Object.freeze([
966
+ EMPTY_RESPONSE_CODE,
967
+ "RATE_LIMIT",
968
+ "SERVER",
969
+ "TIMEOUT",
970
+ "TRANSPORT"
971
+ ]);
972
+ var backoffSchema = Schema.object({
973
+ initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
974
+ maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
975
+ jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
976
+ });
977
+ var normalPolicySchema = Schema.object({
978
+ mode: Schema.const("normal").required(),
979
+ maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
980
+ retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
981
+ backoff: backoffSchema
982
+ });
983
+ var alwaysPolicySchema = Schema.object({
984
+ mode: Schema.const("always").required(),
985
+ backoff: backoffSchema
986
+ });
987
+ var RetryPolicySchema = Schema.union([normalPolicySchema, alwaysPolicySchema]);
988
+ var { version } = createRequire(import.meta.url)("../package.json");
989
+
990
+ // node_modules/.pnpm/@deepseek-ai+dsh-session@0.1.0-rc.7_6fd26f59436a18b115f326d6060415e6/node_modules/@deepseek-ai/dsh-session/lib/index.js
991
+ function deriveEventMessage(event) {
992
+ switch (event.type) {
993
+ case "user/message":
994
+ return event.data;
995
+ case "assistant/message":
996
+ if (event.data.message.content.length === 0) return null;
997
+ return event.data.message;
998
+ case "tool/result":
999
+ return event.data.message;
1000
+ default:
1001
+ return null;
1002
+ }
1003
+ }
1004
+
94
1005
  // src/host/fold.ts
95
1006
  function trimToLastTurns(requests, maxTurns) {
96
1007
  let runs = 0;
@@ -126,6 +1037,21 @@ function trimState(st, bounds) {
126
1037
  st.requests = st.requests.slice(-bounds.maxRequestSteps);
127
1038
  }
128
1039
  if (st.events.length > bounds.maxEvents) st.events = st.events.slice(-bounds.maxEvents);
1040
+ if (st.archived.length > 0) {
1041
+ let drop = 0;
1042
+ const oldestReq = st.requests.length > 0 ? st.requests[0].seq : void 0;
1043
+ if (oldestReq !== void 0) {
1044
+ while (drop < st.archived.length && (st.archived[drop].gone ?? Infinity) <= oldestReq) drop++;
1045
+ }
1046
+ if (st.archived.length - drop > bounds.maxArchiveNodes) {
1047
+ drop = st.archived.length - bounds.maxArchiveNodes;
1048
+ }
1049
+ if (drop > 0) {
1050
+ const floor = st.archived[drop - 1].gone;
1051
+ if (floor !== void 0) st.archiveFloor = Math.max(st.archiveFloor ?? 0, floor);
1052
+ st.archived = st.archived.slice(drop);
1053
+ }
1054
+ }
129
1055
  }
130
1056
  function createTimelineState() {
131
1057
  return {
@@ -140,6 +1066,7 @@ function createTimelineState() {
140
1066
  contextWindow: void 0,
141
1067
  requests: [],
142
1068
  events: [],
1069
+ archived: [],
143
1070
  callNames: {}
144
1071
  };
145
1072
  }
@@ -149,14 +1076,18 @@ function categoryOf(type, message) {
149
1076
  if (isInjection(message?.source)) return "inject";
150
1077
  return "user";
151
1078
  }
1079
+ function archiveRemoved(st, removed, goneSeq) {
1080
+ for (const n of removed) st.archived.push({ ...n, gone: goneSeq });
1081
+ }
152
1082
  function applySurface(st, ev, type, data, message) {
153
- const cat = categoryOf(type, message);
1083
+ const cat = categoryOf(type, message ?? void 0);
154
1084
  const node = {
155
1085
  seq: ev.seq,
156
1086
  time: ev.time,
157
1087
  cat,
158
1088
  // Empty assistant messages project to no model message (usage-only), so
159
- // they price 0 — mirroring dsh's deriveEventMessage/estimate.
1089
+ // they price 0 — `deriveEventMessage` returns null for that case, and
1090
+ // `estimateMessage(null, true)` short-circuits before ROLE_OVERHEAD.
160
1091
  tokens: estimateMessage(message, type === "assistant/message")
161
1092
  };
162
1093
  const source = message?.source;
@@ -198,10 +1129,14 @@ function applySurface(st, ev, type, data, message) {
198
1129
  if (Array.isArray(shadowedSeqs) && shadowedSeqs.length > 0) {
199
1130
  const shadowed = new Set(shadowedSeqs);
200
1131
  const kept = [];
1132
+ const removed = [];
201
1133
  for (const n of st.surface) {
202
- if (shadowed.has(n.seq)) st.sums[n.cat] -= n.tokens;
203
- else kept.push(n);
1134
+ if (shadowed.has(n.seq)) {
1135
+ st.sums[n.cat] -= n.tokens;
1136
+ removed.push(n);
1137
+ } else kept.push(n);
204
1138
  }
1139
+ archiveRemoved(st, removed, ev.seq);
205
1140
  st.surface = kept;
206
1141
  st.sums[cat] += node.tokens;
207
1142
  st.surface.push(node);
@@ -218,6 +1153,7 @@ function applySurface(st, ev, type, data, message) {
218
1153
  }
219
1154
  if (si >= 0 && ei >= si) {
220
1155
  const removed = st.surface.splice(si, ei - si + 1, node);
1156
+ archiveRemoved(st, removed, ev.seq);
221
1157
  for (const r of removed) st.sums[r.cat] -= r.tokens;
222
1158
  st.sums[cat] += node.tokens;
223
1159
  return node;
@@ -236,6 +1172,7 @@ function applyTimeline(state, event, bounds) {
236
1172
  toolList: [...state.toolList],
237
1173
  requests: [...state.requests],
238
1174
  events: [...state.events],
1175
+ archived: [...state.archived],
239
1176
  callNames: { ...state.callNames }
240
1177
  };
241
1178
  const data = event.data;
@@ -273,7 +1210,7 @@ function applyTimeline(state, event, bounds) {
273
1210
  break;
274
1211
  }
275
1212
  case "user/message": {
276
- const msg = data;
1213
+ const msg = deriveEventMessage(event);
277
1214
  const s = ensure();
278
1215
  const node = applySurface(s, event, event.type, data, msg);
279
1216
  const source = msg?.source;
@@ -296,7 +1233,7 @@ function applyTimeline(state, event, bounds) {
296
1233
  break;
297
1234
  }
298
1235
  case "tool/result": {
299
- const toolMsg = data?.message ?? null;
1236
+ const toolMsg = deriveEventMessage(event);
300
1237
  const s = ensure();
301
1238
  applySurface(s, event, event.type, data, toolMsg);
302
1239
  break;
@@ -323,7 +1260,7 @@ function applyTimeline(state, event, bounds) {
323
1260
  if (typeof usage.outputTokens === "number") record.output = usage.outputTokens;
324
1261
  }
325
1262
  s.requests.push(record);
326
- const asstMsg = data?.message ?? null;
1263
+ const asstMsg = deriveEventMessage(event);
327
1264
  applySurface(s, event, event.type, data, asstMsg);
328
1265
  break;
329
1266
  }
@@ -371,10 +1308,21 @@ function buildTimelineView(state, bounds) {
371
1308
  requests: state.requests.map((r) => ({ ...r })),
372
1309
  events: state.events.map((e) => ({ ...e })),
373
1310
  nodes: [],
374
- droppedNodes: 0
1311
+ droppedNodes: 0,
1312
+ archive: state.archived.map((n) => ({ ...n }))
375
1313
  };
376
- result.droppedNodes = Math.max(0, state.surface.length - bounds.maxNodes);
377
- result.nodes = state.surface.slice(-bounds.maxNodes);
1314
+ const overflowCount = Math.max(0, state.surface.length - bounds.maxNodes);
1315
+ const overflow = state.surface.slice(0, overflowCount);
1316
+ const tail = state.surface.slice(overflowCount);
1317
+ const pinned = overflow.filter((n) => n.cat === "inject");
1318
+ result.nodes = pinned.length > 0 ? [...pinned, ...tail] : tail;
1319
+ result.droppedNodes = overflowCount - pinned.length;
1320
+ if (result.droppedNodes > 0) {
1321
+ let floor = 0;
1322
+ for (const n of overflow) if (n.cat !== "inject") floor = Math.max(floor, n.seq);
1323
+ result.surfaceFloor = floor;
1324
+ }
1325
+ if (state.archiveFloor !== void 0) result.archiveFloor = state.archiveFloor;
378
1326
  const requests = result.requests;
379
1327
  const events = result.events;
380
1328
  let ri = 0;
@@ -395,70 +1343,74 @@ function buildTimelineView(state, bounds) {
395
1343
  }
396
1344
 
397
1345
  // src/host/timeline.ts
398
- var surfaceNodeSchema = z2.object({
399
- seq: z2.number().int().nonnegative(),
400
- time: z2.number().optional(),
401
- cat: z2.enum(["user", "inject", "assistant", "tool"]),
402
- tokens: z2.number().int().nonnegative(),
403
- form: z2.string().optional(),
404
- text: z2.string().optional(),
405
- tool: z2.string().optional(),
406
- err: z2.boolean().optional(),
407
- skill: z2.string().optional(),
408
- calls: z2.array(z2.string()).optional()
1346
+ var surfaceNodeSchema = z3.object({
1347
+ seq: z3.number().int().nonnegative(),
1348
+ time: z3.number().optional(),
1349
+ cat: z3.enum(["user", "inject", "assistant", "tool"]),
1350
+ tokens: z3.number().int().nonnegative(),
1351
+ gone: z3.number().int().nonnegative().optional(),
1352
+ form: z3.string().optional(),
1353
+ text: z3.string().optional(),
1354
+ tool: z3.string().optional(),
1355
+ err: z3.boolean().optional(),
1356
+ skill: z3.string().optional(),
1357
+ calls: z3.array(z3.string()).optional()
409
1358
  }).strict();
410
- var requestRecordSchema = z2.object({
411
- turn: z2.number().optional(),
412
- step: z2.number().optional(),
413
- time: z2.number(),
414
- seq: z2.number(),
415
- system: z2.number().int().nonnegative(),
416
- tools: z2.number().int().nonnegative(),
417
- user: z2.number().int().nonnegative(),
418
- inject: z2.number().int().nonnegative(),
419
- assistant: z2.number().int().nonnegative(),
420
- tool: z2.number().int().nonnegative(),
421
- total: z2.number().int().nonnegative(),
422
- prompt: z2.number().int().nonnegative().optional(),
423
- output: z2.number().int().nonnegative().optional(),
424
- stepCount: z2.number().int().positive().optional()
1359
+ var requestRecordSchema = z3.object({
1360
+ turn: z3.number().optional(),
1361
+ step: z3.number().optional(),
1362
+ time: z3.number(),
1363
+ seq: z3.number(),
1364
+ system: z3.number().int().nonnegative(),
1365
+ tools: z3.number().int().nonnegative(),
1366
+ user: z3.number().int().nonnegative(),
1367
+ inject: z3.number().int().nonnegative(),
1368
+ assistant: z3.number().int().nonnegative(),
1369
+ tool: z3.number().int().nonnegative(),
1370
+ total: z3.number().int().nonnegative(),
1371
+ prompt: z3.number().int().nonnegative().optional(),
1372
+ output: z3.number().int().nonnegative().optional(),
1373
+ stepCount: z3.number().int().positive().optional()
425
1374
  }).strict();
426
- var contextEventSchema = z2.object({
427
- seq: z2.number(),
428
- time: z2.number(),
429
- kind: z2.enum(["compaction", "prune", "inject", "model"]),
430
- form: z2.string().optional(),
431
- tokens: z2.number().optional(),
432
- count: z2.number().optional(),
433
- sub: z2.string().optional(),
434
- name: z2.string().optional(),
435
- from: z2.string().optional(),
436
- to: z2.string().optional(),
437
- fromTurn: z2.number().optional(),
438
- fromStep: z2.number().optional(),
439
- turn: z2.number().optional(),
440
- step: z2.number().optional()
1375
+ var contextEventSchema = z3.object({
1376
+ seq: z3.number(),
1377
+ time: z3.number(),
1378
+ kind: z3.enum(["compaction", "prune", "inject", "model"]),
1379
+ form: z3.string().optional(),
1380
+ tokens: z3.number().optional(),
1381
+ count: z3.number().optional(),
1382
+ sub: z3.string().optional(),
1383
+ name: z3.string().optional(),
1384
+ from: z3.string().optional(),
1385
+ to: z3.string().optional(),
1386
+ fromTurn: z3.number().optional(),
1387
+ fromStep: z3.number().optional(),
1388
+ turn: z3.number().optional(),
1389
+ step: z3.number().optional()
441
1390
  }).strict();
442
- var currentSchema = z2.object({
443
- system: z2.number().int().nonnegative(),
444
- tools: z2.number().int().nonnegative(),
445
- user: z2.number().int().nonnegative(),
446
- inject: z2.number().int().nonnegative(),
447
- assistant: z2.number().int().nonnegative(),
448
- tool: z2.number().int().nonnegative(),
449
- total: z2.number().int().nonnegative()
1391
+ var currentSchema = z3.object({
1392
+ system: z3.number().int().nonnegative(),
1393
+ tools: z3.number().int().nonnegative(),
1394
+ user: z3.number().int().nonnegative(),
1395
+ inject: z3.number().int().nonnegative(),
1396
+ assistant: z3.number().int().nonnegative(),
1397
+ tool: z3.number().int().nonnegative(),
1398
+ total: z3.number().int().nonnegative()
450
1399
  }).strict();
451
- var contextTimelineSchema = z2.object({
452
- ok: z2.literal(true),
453
- model: z2.string().optional(),
454
- provider: z2.string().optional(),
455
- contextWindow: z2.number().optional(),
1400
+ var contextTimelineSchema = z3.object({
1401
+ ok: z3.literal(true),
1402
+ model: z3.string().optional(),
1403
+ provider: z3.string().optional(),
1404
+ contextWindow: z3.number().optional(),
456
1405
  current: currentSchema,
457
- toolList: z2.array(z2.object({ name: z2.string(), tokens: z2.number().int().nonnegative() }).strict()),
458
- requests: z2.array(requestRecordSchema),
459
- events: z2.array(contextEventSchema),
460
- nodes: z2.array(surfaceNodeSchema),
461
- droppedNodes: z2.number().int().nonnegative()
1406
+ toolList: z3.array(z3.object({ name: z3.string(), tokens: z3.number().int().nonnegative() }).strict()),
1407
+ requests: z3.array(requestRecordSchema),
1408
+ events: z3.array(contextEventSchema),
1409
+ nodes: z3.array(surfaceNodeSchema),
1410
+ droppedNodes: z3.number().int().nonnegative(),
1411
+ archive: z3.array(surfaceNodeSchema),
1412
+ surfaceFloor: z3.number().int().nonnegative().optional(),
1413
+ archiveFloor: z3.number().int().nonnegative().optional()
462
1414
  }).strict();
463
1415
  function createContextTimelineDefinition(config) {
464
1416
  const bounds = resolveBounds(config);
@@ -472,7 +1424,10 @@ function createContextTimelineDefinition(config) {
472
1424
  // occupancyWindow) left the persisted state — the client now reads the
473
1425
  // official token-meter `contextPressure` projection instead. Old cached
474
1426
  // rows are discarded and refolded.
475
- stateVersion: 2
1427
+ // 3 since 0.12: the removed-node archive (`archived` + `archiveFloor`)
1428
+ // joined the persisted state for the Context browser's per-step
1429
+ // reconstruction — cached rows predate the shape and are refolded.
1430
+ stateVersion: 3
476
1431
  };
477
1432
  }
478
1433
 
@@ -481,6 +1436,7 @@ var name = "dsh-context";
481
1436
  var inject = ["sessionProjections"];
482
1437
  function apply(ctx, config) {
483
1438
  ctx.sessionProjections.register(createContextTimelineDefinition(config));
1439
+ ctx.sessionProjections.register(createContextHeadersDefinition());
484
1440
  }
485
1441
  export {
486
1442
  Config,