@unieai/rabi-session-persistence-jsonl 0.2.1-rc.3 → 0.2.2-rc.5

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
@@ -680,110 +680,95 @@ function enumerableStringKeys(value) {
680
680
  function walkJsonValue(value, detach) {
681
681
  const ancestors = /* @__PURE__ */ new Set();
682
682
  let root;
683
- const assign = (destination, item) => {
684
- if (destination === void 0) return;
685
- if (destination.kind === "root") root = item;
686
- else if (destination.kind === "array") destination.target[destination.index] = item;
687
- else Object.defineProperty(destination.target, destination.key, {
683
+ let parent;
684
+ const assign = (item) => {
685
+ if (parent === void 0) {
686
+ if (detach) root = item;
687
+ } else if (parent.kind === "array") {
688
+ if (parent.target !== void 0) parent.target[parent.key] = item;
689
+ } else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {
688
690
  value: item,
689
691
  enumerable: true,
690
692
  configurable: true,
691
693
  writable: true
692
694
  });
693
695
  };
694
- const tasks = [{
695
- kind: "visit",
696
- value,
697
- ...detach ? { destination: { kind: "root" } } : {}
698
- }];
699
- for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
700
- if (task.kind === "leave") {
701
- ancestors.delete(task.source);
702
- continue;
703
- }
704
- if (task.kind === "array-item") {
705
- if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;
706
- tasks.push({
707
- kind: "visit",
708
- value: task.source[task.index],
709
- ...task.target === void 0 ? {} : { destination: {
696
+ const frames = [];
697
+ let current = value;
698
+ for (;;) {
699
+ if (current === null) assign(null);
700
+ else if (typeof current === "boolean" || typeof current === "string") assign(current);
701
+ else if (typeof current === "number") {
702
+ if (!Number.isFinite(current) || Object.is(current, -0)) return void 0;
703
+ assign(current);
704
+ } else {
705
+ if (typeof current !== "object") return void 0;
706
+ if (ancestors.has(current)) return void 0;
707
+ if (Array.isArray(current)) {
708
+ if (!hasPlainArrayPrototype(current)) return void 0;
709
+ const length = current.length;
710
+ if (Reflect.ownKeys(current).length !== length + 1) return void 0;
711
+ const target = detach ? [] : void 0;
712
+ if (target !== void 0) assign(target);
713
+ let indices;
714
+ if (!Number.isInteger(length)) {
715
+ indices = [];
716
+ for (let index = length - 1; index >= 0; index--) indices.push(index);
717
+ }
718
+ frames.push({
710
719
  kind: "array",
711
- target: task.target,
712
- index: task.index
713
- } }
714
- });
715
- continue;
716
- }
717
- if (task.kind === "object-property") {
718
- tasks.push({
719
- kind: "visit",
720
- value: task.source[task.key],
721
- ...task.target === void 0 ? {} : { destination: {
720
+ source: current,
721
+ length: indices?.length ?? length,
722
+ index: 0,
723
+ key: 0,
724
+ indices,
725
+ target
726
+ });
727
+ } else {
728
+ if (!hasPlainObjectPrototype(current)) return void 0;
729
+ const keys = enumerableStringKeys(current);
730
+ if (keys === void 0) return void 0;
731
+ const target = detach ? {} : void 0;
732
+ if (target !== void 0) assign(target);
733
+ frames.push({
722
734
  kind: "object",
723
- target: task.target,
724
- key: task.key
725
- } }
726
- });
727
- continue;
728
- }
729
- const current = task.value;
730
- if (current === null) {
731
- assign(task.destination, null);
732
- continue;
733
- }
734
- if (typeof current === "boolean" || typeof current === "string") {
735
- assign(task.destination, current);
736
- continue;
737
- }
738
- if (typeof current === "number") {
739
- if (!Number.isFinite(current) || Object.is(current, -0)) return void 0;
740
- assign(task.destination, current);
741
- continue;
742
- }
743
- if (typeof current !== "object") return void 0;
744
- if (ancestors.has(current)) return void 0;
745
- if (Array.isArray(current)) {
746
- if (!hasPlainArrayPrototype(current)) return void 0;
747
- const length = current.length;
748
- if (Reflect.ownKeys(current).length !== length + 1) return void 0;
749
- const target = detach ? [] : void 0;
750
- if (target !== void 0) assign(task.destination, target);
735
+ source: current,
736
+ keys,
737
+ index: 0,
738
+ key: "",
739
+ target
740
+ });
741
+ }
751
742
  ancestors.add(current);
752
- tasks.push({
753
- kind: "leave",
754
- source: current
755
- });
756
- for (let index = length - 1; index >= 0; index--) tasks.push({
757
- kind: "array-item",
758
- source: current,
759
- index,
760
- ...target === void 0 ? {} : { target }
761
- });
762
- continue;
763
743
  }
764
- if (!hasPlainObjectPrototype(current)) return void 0;
765
- const keys = enumerableStringKeys(current);
766
- if (keys === void 0) return void 0;
767
- const target = detach ? {} : void 0;
768
- if (target !== void 0) assign(task.destination, target);
769
- ancestors.add(current);
770
- tasks.push({
771
- kind: "leave",
772
- source: current
773
- });
774
- for (let index = keys.length - 1; index >= 0; index--) {
775
- const key = keys[index];
776
- /* v8 ignore next -- the loop is bounded by the captured key count. */
777
- if (key === void 0) return void 0;
778
- tasks.push({
779
- kind: "object-property",
780
- source: current,
781
- key,
782
- ...target === void 0 ? {} : { target }
783
- });
744
+ for (;;) {
745
+ const frame = frames.at(-1);
746
+ if (frame === void 0) return detach ? root : true;
747
+ const length = frame.kind === "array" ? frame.length : frame.keys.length;
748
+ if (frame.index >= length) {
749
+ ancestors.delete(frame.source);
750
+ frames.pop();
751
+ continue;
752
+ }
753
+ const index = frame.index++;
754
+ parent = frame;
755
+ if (frame.kind === "array") {
756
+ const key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];
757
+ /* v8 ignore next -- the loop is bounded by the captured index count. */
758
+ if (key === void 0) return void 0;
759
+ if (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;
760
+ frame.key = key;
761
+ current = frame.source[key];
762
+ } else {
763
+ const key = frame.keys[index];
764
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
765
+ if (key === void 0) return void 0;
766
+ frame.key = key;
767
+ current = frame.source[key];
768
+ }
769
+ break;
784
770
  }
785
771
  }
786
- return detach ? root : true;
787
772
  }
788
773
  /**
789
774
  * Validate and detach lossless JSON in one read per property.
@@ -1275,6 +1260,7 @@ var DisposableList = class {
1275
1260
  /** Shared symbols used to avoid public property-name collisions. */
1276
1261
  const symbols = {
1277
1262
  shadow: Symbol.for("cordis.shadow"),
1263
+ caller: Symbol.for("cordis.caller"),
1278
1264
  receiver: Symbol.for("cordis.receiver"),
1279
1265
  original: Symbol.for("cordis.original"),
1280
1266
  metadata: Symbol.for("cordis.metadata"),
@@ -1349,11 +1335,12 @@ function withProp(target, prop, value) {
1349
1335
  writable: false
1350
1336
  }));
1351
1337
  }
1352
- function createShadow(ctx, target, property, receiver) {
1338
+ function createShadow(useSite, target, property, receiver) {
1353
1339
  if (!property) return receiver;
1354
- const origin = Reflect.getOwnPropertyDescriptor(target, property)?.value;
1355
- if (!origin) return receiver;
1356
- return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
1340
+ const value = getPropertyDescriptor(target, property)?.value;
1341
+ if (!value) return receiver;
1342
+ const defSite = value[symbols.shadow] ?? value;
1343
+ return withProp(receiver, property, useSite.extend({ [symbols.shadow]: defSite }));
1357
1344
  }
1358
1345
  function createShadowMethod(ctx, value, outer, shadow) {
1359
1346
  return new Proxy(value, { apply: (target, thisArg, args) => {
@@ -1362,37 +1349,40 @@ function createShadowMethod(ctx, value, outer, shadow) {
1362
1349
  } });
1363
1350
  }
1364
1351
  function createTraceable(ctx, value, tracker) {
1365
- if (ctx[symbols.shadow] && !tracker.noShadow) ctx = Object.getPrototypeOf(ctx);
1352
+ const defSite = ctx[symbols.shadow] ?? ctx;
1353
+ const useSite = ctx[symbols.shadow] ? Object.getPrototypeOf(ctx) : ctx;
1366
1354
  const proxy = new Proxy(value, {
1367
1355
  get: (target, prop, receiver) => {
1368
1356
  if (prop === symbols.original) return target;
1369
- if (prop === tracker.property) return ctx;
1357
+ if (prop === symbols.caller) return defSite;
1358
+ if (prop === tracker.property) return useSite;
1370
1359
  if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
1371
- if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
1360
+ if (tracker.associate && useSite.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
1372
1361
  let shadow, innerValue;
1373
1362
  const desc = getPropertyDescriptor(target, prop);
1374
1363
  if (desc && "value" in desc) innerValue = desc.value;
1375
1364
  else {
1376
- shadow = createShadow(ctx, target, tracker.property, receiver);
1365
+ shadow = createShadow(useSite, target, tracker.property, receiver);
1377
1366
  innerValue = Reflect.get(target, prop, shadow);
1378
1367
  }
1379
1368
  const innerTracker = innerValue?.[symbols.tracker];
1380
- if (innerTracker) return createTraceable(ctx, innerValue, innerTracker);
1369
+ if (innerTracker) return createTraceable(useSite, innerValue, innerTracker);
1381
1370
  else if (!tracker.noShadow && typeof innerValue === "function") {
1382
- shadow ??= createShadow(ctx, target, tracker.property, receiver);
1383
- return createShadowMethod(ctx, innerValue, receiver, shadow);
1371
+ shadow ??= createShadow(useSite, target, tracker.property, receiver);
1372
+ return createShadowMethod(useSite, innerValue, receiver, shadow);
1384
1373
  } else return innerValue;
1385
1374
  },
1386
1375
  set: (target, prop, value, receiver) => {
1387
1376
  if (prop === symbols.original) return false;
1377
+ if (prop === symbols.caller) return false;
1388
1378
  if (prop === tracker.property) return false;
1389
1379
  if (typeof prop === "symbol") return Reflect.set(target, prop, value, receiver);
1390
- if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value, withProp(ctx, symbols.receiver, receiver));
1391
- const shadow = createShadow(ctx, target, tracker.property, receiver);
1380
+ if (tracker.associate && useSite.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value, withProp(ctx, symbols.receiver, receiver));
1381
+ const shadow = createShadow(useSite, target, tracker.property, receiver);
1392
1382
  return Reflect.set(target, prop, value, shadow);
1393
1383
  },
1394
1384
  apply: (target, thisArg, args) => {
1395
- return applyTraceable(proxy, target, thisArg, args);
1385
+ return applyTraceable(tracker.noShadow ? proxy : createShadow(useSite, target, tracker.property, proxy), target, thisArg, args);
1396
1386
  }
1397
1387
  });
1398
1388
  return proxy;
@@ -1404,7 +1394,8 @@ function applyTraceable(proxy, value, thisArg, args) {
1404
1394
  /** Create a callable service object that dispatches through `symbols.invoke`. */
1405
1395
  function createCallable(name, proto, tracker) {
1406
1396
  const self = function(...args) {
1407
- return applyTraceable(createTraceable(self["ctx"], self, tracker), self, this, args);
1397
+ const proxy = createTraceable(self["ctx"], self, tracker);
1398
+ return Reflect.apply(proxy, this, args);
1408
1399
  };
1409
1400
  defineProperty(self, "name", name);
1410
1401
  return Object.setPrototypeOf(self, proto);
@@ -1450,649 +1441,215 @@ function buildOuterStack(offset = 0) {
1450
1441
  return () => outerError.stack.split("\n").slice(3 + offset);
1451
1442
  }
1452
1443
  //#endregion
1453
- //#region ../../../vendor/cordis/src/events.ts
1444
+ //#region ../../../vendor/cordis/src/fiber.ts
1445
+ const kValidationError$1 = Symbol.for("ValidationError");
1446
+ /** Error raised when plugin configuration fails standard-schema validation. */
1447
+ var ValidationError$1 = class extends TypeError {
1448
+ name = "ValidationError";
1449
+ /**
1450
+ * Build the aggregated message from schema issues.
1451
+ *
1452
+ * @param issues — the standard-schema issues, one message line each.
1453
+ */
1454
+ constructor(issues) {
1455
+ super(`invalid config:\n` + issues.map((issue) => {
1456
+ if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
1457
+ else return ` - ${issue.message}`;
1458
+ }).join("\n"));
1459
+ }
1460
+ };
1461
+ Object.defineProperty(ValidationError$1.prototype, kValidationError$1, { value: true });
1454
1462
  /**
1455
- * Return whether an event result should stop a bail-style dispatch.
1463
+ * Validate and normalize config for a plugin runtime before it starts.
1456
1464
  *
1457
- * @param value — a listener's return value.
1458
- * @returns `true` unless `value` is `null`, `false`, or `undefined`.
1465
+ * @param runtime — the plugin runtime whose `Config` schema to apply.
1466
+ * @param config — the raw user config.
1467
+ * @returns the validated config, or `config` unchanged if the runtime has no schema.
1468
+ * @throws {ValidationError} when validation reports issues.
1459
1469
  */
1460
- function isBailed(value) {
1461
- return value !== null && value !== false && value !== void 0;
1470
+ function resolveConfig(runtime, config) {
1471
+ if (!runtime.Config) return config;
1472
+ const result = runtime.Config["~standard"].validate(config);
1473
+ if ("then" in result) throw new TypeError("Async config validation is not supported");
1474
+ if (result.issues) throw new ValidationError$1(result.issues);
1475
+ else return result.value;
1476
+ }
1477
+ const effectInertia = /* @__PURE__ */ new WeakMap();
1478
+ function runDisposable(dispose) {
1479
+ const result = dispose();
1480
+ return effectInertia.get(dispose)?.() ?? result;
1481
+ }
1482
+ /** Notify plugin teardown without allowing one observer to break ownership cleanup. */
1483
+ function emitPluginDisposed(context, fiber) {
1484
+ const args = ["internal/plugin", fiber];
1485
+ let callbacks;
1486
+ try {
1487
+ callbacks = context.events.dispatch("emit", args);
1488
+ } catch (error) {
1489
+ context.logger.error(error);
1490
+ return;
1491
+ }
1492
+ for (const callback of callbacks) try {
1493
+ const returned = callback(...args);
1494
+ Promise.resolve(returned).catch((error) => context.logger.error(error));
1495
+ } catch (error) {
1496
+ context.logger.error(error);
1497
+ }
1462
1498
  }
1499
+ /** Framework error with a stable machine-readable code. */
1500
+ var CordisError = class CordisError extends Error {
1501
+ code;
1502
+ /**
1503
+ * @param code — the stable error code; also the default message.
1504
+ * @param message — optional human-readable override.
1505
+ */
1506
+ constructor(code, message) {
1507
+ super(message ?? CordisError.Code[code]);
1508
+ this.code = code;
1509
+ }
1510
+ };
1511
+ (function(_CordisError) {
1512
+ _CordisError.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" };
1513
+ })(CordisError || (CordisError = {}));
1514
+ const INACTIVE = "__INACTIVE__";
1463
1515
  /**
1464
- * Event bus installed as `ctx.events` and mixed into every context.
1516
+ * Runtime instance of one plugin application.
1465
1517
  *
1466
- * The service supports concurrent, synchronous, serial, bail, and waterfall
1467
- * dispatch and automatically disposes listeners with their owning fiber.
1518
+ * A fiber tracks dependency state, raw and effective config, lifecycle effects, and
1519
+ * cleanup for the plugin context returned by `ctx.plugin()`.
1468
1520
  */
1469
- var EventsService = class {
1521
+ var Fiber = class {
1522
+ parent;
1523
+ inject;
1524
+ runtime;
1525
+ /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */
1526
+ uid;
1527
+ /** The context this fiber's plugin runs in (extends the parent context). */
1470
1528
  ctx;
1471
- _hooks = {};
1472
- constructor(ctx) {
1473
- this.ctx = ctx;
1474
- defineProperty(this, symbols.tracker, {
1475
- property: "ctx",
1476
- noShadow: true
1477
- });
1478
- this.on("internal/listener", function(name, listener, options) {
1479
- if (name === "internal/update" && !options.global) return (this.fiber._hooks["internal/update"] ??= new DisposableList())[options.prepend ? "unshift" : "push"](listener);
1480
- });
1481
- this.on("internal/update", function(config, noSave, next) {
1482
- const cbs = [...this._hooks["internal/update"] || []];
1483
- const _next = () => {
1484
- return (cbs.shift() ?? next).call(this, config, noSave, _next);
1485
- };
1486
- return _next();
1487
- }, {
1488
- global: true,
1489
- prepend: true
1490
- });
1491
- }
1529
+ /** Raw plugin input retained for the next activation. */
1530
+ config;
1531
+ /** Current lifecycle state; transitions emit `internal/status`. */
1532
+ state = 0;
1533
+ /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */
1534
+ dispose;
1535
+ /** Required implementations retained through dependent teardown. */
1536
+ committed;
1537
+ /** Service implementations owned by this fiber, including isolated provisions. */
1538
+ provisions = /* @__PURE__ */ new Set();
1539
+ /** The in-flight load/unload transition, if one is currently running. */
1540
+ inertia;
1541
+ _hooks = Object.create(null);
1542
+ _disposables = new DisposableList();
1543
+ context;
1544
+ _error;
1545
+ _revision = 0;
1546
+ _configRevision = 0;
1547
+ _effectiveConfig;
1548
+ _runner;
1549
+ _store = Object.create(null);
1550
+ _release;
1492
1551
  /**
1493
- * Resolve listeners for one dispatch and apply context filtering.
1552
+ * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()`
1553
+ * rather than constructing them directly.
1494
1554
  *
1495
- * @param type — the dispatch mode, reported on `internal/dispatch`.
1496
- * @param args — the raw dispatch arguments; consumed up to the event name.
1497
- * @returns the matching listener callbacks, bound to the dispatch `this`.
1555
+ * @param parent — the context the plugin was loaded from.
1556
+ * @param config — raw config, validated against the runtime's schema.
1557
+ * @param inject — resolved dependency map (service name → intercept config).
1558
+ * @param runtime — the shared plugin runtime, or `null` for the root fiber.
1559
+ * @param getOuterStack — captures the caller stack for effect diagnostics.
1498
1560
  */
1499
- dispatch(type, args) {
1500
- const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
1501
- const name = args.shift();
1502
- if (!name.startsWith("internal/")) this.emit("internal/dispatch", type, name, args, thisArg);
1503
- const filter = thisArg?.[Context.filter];
1504
- return (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback.bind(thisArg));
1561
+ constructor(parent, config, inject, runtime, getOuterStack) {
1562
+ this.parent = parent;
1563
+ this.inject = inject;
1564
+ this.runtime = runtime;
1565
+ this.config = config;
1566
+ const collect = (dispose) => {
1567
+ this._disposables.push(dispose);
1568
+ };
1569
+ if (runtime) {
1570
+ this.uid = parent.registry.counter;
1571
+ 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
+ this._runner = {
1581
+ epoch: INACTIVE,
1582
+ getOuterStack,
1583
+ execute: function() {
1584
+ const config = this.resolveConfig(this.config);
1585
+ this._effectiveConfig = config;
1586
+ if (isConstructor(runtime.callback)) {
1587
+ const instance = new runtime.callback(this.ctx, config);
1588
+ for (const hook of instance?.[symbols.initHooks] ?? []) hook();
1589
+ return instance?.[symbols.init]?.();
1590
+ } else return runtime.callback(this.ctx, config);
1591
+ },
1592
+ collect
1593
+ };
1594
+ this.dispose = parent.fiber.effect(() => {
1595
+ const remove = runtime.fibers.push(this);
1596
+ return async () => {
1597
+ this.uid = null;
1598
+ emitPluginDisposed(this.context, this);
1599
+ if (this.ctx.registry.has(runtime.callback)) {
1600
+ remove();
1601
+ if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback);
1602
+ }
1603
+ this._setEpoch(INACTIVE);
1604
+ if (!this.inertia) this._updateState(() => {
1605
+ this.inertia = this._unload();
1606
+ return 5;
1607
+ });
1608
+ while (this.inertia) await this.inertia;
1609
+ };
1610
+ }, "ctx.plugin()");
1611
+ try {
1612
+ this.context.emit("internal/plugin", this);
1613
+ } catch (error) {
1614
+ Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason));
1615
+ throw error;
1616
+ }
1617
+ if (this.uid !== null && parent.fiber.state !== 5) {
1618
+ for (const name of Object.keys(this.inject)) this._checkImpl(name);
1619
+ this._refresh();
1620
+ }
1621
+ } else {
1622
+ this.uid = 0;
1623
+ this.ctx = this.context = parent;
1624
+ this.state = 2;
1625
+ this.committed = Object.create(null);
1626
+ this._runner = {
1627
+ epoch: "0",
1628
+ getOuterStack,
1629
+ execute: () => {},
1630
+ collect
1631
+ };
1632
+ this.dispose = () => this.restart();
1633
+ }
1634
+ }
1635
+ /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */
1636
+ get name() {
1637
+ let fiber = this;
1638
+ do {
1639
+ if (fiber.runtime?.name) return fiber.runtime.name;
1640
+ fiber = fiber.parent.fiber;
1641
+ } while (fiber !== fiber.parent.fiber);
1642
+ return "root";
1505
1643
  }
1506
1644
  /**
1507
- * Run listeners concurrently and wait for all of them.
1645
+ * Throw if the fiber has already been disposed.
1508
1646
  *
1509
- * @param args — optional `this`, the event name, then listener arguments.
1510
- * @returns a promise resolving once every listener has settled.
1647
+ * @returns nothing when the fiber is still active.
1648
+ * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared.
1511
1649
  */
1512
- async parallel(...args) {
1513
- const errors = (await Promise.allSettled(this.dispatch("emit", args).map(async (cb) => cb(...args)))).filter((result) => result.status === "rejected");
1514
- if (errors.length) throw new AggregateError(errors.map((error) => error.reason));
1515
- }
1516
- /**
1517
- * Run listeners synchronously without waiting for returned promises.
1518
- *
1519
- * @param args — optional `this`, the event name, then listener arguments.
1520
- */
1521
- emit(...args) {
1522
- this.dispatch("emit", args).map((cb) => cb(...args));
1523
- }
1524
- /**
1525
- * Run listeners in order, awaiting each, until one returns a bail value.
1526
- *
1527
- * @param args — optional `this`, the event name, then listener arguments.
1528
- * @returns the first bail value (see {@link isBailed}), if any.
1529
- */
1530
- async serial(...args) {
1531
- for (const cb of this.dispatch("serial", args)) {
1532
- const result = await cb(...args);
1533
- if (isBailed(result)) return result;
1534
- }
1535
- }
1536
- /**
1537
- * Run listeners synchronously until one returns a bail value.
1538
- *
1539
- * @param args — optional `this`, the event name, then listener arguments.
1540
- * @returns the first bail value (see {@link isBailed}), if any.
1541
- */
1542
- bail(...args) {
1543
- for (const cb of this.dispatch("bail", args)) {
1544
- const result = cb(...args);
1545
- if (isBailed(result)) return result;
1546
- }
1547
- }
1548
- /**
1549
- * Compose listeners around the final `next` callback.
1550
- *
1551
- * The last dispatch argument is treated as the innermost `next`. Listeners
1552
- * run outermost-first; a listener that does not call `next()` vetoes the
1553
- * rest of the chain, including the built-in behavior.
1554
- *
1555
- * @param args — optional `this`, the event name, listener arguments, then `next`.
1556
- * @returns the outermost listener's return value.
1557
- */
1558
- waterfall(...args) {
1559
- const cbs = this.dispatch("waterfall", args);
1560
- const inner = args.pop();
1561
- const next = () => {
1562
- return (cbs.shift() ?? inner)(...args);
1563
- };
1564
- args.push(next);
1565
- return next();
1566
- }
1567
- /**
1568
- * Store a listener record as an effect on the current fiber.
1569
- *
1570
- * @param label — effect label shown in fiber diagnostics.
1571
- * @param hooks — the listener list for one event.
1572
- * @param callback — the listener to store.
1573
- * @param options — placement and filtering options.
1574
- * @returns a disposer that unregisters the listener.
1575
- */
1576
- register(label, hooks, callback, options) {
1577
- const method = options.prepend ? "unshift" : "push";
1578
- return this.ctx.fiber.effect(() => {
1579
- hooks[method]({
1580
- ctx: this.ctx,
1581
- callback,
1582
- ...options
1583
- });
1584
- return () => this.unregister(hooks, callback);
1585
- }, label);
1586
- }
1587
- /**
1588
- * Remove a stored listener record.
1589
- *
1590
- * @param hooks — the listener list for one event.
1591
- * @param callback — the listener to remove.
1592
- * @returns `true` if the listener was found and removed.
1593
- */
1594
- unregister(hooks, callback) {
1595
- const index = hooks.findIndex((hook) => hook.callback === callback);
1596
- if (index >= 0) {
1597
- hooks.splice(index, 1);
1598
- return true;
1599
- }
1600
- }
1601
- /**
1602
- * Register an event listener owned by the current fiber.
1603
- *
1604
- * The listener is removed automatically when the fiber unloads. Throws
1605
- * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
1606
- *
1607
- * @param name — the event name to listen for.
1608
- * @param listener — called with the dispatch arguments.
1609
- * @param options — listener options; a boolean is shorthand for `prepend`.
1610
- * @returns a disposer removing the listener; `true` if it was still registered.
1611
- */
1612
- on(name, listener, options) {
1613
- if (typeof options !== "object") options = { prepend: options };
1614
- this.ctx.fiber.assertActive();
1615
- listener = this.ctx.reflect.bind(listener);
1616
- const result = this.bail(this.ctx, "internal/listener", name, listener, options);
1617
- if (result) return result;
1618
- const hooks = this._hooks[name] ||= [];
1619
- const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
1620
- return this.register(label, hooks, listener, options);
1621
- }
1622
- /**
1623
- * Register an event listener that disposes itself after the first call.
1624
- *
1625
- * @param name — the event name to listen for.
1626
- * @param listener — called at most once with the dispatch arguments.
1627
- * @param options — listener options; a boolean is shorthand for `prepend`.
1628
- * @returns a disposer removing the listener; `true` if it was still registered.
1629
- */
1630
- once(name, listener, options) {
1631
- const dispose = this.on(name, function(...args) {
1632
- dispose();
1633
- return listener.apply(this, args);
1634
- }, options);
1635
- return dispose;
1636
- }
1637
- };
1638
- //#endregion
1639
- //#region ../../../vendor/cordis/src/logger.ts
1640
- /** Built-in placeholder formatters used by `Logger.format()`. */
1641
- const defaultFormatters = {
1642
- s: (value) => String(value),
1643
- d: (value) => Math.trunc(Number(value)),
1644
- i: (value) => Math.trunc(Number(value)),
1645
- f: (value) => Number(value),
1646
- o: (value) => JSON.stringify(value),
1647
- O: (value) => JSON.stringify(value),
1648
- c: () => "",
1649
- C: (value, exporter, message) => {
1650
- return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
1651
- }
1652
- };
1653
- function isAggregateError(error) {
1654
- return error instanceof Error && Array.isArray(error["errors"]);
1655
- }
1656
- /** Logger facade for one named subsystem. */
1657
- var Logger = class {
1658
- service;
1659
- static color(exporter, code, value, decoration = "") {
1660
- if (!exporter.colors) return "" + value;
1661
- return `\u001b[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\u001b[0m`;
1662
- }
1663
- static code(name, level) {
1664
- let hash = 0;
1665
- for (let i = 0; i < name.length; i++) {
1666
- hash = (hash << 3) - hash + name.charCodeAt(i) + 13;
1667
- hash |= 0;
1668
- }
1669
- const colors = !level ? [] : level >= 2 ? c256 : c16;
1670
- return colors[Math.abs(hash) % colors.length];
1671
- }
1672
- static format(exporter, message) {
1673
- const args = message.args.slice();
1674
- if (args[0] instanceof Error) {
1675
- args[0] = args[0].stack || args[0].message;
1676
- args.unshift("%s");
1677
- } else if (typeof args[0] !== "string") args.unshift("%o");
1678
- let format = args.shift();
1679
- format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
1680
- if (match === "%%") return "%";
1681
- const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
1682
- if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
1683
- return match;
1684
- });
1685
- const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
1686
- for (let arg of args) {
1687
- if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
1688
- format += " " + arg;
1689
- }
1690
- const { maxLength = 10240 } = exporter;
1691
- return format.split(/\r?\n/g).map((line) => {
1692
- return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
1693
- }).join("\n");
1694
- }
1695
- constructor(options, service) {
1696
- this.service = service;
1697
- Object.assign(this, options);
1698
- this.error = this._method("error", 0);
1699
- this.info = this._method("info", 1);
1700
- this.warn = this._method("warn", 2);
1701
- this.debug = this._method("debug", 3);
1702
- }
1703
- _method(type, level) {
1704
- return (...args) => {
1705
- if (args.length === 1 && args[0] instanceof Error) {
1706
- if (args[0].cause) this[type](args[0].cause);
1707
- else if (isAggregateError(args[0])) {
1708
- args[0].errors.forEach((error) => this[type](error));
1709
- return;
1710
- }
1711
- }
1712
- const sn = ++this.service._snMessage;
1713
- const ts = Date.now();
1714
- for (const exporter of this.service.exporters.values()) {
1715
- if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 1) < level) continue;
1716
- const message = {
1717
- sn,
1718
- ts,
1719
- type,
1720
- level,
1721
- name: this.name,
1722
- ...this.meta,
1723
- args
1724
- };
1725
- exporter.export(message);
1726
- }
1727
- };
1728
- }
1729
- };
1730
- /** ANSI 16-color palette indexes used for logger name coloring. */
1731
- const c16 = [
1732
- 6,
1733
- 2,
1734
- 3,
1735
- 4,
1736
- 5,
1737
- 1
1738
- ];
1739
- /** ANSI 256-color palette indexes used for logger name coloring. */
1740
- const c256 = [
1741
- 20,
1742
- 21,
1743
- 26,
1744
- 27,
1745
- 32,
1746
- 33,
1747
- 38,
1748
- 39,
1749
- 40,
1750
- 41,
1751
- 42,
1752
- 43,
1753
- 44,
1754
- 45,
1755
- 56,
1756
- 57,
1757
- 62,
1758
- 63,
1759
- 68,
1760
- 69,
1761
- 74,
1762
- 75,
1763
- 76,
1764
- 77,
1765
- 78,
1766
- 79,
1767
- 80,
1768
- 81,
1769
- 92,
1770
- 93,
1771
- 98,
1772
- 99,
1773
- 112,
1774
- 113,
1775
- 129,
1776
- 134,
1777
- 135,
1778
- 148,
1779
- 149,
1780
- 160,
1781
- 161,
1782
- 162,
1783
- 163,
1784
- 164,
1785
- 165,
1786
- 166,
1787
- 167,
1788
- 168,
1789
- 169,
1790
- 170,
1791
- 171,
1792
- 172,
1793
- 173,
1794
- 178,
1795
- 179,
1796
- 184,
1797
- 185,
1798
- 196,
1799
- 197,
1800
- 198,
1801
- 199,
1802
- 200,
1803
- 201,
1804
- 202,
1805
- 203,
1806
- 204,
1807
- 205,
1808
- 206,
1809
- 207,
1810
- 208,
1811
- 209,
1812
- 214,
1813
- 215,
1814
- 220,
1815
- 221
1816
- ];
1817
- /**
1818
- * Built-in logging service.
1819
- *
1820
- * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
1821
- * directly to log with the current fiber-derived name.
1822
- */
1823
- var LoggerService = class LoggerService {
1824
- bufferSize = 1e3;
1825
- buffer = [];
1826
- ctx;
1827
- _snMessage = 0;
1828
- _snExporter = 0;
1829
- exporters = /* @__PURE__ */ new Map();
1830
- constructor(ctx) {
1831
- const tracker = {
1832
- property: "ctx",
1833
- noShadow: true
1834
- };
1835
- const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
1836
- Object.assign(self, this);
1837
- self.ctx = ctx;
1838
- defineProperty(self, symbols.tracker, tracker);
1839
- self.exporter({
1840
- colors: 3,
1841
- export: (message) => {
1842
- self.buffer.push(message);
1843
- if (self.buffer.length > self.bufferSize) self.buffer = self.buffer.slice(-self.bufferSize);
1844
- }
1845
- });
1846
- return self;
1847
- }
1848
- /**
1849
- * Register an exporter and dispose it with the current fiber.
1850
- *
1851
- * @param exporter — the sink that receives structured log messages.
1852
- * @returns a disposer that removes the exporter.
1853
- */
1854
- exporter(exporter) {
1855
- return this.ctx.effect(() => {
1856
- const id = ++this._snExporter;
1857
- this.exporters.set(id, exporter);
1858
- return () => this.exporters.delete(id);
1859
- }, "ctx.logger.exporter()");
1860
- }
1861
- _resolveConfig() {
1862
- let intercept = this.ctx[symbols.intercept];
1863
- const configs = [];
1864
- while ("logger" in intercept) {
1865
- if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]);
1866
- intercept = Object.getPrototypeOf(intercept);
1867
- }
1868
- return Object.assign({}, ...configs);
1869
- }
1870
- [symbols.invoke](name) {
1871
- const config = this._resolveConfig();
1872
- const fiber = (this.ctx[symbols.shadow] ?? this.ctx).fiber;
1873
- name ??= config.name;
1874
- name ??= hyphenate(fiber.name);
1875
- return new Logger({
1876
- name,
1877
- level: config.level,
1878
- meta: { fiber: new WeakRef(fiber) }
1879
- }, this);
1880
- }
1881
- static {
1882
- for (const type of [
1883
- "error",
1884
- "info",
1885
- "warn",
1886
- "debug"
1887
- ]) LoggerService.prototype[type] = function(...args) {
1888
- return this()[type](...args);
1889
- };
1890
- }
1891
- };
1892
- //#endregion
1893
- //#region ../../../vendor/cordis/src/fiber.ts
1894
- const kValidationError$1 = Symbol.for("ValidationError");
1895
- /** Error raised when plugin configuration fails standard-schema validation. */
1896
- var ValidationError$1 = class extends TypeError {
1897
- name = "ValidationError";
1898
- /**
1899
- * Build the aggregated message from schema issues.
1900
- *
1901
- * @param issues — the standard-schema issues, one message line each.
1902
- */
1903
- constructor(issues) {
1904
- super(`invalid config:\n` + issues.map((issue) => {
1905
- if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
1906
- else return ` - ${issue.message}`;
1907
- }).join("\n"));
1908
- }
1909
- };
1910
- Object.defineProperty(ValidationError$1.prototype, kValidationError$1, { value: true });
1911
- /**
1912
- * Validate and normalize config for a plugin runtime before it starts.
1913
- *
1914
- * @param runtime — the plugin runtime whose `Config` schema to apply.
1915
- * @param config — the raw user config.
1916
- * @returns the validated config, or `config` unchanged if the runtime has no schema.
1917
- * @throws {ValidationError} when validation reports issues.
1918
- */
1919
- function resolveConfig(runtime, config) {
1920
- if (!runtime.Config) return config;
1921
- const result = runtime.Config["~standard"].validate(config);
1922
- if ("then" in result) throw new TypeError("Async config validation is not supported");
1923
- if (result.issues) throw new ValidationError$1(result.issues);
1924
- else return result.value;
1925
- }
1926
- const effectInertia = /* @__PURE__ */ new WeakMap();
1927
- function runDisposable(dispose) {
1928
- const result = dispose();
1929
- return effectInertia.get(dispose)?.() ?? result;
1930
- }
1931
- /** Notify plugin teardown without allowing one observer to break ownership cleanup. */
1932
- function emitPluginDisposed(context, fiber) {
1933
- const args = ["internal/plugin", fiber];
1934
- let callbacks;
1935
- try {
1936
- callbacks = context.events.dispatch("emit", args);
1937
- } catch (error) {
1938
- context.logger.error(error);
1939
- return;
1940
- }
1941
- for (const callback of callbacks) try {
1942
- const returned = callback(...args);
1943
- Promise.resolve(returned).catch((error) => context.logger.error(error));
1944
- } catch (error) {
1945
- context.logger.error(error);
1946
- }
1947
- }
1948
- /** Framework error with a stable machine-readable code. */
1949
- var CordisError = class CordisError extends Error {
1950
- code;
1951
- /**
1952
- * @param code — the stable error code; also the default message.
1953
- * @param message — optional human-readable override.
1954
- */
1955
- constructor(code, message) {
1956
- super(message ?? CordisError.Code[code]);
1957
- this.code = code;
1958
- }
1959
- };
1960
- (function(_CordisError) {
1961
- _CordisError.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" };
1962
- })(CordisError || (CordisError = {}));
1963
- const INACTIVE = "__INACTIVE__";
1964
- /**
1965
- * Runtime instance of one plugin application.
1966
- *
1967
- * A fiber tracks dependency state, validated config, lifecycle effects, and
1968
- * cleanup for the plugin context returned by `ctx.plugin()`.
1969
- */
1970
- var Fiber = class {
1971
- parent;
1972
- inject;
1973
- runtime;
1974
- /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */
1975
- uid;
1976
- /** The context this fiber's plugin runs in (extends the parent context). */
1977
- ctx;
1978
- /** The validated plugin config (updated by `update()`). */
1979
- config;
1980
- /** The raw plugin config, re-resolved before each activation. */
1981
- _config;
1982
- /** Current lifecycle state; transitions emit `internal/status`. */
1983
- state = 0;
1984
- /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */
1985
- dispose;
1986
- /** Snapshot of required service implementations while loaded; `undefined` otherwise. */
1987
- store;
1988
- /** The in-flight load/unload transition, if one is currently running. */
1989
- inertia;
1990
- _hooks = Object.create(null);
1991
- _disposables = new DisposableList();
1992
- context;
1993
- _error;
1994
- _runner;
1995
- _store = Object.create(null);
1996
- /**
1997
- * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()`
1998
- * rather than constructing them directly.
1999
- *
2000
- * @param parent — the context the plugin was loaded from.
2001
- * @param config — raw config, validated against the runtime's schema.
2002
- * @param inject — resolved dependency map (service name → intercept config).
2003
- * @param runtime — the shared plugin runtime, or `null` for the root fiber.
2004
- * @param getOuterStack — captures the caller stack for effect diagnostics.
2005
- */
2006
- constructor(parent, config, inject, runtime, getOuterStack) {
2007
- this.parent = parent;
2008
- this.inject = inject;
2009
- this.runtime = runtime;
2010
- this._config = config;
2011
- const collect = (dispose) => {
2012
- this._disposables.push(dispose);
2013
- };
2014
- if (runtime) {
2015
- this.uid = parent.registry.counter;
2016
- this.ctx = this.context = parent.extend({ fiber: this });
2017
- const injectEntries = Object.entries(this.inject);
2018
- if (injectEntries.length) {
2019
- this.ctx[Context.intercept] = Object.create(parent[Context.intercept]);
2020
- for (const [name, config] of injectEntries) {
2021
- if (isNullable(config)) continue;
2022
- this.ctx[Context.intercept][name] = config;
2023
- }
2024
- }
2025
- this._runner = {
2026
- epoch: INACTIVE,
2027
- getOuterStack,
2028
- execute: function() {
2029
- if (isConstructor(runtime.callback)) {
2030
- const instance = new runtime.callback(this.ctx, this.config);
2031
- for (const hook of instance?.[symbols.initHooks] ?? []) hook();
2032
- return instance?.[symbols.init]?.();
2033
- } else return runtime.callback(this.ctx, this.config);
2034
- },
2035
- collect
2036
- };
2037
- this.dispose = parent.fiber.effect(() => {
2038
- const remove = runtime.fibers.push(this);
2039
- return async () => {
2040
- this.uid = null;
2041
- emitPluginDisposed(this.context, this);
2042
- if (this.ctx.registry.has(runtime.callback)) {
2043
- remove();
2044
- if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback);
2045
- }
2046
- this._setEpoch(INACTIVE);
2047
- if (!this.inertia) this._updateState(() => {
2048
- this.inertia = this._unload();
2049
- return 5;
2050
- });
2051
- while (this.inertia) await this.inertia;
2052
- };
2053
- }, "ctx.plugin()");
2054
- try {
2055
- this.context.emit("internal/plugin", this);
2056
- } catch (error) {
2057
- Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason));
2058
- throw error;
2059
- }
2060
- if (this.uid !== null && parent.fiber.state !== 5) {
2061
- for (const name of Object.keys(this.inject)) this._checkImpl(name);
2062
- this._refresh();
2063
- }
2064
- } else {
2065
- this.uid = 0;
2066
- this.ctx = this.context = parent;
2067
- this.state = 2;
2068
- this.store = Object.create(null);
2069
- this._runner = {
2070
- epoch: "",
2071
- getOuterStack,
2072
- execute: () => {},
2073
- collect
2074
- };
2075
- this.dispose = () => this.restart();
2076
- }
2077
- }
2078
- /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */
2079
- get name() {
2080
- let fiber = this;
2081
- do {
2082
- if (fiber.runtime?.name) return fiber.runtime.name;
2083
- fiber = fiber.parent.fiber;
2084
- } while (fiber !== fiber.parent.fiber);
2085
- return "root";
2086
- }
2087
- /**
2088
- * Throw if the fiber has already been disposed.
2089
- *
2090
- * @returns nothing when the fiber is still active.
2091
- * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared.
2092
- */
2093
- assertActive() {
2094
- if (this.uid !== null) return;
2095
- throw new CordisError("INACTIVE_EFFECT");
1650
+ assertActive() {
1651
+ if (this.uid !== null) return;
1652
+ throw new CordisError("INACTIVE_EFFECT");
2096
1653
  }
2097
1654
  _execute(runner) {
2098
1655
  const oldEpoch = runner.epoch;
@@ -2223,184 +1780,678 @@ var Fiber = class {
2223
1780
  if (isObject(cleanup) && "then" in cleanup) cleanup.catch((error) => this.ctx.logger.error(error));
2224
1781
  throw reason;
2225
1782
  }
2226
- executing = false;
2227
- if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup);
2228
- task?.catch(() => {
2229
- if (!runner.epoch) return dispose();
2230
- return finalizeDisposal(dispose);
2231
- }).catch((error) => this.ctx.logger.error(error));
2232
- const disposeAsync = () => {
2233
- if (!runner.epoch) return;
2234
- runner.epoch = false;
2235
- return finalizeDisposal(dispose);
2236
- };
2237
- wrapper.then = async (onFulfilled, onRejected) => {
2238
- return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
2239
- };
2240
- return wrapper;
1783
+ executing = false;
1784
+ if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup);
1785
+ task?.catch(() => {
1786
+ if (!runner.epoch) return dispose();
1787
+ return finalizeDisposal(dispose);
1788
+ }).catch((error) => this.ctx.logger.error(error));
1789
+ const disposeAsync = () => {
1790
+ if (!runner.epoch) return;
1791
+ runner.epoch = false;
1792
+ return finalizeDisposal(dispose);
1793
+ };
1794
+ wrapper.then = async (onFulfilled, onRejected) => {
1795
+ return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
1796
+ };
1797
+ return wrapper;
1798
+ }
1799
+ /**
1800
+ * Return metadata for currently registered effects.
1801
+ *
1802
+ * @returns one {@link EffectMeta} tree per labeled live effect.
1803
+ */
1804
+ getEffects() {
1805
+ return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
1806
+ }
1807
+ _getState() {
1808
+ if (this.uid === null) return 4;
1809
+ if (this._error) return 3;
1810
+ if (this._runner.epoch !== INACTIVE) return 2;
1811
+ return 0;
1812
+ }
1813
+ _updateState(callback) {
1814
+ const oldState = this.state;
1815
+ this.state = callback() ?? this._getState();
1816
+ if (oldState === this.state) return;
1817
+ this.context.emit("internal/status", this, oldState);
1818
+ if (oldState !== 2 && this.state !== 2) return;
1819
+ for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
1820
+ const impl = this.ctx.reflect.store[key];
1821
+ if (impl.ctx.fiber !== this) continue;
1822
+ this.ctx.isolate(impl.name, impl.isolate).reflect.notify([impl.name]);
1823
+ }
1824
+ }
1825
+ _checkImpl(name) {
1826
+ const impl = this.ctx.reflect._getImpl(name, true);
1827
+ if (!impl) return delete this._store[name];
1828
+ try {
1829
+ if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name];
1830
+ } catch (error) {
1831
+ impl.ctx.logger.error(error);
1832
+ return delete this._store[name];
1833
+ }
1834
+ this._store[name] = impl;
1835
+ }
1836
+ _refresh() {
1837
+ let epoch = `${this._revision}`;
1838
+ for (const name of Object.keys(this.inject)) {
1839
+ const impl = this._store[name];
1840
+ if (!impl) {
1841
+ epoch = INACTIVE;
1842
+ break;
1843
+ }
1844
+ epoch += ":" + impl.uid;
1845
+ }
1846
+ this._setEpoch(epoch);
1847
+ }
1848
+ _setEpoch(epoch) {
1849
+ const oldEpoch = this._runner.epoch;
1850
+ if (epoch === oldEpoch) return;
1851
+ if (this._error) return;
1852
+ this._runner.epoch = epoch;
1853
+ if (this.inertia) return;
1854
+ this._updateState(() => {
1855
+ if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
1856
+ this.inertia = this._reload();
1857
+ return 1;
1858
+ } else {
1859
+ this.inertia = this._unload();
1860
+ return 5;
1861
+ }
1862
+ });
1863
+ }
1864
+ /** Raw input retained for the next activation, without evaluating expressions or validating it. */
1865
+ get rawConfig() {
1866
+ return this.ctx.fiber.config;
1867
+ }
1868
+ /** Retain raw input without changing the running config or triggering an update. */
1869
+ set rawConfig(config) {
1870
+ this.ctx.fiber.config = config;
1871
+ this.ctx.fiber._configRevision++;
1872
+ }
1873
+ /**
1874
+ * The object passed to plugin activation or the latest successful update that retained the instance.
1875
+ * Candidate resolution does not publish it; volatile updates retain its references.
1876
+ * Undefined before activation and readable after unload; callers requiring a live instance check `state`.
1877
+ */
1878
+ get effectiveConfig() {
1879
+ return this.ctx.fiber._effectiveConfig;
1880
+ }
1881
+ /**
1882
+ * Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema.
1883
+ * Does not publish the result, replace raw input, or commit running volatile references.
1884
+ * Required injections must be available when a hook uses them.
1885
+ * @param config Raw candidate input.
1886
+ * @returns The candidate's resolved config, retaining the schema's result identity.
1887
+ * @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate.
1888
+ */
1889
+ resolveConfig(config) {
1890
+ const fiber = this.ctx.fiber;
1891
+ return fiber.context.waterfall("internal/config", fiber, () => config);
1892
+ }
1893
+ async _reload() {
1894
+ this.committed = { ...this._store };
1895
+ for (const impl of Object.values(this.committed)) {
1896
+ if (impl.ctx.fiber === this) continue;
1897
+ impl.dependents.add(this);
1898
+ }
1899
+ const oldEpoch = this._runner.epoch;
1900
+ try {
1901
+ await Promise.resolve();
1902
+ if (this._runner.epoch === oldEpoch) await this._execute(this._runner);
1903
+ } catch (reason) {
1904
+ this.ctx.logger.error(reason);
1905
+ if (this._runner.epoch === oldEpoch) {
1906
+ this._error = reason;
1907
+ this._runner.epoch = INACTIVE;
1908
+ }
1909
+ }
1910
+ this._updateState(() => {
1911
+ if (this._runner.epoch === oldEpoch) this.inertia = void 0;
1912
+ else {
1913
+ this.inertia = this._unload();
1914
+ return 5;
1915
+ }
1916
+ });
1917
+ }
1918
+ async _unload() {
1919
+ while ([...this.provisions].some((impl) => impl.dependents.size)) await new Promise((resolve) => this._release = resolve);
1920
+ this._release = void 0;
1921
+ await Promise.all(this._disposables.clear().map(async (dispose) => {
1922
+ try {
1923
+ await composeError(async (info) => {
1924
+ await Promise.resolve();
1925
+ info.error = /* @__PURE__ */ new Error();
1926
+ await runDisposable(dispose);
1927
+ }, this._runner.getOuterStack);
1928
+ } catch (reason) {
1929
+ this.ctx.logger.error(reason);
1930
+ }
1931
+ }));
1932
+ for (const impl of Object.values(this.committed ?? {})) {
1933
+ if (!impl.dependents.delete(this) || impl.dependents.size) continue;
1934
+ impl.release?.();
1935
+ impl.ctx.fiber._release?.();
1936
+ }
1937
+ this.committed = void 0;
1938
+ this._updateState(() => {
1939
+ if (this._runner.epoch === INACTIVE) this.inertia = void 0;
1940
+ else {
1941
+ this.inertia = this._reload();
1942
+ return 1;
1943
+ }
1944
+ });
1945
+ }
1946
+ /**
1947
+ * Wait for current lifecycle work and rethrow startup errors.
1948
+ *
1949
+ * @returns this fiber, once it has settled into a stable state.
1950
+ * @throws the config-validation or plugin-startup error, if any.
1951
+ */
1952
+ async await() {
1953
+ while (this.inertia) await this.inertia;
1954
+ if (this._error) throw this._error;
1955
+ return this;
1956
+ }
1957
+ /**
1958
+ * Dispose and immediately reload this plugin with its current config.
1959
+ *
1960
+ * @returns a promise resolving once the reload settled.
1961
+ * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
1962
+ */
1963
+ async restart() {
1964
+ const fiber = this.ctx.fiber;
1965
+ fiber.assertActive();
1966
+ fiber._revision++;
1967
+ fiber._refresh();
1968
+ await fiber.await();
1969
+ }
1970
+ /**
1971
+ * Resolve a candidate, retain its raw config and apply it through the update waterfall.
1972
+ * @param config Raw config; pending fibers defer resolution until activation.
1973
+ * @param noSave Suppress the persistence notification when true.
1974
+ * @returns The awaited update/restart result, or undefined when a synchronous listener handles it.
1975
+ * @throws {ValidationError} when an active fiber's candidate is invalid.
1976
+ */
1977
+ update(config, noSave = false) {
1978
+ const fiber = this.ctx.fiber;
1979
+ fiber.assertActive();
1980
+ const loaded = fiber._runner.epoch !== INACTIVE;
1981
+ const resolved = loaded ? fiber.resolveConfig(config) : void 0;
1982
+ if (!noSave) fiber.context.emit("internal/commit", fiber, config);
1983
+ fiber.config = config;
1984
+ fiber._error = void 0;
1985
+ const configRevision = ++fiber._configRevision;
1986
+ const epoch = fiber._runner.epoch;
1987
+ const committed = fiber.committed;
1988
+ let restarted = false;
1989
+ const restart = () => {
1990
+ restarted = true;
1991
+ return fiber.restart();
1992
+ };
1993
+ const publish = () => {
1994
+ if (!restarted && fiber.uid !== null && fiber._configRevision === configRevision && fiber._runner.epoch === epoch && fiber.committed === committed) fiber._effectiveConfig = resolved;
1995
+ };
1996
+ const result = loaded ? fiber.context.waterfall(fiber, "internal/update", resolved, restart) : restart();
1997
+ if (result === void 0) {
1998
+ publish();
1999
+ return;
2000
+ }
2001
+ const task = Promise.resolve(result).then(publish);
2002
+ task.catch(() => {});
2003
+ return task;
2004
+ }
2005
+ };
2006
+ //#endregion
2007
+ //#region ../../../vendor/cordis/src/events.ts
2008
+ /**
2009
+ * Return whether an event result should stop a bail-style dispatch.
2010
+ *
2011
+ * @param value — a listener's return value.
2012
+ * @returns `true` unless `value` is `null`, `false`, or `undefined`.
2013
+ */
2014
+ function isBailed(value) {
2015
+ return value !== null && value !== false && value !== void 0;
2016
+ }
2017
+ /**
2018
+ * Event bus installed as `ctx.events` and mixed into every context.
2019
+ *
2020
+ * The service supports concurrent, synchronous, serial, bail, and waterfall
2021
+ * dispatch and automatically disposes listeners with their owning fiber.
2022
+ */
2023
+ var EventsService = class {
2024
+ ctx;
2025
+ _hooks = Object.create(null);
2026
+ constructor(ctx) {
2027
+ this.ctx = ctx;
2028
+ defineProperty(this, symbols.tracker, {
2029
+ property: "ctx",
2030
+ noShadow: true
2031
+ });
2032
+ this.on("internal/listener", function(name, listener, options) {
2033
+ if (name === "internal/update" && !options.global) {
2034
+ const hooks = this.fiber._hooks["internal/update"] ??= new DisposableList();
2035
+ const method = options.prepend ? "unshift" : "push";
2036
+ return this.fiber.effect(() => hooks[method](listener), "ctx.on(\"internal/update\")");
2037
+ }
2038
+ });
2039
+ this.on("internal/update", function(config, next) {
2040
+ const cbs = [...this._hooks["internal/update"] || []];
2041
+ const _next = () => {
2042
+ return (cbs.shift() ?? next).call(this, config, _next);
2043
+ };
2044
+ return _next();
2045
+ }, {
2046
+ global: true,
2047
+ prepend: true
2048
+ });
2049
+ this.on("internal/config", (fiber, next) => {
2050
+ const config = next();
2051
+ return fiber.runtime ? resolveConfig(fiber.runtime, config) : config;
2052
+ });
2053
+ }
2054
+ _resolve(type, args) {
2055
+ const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
2056
+ const name = args.shift();
2057
+ if ((typeof name !== "string" || !name.startsWith("internal/")) && this._hooks["internal/dispatch"]?.length) this.emit("internal/dispatch", type, name, args, thisArg);
2058
+ 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)];
2060
+ }
2061
+ /**
2062
+ * Resolve bound callbacks using the event's context filter.
2063
+ * @param type Dispatch mode reported to observers.
2064
+ * @param args Dispatch arguments, consumed through the event name.
2065
+ * @returns Matching callbacks bound to the dispatch receiver.
2066
+ * RABI retains callback enumeration for per-listener error containment.
2067
+ */
2068
+ dispatch(type, args) {
2069
+ const [thisArg, callbacks] = this._resolve(type, args);
2070
+ return callbacks.map((callback) => callback.bind(thisArg));
2071
+ }
2072
+ /**
2073
+ * Run listeners concurrently and wait for all of them.
2074
+ *
2075
+ * @param args — optional `this`, the event name, then listener arguments.
2076
+ * @returns a promise resolving once every listener has settled.
2077
+ */
2078
+ async parallel(...args) {
2079
+ const [thisArg, callbacks] = this._resolve("parallel", args);
2080
+ 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));
2082
+ }
2083
+ /**
2084
+ * Run listeners synchronously without waiting for returned promises.
2085
+ *
2086
+ * @param args — optional `this`, the event name, then listener arguments.
2087
+ */
2088
+ emit(...args) {
2089
+ const [thisArg, callbacks] = this._resolve("emit", args);
2090
+ for (const callback of callbacks) Reflect.apply(callback, thisArg, args);
2091
+ }
2092
+ /**
2093
+ * Run listeners in order, awaiting each, until one returns a bail value.
2094
+ *
2095
+ * @param args — optional `this`, the event name, then listener arguments.
2096
+ * @returns the first bail value (see {@link isBailed}), if any.
2097
+ */
2098
+ async serial(...args) {
2099
+ const [thisArg, callbacks] = this._resolve("serial", args);
2100
+ for (const callback of callbacks) {
2101
+ const result = await Reflect.apply(callback, thisArg, args);
2102
+ if (isBailed(result)) return result;
2103
+ }
2104
+ }
2105
+ /**
2106
+ * Run listeners synchronously until one returns a bail value.
2107
+ *
2108
+ * @param args — optional `this`, the event name, then listener arguments.
2109
+ * @returns the first bail value (see {@link isBailed}), if any.
2110
+ */
2111
+ bail(...args) {
2112
+ const [thisArg, callbacks] = this._resolve("bail", args);
2113
+ for (const callback of callbacks) {
2114
+ const result = Reflect.apply(callback, thisArg, args);
2115
+ if (isBailed(result)) return result;
2116
+ }
2241
2117
  }
2242
2118
  /**
2243
- * Return metadata for currently registered effects.
2119
+ * Compose listeners around the final `next` callback.
2244
2120
  *
2245
- * @returns one {@link EffectMeta} tree per labeled live effect.
2121
+ * The last dispatch argument is treated as the innermost `next`. Listeners
2122
+ * run outermost-first; a listener that does not call `next()` vetoes the
2123
+ * rest of the chain, including the built-in behavior.
2124
+ *
2125
+ * @param args — optional `this`, the event name, listener arguments, then `next`.
2126
+ * @returns the outermost listener's return value.
2246
2127
  */
2247
- getEffects() {
2248
- return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
2128
+ waterfall(...args) {
2129
+ const [thisArg, callbacks] = this._resolve("waterfall", args);
2130
+ const inner = args.pop();
2131
+ const dispatch = () => {
2132
+ const callback = callbacks.shift();
2133
+ if (!callback) return inner();
2134
+ let called = false;
2135
+ const next = () => {
2136
+ if (called) throw new Error("next() called multiple times");
2137
+ called = true;
2138
+ return dispatch();
2139
+ };
2140
+ return Reflect.apply(callback, thisArg, [...args, next]);
2141
+ };
2142
+ return dispatch();
2249
2143
  }
2250
- _getState() {
2251
- if (this.uid === null) return 4;
2252
- if (this._error) return 3;
2253
- if (this._runner.epoch !== INACTIVE) return 2;
2254
- return 0;
2144
+ register(label, name, callback, options) {
2145
+ const method = options.prepend ? "unshift" : "push";
2146
+ return this.ctx.fiber.effect(() => {
2147
+ (this._hooks[name] ??= [])[method]({
2148
+ ctx: this.ctx,
2149
+ callback,
2150
+ ...options
2151
+ });
2152
+ return () => this.unregister(name, callback);
2153
+ }, label);
2255
2154
  }
2256
- _updateState(callback) {
2257
- const oldState = this.state;
2258
- this.state = callback() ?? this._getState();
2259
- if (oldState === this.state) return;
2260
- this.context.emit("internal/status", this, oldState);
2261
- if (oldState !== 2 && this.state !== 2) return;
2262
- for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
2263
- const impl = this.ctx.reflect.store[key];
2264
- if (impl.fiber !== this) continue;
2265
- this.ctx.reflect.notify([impl.name]);
2155
+ unregister(name, callback) {
2156
+ const hooks = this._hooks[name];
2157
+ if (!hooks) return;
2158
+ const index = hooks.findIndex((hook) => hook.callback === callback);
2159
+ if (index >= 0) {
2160
+ hooks.splice(index, 1);
2161
+ if (!hooks.length) delete this._hooks[name];
2162
+ return true;
2266
2163
  }
2267
2164
  }
2268
- _checkImpl(name) {
2269
- const impl = this.ctx.reflect._getImpl(name, true);
2270
- if (!impl) return delete this._store[name];
2271
- try {
2272
- if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name];
2273
- } catch (error) {
2274
- impl.fiber.ctx.logger.error(error);
2275
- return delete this._store[name];
2276
- }
2277
- this._store[name] = impl;
2165
+ /**
2166
+ * Register an event listener owned by the current fiber.
2167
+ *
2168
+ * The listener is removed automatically when the fiber unloads. Throws
2169
+ * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
2170
+ *
2171
+ * @param name — the event name to listen for.
2172
+ * @param listener — called with the dispatch arguments.
2173
+ * @param options — listener options; a boolean is shorthand for `prepend`.
2174
+ * @returns a disposer removing the listener; `true` if it was still registered.
2175
+ */
2176
+ on(name, listener, options) {
2177
+ if (typeof options !== "object") options = { prepend: options };
2178
+ this.ctx.fiber.assertActive();
2179
+ listener = this.ctx.reflect.bind(listener);
2180
+ const result = this.bail(this.ctx, "internal/listener", name, listener, options);
2181
+ if (result) return result;
2182
+ const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
2183
+ return this.register(label, name, listener, options);
2278
2184
  }
2279
- _refresh() {
2280
- let epoch = false;
2281
- epoch = "";
2282
- for (const name of Object.keys(this.inject)) {
2283
- const impl = this._store[name];
2284
- if (!impl) {
2285
- epoch = INACTIVE;
2286
- break;
2287
- }
2288
- epoch += ":" + impl.fiber.uid;
2185
+ /**
2186
+ * Register an event listener that disposes itself after the first call.
2187
+ *
2188
+ * @param name — the event name to listen for.
2189
+ * @param listener — called at most once with the dispatch arguments.
2190
+ * @param options — listener options; a boolean is shorthand for `prepend`.
2191
+ * @returns a disposer removing the listener; `true` if it was still registered.
2192
+ */
2193
+ once(name, listener, options) {
2194
+ const dispose = this.on(name, function(...args) {
2195
+ dispose();
2196
+ return listener.apply(this, args);
2197
+ }, options);
2198
+ return dispose;
2199
+ }
2200
+ };
2201
+ //#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"]);
2218
+ }
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;
2289
2231
  }
2290
- this._setEpoch(epoch);
2232
+ const colors = !level ? [] : level >= 2 ? c256 : c16;
2233
+ return colors[Math.abs(hash) % colors.length];
2291
2234
  }
2292
- _setEpoch(epoch) {
2293
- const oldEpoch = this._runner.epoch;
2294
- if (epoch === oldEpoch) return;
2295
- this._runner.epoch = epoch;
2296
- if (this.inertia) return;
2297
- this._updateState(() => {
2298
- if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
2299
- this.inertia = this._reload();
2300
- return 1;
2301
- } else {
2302
- this.inertia = this._unload();
2303
- return 5;
2304
- }
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;
2305
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");
2306
2257
  }
2307
- _resolveConfig(config) {
2308
- config = this.context.waterfall(this, "internal/config", config, () => config);
2309
- return this.runtime ? resolveConfig(this.runtime, config) : config;
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);
2310
2265
  }
2311
- async _reload() {
2312
- this.store = { ...this._store };
2313
- const oldEpoch = this._runner.epoch;
2314
- try {
2315
- await Promise.resolve();
2316
- if (this._runner.epoch === oldEpoch) {
2317
- this.config = this._resolveConfig(this._config);
2318
- await this._execute(this._runner);
2319
- this._error = void 0;
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
+ }
2320
2274
  }
2321
- } catch (reason) {
2322
- this.ctx.logger.error(reason);
2323
- this._error = reason;
2324
- this._runner.epoch = INACTIVE;
2325
- }
2326
- this._updateState(() => {
2327
- if (this._runner.epoch === oldEpoch) this.inertia = void 0;
2328
- else {
2329
- this.inertia = this._unload();
2330
- return 5;
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);
2331
2289
  }
2332
- });
2290
+ };
2333
2291
  }
2334
- async _unload() {
2335
- await Promise.all(this._disposables.clear().map(async (dispose) => {
2336
- try {
2337
- await composeError(async (info) => {
2338
- await Promise.resolve();
2339
- info.error = /* @__PURE__ */ new Error();
2340
- await runDisposable(dispose);
2341
- }, this._runner.getOuterStack);
2342
- } catch (reason) {
2343
- this.ctx.logger.error(reason);
2344
- }
2345
- }));
2346
- this.store = void 0;
2347
- this._updateState(() => {
2348
- if (this._runner.epoch === INACTIVE) this.inertia = void 0;
2349
- else {
2350
- this.inertia = this._reload();
2351
- return 1;
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
+ ];
2380
+ /**
2381
+ * Built-in logging service.
2382
+ *
2383
+ * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
2384
+ * directly to log with the current fiber-derived name.
2385
+ */
2386
+ var LoggerService = class LoggerService {
2387
+ bufferSize = 1e3;
2388
+ buffer = [];
2389
+ 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);
2352
2409
  }
2353
2410
  });
2411
+ return self;
2354
2412
  }
2355
2413
  /**
2356
- * Wait for current lifecycle work and rethrow startup errors.
2357
- *
2358
- * @returns this fiber, once it has settled into a stable state.
2359
- * @throws the config-validation or plugin-startup error, if any.
2360
- */
2361
- async await() {
2362
- while (this.inertia) await this.inertia;
2363
- if (this._error) throw this._error;
2364
- return this;
2365
- }
2366
- /**
2367
- * Dispose and immediately reload this plugin with its current config.
2414
+ * Register an exporter and dispose it with the current fiber.
2368
2415
  *
2369
- * @returns a promise resolving once the reload settled.
2370
- * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
2416
+ * @param exporter — the sink that receives structured log messages.
2417
+ * @returns a disposer that removes the exporter.
2371
2418
  */
2372
- async restart() {
2373
- this.assertActive();
2374
- this._setEpoch(INACTIVE);
2375
- this._refresh();
2376
- await this.await();
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()");
2377
2425
  }
2378
- /**
2379
- * Validate and apply new config, then restart the plugin.
2380
- *
2381
- * Runs the `internal/update` waterfall first, so update hooks (and HMR)
2382
- * can veto or replace the restart.
2383
- *
2384
- * @param config — the new raw config; validated before anything restarts.
2385
- * @param noSave — hint for persistence hooks not to write the change back.
2386
- * @returns nothing; the restart runs behind the `internal/update` waterfall.
2387
- * @throws {ValidationError} when the new config fails validation.
2388
- */
2389
- update(config, noSave = false) {
2390
- this.assertActive();
2391
- this._config = config;
2392
- if (this.state !== 2) {
2393
- this._error = void 0;
2394
- this._setEpoch(INACTIVE);
2395
- this._refresh();
2396
- return;
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);
2397
2432
  }
2398
- config = this._resolveConfig(config);
2399
- this.context.waterfall(this, "internal/update", config, noSave, () => {
2400
- this.config = config;
2401
- this._error = void 0;
2402
- return this.restart();
2403
- });
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
+ };
2404
2455
  }
2405
2456
  };
2406
2457
  //#endregion
@@ -2432,12 +2483,14 @@ var ReflectService = class {
2432
2483
  try {
2433
2484
  const def = target.reflect.props[prop];
2434
2485
  if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
2435
- if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
2486
+ const defSite = ctx[symbols.shadow] ?? ctx;
2487
+ if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false);
2436
2488
  return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
2437
- const key = target[symbols.isolate][prop];
2438
- let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
2489
+ const key = defSite[symbols.isolate][prop];
2490
+ let fiber = defSite.fiber;
2439
2491
  while (true) {
2440
- const impl = fiber.store?.[prop];
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;
2441
2494
  if (impl) return getTraceable(ctx, impl.value);
2442
2495
  if (prop in fiber.inject) {
2443
2496
  error.message = `cannot get required service "${prop}" in inactive context`;
@@ -2482,6 +2535,7 @@ var ReflectService = class {
2482
2535
  store = Object.create(null);
2483
2536
  /** Declared context properties (services and accessors), by name. */
2484
2537
  props = Object.create(null);
2538
+ _implCounter = 0;
2485
2539
  constructor(ctx) {
2486
2540
  this.ctx = ctx;
2487
2541
  defineProperty(this, symbols.tracker, {
@@ -2522,7 +2576,7 @@ var ReflectService = class {
2522
2576
  const key = this.ctx[symbols.isolate][name];
2523
2577
  const impl = key && this.store[key];
2524
2578
  if (!impl) return;
2525
- if (strict && impl.fiber.state !== 2) return;
2579
+ if (strict && impl.ctx.fiber.state !== 2) return;
2526
2580
  return impl;
2527
2581
  }
2528
2582
  /**
@@ -2538,7 +2592,7 @@ var ReflectService = class {
2538
2592
  const key = this.ctx[symbols.isolate][name];
2539
2593
  const impl = this.store[key];
2540
2594
  if (!impl) throw new Error(`cannot set property "${name}" without provide`);
2541
- if (impl.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`);
2595
+ if (impl.ctx.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`);
2542
2596
  impl.value = value;
2543
2597
  return true;
2544
2598
  }
@@ -2560,20 +2614,27 @@ var ReflectService = class {
2560
2614
  this.ctx.root[symbols.isolate][name] ??= Symbol(name);
2561
2615
  const key = this.ctx[symbols.isolate][name];
2562
2616
  const impl = {
2617
+ uid: ++this._implCounter,
2563
2618
  name,
2564
2619
  value,
2565
- fiber: this.ctx.fiber,
2566
- check
2620
+ ctx: this.ctx,
2621
+ check,
2622
+ isolate: key,
2623
+ dependents: /* @__PURE__ */ new Set()
2567
2624
  };
2568
- if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].fiber.name}>`);
2625
+ if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].ctx.fiber.name}>`);
2569
2626
  this.store[key] = impl;
2570
- this.ctx.fiber.store[name] = impl;
2627
+ this.ctx.fiber.provisions.add(impl);
2571
2628
  if (this.ctx.fiber.state === 2) this.notify([name]);
2572
2629
  return async () => {
2573
- delete this.store[key];
2574
- const fibers = this.notify([name]);
2575
- await Promise.allSettled(fibers.map((fiber) => fiber.await()));
2576
- delete this.ctx.fiber.store[name];
2630
+ if (this.store[impl.isolate] === impl) delete this.store[impl.isolate];
2631
+ this.ctx.isolate(name, impl.isolate).reflect.notify([name]);
2632
+ await new Promise((resolve) => {
2633
+ impl.release = resolve;
2634
+ if (!impl.dependents.size) resolve();
2635
+ });
2636
+ impl.release = void 0;
2637
+ this.ctx.fiber.provisions.delete(impl);
2577
2638
  };
2578
2639
  }, `ctx.provide(${JSON.stringify(name)})`);
2579
2640
  }
@@ -2582,10 +2643,8 @@ var ReflectService = class {
2582
2643
  *
2583
2644
  * @param names — the service names that changed.
2584
2645
  * @param filter — restricts notification to matching isolation scopes.
2585
- * @returns the fibers whose dependency state was refreshed.
2586
2646
  */
2587
2647
  notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) {
2588
- const fibers = [];
2589
2648
  for (const runtime of this.ctx.registry.values()) for (const fiber of runtime.fibers) {
2590
2649
  let hasUpdate = false;
2591
2650
  for (const name of names) {
@@ -2596,14 +2655,12 @@ var ReflectService = class {
2596
2655
  }
2597
2656
  if (!hasUpdate) continue;
2598
2657
  fiber._refresh();
2599
- fibers.push(fiber);
2600
2658
  }
2601
2659
  for (const name of names) {
2602
2660
  const self = Object.create(this.ctx);
2603
2661
  self[symbols.filter] = (target) => filter(target, name);
2604
2662
  this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value);
2605
2663
  }
2606
- return fibers;
2607
2664
  }
2608
2665
  /**
2609
2666
  * Define a computed context property backed by get/set hooks.
@@ -3172,6 +3229,7 @@ const KNOWN_SESSION_EVENT_TYPES = new Set([
3172
3229
  "team/member",
3173
3230
  "team/message/delivered",
3174
3231
  "team/message/queued",
3232
+ "team/mode",
3175
3233
  "team/task",
3176
3234
  "todo/write",
3177
3235
  "tool-workflow/agent-end",
@@ -3338,12 +3396,12 @@ function assertSourceEventReferences(event, shadowedSeqs) {
3338
3396
  if (missing.length > 0) throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(", ")}`);
3339
3397
  }
3340
3398
  /** Resolve tool additions against their immutable historical request header. */
3341
- function assertDeveloperHeader(event, events, baseSeq) {
3399
+ function assertDeveloperHeader(event, read) {
3342
3400
  if (event.type !== "developer/message") return;
3343
3401
  validateSessionEventData(event, `developer/message at seq ${event.seq}`);
3344
3402
  if (event.data.headerSeq === void 0) return;
3345
3403
  const headerSeq = event.data.headerSeq;
3346
- const headerEvent = events[headerSeq - baseSeq];
3404
+ const headerEvent = read(headerSeq);
3347
3405
  if (headerSeq >= event.seq || headerEvent?.type !== "request/header") throw new Error("developer/message headerSeq must reference an earlier request/header");
3348
3406
  for (const block of event.data.message.content) {
3349
3407
  if (block.type !== "tool-addition") continue;
@@ -3398,11 +3456,11 @@ function isDeepEqualJson(a, b) {
3398
3456
  return aKeys.every((key) => Object.hasOwn(b, key) && isDeepEqualJson(a[key], bRecord[key]));
3399
3457
  }
3400
3458
  /** Restrict a tool-result replacement to one current result's content. */
3401
- function assertToolResultRewrite(event, shadowedSeqs, events, baseSeq) {
3459
+ function assertToolResultRewrite(event, shadowedSeqs, read) {
3402
3460
  if (event.type !== "tool/result") return;
3403
3461
  if (shadowedSeqs.length !== 1) throw new Error("tool/result surface replacement must rewrite exactly one current node");
3404
3462
  for (const originalSeq of shadowedSeqs) {
3405
- const original = events[originalSeq - baseSeq];
3463
+ const original = read(originalSeq);
3406
3464
  if (original?.type !== "tool/result") throw new Error("tool/result surface replacement must target a current tool/result");
3407
3465
  const originalRest = { ...original.data };
3408
3466
  const replacementRest = { ...event.data };
@@ -3423,27 +3481,36 @@ function assertToolResultRewrite(event, shadowedSeqs, events, baseSeq) {
3423
3481
  * exactly that node; later system nodes carry no protection and a compaction
3424
3482
  * range may shadow them.
3425
3483
  */
3426
- function assertSystemHeadRewrite(event, state, startIdx, shadowedSeqs, events, baseSeq) {
3484
+ function assertSystemHeadRewrite(event, state, startIdx, shadowedSeqs, read) {
3427
3485
  if (startIdx !== 0) return;
3428
- if (events[state.nodes[0] - baseSeq]?.type !== "system/message") return;
3486
+ if (read(state.nodes[0])?.type !== "system/message") return;
3429
3487
  if (event.type !== "system/message" || shadowedSeqs.length !== 1) throw new Error("surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node");
3430
3488
  }
3431
3489
  /** Validate one event at its replay boundary and prepare its atomic fold transition. */
3432
- function planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections) {
3490
+ function planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections, candidates) {
3433
3491
  if (event.seq !== expectedSeq) throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`);
3434
3492
  const surfaceOp = validateSurfaceMetadata(event);
3435
- assertDeveloperHeader(event, events, baseSeq);
3436
- const projection = projections.find((item) => item.type === event.type);
3437
- if (projection !== void 0) return {
3438
- kind: "project",
3439
- projection,
3440
- messages: projection.project(event, {
3441
- nodes: state.nodes,
3442
- events,
3443
- baseSeq,
3444
- messages: state.projectedMessages
3445
- })
3493
+ const read = (seq) => {
3494
+ const index = seq - baseSeq;
3495
+ return index < events.length ? events[index] : candidates?.[index - events.length];
3446
3496
  };
3497
+ assertDeveloperHeader(event, read);
3498
+ const projection = projections.find((item) => item.type === event.type);
3499
+ if (projection !== void 0) {
3500
+ let projectionEvents;
3501
+ return {
3502
+ kind: "project",
3503
+ projection,
3504
+ messages: projection.project(event, {
3505
+ nodes: state.nodes,
3506
+ get events() {
3507
+ return candidates === void 0 ? events : projectionEvents ??= [...events, ...candidates];
3508
+ },
3509
+ baseSeq,
3510
+ messages: state.projectedMessages
3511
+ })
3512
+ };
3513
+ }
3447
3514
  if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) throw new Error(`session event "${event.type}" requires a message projection; load its owning plugin or supply its projection definition`);
3448
3515
  if (surfaceOp === void 0) return;
3449
3516
  if (surfaceOp === "append") return {
@@ -3452,8 +3519,8 @@ function planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projection
3452
3519
  };
3453
3520
  const range = replacementRange(state, surfaceOp);
3454
3521
  assertSourceEventReferences(event, range.shadowedSeqs);
3455
- assertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq);
3456
- assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, events, baseSeq);
3522
+ assertToolResultRewrite(event, range.shadowedSeqs, read);
3523
+ assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read);
3457
3524
  return {
3458
3525
  kind: "replace",
3459
3526
  seq: event.seq,
@@ -3522,6 +3589,40 @@ var SurfaceManager = class {
3522
3589
  plan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq, this.projections)
3523
3590
  };
3524
3591
  }
3592
+ /**
3593
+ * Validate consecutive candidates against an isolated surface fold.
3594
+ * @param events - candidates immediately following the committed log.
3595
+ * @returns a callback adopting the validated fold after all candidates enter the log.
3596
+ */
3597
+ prepareBatch(events) {
3598
+ this._assertProjections();
3599
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
3600
+ const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1);
3601
+ if (events.every((event) => (event.surfaceOp === void 0 || event.surfaceOp === "append") && !this.projections.some((projection) => projection.type === event.type))) {
3602
+ const plans = events.map((event, index) => planSurfaceEvent(this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events));
3603
+ return () => {
3604
+ for (const plan of plans) applySurfacePlan(this._state, plan);
3605
+ this._lastProcessedSeq = lastProcessedSeq;
3606
+ this._pendingPlan = void 0;
3607
+ };
3608
+ }
3609
+ const state = {
3610
+ ...this._state,
3611
+ nodes: [...this._state.nodes],
3612
+ projectedMessages: new Map(this._state.projectedMessages),
3613
+ projections: new Set(this._state.projections)
3614
+ };
3615
+ const plans = events.map((event, index) => {
3616
+ const plan = planSurfaceEvent(state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events);
3617
+ applySurfacePlan(state, plan);
3618
+ return plan;
3619
+ });
3620
+ return () => {
3621
+ for (const plan of plans) applySurfacePlan(this._state, plan);
3622
+ this._lastProcessedSeq = lastProcessedSeq;
3623
+ this._pendingPlan = void 0;
3624
+ };
3625
+ }
3525
3626
  /** Monotonic count of folded positional replacements. */
3526
3627
  get replaceGeneration() {
3527
3628
  this._assertProjections();
@@ -4442,11 +4543,11 @@ defineMethod("transform", [
4442
4543
  /** Largest delay Node schedules without clamping it to one millisecond. */
4443
4544
  const MAX_TIMER_DELAY_MS = 2147483647;
4444
4545
  //#endregion
4445
- //#region ../../llm/llm/src/error.ts
4546
+ //#region ../../util/error/src/index.ts
4446
4547
  /**
4447
4548
  * Harness error base with a stable machine-routable code and chained cause.
4448
4549
  * Package errors extend it so tool results and replay can retain failure class.
4449
- * @module @unieai/rabi-llm/error
4550
+ * @module @unieai/rabi-error
4450
4551
  */
4451
4552
  /**
4452
4553
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -4463,6 +4564,76 @@ var HarnessError = class extends Error {
4463
4564
  this.name = new.target.name;
4464
4565
  }
4465
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 `@unieai/rabi-error` and is re-exported here, so both
4572
+ * import paths name the same class.
4573
+ * @module @unieai/rabi-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]));
4466
4637
  /**
4467
4638
  * Canonical provider-neutral code for a response that completed normally but
4468
4639
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -4498,14 +4669,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
4498
4669
  "TRANSPORT"
4499
4670
  ]);
4500
4671
  const backoffSchema = Schema.object({
4501
- initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
4502
- maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
4672
+ initialDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
4673
+ maxDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
4503
4674
  jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
4504
4675
  });
4505
4676
  const normalPolicySchema = Schema.object({
4506
4677
  mode: Schema.const("normal").required(),
4507
4678
  maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
4508
- retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
4679
+ retryableCodes: Schema.array(Schema.union([...RETRY_CODE_CHOICES.map((code) => Schema.const(code)), Schema.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
4509
4680
  backoff: backoffSchema
4510
4681
  });
4511
4682
  const alwaysPolicySchema = Schema.object({
@@ -4789,27 +4960,47 @@ function withoutDeveloperMessages(messages) {
4789
4960
  const retained = messages.filter((message) => message.role !== "developer");
4790
4961
  return retained.length === messages.length ? messages : retained;
4791
4962
  }
4792
- function toolDeclarations(tools, mode, history) {
4963
+ function toolDeclarations(history) {
4793
4964
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
4794
4965
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
4795
4966
  ...tool,
4796
4967
  deferLoading: true
4797
4968
  });
4798
- switch (mode) {
4799
- case "in-history": return declarations;
4800
- case "addition-only": {
4801
- const activeNames = new Set(tools?.map((tool) => tool.name));
4802
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
4803
- return declarations;
4804
- }
4805
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
4806
- default: return assertNever(mode);
4807
- }
4969
+ return declarations;
4970
+ }
4971
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
4972
+ function rebaseAdditionOnlyHistory(history, messages) {
4973
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
4974
+ let baseline = history.tools;
4975
+ let retainedFrom = 0;
4976
+ for (const [index, update] of history.updates.entries()) {
4977
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
4978
+ let reset = available.size === 0 && additions.size > 0;
4979
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
4980
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
4981
+ available.set(tool.name, tool);
4982
+ } else if (block.type === "tool-removal") {
4983
+ reset = true;
4984
+ available.delete(block.toolName);
4985
+ }
4986
+ if (reset) {
4987
+ baseline = [...available.values()];
4988
+ retainedFrom = index + 1;
4989
+ }
4990
+ }
4991
+ return retainedFrom === 0 ? history : {
4992
+ tools: baseline,
4993
+ updates: history.updates.slice(retainedFrom)
4994
+ };
4808
4995
  }
4809
4996
  /**
4810
4997
  * Construct provider declarations from session-folded history without changing logged active tools.
4811
4998
  * Unsupported routes and incomplete history use current declarations without developer updates.
4812
- * Explicitly deferred baseline tools become available only after their first retained addition.
4999
+ * Explicitly deferred declarations require an addition to activate them.
5000
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
5001
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
5002
+ * deferred declarations count as existing tools.
5003
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
4813
5004
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
4814
5005
  * @param tools - currently active tool schemas.
4815
5006
  * @param toolUpdate - the resolved route's update mode.
@@ -4829,14 +5020,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
4829
5020
  messages: withoutDeveloperMessages(messages),
4830
5021
  tools
4831
5022
  };
4832
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
4833
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
5023
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
5024
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
4834
5025
  messages: withoutDeveloperMessages(messages),
4835
5026
  tools
4836
5027
  };
4837
- const declarations = toolDeclarations(tools, toolUpdate, history);
5028
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
5029
+ const declarations = toolDeclarations(projectedHistory);
4838
5030
  const updateIds = new Set(history.updates.map((update) => update.messageId));
4839
- const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
5031
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
5032
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
4840
5033
  const projectedMessages = [];
4841
5034
  for (const message of messages) {
4842
5035
  if (message.role !== "developer") {
@@ -4847,6 +5040,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
4847
5040
  const content = message.content.filter((block) => {
4848
5041
  switch (block.type) {
4849
5042
  case "tool-addition":
5043
+ if (!retainedUpdateIds.has(message.id)) return false;
4850
5044
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
4851
5045
  offered.add(block.toolName);
4852
5046
  return true;
@@ -5377,13 +5571,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
5377
5571
  /**
5378
5572
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
5379
5573
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
5574
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
5575
+ * another provider, whose code may be any string, is re-raised through
5576
+ * {@link LlmError.fromFailure}.
5380
5577
  */
5381
- var LlmError = class extends HarnessError {
5578
+ var LlmError = class LlmError extends HarnessError {
5382
5579
  /** Serializable facts retained beside this live Error. */
5383
5580
  failure;
5384
5581
  /**
5385
5582
  * @param message - non-empty human-readable failure summary.
5386
- * @param code - non-empty stable provider-neutral machine code.
5583
+ * @param code - built-in stable provider-neutral machine code.
5387
5584
  * @param options - optional cause and validated serializable provider facts.
5388
5585
  */
5389
5586
  constructor(message, code, options) {
@@ -5403,6 +5600,18 @@ var LlmError = class extends HarnessError {
5403
5600
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
5404
5601
  });
5405
5602
  }
5603
+ /**
5604
+ * Raise an observed failure again with its own code, which any provider may have chosen.
5605
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
5606
+ * @param options - optional cause.
5607
+ * @returns an error carrying the failure's message, code, and provider facts.
5608
+ */
5609
+ static fromFailure(failure, options) {
5610
+ return new LlmError(failure.message, failure.code, {
5611
+ ...failure,
5612
+ ...options
5613
+ });
5614
+ }
5406
5615
  };
5407
5616
  (() => {
5408
5617
  let _classSuper = TypertRemoteService;
@@ -5737,12 +5946,17 @@ var LlmError = class extends HarnessError {
5737
5946
  if (typeof model.provider !== "string" || model.provider !== provider || typeof model.id !== "string" || model.id.length === 0 || typeof model.name !== "string" || model.name.length === 0 || model.description !== void 0 && typeof model.description !== "string" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider "${provider}"`, "INVALID_CATALOG");
5738
5947
  seen.add(model.id);
5739
5948
  const inputModalities = this.detachedModalities(model.inputModalities);
5949
+ const badge = model.badge;
5740
5950
  return {
5741
5951
  provider: model.provider,
5742
5952
  id: model.id,
5743
5953
  name: model.name,
5744
5954
  ...model.description === void 0 ? {} : { description: model.description },
5745
- ...inputModalities === void 0 ? {} : { inputModalities }
5955
+ ...inputModalities === void 0 ? {} : { inputModalities },
5956
+ ...badge === void 0 ? {} : { badge: {
5957
+ text: typeof badge.text === "string" ? badge.text : { ...badge.text },
5958
+ tone: badge.tone
5959
+ } }
5746
5960
  };
5747
5961
  });
5748
5962
  }
@@ -6373,7 +6587,7 @@ function invokeContainedSessionObservers(ctx, name, id, args, callbacks) {
6373
6587
  ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`);
6374
6588
  }
6375
6589
  }
6376
- /** Store attachment for the append path; module-private to keep Session store-agnostic publicly. */
6590
+ /** Store-owned Sessions retain a null entry while unentered; absent keys are independent. */
6377
6591
  const attachments = /* @__PURE__ */ new WeakMap();
6378
6592
  /**
6379
6593
  * Grammar of a {@link PluginRecordType}: `plugin:` followed by
@@ -6401,6 +6615,36 @@ function assertPluginRecordEvent(value) {
6401
6615
  const { type } = value;
6402
6616
  if (!isPluginRecordType(type)) throw new Error(`plugin record type "${type}" must be "plugin:" followed by lowercase slash-separated segments`);
6403
6617
  }
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`);
6629
+ return {
6630
+ type,
6631
+ data: dataSnapshot,
6632
+ surface
6633
+ };
6634
+ }
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;
6647
+ }
6404
6648
  /**
6405
6649
  * An event-sourced session: an append-only log of {@link SessionEvent}s.
6406
6650
  *
@@ -6411,6 +6655,7 @@ function assertPluginRecordEvent(value) {
6411
6655
  */
6412
6656
  var Session = class Session {
6413
6657
  log = [];
6658
+ batchPublication;
6414
6659
  /** Single incremental owner of surface acceptance and projection state. */
6415
6660
  surfaceManager;
6416
6661
  /** The ordered surface over this session's event log. */
@@ -6565,65 +6810,68 @@ var Session = class Session {
6565
6810
  get seq() {
6566
6811
  return SessionLogOffset(this.log.length);
6567
6812
  }
6568
- /**
6569
- * Append one typed event to the log and synchronously notify observers via
6570
- * the store-owned, module-private publication hooks. The hot path never blocks
6571
- * on I/O — persistence plugins buffer asynchronously. Once the event enters
6572
- * the log, the append is committed: observer failures are logged and
6573
- * contained per listener, so they do not change the return value or prevent
6574
- * later listeners from observing the same accepted event.
6575
- *
6576
- * @param type - The event type (key of {@link SessionEventMap}).
6577
- * @param data - The event payload; must be JSON-serializable.
6578
- * @param opts - Surface metadata: `surfaceOp` controls how the event enters
6579
- * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
6580
- * events this one derives from. REQUIRED for
6581
- * {@link SurfaceEventType} events (every message-producing event must
6582
- * declare how it joins the surface, the sole source of derived model
6583
- * history) and
6584
- * rejected by the compiler for non-surface types like `turn/start` or
6585
- * `assistant/attempt`. Assistant messages embed their exact provider
6586
- * stream and cannot cite top-level source events.
6587
- * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
6588
- * `data` that entered the log, so reading `event.data` back sees the logged
6589
- * value, never the caller's still-mutable input.
6590
- * @throws if `data` or surface metadata is not losslessly JSON-serializable
6591
- * (BigInt, function, symbol, undefined, negative zero, non-finite number,
6592
- * circular reference, sparse array, or an exotic object such as
6593
- * Map/Set/Date/class instance), or when the candidate violates the
6594
- * request-header empty-field or tool-error consistency rules, or the
6595
- * canonical surface contract (marker shape and eligibility, unique
6596
- * earlier source-event references, positional replacement validity, and complete
6597
- * shadowed-node coverage). One iterative pass reads, validates, and
6598
- * copies each nested value once, so a stateful getter cannot supply one value
6599
- * to validation and another to storage. The event log is the durable source
6600
- * of truth, so a bad event fails at the append site rather than later during
6601
- * a backend flush. A synchronous internal dispatch validation failure or an
6602
- * append reentered while this acceptance/publication boundary is open also
6603
- * rejects before the log changes.
6604
- */
6813
+ /** Current event while synchronously notifying a batch's observers. */
6814
+ get currentBatchPublication() {
6815
+ return this.batchPublication;
6816
+ }
6605
6817
  append(type, data, ...opts) {
6606
- const surfaceOpts = opts[0];
6607
- const surfaceMetadata = {
6608
- ...surfaceOpts?.sourceEventSeqs === void 0 ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs },
6609
- ...surfaceOpts?.surfaceOp === void 0 ? {} : { surfaceOp: surfaceOpts.surfaceOp }
6610
- };
6611
- const dataSnapshot = snapshotJsonValue(data);
6612
- if (dataSnapshot === void 0) throw new Error(`session event "${type}" carries non-JSON-serializable data`);
6613
- const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata);
6614
- if (surfaceMetadataSnapshot === void 0) throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`);
6818
+ if (typeof type !== "string") return this.#appendEvents(type);
6819
+ this.publicationEntry();
6820
+ const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`);
6615
6821
  const entry = this.publicationEntry();
6616
- const event = deepFreeze({
6617
- type,
6618
- seq: SessionSeq(this.log.length),
6619
- time: Date.now(),
6620
- data: dataSnapshot,
6621
- ...surfaceMetadataSnapshot
6622
- });
6623
- validateSessionEventData(event, `session event "${type}" at seq ${event.seq}`);
6822
+ const event = createAppendEvent(snapshot, SessionSeq(this.log.length));
6624
6823
  this.commit(event, entry);
6625
6824
  return event;
6626
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
+ }
6627
6875
  static {}
6628
6876
  /**
6629
6877
  * Commit one plugin record; {@link appendPluginRecord} is the only caller.
@@ -6632,6 +6880,7 @@ var Session = class Session {
6632
6880
  * @returns the record's sequence number.
6633
6881
  */
6634
6882
  #appendRecord(type, data) {
6883
+ this.publicationEntry();
6635
6884
  const dataSnapshot = snapshotJsonValue(data);
6636
6885
  if (dataSnapshot === void 0) throw new Error(`plugin record "${type}" carries non-JSON-serializable data`);
6637
6886
  const entry = this.publicationEntry();
@@ -6647,12 +6896,13 @@ var Session = class Session {
6647
6896
  return record.seq;
6648
6897
  }
6649
6898
  /**
6650
- * Read the store attachment for one append, refusing an append that
6651
- * reenters while another append is being published.
6652
- * @returns the attachment, or undefined for a detached Session.
6899
+ * Require announced membership for store-owned Sessions and refuse reentrant publication.
6900
+ * @returns the current store attachment, or undefined for an independent Session.
6653
6901
  */
6654
6902
  publicationEntry() {
6655
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`);
6656
6906
  if (entry?.appending) throw new Error("session append cannot reenter while another append is being published");
6657
6907
  return entry;
6658
6908
  }
@@ -6666,20 +6916,19 @@ var Session = class Session {
6666
6916
  this.surfaceManager.validateNext(event);
6667
6917
  if (entry !== void 0) entry.appending = true;
6668
6918
  try {
6669
- let callbacks;
6670
6919
  const callbackArgs = [this, event];
6671
- if (entry !== void 0) callbacks = collectSessionCallbacks(entry.emitCtx, [
6920
+ const callbacks = entry === void 0 ? void 0 : collectSessionCallbacks(entry.emitCtx, [
6672
6921
  entry.carrier,
6673
6922
  "session/event",
6674
6923
  ...callbackArgs
6675
6924
  ]);
6676
6925
  this.log.push(event);
6677
6926
  this.eventsSnapshot = void 0;
6678
- if (callbacks !== void 0 && entry !== void 0) invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, callbackArgs, callbacks);
6927
+ if (entry !== void 0 && callbacks !== void 0) invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, callbackArgs, callbacks);
6679
6928
  } finally {
6680
6929
  if (entry !== void 0) {
6681
6930
  entry.appending = false;
6682
- if (entry.detachRequested && !entry.announcing) entry.detach();
6931
+ if (entry.detachRequested && entry.announcement !== "dispatching") entry.detach();
6683
6932
  }
6684
6933
  }
6685
6934
  }
@@ -7514,11 +7763,8 @@ const RELEASED_V0_EVENT_DISPOSITIONS = Object.freeze({
7514
7763
  ]),
7515
7764
  "step/end": disposition(["turn", "step"]),
7516
7765
  "step/start": disposition(["turn", "step"]),
7517
- "subagent/descriptor": disposition([
7766
+ "subagent/descriptor": disposition(["version", "provider"], [
7518
7767
  "mode",
7519
- "version",
7520
- "provider"
7521
- ], [
7522
7768
  "label",
7523
7769
  "agentProvider",
7524
7770
  "agentModel",
@@ -7606,6 +7852,43 @@ const RELEASED_V0_EVENT_DISPOSITIONS = Object.freeze({
7606
7852
  });
7607
7853
  Object.freeze(Object.keys(RELEASED_V0_EVENT_DISPOSITIONS).sort((left, right) => left.localeCompare(right, "en")));
7608
7854
  //#endregion
7855
+ //#region ../../util/time/src/instant.ts
7856
+ /** Inclusive lower epoch-millisecond bound of a four-digit-year RFC 3339 UTC instant. */
7857
+ const MIN_FOUR_DIGIT_YEAR_MS = Date.parse("0001-01-01T00:00:00.000Z");
7858
+ /** Inclusive upper epoch-millisecond bound of a four-digit-year RFC 3339 UTC instant. */
7859
+ const MAX_FOUR_DIGIT_YEAR_MS = Date.parse("9999-12-31T23:59:59.999Z");
7860
+ /** Canonical four-digit-year RFC 3339 UTC instant with mandatory milliseconds. */
7861
+ const UTC_INSTANT = /^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/;
7862
+ new RegExp(String.raw`^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})` + String.raw`T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})` + String.raw`(?:\.(?<fraction>\d{1,3}))?(?<zone>Z|(?<sign>[+-])` + String.raw`(?<offsetHour>\d{2}):(?<offsetMinute>\d{2}))$`);
7863
+ /** Reject with one stable reason. */
7864
+ function rejected(reason) {
7865
+ return Object.freeze({
7866
+ kind: "rejected",
7867
+ reason
7868
+ });
7869
+ }
7870
+ /** Whether an integral epoch is inside the four-digit-year range. */
7871
+ function inFourDigitYearRange(epoch) {
7872
+ return Number.isSafeInteger(epoch) && epoch >= MIN_FOUR_DIGIT_YEAR_MS && epoch <= MAX_FOUR_DIGIT_YEAR_MS;
7873
+ }
7874
+ /**
7875
+ * Validate one canonical four-digit-year RFC 3339 UTC instant.
7876
+ *
7877
+ * The accepted profile carries exactly three fractional digits and a `Z`, and
7878
+ * every year from 0001 through 9999 whose calendar date exists is representable.
7879
+ * @param value - Untrusted candidate instant.
7880
+ * @returns The epoch milliseconds, or the reason the text is not the canonical profile.
7881
+ */
7882
+ function fourDigitYearEpoch(value) {
7883
+ if (!UTC_INSTANT.test(value)) return rejected("not_rfc3339");
7884
+ const epoch = Date.parse(value);
7885
+ if (!Number.isFinite(epoch) || !inFourDigitYearRange(epoch) || new Date(epoch).toISOString() !== value) return rejected("not_a_calendar_date");
7886
+ return Object.freeze({
7887
+ kind: "accepted",
7888
+ epoch
7889
+ });
7890
+ }
7891
+ //#endregion
7609
7892
  //#region ../session-format-v0-to-v1/src/validation-helpers.ts
7610
7893
  /**
7611
7894
  * Require one plain JSON object.
@@ -8638,7 +8921,7 @@ function scheduleIdValue(value, label) {
8638
8921
  if (value.trim() !== value) throw new SessionFormatError(`${label} must not have surrounding whitespace`);
8639
8922
  }
8640
8923
  function instantValue(value, label) {
8641
- if (typeof value !== "string" || !/^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/u.test(value) || !Number.isFinite(Date.parse(value)) || new Date(Date.parse(value)).toISOString() !== value) throw new SessionFormatError(`${label} must be a canonical UTC instant`);
8924
+ if (typeof value !== "string" || fourDigitYearEpoch(value).kind !== "accepted") throw new SessionFormatError(`${label} must be a canonical UTC instant`);
8642
8925
  }
8643
8926
  function titleSourceValue(value, label) {
8644
8927
  const source = releasedV0Record(value, label);
@@ -8656,10 +8939,27 @@ function modelRouteValue(value, label) {
8656
8939
  nonEmptyString(route["provider"], `${label} provider`);
8657
8940
  nonEmptyString(route["model"], `${label} model`);
8658
8941
  }
8942
+ /** `subagent/descriptor` versions that format v0 logs contain. */
8943
+ const SUBAGENT_DESCRIPTOR_VERSIONS = [
8944
+ 1,
8945
+ 2,
8946
+ 3
8947
+ ];
8659
8948
  function subagentDescriptorValue(data, label) {
8660
- literalValue(data["version"], [3], `${label} version`);
8949
+ literalValue(data["version"], SUBAGENT_DESCRIPTOR_VERSIONS, `${label} version`);
8661
8950
  nonEmptyString(data["provider"], `${label} provider`);
8662
- if (data["mode"] === "one-shot") {
8951
+ const composition = [
8952
+ "agentProvider",
8953
+ "agentModel",
8954
+ "persona",
8955
+ "toolFilter"
8956
+ ];
8957
+ if (data["version"] === 1) assertReleasedV0Keys(data, [
8958
+ "version",
8959
+ "provider",
8960
+ "label"
8961
+ ], composition, `${label} data`);
8962
+ else if (data["mode"] === "one-shot") {
8663
8963
  assertReleasedV0Keys(data, [
8664
8964
  "mode",
8665
8965
  "version",
@@ -8667,21 +8967,30 @@ function subagentDescriptorValue(data, label) {
8667
8967
  ], ["label"], `${label} data`);
8668
8968
  if (data["label"] !== void 0) stringValue(data["label"], `${label} label`);
8669
8969
  return;
8970
+ } else {
8971
+ literalValue(data["mode"], ["continuable"], `${label} mode`);
8972
+ assertReleasedV0Keys(data, [
8973
+ "mode",
8974
+ "version",
8975
+ "provider",
8976
+ "label"
8977
+ ], data["version"] === 3 ? [...composition, "agentReasoningEffort"] : composition, `${label} data`);
8670
8978
  }
8671
- literalValue(data["mode"], ["continuable"], `${label} mode`);
8672
- nonEmptyString(data["label"], `${label} label`);
8979
+ const strict = data["version"] === 3;
8980
+ const stringField = strict ? nonEmptyString : stringValue;
8981
+ stringField(data["label"], `${label} label`);
8673
8982
  for (const key of [
8674
8983
  "agentProvider",
8675
8984
  "agentModel",
8676
8985
  "agentReasoningEffort",
8677
8986
  "persona"
8678
- ]) if (data[key] !== void 0) nonEmptyString(data[key], `${label} ${key}`);
8679
- if (data["agentProvider"] === void 0 !== (data["agentModel"] === void 0)) throw new SessionFormatError(`${label} agentProvider and agentModel must be paired`);
8987
+ ]) if (data[key] !== void 0) stringField(data[key], `${label} ${key}`);
8988
+ if (strict && data["agentProvider"] === void 0 !== (data["agentModel"] === void 0)) throw new SessionFormatError(`${label} agentProvider and agentModel must be paired`);
8680
8989
  if (data["toolFilter"] !== void 0) {
8681
8990
  const filter = exactRecord(data["toolFilter"], `${label} toolFilter`, [], ["allow", "deny"]);
8682
8991
  if (filter["allow"] === void 0 && filter["deny"] === void 0) throw new SessionFormatError(`${label} toolFilter requires allow or deny`);
8683
- if (filter["allow"] !== void 0) arrayValue(filter["allow"], `${label} allow`, nonEmptyString);
8684
- if (filter["deny"] !== void 0) arrayValue(filter["deny"], `${label} deny`, nonEmptyString);
8992
+ if (filter["allow"] !== void 0) arrayValue(filter["allow"], `${label} allow`, stringField);
8993
+ if (filter["deny"] !== void 0) arrayValue(filter["deny"], `${label} deny`, stringField);
8685
8994
  }
8686
8995
  }
8687
8996
  function allowedModelsValue(value, label) {
@@ -8881,7 +9190,7 @@ function assertReleasedEventPayload(event, version) {
8881
9190
  /* v8 ignore next -- artifact coordinate validation admits only the frozen inventory before payload validation. */
8882
9191
  if (disposition === void 0) throw new SessionFormatUnsupportedMigrationError(`format v0 contains unknown historical event type ${JSON.stringify(event.type)} at seq ${event.seq}; migration refuses unknown historical events even when ignorable`);
8883
9192
  const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`);
8884
- if (event.type === "subagent/descriptor" && data["version"] !== 3) {
9193
+ if (event.type === "subagent/descriptor" && !SUBAGENT_DESCRIPTOR_VERSIONS.some((known) => known === data["version"])) {
8885
9194
  const descriptorVersion = sessionFormatCount(data["version"], `${event.type} ${event.seq} version`);
8886
9195
  if (version === 0) throw new SessionFormatUnsupportedMigrationError(`${event.type} ${event.seq} uses unsupported descriptor version ${descriptorVersion}`);
8887
9196
  return;
@@ -12416,20 +12725,38 @@ function validateDeliveryAccepted(event, currentVersion) {
12416
12725
  */
12417
12726
  function assertReleasedV4Relationships(artifact, knownEventTypes) {
12418
12727
  const ids = /* @__PURE__ */ new Set();
12728
+ const names = /* @__PURE__ */ new Set();
12419
12729
  for (const event of artifact.events) {
12420
12730
  if (!knownEventTypes.has(event.type)) continue;
12421
12731
  assertV4DeveloperData(event);
12422
12732
  assertV4MessageSources(event);
12423
12733
  const deliveryId = validateDeliveryAccepted(event, 4);
12424
- if (deliveryId !== void 0 && !(artifact.header.parentSession !== void 0 && event.seq < artifact.inheritedEventCount) && deliveryId !== artifact.header.id) throw new SessionFormatError("current-generation delivery marker names the wrong Session");
12734
+ if (deliveryId !== void 0 && event.seq >= artifact.inheritedEventCount && deliveryId !== artifact.header.id) throw new SessionFormatError("current-generation delivery marker names the wrong Session");
12425
12735
  if (event.type === "subagent/catalog" && event.seq >= artifact.inheritedEventCount) {
12426
- const id = catalogFact(event.data)["childId"];
12736
+ const fact = nativeCatalogFact(event.data);
12737
+ const id = fact["childId"];
12427
12738
  if (ids.has(id)) throw new SessionFormatError(`duplicate catalog child ${id}`);
12428
12739
  ids.add(id);
12740
+ if (fact["name"] === void 0) continue;
12741
+ const name = fact["name"];
12742
+ if (names.has(name)) throw new SessionFormatError(`duplicate catalog child name ${name}`);
12743
+ names.add(name);
12429
12744
  }
12430
12745
  }
12431
12746
  assertV4LifecycleRelationships(artifact, knownEventTypes);
12432
12747
  }
12748
+ /**
12749
+ * Validate an own native V4 catalog payload: a historical version or version 3,
12750
+ * which adds the child's name and is written only by native V4 creation.
12751
+ * @param value - native `subagent/catalog` payload.
12752
+ * @returns validated catalog payload.
12753
+ */
12754
+ function nativeCatalogFact(value) {
12755
+ if (!isSessionFormatJsonObject(value) || value["version"] !== 3) return catalogFact(value);
12756
+ if (typeof value["childId"] !== "string" || value["mode"] !== "continuable" && value["mode"] !== "external" || typeof value["name"] !== "string" || !/^[a-z][a-z0-9-]{0,31}$/u.test(value["name"]) || value["name"] === "lead" || value["mode"] === "continuable" && typeof value["label"] !== "string" || value["label"] !== void 0 && typeof value["label"] !== "string") throw new SessionFormatError("subagent/catalog requires a supported versioned catalog fact");
12757
+ sessionFormatCount(value["childCreatedAt"], "catalog child creation time");
12758
+ return value;
12759
+ }
12433
12760
  //#endregion
12434
12761
  //#region ../session-format-v3-to-v4/src/codec.ts
12435
12762
  /** V4 framing with native tool-role admission and released physical rows. */
@@ -12982,7 +13309,7 @@ function privateZstdStream(stream) {
12982
13309
  const candidate = stream;
12983
13310
  const handle = candidate._handle;
12984
13311
  const errorKey = Reflect.ownKeys(stream).find((key) => typeof key === "symbol" && key.description === "kError");
12985
- /* v8 ignore next -- one test runtime exposes one Node-private shape; the Node 22/24/26 matrix checks compatibility. */
13312
+ /* v8 ignore next -- one test runtime exposes one Node-private shape; the Node 24/26 matrix checks compatibility. */
12986
13313
  if (typeof handle !== "object" || handle === null || typeof handle.writeSync !== "function" || !(candidate._writeState instanceof Uint32Array) || candidate._writeState.length < 2 || typeof candidate._defaultFlushFlag !== "number" || errorKey === void 0 || candidate[errorKey] !== null) return void 0;
12987
13314
  return {
12988
13315
  stream,
@@ -13211,7 +13538,7 @@ async function compressZstdFrame(input) {
13211
13538
  return zstdCompressAsync(input, CHECKSUM_OPTIONS);
13212
13539
  }
13213
13540
  /**
13214
- * Select the shared private decoder when the running Node 22/24/26 shape is
13541
+ * Select the shared private decoder when the running Node 24/26 shape is
13215
13542
  * compatible, otherwise preserve correctness with the public one-shot API.
13216
13543
  * @returns a synchronous decoder with an implementation-independent lifecycle.
13217
13544
  */