@deepseek-ai/dsh-session-persistence-jsonl 0.2.2-rc.5 → 0.2.3-alpha.2

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/worker.cjs CHANGED
@@ -1263,20 +1263,22 @@ const symbols = {
1263
1263
  caller: Symbol.for("cordis.caller"),
1264
1264
  receiver: Symbol.for("cordis.receiver"),
1265
1265
  original: Symbol.for("cordis.original"),
1266
- metadata: Symbol.for("cordis.metadata"),
1266
+ decorator: Symbol.for("cordis.decorator"),
1267
1267
  initHooks: Symbol.for("cordis.initHooks"),
1268
1268
  checkProto: Symbol.for("cordis.checkProto"),
1269
+ root: Symbol.for("cordis.root"),
1269
1270
  effect: Symbol.for("cordis.effect"),
1270
1271
  filter: Symbol.for("cordis.filter"),
1271
1272
  isolate: Symbol.for("cordis.isolate"),
1272
1273
  intercept: Symbol.for("cordis.intercept"),
1273
1274
  init: Symbol.for("cordis.init"),
1274
1275
  check: Symbol.for("cordis.check"),
1275
- config: Symbol.for("cordis.config"),
1276
1276
  invoke: Symbol.for("cordis.invoke"),
1277
+ metadata: Symbol.for("cordis.metadata"),
1277
1278
  extend: Symbol.for("cordis.extend"),
1278
1279
  tracker: Symbol.for("cordis.tracker"),
1279
- resolveConfig: Symbol.for("cordis.resolveConfig")
1280
+ mergeIntercept: Symbol.for("cordis.mergeIntercept"),
1281
+ resolveIntercept: Symbol.for("cordis.resolveIntercept")
1280
1282
  };
1281
1283
  const GeneratorFunction = function* () {}.constructor;
1282
1284
  const AsyncGeneratorFunction = async function* () {}.constructor;
@@ -1444,7 +1446,8 @@ function buildOuterStack(offset = 0) {
1444
1446
  //#region ../../../vendor/cordis/src/fiber.ts
1445
1447
  const kValidationError$1 = Symbol.for("ValidationError");
1446
1448
  /** Error raised when plugin configuration fails standard-schema validation. */
1447
- var ValidationError$1 = class extends TypeError {
1449
+ var ValidationError$1 = class ValidationError$1 extends TypeError {
1450
+ issues;
1448
1451
  name = "ValidationError";
1449
1452
  /**
1450
1453
  * Build the aggregated message from schema issues.
@@ -1453,9 +1456,37 @@ var ValidationError$1 = class extends TypeError {
1453
1456
  */
1454
1457
  constructor(issues) {
1455
1458
  super(`invalid config:\n` + issues.map((issue) => {
1456
- if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
1459
+ if (issue.path?.length) return ` - ${issue.message} (at ${ValidationError$1.formatPath(issue.path)})`;
1457
1460
  else return ` - ${issue.message}`;
1458
1461
  }).join("\n"));
1462
+ this.issues = issues;
1463
+ }
1464
+ /**
1465
+ * Test whether a value is a config `ValidationError`, including one from another copy of Cordis.
1466
+ *
1467
+ * @param error — the value to test.
1468
+ * @returns `true` if `error` carries the global validation-error brand.
1469
+ */
1470
+ static is(error) {
1471
+ return !!error?.[kValidationError$1];
1472
+ }
1473
+ /**
1474
+ * Convert an issue path to plain property keys.
1475
+ *
1476
+ * @param path — the standard-schema issue path; segments may be `{ key }` objects.
1477
+ * @returns the property keys, or an empty array when the issue has no path.
1478
+ */
1479
+ static normalizePath(path = []) {
1480
+ return path.map((segment) => typeof segment === "object" ? segment.key : segment);
1481
+ }
1482
+ /**
1483
+ * Format an issue path as a dotted string.
1484
+ *
1485
+ * @param path — the standard-schema issue path.
1486
+ * @returns the keys joined with `.`.
1487
+ */
1488
+ static formatPath(path) {
1489
+ return ValidationError$1.normalizePath(path).map(String).join(".");
1459
1490
  }
1460
1491
  };
1461
1492
  Object.defineProperty(ValidationError$1.prototype, kValidationError$1, { value: true });
@@ -1569,14 +1600,6 @@ var Fiber = class {
1569
1600
  if (runtime) {
1570
1601
  this.uid = parent.registry.counter;
1571
1602
  this.ctx = this.context = parent.extend({ fiber: this });
1572
- const injectEntries = Object.entries(this.inject);
1573
- if (injectEntries.length) {
1574
- this.ctx[Context.intercept] = Object.create(parent[Context.intercept]);
1575
- for (const [name, config] of injectEntries) {
1576
- if (isNullable(config)) continue;
1577
- this.ctx[Context.intercept][name] = config;
1578
- }
1579
- }
1580
1603
  this._runner = {
1581
1604
  epoch: INACTIVE,
1582
1605
  getOuterStack,
@@ -1606,6 +1629,7 @@ var Fiber = class {
1606
1629
  return 5;
1607
1630
  });
1608
1631
  while (this.inertia) await this.inertia;
1632
+ this._updateState(() => {});
1609
1633
  };
1610
1634
  }, "ctx.plugin()");
1611
1635
  try {
@@ -2056,7 +2080,11 @@ var EventsService = class {
2056
2080
  const name = args.shift();
2057
2081
  if ((typeof name !== "string" || !name.startsWith("internal/")) && this._hooks["internal/dispatch"]?.length) this.emit("internal/dispatch", type, name, args, thisArg);
2058
2082
  const filter = thisArg?.[Context.filter];
2059
- return [thisArg, (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback)];
2083
+ return [
2084
+ thisArg,
2085
+ (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback),
2086
+ name
2087
+ ];
2060
2088
  }
2061
2089
  /**
2062
2090
  * Resolve bound callbacks using the event's context filter.
@@ -2076,9 +2104,11 @@ var EventsService = class {
2076
2104
  * @returns a promise resolving once every listener has settled.
2077
2105
  */
2078
2106
  async parallel(...args) {
2079
- const [thisArg, callbacks] = this._resolve("parallel", args);
2107
+ const [thisArg, callbacks, name] = this._resolve("parallel", args);
2080
2108
  const errors = (await Promise.allSettled(callbacks.map(async (callback) => Reflect.apply(callback, thisArg, args)))).filter((result) => result.status === "rejected");
2081
- if (errors.length) throw new AggregateError(errors.map((error) => error.reason));
2109
+ if (!errors.length) return;
2110
+ const label = typeof name === "symbol" ? String(name) : `"${name}"`;
2111
+ throw new AggregateError(errors.map((error) => error.reason), `one or more listeners of event ${label} failed`);
2082
2112
  }
2083
2113
  /**
2084
2114
  * Run listeners synchronously without waiting for returned promises.
@@ -2199,310 +2229,78 @@ var EventsService = class {
2199
2229
  }
2200
2230
  };
2201
2231
  //#endregion
2202
- //#region ../../../vendor/cordis/src/logger.ts
2203
- /** Built-in placeholder formatters used by `Logger.format()`. */
2204
- const defaultFormatters = {
2205
- s: (value) => String(value),
2206
- d: (value) => Math.trunc(Number(value)),
2207
- i: (value) => Math.trunc(Number(value)),
2208
- f: (value) => Number(value),
2209
- o: (value) => JSON.stringify(value),
2210
- O: (value) => JSON.stringify(value),
2211
- c: () => "",
2212
- C: (value, exporter, message) => {
2213
- return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
2214
- }
2215
- };
2216
- function isAggregateError(error) {
2217
- return error instanceof Error && Array.isArray(error["errors"]);
2232
+ //#region ../../../vendor/cordis/src/reflect.ts
2233
+ function enhanceError(error) {
2234
+ const lines = error.stack.split("\n");
2235
+ lines.splice(0, 2, `Error: ${error.message}`);
2236
+ error.stack = lines.join("\n");
2237
+ return error;
2218
2238
  }
2219
- /** Logger facade for one named subsystem. */
2220
- var Logger = class {
2221
- service;
2222
- static color(exporter, code, value, decoration = "") {
2223
- if (!exporter.colors) return "" + value;
2224
- return `\u001b[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\u001b[0m`;
2225
- }
2226
- static code(name, level) {
2227
- let hash = 0;
2228
- for (let i = 0; i < name.length; i++) {
2229
- hash = (hash << 3) - hash + name.charCodeAt(i) + 13;
2230
- hash |= 0;
2231
- }
2232
- const colors = !level ? [] : level >= 2 ? c256 : c16;
2233
- return colors[Math.abs(hash) % colors.length];
2234
- }
2235
- static format(exporter, message) {
2236
- const args = message.args.slice();
2237
- if (args[0] instanceof Error) {
2238
- args[0] = args[0].stack || args[0].message;
2239
- args.unshift("%s");
2240
- } else if (typeof args[0] !== "string") args.unshift("%o");
2241
- let format = args.shift();
2242
- format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
2243
- if (match === "%%") return "%";
2244
- const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
2245
- if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
2246
- return match;
2247
- });
2248
- const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
2249
- for (let arg of args) {
2250
- if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
2251
- format += " " + arg;
2252
- }
2253
- const { maxLength = 10240 } = exporter;
2254
- return format.split(/\r?\n/g).map((line) => {
2255
- return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
2256
- }).join("\n");
2257
- }
2258
- constructor(options, service) {
2259
- this.service = service;
2260
- Object.assign(this, options);
2261
- this.error = this._method("error", 0);
2262
- this.info = this._method("info", 2);
2263
- this.warn = this._method("warn", 1);
2264
- this.debug = this._method("debug", 3);
2265
- }
2266
- _method(type, level) {
2267
- return (...args) => {
2268
- if (args.length === 1 && args[0] instanceof Error) {
2269
- if (args[0].cause) this[type](args[0].cause);
2270
- else if (isAggregateError(args[0])) {
2271
- args[0].errors.forEach((error) => this[type](error));
2272
- return;
2273
- }
2274
- }
2275
- const sn = ++this.service._snMessage;
2276
- const ts = Date.now();
2277
- for (const exporter of this.service.exporters.values()) {
2278
- if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 2) < level) continue;
2279
- const message = {
2280
- sn,
2281
- ts,
2282
- type,
2283
- level,
2284
- name: this.name,
2285
- ...this.meta,
2286
- args
2287
- };
2288
- exporter.export(message);
2289
- }
2239
+ const RESERVED_WORDS = ["prototype", "then"];
2240
+ function isSpecialProperty(prop) {
2241
+ return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
2242
+ }
2243
+ /**
2244
+ * Resolve an access to service `name` from the def site `ctx` by walking up its fibers.
2245
+ *
2246
+ * - `{ impl }`: a fiber provides the impl itself in the same isolation.
2247
+ * - `{ fiber, impl }`: the impl comes from the committed view of `fiber`.
2248
+ * - `{ fiber }`: `fiber` declares the service but is inactive.
2249
+ * - `undefined`: no fiber declares the service, or the walk reaches a context that isolates `name` again.
2250
+ *
2251
+ * @param ctx — the def-site context of the access.
2252
+ * @param name — the service name being accessed.
2253
+ * @returns the fiber whose `inject` admits the access and the impl the access reaches, or `undefined`.
2254
+ */
2255
+ function locate(ctx, name) {
2256
+ const key = ctx[symbols.isolate][name];
2257
+ let table = ctx[symbols.isolate];
2258
+ let fiber = ctx.fiber;
2259
+ while (true) {
2260
+ let impl;
2261
+ for (const provision of fiber.provisions) if (provision.name === name && provision.ctx[symbols.isolate][name] === key) impl = provision;
2262
+ if (impl) return { impl };
2263
+ while (table !== fiber.ctx[symbols.isolate]) {
2264
+ if (!table || Object.hasOwn(table, name)) return;
2265
+ table = Object.getPrototypeOf(table);
2266
+ }
2267
+ impl = fiber.committed?.[name];
2268
+ if (impl || name in fiber.inject) return {
2269
+ fiber,
2270
+ impl
2290
2271
  };
2272
+ if (!fiber.runtime) return;
2273
+ fiber = fiber.parent.fiber;
2291
2274
  }
2292
- };
2293
- /** ANSI 16-color palette indexes used for logger name coloring. */
2294
- const c16 = [
2295
- 6,
2296
- 2,
2297
- 3,
2298
- 4,
2299
- 5,
2300
- 1
2301
- ];
2302
- /** ANSI 256-color palette indexes used for logger name coloring. */
2303
- const c256 = [
2304
- 20,
2305
- 21,
2306
- 26,
2307
- 27,
2308
- 32,
2309
- 33,
2310
- 38,
2311
- 39,
2312
- 40,
2313
- 41,
2314
- 42,
2315
- 43,
2316
- 44,
2317
- 45,
2318
- 56,
2319
- 57,
2320
- 62,
2321
- 63,
2322
- 68,
2323
- 69,
2324
- 74,
2325
- 75,
2326
- 76,
2327
- 77,
2328
- 78,
2329
- 79,
2330
- 80,
2331
- 81,
2332
- 92,
2333
- 93,
2334
- 98,
2335
- 99,
2336
- 112,
2337
- 113,
2338
- 129,
2339
- 134,
2340
- 135,
2341
- 148,
2342
- 149,
2343
- 160,
2344
- 161,
2345
- 162,
2346
- 163,
2347
- 164,
2348
- 165,
2349
- 166,
2350
- 167,
2351
- 168,
2352
- 169,
2353
- 170,
2354
- 171,
2355
- 172,
2356
- 173,
2357
- 178,
2358
- 179,
2359
- 184,
2360
- 185,
2361
- 196,
2362
- 197,
2363
- 198,
2364
- 199,
2365
- 200,
2366
- 201,
2367
- 202,
2368
- 203,
2369
- 204,
2370
- 205,
2371
- 206,
2372
- 207,
2373
- 208,
2374
- 209,
2375
- 214,
2376
- 215,
2377
- 220,
2378
- 221
2379
- ];
2275
+ }
2380
2276
  /**
2381
- * Built-in logging service.
2277
+ * Reflection and service-resolution layer installed as `ctx.reflect`.
2382
2278
  *
2383
- * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
2384
- * directly to log with the current fiber-derived name.
2279
+ * This service powers the context proxy, service registration, accessors, and
2280
+ * the mixins that expose core service methods directly on `ctx`.
2385
2281
  */
2386
- var LoggerService = class LoggerService {
2387
- bufferSize = 1e3;
2388
- buffer = [];
2282
+ var ReflectService = class {
2389
2283
  ctx;
2390
- _snMessage = 0;
2391
- _snExporter = 0;
2392
- exporters = /* @__PURE__ */ new Map();
2393
- constructor(ctx) {
2394
- const tracker = {
2395
- property: "ctx",
2396
- noShadow: true
2397
- };
2398
- const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
2399
- Object.assign(self, this);
2400
- self.ctx = ctx;
2401
- defineProperty(self, symbols.tracker, tracker);
2402
- self.exporter({
2403
- colors: 3,
2404
- export: (message) => {
2405
- self.buffer.push(message);
2406
- const overflow = self.buffer.length - self.bufferSize;
2407
- if (overflow === 1) self.buffer.shift();
2408
- else if (overflow > 1) self.buffer.splice(0, overflow);
2409
- }
2410
- });
2411
- return self;
2412
- }
2413
- /**
2414
- * Register an exporter and dispose it with the current fiber.
2415
- *
2416
- * @param exporter — the sink that receives structured log messages.
2417
- * @returns a disposer that removes the exporter.
2418
- */
2419
- exporter(exporter) {
2420
- return this.ctx.effect(() => {
2421
- const id = ++this._snExporter;
2422
- this.exporters.set(id, exporter);
2423
- return () => this.exporters.delete(id);
2424
- }, "ctx.logger.exporter()");
2425
- }
2426
- _resolveConfig() {
2427
- let intercept = this.ctx[symbols.intercept];
2428
- const configs = [];
2429
- while ("logger" in intercept) {
2430
- if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]);
2431
- intercept = Object.getPrototypeOf(intercept);
2432
- }
2433
- return Object.assign({}, ...configs);
2434
- }
2435
- [symbols.invoke](name) {
2436
- const config = this._resolveConfig();
2437
- const fiber = (this[symbols.caller] ?? this.ctx).fiber;
2438
- name ??= config.name;
2439
- name ??= hyphenate(fiber.name);
2440
- return new Logger({
2441
- name,
2442
- level: config.level,
2443
- meta: { fiber: new WeakRef(fiber) }
2444
- }, this);
2445
- }
2446
- static {
2447
- for (const type of [
2448
- "error",
2449
- "info",
2450
- "warn",
2451
- "debug"
2452
- ]) LoggerService.prototype[type] = function(...args) {
2453
- return this()[type](...args);
2454
- };
2455
- }
2456
- };
2457
- //#endregion
2458
- //#region ../../../vendor/cordis/src/reflect.ts
2459
- function enhanceError(error) {
2460
- const lines = error.stack.split("\n");
2461
- lines.splice(0, 2, `Error: ${error.message}`);
2462
- error.stack = lines.join("\n");
2463
- return error;
2464
- }
2465
- const RESERVED_WORDS = ["prototype", "then"];
2466
- function isSpecialProperty(prop) {
2467
- return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
2468
- }
2469
- /**
2470
- * Reflection and service-resolution layer installed as `ctx.reflect`.
2471
- *
2472
- * This service powers the context proxy, service registration, accessors, and
2473
- * the mixins that expose core service methods directly on `ctx`.
2474
- */
2475
- var ReflectService = class {
2476
- ctx;
2477
- /** Proxy traps implementing service resolution for every context object. */
2478
- static handler = {
2479
- get: (target, prop, ctx) => {
2480
- if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx);
2481
- if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx));
2482
- const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`);
2483
- try {
2484
- const def = target.reflect.props[prop];
2485
- if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
2486
- const defSite = ctx[symbols.shadow] ?? ctx;
2487
- if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false);
2488
- return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
2489
- const key = defSite[symbols.isolate][prop];
2490
- let fiber = defSite.fiber;
2491
- while (true) {
2492
- let impl = fiber.committed?.[prop];
2493
- for (const provision of fiber.provisions) if (provision.name === prop && provision.ctx[symbols.isolate][prop] === key) impl = provision;
2494
- if (impl) return getTraceable(ctx, impl.value);
2495
- if (prop in fiber.inject) {
2496
- error.message = `cannot get required service "${prop}" in inactive context`;
2497
- throw error;
2498
- }
2499
- if (!fiber.runtime) throw error;
2500
- if (fiber.parent[symbols.isolate][prop] !== key) throw error;
2501
- fiber = fiber.parent.fiber;
2502
- }
2503
- });
2504
- } catch (e) {
2505
- throw e === error ? enhanceError(e) : e;
2284
+ /** Proxy traps implementing service resolution for every context object. */
2285
+ static handler = {
2286
+ get: (target, prop, ctx) => {
2287
+ if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx);
2288
+ if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx));
2289
+ const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`);
2290
+ try {
2291
+ const def = target.reflect.props[prop];
2292
+ if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
2293
+ const defSite = ctx[symbols.shadow] ?? ctx;
2294
+ if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false);
2295
+ return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
2296
+ const result = locate(defSite, prop);
2297
+ if (!result) throw error;
2298
+ if (result.impl) return getTraceable(ctx, result.impl.value);
2299
+ error.message = `cannot get required service "${prop}" in inactive context`;
2300
+ throw error;
2301
+ });
2302
+ } catch (e) {
2303
+ throw e === error ? enhanceError(e) : e;
2506
2304
  }
2507
2305
  },
2508
2306
  set: (target, prop, value, ctx) => {
@@ -2611,7 +2409,7 @@ var ReflectService = class {
2611
2409
  if (!this.props[name]) this.props[name] ??= { type: "service" };
2612
2410
  else if (this.props[name].type !== "service") throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
2613
2411
  this.props[name] = { type: "service" };
2614
- this.ctx.root[symbols.isolate][name] ??= Symbol(name);
2412
+ this.ctx[symbols.root][symbols.isolate][name] ??= Symbol(name);
2615
2413
  const key = this.ctx[symbols.isolate][name];
2616
2414
  const impl = {
2617
2415
  uid: ++this._implCounter,
@@ -2739,6 +2537,358 @@ var ReflectService = class {
2739
2537
  }
2740
2538
  };
2741
2539
  //#endregion
2540
+ //#region ../../../vendor/cordis/src/service.ts
2541
+ /**
2542
+ * Base class for services that expose a named API on `ctx`.
2543
+ *
2544
+ * Subclasses call `super(ctx, name)` from their constructor. The service is
2545
+ * registered immediately and is automatically removed with the owning fiber.
2546
+ */
2547
+ var Service = class Service {
2548
+ ctx;
2549
+ /** Symbol key of an instance method run after construction (class plugins). */
2550
+ static init = symbols.init;
2551
+ /** Symbol key of the availability predicate passed to `ctx.provide()`. */
2552
+ static check = symbols.check;
2553
+ /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
2554
+ static invoke = symbols.invoke;
2555
+ /** Symbol key of the phantom intercept-metadata type parameter. */
2556
+ static metadata = symbols.metadata;
2557
+ /** Symbol key of the helper deriving an extended service instance. */
2558
+ static extend = symbols.extend;
2559
+ /** Symbol key of the tracker metadata used for context tracing. */
2560
+ static tracker = symbols.tracker;
2561
+ /** Symbol key of the intercept-metadata merge hook below. */
2562
+ static mergeIntercept = symbols.mergeIntercept;
2563
+ /** Symbol key of the intercept-metadata resolution helper below. */
2564
+ static resolveIntercept = symbols.resolveIntercept;
2565
+ /** The service name this instance is registered under. */
2566
+ name;
2567
+ /**
2568
+ * Register this instance as `name` in the current context.
2569
+ *
2570
+ * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the
2571
+ * service is unregistered automatically when the owning fiber unloads.
2572
+ * Services with a `[Service.invoke]` body return a callable instance.
2573
+ *
2574
+ * @param ctx — the context to register in (stored as `this.ctx`).
2575
+ * @param name — the service name; defaults to the static `provide` field.
2576
+ */
2577
+ constructor(ctx, name) {
2578
+ this.ctx = ctx;
2579
+ name ??= this.constructor["provide"];
2580
+ let self = this;
2581
+ const tracker = {
2582
+ associate: name,
2583
+ property: "ctx"
2584
+ };
2585
+ if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
2586
+ self.ctx = ctx;
2587
+ self.name = name;
2588
+ defineProperty(self, symbols.tracker, tracker);
2589
+ self.ctx.reflect.provide(name, self, this[symbols.check]);
2590
+ return self;
2591
+ }
2592
+ [symbols.filter](ctx) {
2593
+ return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
2594
+ }
2595
+ [symbols.extend](props) {
2596
+ let self;
2597
+ if (this[Service.invoke]) self = createCallable(this.name, this, this[symbols.tracker]);
2598
+ else self = Object.create(this);
2599
+ return Object.assign(self, props);
2600
+ }
2601
+ /**
2602
+ * Merge intercept metadata values, lowest precedence first.
2603
+ *
2604
+ * Override to customize merging; the default is a shallow `Object.assign`.
2605
+ *
2606
+ * @param values — the metadata values in increasing precedence.
2607
+ * @returns the merged metadata.
2608
+ */
2609
+ [symbols.mergeIntercept](...values) {
2610
+ return Object.assign({}, ...values);
2611
+ }
2612
+ /**
2613
+ * Resolve the intercept metadata visible to the current caller.
2614
+ *
2615
+ * The metadata injected by the fiber that admits the access applies first,
2616
+ * then intercepts added by ancestor contexts, closest to the root first.
2617
+ * The values are combined with `[Service.mergeIntercept]`.
2618
+ *
2619
+ * @returns the merged metadata.
2620
+ */
2621
+ [symbols.resolveIntercept]() {
2622
+ const values = [];
2623
+ let intercept = this.ctx[Context.intercept];
2624
+ while (this.name in intercept) {
2625
+ if (Object.hasOwn(intercept, this.name)) values.unshift(intercept[this.name]);
2626
+ intercept = Object.getPrototypeOf(intercept);
2627
+ }
2628
+ const value = locate(this[symbols.caller] ?? this.ctx, this.name)?.fiber?.inject[this.name];
2629
+ if (!isNullable(value)) values.unshift(value);
2630
+ return (this[symbols.mergeIntercept] ?? Service.prototype[symbols.mergeIntercept]).apply(this, values);
2631
+ }
2632
+ static [Symbol.hasInstance](instance) {
2633
+ if (!instance) return false;
2634
+ let constructor = instance.constructor;
2635
+ while (constructor) {
2636
+ constructor = constructor.prototype?.constructor;
2637
+ if (constructor === this) return true;
2638
+ constructor &&= Object.getPrototypeOf(constructor);
2639
+ }
2640
+ return false;
2641
+ }
2642
+ };
2643
+ //#endregion
2644
+ //#region ../../../vendor/cordis/src/logger.ts
2645
+ /** Built-in placeholder formatters used by `Logger.format()`. */
2646
+ const defaultFormatters = {
2647
+ s: (value) => String(value),
2648
+ d: (value) => Math.trunc(Number(value)),
2649
+ i: (value) => Math.trunc(Number(value)),
2650
+ f: (value) => Number(value),
2651
+ o: (value) => JSON.stringify(value),
2652
+ O: (value) => JSON.stringify(value),
2653
+ c: () => "",
2654
+ C: (value, exporter, message) => {
2655
+ return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
2656
+ }
2657
+ };
2658
+ function isAggregateError(error) {
2659
+ return error instanceof Error && Array.isArray(error["errors"]);
2660
+ }
2661
+ /** Logger facade for one named subsystem. */
2662
+ var Logger = class {
2663
+ service;
2664
+ static color(exporter, code, value, decoration = "") {
2665
+ if (!exporter.colors) return "" + value;
2666
+ return `\u001b[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\u001b[0m`;
2667
+ }
2668
+ static code(name, level) {
2669
+ let hash = 0;
2670
+ for (let i = 0; i < name.length; i++) {
2671
+ hash = (hash << 3) - hash + name.charCodeAt(i) + 13;
2672
+ hash |= 0;
2673
+ }
2674
+ const colors = !level ? [] : level >= 2 ? c256 : c16;
2675
+ return colors[Math.abs(hash) % colors.length];
2676
+ }
2677
+ static format(exporter, message) {
2678
+ const args = message.args.slice();
2679
+ if (args[0] instanceof Error) {
2680
+ args[0] = args[0].stack || args[0].message;
2681
+ args.unshift("%s");
2682
+ } else if (typeof args[0] !== "string") args.unshift("%o");
2683
+ let format = args.shift();
2684
+ format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
2685
+ if (match === "%%") return "%";
2686
+ const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
2687
+ if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
2688
+ return match;
2689
+ });
2690
+ const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
2691
+ for (let arg of args) {
2692
+ if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
2693
+ format += " " + arg;
2694
+ }
2695
+ const { maxLength = 10240 } = exporter;
2696
+ return format.split(/\r?\n/g).map((line) => {
2697
+ return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
2698
+ }).join("\n");
2699
+ }
2700
+ constructor(options, service) {
2701
+ this.service = service;
2702
+ Object.assign(this, options);
2703
+ this.error = this._method("error", 0);
2704
+ this.info = this._method("info", 2);
2705
+ this.warn = this._method("warn", 1);
2706
+ this.debug = this._method("debug", 3);
2707
+ }
2708
+ _method(type, level) {
2709
+ return (...args) => {
2710
+ if (args.length === 1 && args[0] instanceof Error) {
2711
+ if (args[0].cause) this[type](args[0].cause);
2712
+ else if (isAggregateError(args[0]) && args[0].errors.length) {
2713
+ args[0].errors.forEach((error) => this[type](error));
2714
+ return;
2715
+ }
2716
+ }
2717
+ const sn = ++this.service._snMessage;
2718
+ const ts = Date.now();
2719
+ for (const exporter of this.service.exporters.values()) {
2720
+ if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 2) < level) continue;
2721
+ const message = {
2722
+ sn,
2723
+ ts,
2724
+ type,
2725
+ level,
2726
+ name: this.name,
2727
+ ...this.meta,
2728
+ args
2729
+ };
2730
+ exporter.export(message);
2731
+ }
2732
+ };
2733
+ }
2734
+ };
2735
+ /** ANSI 16-color palette indexes used for logger name coloring. */
2736
+ const c16 = [
2737
+ 6,
2738
+ 2,
2739
+ 3,
2740
+ 4,
2741
+ 5,
2742
+ 1
2743
+ ];
2744
+ /** ANSI 256-color palette indexes used for logger name coloring. */
2745
+ const c256 = [
2746
+ 20,
2747
+ 21,
2748
+ 26,
2749
+ 27,
2750
+ 32,
2751
+ 33,
2752
+ 38,
2753
+ 39,
2754
+ 40,
2755
+ 41,
2756
+ 42,
2757
+ 43,
2758
+ 44,
2759
+ 45,
2760
+ 56,
2761
+ 57,
2762
+ 62,
2763
+ 63,
2764
+ 68,
2765
+ 69,
2766
+ 74,
2767
+ 75,
2768
+ 76,
2769
+ 77,
2770
+ 78,
2771
+ 79,
2772
+ 80,
2773
+ 81,
2774
+ 92,
2775
+ 93,
2776
+ 98,
2777
+ 99,
2778
+ 112,
2779
+ 113,
2780
+ 129,
2781
+ 134,
2782
+ 135,
2783
+ 148,
2784
+ 149,
2785
+ 160,
2786
+ 161,
2787
+ 162,
2788
+ 163,
2789
+ 164,
2790
+ 165,
2791
+ 166,
2792
+ 167,
2793
+ 168,
2794
+ 169,
2795
+ 170,
2796
+ 171,
2797
+ 172,
2798
+ 173,
2799
+ 178,
2800
+ 179,
2801
+ 184,
2802
+ 185,
2803
+ 196,
2804
+ 197,
2805
+ 198,
2806
+ 199,
2807
+ 200,
2808
+ 201,
2809
+ 202,
2810
+ 203,
2811
+ 204,
2812
+ 205,
2813
+ 206,
2814
+ 207,
2815
+ 208,
2816
+ 209,
2817
+ 214,
2818
+ 215,
2819
+ 220,
2820
+ 221
2821
+ ];
2822
+ /**
2823
+ * Built-in logging service.
2824
+ *
2825
+ * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
2826
+ * directly to log with the current fiber-derived name.
2827
+ */
2828
+ var LoggerService = class LoggerService {
2829
+ bufferSize = 1e3;
2830
+ buffer = [];
2831
+ ctx;
2832
+ _snMessage = 0;
2833
+ _snExporter = 0;
2834
+ exporters = /* @__PURE__ */ new Map();
2835
+ constructor(ctx) {
2836
+ const tracker = {
2837
+ property: "ctx",
2838
+ noShadow: true
2839
+ };
2840
+ const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
2841
+ Object.assign(self, this);
2842
+ self.ctx = ctx;
2843
+ defineProperty(self, symbols.tracker, tracker);
2844
+ self.exporter({
2845
+ colors: 3,
2846
+ export: (message) => {
2847
+ self.buffer.push(message);
2848
+ const overflow = self.buffer.length - self.bufferSize;
2849
+ if (overflow === 1) self.buffer.shift();
2850
+ else if (overflow > 1) self.buffer.splice(0, overflow);
2851
+ }
2852
+ });
2853
+ return self;
2854
+ }
2855
+ /**
2856
+ * Register an exporter and dispose it with the current fiber.
2857
+ *
2858
+ * @param exporter — the sink that receives structured log messages.
2859
+ * @returns a disposer that removes the exporter.
2860
+ */
2861
+ exporter(exporter) {
2862
+ return this.ctx.effect(() => {
2863
+ const id = ++this._snExporter;
2864
+ this.exporters.set(id, exporter);
2865
+ return () => this.exporters.delete(id);
2866
+ }, "ctx.logger.exporter()");
2867
+ }
2868
+ [symbols.invoke](name) {
2869
+ const caller = this[symbols.caller];
2870
+ const config = Service.prototype[Service.resolveIntercept].call(this);
2871
+ const fiber = (caller ?? this.ctx).fiber;
2872
+ name ??= config.name;
2873
+ name ??= hyphenate(fiber.name);
2874
+ return new Logger({
2875
+ name,
2876
+ level: config.level,
2877
+ meta: { fiber: new WeakRef(fiber) }
2878
+ }, this);
2879
+ }
2880
+ static {
2881
+ for (const type of [
2882
+ "error",
2883
+ "info",
2884
+ "warn",
2885
+ "debug"
2886
+ ]) LoggerService.prototype[type] = function(...args) {
2887
+ return this()[type](...args);
2888
+ };
2889
+ }
2890
+ };
2891
+ //#endregion
2742
2892
  //#region ../../../vendor/cordis/src/registry.ts
2743
2893
  function isApplicable(object) {
2744
2894
  return object && typeof object === "object" && typeof object.apply === "function";
@@ -2751,7 +2901,7 @@ function isApplicable(object) {
2751
2901
  */
2752
2902
  /**
2753
2903
  * @param name — the required service name.
2754
- * @param config — optional intercept config applied for that service.
2904
+ * @param config — optional intercept metadata injected for that service.
2755
2905
  * @returns the class or method decorator.
2756
2906
  */
2757
2907
  function Inject(name, config) {
@@ -2763,7 +2913,7 @@ function Inject(name, config) {
2763
2913
  }
2764
2914
  value.inject[name] = config;
2765
2915
  } else if (decorator.kind === "method") {
2766
- const inject = (value[symbols.metadata] ??= {}).inject ??= Object.create(null);
2916
+ const inject = (value[symbols.decorator] ??= {}).inject ??= Object.create(null);
2767
2917
  inject[name] = config;
2768
2918
  decorator.addInitializer(function() {
2769
2919
  const property = this[symbols.tracker]?.property;
@@ -2939,13 +3089,15 @@ var RegistryService = class {
2939
3089
  * contexts without mutating their parent.
2940
3090
  */
2941
3091
  var Context = class Context {
3092
+ /** Symbol key of the root context: `ctx[Context.root]` is the application's root context, shared by every child context. */
3093
+ static root = symbols.root;
2942
3094
  /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */
2943
3095
  static effect = symbols.effect;
2944
3096
  /** Symbol key for a context's listener filter, consulted on every event dispatch. */
2945
3097
  static filter = symbols.filter;
2946
- /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */
3098
+ /** Symbol key of the isolation map: `ctx[Context.isolate]` maps each service name to its scope label. */
2947
3099
  static isolate = symbols.isolate;
2948
- /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */
3100
+ /** Symbol key of the intercept map: `ctx[Context.intercept]` maps each service name to its intercept metadata. */
2949
3101
  static intercept = symbols.intercept;
2950
3102
  /**
2951
3103
  * Returns true for Cordis context proxies and context prototypes.
@@ -2968,7 +3120,7 @@ var Context = class Context {
2968
3120
  this[symbols.isolate] = Object.create(null);
2969
3121
  this[symbols.intercept] = Object.create(null);
2970
3122
  const self = new Proxy(this, ReflectService.handler);
2971
- this.root = self;
3123
+ this[symbols.root] = self;
2972
3124
  this.baseUrl = void 0;
2973
3125
  this.fiber = new Fiber(self, {}, Object.create(null), null, () => []);
2974
3126
  this.reflect = new ReflectService(self);
@@ -3004,6 +3156,9 @@ var Context = class Context {
3004
3156
  * resolve against the new label instead of the parent's, so a different
3005
3157
  * implementation can be provided without affecting the parent scope.
3006
3158
  * Passing the same `label` to two `isolate()` calls joins their scopes.
3159
+ * The returned context and plugins started below it never fall back to the
3160
+ * enclosing plugin's injected `name`, even when `label` equals the parent's
3161
+ * label; until a provider in the new scope supplies `name`, reading it throws.
3007
3162
  *
3008
3163
  * @param name — the service name to isolate.
3009
3164
  * @param label — scope label to join; defaults to a fresh unique symbol.
@@ -3021,100 +3176,6 @@ var Context = class Context {
3021
3176
  }
3022
3177
  };
3023
3178
  //#endregion
3024
- //#region ../../../vendor/cordis/src/service.ts
3025
- /**
3026
- * Base class for services that expose a named API on `ctx`.
3027
- *
3028
- * Subclasses call `super(ctx, name)` from their constructor. The service is
3029
- * registered immediately and is automatically removed with the owning fiber.
3030
- */
3031
- var Service = class Service {
3032
- ctx;
3033
- /** Symbol key of an instance method run after construction (class plugins). */
3034
- static init = symbols.init;
3035
- /** Symbol key of the availability predicate passed to `ctx.provide()`. */
3036
- static check = symbols.check;
3037
- /** Symbol key of the phantom intercept-config type parameter. */
3038
- static config = symbols.config;
3039
- /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
3040
- static invoke = symbols.invoke;
3041
- /** Symbol key of the helper deriving an extended service instance. */
3042
- static extend = symbols.extend;
3043
- /** Symbol key of the tracker metadata used for context tracing. */
3044
- static tracker = symbols.tracker;
3045
- /** Symbol key of the intercept-config resolution helper below. */
3046
- static resolveConfig = symbols.resolveConfig;
3047
- /** The service name this instance is registered under. */
3048
- name;
3049
- /**
3050
- * Register this instance as `name` in the current context.
3051
- *
3052
- * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the
3053
- * service is unregistered automatically when the owning fiber unloads.
3054
- * Services with a `[Service.invoke]` body return a callable instance.
3055
- *
3056
- * @param ctx — the context to register in (stored as `this.ctx`).
3057
- * @param name — the service name; defaults to the static `provide` field.
3058
- */
3059
- constructor(ctx, name) {
3060
- this.ctx = ctx;
3061
- name ??= this.constructor["provide"];
3062
- let self = this;
3063
- const tracker = {
3064
- associate: name,
3065
- property: "ctx"
3066
- };
3067
- if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
3068
- self.ctx = ctx;
3069
- self.name = name;
3070
- defineProperty(self, symbols.tracker, tracker);
3071
- self.ctx.reflect.provide(name, self, this[symbols.check]);
3072
- return self;
3073
- }
3074
- [symbols.filter](ctx) {
3075
- return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
3076
- }
3077
- [symbols.extend](props) {
3078
- let self;
3079
- if (this[Service.invoke]) self = createCallable(this.name, this, this[symbols.tracker]);
3080
- else self = Object.create(this);
3081
- return Object.assign(self, props);
3082
- }
3083
- /**
3084
- * Merge intercept config from ancestors with optional base and head values.
3085
- *
3086
- * Entries added closer to the root apply first; `base` is prepended and
3087
- * `head` appended. Uses `Config.merge` when the service declares one,
3088
- * otherwise a shallow `Object.assign`.
3089
- *
3090
- * @param base — lowest-precedence config merged before all intercepts.
3091
- * @param head — highest-precedence config merged after all intercepts.
3092
- * @returns the merged config.
3093
- */
3094
- [symbols.resolveConfig](base, head) {
3095
- let intercept = this.ctx[Context.intercept];
3096
- const configs = [];
3097
- while (this.name in intercept) {
3098
- if (Object.hasOwn(intercept, this.name)) configs.unshift(intercept[this.name]);
3099
- intercept = Object.getPrototypeOf(intercept);
3100
- }
3101
- if (base) configs.unshift(base);
3102
- if (head) configs.push(head);
3103
- if (this["Config"]?.merge) return this["Config"].merge(...configs);
3104
- else return Object.assign({}, ...configs);
3105
- }
3106
- static [Symbol.hasInstance](instance) {
3107
- if (!instance) return false;
3108
- let constructor = instance.constructor;
3109
- while (constructor) {
3110
- constructor = constructor.prototype?.constructor;
3111
- if (constructor === this) return true;
3112
- constructor &&= Object.getPrototypeOf(constructor);
3113
- }
3114
- return false;
3115
- }
3116
- };
3117
- //#endregion
3118
3179
  //#region ../../util/brand/src/index.ts
3119
3180
  /**
3120
3181
  * Apply a compile-time string brand without changing the value.
@@ -3135,14 +3196,6 @@ function brandNumber(value) {
3135
3196
  //#endregion
3136
3197
  //#region ../../core/session/src/types.ts
3137
3198
  /**
3138
- * Brand a string as a {@link SessionId}.
3139
- * @param id - the raw session id string.
3140
- * @returns the same string with the session-id brand.
3141
- */
3142
- function SessionId(id) {
3143
- return brandString(id);
3144
- }
3145
- /**
3146
3199
  * Admit a numeric value as an existing Session event position.
3147
3200
  * @param value - non-negative safe integer admitted by the owning log operation.
3148
3201
  * @returns the same number with the Session-sequence brand.
@@ -3183,6 +3236,7 @@ function SessionLogOffset(value) {
3183
3236
  * `.agents/notes/implemented/architecture/2026-08-30-retain-ignorable-external-session-events.md`.
3184
3237
  */
3185
3238
  const KNOWN_SESSION_EVENT_TYPES = new Set([
3239
+ "action-cards/decision",
3186
3240
  "agent-preset/selected",
3187
3241
  "agent/inbox/spliced",
3188
3242
  "approval/asked",
@@ -3245,6 +3299,7 @@ const KNOWN_SESSION_EVENT_TYPES = new Set([
3245
3299
  "user/message",
3246
3300
  "web/deepseek-search-llm-request",
3247
3301
  "working-directory/change",
3302
+ "workspace-root/change",
3248
3303
  "workspace/changes"
3249
3304
  ]);
3250
3305
  /** Event types whose model-visible effects require an explicit pure interpreter. */
@@ -3651,6 +3706,18 @@ var SurfaceManager = class {
3651
3706
  if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
3652
3707
  return this._state.nodes;
3653
3708
  }
3709
+ /** System nodes in surface order, including nodes whose content array is empty; scans current nodes on each read. */
3710
+ get systemNodes() {
3711
+ const systems = [];
3712
+ for (const seq of this.nodes) {
3713
+ const event = this.log[seq - this.baseSeq];
3714
+ if (event?.type === "system/message") systems.push({
3715
+ seq,
3716
+ isEmpty: event.data.message.content.length === 0
3717
+ });
3718
+ }
3719
+ return systems;
3720
+ }
3654
3721
  /** Fold events appended since the previous access. */
3655
3722
  _processDelta() {
3656
3723
  const tailSeq = this.baseSeq + this.log.length - 1;
@@ -3673,15 +3740,39 @@ var SurfaceManager = class {
3673
3740
  }
3674
3741
  };
3675
3742
  //#endregion
3743
+ //#region ../../util/error/src/index.ts
3744
+ /**
3745
+ * Harness error base with a stable machine-routable code and chained cause.
3746
+ * Package errors extend it so tool results and replay can retain failure class.
3747
+ * @module @deepseek-ai/dsh-error
3748
+ */
3749
+ /**
3750
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
3751
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
3752
+ * human-readable `message`, and supports `cause` chaining via the standard
3753
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
3754
+ */
3755
+ var HarnessError = class extends Error {
3756
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
3757
+ code;
3758
+ constructor(message, code, options) {
3759
+ super(message, options);
3760
+ this.code = code;
3761
+ this.name = new.target.name;
3762
+ }
3763
+ };
3764
+ //#endregion
3676
3765
  //#region ../../typert/protocol/src/remote-error.ts
3766
+ /** The one Remote failure class shared by owners, the Gateway, and consumers. */
3677
3767
  /**
3678
- * One Remote call failure: a real Error carrying its stable code and typed
3768
+ * One Remote call failure: a `HarnessError` carrying its stable code and typed
3679
3769
  * details. Owners throw it at the failure point; the Host Gateway encodes it
3680
3770
  * onto the wire unchanged; the Client face rebuilds an instance for the
3681
3771
  * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
3682
- * Discrimination is always by `code`, never by instanceof.
3772
+ * A tool body that throws it records `name: 'RemoteError'` and its Remote code
3773
+ * on `tool/result`. Discrimination is always by `code`, never by instanceof.
3683
3774
  */
3684
- var RemoteError = class extends Error {
3775
+ var RemoteError = class extends HarnessError {
3685
3776
  code;
3686
3777
  details;
3687
3778
  /** Structural marker: cross-realm/bundle identification never uses instanceof. */
@@ -3693,7 +3784,7 @@ var RemoteError = class extends Error {
3693
3784
  * @param options - standard Error options (`cause` survives in-process only).
3694
3785
  */
3695
3786
  constructor(code, message, details, options) {
3696
- super(message, options);
3787
+ super(message, code, options);
3697
3788
  this.code = code;
3698
3789
  this.details = details;
3699
3790
  this.name = "RemoteError";
@@ -3761,8 +3852,8 @@ var TypertRemoteService = class extends Service {
3761
3852
  * tree registers it on the root, where it outlives any one Service.
3762
3853
  */
3763
3854
  function provideInvocationAccessor(ctx) {
3764
- if (Object.hasOwn(ctx.root.reflect.props, "invocation")) return;
3765
- ctx.root.accessor("invocation", { get: () => void 0 });
3855
+ if (Object.hasOwn(ctx[Context.root].reflect.props, "invocation")) return;
3856
+ ctx[Context.root].accessor("invocation", { get: () => void 0 });
3766
3857
  }
3767
3858
  function Remote(methodExportOrOptions, context) {
3768
3859
  if (typeof methodExportOrOptions === "string") {
@@ -3869,8 +3960,91 @@ function randomUUID() {
3869
3960
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3870
3961
  }
3871
3962
  //#endregion
3963
+ //#region ../../llm/llm/src/error.ts
3964
+ /**
3965
+ * LLM failure codes and helpers over the shared Harness error base. The base
3966
+ * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
3967
+ * import paths name the same class.
3968
+ * @module @deepseek-ai/dsh-llm/error
3969
+ */
3970
+ /**
3971
+ * Every failure code the built-in providers and the LLM runtime raise. An entry
3972
+ * marked `retryChoice` is offered as a choice for a provider retry policy's
3973
+ * `retryableCodes`; being a choice does not make a code retried by default.
3974
+ */
3975
+ const LLM_FAILURE_CODES = {
3976
+ ABORTED: {},
3977
+ ACCOUNT_QUOTA: {},
3978
+ ACCOUNT_SIGN_IN_REQUIRED: {},
3979
+ ACCOUNT_TOKEN_INVALID: {},
3980
+ AUTH: {},
3981
+ CLIENT_UPGRADE_REQUIRED: {},
3982
+ CONTENT_REFUSED: {},
3983
+ CONTEXT_WINDOW_EXCEEDED: {},
3984
+ DISCOVERY_FAILED: {},
3985
+ DISCOVERY_UNSUPPORTED: {},
3986
+ DUPLICATE_ADAPTER: {},
3987
+ DUPLICATE_DIRECTORY: {},
3988
+ DUPLICATE_DISCOVERY: {},
3989
+ EMPTY_RESPONSE: { retryChoice: true },
3990
+ FILES_API: {},
3991
+ IMAGE_OFFLOAD_REQUIRED: {},
3992
+ INVALID_ADAPTER: {},
3993
+ INVALID_CATALOG: {},
3994
+ INVALID_CONFIG: {},
3995
+ INVALID_CREDENTIAL: {},
3996
+ INVALID_DIRECTORY: {},
3997
+ INVALID_DISCOVERY: {},
3998
+ INVALID_MODEL_CONTEXT: {},
3999
+ INVALID_MODEL_INFO: {},
4000
+ INVALID_MODEL_MAX_TOKENS: {},
4001
+ INVALID_MODEL_REASONING: {},
4002
+ INVALID_PREPARED_CALL: {},
4003
+ INVALID_REPLAY_STATE: {},
4004
+ INVALID_REQUEST: {},
4005
+ INVALID_RESPONSE: {},
4006
+ MALFORMED_RESPONSE: { retryChoice: true },
4007
+ MISSING_CREDENTIAL: {},
4008
+ MODEL_SWITCH_COMPACTION_FAILED: {},
4009
+ MODEL_UNSUPPORTED: {},
4010
+ NO_ADAPTER: {},
4011
+ NO_CREDENTIAL_STORE: {},
4012
+ NO_DISCOVERY: {},
4013
+ PI_AI_ERROR: {},
4014
+ QUOTA: { retryChoice: true },
4015
+ RATE_LIMIT: { retryChoice: true },
4016
+ REGISTRATION_DISPOSED: {},
4017
+ REQUEST_EXTENSION: {},
4018
+ REQUEST_HEADERS: {},
4019
+ SERVER: { retryChoice: true },
4020
+ STREAM_CLOSED: { retryChoice: true },
4021
+ TIMEOUT: { retryChoice: true },
4022
+ TRANSPORT: { retryChoice: true },
4023
+ UNKNOWN: {},
4024
+ UNKNOWN_MODEL: {},
4025
+ UNSTORABLE_PROVIDER_ID: {},
4026
+ UNSUPPORTED_CONTENT: {},
4027
+ UNSUPPORTED_OPTION: {},
4028
+ UNSUPPORTED_REASONING_EFFORT: {}
4029
+ };
4030
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
4031
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
4032
+ /**
4033
+ * Canonical provider-neutral code for a response that completed normally but
4034
+ * carried no content blocks at all. Providers occasionally emit a degenerate
4035
+ * completion (a terminal stop with zero output); adapters classify it as this
4036
+ * failure instead of yielding an empty assistant message, because an empty
4037
+ * message silently ends the turn with nothing for the user or the loop to act
4038
+ * on. The attempt produced nothing durable, so retry policy treats it as safe
4039
+ * to repeat.
4040
+ */
4041
+ const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
4042
+ 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");
4043
+ 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");
4044
+ 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");
4045
+ //#endregion
3872
4046
  //#region ../../llm/llm/src/message.ts
3873
- /** Message value types, identity, and immutable construction helpers. */
4047
+ /** Message value types, content text extraction, identity, and immutable construction helpers. */
3874
4048
  /**
3875
4049
  * Detach and deep-freeze a message whose identity already exists.
3876
4050
  * @param message - complete message, including its stable identity.
@@ -4475,178 +4649,73 @@ function defineMethod(name, keys, format) {
4475
4649
  break;
4476
4650
  case "list":
4477
4651
  schema.list = args[index].map(Schema.from);
4478
- break;
4479
- case "dict":
4480
- schema.dict = mapValues(args[index], Schema.from);
4481
- break;
4482
- case "bits":
4483
- schema.bits = {};
4484
- for (const key in args[index]) {
4485
- if (typeof args[index][key] !== "number") continue;
4486
- schema.bits[key] = args[index][key];
4487
- }
4488
- break;
4489
- case "callback": {
4490
- const callback = schema.callback = args[index];
4491
- callback["toJSON"] ||= () => callback.toString();
4492
- break;
4493
- }
4494
- case "constructor": {
4495
- const constructor = schema.constructor = args[index];
4496
- if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
4497
- break;
4498
- }
4499
- default: schema[key] = args[index];
4500
- }
4501
- });
4502
- if (name === "object" || name === "dict") schema.meta.default = {};
4503
- else if (name === "array" || name === "tuple") schema.meta.default = [];
4504
- else if (name === "bitset") schema.meta.default = 0;
4505
- return schema;
4506
- } });
4507
- }
4508
- defineMethod("is", ["constructor"], ({ constructor }) => {
4509
- if (typeof constructor === "function") return constructor.name;
4510
- else return constructor;
4511
- });
4512
- defineMethod("any", [], () => "any");
4513
- defineMethod("never", [], () => "never");
4514
- defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
4515
- defineMethod("string", [], () => "string");
4516
- defineMethod("number", [], () => "number");
4517
- defineMethod("boolean", [], () => "boolean");
4518
- defineMethod("bitset", ["bits"], () => "bitset");
4519
- defineMethod("function", [], () => "function");
4520
- defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
4521
- defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
4522
- defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
4523
- defineMethod("object", ["dict"], ({ dict }) => {
4524
- if (Object.keys(dict).length === 0) return "{}";
4525
- return `{ ${Object.entries(dict).map(([key, inner]) => {
4526
- return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
4527
- }).join(", ")} }`;
4528
- });
4529
- defineMethod("union", ["list"], ({ list }, inline) => {
4530
- const result = list.map(({ toString: format }) => format()).join(" | ");
4531
- return inline ? `(${result})` : result;
4532
- });
4533
- defineMethod("intersect", ["list"], ({ list }) => {
4534
- return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
4535
- });
4536
- defineMethod("transform", [
4537
- "inner",
4538
- "callback",
4539
- "preserve"
4540
- ], ({ inner }, isInner) => inner.toString(isInner));
4541
- //#endregion
4542
- //#region ../../util/timeout/src/index.ts
4543
- /** Largest delay Node schedules without clamping it to one millisecond. */
4544
- const MAX_TIMER_DELAY_MS = 2147483647;
4545
- //#endregion
4546
- //#region ../../util/error/src/index.ts
4547
- /**
4548
- * Harness error base with a stable machine-routable code and chained cause.
4549
- * Package errors extend it so tool results and replay can retain failure class.
4550
- * @module @deepseek-ai/dsh-error
4551
- */
4552
- /**
4553
- * Base class for all harness errors. Carries a `code` (stable, programmatic —
4554
- * e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the
4555
- * human-readable `message`, and supports `cause` chaining via the standard
4556
- * `ErrorOptions`. `name` defaults to the subclass constructor name.
4557
- */
4558
- var HarnessError = class extends Error {
4559
- /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
4560
- code;
4561
- constructor(message, code, options) {
4562
- super(message, options);
4563
- this.code = code;
4564
- this.name = new.target.name;
4565
- }
4566
- };
4567
- //#endregion
4568
- //#region ../../llm/llm/src/error.ts
4569
- /**
4570
- * LLM failure codes and helpers over the shared Harness error base. The base
4571
- * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
4572
- * import paths name the same class.
4573
- * @module @deepseek-ai/dsh-llm/error
4574
- */
4575
- /**
4576
- * Every failure code the built-in providers and the LLM runtime raise. An entry
4577
- * marked `retryChoice` is offered as a choice for a provider retry policy's
4578
- * `retryableCodes`; being a choice does not make a code retried by default.
4579
- */
4580
- const LLM_FAILURE_CODES = {
4581
- ABORTED: {},
4582
- ACCOUNT_QUOTA: {},
4583
- ACCOUNT_SIGN_IN_REQUIRED: {},
4584
- ACCOUNT_TOKEN_INVALID: {},
4585
- AUTH: {},
4586
- CLIENT_UPGRADE_REQUIRED: {},
4587
- CONTENT_REFUSED: {},
4588
- CONTEXT_WINDOW_EXCEEDED: {},
4589
- DISCOVERY_FAILED: {},
4590
- DISCOVERY_UNSUPPORTED: {},
4591
- DUPLICATE_ADAPTER: {},
4592
- DUPLICATE_DIRECTORY: {},
4593
- DUPLICATE_DISCOVERY: {},
4594
- EMPTY_RESPONSE: { retryChoice: true },
4595
- FILES_API: {},
4596
- IMAGE_OFFLOAD_REQUIRED: {},
4597
- INVALID_ADAPTER: {},
4598
- INVALID_CATALOG: {},
4599
- INVALID_CONFIG: {},
4600
- INVALID_CREDENTIAL: {},
4601
- INVALID_DIRECTORY: {},
4602
- INVALID_DISCOVERY: {},
4603
- INVALID_MODEL_CONTEXT: {},
4604
- INVALID_MODEL_INFO: {},
4605
- INVALID_MODEL_MAX_TOKENS: {},
4606
- INVALID_MODEL_REASONING: {},
4607
- INVALID_PREPARED_CALL: {},
4608
- INVALID_REPLAY_STATE: {},
4609
- INVALID_REQUEST: {},
4610
- INVALID_RESPONSE: {},
4611
- MALFORMED_RESPONSE: { retryChoice: true },
4612
- MISSING_CREDENTIAL: {},
4613
- MODEL_SWITCH_COMPACTION_FAILED: {},
4614
- MODEL_UNSUPPORTED: {},
4615
- NO_ADAPTER: {},
4616
- NO_CREDENTIAL_STORE: {},
4617
- NO_DISCOVERY: {},
4618
- PI_AI_ERROR: {},
4619
- QUOTA: { retryChoice: true },
4620
- RATE_LIMIT: { retryChoice: true },
4621
- REGISTRATION_DISPOSED: {},
4622
- REQUEST_EXTENSION: {},
4623
- REQUEST_HEADERS: {},
4624
- SERVER: { retryChoice: true },
4625
- STREAM_CLOSED: { retryChoice: true },
4626
- TIMEOUT: { retryChoice: true },
4627
- TRANSPORT: { retryChoice: true },
4628
- UNKNOWN: {},
4629
- UNKNOWN_MODEL: {},
4630
- UNSTORABLE_PROVIDER_ID: {},
4631
- UNSUPPORTED_CONTENT: {},
4632
- UNSUPPORTED_OPTION: {},
4633
- UNSUPPORTED_REASONING_EFFORT: {}
4634
- };
4635
- /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
4636
- const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
4637
- /**
4638
- * Canonical provider-neutral code for a response that completed normally but
4639
- * carried no content blocks at all. Providers occasionally emit a degenerate
4640
- * completion (a terminal stop with zero output); adapters classify it as this
4641
- * failure instead of yielding an empty assistant message, because an empty
4642
- * message silently ends the turn with nothing for the user or the loop to act
4643
- * on. The attempt produced nothing durable, so retry policy treats it as safe
4644
- * to repeat.
4645
- */
4646
- const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
4647
- 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");
4648
- 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");
4649
- 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");
4652
+ break;
4653
+ case "dict":
4654
+ schema.dict = mapValues(args[index], Schema.from);
4655
+ break;
4656
+ case "bits":
4657
+ schema.bits = {};
4658
+ for (const key in args[index]) {
4659
+ if (typeof args[index][key] !== "number") continue;
4660
+ schema.bits[key] = args[index][key];
4661
+ }
4662
+ break;
4663
+ case "callback": {
4664
+ const callback = schema.callback = args[index];
4665
+ callback["toJSON"] ||= () => callback.toString();
4666
+ break;
4667
+ }
4668
+ case "constructor": {
4669
+ const constructor = schema.constructor = args[index];
4670
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
4671
+ break;
4672
+ }
4673
+ default: schema[key] = args[index];
4674
+ }
4675
+ });
4676
+ if (name === "object" || name === "dict") schema.meta.default = {};
4677
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
4678
+ else if (name === "bitset") schema.meta.default = 0;
4679
+ return schema;
4680
+ } });
4681
+ }
4682
+ defineMethod("is", ["constructor"], ({ constructor }) => {
4683
+ if (typeof constructor === "function") return constructor.name;
4684
+ else return constructor;
4685
+ });
4686
+ defineMethod("any", [], () => "any");
4687
+ defineMethod("never", [], () => "never");
4688
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
4689
+ defineMethod("string", [], () => "string");
4690
+ defineMethod("number", [], () => "number");
4691
+ defineMethod("boolean", [], () => "boolean");
4692
+ defineMethod("bitset", ["bits"], () => "bitset");
4693
+ defineMethod("function", [], () => "function");
4694
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
4695
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
4696
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
4697
+ defineMethod("object", ["dict"], ({ dict }) => {
4698
+ if (Object.keys(dict).length === 0) return "{}";
4699
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
4700
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
4701
+ }).join(", ")} }`;
4702
+ });
4703
+ defineMethod("union", ["list"], ({ list }, inline) => {
4704
+ const result = list.map(({ toString: format }) => format()).join(" | ");
4705
+ return inline ? `(${result})` : result;
4706
+ });
4707
+ defineMethod("intersect", ["list"], ({ list }) => {
4708
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
4709
+ });
4710
+ defineMethod("transform", [
4711
+ "inner",
4712
+ "callback",
4713
+ "preserve"
4714
+ ], ({ inner }, isInner) => inner.toString(isInner));
4715
+ //#endregion
4716
+ //#region ../../util/timeout/src/index.ts
4717
+ /** Largest delay Node schedules without clamping it to one millisecond. */
4718
+ const MAX_TIMER_DELAY_MS = 2147483647;
4650
4719
  //#endregion
4651
4720
  //#region ../../llm/llm/src/retry-policy.ts
4652
4721
  /**
@@ -4847,10 +4916,11 @@ function failureSnapshot(value) {
4847
4916
  }
4848
4917
  /** Read an SDK error message without letting an accessor replace the primary failure. */
4849
4918
  function errorMessage(error) {
4919
+ let message;
4850
4920
  try {
4851
- const message = error.message;
4852
- if (typeof message === "string" && message.length > 0) return message;
4921
+ message = error.message;
4853
4922
  } catch (_sdkMessageGetter) {}
4923
+ if (typeof message === "string" && message.length > 0) return message;
4854
4924
  return "LLM adapter failed";
4855
4925
  }
4856
4926
  /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
@@ -5914,7 +5984,7 @@ var LlmError = class LlmError extends HarnessError {
5914
5984
  * @param provider - registered provider route.
5915
5985
  * @param model - exact model id.
5916
5986
  * @param image - normalized image reference.
5917
- * @returns dimensions and byte target used by the adapter's request serializer.
5987
+ * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions.
5918
5988
  */
5919
5989
  imageRequestTarget(provider, model, image) {
5920
5990
  return this.registration(provider).adapter.imageRequestTarget(provider, model, image);
@@ -6287,112 +6357,12 @@ function detachDirectoryEntry(entry) {
6287
6357
  };
6288
6358
  }
6289
6359
  //#endregion
6290
- //#region ../../core/session/src/request-header.ts
6291
- /**
6292
- * Normalize a header to canonical form: an empty tool list becomes an absent
6293
- * field, matching how requests are built. Logging, folding, and comparison use
6294
- * this one representation.
6295
- * @param header - the header to normalize (not mutated).
6296
- * @returns the canonical header.
6297
- */
6298
- function canonicalHeader(header) {
6299
- const adapterDefaults = header.adapterDefaults;
6300
- return {
6301
- config: header.config,
6302
- ...adapterDefaults?.reasoningEffort === true || adapterDefaults?.maxTokens === true ? { adapterDefaults } : {},
6303
- ...header.tools !== void 0 && header.tools.length > 0 ? { tools: header.tools } : {}
6304
- };
6305
- }
6360
+ //#region ../../core/session/src/validation.ts
6306
6361
  /**
6307
- * Fold the header events of a log (or any prefix) into the
6308
- * {@link EpochHeader} in force after the last snapshot. Non-header events are
6309
- * skipped. This is the pure offline reconstruction path; the live session
6310
- * tracks the same fold incrementally.
6311
- * @param events - session events in log order.
6312
- * @param from - a previously folded state to continue from.
6313
- * @returns the latest canonical header, or undefined when none exists yet.
6362
+ * Session header, seed-event, and inherited-cut validation shared by Session
6363
+ * construction and log validation.
6364
+ * @module @deepseek-ai/dsh-session/validation
6314
6365
  */
6315
- function foldRequestHeader(events, from) {
6316
- let state = from;
6317
- for (const event of events) if (event.type === "request/header") state = canonicalHeader(event.data.header);
6318
- return state;
6319
- }
6320
- //#endregion
6321
- //#region ../../core/session/src/tool-history.ts
6322
- /** Folds committed headers and developer messages independently of model capability. */
6323
- var ToolHistoryProjection = class {
6324
- /** Historical declarations indexed by the header sequence referenced by additions. */
6325
- headers = /* @__PURE__ */ new Map();
6326
- /** Definitions retained in the current declaration series, including removed tools. */
6327
- declared = /* @__PURE__ */ new Map();
6328
- /** Active definitions from the latest request header. */
6329
- active = [];
6330
- /** Active names reconstructed from the baseline and recorded updates. */
6331
- available = /* @__PURE__ */ new Set();
6332
- /** Header that starts the current declaration series; absent before the first header. */
6333
- baselineSeq;
6334
- /** Immutable request snapshot of the current baseline and resolved updates. */
6335
- history = deepFreeze({
6336
- tools: [],
6337
- updates: []
6338
- });
6339
- /**
6340
- * Consume the next committed event in log order.
6341
- * @param event - a session event, including inherited events during restoration.
6342
- */
6343
- apply(event) {
6344
- if (event.type === "request/header") {
6345
- const tools = event.data.header.tools ?? [];
6346
- this.headers.set(event.seq, tools);
6347
- const redeclared = tools.some((tool) => {
6348
- const before = this.declared.get(tool.name);
6349
- return before !== void 0 && JSON.stringify(before) !== JSON.stringify(tool);
6350
- });
6351
- if (this.baselineSeq === void 0 || event.data.reason === "series" || event.data.startsSeries || redeclared) {
6352
- this.baselineSeq = event.seq;
6353
- this.declared = new Map(tools.map((tool) => [tool.name, tool]));
6354
- this.history = deepFreeze({
6355
- tools,
6356
- updates: []
6357
- });
6358
- this.available = new Set(tools.map((tool) => tool.name));
6359
- }
6360
- this.active = tools;
6361
- } else if (event.type === "developer/message") {
6362
- const { message, headerSeq } = event.data;
6363
- const definitions = headerSeq === void 0 ? [] : this.headers.get(headerSeq);
6364
- const additions = message.content.flatMap((block) => {
6365
- if (block.type !== "tool-addition") return [];
6366
- const tool = definitions?.find((tool) => tool.name === block.toolName);
6367
- if (tool === void 0) throw new Error(`tool history: missing definition for ${block.toolName}`);
6368
- return [tool];
6369
- });
6370
- for (const tool of additions) this.declared.set(tool.name, tool);
6371
- for (const block of message.content) if (block.type === "tool-addition") this.available.add(block.toolName);
6372
- else if (block.type === "tool-removal") this.available.delete(block.toolName);
6373
- this.history = deepFreeze({
6374
- tools: this.history.tools,
6375
- updates: [...this.history.updates, {
6376
- messageId: message.id,
6377
- additions
6378
- }]
6379
- });
6380
- }
6381
- }
6382
- /**
6383
- * Read an immutable snapshot; subsequent events do not mutate it.
6384
- * @returns initial declarations and historically resolved additions for the current series.
6385
- */
6386
- snapshot() {
6387
- if (this.active.length !== this.available.size || this.active.some((tool) => !this.available.has(tool.name))) return deepFreeze({
6388
- tools: this.active,
6389
- updates: []
6390
- });
6391
- return this.history;
6392
- }
6393
- };
6394
- //#endregion
6395
- //#region ../../core/session/src/index.ts
6396
6366
  /** Validate and freeze one detached creation header in place. */
6397
6367
  function validateSessionHeader(id, input) {
6398
6368
  if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error("session header is not a plain JSON record");
@@ -6412,7 +6382,13 @@ function validateSessionHeader(id, input) {
6412
6382
  if (record.agentPreset !== void 0 && typeof record.agentPreset !== "string") throw new Error("session header agentPreset must be a string");
6413
6383
  return deepFreeze(record);
6414
6384
  }
6415
- /** Validate and freeze one exclusively owned persistence header in place. */
6385
+ /**
6386
+ * Validate and freeze one exclusively owned persistence header in place.
6387
+ * @param id - Session identity the header must carry.
6388
+ * @param input - decoded header, owned by the caller and frozen in place.
6389
+ * @returns the validated, deeply frozen header.
6390
+ * @throws when `input` is not a plain JSON record or fails header validation.
6391
+ */
6416
6392
  function validateRestoredSessionHeader(id, input) {
6417
6393
  if (input !== null && typeof input === "object" && !Array.isArray(input)) {
6418
6394
  const prototype = Reflect.getPrototypeOf(input);
@@ -6420,7 +6396,13 @@ function validateRestoredSessionHeader(id, input) {
6420
6396
  }
6421
6397
  return validateSessionHeader(id, input);
6422
6398
  }
6423
- /** Detach, validate, and freeze the creation metadata published by a session. */
6399
+ /**
6400
+ * Detach, validate, and freeze the creation metadata published by a session.
6401
+ * @param id - Session identity the header must carry.
6402
+ * @param source - borrowed header; omitted synthesizes a minimal current-format header.
6403
+ * @returns a validated, deeply frozen copy.
6404
+ * @throws when `source` is not losslessly JSON-serializable or fails header validation.
6405
+ */
6424
6406
  function snapshotSessionHeader(id, source) {
6425
6407
  const snapshot = snapshotJsonValue(source === void 0 ? {
6426
6408
  version: 4,
@@ -6431,33 +6413,6 @@ function snapshotSessionHeader(id, source) {
6431
6413
  if (snapshot === void 0) throw new Error("session header is not losslessly JSON-serializable");
6432
6414
  return validateSessionHeader(id, snapshot);
6433
6415
  }
6434
- /**
6435
- * Validate an exclusively owned event and deeply freeze its identified message
6436
- * without copying the event. The caller transfers an object graph that no
6437
- * producer retains and that shares no mutable children with another event.
6438
- * Use {@link snapshotSessionEvent} when exclusive ownership is not guaranteed.
6439
- * @param event - exclusively owned event imported across a trusted boundary.
6440
- * @returns the same event object with a validated, deeply frozen message.
6441
- * @throws when event-local surface metadata, request-header fields, or message invariants are invalid; history relations are not checked.
6442
- */
6443
- function adoptSessionEvent(event) {
6444
- validateSessionEventData(event, `session event at seq ${event.seq}`);
6445
- validateSurfaceMetadata(event);
6446
- assertMessageEventShape(event, `session event at seq ${event.seq}`);
6447
- switch (event.type) {
6448
- case "user/message":
6449
- deepFreeze(event.data);
6450
- break;
6451
- case "developer/message":
6452
- case "system/message":
6453
- case "assistant/message":
6454
- case "tool/result":
6455
- deepFreeze(event.data.message);
6456
- break;
6457
- default: break;
6458
- }
6459
- return event;
6460
- }
6461
6416
  /** Validate the fixed event envelope after one-pass JSON materialization. */
6462
6417
  function assertSessionEventEnvelope(value, index) {
6463
6418
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`seed event at index ${index} has an invalid event envelope`);
@@ -6539,7 +6494,45 @@ const MESSAGE_ROLE_BY_TYPE = {
6539
6494
  "assistant/message": "assistant",
6540
6495
  "tool/result": "tool"
6541
6496
  };
6542
- /** Validate only the event-specific invariants needed to safely replay a message. */
6497
+ /** Validate source attribution without rejecting unrelated metadata fields. */
6498
+ function assertSystemSectionMetadata(sourceRecord, content, subject) {
6499
+ for (const marker of ["complete", "reset"]) if (sourceRecord[marker] !== void 0 && sourceRecord[marker] !== true) throw new Error(`${subject} has invalid ${marker} system prompt marker`);
6500
+ const sections = sourceRecord["sections"];
6501
+ if (sections === void 0) {
6502
+ if (sourceRecord["reset"] !== void 0) throw new Error(`${subject} requires system section attribution`);
6503
+ return;
6504
+ }
6505
+ if (!Array.isArray(sections) || !Array.isArray(content) || content.some((block) => typeof block !== "object" || block === null || !("type" in block) || block.type !== "text" || !("text" in block) || typeof block.text !== "string")) throw new Error(`${subject} has invalid system section attribution`);
6506
+ const names = /* @__PURE__ */ new Set();
6507
+ const indices = /* @__PURE__ */ new Set();
6508
+ const entries = sections;
6509
+ for (const section of entries) {
6510
+ if (typeof section !== "object" || section === null || !("name" in section) || typeof section.name !== "string" || section.name.length === 0) throw new Error(`${subject} has invalid system section attribution`);
6511
+ if (!("state" in section) || section.state !== "active" && section.state !== "retired") throw new Error(`${subject} has invalid system section attribution`);
6512
+ if (section.state === "active" && (!("order" in section) || typeof section.order !== "number" || !Number.isFinite(section.order))) throw new Error(`${subject} has invalid system section attribution`);
6513
+ const contentIndex = "contentIndex" in section ? section.contentIndex : void 0;
6514
+ if (section.state === "retired" && contentIndex !== void 0) throw new Error(`${subject} has invalid system section attribution`);
6515
+ const references = section.state === "active" ? [contentIndex] : [];
6516
+ const noticeIndex = "noticeIndex" in section ? section.noticeIndex : void 0;
6517
+ if (noticeIndex !== void 0) {
6518
+ if (!Array.isArray(noticeIndex)) throw new Error(`${subject} has invalid system section attribution`);
6519
+ const notices = noticeIndex;
6520
+ references.push(...notices);
6521
+ }
6522
+ if (names.has(section.name)) throw new Error(`${subject} has invalid system section attribution`);
6523
+ names.add(section.name);
6524
+ for (const index of references) {
6525
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= content.length || indices.has(index)) throw new Error(`${subject} has invalid system section attribution`);
6526
+ indices.add(index);
6527
+ }
6528
+ }
6529
+ }
6530
+ /**
6531
+ * Validate only the event-specific invariants needed to safely replay a message.
6532
+ * @param event - candidate event record; events that produce no message pass unchecked.
6533
+ * @param subject - description of the event that prefixes each error message.
6534
+ * @throws when a message event lacks its message or has an invalid role, source, or content.
6535
+ */
6543
6536
  function assertMessageEventShape(event, subject) {
6544
6537
  const type = event["type"];
6545
6538
  if (!isMessageEventType(type)) return;
@@ -6556,6 +6549,7 @@ function assertMessageEventShape(event, subject) {
6556
6549
  const sourceRecord = source;
6557
6550
  if (type === "system/message") {
6558
6551
  if (sourceRecord["kind"] !== "system-prompt") throw new Error(`${subject} message must have system-prompt source`);
6552
+ assertSystemSectionMetadata(sourceRecord, messageRecord["content"], subject);
6559
6553
  return;
6560
6554
  }
6561
6555
  if (type === "assistant/message") {
@@ -6572,464 +6566,146 @@ function hasProviderModel(value) {
6572
6566
  const pair = value;
6573
6567
  return typeof pair["provider"] === "string" && pair["provider"].length > 0 && typeof pair["model"] === "string" && pair["model"].length > 0;
6574
6568
  }
6575
- /** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
6576
- function collectSessionCallbacks(ctx, args) {
6577
- return [...ctx.events.dispatch("emit", args)];
6578
- }
6579
- /** Invoke one resolved observe-only listener snapshot with per-listener containment. */
6580
- function invokeContainedSessionObservers(ctx, name, id, args, callbacks) {
6581
- for (const callback of callbacks) try {
6582
- const returned = callback(...args);
6583
- Promise.resolve(returned).catch((error) => {
6584
- ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`);
6585
- });
6586
- } catch (error) {
6587
- ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`);
6588
- }
6589
- }
6590
- /** Store-owned Sessions retain a null entry while unentered; absent keys are independent. */
6591
- const attachments = /* @__PURE__ */ new WeakMap();
6592
- /**
6593
- * Grammar of a {@link PluginRecordType}: `plugin:` followed by
6594
- * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
6595
- * each segment starting with a letter or digit.
6596
- */
6597
- const PLUGIN_RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/u;
6598
6569
  /**
6599
- * Whether one event type name follows the plugin record grammar.
6600
- * @param type - an event type name.
6601
- * @returns whether the name is a {@link PluginRecordType}.
6570
+ * Validate one seed event's lossless JSON form, envelope, and position.
6571
+ * @param source - borrowed (`snapshot`) or adopted event at `index`.
6572
+ * @param index - position in the seed.
6573
+ * @param mode - whether the event is copied before validation.
6574
+ * @returns the detached copy in `snapshot` mode, otherwise `source`.
6575
+ * @throws when the event is not losslessly JSON-serializable, has an invalid envelope, or its seq is not `index`.
6602
6576
  */
6603
- function isPluginRecordType(type) {
6604
- return PLUGIN_RECORD_TYPE.test(type);
6577
+ function validateSeedEvent(source, index, mode) {
6578
+ const snapshot = mode === "snapshot" ? snapshotJsonValue(source) : source;
6579
+ if (snapshot === void 0) throw new Error(`seed event at index ${index} is not losslessly JSON-serializable`);
6580
+ assertSessionEventEnvelope(snapshot, index);
6581
+ if (snapshot.seq !== index) throw new Error(`seed event at index ${index} has seq ${snapshot.seq} (expected ${index}); seed must be contiguous from 0`);
6582
+ return snapshot;
6605
6583
  }
6606
6584
  /**
6607
- * Type one constructed plugin record as a log event after checking its type
6608
- * against the plugin record grammar. A restored Session already holds events
6609
- * whose types are outside `SessionEventMap` when they are marked ignorable;
6610
- * a plugin record is such an event.
6611
- * @param value - the frozen record envelope built by {@link Session}.
6612
- * @throws when the record type is outside the plugin record grammar.
6585
+ * Admit one validated seed event through the surface transition.
6586
+ * @param event - validated event at `index`, not yet in the log `surface` reads.
6587
+ * @param index - position in the seed.
6588
+ * @param surface - incremental surface validator carrying the message interpreters.
6589
+ * @throws `invalid seed event at index <index>: …` when the surface rejects the event.
6613
6590
  */
6614
- function assertPluginRecordEvent(value) {
6615
- const { type } = value;
6616
- if (!isPluginRecordType(type)) throw new Error(`plugin record type "${type}" must be "plugin:" followed by lowercase slash-separated segments`);
6591
+ function replaySurfaceEvent(event, index, surface) {
6592
+ try {
6593
+ surface.validateNext(event);
6594
+ } catch (error) {
6595
+ throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : "invalid surface metadata"}`);
6596
+ }
6597
+ }
6598
+ /**
6599
+ * Validate seed events in order and push each accepted event into `log`, which `surface` reads.
6600
+ * Each event passes {@link validateSeedEvent} and then {@link replaySurfaceEvent} before it enters `log`.
6601
+ * @param seed - borrowed or adopted events.
6602
+ * @param mode - `snapshot` pushes deeply frozen copies; an event state pushes the adopted events.
6603
+ * @param log - empty log that `surface` was constructed over.
6604
+ * @param surface - incremental surface validator carrying the message interpreters.
6605
+ * @throws on the first invalid event; `log` then holds the accepted prefix.
6606
+ */
6607
+ function acceptSeedEvents(seed, mode, log, surface) {
6608
+ for (const [index, source] of seed.entries()) {
6609
+ const snapshot = validateSeedEvent(source, index, mode);
6610
+ replaySurfaceEvent(snapshot, index, surface);
6611
+ log.push(mode === "snapshot" ? deepFreeze(snapshot) : snapshot);
6612
+ }
6613
+ }
6614
+ /** Whether one event is the tagged inherited marker `session/end-seed { inherited: true }`. */
6615
+ function isInheritedSeedMarker(event) {
6616
+ return event?.type === "session/end-seed" && event.data.inherited === true;
6617
+ }
6618
+ /**
6619
+ * Validate the inherited cut of a constructed log against its validated header.
6620
+ * @param header - validated header.
6621
+ * @param hasSeed - whether construction received a seed (an empty seed counts).
6622
+ * @param supplied - inherited event count supplied by the caller.
6623
+ * @param log - accepted seed events.
6624
+ * @param mode - construction mode; only `snapshot` requires a fresh seeded seed to equal its inherited prefix or mark its cut.
6625
+ * @returns the inherited event count, 0 when omitted for an unseeded header.
6626
+ * @throws when the cut is missing, inconsistent with `isSeeded`, beyond the log, or not the final inherited marker.
6627
+ */
6628
+ function validateInheritedCut(header, hasSeed, supplied, log, mode) {
6629
+ if (header.isSeeded && !hasSeed) throw new Error("seeded session requires an explicit constructor seed");
6630
+ if (header.isSeeded && supplied === void 0) throw new Error("seeded session requires an inherited event count");
6631
+ const inheritedEventCount = SessionLogOffset(supplied ?? 0);
6632
+ if (!header.isSeeded && inheritedEventCount !== 0) throw new Error("unseeded session inherited event count must be 0");
6633
+ if (inheritedEventCount > log.length) throw new Error("session inherited event count exceeds its event log");
6634
+ const markedSeed = isInheritedSeedMarker(log[inheritedEventCount]);
6635
+ if (mode === "snapshot" && header.isSeeded && inheritedEventCount !== log.length && !markedSeed) throw new Error("seeded session constructor seed must equal its inherited prefix or mark its inherited cut");
6636
+ if (markedSeed && log.slice(inheritedEventCount + 1).some(isInheritedSeedMarker)) throw new Error("session inherited event count must identify the final inherited marker");
6637
+ return inheritedEventCount;
6617
6638
  }
6618
- /** Copy live append inputs before sequence assignment. */
6619
- function snapshotAppend(type, data, opts, subject) {
6620
- const surfaceOp = opts?.surfaceOp;
6621
- const sourceEventSeqs = opts?.sourceEventSeqs;
6622
- const dataSnapshot = snapshotJsonValue(data);
6623
- if (dataSnapshot === void 0) throw new Error(`${subject} carries non-JSON-serializable data`);
6624
- const surface = snapshotJsonValue({
6625
- ...sourceEventSeqs === void 0 ? {} : { sourceEventSeqs },
6626
- ...surfaceOp === void 0 ? {} : { surfaceOp }
6627
- });
6628
- if (surface === void 0) throw new Error(`${subject} carries non-JSON-serializable surface metadata`);
6639
+ /**
6640
+ * Validate a header, seed, and inherited cut in Session construction order.
6641
+ * An event-state `mode` validates the header first; `snapshot` validates the
6642
+ * events first. Each event passes the surface transition before the next is read.
6643
+ * @param id - Session identity the header must carry.
6644
+ * @param header - borrowed (`snapshot`) or adopted header; omitted synthesizes a minimal header in `snapshot` mode.
6645
+ * @param seed - borrowed or adopted events; omitted means no seed.
6646
+ * @param inheritedEventCount - exact fork-inherited prefix length; required when the header is seeded.
6647
+ * @param mode - construction mode.
6648
+ * @param events - empty log that `surface` was constructed over; receives the accepted events.
6649
+ * @param surface - incremental surface validator carrying the message interpreters.
6650
+ * @returns the validated header and inherited cut.
6651
+ * @throws on the first invalid header field, event envelope, sequence, surface transition, or inherited cut.
6652
+ */
6653
+ function checkSessionLog(id, header, seed, inheritedEventCount, mode, events, surface) {
6654
+ const restoredHeader = mode === "snapshot" ? void 0 : validateRestoredSessionHeader(id, header);
6655
+ if (seed !== void 0) acceptSeedEvents(seed, mode, events, surface);
6656
+ const checkedHeader = restoredHeader ?? snapshotSessionHeader(id, header);
6629
6657
  return {
6630
- type,
6631
- data: dataSnapshot,
6632
- surface
6658
+ header: checkedHeader,
6659
+ inheritedEventCount: validateInheritedCut(checkedHeader, seed !== void 0, inheritedEventCount, events, mode)
6633
6660
  };
6634
6661
  }
6635
- /** Construct and validate one live event from detached inputs. */
6636
- function createAppendEvent(snapshot, seq) {
6637
- const { type, data, surface } = snapshot;
6638
- const event = deepFreeze({
6639
- type,
6640
- seq,
6641
- time: Date.now(),
6642
- data,
6643
- ...surface
6644
- });
6645
- validateSessionEventData(event, `session event "${type}" at seq ${seq}`);
6646
- return event;
6662
+ /**
6663
+ * Validate a header and event log with every check that constructing a Session
6664
+ * performs, in the same order and with the same errors, without constructing one.
6665
+ * Without `eventState` the checks match `Session.create`: events and header are
6666
+ * copied before validation. With it they match `Session.fromRestore`, which
6667
+ * validates and deeply freezes `header` in place and leaves events uncopied.
6668
+ * Embedded Assistant streams are not replayed.
6669
+ * @param header - header whose `id` is the Session identity.
6670
+ * @param events - seed events; omitted means no seed.
6671
+ * @param inheritedEventCount - exact fork-inherited prefix length; required when `header.isSeeded`.
6672
+ * @param eventState - aliasing state of adopted events; omitted for borrowed events.
6673
+ * @param projections - message interpreters for plugin-owned events.
6674
+ * @throws on the first invalid header field, event envelope, sequence, surface transition, or inherited cut.
6675
+ */
6676
+ function validateSessionLog(header, events, inheritedEventCount, eventState, projections = []) {
6677
+ const log = [];
6678
+ checkSessionLog(header.id, header, events, inheritedEventCount, eventState ?? "snapshot", log, new SurfaceManager(log, SessionLogOffset(0), projections));
6647
6679
  }
6680
+ //#endregion
6681
+ //#region ../../core/session/src/index.ts
6648
6682
  /**
6649
- * An event-sourced session: an append-only log of {@link SessionEvent}s.
6650
- *
6651
- * Plain class (not a Service) — create live instances via
6652
- * `ctx.sessions.create()` and detached instances via {@link create}.
6653
- * Seeding with an existing event log replays/forks a session.
6654
- * @typert object
6655
- */
6656
- var Session = class Session {
6657
- log = [];
6658
- batchPublication;
6659
- /** Single incremental owner of surface acceptance and projection state. */
6660
- surfaceManager;
6661
- /** The ordered surface over this session's event log. */
6662
- get surface() {
6663
- return this.surfaceManager;
6664
- }
6665
- /**
6666
- * Detached, deep-frozen creation metadata (format version, cwd, lineage,
6667
- * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
6668
- * `Session` is created without a store-owned header, a minimal header is
6669
- * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
6670
- * `session.header` is always present. Kept out of the event log — it is a
6671
- * storage concern, not replayable conversation state.
6672
- */
6673
- header;
6674
- /** Number of leading events inherited from this Session's fork parent. */
6675
- inheritedEventCount;
6676
- /** The session identity, derived from its durable header's single copy. */
6677
- get id() {
6678
- return this.header.id;
6679
- }
6680
- /**
6681
- * The constructor seed length (0 without one), before any marker appended
6682
- * during construction. Seed events never publish on `session/event`. A
6683
- * marker appended before the store attaches occupies this seq without
6684
- * publishing either; otherwise this seq is available for the next append.
6685
- *
6686
- * This in-process offset is not persisted. A fork seed can already contain
6687
- * the child's inherited marker and synthetic closers, so its child-owned
6688
- * history starts at {@link inheritedEventCount}, before this offset. A
6689
- * resumed Session's seed contains its full stored log, while its inherited
6690
- * count keeps the durable fork cut. Consumers needing complete canonical
6691
- * history start at seq 0.
6692
- */
6693
- firstLiveSeq;
6694
- /**
6695
- * First event produced for this object lifecycle. A new fork includes its
6696
- * child-owned seed marker and closers; a restored Session starts after its
6697
- * complete stored prefix. This in-process capture offset is not persisted.
6698
- */
6699
- firstLifecycleSeq;
6700
- /**
6701
- * Create a detached session by validating and snapshotting borrowed seed
6702
- * events and storage metadata.
6703
- * @param id - session identity.
6704
- * @param seed - optional borrowed replay or fork events.
6705
- * @param header - optional borrowed storage metadata.
6706
- * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
6707
- * @param projections - pure interpreters for plugin-owned message changes.
6708
- * @returns a detached session.
6709
- * @throws when a seed event requires a missing message interpreter or fails validation.
6710
- */
6711
- static create(id, seed, header, inheritedEventCount, projections) {
6712
- return new Session(id, seed, header, "snapshot", inheritedEventCount, projections);
6713
- }
6714
- /**
6715
- * Restore a detached session by adopting an independently owned or deeply frozen seed.
6716
- * Runtime-required event fields, event envelopes, sequence continuity, surface
6717
- * transitions, and header fields are validated without copying or freezing events.
6718
- * Embedded Assistant streams remain opaque until a stream consumer or storage
6719
- * verifier reads them.
6720
- * @param id - restored session identity.
6721
- * @param seed - independently owned or deeply frozen events.
6722
- * @param header - independently owned storage metadata.
6723
- * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
6724
- * @param eventState - aliasing state carried from the operation that produced the seed.
6725
- * @param projections - pure interpreters for plugin-owned message changes.
6726
- * @returns a restored detached session.
6727
- * @throws when a seed event requires a missing message interpreter or fails validation.
6728
- */
6729
- static fromRestore(id, seed, header, inheritedEventCount, eventState, projections) {
6730
- return new Session(id, seed, header, eventState, inheritedEventCount, projections);
6731
- }
6732
- constructor(id, seed, header, mode = "snapshot", suppliedInheritedEventCount, projections = []) {
6733
- this.surfaceManager = new SurfaceManager(this.log, SessionLogOffset(0), projections);
6734
- const restoredHeader = mode === "snapshot" ? void 0 : validateRestoredSessionHeader(id, header);
6735
- if (seed !== void 0) for (const [index, source] of seed.entries()) {
6736
- const snapshot = mode === "snapshot" ? snapshotJsonValue(source) : source;
6737
- if (snapshot === void 0) throw new Error(`seed event at index ${index} is not losslessly JSON-serializable`);
6738
- assertSessionEventEnvelope(snapshot, index);
6739
- if (snapshot.seq !== index) throw new Error(`seed event at index ${index} has seq ${snapshot.seq} (expected ${index}); seed must be contiguous from 0`);
6740
- try {
6741
- this.surfaceManager.validateNext(snapshot);
6742
- } catch (error) {
6743
- throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : "invalid surface metadata"}`);
6744
- }
6745
- this.log.push(mode === "snapshot" ? deepFreeze(snapshot) : snapshot);
6746
- }
6747
- this.firstLiveSeq = SessionLogOffset(this.log.length);
6748
- this.header = restoredHeader ?? snapshotSessionHeader(id, header);
6749
- if (this.header.isSeeded && seed === void 0) throw new Error("seeded session requires an explicit constructor seed");
6750
- if (this.header.isSeeded && suppliedInheritedEventCount === void 0) throw new Error("seeded session requires an inherited event count");
6751
- const inheritedEventCount = SessionLogOffset(suppliedInheritedEventCount ?? 0);
6752
- if (!this.header.isSeeded && inheritedEventCount !== 0) throw new Error("unseeded session inherited event count must be 0");
6753
- if (inheritedEventCount > this.log.length) throw new Error("session inherited event count exceeds its event log");
6754
- const seedMarker = this.log[inheritedEventCount];
6755
- const markedSeed = seedMarker?.type === "session/end-seed" && seedMarker.data.inherited === true;
6756
- if (mode === "snapshot" && this.header.isSeeded && inheritedEventCount !== this.log.length && !markedSeed) throw new Error("seeded session constructor seed must equal its inherited prefix or mark its inherited cut");
6757
- if (markedSeed && this.log.slice(inheritedEventCount + 1).some((event) => event.type === "session/end-seed" && event.data.inherited === true)) throw new Error("session inherited event count must identify the final inherited marker");
6758
- this.inheritedEventCount = inheritedEventCount;
6759
- this.firstLifecycleSeq = mode === "snapshot" && this.header.isSeeded ? inheritedEventCount : this.firstLiveSeq;
6760
- if (seed !== void 0 && mode === "snapshot" && this.header.isSeeded && !markedSeed) this.append("session/end-seed", { inherited: true });
6761
- else if (seed !== void 0 && !(mode === "snapshot" && this.header.isSeeded) && this.log.at(-1)?.type !== "session/end-seed") this.append("session/end-seed", {});
6762
- }
6763
- /** Cached immutable full snapshot of the private append-only log. */
6764
- eventsSnapshot;
6765
- /**
6766
- * Return the immutable event stored at one exact sequence number.
6767
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
6768
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
6769
- * @param seq - event sequence number.
6770
- * @returns the accepted event, or undefined when the log does not contain it.
6771
- */
6772
- eventAt(seq) {
6773
- return this.log[seq];
6774
- }
6775
- /**
6776
- * Materialize an immutable snapshot of a half-open event sequence range.
6777
- * A full current snapshot is reused until the next append; every previously
6778
- * returned snapshot remains stable after later appends.
6779
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
6780
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
6781
- * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
6782
- * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
6783
- * @returns a frozen array of the selected deeply frozen events.
6784
- */
6785
- snapshotEvents(fromSeq = SessionLogOffset(0), toSeqExclusive = this.seq) {
6786
- if (fromSeq === 0 && toSeqExclusive === this.log.length) {
6787
- this.eventsSnapshot ??= Object.freeze([...this.log]);
6788
- return this.eventsSnapshot;
6789
- }
6790
- return Object.freeze(this.log.slice(fromSeq, toSeqExclusive));
6791
- }
6792
- /**
6793
- * Return this Session's events after its fork-inherited prefix.
6794
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
6795
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
6796
- * @returns a fresh array containing child-owned events in log order.
6797
- */
6798
- ownEvents() {
6799
- return this.snapshotEvents(this.inheritedEventCount);
6800
- }
6801
- /**
6802
- * Whether one existing event position is outside the fork-inherited prefix.
6803
- * @param seq - event position in this Session.
6804
- * @returns true when the event belongs to this Session rather than its parent.
6805
- */
6806
- isOwnSeq(seq) {
6807
- return seq >= this.inheritedEventCount && seq < this.seq;
6808
- }
6809
- /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
6810
- get seq() {
6811
- return SessionLogOffset(this.log.length);
6812
- }
6813
- /** Current event while synchronously notifying a batch's observers. */
6814
- get currentBatchPublication() {
6815
- return this.batchPublication;
6816
- }
6817
- append(type, data, ...opts) {
6818
- if (typeof type !== "string") return this.#appendEvents(type);
6819
- this.publicationEntry();
6820
- const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`);
6821
- const entry = this.publicationEntry();
6822
- const event = createAppendEvent(snapshot, SessionSeq(this.log.length));
6823
- this.commit(event, entry);
6824
- return event;
6825
- }
6826
- /**
6827
- * Validate and publish consecutive events together. Observers see the complete log.
6828
- * @param inputs - event payloads and surface intents in commit order.
6829
- * @returns immutable committed events in the same order.
6830
- * @throws before changing the log if any candidate or synchronous dispatch validation fails.
6831
- */
6832
- #appendEvents(inputs) {
6833
- this.publicationEntry();
6834
- if (inputs.length === 0) return [];
6835
- const snapshots = Array.from({ length: inputs.length }, (_, index) => {
6836
- const input = inputs.at(index);
6837
- if (input === void 0) throw new Error(`session batch has an empty member at index ${index}`);
6838
- const [type, data, surfaceOpts] = input;
6839
- return snapshotAppend(type, data, surfaceOpts, `session batch member ${index} ("${type}")`);
6840
- });
6841
- const entry = this.publicationEntry();
6842
- const startSeq = this.log.length;
6843
- const events = snapshots.map((snapshot, index) => createAppendEvent(snapshot, SessionSeq(startSeq + index)));
6844
- const acceptSurface = this.surfaceManager.prepareBatch(events);
6845
- if (entry !== void 0) entry.appending = true;
6846
- try {
6847
- const publications = entry === void 0 ? [] : events.map((event) => {
6848
- const args = [this, event];
6849
- return {
6850
- event,
6851
- args,
6852
- callbacks: collectSessionCallbacks(entry.emitCtx, [
6853
- entry.carrier,
6854
- "session/event",
6855
- ...args
6856
- ])
6857
- };
6858
- });
6859
- for (const event of events) this.log.push(event);
6860
- this.eventsSnapshot = void 0;
6861
- acceptSurface();
6862
- if (entry !== void 0) for (const { event, args, callbacks } of publications) {
6863
- this.batchPublication = event;
6864
- invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, args, callbacks);
6865
- }
6866
- } finally {
6867
- this.batchPublication = void 0;
6868
- if (entry !== void 0) {
6869
- entry.appending = false;
6870
- if (entry.detachRequested) entry.detach();
6871
- }
6872
- }
6873
- return events;
6874
- }
6875
- static {}
6876
- /**
6877
- * Commit one plugin record; {@link appendPluginRecord} is the only caller.
6878
- * @param type - record type, checked against the plugin record grammar.
6879
- * @param data - JSON payload, snapshotted before it enters the log.
6880
- * @returns the record's sequence number.
6881
- */
6882
- #appendRecord(type, data) {
6883
- this.publicationEntry();
6884
- const dataSnapshot = snapshotJsonValue(data);
6885
- if (dataSnapshot === void 0) throw new Error(`plugin record "${type}" carries non-JSON-serializable data`);
6886
- const entry = this.publicationEntry();
6887
- const record = deepFreeze({
6888
- type,
6889
- seq: SessionSeq(this.log.length),
6890
- time: Date.now(),
6891
- data: dataSnapshot,
6892
- ignorable: true
6893
- });
6894
- assertPluginRecordEvent(record);
6895
- this.commit(record, entry);
6896
- return record.seq;
6897
- }
6898
- /**
6899
- * Require announced membership for store-owned Sessions and refuse reentrant publication.
6900
- * @returns the current store attachment, or undefined for an independent Session.
6901
- */
6902
- publicationEntry() {
6903
- const entry = attachments.get(this);
6904
- if (entry === null) throw new Error(`session "${this.id}" cannot append outside a SessionStore`);
6905
- if (entry !== void 0 && entry.announcement !== "complete") throw new Error(`session "${this.id}" cannot append before session/created completes`);
6906
- if (entry?.appending) throw new Error("session append cannot reenter while another append is being published");
6907
- return entry;
6908
- }
6909
- /**
6910
- * Accept one frozen candidate at the next sequence number, enter it into the
6911
- * log, and notify `session/event` observers with per-listener containment.
6912
- * @param event - the candidate built at the current log length.
6913
- * @param entry - the attachment read before the candidate was built.
6914
- */
6915
- commit(event, entry) {
6916
- this.surfaceManager.validateNext(event);
6917
- if (entry !== void 0) entry.appending = true;
6918
- try {
6919
- const callbackArgs = [this, event];
6920
- const callbacks = entry === void 0 ? void 0 : collectSessionCallbacks(entry.emitCtx, [
6921
- entry.carrier,
6922
- "session/event",
6923
- ...callbackArgs
6924
- ]);
6925
- this.log.push(event);
6926
- this.eventsSnapshot = void 0;
6927
- if (entry !== void 0 && callbacks !== void 0) invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, callbackArgs, callbacks);
6928
- } finally {
6929
- if (entry !== void 0) {
6930
- entry.appending = false;
6931
- if (entry.detachRequested && entry.announcement !== "dispatching") entry.detach();
6932
- }
6933
- }
6934
- }
6935
- /** Cached fold of the request-header events — see {@link requestHeader}. */
6936
- headerFold;
6937
- /** Log position (events consumed) the header fold has reached. */
6938
- headerFoldSeq = 0;
6939
- /**
6940
- * The {@link EpochHeader} in force after the log's last header event — the
6941
- * header the NEXT request will be compared against — or undefined before
6942
- * the first `request/header` snapshot. The live, incrementally-maintained
6943
- * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
6944
- * once, when first seen, so a per-step read costs O(new events).
6945
- * @returns the folded header, or undefined when no header event exists yet.
6946
- */
6947
- requestHeader() {
6948
- if (this.headerFoldSeq < this.log.length) {
6949
- this.headerFold = deepFreeze(foldRequestHeader(this.log.slice(this.headerFoldSeq), this.headerFold));
6950
- this.headerFoldSeq = this.log.length;
6951
- }
6952
- return this.headerFold;
6953
- }
6954
- /** Cached fold of `request/context` events. */
6955
- contextFold;
6956
- contextFoldSeq = 0;
6957
- /**
6958
- * Return the latest resolved route metadata, or `undefined` before the first
6959
- * `request/context` event. Each event is folded once.
6960
- * @returns the latest immutable route metadata.
6961
- */
6962
- requestContext() {
6963
- if (this.contextFoldSeq < this.log.length) {
6964
- for (const event of this.log.slice(this.contextFoldSeq)) if (event.type === "request/context") this.contextFold = deepFreeze({ ...event.data });
6965
- this.contextFoldSeq = this.log.length;
6966
- }
6967
- return this.contextFold;
6968
- }
6969
- /** Cached historical tool definitions and updates for request projection. */
6970
- toolHistoryProjection = new ToolHistoryProjection();
6971
- /** Index of the next committed event not yet consumed by the tool-history fold. */
6972
- toolHistorySeq = 0;
6973
- /**
6974
- * Fold unseen committed events into capability-independent tool history.
6975
- * Initial access reconstructs inherited history; later reads consume only new events.
6976
- * @returns an immutable snapshot for LLM request projection, including historical addition definitions.
6977
- */
6978
- toolHistory() {
6979
- for (const event of this.log.slice(this.toolHistorySeq)) this.toolHistoryProjection.apply(event);
6980
- this.toolHistorySeq = this.log.length;
6981
- return this.toolHistoryProjection.snapshot();
6982
- }
6983
- /** The derived-message cache: frozen projections, extended per unseen node. */
6984
- derived = [];
6985
- /** Surface position (nodes projected) the cache has reached. */
6986
- derivedNodes = 0;
6987
- /** {@link SurfaceManager.contentGeneration} the cache was built under. */
6988
- derivedGeneration = 0;
6989
- /**
6990
- * Derive the LLM message history by walking the ordered sequences of
6991
- * message-producing events maintained by `surfaceOp` markers. The
6992
- * surface is the single source of derived history: every message-producing
6993
- * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
6994
- * turn boundary) is correctly absent, and a compaction `replace` deletes the
6995
- * shadowed nodes from the derivation. The projection rules are
6996
- * {@link deriveEventMessage}, with logged message projections applied
6997
- * without changing node membership or message identity.
6998
- *
6999
- * CACHED: pure tail growth costs O(new nodes); a replacement or message projection
7000
- * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is
7001
- * a fresh snapshot per call (later appends never grow an array a caller
7002
- * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
7003
- * Unchanged content reuses frozen event data; projected blocks are frozen
7004
- * derived copies. Consumers cannot mutate the log through either form.
7005
- * @returns a fresh array of the shared, frozen derived history.
7006
- */
7007
- deriveMessages() {
7008
- const surface = this.surface;
7009
- const nodes = surface.nodes;
7010
- const generation = surface.contentGeneration;
7011
- if (generation !== this.derivedGeneration) {
7012
- this.derived = [];
7013
- this.derivedNodes = 0;
7014
- this.derivedGeneration = generation;
7015
- }
7016
- for (const seq of nodes.slice(this.derivedNodes)) {
7017
- const msg = this.deriveEventMessage(this.log[seq]);
7018
- if (msg) this.derived.push(msg);
7019
- }
7020
- this.derivedNodes = nodes.length;
7021
- return [...this.derived];
7022
- }
7023
- /**
7024
- * Project one event with all committed message projections applied.
7025
- * The original durable event remains unchanged.
7026
- * @param event - the event to project.
7027
- * @returns the derived message, or null when the event produces none.
7028
- */
7029
- deriveEventMessage(event) {
7030
- return this.surfaceManager.deriveEventMessage(event);
6683
+ * Validate an exclusively owned event and deeply freeze its identified message
6684
+ * without copying the event. The caller transfers an object graph that no
6685
+ * producer retains and that shares no mutable children with another event.
6686
+ * Use {@link snapshotSessionEvent} when exclusive ownership is not guaranteed.
6687
+ * @param event - exclusively owned event imported across a trusted boundary.
6688
+ * @returns the same event object with a validated, deeply frozen message.
6689
+ * @throws when event-local surface metadata, request-header fields, or message invariants are invalid; history relations are not checked.
6690
+ */
6691
+ function adoptSessionEvent(event) {
6692
+ validateSessionEventData(event, `session event at seq ${event.seq}`);
6693
+ validateSurfaceMetadata(event);
6694
+ assertMessageEventShape(event, `session event at seq ${event.seq}`);
6695
+ switch (event.type) {
6696
+ case "user/message":
6697
+ deepFreeze(event.data);
6698
+ break;
6699
+ case "developer/message":
6700
+ case "system/message":
6701
+ case "assistant/message":
6702
+ case "tool/result":
6703
+ deepFreeze(event.data.message);
6704
+ break;
6705
+ default: break;
7031
6706
  }
7032
- };
6707
+ return event;
6708
+ }
7033
6709
  //#endregion
7034
6710
  //#region ../session-format/src/error.ts
7035
6711
  /** Error raised when a durable Session artifact cannot be restored or migrated losslessly. */
@@ -7609,7 +7285,7 @@ function validateStoredEvents(meta, events, location) {
7609
7285
  */
7610
7286
  function validateInstalledCurrentSessionHeader(header) {
7611
7287
  if (header.version !== 4) throw new Error(`installed Session format is v4, got v${header.version}`);
7612
- Session.fromRestore(SessionId(header.id), [], header, SessionLogOffset(0), "detached");
7288
+ validateSessionLog(header, [], SessionLogOffset(0), "detached");
7613
7289
  }
7614
7290
  /**
7615
7291
  * Validate current header, event envelopes, messages, surface operations, and seed cut through the installed Session package.
@@ -7618,7 +7294,7 @@ function validateInstalledCurrentSessionHeader(header) {
7618
7294
  */
7619
7295
  function validateInstalledCurrentSessionArtifact(artifact) {
7620
7296
  if (artifact.header.version !== 4) throw new Error(`installed Session format is v4, got v${artifact.header.version}`);
7621
- Session.fromRestore(SessionId(artifact.header.id), artifact.events, artifact.header, SessionLogOffset(artifact.inheritedEventCount), "detached", currentSessionMessageProjections);
7297
+ validateSessionLog(artifact.header, artifact.events, SessionLogOffset(artifact.inheritedEventCount), "detached", currentSessionMessageProjections);
7622
7298
  }
7623
7299
  //#endregion
7624
7300
  //#region ../session-format-v0-to-v1/src/dispositions.ts
@@ -13834,7 +13510,7 @@ async function verifyCurrentGeneration(path, compression, expectedId, expectedEv
13834
13510
  });
13835
13511
  if (generation.meta.id !== expectedId) throw new Error(`current session generation contains id "${generation.meta.id}", expected "${expectedId}"`);
13836
13512
  if (generation.events.length !== expectedEventCount) throw new Error(`current session generation contains ${generation.events.length} events, expected ${expectedEventCount}`);
13837
- Session.fromRestore(generation.meta.id, generation.events, generation.meta, generation.inheritedEventCount, "detached", currentSessionMessageProjections);
13513
+ validateSessionLog(generation.meta, generation.events, generation.inheritedEventCount, "detached", currentSessionMessageProjections);
13838
13514
  assertCurrentAssistantStreams(generation.events);
13839
13515
  return {
13840
13516
  identity: snapshot.identity,
@@ -14031,7 +13707,7 @@ async function removeTemporary(path, primaryFailure, internals) {
14031
13707
  async function removeCommittedTemporary(path, internals) {
14032
13708
  try {
14033
13709
  await internals.fs.rm(path);
14034
- } catch {}
13710
+ } catch (_redundantStageRemoveFailed) {}
14035
13711
  }
14036
13712
  async function publishCurrentExclusive(staged, currentPath, internals) {
14037
13713
  if (internals.platform === "win32") try {