@orkestrel/agent 0.0.31 → 0.0.33

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.
@@ -9,7 +9,7 @@ let _orkestrel_workspace = require("@orkestrel/workspace");
9
9
  let _orkestrel_queue = require("@orkestrel/queue");
10
10
  let _orkestrel_workflow = require("@orkestrel/workflow");
11
11
  let _orkestrel_abort = require("@orkestrel/abort");
12
- //#region src/core/constants.ts
12
+ // src/core/constants.ts
13
13
  /**
14
14
  * Lists the roles a conversation message can play, in the order the wire contract names them —
15
15
  * the one list the {@link import('./types.js').MessageRole} union derives from, the message
@@ -21,8 +21,7 @@ var MESSAGE_ROLES = Object.freeze([
21
21
  "assistant",
22
22
  "tool"
23
23
  ]);
24
- //#endregion
25
- //#region src/core/errors.ts
24
+ // src/core/errors.ts
26
25
  /**
27
26
  * Reports a judge call cancelled by the caller's signal or its deadline, carrying the
28
27
  * {@link JudgeResult} merged from the calls that completed before the cancel and the
@@ -41,11 +40,12 @@ var JudgeAbortError = class extends Error {
41
40
  constructor(partial, options) {
42
41
  super("judge call aborted", options);
43
42
  this.name = "JudgeAbortError";
43
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.JudgeAbortError"), { value: this });
44
44
  this.partial = partial;
45
45
  }
46
46
  };
47
47
  /**
48
- * Narrows a caught value to a {@link JudgeAbortError} through `instanceof`, so a `catch` can
48
+ * Narrows a caught value to a {@link JudgeAbortError} through its identity brand and declared members, so a `catch` can
49
49
  * recover its `partial` result.
50
50
  *
51
51
  * @param value - The caught value
@@ -56,10 +56,29 @@ var JudgeAbortError = class extends Error {
56
56
  * ```
57
57
  */
58
58
  function isJudgeAbortError(value) {
59
- return (0, _orkestrel_contract.isInstance)(value, JudgeAbortError);
59
+ return (0, _orkestrel_contract.holds)(() => {
60
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.JudgeAbortError"))?.value === value)) return false;
61
+ if (!(_orkestrel_contract.INTRINSICS.reflect.read(value, "code") === "ABORT")) return false;
62
+ const partial = _orkestrel_contract.INTRINSICS.reflect.read(value, "partial");
63
+ if (!((0, _orkestrel_contract.isObject)(partial) || (0, _orkestrel_contract.isFunction)(partial))) return false;
64
+ const answers = _orkestrel_contract.INTRINSICS.reflect.read(partial, "answers");
65
+ const refusals = _orkestrel_contract.INTRINSICS.reflect.read(partial, "refusals");
66
+ const usage = _orkestrel_contract.INTRINSICS.reflect.read(partial, "usage");
67
+ return (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "model")) && (usage === void 0 || ((0, _orkestrel_contract.isObject)(usage) || (0, _orkestrel_contract.isFunction)(usage)) && [
68
+ "prompt",
69
+ "completion",
70
+ "total"
71
+ ].every((key) => (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(usage, key)))) && ((0, _orkestrel_contract.isObject)(answers) || (0, _orkestrel_contract.isFunction)(answers)) && _orkestrel_contract.INTRINSICS.values(answers).every((answer) => {
72
+ if (!((0, _orkestrel_contract.isObject)(answer) || (0, _orkestrel_contract.isFunction)(answer))) return false;
73
+ const form = _orkestrel_contract.INTRINSICS.reflect.read(answer, "form");
74
+ if (form === "noul") return (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(answer, "noul"));
75
+ const probabilities = _orkestrel_contract.INTRINSICS.reflect.read(answer, "probabilities");
76
+ if (form === "score") return (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isNumber)(probabilities);
77
+ return form === "choice" && ((0, _orkestrel_contract.isObject)(probabilities) || (0, _orkestrel_contract.isFunction)(probabilities)) && _orkestrel_contract.INTRINSICS.values(probabilities).every(_orkestrel_contract.isNumber);
78
+ }) && (refusals === void 0 || ((0, _orkestrel_contract.isObject)(refusals) || (0, _orkestrel_contract.isFunction)(refusals)) && _orkestrel_contract.INTRINSICS.values(refusals).every((refusal) => ((0, _orkestrel_contract.isObject)(refusal) || (0, _orkestrel_contract.isFunction)(refusal)) && (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(refusal, "missing"))));
79
+ });
60
80
  }
61
- //#endregion
62
- //#region src/core/shapers.ts
81
+ // src/core/shapers.ts
63
82
  /**
64
83
  * Describes a tool call's JSON wire projection.
65
84
  *
@@ -89,12 +108,10 @@ var messageShape = (0, _orkestrel_contract.objectShape)({
89
108
  images: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.arrayShape)((0, _orkestrel_contract.stringShape)())),
90
109
  thinking: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
91
110
  });
92
- //#endregion
93
- //#region src/core/contracts.ts
111
+ // src/core/contracts.ts
94
112
  /** Validates and projects conversation messages at a JSON wire boundary. */
95
113
  var messageContract = (0, _orkestrel_contract.createContract)(messageShape);
96
- //#endregion
97
- //#region src/core/cloners.ts
114
+ // src/core/cloners.ts
98
115
  /**
99
116
  * Owns a value by serializing it to JSON and parsing the text, so the copy shares nothing with its source.
100
117
  *
@@ -116,8 +133,7 @@ function copyJSON(value) {
116
133
  if (!text.success || typeof text.value !== "string") return void 0;
117
134
  return (0, _orkestrel_contract.parseJSON)(text.value);
118
135
  }
119
- //#endregion
120
- //#region src/core/helpers.ts
136
+ // src/core/helpers.ts
121
137
  /**
122
138
  * Filters a list of members by a {@link import('./contexts/index.js').ScopeInterface} allow-list of keys —
123
139
  * `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys
@@ -456,8 +472,7 @@ function renderJSON(value) {
456
472
  function matchesJudgment(judgment, question, sources, state, model) {
457
473
  return judgment.model === model && judgment.state === state && judgment.sources.length === sources.length && judgment.sources.every((id, index) => id === sources[index]) && JSON.stringify(judgment.question) === JSON.stringify(question);
458
474
  }
459
- //#endregion
460
- //#region src/core/validators.ts
475
+ // src/core/validators.ts
461
476
  /**
462
477
  * Checks whether a value is a judge entry: a string, a JSON record, or a JSON array.
463
478
  *
@@ -534,8 +549,7 @@ function isJudgeQuestion(value) {
534
549
  function isNonNegativeSafeInteger(value) {
535
550
  return (0, _orkestrel_contract.isFiniteNumber)(value) && Number.isSafeInteger(value) && value >= 0;
536
551
  }
537
- //#endregion
538
- //#region src/core/providers/constants.ts
552
+ // src/core/providers/constants.ts
539
553
  /**
540
554
  * Names the opening tag a {@link import('./ThinkSplitter.js').ThinkSplitter} recognizes as the start of
541
555
  * an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models
@@ -601,8 +615,7 @@ var INVALID_RELAY_STATUS = 400;
601
615
  var OVERSIZED_RELAY_STATUS = 413;
602
616
  /** Names the System One decision endpoint shared by compatible servers. */
603
617
  var SYSTEM_ONE_PATH = "/v1/systemone";
604
- //#endregion
605
- //#region src/core/providers/errors.ts
618
+ // src/core/providers/errors.ts
606
619
  /**
607
620
  * Reports a provider stream cancelled mid-flight by its bound signal — thrown by the
608
621
  * `stream` method of a {@link ProviderInterface}, carrying the {@link ProviderResult} assembled from
@@ -623,11 +636,12 @@ var ProviderAbortError = class extends Error {
623
636
  constructor(partial, options) {
624
637
  super("provider stream aborted", options);
625
638
  this.name = "ProviderAbortError";
639
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ProviderAbortError"), { value: this });
626
640
  this.partial = partial;
627
641
  }
628
642
  };
629
643
  /**
630
- * Narrows an unknown caught value to a {@link ProviderAbortError} through `instanceof`, so a
644
+ * Narrows an unknown caught value to a {@link ProviderAbortError} through its identity brand and declared members, so a
631
645
  * `catch` can recover its `partial` result.
632
646
  *
633
647
  * @param value - The value to test (typically a `catch` binding)
@@ -643,7 +657,19 @@ var ProviderAbortError = class extends Error {
643
657
  * ```
644
658
  */
645
659
  function isProviderAbortError(value) {
646
- return (0, _orkestrel_contract.isInstance)(value, ProviderAbortError);
660
+ return (0, _orkestrel_contract.holds)(() => {
661
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ProviderAbortError"))?.value === value)) return false;
662
+ if (!(_orkestrel_contract.INTRINSICS.reflect.read(value, "code") === "ABORT")) return false;
663
+ const partial = _orkestrel_contract.INTRINSICS.reflect.read(value, "partial");
664
+ if (!((0, _orkestrel_contract.isObject)(partial) || (0, _orkestrel_contract.isFunction)(partial))) return false;
665
+ const usage = _orkestrel_contract.INTRINSICS.reflect.read(partial, "usage");
666
+ const tools = _orkestrel_contract.INTRINSICS.reflect.read(partial, "tools");
667
+ return (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "content")) && (_orkestrel_contract.INTRINSICS.reflect.read(partial, "thinking") === void 0 || (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "thinking"))) && (_orkestrel_contract.INTRINSICS.reflect.read(partial, "truncated") === void 0 || (0, _orkestrel_contract.isBoolean)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "truncated"))) && (usage === void 0 || ((0, _orkestrel_contract.isObject)(usage) || (0, _orkestrel_contract.isFunction)(usage)) && [
668
+ "prompt",
669
+ "completion",
670
+ "total"
671
+ ].every((key) => (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(usage, key)))) && (tools === void 0 || (0, _orkestrel_contract.arrayOf)((tool) => ((0, _orkestrel_contract.isObject)(tool) || (0, _orkestrel_contract.isFunction)(tool)) && (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(tool, "id")) && (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(tool, "name")) && ((0, _orkestrel_contract.isObject)(_orkestrel_contract.INTRINSICS.reflect.read(tool, "arguments")) || (0, _orkestrel_contract.isFunction)(_orkestrel_contract.INTRINSICS.reflect.read(tool, "arguments"))))(tools));
672
+ });
647
673
  }
648
674
  /**
649
675
  * Reports a coded provider failure with its HTTP status and underlying cause when available.
@@ -662,12 +688,13 @@ var ProviderError = class extends Error {
662
688
  constructor(code, message, options) {
663
689
  super(message, options);
664
690
  this.name = "ProviderError";
691
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ProviderError"), { value: this });
665
692
  this.code = code;
666
693
  this.status = options?.status;
667
694
  }
668
695
  };
669
696
  /**
670
- * Narrows a caught value to the provider failure class through `instanceof`.
697
+ * Narrows a caught value to the provider failure class through its identity brand and declared members.
671
698
  *
672
699
  * @param value - The caught value
673
700
  * @returns True if the value is a provider failure; false otherwise
@@ -677,7 +704,13 @@ var ProviderError = class extends Error {
677
704
  * ```
678
705
  */
679
706
  function isProviderError(value) {
680
- return (0, _orkestrel_contract.isInstance)(value, ProviderError);
707
+ return (0, _orkestrel_contract.holds)(() => {
708
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ProviderError"))?.value === value)) return false;
709
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
710
+ if (!(code === "HTTP" || code === "PROTOCOL" || code === "PROVIDER")) return false;
711
+ const status = _orkestrel_contract.INTRINSICS.reflect.read(value, "status");
712
+ return status === void 0 || (0, _orkestrel_contract.isNumber)(status);
713
+ });
681
714
  }
682
715
  /**
683
716
  * Reports a coded judge failure with its HTTP status and underlying cause when available.
@@ -696,12 +729,13 @@ var JudgeError = class extends Error {
696
729
  constructor(code, message, options) {
697
730
  super(message, options);
698
731
  this.name = "JudgeError";
732
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.JudgeError"), { value: this });
699
733
  this.code = code;
700
734
  this.status = options?.status;
701
735
  }
702
736
  };
703
737
  /**
704
- * Narrows a caught value to the judge failure class through `instanceof`.
738
+ * Narrows a caught value to the judge failure class through its identity brand and declared members.
705
739
  *
706
740
  * @param value - The caught value
707
741
  * @returns True if the value is a {@link JudgeError}; false otherwise
@@ -711,10 +745,15 @@ var JudgeError = class extends Error {
711
745
  * ```
712
746
  */
713
747
  function isJudgeError(value) {
714
- return (0, _orkestrel_contract.isInstance)(value, JudgeError);
748
+ return (0, _orkestrel_contract.holds)(() => {
749
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.JudgeError"))?.value === value)) return false;
750
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
751
+ if (!(code === "HTTP" || code === "PROTOCOL" || code === "QUESTION")) return false;
752
+ const status = _orkestrel_contract.INTRINSICS.reflect.read(value, "status");
753
+ return status === void 0 || (0, _orkestrel_contract.isNumber)(status);
754
+ });
715
755
  }
716
- //#endregion
717
- //#region src/core/providers/shapers.ts
756
+ // src/core/providers/shapers.ts
718
757
  /**
719
758
  * Describes a provider request's JSON wire projection.
720
759
  *
@@ -774,16 +813,14 @@ var relayFrameShape = (0, _orkestrel_contract.unionShape)((0, _orkestrel_contrac
774
813
  channel: (0, _orkestrel_contract.literalShape)(["error"]),
775
814
  message: (0, _orkestrel_contract.stringShape)()
776
815
  }));
777
- //#endregion
778
- //#region src/core/providers/contracts.ts
816
+ // src/core/providers/contracts.ts
779
817
  /** Validates and projects provider requests at a JSON wire boundary. */
780
818
  var providerRequestContract = (0, _orkestrel_contract.createContract)(providerRequestShape);
781
819
  /** Validates and projects provider results at a JSON wire boundary. */
782
820
  var providerResultContract = (0, _orkestrel_contract.createContract)(providerResultShape);
783
821
  /** Validates and projects channel-discriminated relay frames at a JSON wire boundary. */
784
822
  var relayFrameContract = (0, _orkestrel_contract.createContract)(relayFrameShape);
785
- //#endregion
786
- //#region src/core/providers/helpers.ts
823
+ // src/core/providers/helpers.ts
787
824
  /**
788
825
  * Assembles a provider result with only populated optional fields.
789
826
  *
@@ -1264,8 +1301,7 @@ function extractSystemOneUsage(usage) {
1264
1301
  });
1265
1302
  return extracted.success ? extracted.value : void 0;
1266
1303
  }
1267
- //#endregion
1268
- //#region src/core/providers/RelayStream.ts
1304
+ // src/core/providers/RelayStream.ts
1269
1305
  /**
1270
1306
  * Streams a provider call as validated NDJSON frames under response backpressure.
1271
1307
  *
@@ -1373,8 +1409,7 @@ var RelayStream = class {
1373
1409
  this.#signal.removeEventListener("abort", this.#listener);
1374
1410
  }
1375
1411
  };
1376
- //#endregion
1377
- //#region src/core/providers/ThinkSplitter.ts
1412
+ // src/core/providers/ThinkSplitter.ts
1378
1413
  /**
1379
1414
  * Separates `<think>…</think>` spans from raw content deltas with per-stream state: text inside a
1380
1415
  * span accumulates on `thinking`, and text outside it returns as clean content, so a provider
@@ -1492,8 +1527,7 @@ var ThinkSplitter = class {
1492
1527
  return Array.from({ length: max }, (_, index) => max - index).find((length) => this.#pending.endsWith(tag.slice(0, length))) ?? 0;
1493
1528
  }
1494
1529
  };
1495
- //#endregion
1496
- //#region src/core/providers/AgentProvider.ts
1530
+ // src/core/providers/AgentProvider.ts
1497
1531
  /**
1498
1532
  * Implements bounded HTTP streaming and result assembly behind concrete wire seams.
1499
1533
  *
@@ -1704,8 +1738,7 @@ var AgentProvider = class {
1704
1738
  return response;
1705
1739
  }
1706
1740
  };
1707
- //#endregion
1708
- //#region src/core/providers/RelayProvider.ts
1741
+ // src/core/providers/RelayProvider.ts
1709
1742
  /**
1710
1743
  * Carries provider calls over an authenticated NDJSON relay endpoint.
1711
1744
  *
@@ -1822,8 +1855,7 @@ var RelayProvider = class extends AgentProvider {
1822
1855
  return parser.parse("\n");
1823
1856
  }
1824
1857
  };
1825
- //#endregion
1826
- //#region src/core/providers/AgentJudge.ts
1858
+ // src/core/providers/AgentJudge.ts
1827
1859
  /**
1828
1860
  * Implements the bounded HTTP calls, validation, and result merging of a judge behind concrete
1829
1861
  * wire seams.
@@ -1963,8 +1995,7 @@ var AgentJudge = class {
1963
1995
  }
1964
1996
  }
1965
1997
  };
1966
- //#endregion
1967
- //#region src/core/providers/validators.ts
1998
+ // src/core/providers/validators.ts
1968
1999
  /**
1969
2000
  * Checks whether a value is a System One response envelope with optional model and usage.
1970
2001
  *
@@ -2022,8 +2053,7 @@ function isSystemOneAnswer(value) {
2022
2053
  });
2023
2054
  return checked.success && checked.value;
2024
2055
  }
2025
- //#endregion
2026
- //#region src/core/providers/SystemOneJudge.ts
2056
+ // src/core/providers/SystemOneJudge.ts
2027
2057
  /**
2028
2058
  * Carries judge questions over the System One protocol and derives answers from server distributions.
2029
2059
  *
@@ -2124,8 +2154,7 @@ var SystemOneJudge = class extends AgentJudge {
2124
2154
  };
2125
2155
  }
2126
2156
  };
2127
- //#endregion
2128
- //#region src/core/providers/factories.ts
2157
+ // src/core/providers/factories.ts
2129
2158
  /**
2130
2159
  * Creates an authorized relay handler that validates a bounded JSON request before streaming.
2131
2160
  *
@@ -2284,8 +2313,7 @@ function createThinkSplitter() {
2284
2313
  function createSystemOneJudge(options) {
2285
2314
  return new SystemOneJudge(options);
2286
2315
  }
2287
- //#endregion
2288
- //#region src/core/conversations/constants.ts
2316
+ // src/core/conversations/constants.ts
2289
2317
  /**
2290
2318
  * Sets the default number of recent live messages the `compact()` method of a
2291
2319
  * {@link ConversationInterface} retains verbatim — `0`, so a manual `compact()` keeps no recent tail and folds every
@@ -2312,8 +2340,7 @@ var DEFAULT_CONVERSATION_KEEP = 0;
2312
2340
  * because it interpolates the per-call provenance `label`).
2313
2341
  */
2314
2342
  var CONVERSATION_RECAP_PREFIX = "[Summary of earlier messages] ";
2315
- //#endregion
2316
- //#region src/core/conversations/errors.ts
2343
+ // src/core/conversations/errors.ts
2317
2344
  /**
2318
2345
  * Reports a conversation with no {@link ConversationSummaryHandler} to fold its messages with, a
2319
2346
  * `sections` cap below `1`, a `keep` that is not a nonnegative safe integer, or a judgment or
@@ -2350,12 +2377,13 @@ var ConversationError = class extends Error {
2350
2377
  constructor(code, message, options) {
2351
2378
  super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
2352
2379
  this.name = "ConversationError";
2380
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ConversationError"), { value: this });
2353
2381
  this.code = code;
2354
2382
  this.context = options?.context;
2355
2383
  }
2356
2384
  };
2357
2385
  /**
2358
- * Narrows an unknown caught value to a {@link ConversationError} through `instanceof`, so a
2386
+ * Narrows an unknown caught value to a {@link ConversationError} through its identity brand and declared members, so a
2359
2387
  * `catch` can branch on its `code`.
2360
2388
  *
2361
2389
  * @param value - The value to test (typically a `catch` binding)
@@ -2371,10 +2399,15 @@ var ConversationError = class extends Error {
2371
2399
  * ```
2372
2400
  */
2373
2401
  function isConversationError(value) {
2374
- return (0, _orkestrel_contract.isInstance)(value, ConversationError);
2402
+ return (0, _orkestrel_contract.holds)(() => {
2403
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ConversationError"))?.value === value)) return false;
2404
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
2405
+ if (!(code === "SUMMARIZER" || code === "SECTIONS" || code === "JUDGMENT" || code === "KEEP")) return false;
2406
+ const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
2407
+ return context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context);
2408
+ });
2375
2409
  }
2376
- //#endregion
2377
- //#region src/core/conversations/validators.ts
2410
+ // src/core/conversations/validators.ts
2378
2411
  /**
2379
2412
  * Checks whether a value satisfies the domain conversation-message contract.
2380
2413
  *
@@ -2516,8 +2549,7 @@ function isConversationSnapshot(value) {
2516
2549
  judgments: (0, _orkestrel_contract.optionalOf)((0, _orkestrel_contract.arrayOf)(isJudgment))
2517
2550
  }, ["judgments"])(value);
2518
2551
  }
2519
- //#endregion
2520
- //#region src/core/conversations/helpers.ts
2552
+ // src/core/conversations/helpers.ts
2521
2553
  /**
2522
2554
  * Builds records for answered or refused request keys, attaching usage only for a single question.
2523
2555
  *
@@ -2726,8 +2758,7 @@ function raceSignal(promise, signal) {
2726
2758
  promise.then(resolve, reject).finally(() => settled.abort());
2727
2759
  });
2728
2760
  }
2729
- //#endregion
2730
- //#region src/core/conversations/JudgmentManager.ts
2761
+ // src/core/conversations/JudgmentManager.ts
2731
2762
  /**
2732
2763
  * Stores judgments in insertion order and asks a judge only for unmatched question identities.
2733
2764
  *
@@ -2823,8 +2854,7 @@ var JudgmentManager = class {
2823
2854
  return structuredClone(judgment);
2824
2855
  }
2825
2856
  };
2826
- //#endregion
2827
- //#region src/core/conversations/Conversation.ts
2857
+ // src/core/conversations/Conversation.ts
2828
2858
  /**
2829
2859
  * Represents a conversation — a live uncompacted tail of messages it owns directly above a flat
2830
2860
  * message store, plus compacted, summarized {@link Section} records and a `summarizable` flag,
@@ -3042,8 +3072,7 @@ var Conversation = class {
3042
3072
  return message;
3043
3073
  }
3044
3074
  };
3045
- //#endregion
3046
- //#region src/core/conversations/ConversationManager.ts
3075
+ // src/core/conversations/ConversationManager.ts
3047
3076
  /**
3048
3077
  * Registers {@link Conversation} instances keyed by `id`, in insertion order, with an active pointer —
3049
3078
  * the id-keyed store over the conversation layer, the `active` / `switch` seam the
@@ -3165,8 +3194,7 @@ var ConversationManager = class {
3165
3194
  return removed;
3166
3195
  }
3167
3196
  };
3168
- //#endregion
3169
- //#region src/core/conversations/stores/MemoryConversationStore.ts
3197
+ // src/core/conversations/stores/MemoryConversationStore.ts
3170
3198
  /**
3171
3199
  * Implements the {@link ConversationStoreInterface} in memory — a process-lifetime `Map` of
3172
3200
  * {@link ConversationSnapshot} records keyed by conversation id, the default store
@@ -3239,8 +3267,7 @@ var MemoryConversationStore = class {
3239
3267
  return Promise.resolve();
3240
3268
  }
3241
3269
  };
3242
- //#endregion
3243
- //#region src/core/conversations/stores/DatabaseConversationStore.ts
3270
+ // src/core/conversations/stores/DatabaseConversationStore.ts
3244
3271
  /**
3245
3272
  * Backs a {@link ConversationStoreInterface} with one table of the `databases` layer — a
3246
3273
  * conversation's durable state is a row holding the snapshot as one opaque JSON column, narrowed
@@ -3347,8 +3374,7 @@ var DatabaseConversationStore = class {
3347
3374
  await this.#table.remove(id);
3348
3375
  }
3349
3376
  };
3350
- //#endregion
3351
- //#region src/core/conversations/factories.ts
3377
+ // src/core/conversations/factories.ts
3352
3378
  /**
3353
3379
  * Creates a conversation — a {@link ConversationInterface} grouping messages above a flat
3354
3380
  * message store it owns directly, with compaction into summarized sections, on-demand
@@ -3523,8 +3549,7 @@ function createDatabaseConversationStore(driver = (0, _orkestrel_database.create
3523
3549
  tables: { conversations: columns }
3524
3550
  }).table("conversations"));
3525
3551
  }
3526
- //#endregion
3527
- //#region src/core/contexts/constants.ts
3552
+ // src/core/contexts/constants.ts
3528
3553
  /**
3529
3554
  * Names the section header the `build()` method of {@link import('./AgentContext.js').AgentContext}
3530
3555
  * renders the active workspace's text files under — `'## Workspace'`, the leading line of the dedicated
@@ -3540,8 +3565,7 @@ function createDatabaseConversationStore(driver = (0, _orkestrel_database.create
3540
3565
  * `base64` payload attaches to the last user message.
3541
3566
  */
3542
3567
  var WORKSPACE_SECTION_HEADER = "## Workspace";
3543
- //#endregion
3544
- //#region src/core/contexts/instructions/Instruction.ts
3568
+ // src/core/contexts/instructions/Instruction.ts
3545
3569
  /**
3546
3570
  * Represents an immutable named directive — an {@link InstructionInterface} assembled once from
3547
3571
  * its input (`name` / `content` and an optional `priority`), the `id` minted at
@@ -3576,8 +3600,7 @@ var Instruction = class {
3576
3600
  if (input.override !== void 0) this.override = input.override;
3577
3601
  }
3578
3602
  };
3579
- //#endregion
3580
- //#region src/core/contexts/instructions/InstructionManager.ts
3603
+ // src/core/contexts/instructions/InstructionManager.ts
3581
3604
  /**
3582
3605
  * Registers the immutable {@link Instruction} instances a richer context assembles a directives block
3583
3606
  * from — keyed by `name` so adding an instruction whose name is already stored overwrites it,
@@ -3668,8 +3691,7 @@ var InstructionManager = class {
3668
3691
  return removed;
3669
3692
  }
3670
3693
  };
3671
- //#endregion
3672
- //#region src/core/contexts/helpers.ts
3694
+ // src/core/contexts/helpers.ts
3673
3695
  /**
3674
3696
  * Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line
3675
3697
  * over a language-tagged fence, the framing the
@@ -3840,8 +3862,7 @@ function intersectKeys(parent, child) {
3840
3862
  const allowed = new Set(parent);
3841
3863
  return child.filter((key) => allowed.has(key));
3842
3864
  }
3843
- //#endregion
3844
- //#region src/core/contexts/scopes/Scope.ts
3865
+ // src/core/contexts/scopes/Scope.ts
3845
3866
  /**
3846
3867
  * Represents a named, immutable filter over a richer context's items — an optional allow-list per
3847
3868
  * category (`instructions` / `tools` / `files`), each keyed by that category's identity (an
@@ -3901,8 +3922,7 @@ var Scope = class Scope {
3901
3922
  });
3902
3923
  }
3903
3924
  };
3904
- //#endregion
3905
- //#region src/core/contexts/scopes/ScopeManager.ts
3925
+ // src/core/contexts/scopes/ScopeManager.ts
3906
3926
  /**
3907
3927
  * Registers the named filters a richer context reuses — immutable {@link Scope} instances keyed by their
3908
3928
  * minted `id`, in insertion order, where `add` always mints and stores rather than overwriting,
@@ -3969,8 +3989,7 @@ var ScopeManager = class {
3969
3989
  return removed;
3970
3990
  }
3971
3991
  };
3972
- //#endregion
3973
- //#region src/core/contexts/AgentContext.ts
3992
+ // src/core/contexts/AgentContext.ts
3974
3993
  /**
3975
3994
  * Assembles a provider request from the richer turn context — the optional system prompt, the
3976
3995
  * observable context managers (instructions / workspaces), the
@@ -4124,8 +4143,7 @@ var AgentContext = class {
4124
4143
  return this.#conversations.active ?? conversation;
4125
4144
  }
4126
4145
  };
4127
- //#endregion
4128
- //#region src/core/contexts/factories.ts
4146
+ // src/core/contexts/factories.ts
4129
4147
  /**
4130
4148
  * Creates an instruction — an immutable {@link InstructionInterface} (a named directive)
4131
4149
  * from its `name` / `content` and optional `priority`, the `id` minted at construction.
@@ -4269,8 +4287,7 @@ function createScopeManager(options) {
4269
4287
  function createAgentContext(options) {
4270
4288
  return new AgentContext(options);
4271
4289
  }
4272
- //#endregion
4273
- //#region src/core/agents/constants.ts
4290
+ // src/core/agents/constants.ts
4274
4291
  /**
4275
4292
  * Caps an {@link AgentInterface} turn's tool iterations by default — `10` context → provider →
4276
4293
  * tools cycles before the loop stops, so a model that keeps requesting tools can never loop
@@ -4297,8 +4314,7 @@ var MESSAGE_TOKEN_OVERHEAD = 4;
4297
4314
  * exact count.
4298
4315
  */
4299
4316
  var IMAGE_TOKEN_ESTIMATE = 512;
4300
- //#endregion
4301
- //#region src/core/agents/errors.ts
4317
+ // src/core/agents/errors.ts
4302
4318
  /**
4303
4319
  * Reports an {@link AgentInterface} run that ended {@link AgentResult.partial} under a
4304
4320
  * `partial` policy of `false` (the default) — thrown by an agent-job handler (a
@@ -4324,11 +4340,12 @@ var AgentJobError = class extends Error {
4324
4340
  constructor(message, partial) {
4325
4341
  super(message);
4326
4342
  this.name = "AgentJobError";
4343
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.AgentJobError"), { value: this });
4327
4344
  this.partial = partial;
4328
4345
  }
4329
4346
  };
4330
4347
  /**
4331
- * Narrows an unknown caught value to an {@link AgentJobError} through `instanceof`, so a
4348
+ * Narrows an unknown caught value to an {@link AgentJobError} through its identity brand and declared members, so a
4332
4349
  * `catch` can recover its `partial` result.
4333
4350
  *
4334
4351
  * @param value - The value to test (typically a `catch` binding or a rejected enqueue)
@@ -4344,7 +4361,30 @@ var AgentJobError = class extends Error {
4344
4361
  * ```
4345
4362
  */
4346
4363
  function isAgentJobError(value) {
4347
- return (0, _orkestrel_contract.isInstance)(value, AgentJobError);
4364
+ return (0, _orkestrel_contract.holds)(() => {
4365
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.AgentJobError"))?.value === value)) return false;
4366
+ if (!(_orkestrel_contract.INTRINSICS.reflect.read(value, "code") === "PARTIAL")) return false;
4367
+ const partial = _orkestrel_contract.INTRINSICS.reflect.read(value, "partial");
4368
+ if (!((0, _orkestrel_contract.isObject)(partial) || (0, _orkestrel_contract.isFunction)(partial))) return false;
4369
+ const usage = _orkestrel_contract.INTRINSICS.reflect.read(partial, "usage");
4370
+ const stop = _orkestrel_contract.INTRINSICS.reflect.read(partial, "stop");
4371
+ if (stop !== void 0) {
4372
+ if (!((0, _orkestrel_contract.isObject)(stop) || (0, _orkestrel_contract.isFunction)(stop))) return false;
4373
+ const layer = _orkestrel_contract.INTRINSICS.reflect.read(stop, "layer");
4374
+ const spent = _orkestrel_contract.INTRINSICS.reflect.read(stop, "usage");
4375
+ if (!(0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(stop, "id")) || !(_orkestrel_contract.INTRINSICS.reflect.read(stop, "estimate") === void 0 || (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(stop, "estimate"))) || !(spent === void 0 || ((0, _orkestrel_contract.isObject)(spent) || (0, _orkestrel_contract.isFunction)(spent)) && [
4376
+ "prompt",
4377
+ "completion",
4378
+ "total"
4379
+ ].every((key) => (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(spent, key))))) return false;
4380
+ if (layer !== "model" && !((layer === "meter" || layer === "budget") && (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(stop, "max")) && (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(stop, "consumed")))) return false;
4381
+ }
4382
+ return (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "content")) && (_orkestrel_contract.INTRINSICS.reflect.read(partial, "thinking") === void 0 || (0, _orkestrel_contract.isString)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "thinking"))) && (0, _orkestrel_contract.isBoolean)(_orkestrel_contract.INTRINSICS.reflect.read(partial, "partial")) && (usage === void 0 || ((0, _orkestrel_contract.isObject)(usage) || (0, _orkestrel_contract.isFunction)(usage)) && [
4383
+ "prompt",
4384
+ "completion",
4385
+ "total"
4386
+ ].every((key) => (0, _orkestrel_contract.isNumber)(_orkestrel_contract.INTRINSICS.reflect.read(usage, key))));
4387
+ });
4348
4388
  }
4349
4389
  /**
4350
4390
  * Reports a run sharing accounting with a live run, a `limit` that is not a nonnegative safe integer, a name absent from a registry pool, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead. Await the call inside `try`/`catch` to catch it.
@@ -4380,12 +4420,13 @@ var AgentError = class extends Error {
4380
4420
  constructor(code, message, options) {
4381
4421
  super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
4382
4422
  this.name = "AgentError";
4423
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.AgentError"), { value: this });
4383
4424
  this.code = code;
4384
4425
  this.context = options?.context;
4385
4426
  }
4386
4427
  };
4387
4428
  /**
4388
- * Narrows an unknown caught value to an {@link AgentError} through `instanceof`, so a `catch`
4429
+ * Narrows an unknown caught value to an {@link AgentError} through its identity brand and declared members, so a `catch`
4389
4430
  * can branch on its `code`.
4390
4431
  *
4391
4432
  * @param value - The value to test (typically a `catch` binding)
@@ -4401,10 +4442,15 @@ var AgentError = class extends Error {
4401
4442
  * ```
4402
4443
  */
4403
4444
  function isAgentError(value) {
4404
- return (0, _orkestrel_contract.isInstance)(value, AgentError);
4445
+ return (0, _orkestrel_contract.holds)(() => {
4446
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.AgentError"))?.value === value)) return false;
4447
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
4448
+ if (!(code === "CONCURRENCY" || code === "LIMIT" || code === "REGISTRY" || code === "WINDOW")) return false;
4449
+ const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
4450
+ return context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context);
4451
+ });
4405
4452
  }
4406
- //#endregion
4407
- //#region src/core/agents/Channel.ts
4453
+ // src/core/agents/Channel.ts
4408
4454
  /**
4409
4455
  * Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`)
4410
4456
  * and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live
@@ -4474,8 +4520,7 @@ var Channel = class {
4474
4520
  });
4475
4521
  }
4476
4522
  };
4477
- //#endregion
4478
- //#region src/core/agents/helpers.ts
4523
+ // src/core/agents/helpers.ts
4479
4524
  /**
4480
4525
  * Projects an unknown value onto a fresh, exact `JSONValue` representation of an
4481
4526
  * {@link AgentResult} — capturing each structural field once through a total boundary,
@@ -4702,7 +4747,7 @@ function estimateTokens(text) {
4702
4747
  function estimateMessages(messages) {
4703
4748
  return messages.reduce((sum, message) => {
4704
4749
  const measure = measureMessage(message);
4705
- return sum + measure.content + measure.framing + measure.calls + measure.thinking + measure.images;
4750
+ return sum + measure.content + measure.uniform + measure.calls + measure.thinking + measure.images;
4706
4751
  }, 0);
4707
4752
  }
4708
4753
  /**
@@ -4712,7 +4757,7 @@ function estimateMessages(messages) {
4712
4757
  * @remarks
4713
4758
  * The result is a structural estimate, not a tokenizer allocation. `id` and `role` are joins back to
4714
4759
  * the message, not token components, and a provider's template effects and the estimation error are
4715
- * not individually attributed. `content` is `ceil(length / 4)`, `framing` is
4760
+ * not individually attributed. `content` is `ceil(length / 4)`, `uniform` is
4716
4761
  * {@link import('./constants.js').MESSAGE_TOKEN_OVERHEAD}, `calls` is the estimate of the JSON-rendered
4717
4762
  * calls (`0` when the message carries none, the framing overhead when they cannot be rendered),
4718
4763
  * `thinking` is the estimate of the thinking (`0` when absent), and `images` is the attached image
@@ -4724,7 +4769,7 @@ function estimateMessages(messages) {
4724
4769
  * @example
4725
4770
  * ```ts
4726
4771
  * measureMessage({ id: '1', role: 'user', content: 'hello' })
4727
- * // { id: '1', role: 'user', content: 2, framing: 4, calls: 0, thinking: 0, images: 0 }
4772
+ * // { id: '1', role: 'user', content: 2, uniform: 4, calls: 0, thinking: 0, images: 0 }
4728
4773
  * ```
4729
4774
  */
4730
4775
  function measureMessage(message) {
@@ -4734,7 +4779,7 @@ function measureMessage(message) {
4734
4779
  id: message.id,
4735
4780
  role: message.role,
4736
4781
  content: estimateTokens(message.content),
4737
- framing: 4,
4782
+ uniform: 4,
4738
4783
  calls,
4739
4784
  thinking: message.thinking === void 0 ? 0 : estimateTokens(message.thinking),
4740
4785
  images: (message.images?.length ?? 0) * 512
@@ -4766,7 +4811,7 @@ function measureMessage(message) {
4766
4811
  */
4767
4812
  function estimateRequest(request) {
4768
4813
  const measure = measureRequest(request);
4769
- return measure.messages.reduce((sum, message) => sum + message.content + message.framing + message.calls + message.thinking + message.images, measure.tools + measure.schema);
4814
+ return measure.messages.reduce((sum, message) => sum + message.content + message.uniform + message.calls + message.thinking + message.images, measure.tools + measure.schema);
4770
4815
  }
4771
4816
  /**
4772
4817
  * Measures the disjoint estimate components of a complete provider request — each message through
@@ -4787,7 +4832,7 @@ function estimateRequest(request) {
4787
4832
  * @example
4788
4833
  * ```ts
4789
4834
  * measureRequest({ messages: [{ id: '1', role: 'user', content: 'hello' }] })
4790
- * // { messages: [{ id: '1', role: 'user', content: 2, framing: 4, calls: 0, thinking: 0, images: 0 }], tools: 0, schema: 0 }
4835
+ * // { messages: [{ id: '1', role: 'user', content: 2, uniform: 4, calls: 0, thinking: 0, images: 0 }], tools: 0, schema: 0 }
4791
4836
  * ```
4792
4837
  */
4793
4838
  function measureRequest(request) {
@@ -5057,8 +5102,7 @@ function extractQueueOptions(options) {
5057
5102
  ...timeout === void 0 ? {} : { timeout }
5058
5103
  };
5059
5104
  }
5060
- //#endregion
5061
- //#region src/core/agents/Agent.ts
5105
+ // src/core/agents/Agent.ts
5062
5106
  /**
5063
5107
  * Composes a {@link ProviderInterface}, an {@link AgentContext}, and a
5064
5108
  * {@link ToolManagerInterface} into a bounded context → provider → tools → repeat turn, exposed
@@ -5239,7 +5283,7 @@ var Agent = class {
5239
5283
  this.#window?.clear();
5240
5284
  const cancelled = abort.signal.aborted;
5241
5285
  const turns = [];
5242
- while (turns.length < limit && (turns.at(-1)?.ending ?? "tools") === "tools") {
5286
+ while (turns.length < limit && (turns.at(-1)?.outcome ?? "tools") === "tools") {
5243
5287
  const index = turns.length;
5244
5288
  const base = turns.at(-1)?.messages ?? entry.messages;
5245
5289
  const futile = turns.at(-1)?.futile ?? false;
@@ -5249,7 +5293,7 @@ var Agent = class {
5249
5293
  usage: void 0,
5250
5294
  spent: void 0,
5251
5295
  messages: base,
5252
- ending: "cancel",
5296
+ outcome: "cancel",
5253
5297
  partial: true,
5254
5298
  futile,
5255
5299
  estimate: void 0,
@@ -5295,7 +5339,7 @@ var Agent = class {
5295
5339
  if (!provided.success) {
5296
5340
  turns.push({
5297
5341
  ...settled,
5298
- ending: "cancel",
5342
+ outcome: "cancel",
5299
5343
  partial: true
5300
5344
  });
5301
5345
  continue;
@@ -5317,7 +5361,7 @@ var Agent = class {
5317
5361
  if (abort.signal.aborted) {
5318
5362
  turns.push({
5319
5363
  ...settled,
5320
- ending: "cancel",
5364
+ outcome: "cancel",
5321
5365
  partial: true
5322
5366
  });
5323
5367
  continue;
@@ -5352,7 +5396,7 @@ var Agent = class {
5352
5396
  assistant,
5353
5397
  ...replies
5354
5398
  ],
5355
- ending: "tools",
5399
+ outcome: "tools",
5356
5400
  partial: true
5357
5401
  });
5358
5402
  continue;
@@ -5365,7 +5409,7 @@ var Agent = class {
5365
5409
  turns.push({
5366
5410
  ...settled,
5367
5411
  content: result.content,
5368
- ending: "answer",
5412
+ outcome: "answer",
5369
5413
  partial: abort.signal.aborted,
5370
5414
  truncated: result.truncated === true
5371
5415
  });
@@ -5373,7 +5417,7 @@ var Agent = class {
5373
5417
  const final = turns.at(-1);
5374
5418
  const thinkings = turns.flatMap((turn) => turn.thinking === void 0 ? [] : [turn.thinking]);
5375
5419
  return {
5376
- content: final?.ending === "answer" ? final.content : turns.map((turn) => turn.content).join(""),
5420
+ content: final?.outcome === "answer" ? final.content : turns.map((turn) => turn.content).join(""),
5377
5421
  thinking: thinkings.length === 0 ? void 0 : thinkings.join("\n\n"),
5378
5422
  usage: [
5379
5423
  ...turns.map((turn) => turn.usage),
@@ -5381,7 +5425,7 @@ var Agent = class {
5381
5425
  ...turns.map((turn) => turn.spent)
5382
5426
  ].reduce((total, one) => one === void 0 ? total : sumUsage(total, one), void 0),
5383
5427
  partial: final?.partial ?? cancelled,
5384
- exhausted: final?.ending === "tools" && !abort.signal.aborted,
5428
+ exhausted: final?.outcome === "tools" && !abort.signal.aborted,
5385
5429
  stop: inferStop(abort.signal.reason, allowance, budget, this.#provider.id, final)
5386
5430
  };
5387
5431
  }
@@ -5621,8 +5665,7 @@ var Agent = class {
5621
5665
  return AbortSignal.any(signals);
5622
5666
  }
5623
5667
  };
5624
- //#endregion
5625
- //#region src/core/agents/AgentFanout.ts
5668
+ // src/core/agents/AgentFanout.ts
5626
5669
  /**
5627
5670
  * Executes one runner's agent jobs — spawning each unit's declared children on its first attempt
5628
5671
  * only, then rehydrating the unit through a registry with the controller signal and settling it
@@ -5680,8 +5723,7 @@ var AgentFanout = class {
5680
5723
  return settleAgentJob(this.#registry.build(controller.input, controller.signal), this.#partial);
5681
5724
  }
5682
5725
  };
5683
- //#endregion
5684
- //#region src/core/agents/Authority.ts
5726
+ // src/core/agents/Authority.ts
5685
5727
  /**
5686
5728
  * Gates the agent loop's tool calls — the synchronous policy consulted before each call runs,
5687
5729
  * turning one {@link AuthorityContext} into an {@link AuthorityDecision} by walking the ordered
@@ -5735,8 +5777,7 @@ var Authority = class {
5735
5777
  return this.#fallback;
5736
5778
  }
5737
5779
  };
5738
- //#endregion
5739
- //#region src/core/agents/AgentRegistry.ts
5780
+ // src/core/agents/AgentRegistry.ts
5740
5781
  /**
5741
5782
  * Makes a durable, JSON-serializable {@link AgentJobInput} runnable — holds the named pools of
5742
5783
  * live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name
@@ -5823,8 +5864,7 @@ var AgentRegistry = class {
5823
5864
  return manager;
5824
5865
  }
5825
5866
  };
5826
- //#endregion
5827
- //#region src/core/agents/factories.ts
5867
+ // src/core/agents/factories.ts
5828
5868
  /**
5829
5869
  * Creates an agent loop — an {@link AgentInterface} composing a
5830
5870
  * {@link ProviderInterface}, its {@link AgentContextInterface}, and a tool registry
@@ -6059,8 +6099,7 @@ function createAgentRunner(options) {
6059
6099
  handler: fanout.execute.bind(fanout)
6060
6100
  });
6061
6101
  }
6062
- //#endregion
6063
- //#region src/core/ledgers/constants.ts
6102
+ // src/core/ledgers/constants.ts
6064
6103
  /**
6065
6104
  * Lists the categories the ledger files a message under, in the order the category question
6066
6105
  * names them — the one list the {@link LedgerCategory} union derives from.
@@ -6163,8 +6202,7 @@ var DEFAULT_RECALL_LIMIT = 2;
6163
6202
  var LEDGER_SCALE_DRIFT = .06;
6164
6203
  /** Matches the logprob decoding failure `invalid or duplicate top logprob token`, which the ledger holds for the ledger's life. */
6165
6204
  var DETERMINISTIC_JUDGE_ERROR = /invalid or duplicate top logprob token/;
6166
- //#endregion
6167
- //#region src/core/ledgers/errors.ts
6205
+ // src/core/ledgers/errors.ts
6168
6206
  /**
6169
6207
  * Reports an invalid ledger configuration, failed calibration, or unowned request selection,
6170
6208
  * carrying the machine-readable `code`.
@@ -6188,11 +6226,12 @@ var LedgerError = class extends Error {
6188
6226
  constructor(code, message) {
6189
6227
  super(message);
6190
6228
  this.name = "LedgerError";
6229
+ _orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/agent.LedgerError"), { value: this });
6191
6230
  this.code = code;
6192
6231
  }
6193
6232
  };
6194
6233
  /**
6195
- * Narrows an unknown caught value to a {@link LedgerError} through `instanceof`, so a `catch` can
6234
+ * Narrows an unknown caught value to a {@link LedgerError} through its identity brand and declared members, so a `catch` can
6196
6235
  * branch on its `code`.
6197
6236
  *
6198
6237
  * @param value - The value to test (typically a `catch` binding)
@@ -6204,17 +6243,21 @@ var LedgerError = class extends Error {
6204
6243
  * ```
6205
6244
  */
6206
6245
  function isLedgerError(value) {
6207
- return (0, _orkestrel_contract.isInstance)(value, LedgerError);
6246
+ return (0, _orkestrel_contract.holds)(() => {
6247
+ if (!(value instanceof Error && _orkestrel_contract.INTRINSICS.prototype(value) !== Error.prototype && _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.LedgerError"))?.value === value)) return false;
6248
+ const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
6249
+ if (!(code === "REQUEST" || code === "THRESHOLD" || code === "SHARE" || code === "CAPACITY" || code === "LIMIT" || code === "TOPIC" || code === "LOOKUP" || code === "GAUGE" || code === "REFERENCE")) return false;
6250
+ return true;
6251
+ });
6208
6252
  }
6209
- //#endregion
6210
- //#region src/core/ledgers/helpers.ts
6253
+ // src/core/ledgers/helpers.ts
6211
6254
  /**
6212
6255
  * Collects the live message ids placed in records or left without a record.
6213
6256
  * @param projection - The projected records and unplaced ids
6214
6257
  * @returns The distinct live message ids
6215
6258
  * @example
6216
6259
  * ```ts
6217
- * collectProjectionIds({ records: [], stale: [], orphans: ['message-1'] }) // Set { 'message-1' }
6260
+ * collectProjectionIds({ records: [], amendments: [], orphans: ['message-1'] }) // Set { 'message-1' }
6218
6261
  * ```
6219
6262
  */
6220
6263
  function collectProjectionIds(projection) {
@@ -6653,8 +6696,8 @@ function matchEntities(registry, text, partial) {
6653
6696
  * argument. A message that names no owner joins where its earlier side of an amendment pair joins,
6654
6697
  * or on the rules record when it is filed as a rule or a correction, and is an orphan otherwise.
6655
6698
  *
6656
- * A sentence an amending message made stale is left out and listed in `stale`. An amending message
6657
- * that is itself replaced keeps that effect, so the old value never revives.
6699
+ * Every live sentence is retained. Accepted direct edges are listed in `amendments`. An amending message
6700
+ * that is itself superseded retains its accepted edge without restoring its text.
6658
6701
  *
6659
6702
  * A sentence that opens with a pronoun takes the party named in the sentence before it. The reading
6660
6703
  * trusts capitals, so a capitalized word that is no person, such as a carrier named mid-sentence,
@@ -6662,7 +6705,7 @@ function matchEntities(registry, text, partial) {
6662
6705
  * the follow-up facts the records exist for.
6663
6706
  *
6664
6707
  * @param input - The messages, readings, entities, and classification to project
6665
- * @returns The records with owner records ordered by their first member and the rules record last, the stale sentences, and the live message ids no record placed
6708
+ * @returns The records with owner records ordered by their first member and the rules record last, the accepted amendments, and the live message ids no record placed
6666
6709
  *
6667
6710
  * @example
6668
6711
  * ```ts
@@ -6687,8 +6730,7 @@ function buildRecords(input) {
6687
6730
  earlier,
6688
6731
  later
6689
6732
  }))), (pair) => pair.later)].map(([later, pairs]) => [later, pairs.map((pair) => pair.earlier)]));
6690
- const stale = collectStale(input, byId, live);
6691
- const dead = new Set(stale.map((entry) => `${entry.source} ${entry.sentence}`));
6733
+ const amendments = collectAmendments(input, byId, live);
6692
6734
  const holders = [...input.owners.values()].flat();
6693
6735
  const system = collectNames(input.system);
6694
6736
  const settled = /* @__PURE__ */ new Map();
@@ -6703,7 +6745,7 @@ function buildRecords(input) {
6703
6745
  id
6704
6746
  }))), (entry) => entry.key)].map(([key, entries]) => {
6705
6747
  const ids = entries.map((entry) => entry.id);
6706
- const lines = ids.flatMap((id) => buildLines(input, byId, id, dead, holders, system));
6748
+ const lines = ids.flatMap((id) => buildLines(input, byId, id, holders, system));
6707
6749
  const owner = key.slice(LEDGER_OWNER_PREFIX.length);
6708
6750
  const holder = input.owners.get(owner)?.[0];
6709
6751
  const title = key === "rules" ? "Rules" : holder === void 0 ? `account ${owner}` : `${holder} (account ${owner})`;
@@ -6717,17 +6759,19 @@ function buildRecords(input) {
6717
6759
  }
6718
6760
  };
6719
6761
  }).sort((left, right) => Number(left.record.key === "rules") - Number(right.record.key === "rules") || left.first - right.first || (left.record.key < right.record.key ? -1 : left.record.key > right.record.key ? 1 : 0)).map(({ record }) => record),
6720
- stale,
6762
+ amendments,
6721
6763
  orphans
6722
6764
  };
6723
6765
  }
6724
6766
  /**
6725
- * Selects a request's view of the projected records.
6767
+ * Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `.
6726
6768
  *
6727
6769
  * @remarks
6728
6770
  * The view holds the owner records the request names in the order it names them, then the rules
6729
6771
  * record with the lines whose topics meet the request's first, each group in position order. The
6730
- * returned records and lines are copies.
6772
+ * returned records and lines are copies. Owner records with the same member ids in the same order
6773
+ * collapse into the first requested record, keeping its key, members, and lines and joining their
6774
+ * titles with `; ` before trimming.
6731
6775
  *
6732
6776
  * @param projection - The output of {@link buildRecords}
6733
6777
  * @param request - The owners and the desk topics the request names
@@ -6743,10 +6787,14 @@ function selectRecords(projection, request) {
6743
6787
  const topics = new Set(request.topics);
6744
6788
  const rules = projection.records.find((one) => one.key === LEDGER_RULES_KEY);
6745
6789
  const sides = Map.groupBy((rules?.lines ?? []).filter(() => true), (line) => line.topics.some((topic) => topics.has(topic)));
6746
- return [...[...new Set(request.owners)].flatMap((owner) => {
6790
+ const owners = [...new Set(request.owners)].flatMap((owner) => {
6747
6791
  const record = projection.records.find((one) => one.key === `${LEDGER_OWNER_PREFIX}${owner}`);
6748
- return record === void 0 ? [] : [structuredClone(record)];
6749
- }), ...rules === void 0 ? [] : [structuredClone({
6792
+ return record === void 0 ? [] : [record];
6793
+ });
6794
+ return [...[...Map.groupBy(owners, (record) => JSON.stringify(record.members)).values()].flatMap(([record, ...rest]) => record === void 0 ? [] : [structuredClone({
6795
+ ...record,
6796
+ title: [record.title, ...rest.map((one) => one.title)].join("; ")
6797
+ })]), ...rules === void 0 ? [] : [structuredClone({
6750
6798
  ...rules,
6751
6799
  lines: [...sides.get(true) ?? [], ...sides.get(false) ?? []]
6752
6800
  })]];
@@ -6758,6 +6806,7 @@ function selectRecords(projection, request) {
6758
6806
  * The briefing joins rendered records with one blank line.
6759
6807
  *
6760
6808
  * @param record - A record or view with a `title` and `lines`
6809
+ * @param context - Rendering facts for optional accepted amendment annotations
6761
6810
  * @returns `## TITLE` followed by `- LINE` for each line
6762
6811
  *
6763
6812
  * @example
@@ -6766,13 +6815,14 @@ function selectRecords(projection, request) {
6766
6815
  * // '## Rules\n- Refunds need a manager.'
6767
6816
  * ```
6768
6817
  */
6769
- function renderLedgerRecord(record) {
6770
- return [`## ${record.title}`, ...record.lines.map((line) => `- ${line.text}`)].join("\n");
6818
+ function renderLedgerRecord(record, context) {
6819
+ return [`## ${record.title}`, ...record.lines.flatMap((line) => [context === void 0 ? "" : renderLedgerAnnotation(line, context), `- ${line.text}`].filter((text) => text !== ""))].join("\n");
6771
6820
  }
6772
6821
  /**
6773
6822
  * Renders one owner record under a `###` heading, which the briefing nests under its one `## Pinned` heading.
6774
6823
  *
6775
6824
  * @param record - An owner record or view with a `title` and `lines`
6825
+ * @param context - Rendering facts for optional accepted amendment annotations
6776
6826
  * @returns `### TITLE` followed by `- LINE` for each line
6777
6827
  *
6778
6828
  * @example
@@ -6780,8 +6830,57 @@ function renderLedgerRecord(record) {
6780
6830
  * renderLedgerPinned({ title: 'Odile Marlow (account OM-30418)', lines: [] }) // '### Odile Marlow (account OM-30418)'
6781
6831
  * ```
6782
6832
  */
6783
- function renderLedgerPinned(record) {
6784
- return `#${renderLedgerRecord(record)}`;
6833
+ function renderLedgerPinned(record, context) {
6834
+ return `#${renderLedgerRecord(record, context)}`;
6835
+ }
6836
+ /**
6837
+ * Derives complete source identities, first occurrences, and local references from the actual briefing lines.
6838
+ * @param messages - Original messages whose indexed sentences establish completeness
6839
+ * @param lines - Retained lines in rendering order after deduplication and trimming
6840
+ * @param amendments - Accepted direct message amendment edges
6841
+ * @returns Immutable rendering facts for this retained population
6842
+ *
6843
+ * @example
6844
+ * ```ts
6845
+ * buildLedgerRenderContext([], [], []).complete.size // 0
6846
+ * ```
6847
+ */
6848
+ function buildLedgerRenderContext(messages, lines, amendments) {
6849
+ const identities = new Set(lines.map((line) => `${line.source} ${line.sentence}`));
6850
+ return {
6851
+ amendments,
6852
+ complete: new Set(messages.filter((message) => {
6853
+ const sentences = splitSentences(message.content);
6854
+ return sentences.length > 0 && sentences.every((_, index) => identities.has(`${message.id} ${index}`));
6855
+ }).map((message) => message.id)),
6856
+ first: new Map(lines.toReversed().map((line) => [line.source, line])),
6857
+ references: new Map([...new Set(lines.map((line) => line.source))].map((source, index) => [source, String(index + 1)]))
6858
+ };
6859
+ }
6860
+ /**
6861
+ * Renders source framing and unresolved amendment scope at a source's first retained line.
6862
+ * @param line - The retained occurrence to annotate
6863
+ * @param context - Actual complete sources, first occurrences, local references, and accepted amendment edges
6864
+ * @returns Source framing and truthful inclusion notes, or empty text for an unrelated or repeated occurrence
6865
+ * @throws {LedgerError} Thrown when the context holds no reference for the annotated source or a fully included amender (code `'REQUEST'`)
6866
+ *
6867
+ * @example
6868
+ * ```ts
6869
+ * renderLedgerAnnotation({ text: 'Unchanged.', source: 'user-1', sentence: 0, topics: [], role: 'user' }, buildLedgerRenderContext([], [], [])) // ''
6870
+ * ```
6871
+ */
6872
+ function renderLedgerAnnotation(line, context) {
6873
+ if (context.first.get(line.source) !== line) return "";
6874
+ const amendments = context.amendments.filter((pair) => pair.earlier === line.source);
6875
+ const endpoint = context.complete.has(line.source) && context.amendments.some((pair) => pair.later === line.source && context.first.has(pair.earlier));
6876
+ if (amendments.length === 0 && !endpoint) return "";
6877
+ const included = amendments.filter((pair) => context.complete.has(pair.later));
6878
+ if (context.references.get(line.source) === void 0 || included.some((pair) => context.references.get(pair.later) === void 0)) throw new LedgerError("REFERENCE", "Ledger rendering requires retained source references");
6879
+ return [
6880
+ `[Ledger source ${context.references.get(line.source)}]`,
6881
+ ...included.map((pair) => `Accepted later amendment [Ledger source ${context.references.get(pair.later)}] is fully included in this briefing. Sentence scope is unresolved.`),
6882
+ ...amendments.some((pair) => !context.complete.has(pair.later)) ? ["Accepted later amendment text is not fully included in this briefing. Sentence scope is unresolved."] : []
6883
+ ].join("\n");
6785
6884
  }
6786
6885
  /**
6787
6886
  * Splits a recall topic at its joints.
@@ -6977,74 +7076,62 @@ function placeMember(input, links, amending, id, seen, settled) {
6977
7076
  return keys;
6978
7077
  }
6979
7078
  /**
6980
- * Collects the sentences that live messages made stale.
7079
+ * Collects accepted direct amendments of live messages.
6981
7080
  *
6982
7081
  * @remarks
6983
- * A sentence of a live message is stale when it shares an id or a number with a message that
6984
- * amends it. An amending message takes effect while it is live, and keeps its effect after another
6985
- * message supersedes it, so the value it replaced never revives. A user or tool message that the
6986
- * input excludes or files quiet never takes effect.
7082
+ * An accepted edge relates an earlier live message to an amender without claiming which sentences
7083
+ * changed. An amender takes effect while live and retains its edge after another message supersedes
7084
+ * it, without restoring the superseded text. An excluded or quiet user or tool message has no effect.
6987
7085
  *
6988
7086
  * @param input - The exclusions and classification to read
6989
7087
  * @param byId - The messages by id
6990
7088
  * @param live - The live message ids from {@link collectLive}
6991
- * @returns The stale sentences in conversation order, each with the tokens it shares
7089
+ * @returns The distinct accepted direct edges in conversation order
6992
7090
  *
6993
7091
  * @example
6994
7092
  * ```ts
6995
- * collectStale(input, byId, ['user-1', 'user-3']) // [{ source: 'user-1', sentence: 1, tokens: ['ESC-2291'] }]
7093
+ * collectAmendments(input, byId, ['user-1', 'user-3']) // [{ earlier: 'user-1', later: 'user-3' }]
6996
7094
  * ```
6997
7095
  */
6998
- function collectStale(input, byId, live) {
7096
+ function collectAmendments(input, byId, live) {
6999
7097
  const { classification } = input;
7000
7098
  const excluded = new Set(input.exclusions);
7099
+ const living = new Set(live);
7100
+ const ordered = [...new Set(input.messages.map((message) => message.id))];
7101
+ const positions = new Map(ordered.map((id, index) => [id, index]));
7001
7102
  const effective = /* @__PURE__ */ new Set([...live, ...[...byId.values()].filter((message) => message.role !== "assistant" && !excluded.has(message.id) && !classification.quiet.has(message.id) && (classification.supersessions.get(message.id) ?? []).length > 0).map((message) => message.id)]);
7002
- return live.flatMap((id) => {
7003
- const laters = (classification.amendments.get(id) ?? []).filter((later) => effective.has(later)).flatMap((later) => {
7004
- const message = byId.get(later);
7005
- return message === void 0 ? [] : [extractTokens(message.content)];
7006
- });
7007
- if (laters.length === 0) return [];
7008
- return splitSentences(byId.get(id)?.content ?? "").flatMap((text, sentence) => {
7009
- const own = extractTokens(text);
7010
- const tokens = new Set(laters.flatMap((other) => [...[...own.ids].filter((token) => other.ids.has(token)), ...[...own.numbers].filter((token) => other.numbers.has(token)).map(String)]));
7011
- return tokens.size > 0 ? [{
7012
- source: id,
7013
- sentence,
7014
- tokens: [...tokens]
7015
- }] : [];
7016
- });
7017
- });
7103
+ return ordered.filter((id) => living.has(id)).flatMap((earlier) => [...new Set(classification.amendments.get(earlier) ?? [])].filter((later) => effective.has(later) && positions.has(later)).sort((a, b) => (positions.get(a) ?? 0) - (positions.get(b) ?? 0)).map((later) => ({
7104
+ earlier,
7105
+ later
7106
+ })));
7018
7107
  }
7019
7108
  /**
7020
7109
  * Builds the record lines of one message.
7021
7110
  *
7022
7111
  * @remarks
7023
- * Each sentence that is not stale becomes a line. A sentence that opens with a pronoun and follows
7112
+ * Each original indexed sentence becomes a line. A sentence that opens with a pronoun and follows
7024
7113
  * another sentence takes the last name of the sentence before it that is neither an owner name nor
7025
7114
  * a system name, and its line text opens with that party and a colon.
7026
7115
  *
7027
7116
  * @param input - The classification whose topics the lines carry
7028
7117
  * @param byId - The messages by id
7029
7118
  * @param id - The message id
7030
- * @param dead - The stale sentences as `SOURCE SENTENCE` keys
7031
7119
  * @param holders - The owner names, which never serve as a party
7032
7120
  * @param system - The system text's names, which never serve as a party
7033
7121
  * @returns The lines in sentence order; empty when the message is absent
7034
7122
  *
7035
7123
  * @example
7036
7124
  * ```ts
7037
- * buildLines(input, byId, 'user-1', new Set(), [], []).map((line) => line.text)
7125
+ * buildLines(input, byId, 'user-1', [], []).map((line) => line.text)
7038
7126
  * // ['Odile Marlow phoned about BW-5512.', 'Odile Marlow: She wants a refund.']
7039
7127
  * ```
7040
7128
  */
7041
- function buildLines(input, byId, id, dead, holders, system) {
7129
+ function buildLines(input, byId, id, holders, system) {
7042
7130
  const message = byId.get(id);
7043
7131
  if (message === void 0) return [];
7044
7132
  const sentences = splitSentences(message.content);
7045
7133
  const topics = input.classification.topics.get(id) ?? [];
7046
7134
  return sentences.flatMap((sentence, at) => {
7047
- if (dead.has(`${id} ${at}`)) return [];
7048
7135
  const party = /^(?:He|She|They|His|Her|Their)(?![\p{L}\p{N}])/u.test(sentence) && at > 0 ? collectNames(sentences[at - 1] ?? "").filter((name) => !holders.includes(name) && !system.includes(name)).at(-1) : void 0;
7049
7136
  const line = {
7050
7137
  text: party === void 0 ? sentence : `${party}: ${sentence}`,
@@ -7059,8 +7146,7 @@ function buildLines(input, byId, id, dead, holders, system) {
7059
7146
  }];
7060
7147
  });
7061
7148
  }
7062
- //#endregion
7063
- //#region src/core/ledgers/Classifier.ts
7149
+ // src/core/ledgers/Classifier.ts
7064
7150
  /**
7065
7151
  * Files messages through the conversation's judgment manager and reads their categories and corrections.
7066
7152
  *
@@ -7346,8 +7432,7 @@ var Classifier = class {
7346
7432
  }
7347
7433
  }
7348
7434
  };
7349
- //#endregion
7350
- //#region src/core/ledgers/validators.ts
7435
+ // src/core/ledgers/validators.ts
7351
7436
  /**
7352
7437
  * Checks whether a value is finite and lies in the interval (0, 1].
7353
7438
  * @param value - The value to inspect
@@ -7372,8 +7457,7 @@ function isFraction(value) {
7372
7457
  function isPositiveSafeInteger(value) {
7373
7458
  return (0, _orkestrel_contract.isFiniteNumber)(value) && Number.isSafeInteger(value) && value > 0;
7374
7459
  }
7375
- //#endregion
7376
- //#region src/core/ledgers/Gauge.ts
7460
+ // src/core/ledgers/Gauge.ts
7377
7461
  /**
7378
7462
  * Prices prompts in tokens from a measured scale and overhead cost, and measures the room a request
7379
7463
  * has left.
@@ -7466,8 +7550,7 @@ var Gauge = class {
7466
7550
  if ((0, _orkestrel_contract.isFiniteNumber)(reply?.completion)) this.#reply = Math.max(this.#reply, reply.completion - (reply.thinking ?? 0));
7467
7551
  }
7468
7552
  };
7469
- //#endregion
7470
- //#region src/core/ledgers/LedgerPass.ts
7553
+ // src/core/ledgers/LedgerPass.ts
7471
7554
  /**
7472
7555
  * Holds what one pass of a ledger request keeps: the selection its run adopted last, the
7473
7556
  * conversation boundary its calls count additions from, its summed usage, and its gauge calls.
@@ -7611,8 +7694,7 @@ var LedgerPass = class {
7611
7694
  this.#log = [...this.#log, { thinking }];
7612
7695
  }
7613
7696
  };
7614
- //#endregion
7615
- //#region src/core/ledgers/LedgerRequest.ts
7697
+ // src/core/ledgers/LedgerRequest.ts
7616
7698
  /**
7617
7699
  * Holds what one ledger request keeps while it is served: its message, its filing readings and
7618
7700
  * plan, the gauge calls of its passes, and its repeat and recall stops.
@@ -7765,8 +7847,7 @@ var LedgerRequest = class {
7765
7847
  return this.#listings.get(result);
7766
7848
  }
7767
7849
  };
7768
- //#endregion
7769
- //#region src/core/ledgers/Ledger.ts
7850
+ // src/core/ledgers/Ledger.ts
7770
7851
  /**
7771
7852
  * Serves one conversation through classified records, a bounded briefing, and a final answer pass.
7772
7853
  * @example
@@ -8124,17 +8205,17 @@ var Ledger = class {
8124
8205
  projection: buildRecords(input)
8125
8206
  };
8126
8207
  }
8127
- #projectLines(input, projection, id) {
8128
- return buildLines(input, new Map(input.messages.map((message) => [message.id, message])), id, new Set(projection.stale.map((line) => `${line.source} ${line.sentence}`)), [...input.owners.values()].flat(), collectNames(this.#options.system));
8208
+ #projectLines(input, id) {
8209
+ return buildLines(input, new Map(input.messages.map((message) => [message.id, message])), id, [...input.owners.values()].flat(), collectNames(this.#options.system));
8129
8210
  }
8130
- #renderSource(id, lines) {
8211
+ #renderSource(id, lines, context) {
8131
8212
  const message = this.#conversation.message(id);
8132
8213
  if (message === void 0) return "";
8133
8214
  const sentences = splitSentences(message.content);
8134
- const text = sentences.length === lines.length ? message.content : lines.map((line) => sentences[line.sentence] ?? "").join(" ");
8135
- if (text === "" || message.role !== "tool") return text;
8215
+ const text = sentences.every((_, index) => lines.some((line) => line.sentence === index)) ? message.content : lines.map((line) => sentences[line.sentence] ?? "").join(" ");
8216
+ if (text === "") return "";
8136
8217
  const reading = this.#readLookups().find((one) => one.id === id);
8137
- return reading === void 0 ? text : `${renderLookupCall(reading.name, reading.arguments)}: ${text}`;
8218
+ return [...lines.map((line) => renderLedgerAnnotation(line, context)), message.role !== "tool" || reading === void 0 ? text : `${renderLookupCall(reading.name, reading.arguments)}: ${text}`].filter((part) => part !== "").join("\n");
8138
8219
  }
8139
8220
  #collectAfter(request) {
8140
8221
  const messages = this.#conversation.messages();
@@ -8217,7 +8298,7 @@ var Ledger = class {
8217
8298
  const score = [...words].filter((word) => asked?.words.has(word)).reduce((sum, word) => sum + Math.log(texts.length / (counts.get(word) ?? 1)), 0);
8218
8299
  return [{
8219
8300
  source: message.id,
8220
- lines: this.#projectLines(input, projection, message.id),
8301
+ lines: this.#projectLines(input, message.id),
8221
8302
  position,
8222
8303
  group,
8223
8304
  ruled,
@@ -8251,7 +8332,7 @@ var Ledger = class {
8251
8332
  source: unit.source,
8252
8333
  record: this.#buildUnitRecord(unit.source, unit.category, input, projection, held)
8253
8334
  }));
8254
- const trimmed = this.#trim(steps, records, mapped, new Set(ordered.map((unit) => unit.source)), cap);
8335
+ const trimmed = this.#trim(steps, records, mapped, new Set(ordered.map((unit) => unit.source)), cap, projection.amendments);
8255
8336
  const briefing = trimmed.briefing;
8256
8337
  const shown = /* @__PURE__ */ new Set([...trimmed.included, ...records.flatMap((record) => record.members.filter((source) => {
8257
8338
  const full = record.lines.filter((line) => line.source === source);
@@ -8263,10 +8344,10 @@ var Ledger = class {
8263
8344
  ...briefing === "" ? {} : { briefing }
8264
8345
  };
8265
8346
  }
8266
- #trim(steps, records, mapped, included, cap) {
8347
+ #trim(steps, records, mapped, included, cap, amendments) {
8267
8348
  const trimmed = steps.reduce((cut, step) => {
8268
8349
  if (cut.briefing !== void 0) return cut;
8269
- const briefing = this.#render(cut.records, mapped, cut.included);
8350
+ const briefing = this.#render(cut.records, mapped, cut.included, amendments);
8270
8351
  const content = [this.#options.system, briefing].filter((part) => part !== "").join("\n\n");
8271
8352
  if (this.#price([{
8272
8353
  id: "system",
@@ -8292,7 +8373,7 @@ var Ledger = class {
8292
8373
  return {
8293
8374
  records: trimmed.records,
8294
8375
  included: trimmed.included,
8295
- briefing: trimmed.briefing ?? this.#render(trimmed.records, mapped, trimmed.included)
8376
+ briefing: trimmed.briefing ?? this.#render(trimmed.records, mapped, trimmed.included, amendments)
8296
8377
  };
8297
8378
  }
8298
8379
  #buildUnitRecord(source, category, input, projection, held) {
@@ -8305,25 +8386,33 @@ var Ledger = class {
8305
8386
  }
8306
8387
  #collectAmended(input, projection, source, held) {
8307
8388
  const live = collectProjectionIds(projection);
8308
- return scanAmendments(input.classification.amendments, source, (id) => id === source || !held.has(id) && live.has(id)).flatMap((id) => this.#projectLines(input, projection, id));
8389
+ return scanAmendments(input.classification.amendments, source, (id) => id === source || !held.has(id) && live.has(id)).flatMap((id) => this.#projectLines(input, id));
8309
8390
  }
8310
- #render(records, mapped, included) {
8311
- const owners = records.filter((record) => record.key !== "rules" && record.lines.length > 0).map(renderLedgerPinned).join("\n\n");
8391
+ #render(records, mapped, included, amendments) {
8312
8392
  const entries = mapped.filter((unit) => included.has(unit.source)).flatMap(({ record: unit }) => [...Map.groupBy(unit.lines, (line) => line.source)].map(([source, lines]) => ({
8313
8393
  unit,
8314
8394
  source,
8315
8395
  lines
8316
8396
  })));
8317
8397
  const first = new Map(entries.toReversed().map((entry) => [entry.source, entry]));
8318
- const rendered = entries.filter((entry) => first.get(entry.source) === entry).map(({ unit, source, lines }) => ({
8398
+ const unique = entries.filter((entry) => first.get(entry.source) === entry);
8399
+ const record = records.find((candidate) => candidate.key === "rules" && candidate.lines.length > 0);
8400
+ const ownerRecords = records.filter((candidate) => candidate.key !== "rules" && candidate.lines.length > 0);
8401
+ const context = buildLedgerRenderContext(this.#conversation.messages(), [
8402
+ ...ownerRecords.flatMap((candidate) => candidate.lines),
8403
+ ...unique.filter((entry) => entry.unit.key !== LEDGER_RULES_KEY).flatMap((entry) => entry.lines),
8404
+ ...record?.lines ?? [],
8405
+ ...unique.filter((entry) => entry.unit.key === LEDGER_RULES_KEY).flatMap((entry) => entry.lines)
8406
+ ], amendments);
8407
+ const owners = ownerRecords.map((owner) => renderLedgerPinned(owner, context)).join("\n\n");
8408
+ const rendered = unique.map(({ unit, source, lines }) => ({
8319
8409
  rules: unit.key === LEDGER_RULES_KEY,
8320
- texts: unit.key === "rules" && source === unit.members[0] ? lines.map((line) => this.#renderSource(source, [line])) : [this.#renderSource(source, lines)]
8410
+ texts: unit.key === "rules" && source === unit.members[0] ? lines.map((line) => this.#renderSource(source, [line], context)) : [this.#renderSource(source, lines, context)]
8321
8411
  }));
8322
8412
  const pinned = rendered.filter((one) => !one.rules).flatMap((one) => one.texts);
8323
8413
  const rules = rendered.filter((one) => one.rules).flatMap((one) => one.texts);
8324
8414
  const body = [owners, pinned.join("\n")].filter((text) => text !== "").join("\n\n");
8325
- const record = records.find((candidate) => candidate.key === "rules" && candidate.lines.length > 0);
8326
- return [body === "" ? "" : `## Pinned\n${body}`, record === void 0 ? rules.length === 0 ? "" : ["## Rules", ...rules].join("\n") : [renderLedgerRecord(record), ...rules].join("\n")].filter((text) => text !== "").join("\n\n");
8415
+ return [body === "" ? "" : `## Pinned\n${body}`, record === void 0 ? rules.length === 0 ? "" : ["## Rules", ...rules].join("\n") : [renderLedgerRecord(record, context), ...rules].join("\n")].filter((text) => text !== "").join("\n\n");
8327
8416
  }
8328
8417
  #selectTail(request, cap, input) {
8329
8418
  const first = input.messages.findIndex((message) => this.#requests.has(message.id));
@@ -8463,8 +8552,7 @@ var Ledger = class {
8463
8552
  return lines.length === 0 ? void 0 : `${LEDGER_NOTES.results}\n${lines.join("\n")}`;
8464
8553
  }
8465
8554
  };
8466
- //#endregion
8467
- //#region src/core/ledgers/factories.ts
8555
+ // src/core/ledgers/factories.ts
8468
8556
  /**
8469
8557
  * Creates a conversation ledger after checking its thresholds, allocation, and tool names.
8470
8558
  * @param provider - The provider that answers requests
@@ -8480,7 +8568,6 @@ var Ledger = class {
8480
8568
  function createLedger(provider, options) {
8481
8569
  return new Ledger(provider, options);
8482
8570
  }
8483
- //#endregion
8484
8571
  exports.Agent = Agent;
8485
8572
  exports.AgentContext = AgentContext;
8486
8573
  exports.AgentError = AgentError;
@@ -8554,6 +8641,7 @@ exports.attachImages = attachImages;
8554
8641
  exports.attachUserImages = attachUserImages;
8555
8642
  exports.buildJudgeResult = buildJudgeResult;
8556
8643
  exports.buildJudgments = buildJudgments;
8644
+ exports.buildLedgerRenderContext = buildLedgerRenderContext;
8557
8645
  exports.buildLines = buildLines;
8558
8646
  exports.buildProviderHeaders = buildProviderHeaders;
8559
8647
  exports.buildProviderResult = buildProviderResult;
@@ -8562,13 +8650,13 @@ exports.buildRecapMessage = buildRecapMessage;
8562
8650
  exports.buildRecords = buildRecords;
8563
8651
  exports.buildSummaryMessage = buildSummaryMessage;
8564
8652
  exports.chargeUsage = chargeUsage;
8653
+ exports.collectAmendments = collectAmendments;
8565
8654
  exports.collectExchanges = collectExchanges;
8566
8655
  exports.collectImageData = collectImageData;
8567
8656
  exports.collectLive = collectLive;
8568
8657
  exports.collectNames = collectNames;
8569
8658
  exports.collectProjectionIds = collectProjectionIds;
8570
8659
  exports.collectRegistry = collectRegistry;
8571
- exports.collectStale = collectStale;
8572
8660
  exports.collectToolGroups = collectToolGroups;
8573
8661
  exports.computeReading = computeReading;
8574
8662
  exports.computeThinking = computeThinking;
@@ -8658,6 +8746,7 @@ exports.removeEntries = removeEntries;
8658
8746
  exports.renderCauseChain = renderCauseChain;
8659
8747
  exports.renderFencedFile = renderFencedFile;
8660
8748
  exports.renderJSON = renderJSON;
8749
+ exports.renderLedgerAnnotation = renderLedgerAnnotation;
8661
8750
  exports.renderLedgerPinned = renderLedgerPinned;
8662
8751
  exports.renderLedgerRecord = renderLedgerRecord;
8663
8752
  exports.renderLookupCall = renderLookupCall;