@orkestrel/scaffold 0.0.115 → 0.0.117

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.
Files changed (70) hide show
  1. package/dist/bin/main.js +138 -16
  2. package/dist/bin/main.js.map +1 -1
  3. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +1 -1
  4. package/dist/host/claude/agents/orkestrel.md +2 -2
  5. package/dist/host/claude/rules/names.md +3 -1
  6. package/dist/host/guides/abort.md +17 -17
  7. package/dist/host/guides/agent.md +445 -445
  8. package/dist/host/guides/brief.md +143 -143
  9. package/dist/host/guides/browser.md +731 -731
  10. package/dist/host/guides/budget.md +39 -39
  11. package/dist/host/guides/capture.md +298 -298
  12. package/dist/host/guides/console.md +109 -109
  13. package/dist/host/guides/contract.md +335 -335
  14. package/dist/host/guides/csv.md +30 -30
  15. package/dist/host/guides/database.md +163 -163
  16. package/dist/host/guides/emitter.md +17 -17
  17. package/dist/host/guides/form.md +99 -99
  18. package/dist/host/guides/guide.md +368 -183
  19. package/dist/host/guides/html.md +49 -49
  20. package/dist/host/guides/indexeddb.md +40 -40
  21. package/dist/host/guides/interpret.md +139 -139
  22. package/dist/host/guides/lsp.md +114 -114
  23. package/dist/host/guides/markdown.md +68 -68
  24. package/dist/host/guides/mcp.md +3745 -3745
  25. package/dist/host/guides/middleware.md +170 -170
  26. package/dist/host/guides/msg.md +95 -95
  27. package/dist/host/guides/ndjson.md +8 -8
  28. package/dist/host/guides/ollama.md +56 -56
  29. package/dist/host/guides/pool.md +21 -21
  30. package/dist/host/guides/probe.md +82 -82
  31. package/dist/host/guides/process.md +99 -99
  32. package/dist/host/guides/program.md +98 -96
  33. package/dist/host/guides/qualifier.md +70 -70
  34. package/dist/host/guides/queue.md +37 -37
  35. package/dist/host/guides/rater.md +38 -38
  36. package/dist/host/guides/reason.md +308 -308
  37. package/dist/host/guides/relation.md +50 -50
  38. package/dist/host/guides/router.md +58 -58
  39. package/dist/host/guides/scaffold.md +558 -419
  40. package/dist/host/guides/sea.md +128 -128
  41. package/dist/host/guides/server.md +100 -100
  42. package/dist/host/guides/sqlite.md +28 -28
  43. package/dist/host/guides/sse.md +20 -20
  44. package/dist/host/guides/study.md +444 -444
  45. package/dist/host/guides/table.md +82 -82
  46. package/dist/host/guides/template.md +41 -41
  47. package/dist/host/guides/terminal.md +121 -121
  48. package/dist/host/guides/test.md +273 -273
  49. package/dist/host/guides/timeout.md +18 -18
  50. package/dist/host/guides/tool.md +27 -27
  51. package/dist/host/guides/toolbox.md +166 -166
  52. package/dist/host/guides/websocket.md +54 -54
  53. package/dist/host/guides/worker.md +24 -24
  54. package/dist/host/guides/workflow.md +187 -187
  55. package/dist/host/guides/workspace.md +55 -55
  56. package/dist/host/manifest.json +55 -55
  57. package/dist/host/tests/setupPolicy.ts +5 -3
  58. package/dist/src/core/index.cjs +90 -4
  59. package/dist/src/core/index.cjs.map +1 -1
  60. package/dist/src/core/index.d.cts +229 -144
  61. package/dist/src/core/index.d.ts +229 -144
  62. package/dist/src/core/index.js +88 -5
  63. package/dist/src/core/index.js.map +1 -1
  64. package/dist/src/server/index.cjs +295 -66
  65. package/dist/src/server/index.cjs.map +1 -1
  66. package/dist/src/server/index.d.cts +193 -6
  67. package/dist/src/server/index.d.ts +193 -6
  68. package/dist/src/server/index.js +290 -69
  69. package/dist/src/server/index.js.map +1 -1
  70. package/package.json +5 -4
@@ -701,95 +701,95 @@ Each module section lists its exports by kind file, and a `Shape` cell reads by
701
701
 
702
702
  The following table lists the types the root declares:
703
703
 
704
- | Type | Kind | Shape | Summary |
705
- | ------------------- | --------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
706
- | `MessageRole` | type | `'system' \| 'user' \| 'assistant' \| 'tool'` | Names the role a `Message` plays in a conversation turn. |
707
- | `ThinkingReplay` | type | `'none' \| 'turn' \| 'all'` | Names which thinking the agent loop, a relay server, and a ledger retain before calling a provider: `'none'` retains none, `'turn'` retains thinking after the last `user` message, and `'all'` retains all thinking. A direct `generate` or `stream` call sends messages as given. |
708
- | `Message` | interface | `{ id, role, content, calls?, call?, images?, thinking? }` | Represents one conversation turn fed to a `ProviderInterface` — a stored, identified message. |
709
- | `MessageInput` | interface | `{ role, content, calls?, call?, images?, thinking? }` | Carries the minimal data needed to author a `Message` — the `id` is assigned by the layer that stores it, so a caller supplies only role / content (and, for a replayed assistant turn, its `calls`; for a tool turn, the `call` it answers). |
710
- | `JudgeEntry` | type | `string \| JSONRecord \| readonly JSONValue[]` | Carries text or structured JSON the model reads; mirrors the TypeSafe `EntryType` without its null arm. |
711
- | `ChoiceCriteria` | type | `Readonly<Record<string, JudgeEntry \| null>>` | Maps each option name the model receives to its description; null keeps an undescribed option in the map. |
712
- | `ScoreCriteria` | type | `readonly [JudgeEntry \| null, JudgeEntry \| null, ...Array<JudgeEntry \| null>]` | Lists at least 2 score levels from level 0 upward; null leaves a level undescribed. |
713
- | `NoulCriteria` | interface | `{ true?, false? }` | Carries what makes a noul answer true and what makes it false; an omitted side is undescribed. |
714
- | `ChoiceQuestion` | interface | `{ form, instructions?, criteria }` | Asks the model to pick one named option from its criteria. |
715
- | `ScoreQuestion` | interface | `{ form, instructions?, criteria }` | Asks the model to place the state on an ordered scale of levels. |
716
- | `NoulQuestion` | interface | `{ form, instructions?, criteria? }` | Asks the model whether a statement about the state holds. |
717
- | `JudgeQuestion` | type | `ChoiceQuestion \| ScoreQuestion \| NoulQuestion` | Names one question by its form, the protocol's type field under the fleet's named discriminant. |
718
- | `JudgeRequest` | interface | `{ state, questions }` | Carries one state and the questions asked about it, keyed by caller ids the prompt never carries; each question is evaluated on its own. |
719
- | `ChoiceAnswer` | interface | `{ form, probabilities }` | Carries a choice distribution keyed by option name, in criteria order. |
720
- | `ScoreAnswer` | interface | `{ form, probabilities }` | Carries a score distribution indexed by level. |
721
- | `NoulAnswer` | interface | `{ form, noul }` | Carries the probability that the answer is yes; the protocol's noul field. |
722
- | `JudgeAnswer` | type | `ChoiceAnswer \| ScoreAnswer \| NoulAnswer` | Names one answer by its form; it stores only the distribution a server returned. |
723
- | `Refusal` | interface | `{ missing }` | Reports a question a wire could not read a candidate for; it lists the caller's keys and invents no probability. |
724
- | `JudgeResult` | interface | `{ model, answers, refusals?, usage? }` | Carries the answering model, the answers keyed by question id, the refusals, and the usage the request's calls spent. |
725
- | `JudgeInterface` | interface | `{ id, name, model } plus ask` | Answers typed questions about one state with probabilities; the sibling of `ProviderInterface`, never a provider. |
726
- | `Judgment` | interface | `{ id, question, answer?, refusal?, model, sources, state, time, usage? }` | Records an answered or refused question with its sources, state, model, and storage time. |
727
- | `JudgmentInput` | interface | `{ id, question, answer?, refusal?, model, sources, state, usage? }` | Supplies an answered or refused question for storage before its time is stamped. |
728
- | `CodedErrorOptions` | interface | `{ cause?, context? }` | Carries the optional cause and context an error class with a machine-readable `code` takes at construction. |
704
+ | Name | Kind | Signature | Summary |
705
+ | ------------------- | --------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
706
+ | `MessageRole` | type | `(typeof MESSAGE_ROLES)[number]` | Names the role a `Message` plays in a conversation turn. |
707
+ | `ThinkingReplay` | type | `'none' \| 'turn' \| 'all'` | Names which thinking the agent loop, a relay server, and a ledger retain before calling a provider: `'none'` retains none, `'turn'` retains thinking after the last `user` message, and `'all'` retains all thinking. A direct `generate` or `stream` call sends messages as given. |
708
+ | `Message` | interface | `{ id, role, content, calls?, call?, images?, thinking? }` | Represents one conversation turn fed to a `ProviderInterface` — a stored, identified message. |
709
+ | `MessageInput` | interface | `{ role, content, calls?, call?, images?, thinking? }` | Carries the minimal data needed to author a `Message` — the `id` is assigned by the layer that stores it, so a caller supplies only role / content (and, for a replayed assistant turn, its `calls`; for a tool turn, the `call` it answers). |
710
+ | `JudgeEntry` | type | `string \| JSONRecord \| readonly JSONValue[]` | Carries text or structured JSON the model reads; mirrors the TypeSafe `EntryType` without its null arm. |
711
+ | `ChoiceCriteria` | type | `Readonly<Record<string, JudgeEntry \| null>>` | Maps each option name the model receives to its description; null keeps an undescribed option in the map. |
712
+ | `ScoreCriteria` | type | `readonly [ JudgeEntry \| null, JudgeEntry \| null, ...Array<JudgeEntry \| null> ]` | Lists at least 2 score levels from level 0 upward; null leaves a level undescribed. |
713
+ | `NoulCriteria` | interface | `{ true?, false? }` | Carries what makes a noul answer true and what makes it false; an omitted side is undescribed. |
714
+ | `ChoiceQuestion` | interface | `{ form, instructions?, criteria }` | Asks the model to pick one named option from its criteria. |
715
+ | `ScoreQuestion` | interface | `{ form, instructions?, criteria }` | Asks the model to place the state on an ordered scale of levels. |
716
+ | `NoulQuestion` | interface | `{ form, instructions?, criteria? }` | Asks the model whether a statement about the state holds. |
717
+ | `JudgeQuestion` | type | `ChoiceQuestion \| ScoreQuestion \| NoulQuestion` | Names one question by its form, the protocol's type field under the fleet's named discriminant. |
718
+ | `JudgeRequest` | interface | `{ state, questions }` | Carries one state and the questions asked about it, keyed by caller ids the prompt never carries; each question is evaluated on its own. |
719
+ | `ChoiceAnswer` | interface | `{ form, probabilities }` | Carries a choice distribution keyed by option name, in criteria order. |
720
+ | `ScoreAnswer` | interface | `{ form, probabilities }` | Carries a score distribution indexed by level. |
721
+ | `NoulAnswer` | interface | `{ form, noul }` | Carries the probability that the answer is yes; the protocol's noul field. |
722
+ | `JudgeAnswer` | type | `ChoiceAnswer \| ScoreAnswer \| NoulAnswer` | Names one answer by its form; it stores only the distribution a server returned. |
723
+ | `Refusal` | interface | `{ missing }` | Reports a question a wire could not read a candidate for; it lists the caller's keys and invents no probability. |
724
+ | `JudgeResult` | interface | `{ model, answers, refusals?, usage? }` | Carries the answering model, the answers keyed by question id, the refusals, and the usage the request's calls spent. |
725
+ | `JudgeInterface` | interface | `{ id, name, model, ask() }` | Answers typed questions about one state with probabilities; the sibling of `ProviderInterface`, never a provider. |
726
+ | `Judgment` | interface | `{ id, question, answer?, refusal?, model, sources, state, time, usage? }` | Records an answered or refused question with its sources, state, model, and storage time. |
727
+ | `JudgmentInput` | interface | `{ id, question, answer?, refusal?, model, sources, state, usage? }` | Supplies an answered or refused question for storage before its time is stamped. |
728
+ | `CodedErrorOptions` | interface | `{ cause?, context? }` | Carries the optional cause and context an error class with a machine-readable `code` takes at construction. |
729
729
 
730
730
  #### Constants
731
731
 
732
732
  The following table lists the constants the root declares:
733
733
 
734
- | API | Kind | Shape | Summary |
734
+ | Name | Kind | Signature | Summary |
735
735
  | --------------- | ----- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
736
- | `MESSAGE_ROLES` | const | `readonly ['system', 'user', 'assistant', 'tool']` | Lists the roles a conversation message can play, in the order the wire contract names them — the one list the `MessageRole` union derives from, the message guard tests membership against, and the message shape passes to its literal contract. |
736
+ | `MESSAGE_ROLES` | const | `readonly ["system", "user", "assistant", "tool"]` | Lists the roles a conversation message can play, in the order the wire contract names them — the one list the `MessageRole` union derives from, the message guard tests membership against, and the message shape passes to its literal contract. |
737
737
 
738
738
  #### Errors
739
739
 
740
740
  The following table lists the errors the root declares and the guards that narrow them:
741
741
 
742
- | API | Kind | Summary |
743
- | ------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
744
- | `JudgeAbortError` | class | Reports a judge call cancelled by the caller's signal or its deadline, carrying the `JudgeResult` merged from the calls that completed before the cancel and the machine-readable `code` `'ABORT'`. |
745
- | `isJudgeAbortError` | function | Narrows a caught value to a `JudgeAbortError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
742
+ | Name | Kind | Signature | Summary |
743
+ | ------------------- | -------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
744
+ | `JudgeAbortError` | class | `new (partial: JudgeResult, options?: ErrorOptions) => JudgeAbortError` | Reports a judge call cancelled by the caller's signal or its deadline, carrying the `JudgeResult` merged from the calls that completed before the cancel and the machine-readable `code` `'ABORT'`. |
745
+ | `isJudgeAbortError` | function | `(value: unknown) => value is JudgeAbortError` | Narrows a caught value to a `JudgeAbortError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
746
746
 
747
747
  #### Shapes and contracts
748
748
 
749
749
  The following table lists the root wire shapes and the contract compiled from them:
750
750
 
751
- | API | Kind | Shape | Summary |
752
- | ----------------- | ----- | ---------------------------------------------------------- | --------------------------------------------------------------------- |
753
- | `toolCallShape` | const | `{ id, name, arguments }` | Describes a tool call's JSON wire projection. |
754
- | `messageShape` | const | `{ id, role, content, calls?, call?, images?, thinking? }` | Describes a conversation message's JSON wire projection. |
755
- | `messageContract` | const | `Message` | Validates and projects conversation messages at a JSON wire boundary. |
751
+ | Name | Kind | Signature | Summary |
752
+ | ----------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
753
+ | `toolCallShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>` | Describes a tool call's JSON wire projection. |
754
+ | `messageShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>` | Describes a conversation message's JSON wire projection. |
755
+ | `messageContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>>` | Validates and projects conversation messages at a JSON wire boundary. |
756
756
 
757
757
  #### Cloners
758
758
 
759
759
  The following table lists the cloners the root declares:
760
760
 
761
- | API | Kind | Summary |
762
- | ---------- | -------- | -------------------------------------------------------------------------------------------------------- |
763
- | `copyJSON` | function | Owns a value by serializing it to JSON and parsing the text, so the copy shares nothing with its source. |
761
+ | Name | Kind | Signature | Summary |
762
+ | ---------- | -------- | ----------------------------- | -------------------------------------------------------------------------------------------------------- |
763
+ | `copyJSON` | function | `(value: unknown) => unknown` | Owns a value by serializing it to JSON and parsing the text, so the copy shares nothing with its source. |
764
764
 
765
765
  #### Helpers
766
766
 
767
767
  The following table lists the helpers the root declares:
768
768
 
769
- | API | Kind | Summary |
770
- | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
771
- | `filterAllowList` | function | Filters a list of members by a `ScopeInterface` allow-list of keys — `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys alone, order preserved. The pure, total set-membership primitive the context's build step and the agent loop's tool-advertise step apply a scope through. |
772
- | `sanitizeToken` | function | Sanitizes one reported token count into a non-negative integer — a non-finite or non-positive value becomes `0`, and a positive fractional value floors down. |
773
- | `sanitizeUsage` | function | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total. |
774
- | `joinThinking` | function | Joins the reasoning a run's provider calls separated from the answer — the first call seeds the accumulation, a later call appends blank-line separated so each turn's reasoning stays readable. |
775
- | `stripThinking` | function | Applies a `ThinkingReplay` policy to a conversation, returning the messages a provider sends with only the assistant thinking the policy allows. |
776
- | `sumUsage` | function | Adds two `TokenUsage` values field by field — the running total an agent run keeps across its provider calls. |
777
- | `removeEntries` | function | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
778
- | `collectExchanges` | function | Collects whole exchanges, joining every exchange spanned by a tool group. |
779
- | `collectToolGroups` | function | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
780
- | `hasCalls` | function | Checks whether a message carries at least one tool call. |
781
- | `renderJSON` | function | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
782
- | `matchesJudgment` | function | Matches a recorded question, ordered sources, rendered state, and judge identity by JSON text, so key order counts. |
769
+ | Name | Kind | Signature | Summary |
770
+ | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
771
+ | `filterAllowList` | function | `<T>(allow: readonly string[] \| undefined, members: readonly T[], key: (member: T) => string) => readonly T[]` | Filters a list of members by a `ScopeInterface` allow-list of keys — `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys alone, order preserved. The pure, total set-membership primitive the context's build step and the agent loop's tool-advertise step apply a scope through. |
772
+ | `sanitizeToken` | function | `(value: number) => number` | Sanitizes one reported token count into a non-negative integer — a non-finite or non-positive value becomes `0`, and a positive fractional value floors down. |
773
+ | `sanitizeUsage` | function | `(usage: TokenUsage) => TokenUsage` | Sanitizes a `TokenUsage` into non-negative integers — the guard an agent's abort-usage path applies to a provider's partial usage before it is charged against a budget or folded into the run total. |
774
+ | `joinThinking` | function | `(running: string \| undefined, next: string) => string` | Joins the reasoning a run's provider calls separated from the answer — the first call seeds the accumulation, a later call appends blank-line separated so each turn's reasoning stays readable. |
775
+ | `stripThinking` | function | `(messages: readonly Message[], replay: ThinkingReplay) => readonly Message[]` | Applies a `ThinkingReplay` policy to a conversation, returning the messages a provider sends with only the assistant thinking the policy allows. |
776
+ | `sumUsage` | function | `(running: TokenUsage \| undefined, next: TokenUsage) => TokenUsage` | Adds two `TokenUsage` values field by field — the running total an agent run keeps across its provider calls. |
777
+ | `removeEntries` | function | `<K>(keys: readonly K[], remove: (key: K) => boolean) => boolean` | Removes each key through a single-key remover and folds the outcomes, so a batch `remove` reports whether the whole batch applied. |
778
+ | `collectExchanges` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects whole exchanges, joining every exchange spanned by a tool group. |
779
+ | `collectToolGroups` | function | `(messages: readonly Message[]) => ReadonlyArray<readonly Message[]>` | Collects each assistant message that carries calls together with the tool messages that answer it, then each run of tool messages that no assistant message owns. |
780
+ | `hasCalls` | function | `(message: Pick<Message, 'calls'>) => boolean` | Checks whether a message carries at least one tool call. |
781
+ | `renderJSON` | function | `(value: unknown) => string \| undefined` | Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot carry the value. |
782
+ | `matchesJudgment` | function | `(judgment: Judgment, question: JudgeQuestion, sources: readonly string[], state: string, model: string) => boolean` | Matches a recorded question, ordered sources, rendered state, and judge identity by JSON text, so key order counts. |
783
783
 
784
784
  #### Validators
785
785
 
786
786
  The following table lists the guards the root declares:
787
787
 
788
- | API | Kind | Shape | Summary |
789
- | -------------------------- | -------- | --------------- | ------------------------------------------------------------------------------------------ |
790
- | `isJudgeEntry` | function | `JudgeEntry` | Checks whether a value is a judge entry: a string, a JSON record, or a JSON array. |
791
- | `isJudgeQuestion` | function | `JudgeQuestion` | Checks whether a value is a well-formed judge question of the choice, score, or noul form. |
792
- | `isNonNegativeSafeInteger` | function | `number` | Checks whether a value is a non-negative safe integer, `-0` included. |
788
+ | Name | Kind | Signature | Summary |
789
+ | -------------------------- | -------- | -------------------------------------------- | ------------------------------------------------------------------------------------------ |
790
+ | `isJudgeEntry` | function | `(value: unknown) => value is JudgeEntry` | Checks whether a value is a judge entry: a string, a JSON record, or a JSON array. |
791
+ | `isJudgeQuestion` | function | `(value: unknown) => value is JudgeQuestion` | Checks whether a value is a well-formed judge question of the choice, score, or noul form. |
792
+ | `isNonNegativeSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a non-negative safe integer, `-0` included. |
793
793
 
794
794
  ### Providers module
795
795
 
@@ -799,87 +799,87 @@ The `providers` module holds the inference boundary and its HTTP engine, the rel
799
799
 
800
800
  The following table lists the types the providers module declares:
801
801
 
802
- | Type | Kind | Shape | Summary |
803
- | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
804
- | `ProviderResult` | interface | `{ content, thinking?, tools?, usage?, truncated? }` | Holds a single inference turn's structured outcome — the assembled assistant content, any reasoning the provider separated from it, any tool calls the model requested, and the token usage it reported. |
805
- | `ProviderDelta` | type | `{ channel: 'content', text } \| { channel: 'thinking', text }` | Represents one streamed delta the `stream` method of a `ProviderInterface` yields — a unit tagged by the channel it belongs to, so the agent loop can forward answer content and live reasoning separately as each delta arrives. |
806
- | `ProviderStreamOptions` | interface | `{ think?, schema? }` | Carries the per-call options threaded into the `generate` and `stream` methods of a `ProviderInterface` — the bag a caller passes to influence one inference call without reconfiguring the provider instance. |
807
- | `ProviderInterface` | interface | `{ id, name, replay? } plus generate, stream` | Defines the pluggable LLM inference boundary — the one contract every agent chunk depends on. A provider turns a conversation (plus optional tools) into either a single assembled `ProviderResult` (`generate`) or a stream of `ProviderDelta` values that returns the assembled result (`stream`). The agent loop, a relay server, and a ledger apply its `replay` policy before calling it. A direct `generate` or `stream` call sends messages as given. |
808
- | `ProviderParserInterface` | interface | `{} plus parse, clear` | Defines the structural framing seam supplied by a concrete provider. |
809
- | `ProviderRequest` | interface | `{ messages, tools?, options? }` | Carries the conversation and per-call configuration sent to a provider. |
810
- | `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result? }` | Holds the decoded contribution of a wire record to a provider turn. |
811
- | `ProviderOptions` | interface | `{ timeout?, replay?, fetch?, headers? }` | Configures a provider's deadline, transport, and headers. |
812
- | `AgentProviderInput` | interface | `ProviderOptions plus { url, path?, split?, strict? }` | Configures the HTTP destination and stream assembly of a provider base. |
813
- | `AgentProviderInterface` | interface | `ProviderInterface plus frame, encode, read, finish` | Defines the wire-specific seams of the shared HTTP provider engine. |
814
- | `ProviderErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'PROVIDER'` | Names the machine-readable provider failure conditions. |
815
- | `ProviderErrorOptions` | interface | `{ status?, cause? }` | Carries a provider failure's HTTP status and underlying cause. |
816
- | `FailureRead` | interface | `{ message, status, cause? }` | Carries an HTTP failure message, the response status, and the underlying body-read cause when available. |
817
- | `TextRead` | interface | `{ text, complete }` | Carries a decoded stream prefix and whether the stream ended within its byte budget. |
818
- | `RelayFrame` | type | `ProviderDelta \| { channel: 'result', result } \| { channel: 'abort', partial } \| { channel: 'error', message }` | Carries a relay delta, settled result, remote abort, or remote failure. |
819
- | `RelayHandler` | type | `(request: Request) => Promise<Response>` | Defines a host-independent relay request handler. |
820
- | `RelayOptions` | interface | `{ provider, authorize, limit? }` | Configures the upstream provider, mandatory authorization, and request byte limit. |
821
- | `RelayProviderOptions` | interface | `ProviderOptions plus { url, parser }` | Configures a relay destination and its fresh structural parser factory. |
822
- | `RelayStreamOptions` | interface | `{ provider, request, signal }` | Carries the upstream call and cancellation bound of a relay response stream. |
823
- | `ThinkSplitterInterface` | interface | `{ content, thinking } plus split, flush` | Splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer, delta by delta with per-stream state, so a provider yields clean content alone and surfaces the reasoning as `ProviderResult.thinking`. |
824
- | `AgentJudgeInput` | interface | `Pick<ProviderOptions, 'timeout' \| 'fetch' \| 'headers'> plus { url, path?, model, batch? }` | Configures the judge engine's destination, identity, and call split. |
825
- | `AgentJudgeInterface` | interface | `JudgeInterface plus encode, read` | Defines the wire seams of the shared judge engine. |
826
- | `JudgeErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'QUESTION'` | Names the machine-readable judge failure conditions. |
827
- | `Reading` | interface | `{ winner, probability, confidence, score? }` | Carries the measures `computeReading` derives from an answer; nothing stores them. |
828
- | `SystemOneJudgeOptions` | interface | `Pick<ProviderOptions, 'timeout' \| 'fetch' \| 'headers'> plus { url, model }` | Configures the System One server, model, transport, authentication, and deadline. |
829
- | `SystemOneEntry` | type | `JudgeEntry \| null` | Carries a TypeSafe System One entry, including the wire's explicit null. |
830
- | `SystemOneQuestion` | interface | `{ type, instructions?, criteria? }` | Transliterates a TypeSafe System One question with its protocol discriminant and criteria. |
831
- | `SystemOneRequest` | interface | `{ state, model, questions }` | Transliterates the TypeSafe System One request body. |
832
- | `SystemOneUsage` | interface | `{ input_tokens?, output_tokens? }` | Transliterates TypeSafe System One token counts with missing or null counts permitted. |
833
- | `SystemOneChoiceAnswer` | interface | `{ type, probabilities, choice?, confidence? }` | Transliterates a TypeSafe System One choice distribution and optional server measures. |
834
- | `SystemOneScoreAnswer` | interface | `{ type, probabilities, score?, legend?, confidence? }` | Accepts System One score probabilities and legends as maps or llama.cpp arrays. |
835
- | `SystemOneNoulAnswer` | interface | `{ type, noul, confidence? }` | Transliterates a TypeSafe System One yes probability and optional server confidence. |
836
- | `SystemOneAnswer` | type | `SystemOneChoiceAnswer \| SystemOneScoreAnswer \| SystemOneNoulAnswer` | Unites the TypeSafe System One answer forms. |
837
- | `SystemOneResponse` | interface | `{ model?, answers, usage? }` | Transliterates the System One response envelope before question-specific answer validation. |
802
+ | Name | Kind | Signature | Summary |
803
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
804
+ | `ProviderResult` | interface | `{ content, thinking?, tools?, usage?, truncated? }` | Holds a single inference turn's structured outcome — the assembled assistant content, any reasoning the provider separated from it, any tool calls the model requested, and the token usage it reported. |
805
+ | `ProviderDelta` | type | `{ readonly channel: 'content'; readonly text: string; } \| { readonly channel: 'thinking'; readonly text: string; }` | Represents one streamed delta the `stream` method of a `ProviderInterface` yields — a unit tagged by the channel it belongs to, so the agent loop can forward answer content and live reasoning separately as each delta arrives. |
806
+ | `ProviderStreamOptions` | interface | `{ think?, schema? }` | Carries the per-call options threaded into the `generate` and `stream` methods of a `ProviderInterface` — the bag a caller passes to influence one inference call without reconfiguring the provider instance. |
807
+ | `ProviderInterface` | interface | `{ id, name, replay?, generate(), stream() }` | Defines the pluggable LLM inference boundary — the one contract every agent chunk depends on. A provider turns a conversation (plus optional tools) into either a single assembled `ProviderResult` (`generate`) or a stream of `ProviderDelta` values that returns the assembled result (`stream`). The agent loop, a relay server, and a ledger apply its `replay` policy before calling it. A direct `generate` or `stream` call sends messages as given. |
808
+ | `ProviderParserInterface` | interface | `{ parse(), clear() }` | Defines the structural framing seam supplied by a concrete provider. |
809
+ | `ProviderRequest` | interface | `{ messages, tools?, options? }` | Carries the conversation and per-call configuration sent to a provider. |
810
+ | `ProviderIncrement` | interface | `{ content, thinking, tools, usage?, truncated?, result? }` | Holds the decoded contribution of a wire record to a provider turn. |
811
+ | `ProviderOptions` | interface | `{ timeout?, replay?, fetch?, headers? }` | Configures a provider's deadline, transport, and headers. |
812
+ | `AgentProviderInput` | interface | `{ url, path?, split?, strict? }` | Configures the HTTP destination and stream assembly of a provider base. |
813
+ | `AgentProviderInterface` | interface | `{ frame(), encode(), read(), finish() }` | Defines the wire-specific seams of the shared HTTP provider engine. |
814
+ | `ProviderErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'PROVIDER'` | Names the machine-readable provider failure conditions. |
815
+ | `ProviderErrorOptions` | interface | `{ status?, cause? }` | Carries a provider failure's HTTP status and underlying cause. |
816
+ | `FailureRead` | interface | `{ message, status, cause? }` | Carries an HTTP failure message, the response status, and the underlying body-read cause when available. |
817
+ | `TextRead` | interface | `{ text, complete }` | Carries a decoded stream prefix and whether the stream ended within its byte budget. |
818
+ | `RelayFrame` | type | `ProviderDelta \| { readonly channel: 'result'; readonly result: ProviderResult; } \| { readonly channel: 'abort'; readonly partial: ProviderResult; } \| { readonly channel: 'error'; readonly message: string; }` | Carries a relay delta, settled result, remote abort, or remote failure. |
819
+ | `RelayHandler` | type | `(request: Request) => Promise<Response>` | Defines a host-independent relay request handler. |
820
+ | `RelayOptions` | interface | `{ provider, authorize, limit? }` | Configures the upstream provider, mandatory authorization, and request byte limit. |
821
+ | `RelayProviderOptions` | interface | `{ url, parser }` | Configures a relay destination and its fresh structural parser factory. |
822
+ | `RelayStreamOptions` | interface | `{ provider, request, signal }` | Carries the upstream call and cancellation bound of a relay response stream. |
823
+ | `ThinkSplitterInterface` | interface | `{ content, thinking, split(), flush() }` | Splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer, delta by delta with per-stream state, so a provider yields clean content alone and surfaces the reasoning as `ProviderResult.thinking`. |
824
+ | `AgentJudgeInput` | interface | `{ url, path?, model, batch? }` | Configures the judge engine's destination, identity, and call split. |
825
+ | `AgentJudgeInterface` | interface | `{ encode(), read() }` | Defines the wire seams of the shared judge engine. |
826
+ | `JudgeErrorCode` | type | `'HTTP' \| 'PROTOCOL' \| 'QUESTION'` | Names the machine-readable judge failure conditions. |
827
+ | `Reading` | interface | `{ winner, probability, confidence, score? }` | Carries the measures `computeReading` derives from an answer; nothing stores them. |
828
+ | `SystemOneJudgeOptions` | interface | `{ url, model }` | Configures the System One server, model, transport, authentication, and deadline. |
829
+ | `SystemOneEntry` | type | `JudgeEntry \| null` | Carries a TypeSafe System One entry, including the wire's explicit null. |
830
+ | `SystemOneQuestion` | interface | `{ type, instructions?, criteria? }` | Transliterates a TypeSafe System One question with its protocol discriminant and criteria. |
831
+ | `SystemOneRequest` | interface | `{ state, model, questions }` | Transliterates the TypeSafe System One request body. |
832
+ | `SystemOneUsage` | interface | `{ input_tokens?, output_tokens? }` | Transliterates TypeSafe System One token counts with missing or null counts permitted. |
833
+ | `SystemOneChoiceAnswer` | interface | `{ type, probabilities, choice?, confidence? }` | Transliterates a TypeSafe System One choice distribution and optional server measures. |
834
+ | `SystemOneScoreAnswer` | interface | `{ type, probabilities, score?, legend?, confidence? }` | Accepts System One score probabilities and legends as maps or llama.cpp arrays. |
835
+ | `SystemOneNoulAnswer` | interface | `{ type, noul, confidence? }` | Transliterates a TypeSafe System One yes probability and optional server confidence. |
836
+ | `SystemOneAnswer` | type | `SystemOneChoiceAnswer \| SystemOneScoreAnswer \| SystemOneNoulAnswer` | Unites the TypeSafe System One answer forms. |
837
+ | `SystemOneResponse` | interface | `{ model?, answers, usage? }` | Transliterates the System One response envelope before question-specific answer validation. |
838
838
 
839
839
  #### Constants
840
840
 
841
841
  The following table lists the constants the providers module declares:
842
842
 
843
- | API | Kind | Shape | Summary |
844
- | --------------------------- | ----- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
845
- | `THINK_OPEN` | const | `string` | Names the opening tag a `ThinkSplitter` recognizes as the start of an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models (qwen3, DeepSeek-R1 family) emit their chain-of-thought under when a daemon renders it inline instead of on a separate wire field. Paired with `THINK_CLOSE`. |
846
- | `THINK_CLOSE` | const | `string` | Names the closing tag that ends a `THINK_OPEN` reasoning span — `'</think>'`. A span the stream never closes (the model was cut off mid-reasoning) is treated as thinking to its end, and `ThinkSplitterInterface.flush` settles it. |
847
- | `DEFAULT_PROVIDER_TIMEOUT` | const | `number` | Holds the default provider deadline in milliseconds — `120_000`, the wall-clock bound a call runs under when `AgentProviderInput.timeout` is omitted, folded with the caller's signal so whichever trips first cancels the call. |
848
- | `MAX_ERROR_BODY_LENGTH` | const | `number` | Bounds the decoded error excerpt's input in bytes — `2048`, the leading bytes of a non-OK response body handed to the decoder before the read cancels the remainder, so a `ProviderError` message never carries a longer excerpt. |
849
- | `DEFAULT_RELAY_LIMIT` | const | `number` | Holds the default relay request limit in bytes — `1_048_576`, the byte budget a relay applies to an inbound body when `RelayOptions.limit` is omitted, refusing a body that reaches it. |
850
- | `RELAY_CONTENT_TYPE` | const | `string` | Names the relay's newline-delimited JSON content type — `'application/x-ndjson; charset=utf-8'`, the header a relay response carries beside `cache-control: no-store`. |
851
- | `RELAY_PROVIDER_MESSAGE` | const | `string` | Names the public message for an unexpected upstream relay failure — `'relay provider failed'`, the fixed text every `error` frame carries, so an upstream failure's own message never reaches the browser. |
852
- | `UNAUTHORIZED_RELAY_STATUS` | const | `number` | Names the status a relay answers when the `authorize` callback returns anything but `true` or throws — `401`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
853
- | `INVALID_RELAY_STATUS` | const | `number` | Names the status a relay answers for a body that is missing, unreadable, or rejected by `providerRequestContract` — `400`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
854
- | `OVERSIZED_RELAY_STATUS` | const | `number` | Names the status a relay answers for a request body at or above its byte budget — `413`, carried with no body and answered for an aborted inbound read as well. |
855
- | `UPSTREAM_RELAY_STATUS` | const | `number` | Names the status a relay answers when the upstream provider call cannot be constructed — `502`, carried with no body after `provider.stream` was entered and threw before returning its iterator. |
856
- | `SYSTEM_ONE_PATH` | const | `string` | Names the System One decision endpoint shared by compatible servers. |
843
+ | Name | Kind | Signature | Summary |
844
+ | --------------------------- | ----- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
845
+ | `THINK_OPEN` | const | `"<think>"` | Names the opening tag a `ThinkSplitter` recognizes as the start of an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models (qwen3, DeepSeek-R1 family) emit their chain-of-thought under when a daemon renders it inline instead of on a separate wire field. Paired with `THINK_CLOSE`. |
846
+ | `THINK_CLOSE` | const | `"</think>"` | Names the closing tag that ends a `THINK_OPEN` reasoning span — `'</think>'`. A span the stream never closes (the model was cut off mid-reasoning) is treated as thinking to its end, and `ThinkSplitterInterface.flush` settles it. |
847
+ | `DEFAULT_PROVIDER_TIMEOUT` | const | `120000` | Holds the default provider deadline in milliseconds — `120_000`, the wall-clock bound a call runs under when `AgentProviderInput.timeout` is omitted, folded with the caller's signal so whichever trips first cancels the call. |
848
+ | `MAX_ERROR_BODY_LENGTH` | const | `2048` | Bounds the decoded error excerpt's input in bytes — `2048`, the leading bytes of a non-OK response body handed to the decoder before the read cancels the remainder, so a `ProviderError` message never carries a longer excerpt. |
849
+ | `DEFAULT_RELAY_LIMIT` | const | `1048576` | Holds the default relay request limit in bytes — `1_048_576`, the byte budget a relay applies to an inbound body when `RelayOptions.limit` is omitted, refusing a body that reaches it. |
850
+ | `RELAY_CONTENT_TYPE` | const | `"application/x-ndjson; charset=utf-8"` | Names the relay's newline-delimited JSON content type — `'application/x-ndjson; charset=utf-8'`, the header a relay response carries beside `cache-control: no-store`. |
851
+ | `RELAY_PROVIDER_MESSAGE` | const | `"relay provider failed"` | Names the public message for an unexpected upstream relay failure — `'relay provider failed'`, the fixed text every `error` frame carries, so an upstream failure's own message never reaches the browser. |
852
+ | `UNAUTHORIZED_RELAY_STATUS` | const | `401` | Names the status a relay answers when the `authorize` callback returns anything but `true` or throws — `401`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
853
+ | `INVALID_RELAY_STATUS` | const | `400` | Names the status a relay answers for a body that is missing, unreadable, or rejected by `providerRequestContract` — `400`, carried with no body and reaching the browser as a `ProviderError` with the `HTTP` code. |
854
+ | `OVERSIZED_RELAY_STATUS` | const | `413` | Names the status a relay answers for a request body at or above its byte budget — `413`, carried with no body and answered for an aborted inbound read as well. |
855
+ | `UPSTREAM_RELAY_STATUS` | const | `502` | Names the status a relay answers when the upstream provider call cannot be constructed — `502`, carried with no body after `provider.stream` was entered and threw before returning its iterator. |
856
+ | `SYSTEM_ONE_PATH` | const | `"/v1/systemone"` | Names the System One decision endpoint shared by compatible servers. |
857
857
 
858
858
  #### Errors
859
859
 
860
860
  The following table lists the errors the providers module declares and the guards that narrow them:
861
861
 
862
- | API | Kind | Summary |
863
- | ---------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
864
- | `ProviderAbortError` | class | Reports a provider stream cancelled mid-flight by its bound signal — thrown by the `stream` method of a `ProviderInterface`, carrying the `ProviderResult` assembled from whatever streamed before the cancel and the machine-readable `code` `'ABORT'`. |
865
- | `isProviderAbortError` | function | Narrows an unknown caught value to a `ProviderAbortError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
866
- | `ProviderError` | class | Reports a coded provider failure with its HTTP status and underlying cause when available. |
867
- | `isProviderError` | function | Narrows a caught value to the provider failure class through its identity brand and declared members. |
868
- | `JudgeError` | class | Reports a coded judge failure with its HTTP status and underlying cause when available. |
869
- | `isJudgeError` | function | Narrows a caught value to the judge failure class through its identity brand and declared members. |
862
+ | Name | Kind | Signature | Summary |
863
+ | ---------------------- | -------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
864
+ | `ProviderAbortError` | class | `new (partial: ProviderResult, options?: ErrorOptions) => ProviderAbortError` | Reports a provider stream cancelled mid-flight by its bound signal — thrown by the `stream` method of a `ProviderInterface`, carrying the `ProviderResult` assembled from whatever streamed before the cancel and the machine-readable `code` `'ABORT'`. |
865
+ | `isProviderAbortError` | function | `(value: unknown) => value is ProviderAbortError` | Narrows an unknown caught value to a `ProviderAbortError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
866
+ | `ProviderError` | class | `new (code: ProviderErrorCode, message: string, options?: ProviderErrorOptions) => ProviderError` | Reports a coded provider failure with its HTTP status and underlying cause when available. |
867
+ | `isProviderError` | function | `(value: unknown) => value is ProviderError` | Narrows a caught value to the provider failure class through its identity brand and declared members. |
868
+ | `JudgeError` | class | `new (code: JudgeErrorCode, message: string, options?: ProviderErrorOptions) => JudgeError` | Reports a coded judge failure with its HTTP status and underlying cause when available. |
869
+ | `isJudgeError` | function | `(value: unknown) => value is JudgeError` | Narrows a caught value to the judge failure class through its identity brand and declared members. |
870
870
 
871
871
  #### Shapes and contracts
872
872
 
873
873
  The JSON wire projections the relay validates against, and the contracts compiled from them, sit here. Each projection is strictly narrower than the domain type it mirrors: a value JSON can't carry is refused rather than silently dropped, and the `caller` member of a `ToolCall` is local context that never appears here.
874
874
 
875
- | API | Kind | Shape | Summary |
876
- | ------------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
877
- | `providerRequestShape` | const | `{ messages, tools?, options? }` | Describes a provider request's JSON wire projection. |
878
- | `providerResultShape` | const | `{ content, thinking?, tools?, usage?, truncated? }` | Describes a provider result's JSON wire projection. |
879
- | `relayFrameShape` | const | `{ channel: 'content' \| 'thinking', text } \| { channel: 'result', result } \| { channel: 'abort', partial } \| { channel: 'error', message }` | Describes the channel-discriminated JSON relay wire projection. |
880
- | `providerRequestContract` | const | `ProviderRequest` | Validates and projects provider requests at a JSON wire boundary. |
881
- | `providerResultContract` | const | `ProviderResult` | Validates and projects provider results at a JSON wire boundary. |
882
- | `relayFrameContract` | const | `RelayFrame` | Validates and projects channel-discriminated relay frames at a JSON wire boundary. |
875
+ | Name | Kind | Signature | Summary |
876
+ | ------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
877
+ | `providerRequestShape` | const | `import("@orkestrel/contract").ObjectShape<{ messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ name: import("@orkestrel/contract").StringShape; description: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; parameters: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>; }, boolean \| ContractShape>>>; options: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ think: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; schema: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a provider request's JSON wire projection. |
878
+ | `providerResultShape` | const | `import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; truncated: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, boolean \| ContractShape>` | Describes a provider result's JSON wire projection. |
879
+ | `relayFrameShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ channel: import("@orkestrel/contract").LiteralShape<readonly ["content", "thinking"]>; text: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ channel: import("@orkestrel/contract").LiteralShape<readonly ["result"]>; result: import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; truncated: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ channel: import("@orkestrel/contract").LiteralShape<readonly ["abort"]>; partial: import("@orkestrel/contract").ObjectShape<{ content: import("@orkestrel/contract").StringShape; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tools: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; truncated: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ channel: import("@orkestrel/contract").LiteralShape<readonly ["error"]>; message: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>]>` | Describes the channel-discriminated JSON relay wire projection. |
880
+ | `providerRequestContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { tools?: readonly Readonly<{ name: string; } & { description?: string; parameters?: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>[]; options?: Readonly<{} & { think?: boolean; schema?: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>>` | Validates and projects provider requests at a JSON wire boundary. |
881
+ | `providerResultContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ content: string; } & { thinking?: string; tools?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; truncated?: boolean; }>>` | Validates and projects provider results at a JSON wire boundary. |
882
+ | `relayFrameContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ channel: "content" \| "thinking"; text: string; } & {}> \| Readonly<{ channel: "result"; result: Readonly<{ content: string; } & { thinking?: string; tools?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; truncated?: boolean; }>; } & {}> \| Readonly<{ channel: "abort"; partial: Readonly<{ content: string; } & { thinking?: string; tools?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; truncated?: boolean; }>; } & {}> \| Readonly<{ channel: "error"; message: string; } & {}>>` | Validates and projects channel-discriminated relay frames at a JSON wire boundary. |
883
883
 
884
884
  A contract's `is` narrows an unknown record to its wire shape, and its `parse` projects one — returning the value stripped to that shape, or `undefined` when the value is invalid — so the same declaration guards an inbound body and shapes a frame written back out:
885
885
 
@@ -906,54 +906,54 @@ relayFrameContract.parse({ channel: 'error', message: 'oops', code: 'X' }) // {
906
906
 
907
907
  The following table lists the factories the providers module declares:
908
908
 
909
- | API | Kind | Summary |
910
- | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
911
- | `createRelay` | function | Creates an authorized relay handler that validates a bounded JSON request before streaming. |
912
- | `createRelayProvider` | function | Creates a provider that carries calls through a relay endpoint. |
913
- | `createSystemOneJudge` | function | Creates a judge that sends every question through the configured System One server. |
914
- | `createThinkSplitter` | function | Creates a fresh stream-stateful `<think>` separator — a `ThinkSplitterInterface` that splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer, delta by delta, so a provider yields clean content alone and surfaces the accumulated reasoning as `ProviderResult.thinking`. One splitter serves one stream. |
909
+ | Name | Kind | Signature | Summary |
910
+ | ---------------------- | -------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
911
+ | `createRelay` | function | `(options: RelayOptions) => RelayHandler` | Creates an authorized relay handler that validates a bounded JSON request before streaming. |
912
+ | `createRelayProvider` | function | `(options: RelayProviderOptions) => ProviderInterface` | Creates a provider that carries calls through a relay endpoint. |
913
+ | `createSystemOneJudge` | function | `(options: SystemOneJudgeOptions) => JudgeInterface` | Creates a judge that sends every question through the configured System One server. |
914
+ | `createThinkSplitter` | function | `() => ThinkSplitterInterface` | Creates a fresh stream-stateful `<think>` separator — a `ThinkSplitterInterface` that splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer, delta by delta, so a provider yields clean content alone and surfaces the accumulated reasoning as `ProviderResult.thinking`. One splitter serves one stream. |
915
915
 
916
916
  #### Classes
917
917
 
918
918
  The following table lists the classes the providers module declares:
919
919
 
920
- | API | Kind | Summary |
921
- | ---------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
922
- | `AgentProvider` | class | Implements bounded HTTP streaming and result assembly behind concrete wire seams. |
923
- | `RelayProvider` | class | Carries provider calls over an authenticated NDJSON relay endpoint. |
924
- | `RelayStream` | class | Streams a provider call as validated NDJSON frames under response backpressure. |
925
- | `AgentJudge` | class | Implements the bounded HTTP calls, validation, and result merging of a judge behind concrete wire seams. |
926
- | `SystemOneJudge` | class | Carries judge questions over the System One protocol and derives answers from server distributions. |
927
- | `ThinkSplitter` | class | Separates `<think>…</think>` spans from raw content deltas with per-stream state: text inside a span accumulates on `thinking`, and text outside it returns as clean content, so a provider yields the answer alone and surfaces the reasoning as `ProviderResult.thinking`. A tag split across deltas is held until disambiguated, `flush()` settles the stream end, and one splitter serves one stream. |
920
+ | Name | Kind | Signature | Summary |
921
+ | ---------------- | ----- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
922
+ | `AgentProvider` | class | `new <TRecord = Readonly<Record<string, unknown>>>(input: AgentProviderInput) => AgentProviderInterface<TRecord>` | Implements bounded HTTP streaming and result assembly behind concrete wire seams. |
923
+ | `RelayProvider` | class | `new (options: RelayProviderOptions) => RelayProvider` | Carries provider calls over an authenticated NDJSON relay endpoint. |
924
+ | `RelayStream` | class | `new (options: RelayStreamOptions) => RelayStream` | Streams a provider call as validated NDJSON frames under response backpressure. |
925
+ | `AgentJudge` | class | `new (input: AgentJudgeInput) => AgentJudgeInterface` | Implements the bounded HTTP calls, validation, and result merging of a judge behind concrete wire seams. |
926
+ | `SystemOneJudge` | class | `new (options: SystemOneJudgeOptions) => SystemOneJudge` | Carries judge questions over the System One protocol and derives answers from server distributions. |
927
+ | `ThinkSplitter` | class | `new () => ThinkSplitterInterface` | Separates `<think>…</think>` spans from raw content deltas with per-stream state: text inside a span accumulates on `thinking`, and text outside it returns as clean content, so a provider yields the answer alone and surfaces the reasoning as `ProviderResult.thinking`. A tag split across deltas is held until disambiguated, `flush()` settles the stream end, and one splitter serves one stream. |
928
928
 
929
929
  #### Helpers
930
930
 
931
931
  The following table lists the helpers the providers module declares:
932
932
 
933
- | API | Kind | Summary |
934
- | ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
935
- | `buildProviderResult` | function | Assembles a provider result with only populated optional fields. |
936
- | `armReaderAbort` | function | Arms signal propagation to a byte reader and returns the controller that removes the listener. |
937
- | `readFailure` | function | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
938
- | `readText` | function | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
939
- | `readChunks` | function | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
940
- | `releaseReader` | function | Cancels a stream reader and releases its lock, swallowing a cancellation failure so the caller's own outcome stands. |
941
- | `computeReading` | function | Derives the winner, its probability, the published confidence, and a score answer's expected level from a judge answer's distribution. |
942
- | `buildJudgeResult` | function | Merges the results of a judge request's calls into one result. |
943
- | `buildProviderHeaders` | function | Builds a request's JSON headers, awaiting the caller's header hook inside the call's cancellation bound. |
944
- | `requestToRelay` | function | Projects a provider request onto the declared members the relay wire carries. |
945
- | `questionToSystemOne` | function | Projects a judge question onto the System One wire while preserving omitted members. |
946
- | `extractSystemOneAnswer` | function | Extracts a System One distribution in question criteria order and drops server measures. |
947
- | `extractSystemOneUsage` | function | Maps complete System One token counts onto validated token usage. |
933
+ | Name | Kind | Signature | Summary |
934
+ | ------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
935
+ | `buildProviderResult` | function | `(content: string, thinking: string, tools: readonly ToolCall[], usage: TokenUsage \| undefined, truncated: boolean \| undefined) => ProviderResult` | Assembles a provider result with only populated optional fields. |
936
+ | `armReaderAbort` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>, signal: AbortSignal \| undefined) => Promise<AbortController>` | Arms signal propagation to a byte reader and returns the controller that removes the listener. |
937
+ | `readFailure` | function | `(response: Response, prefix: string, signal: AbortSignal) => Promise<FailureRead>` | Reads a bounded HTTP failure excerpt and preserves an unreadable body's cause. |
938
+ | `readText` | function | `(body: ReadableStream<Uint8Array>, limit?: number, signal?: AbortSignal) => Promise<TextRead>` | Reads a UTF-8 prefix of a byte stream and cancels its remainder. |
939
+ | `readChunks` | function | `(body: ReadableStream<Uint8Array>, signal?: AbortSignal) => AsyncGenerator<string>` | Decodes UTF-8 chunks with a final flush and releases the stream on every exit. |
940
+ | `releaseReader` | function | `(reader: ReadableStreamDefaultReader<Uint8Array>) => Promise<void>` | Cancels a stream reader and releases its lock, swallowing a cancellation failure so the caller's own outcome stands. |
941
+ | `computeReading` | function | `(answer: JudgeAnswer) => Reading` | Derives the winner, its probability, the published confidence, and a score answer's expected level from a judge answer's distribution. |
942
+ | `buildJudgeResult` | function | `(model: string, results: readonly JudgeResult[]) => JudgeResult` | Merges the results of a judge request's calls into one result. |
943
+ | `buildProviderHeaders` | function | `(hook: ProviderOptions['headers'], signal: AbortSignal) => Promise<Headers>` | Builds a request's JSON headers, awaiting the caller's header hook inside the call's cancellation bound. |
944
+ | `requestToRelay` | function | `(request: ProviderRequest) => ProviderRequest` | Projects a provider request onto the declared members the relay wire carries. |
945
+ | `questionToSystemOne` | function | `(question: JudgeQuestion) => SystemOneQuestion` | Projects a judge question onto the System One wire while preserving omitted members. |
946
+ | `extractSystemOneAnswer` | function | `(answer: SystemOneAnswer, question: JudgeQuestion) => JudgeAnswer \| undefined` | Extracts a System One distribution in question criteria order and drops server measures. |
947
+ | `extractSystemOneUsage` | function | `(usage: SystemOneUsage \| undefined) => TokenUsage \| undefined` | Maps complete System One token counts onto validated token usage. |
948
948
 
949
949
  #### Validators
950
950
 
951
951
  The following table lists the guards the providers module declares:
952
952
 
953
- | API | Kind | Shape | Summary |
954
- | --------------------- | -------- | ------------------- | -------------------------------------------------------------------------------------------- |
955
- | `isSystemOneResponse` | function | `SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage. |
956
- | `isSystemOneAnswer` | function | `SystemOneAnswer` | Checks whether a value is a System One answer whose type and distribution the wire can read. |
953
+ | Name | Kind | Signature | Summary |
954
+ | --------------------- | -------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------- |
955
+ | `isSystemOneResponse` | function | `(value: unknown) => value is SystemOneResponse` | Checks whether a value is a System One response envelope with optional model and usage. |
956
+ | `isSystemOneAnswer` | function | `(value: unknown) => value is SystemOneAnswer` | Checks whether a value is a System One answer whose type and distribution the wire can read. |
957
957
 
958
958
  ### Conversations module
959
959
 
@@ -963,91 +963,91 @@ The `conversations` module holds the conversation, its judgment store, the conve
963
963
 
964
964
  The following table lists the types the conversations module declares:
965
965
 
966
- | Type | Kind | Shape | Summary |
967
- | ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
968
- | `MessageManagerInterface` | interface | `{ count } plus add, message, messages, remove, clear` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract `AgentContextInterface.messages` is typed to, which the active `ConversationInterface` satisfies structurally. |
969
- | `ConversationSummaryHandler` | type | `(messages: readonly Message[], signal?: AbortSignal) => Promise<string>` | Summarizes a conversation, provider-agnostically — the seam the agent runtime supplies so core never imports a provider. Given the folded messages, it resolves their digest, the model-written summary of a compacted `Section` or of the oldest sections a `sections` cap merges. |
970
- | `Section` | interface | `{ id, summary, messages }` | Holds a slice of folded messages digested into a summary — the unit of compaction a `ConversationInterface` produces when its `compact()` call folds the live tail. |
971
- | `ConversationEventMap` | type | `{ compact, rehydrate, collapse }` | Maps the push observation surface of a `ConversationInterface` — the compaction moments a fire-and-forget observer subscribes to through `conversation.emitter.on`. |
972
- | `ConversationOptions` | interface | `{ id?, on?, error?, summarize?, keep?, sections?, snapshot? }` | Configures `createConversation` — the optional `id`, the reserved `on` hooks, the provider-agnostic `summarize` seam, the retained-tail size, an optional cap on the compacted `sections` list, and a `ConversationSnapshot` to hydrate from. |
973
- | `CompactOptions` | interface | `{ keep?, sections?, signal? }` | Configures one `ConversationInterface.compact` call — the retained-tail size, the `sections` cap, or both, overridden for one fold. |
974
- | `ConversationReferenceOptions` | interface | `{ label?, messages? }` | Configures `ConversationInterface.reference` — how to render one conversation as a self-labeled, fenced provenance block to pull into another conversation by writing it to the active workspace of the active context: `label` names the source and `messages` lists the cherry-picked excerpts. |
975
- | `ConversationInterface` | interface | `{ id, judgments, emitter, sections, summarizable, count } plus add, message, messages, remove, clear, view, compact, rehydrate, search, reference, snapshot` | Groups messages above the flat `MessageManagerInterface` — a live uncompacted tail plus compacted, summarized `Section` records, with on-demand `rehydrate`, substring `search`, a cross-conversation `reference`, and a JSON `snapshot`, driven by a provider-agnostic `ConversationSummaryHandler` seam; `summarizable` reports whether that seam was supplied, and the agent loop gates automatic compaction on it. |
976
- | `ConversationInput` | interface | `{ id?, summarize?, keep?, sections?, rolling?, on?, error?, snapshot? }` | Carries the data to author a `ConversationInterface` through a `ConversationManagerInterface` — the optional `id`, a `summarize` override, a `keep` override, a `sections` cap override, the `rolling` switch, the reserved `on` hooks, and a `ConversationSnapshot` to hydrate from. |
977
- | `ConversationManagerOptions` | interface | `{ summarize?, keep?, sections?, store? }` | Configures `createConversationManager` — the default `ConversationSummaryHandler`, retained-tail size, and `sections` cap the conversations it creates inherit, plus the optional durable `store` backing `open` / `save`. |
978
- | `ConversationManagerInterface` | interface | `{ count, active } plus conversation, conversations, add, switch, open, save, remove, clear` | Registers `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContextInterface` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManagerInterface`); the observability lives on each `ConversationInterface`. |
979
- | `ConversationSnapshot` | interface | `{ id, sections, messages, judgments? }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, the compacted `sections`, and the live tail `messages` — the durable payload the `ConversationStoreInterface` persists. The exact analogue of `WorkspaceSnapshot`. |
980
- | `ConversationStoreInterface` | interface | `{} plus get, set, delete` | Persists a `ConversationSnapshot` durably — the async `get` / `set` / `delete` primitives, keyed by a conversation id and holding no expiry, the exact analogue of `WorkspaceStoreInterface`. |
981
- | `ConversationSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseConversationStore` persists — a conversation `id` plus its `ConversationSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. The exact analogue of `WorkspaceSnapshotRow`. |
982
- | `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP'` | Names the machine-readable condition a `ConversationError` reports. |
983
- | `JudgmentManagerInterface` | interface | `{ count } plus add, judgment, judgments, remove, clear, resolve` | Stores judgments by caller key and resolves requests by reusing matching records. |
966
+ | Name | Kind | Signature | Summary |
967
+ | ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
968
+ | `MessageManagerInterface` | interface | `{ count, add(), message(), messages(), remove(), clear() }` | Stores immutable `Message` records in insertion order and mints each `id` on `add` — the message-store contract `AgentContextInterface.messages` is typed to, which the active `ConversationInterface` satisfies structurally. |
969
+ | `ConversationSummaryHandler` | type | `(messages: readonly Message[], signal?: AbortSignal) => Promise<string>` | Summarizes a conversation, provider-agnostically — the seam the agent runtime supplies so core never imports a provider. Given the folded messages, it resolves their digest, the model-written summary of a compacted `Section` or of the oldest sections a `sections` cap merges. |
970
+ | `Section` | interface | `{ id, summary, messages }` | Holds a slice of folded messages digested into a summary — the unit of compaction a `ConversationInterface` produces when its `compact()` call folds the live tail. |
971
+ | `ConversationEventMap` | type | `{ readonly compact: readonly [section: Section]; readonly rehydrate: readonly [id: string]; readonly collapse: readonly [section: Section]; }` | Maps the push observation surface of a `ConversationInterface` — the compaction moments a fire-and-forget observer subscribes to through `conversation.emitter.on`. |
972
+ | `ConversationOptions` | interface | `{ id?, on?, error?, summarize?, keep?, sections?, rolling?, snapshot? }` | Configures `createConversation` — the optional `id`, the reserved `on` hooks, the provider-agnostic `summarize` seam, the retained-tail size, an optional cap on the compacted `sections` list, and a `ConversationSnapshot` to hydrate from. |
973
+ | `CompactOptions` | interface | `{ keep?, sections?, signal? }` | Configures one `ConversationInterface.compact` call — the retained-tail size, the `sections` cap, or both, overridden for one fold. |
974
+ | `ConversationReferenceOptions` | interface | `{ label?, messages? }` | Configures `ConversationInterface.reference` — how to render one conversation as a self-labeled, fenced provenance block to pull into another conversation by writing it to the active workspace of the active context: `label` names the source and `messages` lists the cherry-picked excerpts. |
975
+ | `ConversationInterface` | interface | `{ id, judgments, emitter, sections, summarizable, count, add(), message(), messages(), remove(), clear(), view(), compact(), rehydrate(), search(), reference(), snapshot() }` | Groups messages above the flat `MessageManagerInterface` — a live uncompacted tail plus compacted, summarized `Section` records, with on-demand `rehydrate`, substring `search`, a cross-conversation `reference`, and a JSON `snapshot`, driven by a provider-agnostic `ConversationSummaryHandler` seam; `summarizable` reports whether that seam was supplied, and the agent loop gates automatic compaction on it. |
976
+ | `ConversationInput` | interface | `{ id?, summarize?, keep?, sections?, rolling?, on?, error?, snapshot? }` | Carries the data to author a `ConversationInterface` through a `ConversationManagerInterface` — the optional `id`, a `summarize` override, a `keep` override, a `sections` cap override, the `rolling` switch, the reserved `on` hooks, and a `ConversationSnapshot` to hydrate from. |
977
+ | `ConversationManagerOptions` | interface | `{ summarize?, keep?, sections?, store? }` | Configures `createConversationManager` — the default `ConversationSummaryHandler`, retained-tail size, and `sections` cap the conversations it creates inherit, plus the optional durable `store` backing `open` / `save`. |
978
+ | `ConversationManagerInterface` | interface | `{ count, active, conversation(), conversations(), add(), switch(), open(), save(), remove(), clear() }` | Registers `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContextInterface` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManagerInterface`); the observability lives on each `ConversationInterface`. |
979
+ | `ConversationSnapshot` | interface | `{ id, judgments?, sections, messages }` | Holds a JSON-serializable snapshot of the state of a conversation — its `id`, the compacted `sections`, and the live tail `messages` — the durable payload the `ConversationStoreInterface` persists. The exact analogue of `WorkspaceSnapshot`. |
980
+ | `ConversationStoreInterface` | interface | `{ get(), set(), delete() }` | Persists a `ConversationSnapshot` durably — the async `get` / `set` / `delete` primitives, keyed by a conversation id and holding no expiry, the exact analogue of `WorkspaceStoreInterface`. |
981
+ | `ConversationSnapshotRow` | interface | `{ id, snapshot }` | Represents one row of the table a `DatabaseConversationStore` persists — a conversation `id` plus its `ConversationSnapshot` held as one opaque JSON column, read back as `unknown` and narrowed on `get`. The exact analogue of `WorkspaceSnapshotRow`. |
982
+ | `ConversationErrorCode` | type | `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP'` | Names the machine-readable condition a `ConversationError` reports. |
983
+ | `JudgmentManagerInterface` | interface | `{ count, add(), judgment(), judgments(), remove(), clear(), resolve() }` | Stores judgments by caller key and resolves requests by reusing matching records. |
984
984
 
985
985
  #### Constants
986
986
 
987
987
  The following table lists the constants the conversations module declares:
988
988
 
989
- | API | Kind | Shape | Summary |
990
- | --------------------------- | ----- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
991
- | `CONVERSATION_RECAP_PREFIX` | const | `string` | Names the framing label the `view()` method of a `ConversationInterface` prefixes onto the summary of each compacted section so a small model reads it as a condensed recap of earlier turns — the lean `'[Summary of earlier messages] '` marker, never a literal assistant turn to echo or treat as the live answer. |
992
- | `DEFAULT_CONVERSATION_KEEP` | const | `number` | Sets the default number of recent live messages the `compact()` method of a `ConversationInterface` retains verbatim — `0`, so a manual `compact()` keeps no recent tail and folds every exchange before the newest user message into one summarized section. A caller retains a recent tail by passing `keep` (on `ConversationOptions`, `ConversationManagerOptions`, or per-fold through `CompactOptions`), folding at most the older `count - keep` messages, cut back to whole exchanges, and leaving at least the most recent `keep` live for the next turn. Overridable everywhere `keep` is accepted. |
989
+ | Name | Kind | Signature | Summary |
990
+ | --------------------------- | ----- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
991
+ | `CONVERSATION_RECAP_PREFIX` | const | `"[Summary of earlier messages] "` | Names the framing label the `view()` method of a `ConversationInterface` prefixes onto the summary of each compacted section so a small model reads it as a condensed recap of earlier turns — the lean `'[Summary of earlier messages] '` marker, never a literal assistant turn to echo or treat as the live answer. |
992
+ | `DEFAULT_CONVERSATION_KEEP` | const | `0` | Sets the default number of recent live messages the `compact()` method of a `ConversationInterface` retains verbatim — `0`, so a manual `compact()` keeps no recent tail and folds every exchange before the newest user message into one summarized section. A caller retains a recent tail by passing `keep` (on `ConversationOptions`, `ConversationManagerOptions`, or per-fold through `CompactOptions`), folding at most the older `count - keep` messages, cut back to whole exchanges, and leaving at least the most recent `keep` live for the next turn. Overridable everywhere `keep` is accepted. |
993
993
 
994
994
  #### Errors
995
995
 
996
996
  The following table lists the errors the conversations module declares and the guards that narrow them:
997
997
 
998
- | API | Kind | Summary |
999
- | --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1000
- | `ConversationError` | class | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap below `1`, a `keep` that is not a nonnegative safe integer, or a judgment or judge request that JSON cannot carry — thrown by the `compact()` method of a `ConversationInterface`, its construction, or its judgment store, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP'`. |
1001
- | `isConversationError` | function | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
998
+ | Name | Kind | Signature | Summary |
999
+ | --------------------- | -------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1000
+ | `ConversationError` | class | `new (code: ConversationErrorCode, message: string, options?: CodedErrorOptions) => ConversationError` | Reports a conversation with no `ConversationSummaryHandler` to fold its messages with, a `sections` cap below `1`, a `keep` that is not a nonnegative safe integer, or a judgment or judge request that JSON cannot carry — thrown by the `compact()` method of a `ConversationInterface`, its construction, or its judgment store, carrying the machine-readable `code` `'SUMMARIZER' \| 'SECTIONS' \| 'JUDGMENT' \| 'KEEP'`. |
1001
+ | `isConversationError` | function | `(value: unknown) => value is ConversationError` | Narrows an unknown caught value to a `ConversationError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1002
1002
 
1003
1003
  #### Factories
1004
1004
 
1005
1005
  The following table lists the factories the conversations module declares:
1006
1006
 
1007
- | API | Kind | Summary |
1008
- | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1009
- | `createConversation` | function | Creates a conversation — a `ConversationInterface` grouping messages above a flat message store it owns directly, with compaction into summarized sections, on-demand `rehydrate`, and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam. |
1010
- | `createConversationManager` | function | Creates a conversation registry — a `ConversationManagerInterface` holding `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer: the id-keyed store over the conversation layer plus the `active` / `switch` seam the context renders. `add` auto-activates the first conversation and flows the registry's default `summarize` / `keep` into every conversation it creates. |
1011
- | `createMemoryConversationStore` | function | Creates the in-memory conversation store — a `ConversationStoreInterface` backed by a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default backing for the durable `ConversationManagerInterface.open` / `ConversationManagerInterface.save` seam. The exact twin of `createMemoryWorkspaceStore`. |
1012
- | `createDatabaseConversationStore` | function | Creates a `DatabaseConversationStore` over any `DriverInterface` — the durable, driver-pluggable backing for the conversation persistence seam, holding each snapshot as one opaque JSON column and standing as the opt-in twin of `createMemoryConversationStore`. The exact twin of `createDatabaseWorkspaceStore`. |
1007
+ | Name | Kind | Signature | Summary |
1008
+ | --------------------------------- | -------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1009
+ | `createConversation` | function | `(options?: ConversationOptions) => ConversationInterface` | Creates a conversation — a `ConversationInterface` grouping messages above a flat message store it owns directly, with compaction into summarized sections, on-demand `rehydrate`, and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam. |
1010
+ | `createConversationManager` | function | `(options?: ConversationManagerOptions) => ConversationManagerInterface` | Creates a conversation registry — a `ConversationManagerInterface` holding `ConversationInterface` instances keyed by their `id`, in insertion order, with an active pointer: the id-keyed store over the conversation layer plus the `active` / `switch` seam the context renders. `add` auto-activates the first conversation and flows the registry's default `summarize` / `keep` into every conversation it creates. |
1011
+ | `createMemoryConversationStore` | function | `() => ConversationStoreInterface` | Creates the in-memory conversation store — a `ConversationStoreInterface` backed by a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default backing for the durable `ConversationManagerInterface.open` / `ConversationManagerInterface.save` seam. The exact twin of `createMemoryWorkspaceStore`. |
1012
+ | `createDatabaseConversationStore` | function | `(driver?: DriverInterface) => ConversationStoreInterface` | Creates a `DatabaseConversationStore` over any `DriverInterface` — the durable, driver-pluggable backing for the conversation persistence seam, holding each snapshot as one opaque JSON column and standing as the opt-in twin of `createMemoryConversationStore`. The exact twin of `createDatabaseWorkspaceStore`. |
1013
1013
 
1014
1014
  #### Classes
1015
1015
 
1016
1016
  The following table lists the classes the conversations module declares:
1017
1017
 
1018
- | API | Kind | Summary |
1019
- | --------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1020
- | `Conversation` | class | Represents a conversation — a live uncompacted tail of messages it owns directly above a flat message store, plus compacted, summarized `Section` records and a `summarizable` flag, with on-demand `rehydrate` and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam so `core` never imports a provider. Observable through its own `emitter`. |
1021
- | `ConversationManager` | class | Registers `Conversation` instances keyed by `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContext` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManager`); the observability lives on each `Conversation`. |
1022
- | `MemoryConversationStore` | class | Implements the `ConversationStoreInterface` in memory — a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default store `createMemoryConversationStore` builds and the default backing for `open` / `save`. The exact twin of `MemoryWorkspaceStore`. |
1023
- | `DatabaseConversationStore` | class | Backs a `ConversationStoreInterface` with one table of the `databases` layer — a conversation's durable state is a row holding the snapshot as one opaque JSON column, narrowed back on `get` by `isConversationSnapshot`, so persistence reduces to keyed point-access (`get` / `set` / `delete`) over a `TableInterface`. The driver-pluggable twin of the plain-`Map` `MemoryConversationStore`, and the exact twin of `DatabaseWorkspaceStore`. |
1024
- | `JudgmentManager` | class | Stores judgments in insertion order and asks a judge only for unmatched question identities. |
1018
+ | Name | Kind | Signature | Summary |
1019
+ | --------------------------- | ----- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1020
+ | `Conversation` | class | `new (options?: ConversationOptions) => ConversationInterface` | Represents a conversation — a live uncompacted tail of messages it owns directly above a flat message store, plus compacted, summarized `Section` records and a `summarizable` flag, with on-demand `rehydrate` and substring `search`, driven by a provider-agnostic `ConversationSummaryHandler` seam so `core` never imports a provider. Observable through its own `emitter`. |
1021
+ | `ConversationManager` | class | `new (options?: ConversationManagerOptions) => ConversationManagerInterface` | Registers `Conversation` instances keyed by `id`, in insertion order, with an active pointer — the id-keyed store over the conversation layer, the `active` / `switch` seam the `AgentContext` renders, and the durable `open` / `save` store seam. Event-free (a registry, like `WorkspaceManager`); the observability lives on each `Conversation`. |
1022
+ | `MemoryConversationStore` | class | `new () => ConversationStoreInterface` | Implements the `ConversationStoreInterface` in memory — a process-lifetime `Map` of `ConversationSnapshot` records keyed by conversation id, the default store `createMemoryConversationStore` builds and the default backing for `open` / `save`. The exact twin of `MemoryWorkspaceStore`. |
1023
+ | `DatabaseConversationStore` | class | `new (table: TableInterface<ConversationSnapshotRow>) => ConversationStoreInterface` | Backs a `ConversationStoreInterface` with one table of the `databases` layer — a conversation's durable state is a row holding the snapshot as one opaque JSON column, narrowed back on `get` by `isConversationSnapshot`, so persistence reduces to keyed point-access (`get` / `set` / `delete`) over a `TableInterface`. The driver-pluggable twin of the plain-`Map` `MemoryConversationStore`, and the exact twin of `DatabaseWorkspaceStore`. |
1024
+ | `JudgmentManager` | class | `new (judgments?: readonly Judgment[]) => JudgmentManagerInterface` | Stores judgments in insertion order and asks a judge only for unmatched question identities. |
1025
1025
 
1026
1026
  #### Helpers
1027
1027
 
1028
1028
  The following table lists the helpers the conversations module declares:
1029
1029
 
1030
- | API | Kind | Summary |
1031
- | --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1032
- | `buildSummaryMessage` | function | Builds the raw synthetic summary message for one compacted section — role `'assistant'`, the section's stable `id`, and its `summary` verbatim as content. |
1033
- | `buildRecapMessage` | function | Builds the framed recap message for one compacted section — the same role and stable `id` as `buildSummaryMessage`, with the content prefixed by `CONVERSATION_RECAP_PREFIX`. |
1034
- | `requireJudgment` | function | Returns a stored judgment record after checking it, or throws a coded error. |
1035
- | `requireSectionsCap` | function | Returns a `sections` cap after checking its lower bound, or throws a coded error. |
1036
- | `requireRolling` | function | Returns the rolling switch after checking it does not combine with a `sections` cap, or throws a coded error. |
1037
- | `requireKeep` | function | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
1038
- | `raceSignal` | function | Settles with a promise, or rejects with the reason of a signal that aborts first, so a caller is released at once even when the work behind the promise ignores the signal. |
1039
- | `buildJudgments` | function | Builds records for answered or refused request keys, attaching usage only for a single question. |
1030
+ | Name | Kind | Signature | Summary |
1031
+ | --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1032
+ | `buildSummaryMessage` | function | `(section: Section) => Message` | Builds the raw synthetic summary message for one compacted section — role `'assistant'`, the section's stable `id`, and its `summary` verbatim as content. |
1033
+ | `buildRecapMessage` | function | `(section: Section) => Message` | Builds the framed recap message for one compacted section — the same role and stable `id` as `buildSummaryMessage`, with the content prefixed by `CONVERSATION_RECAP_PREFIX`. |
1034
+ | `requireJudgment` | function | `(value: unknown) => Judgment` | Returns a stored judgment record after checking it, or throws a coded error. |
1035
+ | `requireSectionsCap` | function | `(cap: number \| undefined) => number \| undefined` | Returns a `sections` cap after checking its lower bound, or throws a coded error. |
1036
+ | `requireRolling` | function | `(rolling: boolean, cap: number \| undefined) => boolean` | Returns the rolling switch after checking it does not combine with a `sections` cap, or throws a coded error. |
1037
+ | `requireKeep` | function | `(keep: number) => number` | Returns a retained-tail size after checking it is a nonnegative safe integer, or throws a coded error. |
1038
+ | `raceSignal` | function | `<T>(promise: Promise<T>, signal: AbortSignal \| undefined) => Promise<T>` | Settles with a promise, or rejects with the reason of a signal that aborts first, so a caller is released at once even when the work behind the promise ignores the signal. |
1039
+ | `buildJudgments` | function | `(request: JudgeRequest, result: JudgeResult, sources: readonly string[], state: string, model: string) => readonly JudgmentInput[]` | Builds records for answered or refused request keys, attaching usage only for a single question. |
1040
1040
 
1041
1041
  #### Validators
1042
1042
 
1043
1043
  The following table lists the guards the conversations module declares:
1044
1044
 
1045
- | API | Kind | Shape | Summary |
1046
- | ------------------------ | -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1047
- | `isMessage` | function | `Message` | Checks whether a value satisfies the domain conversation-message contract. |
1048
- | `isSection` | function | `Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
1049
- | `isConversationSnapshot` | function | `ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
1050
- | `isJudgment` | function | `Judgment` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1045
+ | Name | Kind | Signature | Summary |
1046
+ | ------------------------ | -------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1047
+ | `isMessage` | function | `(value: unknown) => value is Message` | Checks whether a value satisfies the domain conversation-message contract. |
1048
+ | `isSection` | function | `(value: unknown) => value is Section` | Checks whether an `unknown` is structurally a `Section` record — a `string` `id` and `summary` beside a `messages` array of valid `Message` records, the per-section step of the `isConversationSnapshot` read-boundary narrow. Total, never throwing, and never an assertion. |
1049
+ | `isConversationSnapshot` | function | `(value: unknown) => value is ConversationSnapshot` | Narrows an `unknown` to a `ConversationSnapshot` — a `string` `id` and valid `sections` and `messages` arrays; the total boundary guard for an untrusted snapshot read (a storage row a `DatabaseConversationStore` reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact analogue of `isWorkspaceSnapshot`. |
1050
+ | `isJudgment` | function | `(value: unknown) => value is Judgment` | Checks whether a stored judgment carries a valid question and exactly one answer or refusal. |
1051
1051
 
1052
1052
  A `DatabaseConversationStore` reads its snapshot column back as `unknown` and narrows it through `isConversationSnapshot`, so a malformed blob resolves `undefined` rather than a broken conversation:
1053
1053
 
@@ -1066,69 +1066,69 @@ The `contexts` module holds the turn context, its instruction and scope managers
1066
1066
 
1067
1067
  The following table lists the types the contexts module declares:
1068
1068
 
1069
- | Type | Kind | Shape | Summary |
1070
- | ----------------------------- | --------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1071
- | `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
1072
- | `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
1073
- | `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
1074
- | `InstructionManagerEventMap` | type | `{ add, remove, clear }` | Maps the push observation surface of an `InstructionManagerInterface` — the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1075
- | `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
1076
- | `InstructionManagerInterface` | interface | `{ emitter, count, open, close } plus add, instruction, instructions, render, remove, clear` | Registers `InstructionInterface` values keyed by `name` — `add` (one or a batch) mints each `id` and overwrites a same-name instruction, last write wins, while `instructions()` lists them sorted by descending `priority` and stable for ties. |
1077
- | `ScopeFilter` | interface | `{ instructions?, tools?, files? }` | Lists the per-category allow-lists a `ScopeInterface` carries — an optional `readonly string[]` for `instructions`, for `tools`, and for `files`, each keyed by that category's identity (an instruction's `name`, a tool's `name`, a workspace file's `path`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. |
1078
- | `Selection` | interface | `{ messages, judgments, usage?, fault?, briefing? }` | Carries the conversation part of the next prompt and the receipt for it. |
1079
- | `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
1080
- | `ScopeInput` | interface | `ScopeFilter plus { name, select? }` | Carries the data to author a `ScopeInterface` — a `ScopeFilter` plus the required `name` (a human label; the `id` is minted by the layer that stores it). |
1081
- | `ScopeInterface` | interface | `ScopeFilter plus { id, name, select? } plus narrow` | Represents a named, immutable filter over a richer context's items — the per-category allow-lists (`ScopeFilter`) plus an `id` / `name`, and a `narrow` that composes a tighter child by set intersection. |
1082
- | `ScopeManagerEventMap` | type | `{ add, remove, clear }` | Maps the push observation surface of a `ScopeManagerInterface` — analogous to `InstructionManagerEventMap`, but keyed by the minted `id`, so `add` never reports a replaced scope. |
1083
- | `ScopeManagerOptions` | interface | `{ on?, error? }` | Configures `createScopeManager` — the reserved `on` hooks: initial listeners for the manager's `ScopeManagerEventMap`, wired at construction. |
1084
- | `ScopeManagerInterface` | interface | `{ emitter, count } plus add, scope, scopes, remove, clear` | Registers reusable `ScopeInterface` instances keyed by their minted `id` — `add` mints + stores one (never overwrites), `scopes()` lists them in insertion order. |
1085
- | `AgentContextOptions` | interface | `{ system?, tools?, instructions?, workspaces?, scope?, conversations?, select? }` | Configures `createAgentContext` — the optional system prompt plus the pre-built managers to reuse: an `instructions` registry, a `workspaces` registry (the only document channel), a `conversations` registry (the message source), a `tools` registry (the loop's advertise and dispatch surface), and an initial `scope`. |
1086
- | `AgentContextInterface` | interface | `{ system, instructions, workspaces, messages, conversations, tools, scope } plus apply, select, build` | Assembles a turn's provider input from the system prompt + the context managers + the conversation, applying the active scope per category. |
1069
+ | Name | Kind | Signature | Summary |
1070
+ | ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1071
+ | `ContextSectionFormat` | interface | `{ open?, render?, close? }` | Overrides one context section's format — an `open` / `render` / `close` trio that frames a section in the `AgentContext` build cascade: a top line rendered once before the items, a per-item rendering, and a bottom line rendered once after the items. |
1072
+ | `InstructionInterface` | interface | `{ id, name, content, priority, override? }` | Represents an immutable instruction — a named directive a richer context places between the system prompt and the conversation, ordered by descending `priority`. |
1073
+ | `InstructionInput` | interface | `{ name, content, priority?, override? }` | Carries the minimal data to author an `InstructionInterface` — the `id` is minted by the `InstructionManagerInterface` that stores it, so a caller supplies only `name` / `content` and an optional `priority`. Default: `0`. |
1074
+ | `InstructionManagerEventMap` | type | `{ readonly add: readonly [instruction: InstructionInterface]; readonly remove: readonly [name: string]; readonly clear: readonly []; }` | Maps the push observation surface of an `InstructionManagerInterface` — the mutation moments a fire-and-forget observer subscribes to through `manager.emitter.on`. |
1075
+ | `InstructionManagerOptions` | interface | `{ on?, error?, format? }` | Configures `createInstructionManager` — the reserved `on` hooks plus an optional per-section format override. |
1076
+ | `InstructionManagerInterface` | interface | `{ emitter, count, open, close, add(), instruction(), instructions(), render(), remove(), clear() }` | Registers `InstructionInterface` values keyed by `name` — `add` (one or a batch) mints each `id` and overwrites a same-name instruction, last write wins, while `instructions()` lists them sorted by descending `priority` and stable for ties. |
1077
+ | `ScopeFilter` | interface | `{ instructions?, tools?, files? }` | Lists the per-category allow-lists a `ScopeInterface` carries — an optional `readonly string[]` for `instructions`, for `tools`, and for `files`, each keyed by that category's identity (an instruction's `name`, a tool's `name`, a workspace file's `path`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. |
1078
+ | `Selection` | interface | `{ messages, judgments, usage?, fault?, briefing? }` | Carries the conversation part of the next prompt and the receipt for it. |
1079
+ | `SelectionHandler` | type | `(conversation: ConversationInterface, request: Message, signal: AbortSignal) => Promise<Selection>` | Chooses the conversation messages the next prompt carries for one user request. |
1080
+ | `ScopeInput` | interface | `{ name, select? }` | Carries the data to author a `ScopeInterface` — a `ScopeFilter` plus the required `name` (a human label; the `id` is minted by the layer that stores it). |
1081
+ | `ScopeInterface` | interface | `{ id, name, select?, narrow() }` | Represents a named, immutable filter over a richer context's items — the per-category allow-lists (`ScopeFilter`) plus an `id` / `name`, and a `narrow` that composes a tighter child by set intersection. |
1082
+ | `ScopeManagerEventMap` | type | `{ readonly add: readonly [scope: ScopeInterface]; readonly remove: readonly [id: string]; readonly clear: readonly []; }` | Maps the push observation surface of a `ScopeManagerInterface` — analogous to `InstructionManagerEventMap`, but keyed by the minted `id`, so `add` never reports a replaced scope. |
1083
+ | `ScopeManagerOptions` | interface | `{ on?, error? }` | Configures `createScopeManager` — the reserved `on` hooks: initial listeners for the manager's `ScopeManagerEventMap`, wired at construction. |
1084
+ | `ScopeManagerInterface` | interface | `{ emitter, count, add(), scope(), scopes(), remove(), clear() }` | Registers reusable `ScopeInterface` instances keyed by their minted `id` — `add` mints + stores one (never overwrites), `scopes()` lists them in insertion order. |
1085
+ | `AgentContextOptions` | interface | `{ system?, tools?, instructions?, workspaces?, scope?, conversations?, select? }` | Configures `createAgentContext` — the optional system prompt plus the pre-built managers to reuse: an `instructions` registry, a `workspaces` registry (the only document channel), a `conversations` registry (the message source), a `tools` registry (the loop's advertise and dispatch surface), and an initial `scope`. |
1086
+ | `AgentContextInterface` | interface | `{ system, instructions, workspaces, messages, conversations, tools, scope, apply(), select(), build() }` | Assembles a turn's provider input from the system prompt + the context managers + the conversation, applying the active scope per category. |
1087
1087
 
1088
1088
  #### Constants
1089
1089
 
1090
1090
  The following table lists the constants the contexts module declares:
1091
1091
 
1092
- | API | Kind | Shape | Summary |
1093
- | -------------------------- | ----- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1094
- | `WORKSPACE_SECTION_HEADER` | const | `string` | Names the section header the `build()` method of `AgentContext` renders the active workspace's text files under — `'## Workspace'`, the leading line of the dedicated workspace block in the system message. |
1092
+ | Name | Kind | Signature | Summary |
1093
+ | -------------------------- | ----- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1094
+ | `WORKSPACE_SECTION_HEADER` | const | `"## Workspace"` | Names the section header the `build()` method of `AgentContext` renders the active workspace's text files under — `'## Workspace'`, the leading line of the dedicated workspace block in the system message. |
1095
1095
 
1096
1096
  #### Factories
1097
1097
 
1098
1098
  The following table lists the factories the contexts module declares:
1099
1099
 
1100
- | API | Kind | Summary |
1101
- | -------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1102
- | `createInstruction` | function | Creates an instruction — an immutable `InstructionInterface` (a named directive) from its `name` / `content` and optional `priority`, the `id` minted at construction. |
1103
- | `createInstructionManager` | function | Creates an instruction registry — an `InstructionManagerInterface` holding immutable instructions keyed by `name`, listed by descending `priority`. |
1104
- | `createScope` | function | Creates a named scope — an immutable `ScopeInterface` from its `name` and its per-category allow-lists, the `id` minted at construction. |
1105
- | `createScopeManager` | function | Creates a scope registry — a `ScopeManagerInterface` holding immutable scopes keyed by their minted `id`, in insertion order. |
1106
- | `createAgentContext` | function | Creates a richer turn context — an `AgentContextInterface` assembling a provider request from the optional system prompt, the instruction registry, the workspace registry (the only document channel), the conversation registry that is its `messages` source, the tool registry, and the active scope, which `build()` folds into the next turn's input. |
1100
+ | Name | Kind | Signature | Summary |
1101
+ | -------------------------- | -------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1102
+ | `createInstruction` | function | `(input: InstructionInput) => InstructionInterface` | Creates an instruction — an immutable `InstructionInterface` (a named directive) from its `name` / `content` and optional `priority`, the `id` minted at construction. |
1103
+ | `createInstructionManager` | function | `(options?: InstructionManagerOptions) => InstructionManagerInterface` | Creates an instruction registry — an `InstructionManagerInterface` holding immutable instructions keyed by `name`, listed by descending `priority`. |
1104
+ | `createScope` | function | `(input: ScopeInput) => ScopeInterface` | Creates a named scope — an immutable `ScopeInterface` from its `name` and its per-category allow-lists, the `id` minted at construction. |
1105
+ | `createScopeManager` | function | `(options?: ScopeManagerOptions) => ScopeManagerInterface` | Creates a scope registry — a `ScopeManagerInterface` holding immutable scopes keyed by their minted `id`, in insertion order. |
1106
+ | `createAgentContext` | function | `(options?: AgentContextOptions) => AgentContextInterface` | Creates a richer turn context — an `AgentContextInterface` assembling a provider request from the optional system prompt, the instruction registry, the workspace registry (the only document channel), the conversation registry that is its `messages` source, the tool registry, and the active scope, which `build()` folds into the next turn's input. |
1107
1107
 
1108
1108
  #### Classes
1109
1109
 
1110
1110
  The following table lists the classes the contexts module declares:
1111
1111
 
1112
- | API | Kind | Summary |
1113
- | -------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1114
- | `Instruction` | class | Represents an immutable named directive — an `InstructionInterface` assembled once from its input (`name` / `content` and an optional `priority`), the `id` minted at construction. Default: `0` for `priority`. |
1115
- | `InstructionManager` | class | Registers the immutable `Instruction` instances a richer context assembles a directives block from — keyed by `name` so adding an instruction whose name is already stored overwrites it, last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1116
- | `Scope` | class | Represents a named, immutable filter over a richer context's items — an optional allow-list per category (`instructions` / `tools` / `files`), each keyed by that category's identity (an instruction's `name`, a tool's `name`, a workspace file's `path`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. `narrow` composes a tighter child by set intersection. |
1117
- | `ScopeManager` | class | Registers the named filters a richer context reuses — immutable `Scope` instances keyed by their minted `id`, in insertion order, where `add` always mints and stores rather than overwriting, and an observable `emitter` reports each change. |
1118
- | `AgentContext` | class | Assembles a provider request from the richer turn context — the optional system prompt, the observable context managers (instructions / workspaces), the `ConversationManagerInterface` message source whose active conversation is `messages`, the `ToolManagerInterface` registry, and an active `ScopeInterface` changed through `AgentContextInterface.apply`. `build()` folds the scoped managers and the active workspace into one system block, then the conversation, and never reads `tools`. |
1112
+ | Name | Kind | Signature | Summary |
1113
+ | -------------------- | ----- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1114
+ | `Instruction` | class | `new (input: InstructionInput) => InstructionInterface` | Represents an immutable named directive — an `InstructionInterface` assembled once from its input (`name` / `content` and an optional `priority`), the `id` minted at construction. Default: `0` for `priority`. |
1115
+ | `InstructionManager` | class | `new (options?: InstructionManagerOptions) => InstructionManagerInterface` | Registers the immutable `Instruction` instances a richer context assembles a directives block from — keyed by `name` so adding an instruction whose name is already stored overwrites it, last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`. |
1116
+ | `Scope` | class | `new (input: ScopeInput) => ScopeInterface` | Represents a named, immutable filter over a richer context's items — an optional allow-list per category (`instructions` / `tools` / `files`), each keyed by that category's identity (an instruction's `name`, a tool's `name`, a workspace file's `path`) and read as an allow-list: `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed keys alone. `narrow` composes a tighter child by set intersection. |
1117
+ | `ScopeManager` | class | `new (options?: ScopeManagerOptions) => ScopeManagerInterface` | Registers the named filters a richer context reuses — immutable `Scope` instances keyed by their minted `id`, in insertion order, where `add` always mints and stores rather than overwriting, and an observable `emitter` reports each change. |
1118
+ | `AgentContext` | class | `new (options?: AgentContextOptions) => AgentContextInterface` | Assembles a provider request from the richer turn context — the optional system prompt, the observable context managers (instructions / workspaces), the `ConversationManagerInterface` message source whose active conversation is `messages`, the `ToolManagerInterface` registry, and an active `ScopeInterface` changed through `AgentContextInterface.apply`. `build()` folds the scoped managers and the active workspace into one system block, then the conversation, and never reads `tools`. |
1119
1119
 
1120
1120
  #### Helpers
1121
1121
 
1122
1122
  The following table lists the helpers the contexts module declares:
1123
1123
 
1124
- | API | Kind | Summary |
1125
- | ------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1126
- | `renderFencedFile` | function | Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line over a language-tagged fence, the framing the active-workspace text-file render of `AgentContext` emits. |
1127
- | `renderSection` | function | Renders one context section — the resolved `open`, each item's rendering, and the resolved `close` when one exists, blank-line joined; `undefined` when the section has no items. |
1128
- | `attachImages` | function | Copies a message with image data merged onto its `images` — the message's own images first, then the attached data, keeping every other field and never mutating the original. |
1129
- | `attachUserImages` | function | Attaches image data to a conversation's last user message — the turn a vision provider reads images off — as a new array with that one message replaced by its carrying copy, and unchanged when there is no data or no user turn. |
1130
- | `collectImageData` | function | Collects the `base64` payload of the image files in a workspace file list — the data an agent context attaches to the last user message. |
1131
- | `intersectKeys` | function | Intersects two scope category lists under the "`undefined` is the universal set" rule — a fresh copy that can only tighten, and the primitive a scope narrows through. |
1124
+ | Name | Kind | Signature | Summary |
1125
+ | ------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1126
+ | `renderFencedFile` | function | `(path: string, language: string, content: string) => string` | Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line over a language-tagged fence, the framing the active-workspace text-file render of `AgentContext` emits. |
1127
+ | `renderSection` | function | `<T>(open: string, members: readonly T[], render: (member: T) => string, close: string \| undefined) => string \| undefined` | Renders one context section — the resolved `open`, each item's rendering, and the resolved `close` when one exists, blank-line joined; `undefined` when the section has no items. |
1128
+ | `attachImages` | function | `(message: Message, payloads: readonly string[]) => Message` | Copies a message with image data merged onto its `images` — the message's own images first, then the attached data, keeping every other field and never mutating the original. |
1129
+ | `attachUserImages` | function | `(conversation: readonly Message[], payloads: readonly string[]) => readonly Message[]` | Attaches image data to a conversation's last user message — the turn a vision provider reads images off — as a new array with that one message replaced by its carrying copy, and unchanged when there is no data or no user turn. |
1130
+ | `collectImageData` | function | `(files: readonly FileInterface[]) => readonly string[]` | Collects the `base64` payload of the image files in a workspace file list — the data an agent context attaches to the last user message. |
1131
+ | `intersectKeys` | function | `(parent: readonly string[] \| undefined, child: readonly string[] \| undefined) => readonly string[] \| undefined` | Intersects two scope category lists under the "`undefined` is the universal set" rule — a fresh copy that can only tighten, and the primitive a scope narrows through. |
1132
1132
 
1133
1133
  ### Agents module
1134
1134
 
@@ -1138,106 +1138,106 @@ The `agents` module holds the loop, the authority gate, the channel, and the dur
1138
1138
 
1139
1139
  The following table lists the types the agents module declares:
1140
1140
 
1141
- | Type | Kind | Shape | Summary |
1142
- | ------------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1143
- | `AgentStatus` | type | `'idle' \| 'running' \| 'done' \| 'error'` | Names the lifecycle state of an `AgentInterface` turn — `idle` before a run, `running` while the loop is in flight, then the settled `done` (a normal finish or a cancel) or `error` (a genuine provider / tool failure). |
1144
- | `AgentChunk` | type | `{ category: 'token', content } \| { category: 'think', content } \| { category: 'tool', call, result } \| { category: 'usage', usage, estimate }` | Represents a streamed step of an agent turn — the union the loop yields as it runs, discriminated by the `category` of step it carries, and the pull surface beside the push `AgentEventMap`. |
1145
- | `AgentEventMap` | type | `{ start, turn, tool, usage, deny, finish, error, abort, exhaust, fault, select }` | Maps the push observation surface of an `AgentInterface` — the lifecycle, usage, and tool moments a fire-and-forget observer (logging, metrics, tracing) subscribes to, beside the pull `AgentChunk` stream. |
1146
- | `AgentResult` | interface | `{ content, thinking?, usage?, partial, stop? }` | Holds the settled outcome of an agent turn — the assembled assistant `content`, the `usage` summed across the turn's provider calls, and whether it was committed `partial`. |
1147
- | `AgentRunResult` | interface | `{ content, thinking, usage, partial, exhausted, stop }` | Holds the immutable outcome of one agent loop, assembled into the `AgentResult` resolved by the stream handle. |
1148
- | `AgentTurn` | interface | `{ content, thinking, usage, spent, messages, ending, partial, futile, estimate, interrupted, truncated }` | Holds what one agent loop turn contributed to its run and how the turn ended — the readonly record the loop appends for each turn, from which the run derives its `AgentRunResult`. |
1149
- | `AgentStop` | type | `{ layer: 'meter' \| 'budget', id, max, consumed, estimate?, usage? } \| { layer: 'model', id, estimate?, usage? }` | Represents why one of a run's three allowed failure layers stopped it — the meter's estimate allowance, the cost budget, or the model's own token limit — with the readings that layer crossed. |
1150
- | `AgentErrorCode` | type | `'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'WINDOW'` | Names the machine-readable agent concurrency, limit, registry, and window failures. |
1151
- | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1152
- | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1153
- | `ChannelInterface` | interface | `{} plus push, close, fail, drain` | Buffers values in an unbounded async channel — a producer writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
1154
- | `StreamInterface` | interface | `{ events, result } plus abort` | Pairs a live event stream with the eventual settled result and a cancel — the generic pull/streaming handle a long-running operation hands back. |
1155
- | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1156
- | `AgentOptions` | interface | `{ on?, error?, system?, tools?, instructions?, workspaces?, scope?, limit?, timeout?, budget?, allowance?, scheduler?, signal?, authority?, conversations?, window?, strict?, select? }` | Configures `createAgent` — the loop's bounds and pacing, the reserved `on` hooks, the construction-time context wiring (`instructions` / `workspaces` / `scope`), the `conversations` registry that is the message source, the context `window` budget that opts into automatic compaction of the active conversation, and the `strict` switch that aborts the run on an automatic-compaction summarizer failure instead of the lenient default. |
1157
- | `AgentRunOptions` | interface | `{ think?, schema?, limit?, timeout?, budget?, allowance?, signal? }` | Carries overrides for one call to the `generate` or `stream` method of an `AgentInterface`. Each member overrides the matching `AgentOptions` value, while `signal` composes with the construction signal. |
1158
- | `AgentInterface` | interface | `{ emitter, id, status, context } plus generate, stream, abort` | Composes a `ProviderInterface`, an `AgentContextInterface`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn. |
1159
- | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1160
- | `AuthorityDecision` | interface | `{ zone, allowed, reason? }` | Holds the authority verdict on one tool call. |
1161
- | `AuthorityRule` | interface | `{ match, zone, allowed?, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1162
- | `AuthorityOptions` | interface | `{ rules?, fallback? }` | Configures `createAuthority` — the ordered rules and the no-match fallback. |
1163
- | `AuthorityInterface` | interface | `{} plus evaluate` | Gates each tool call before it runs — the synchronous policy that turns one `AuthorityContext` into an `AuthorityDecision`. |
1164
- | `AgentJobInput` | interface | `{ provider, messages, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
1165
- | `AgentRegistryInterface` | interface | `{} plus provider, tool, authority, scheduler, build` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1166
- | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1167
- | `AgentQueueOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout?, store? }` | Configures `createAgentQueue` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createQueue`. |
1168
- | `AgentRunnerOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout? }` | Configures `createAgentRunner` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createRunner`. |
1141
+ | Name | Kind | Signature | Summary |
1142
+ | ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1143
+ | `AgentStatus` | type | `'idle' \| 'running' \| 'done' \| 'error'` | Names the lifecycle state of an `AgentInterface` turn — `idle` before a run, `running` while the loop is in flight, then the settled `done` (a normal finish or a cancel) or `error` (a genuine provider / tool failure). |
1144
+ | `AgentChunk` | type | `{ readonly category: 'token'; readonly content: string; } \| { readonly category: 'think'; readonly content: string; } \| { readonly category: 'tool'; readonly call: ToolCall; readonly result: ToolResult; } \| { readonly category: 'usage'; readonly usage: TokenUsage; readonly estimate: number; }` | Represents a streamed step of an agent turn — the union the loop yields as it runs, discriminated by the `category` of step it carries, and the pull surface beside the push `AgentEventMap`. |
1145
+ | `AgentEventMap` | type | `{ readonly start: readonly [id: string]; readonly turn: readonly [index: number]; readonly tool: readonly [call: ToolCall, result: ToolResult]; readonly usage: readonly [usage: TokenUsage, estimate: number]; readonly deny: readonly [call: ToolCall, reason: string \| undefined]; readonly finish: readonly [result: AgentResult]; readonly error: readonly [error: unknown]; readonly abort: readonly [reason: unknown]; readonly exhaust: readonly [turns: number]; readonly fault: readonly [error: unknown]; readonly select: readonly [selection: Selection]; }` | Maps the push observation surface of an `AgentInterface` — the lifecycle, usage, and tool moments a fire-and-forget observer (logging, metrics, tracing) subscribes to, beside the pull `AgentChunk` stream. |
1146
+ | `AgentResult` | interface | `{ content, thinking?, usage?, partial, stop? }` | Holds the settled outcome of an agent turn — the assembled assistant `content`, the `usage` summed across the turn's provider calls, and whether it was committed `partial`. |
1147
+ | `AgentRunResult` | interface | `{ content, thinking, usage, partial, exhausted, stop }` | Holds the immutable outcome of one agent loop, assembled into the `AgentResult` resolved by the stream handle. |
1148
+ | `AgentTurn` | interface | `{ content, thinking, usage, spent, messages, outcome, partial, futile, estimate, interrupted, truncated }` | Holds what one agent loop turn contributed to its run and how the turn ended — the readonly record the loop appends for each turn, from which the run derives its `AgentRunResult`. |
1149
+ | `AgentStop` | type | `{ readonly layer: 'meter' \| 'budget'; readonly id: string; readonly max: number; readonly consumed: number; readonly estimate?: number; readonly usage?: TokenUsage; } \| { readonly layer: 'model'; readonly id: string; readonly estimate?: number; readonly usage?: TokenUsage; }` | Represents why one of a run's three allowed failure layers stopped it — the meter's estimate allowance, the cost budget, or the model's own token limit — with the readings that layer crossed. |
1150
+ | `AgentErrorCode` | type | `'CONCURRENCY' \| 'LIMIT' \| 'REGISTRY' \| 'WINDOW'` | Names the machine-readable agent concurrency, limit, registry, and window failures. |
1151
+ | `MessageMeasure` | interface | `{ id, role, content, uniform, calls, thinking, images }` | Holds the disjoint estimate components of one message, in heuristic estimate units. |
1152
+ | `RequestMeasure` | interface | `{ messages, tools, schema }` | Holds the disjoint estimate components of one provider request, in heuristic estimate units. |
1153
+ | `ChannelInterface` | interface | `{ push(), close(), fail(), drain() }` | Buffers values in an unbounded async channel — a producer writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
1154
+ | `StreamInterface` | interface | `{ events, result, abort() }` | Pairs a live event stream with the eventual settled result and a cancel — the generic pull/streaming handle a long-running operation hands back. |
1155
+ | `AgentStreamInterface` | type | `StreamInterface<AgentChunk, AgentResult>` | Names the agent turn's live handle carrying `AgentChunk` values and resolving an `AgentResult`. |
1156
+ | `AgentOptions` | interface | `{ on?, error?, system?, tools?, instructions?, workspaces?, scope?, limit?, timeout?, budget?, allowance?, scheduler?, signal?, authority?, conversations?, window?, strict?, select? }` | Configures `createAgent` — the loop's bounds and pacing, the reserved `on` hooks, the construction-time context wiring (`instructions` / `workspaces` / `scope`), the `conversations` registry that is the message source, the context `window` budget that opts into automatic compaction of the active conversation, and the `strict` switch that aborts the run on an automatic-compaction summarizer failure instead of the lenient default. |
1157
+ | `AgentRunOptions` | interface | `{ think?, schema?, limit?, timeout?, budget?, allowance?, signal? }` | Carries overrides for one call to the `generate` or `stream` method of an `AgentInterface`. Each member overrides the matching `AgentOptions` value, while `signal` composes with the construction signal. |
1158
+ | `AgentInterface` | interface | `{ emitter, id, status, context, generate(), stream(), abort() }` | Composes a `ProviderInterface`, an `AgentContextInterface`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn. |
1159
+ | `AuthorityContext` | interface | `{ call }` | Carries what an `AuthorityInterface` evaluates for one tool call — the call under consideration. |
1160
+ | `AuthorityDecision` | interface | `{ zone, allowed, reason? }` | Holds the authority verdict on one tool call. |
1161
+ | `AuthorityRule` | interface | `{ match, zone, allowed?, reason? }` | Represents one ordered policy rule an `AuthorityInterface` evaluates. |
1162
+ | `AuthorityOptions` | interface | `{ rules?, fallback? }` | Configures `createAuthority` — the ordered rules and the no-match fallback. |
1163
+ | `AuthorityInterface` | interface | `{ evaluate() }` | Gates each tool call before it runs — the synchronous policy that turns one `AuthorityContext` into an `AuthorityDecision`. |
1164
+ | `AgentJobInput` | interface | `{ provider, messages, system?, tools?, authority?, scheduler?, limit?, timeout?, budget?, children? }` | Represents a JSON-serializable agent job — the descriptor a durable queue or runner runs. Its non-serializable pieces (the provider, tools, authority, scheduler) are referenced by name and resolved to live objects through an `AgentRegistryInterface` at handler time, while its data fields (the seed `messages`, `system`, `limit`, `timeout`, and a token `budget` ceiling) carry directly. |
1165
+ | `AgentRegistryInterface` | interface | `{ provider(), tool(), authority(), scheduler(), build() }` | Resolves the names in an `AgentJobInput` to live dependencies and rehydrates a seeded, signal-wired `AgentInterface`. |
1166
+ | `AgentRegistryOptions` | interface | `{ providers, tools?, authorities?, schedulers?, store? }` | Configures the named pools of live dependencies used by `createAgentRegistry` and the optional durable store shared by built agents. |
1167
+ | `AgentQueueOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout?, store? }` | Configures `createAgentQueue` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createQueue`. |
1168
+ | `AgentRunnerOptions` | interface | `{ registry, partial?, concurrency?, retries?, timeout? }` | Configures `createAgentRunner` — the registry that rehydrates jobs, the partial-result policy, and the substrate knobs threaded into the backing `createRunner`. |
1169
1169
 
1170
1170
  #### Constants
1171
1171
 
1172
1172
  The following table lists the constants the agents module declares:
1173
1173
 
1174
- | API | Kind | Shape | Summary |
1175
- | ------------------------ | ----- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1176
- | `DEFAULT_AGENT_LIMIT` | const | `number` | Caps an `AgentInterface` turn's tool iterations by default — `10` context → provider → tools cycles before the loop stops, so a model that keeps requesting tools can never loop forever. Overridable per agent through `AgentOptions.limit`. |
1177
- | `DEFAULT_AUTHORITY_ZONE` | const | `string` | Names the default zone for an unmatched tool call allowed by an authority. |
1178
- | `MESSAGE_TOKEN_OVERHEAD` | const | `number` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1179
- | `IMAGE_TOKEN_ESTIMATE` | const | `number` | Names the coarse, deliberately approximate per-image token cost `estimateMessages` charges for each attached image — `512`, because a base64 payload's length is no reliable token proxy. |
1174
+ | Name | Kind | Signature | Summary |
1175
+ | ------------------------ | ----- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1176
+ | `DEFAULT_AGENT_LIMIT` | const | `10` | Caps an `AgentInterface` turn's tool iterations by default — `10` context → provider → tools cycles before the loop stops, so a model that keeps requesting tools can never loop forever. Overridable per agent through `AgentOptions.limit`. |
1177
+ | `DEFAULT_AUTHORITY_ZONE` | const | `"default"` | Names the default zone for an unmatched tool call allowed by an authority. |
1178
+ | `MESSAGE_TOKEN_OVERHEAD` | const | `4` | Estimates the role and framing overhead added to each message by `estimateMessages`. |
1179
+ | `IMAGE_TOKEN_ESTIMATE` | const | `512` | Names the coarse, deliberately approximate per-image token cost `estimateMessages` charges for each attached image — `512`, because a base64 payload's length is no reliable token proxy. |
1180
1180
 
1181
1181
  #### Errors
1182
1182
 
1183
1183
  The following table lists the errors the agents module declares and the guards that narrow them:
1184
1184
 
1185
- | API | Kind | Summary |
1186
- | ----------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1187
- | `AgentJobError` | class | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`. |
1188
- | `isAgentJobError` | function | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
1189
- | `AgentError` | class | 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. |
1190
- | `isAgentError` | function | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1185
+ | Name | Kind | Signature | Summary |
1186
+ | ----------------- | -------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1187
+ | `AgentJobError` | class | `new (message: string, partial: AgentResult) => AgentJobError` | Reports an `AgentInterface` run that ended `AgentResult.partial` under a `partial` policy of `false` (the default) — thrown by an agent-job handler (a `createAgentQueue` / `createAgentRunner` job), carrying the partial `AgentResult` so the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`. |
1188
+ | `isAgentJobError` | function | `(value: unknown) => value is AgentJobError` | Narrows an unknown caught value to an `AgentJobError` through its identity brand and declared members, so a `catch` can recover its `partial` result. |
1189
+ | `AgentError` | class | `new (code: AgentErrorCode, message: string, options?: CodedErrorOptions) => AgentError` | 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. |
1190
+ | `isAgentError` | function | `(value: unknown) => value is AgentError` | Narrows an unknown caught value to an `AgentError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1191
1191
 
1192
1192
  #### Factories
1193
1193
 
1194
1194
  The following table lists the factories the agents module declares:
1195
1195
 
1196
- | API | Kind | Summary |
1197
- | --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1198
- | `createAgent` | function | Creates an agent loop — an `AgentInterface` composing a `ProviderInterface`, its `AgentContextInterface`, and a tool registry into a bounded context → provider → tools → repeat turn, exposed as a one-shot `generate` and a live `stream`. |
1199
- | `createAuthority` | function | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the configured default when none match. |
1200
- | `createChannel` | function | Creates an empty unbounded async channel — a `ChannelInterface` a producer writes values into (`push`) and ends (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
1201
- | `createAgentRegistry` | function | Creates a registry of live providers, tools, authorities, and schedulers whose `build` method returns a seeded, signal-wired `AgentInterface` from a serializable job. |
1202
- | `createAgentQueue` | function | Creates a durable, bounded-concurrency agent-job queue — a `QueueInterface` over serializable values of `AgentJobInput` that composes `createQueue`: each job is rehydrated through the `registry` into a live `AgentInterface`, run to its `AgentResult`, and subjected to the partial-as-configurable-failure policy. |
1203
- | `createAgentRunner` | function | Creates an agent-job runner — a `RunnerInterface` over serializable values of `AgentJobInput` that composes `createRunner` (one-shot, ordered, fail-fast), each unit rehydrated through the `registry` and subjected to the partial policy. The runner also carries sub-agent fan-out: a parent job's handler can call `controller.spawn` with a child job. |
1196
+ | Name | Kind | Signature | Summary |
1197
+ | --------------------- | -------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1198
+ | `createAgent` | function | `(provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Creates an agent loop — an `AgentInterface` composing a `ProviderInterface`, its `AgentContextInterface`, and a tool registry into a bounded context → provider → tools → repeat turn, exposed as a one-shot `generate` and a live `stream`. |
1199
+ | `createAuthority` | function | `(options?: AuthorityOptions) => AuthorityInterface` | Creates a policy gate — an `AuthorityInterface` the agent loop consults before each tool call runs, evaluating the ordered rules first-match-wins and falling back to the configured default when none match. |
1200
+ | `createChannel` | function | `<T>() => ChannelInterface<T>` | Creates an empty unbounded async channel — a `ChannelInterface` a producer writes values into (`push`) and ends (`close` / `fail`) regardless of consumption, while a consumer reads them back live through `drain`. |
1201
+ | `createAgentRegistry` | function | `(options: AgentRegistryOptions) => AgentRegistryInterface` | Creates a registry of live providers, tools, authorities, and schedulers whose `build` method returns a seeded, signal-wired `AgentInterface` from a serializable job. |
1202
+ | `createAgentQueue` | function | `(options: AgentQueueOptions) => QueueInterface<AgentJobInput, AgentResult>` | Creates a durable, bounded-concurrency agent-job queue — a `QueueInterface` over serializable values of `AgentJobInput` that composes `createQueue`: each job is rehydrated through the `registry` into a live `AgentInterface`, run to its `AgentResult`, and subjected to the partial-as-configurable-failure policy. |
1203
+ | `createAgentRunner` | function | `(options: AgentRunnerOptions) => RunnerInterface<AgentJobInput, AgentResult>` | Creates an agent-job runner — a `RunnerInterface` over serializable values of `AgentJobInput` that composes `createRunner` (one-shot, ordered, fail-fast), each unit rehydrated through the `registry` and subjected to the partial policy. The runner also carries sub-agent fan-out: a parent job's handler can call `controller.spawn` with a child job. |
1204
1204
 
1205
1205
  #### Classes
1206
1206
 
1207
1207
  The following table lists the classes the agents module declares:
1208
1208
 
1209
- | API | Kind | Summary |
1210
- | --------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1211
- | `Agent` | class | Composes a `ProviderInterface`, an `AgentContext`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn, exposed as both a one-shot `generate` and a live `stream` that share one private run — bounded by the run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by `scheduler`, with tool iteration capped at `limit`. |
1212
- | `AgentFanout` | class | Executes one runner's agent jobs — spawning each unit's declared children on its first attempt only, then rehydrating the unit through a registry with the controller signal and settling it under the shared partial-result policy. |
1213
- | `Authority` | class | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to a configurable default, which allows an unmatched call unless its `fallback` denies. |
1214
- | `AgentRegistry` | class | Makes a durable, JSON-serializable `AgentJobInput` runnable — holds the named pools of live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name absent from its pool, and its `build` method returns a seeded, signal-wired `Agent` from a job's names and data. |
1215
- | `Channel` | class | Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through the `drain` async-iterator. Decoupling write from read is what lets a producer make progress without a consumer pulling, and it is why an agent's `result` settles whether or not its `events` are drained. |
1209
+ | Name | Kind | Signature | Summary |
1210
+ | --------------- | ----- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1211
+ | `Agent` | class | `new (provider: ProviderInterface, options?: AgentOptions) => AgentInterface` | Composes a `ProviderInterface`, an `AgentContext`, and a `ToolManagerInterface` into a bounded context → provider → tools → repeat turn, exposed as both a one-shot `generate` and a live `stream` that share one private run — bounded by the run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by `scheduler`, with tool iteration capped at `limit`. |
1212
+ | `AgentFanout` | class | `new (registry: AgentRegistryInterface, partial: boolean) => AgentFanout` | Executes one runner's agent jobs — spawning each unit's declared children on its first attempt only, then rehydrating the unit through a registry with the controller signal and settling it under the shared partial-result policy. |
1213
+ | `Authority` | class | `new (options?: AuthorityOptions) => AuthorityInterface` | Gates the agent loop's tool calls — the synchronous policy consulted before each call runs, turning one `AuthorityContext` into an `AuthorityDecision` by walking the ordered rules first-match-wins and falling back to a configurable default, which allows an unmatched call unless its `fallback` denies. |
1214
+ | `AgentRegistry` | class | `new (options: AgentRegistryOptions) => AgentRegistryInterface` | Makes a durable, JSON-serializable `AgentJobInput` runnable — holds the named pools of live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name absent from its pool, and its `build` method returns a seeded, signal-wired `Agent` from a job's names and data. |
1215
+ | `Channel` | class | `new <T>() => ChannelInterface<T>` | Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`) and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live through the `drain` async-iterator. Decoupling write from read is what lets a producer make progress without a consumer pulling, and it is why an agent's `result` settles whether or not its `events` are drained. |
1216
1216
 
1217
1217
  #### Helpers
1218
1218
 
1219
1219
  The following table lists the helpers the agents module declares:
1220
1220
 
1221
- | API | Kind | Summary |
1222
- | --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1223
- | `agentResultToJSON` | function | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving finite negative and fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a non-finite usage number, a throwing getter, or a hostile or revoked proxy. |
1224
- | `tokenUsageToJSON` | function | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving finite negative and fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing or non-finite count, a throwing getter, or a hostile or revoked proxy. |
1225
- | `inferStop` | function | Infers which of a run's three failure layers stopped it — the meter allowance, a cost budget, or the model's own token limit — and returns the stop record with the final call's readings, or `undefined` when no layer stopped the run. |
1226
- | `estimateTokens` | function | Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)` character heuristic `estimateMessages` sums over a conversation's messages (the default context-budget estimator). |
1227
- | `estimateMessages` | function | Estimates the context-token footprint of a batch of messages — each message's content plus `MESSAGE_TOKEN_OVERHEAD`, a tool-call JSON estimate, a thinking estimate, and `IMAGE_TOKEN_ESTIMATE` for each attached image. The `estimateRequest` message term for an agent's context budget (the `AgentOptions` `window`), a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
1228
- | `estimateRequest` | function | Estimates the context-token footprint of a complete provider request — its messages through `estimateMessages`, plus the rendered advertised `tools`, plus the rendered `options.schema`. The `consumer` estimator an agent's `window` budget measures every request through, a provider-independent heuristic rather than an exact tokenizer count. |
1229
- | `measureMessage` | function | Measures the disjoint estimate components of one message — its content, framing, rendered calls, thinking, and attached images — as the same heuristic units `estimateMessages` sums. |
1230
- | `measureRequest` | function | Measures the disjoint estimate components of a complete provider request — each message through `measureMessage`, plus the rendered advertised `tools` and `options.schema` — as the same heuristic units `estimateRequest` sums. |
1231
- | `settleAgentJob` | function | Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial run throws an `AgentJobError` unless the `partial` policy allows it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and `createAgentRunner` both settle each job through, so the policy can never diverge between them. |
1232
- | `handleAgentQueueJob` | function | Handles one queued agent job by rehydrating it through a registry with the queue attempt's signal, then applying the shared partial-result policy. |
1233
- | `assembleResult` | function | Assembles the settled `AgentResult` from a run's `AgentRunResult` — `thinking`, `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is left out. |
1234
- | `denyCall` | function | Synthesizes the denial `ToolResult` an authority-blocked call is fed back with — the call's `id` / `name` keyed back, carrying a denial `error` instead of a value. |
1235
- | `chargeUsage` | function | Consumes a reported usage against a budget over what was already charged, so a turn's total draw is never less than the report and nothing is charged twice. |
1236
- | `requireLimit` | function | Returns a tool-iteration cap after checking it is a nonnegative safe integer, or throws a coded error. |
1237
- | `requireBudget` | function | Returns a run's budget or allowance after checking it implements `BudgetInterface`, or throws a coded error before the run starts it. |
1238
- | `renderToolValue` | function | Renders a tool's output as the string content of its tool message. |
1239
- | `requireEntry` | function | Returns a registered value or throws when its name is absent. |
1240
- | `extractQueueOptions` | function | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
1221
+ | Name | Kind | Signature | Summary |
1222
+ | --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1223
+ | `agentResultToJSON` | function | `(value: unknown) => JSONValue \| undefined` | Projects an unknown value onto a fresh, exact `JSONValue` representation of an `AgentResult` — capturing each structural field once through a total boundary, accepting conforming accessors and inherited properties, preserving finite negative and fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a non-finite usage number, a throwing getter, or a hostile or revoked proxy. |
1224
+ | `tokenUsageToJSON` | function | `(value: unknown) => TokenUsage \| undefined` | Projects an unknown value onto a fresh, exact `TokenUsage` — capturing `prompt`, `completion`, and `total` once each through a total boundary, preserving finite negative and fractional counts, dropping extras, and resolving `undefined` for a non-object, a missing or non-finite count, a throwing getter, or a hostile or revoked proxy. |
1225
+ | `inferStop` | function | `(reason: unknown, allowance: BudgetInterface<TokenUsage> \| undefined, budget: BudgetInterface<TokenUsage> \| undefined, provider: string, turn: AgentTurn \| undefined) => AgentStop \| undefined` | Infers which of a run's three failure layers stopped it — the meter allowance, a cost budget, or the model's own token limit — and returns the stop record with the final call's readings, or `undefined` when no layer stopped the run. |
1226
+ | `estimateTokens` | function | `(text: string) => number` | Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)` character heuristic `estimateMessages` sums over a conversation's messages (the default context-budget estimator). |
1227
+ | `estimateMessages` | function | `(messages: readonly Message[]) => number` | Estimates the context-token footprint of a batch of messages — each message's content plus `MESSAGE_TOKEN_OVERHEAD`, a tool-call JSON estimate, a thinking estimate, and `IMAGE_TOKEN_ESTIMATE` for each attached image. The `estimateRequest` message term for an agent's context budget (the `AgentOptions` `window`), a provider-independent approximation for conforming messages rather than an exact tokenizer count. |
1228
+ | `estimateRequest` | function | `(request: ProviderRequest) => number` | Estimates the context-token footprint of a complete provider request — its messages through `estimateMessages`, plus the rendered advertised `tools`, plus the rendered `options.schema`. The `consumer` estimator an agent's `window` budget measures every request through, a provider-independent heuristic rather than an exact tokenizer count. |
1229
+ | `measureMessage` | function | `(message: Message) => MessageMeasure` | Measures the disjoint estimate components of one message — its content, framing, rendered calls, thinking, and attached images — as the same heuristic units `estimateMessages` sums. |
1230
+ | `measureRequest` | function | `(request: ProviderRequest) => RequestMeasure` | Measures the disjoint estimate components of a complete provider request — each message through `measureMessage`, plus the rendered advertised `tools` and `options.schema` — as the same heuristic units `estimateRequest` sums. |
1231
+ | `settleAgentJob` | function | `(agent: AgentInterface, partial: boolean) => Promise<AgentResult>` | Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial run throws an `AgentJobError` unless the `partial` policy allows it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and `createAgentRunner` both settle each job through, so the policy can never diverge between them. |
1232
+ | `handleAgentQueueJob` | function | `(registry: AgentRegistryInterface, partial: boolean, input: AgentJobInput, context: QueueContext) => Promise<AgentResult>` | Handles one queued agent job by rehydrating it through a registry with the queue attempt's signal, then applying the shared partial-result policy. |
1233
+ | `assembleResult` | function | `(outcome: AgentRunResult) => AgentResult` | Assembles the settled `AgentResult` from a run's `AgentRunResult` — `thinking`, `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is left out. |
1234
+ | `denyCall` | function | `(call: ToolCall, reason: string \| undefined) => ToolResult` | Synthesizes the denial `ToolResult` an authority-blocked call is fed back with — the call's `id` / `name` keyed back, carrying a denial `error` instead of a value. |
1235
+ | `chargeUsage` | function | `(budget: BudgetInterface<TokenUsage> \| undefined, usage: TokenUsage, charged: number) => void` | Consumes a reported usage against a budget over what was already charged, so a turn's total draw is never less than the report and nothing is charged twice. |
1236
+ | `requireLimit` | function | `(limit: number) => number` | Returns a tool-iteration cap after checking it is a nonnegative safe integer, or throws a coded error. |
1237
+ | `requireBudget` | function | `(value: BudgetInterface<TokenUsage> \| undefined, key: 'budget' \| 'allowance') => BudgetInterface<TokenUsage> \| undefined` | Returns a run's budget or allowance after checking it implements `BudgetInterface`, or throws a coded error before the run starts it. |
1238
+ | `renderToolValue` | function | `(value: unknown) => string` | Renders a tool's output as the string content of its tool message. |
1239
+ | `requireEntry` | function | `<T>(pool: ReadonlyMap<string, T>, category: string, name: string) => T` | Returns a registered value or throws when its name is absent. |
1240
+ | `extractQueueOptions` | function | `(options: Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>) => Pick<QueueOptions<AgentJobInput, AgentResult>, 'concurrency' \| 'retries' \| 'timeout'>` | Extracts the present concurrency, retry, and deadline options for an agent job queue. |
1241
1241
 
1242
1242
  The measures are structural estimates, not tokenizer allocations. A message's `id` and `role` join a measure back to its message and are not token components, and a provider's template effects and the estimation error are not individually attributed.
1243
1243
 
@@ -1283,151 +1283,151 @@ The `ledgers` module serves a conversation through an event-sourced briefing: th
1283
1283
 
1284
1284
  The following table lists the types the ledger declares, each with its shape:
1285
1285
 
1286
- | Type | Kind | Shape | Summary |
1287
- | ------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1288
- | `LedgerCategory` | type | `'fact' \| 'rule' \| 'correction' \| 'request' \| 'opinion' \| 'chatter' \| 'distractor'` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1289
- | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1290
- | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1291
- | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1292
- | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1293
- | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1294
- | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1295
- | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1296
- | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1297
- | `LedgerLookupHandler` | type | `(args, text) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1298
- | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1299
- | `LedgerLookupReading` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1300
- | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1301
- | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1302
- | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1303
- | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on'>` | Selects the agent bounds and hooks a ledger passes through to the agent it builds. |
1304
- | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?: boolean, gauge?, lookups?, share?, recall?, agent? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, recall, and agent bounds. |
1305
- | `LedgerResult` | interface | `{ content, thinking?, usage?, partial, stop?, passes, readings }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1306
- | `LedgerInterface` | interface | `{ agent, conversation, gauge } plus respond, calibrate` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1307
- | `LedgerRequestInterface` | interface | `{ message, plan, selection, boundary, usage, calls, readings } plus enter, open, adopt, observe, spend, think, file, admit, recall, close, list, listing` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing readings and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1308
- | `LedgerTokenSet` | interface | `{ ids, numbers }` | Carries the id-shaped tokens and the numbers of a text. |
1309
- | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1310
- | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1311
- | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1312
- | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1313
- | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1314
- | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one briefing rendering. |
1315
- | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1316
- | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, readings, entities, classification }` | Carries what a projection reads. |
1317
- | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1318
- | `LedgerCategoryHandler` | type | `(message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1319
- | `LedgerEntityHandler` | type | `(text, partial) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1320
- | `ClassifierOptions` | interface | `{ conversation, judge, questions, topics, thresholds, assign, entities }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, and the ledger's handlers. |
1321
- | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1322
- | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1323
- | `ClassifierReading` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1324
- | `ClassifierResult` | interface | `{ judgments, usage?, readings, fault? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1325
- | `ClassifierInterface` | interface | `{} plus classify, category, quiet, decisive, topics, classification` | Files a conversation's messages through a judge and reads the filing. |
1326
- | `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1327
- | `GaugeOptions` | interface | `{ scale, overhead, capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1328
- | `GaugeInterface` | interface | `{ scale, overhead } plus rate, remainder, reserve, room, observe` | Prices prompts in tokens and measures the room a request has left. |
1329
- | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names a briefing source's planning group: a topic match, an off-topic rule or correction, or a name match. |
1330
- | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE'` | Names the machine-readable conditions a `LedgerError` error reports. |
1286
+ | Name | Kind | Signature | Summary |
1287
+ | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1288
+ | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1289
+ | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1290
+ | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1291
+ | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1292
+ | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1293
+ | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1294
+ | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1295
+ | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1296
+ | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1297
+ | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1298
+ | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1299
+ | `LedgerLookupReading` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1300
+ | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1301
+ | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1302
+ | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1303
+ | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on'>` | Selects the agent bounds and hooks a ledger passes through to the agent it builds. |
1304
+ | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, agent? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, recall, and agent bounds. |
1305
+ | `LedgerResult` | interface | `{ passes, readings }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1306
+ | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1307
+ | `LedgerRequestInterface` | interface | `{ message, plan, selection, boundary, usage, calls, readings, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), listing() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing readings and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1308
+ | `LedgerTokenSet` | interface | `{ ids, numbers }` | Carries the id-shaped tokens and the numbers of a text. |
1309
+ | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1310
+ | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1311
+ | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1312
+ | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1313
+ | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1314
+ | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one briefing rendering. |
1315
+ | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1316
+ | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, readings, entities, classification }` | Carries what a projection reads. |
1317
+ | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1318
+ | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1319
+ | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1320
+ | `ClassifierOptions` | interface | `{ conversation, judge, questions, topics, thresholds, assign, entities }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, and the ledger's handlers. |
1321
+ | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1322
+ | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1323
+ | `ClassifierReading` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1324
+ | `ClassifierResult` | interface | `{ judgments, usage?, readings, fault? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1325
+ | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1326
+ | `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1327
+ | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1328
+ | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1329
+ | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names a briefing source's planning group: a topic match, an off-topic rule or correction, or a name match. |
1330
+ | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE'` | Names the machine-readable conditions a `LedgerError` error reports. |
1331
1331
 
1332
1332
  #### Constants
1333
1333
 
1334
1334
  The following table lists the constants that hold the ledger's categories, record keys, measured wording, shares, and limits:
1335
1335
 
1336
- | API | Kind | Shape | Summary |
1337
- | --------------------------- | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1338
- | `LEDGER_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories the ledger files a message under, in the order the category question names them — the one list the `LedgerCategory` union derives from. |
1339
- | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1340
- | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the briefing renders. |
1341
- | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1342
- | `LEDGER_RULES_KEY` | const | `string` | Names the key of the record that holds the rules no owner claims. |
1343
- | `LEDGER_OWNER_PREFIX` | const | `string` | Prefixes the key of an owner's record, which the owner's id follows. |
1344
- | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1345
- | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1346
- | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
1347
- | `DEFAULT_LEDGER_LIMIT` | const | `number` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1348
- | `DEFAULT_RECALL_LIMIT` | const | `number` | Caps the `recall` calls of one request at 2 calls. |
1349
- | `LEDGER_SCALE_DRIFT` | const | `number` | Holds back the share of the prompt budget the scale can rise by between calibration and a request's first call. |
1350
- | `DETERMINISTIC_JUDGE_ERROR` | const | `RegExp` | Matches the logprob decoding failure `invalid or duplicate top logprob token`, which the ledger holds for the ledger's life. |
1336
+ | Name | Kind | Signature | Summary |
1337
+ | --------------------------- | ----- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1338
+ | `LEDGER_CATEGORIES` | const | `readonly ["fact", "rule", "correction", "request", "opinion", "chatter", "distractor"]` | Lists the categories the ledger files a message under, in the order the category question names them — the one list the `LedgerCategory` union derives from. |
1339
+ | `QUIET_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages the projection leaves out as quiet. |
1340
+ | `DECISIVE_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories whose messages state what the desk acts on, which the briefing renders. |
1341
+ | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1342
+ | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1343
+ | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1344
+ | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1345
+ | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1346
+ | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
1347
+ | `DEFAULT_LEDGER_LIMIT` | const | `8` | Caps the tool-iteration turns of a ledger's agent at 8 turns. |
1348
+ | `DEFAULT_RECALL_LIMIT` | const | `2` | Caps the `recall` calls of one request at 2 calls. |
1349
+ | `LEDGER_SCALE_DRIFT` | const | `0.06` | Holds back the share of the prompt budget the scale can rise by between calibration and a request's first call. |
1350
+ | `DETERMINISTIC_JUDGE_ERROR` | const | `RegExp` | Matches the logprob decoding failure `invalid or duplicate top logprob token`, which the ledger holds for the ledger's life. |
1351
1351
 
1352
1352
  #### Errors
1353
1353
 
1354
1354
  The following table lists the error the ledger raises and the guard that narrows it:
1355
1355
 
1356
- | API | Kind | Summary |
1357
- | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
1358
- | `LedgerError` | class | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
1359
- | `isLedgerError` | function | Narrows an unknown caught value to a `LedgerError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1356
+ | Name | Kind | Signature | Summary |
1357
+ | --------------- | -------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
1358
+ | `LedgerError` | class | `new (code: LedgerErrorCode, message: string) => LedgerError` | Reports an invalid ledger configuration, failed calibration, or unowned request selection, carrying the machine-readable `code`. |
1359
+ | `isLedgerError` | function | `(value: unknown) => value is LedgerError` | Narrows an unknown caught value to a `LedgerError` through its identity brand and declared members, so a `catch` can branch on its `code`. |
1360
1360
 
1361
1361
  #### Factories
1362
1362
 
1363
1363
  The following table lists the factory that builds a ledger:
1364
1364
 
1365
- | API | Kind | Signature | Summary |
1366
- | -------------- | -------- | ---------------------------------------- | ---------------------------------------------------------------------------------------- |
1367
- | `createLedger` | function | `(provider, options) => LedgerInterface` | Creates a conversation ledger after checking its thresholds, allocation, and tool names. |
1365
+ | Name | Kind | Signature | Summary |
1366
+ | -------------- | -------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
1367
+ | `createLedger` | function | `(provider: ProviderInterface, options: LedgerOptions) => LedgerInterface` | Creates a conversation ledger after checking its thresholds, allocation, and tool names. |
1368
1368
 
1369
1369
  #### Classes
1370
1370
 
1371
1371
  The following table lists the classes that serve, file, and price a conversation and hold one request:
1372
1372
 
1373
- | API | Kind | Summary |
1374
- | --------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1375
- | `Ledger` | class | Serves one conversation through classified records, a bounded briefing, and a final answer pass. |
1376
- | `LedgerRequest` | class | Holds what one ledger request keeps while it is served: its message, its filing readings and plan, the gauge calls of its passes, and its repeat and recall stops. |
1377
- | `Classifier` | class | Files messages through the conversation's judgment manager and reads their categories and corrections. |
1378
- | `Gauge` | class | Prices prompts in tokens from a measured scale and overhead cost, and measures the room a request has left. |
1373
+ | Name | Kind | Signature | Summary |
1374
+ | --------------- | ----- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1375
+ | `Ledger` | class | `new (provider: ProviderInterface, options: LedgerOptions) => LedgerInterface` | Serves one conversation through classified records, a bounded briefing, and a final answer pass. |
1376
+ | `LedgerRequest` | class | `new (content: string, limit?: number) => LedgerRequestInterface` | Holds what one ledger request keeps while it is served: its message, its filing readings and plan, the gauge calls of its passes, and its repeat and recall stops. |
1377
+ | `Classifier` | class | `new (options: ClassifierOptions) => ClassifierInterface` | Files messages through the conversation's judgment manager and reads their categories and corrections. |
1378
+ | `Gauge` | class | `new (options: GaugeOptions) => GaugeInterface` | Prices prompts in tokens from a measured scale and overhead cost, and measures the room a request has left. |
1379
1379
 
1380
1380
  #### Validators
1381
1381
 
1382
1382
  The following guards validate ledger fractions and capacity:
1383
1383
 
1384
- | API | Kind | Summary |
1385
- | ----------------------- | -------- | ----------------------------------------------------------------- |
1386
- | `isFraction` | function | Checks whether a value is finite and lies in the interval (0, 1]. |
1387
- | `isPositiveSafeInteger` | function | Checks whether a value is a positive safe integer. |
1384
+ | Name | Kind | Signature | Summary |
1385
+ | ----------------------- | -------- | ------------------------------------- | ------------------------------------------------------------------ |
1386
+ | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1387
+ | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1388
1388
 
1389
1389
  #### Helpers
1390
1390
 
1391
1391
  The following table lists the pure helpers that read text, project and select records, render a briefing, and fit a price:
1392
1392
 
1393
- | API | Kind | Signature | Summary |
1394
- | -------------------------- | -------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
1395
- | `splitSentences` | function | `(text) => readonly string[]` | Splits a message into its sentences. |
1396
- | `extractTokens` | function | `(text) => LedgerTokenSet` | Reads the id-shaped tokens and the numbers of a text. |
1397
- | `collectNames` | function | `(text) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
1398
- | `identifyLookup` | function | `(name, args) => string \| undefined` | Identifies a lookup reading for projection by its tool name and normalized arguments. |
1399
- | `linkOwners` | function | `(readings, owners) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
1400
- | `collectRegistry` | function | `(readings) => LedgerRegistry` | Collects the ids and the owner names the lookup readings named. |
1401
- | `matchEntities` | function | `(registry, text, partial) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
1402
- | `buildRecords` | function | `(input) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
1403
- | `selectRecords` | function | `(projection, request) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
1404
- | `findLedgerCall` | function | `(group, message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
1405
- | `collectProjectionIds` | function | `(projection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
1406
- | `scanAmendments` | function | `(amendments, start, admit) => readonly string[]` | Scans admitted amendments in breadth-first order without revisiting a message. |
1407
- | `buildRecallMessage` | function | `(topic) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
1408
- | `renderTopicNames` | function | `(topics) => string` | Renders topic names as a comma-separated list in their supplied order. |
1409
- | `renderCauseChain` | function | `(error) => string` | Renders an error and its causes, stopping after 4 entries. |
1410
- | `extractWords` | function | `(message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
1411
- | `splitWords` | function | `(part) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
1412
- | `rankLedgerCut` | function | `(group, unsettled, category) => number` | Ranks a briefing source for removal before the next prompt. |
1413
- | `renderLedgerRecord` | function | `(record, context?) => string` | Renders one record as a heading and one list item per line. |
1414
- | `renderLedgerPinned` | function | `(record, context?) => string` | Renders one owner record under a `###` heading, which the briefing nests under its one `## Pinned` heading. |
1415
- | `splitTopic` | function | `(topic) => readonly string[]` | Splits a recall topic at its joints. |
1416
- | `cutListing` | function | `(entries, room) => string` | Cuts entries to a room and names how many it left out. |
1417
- | `matchesCutLine` | function | `(line) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
1418
- | `normalizeArgument` | function | `(value) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
1419
- | `splitResultLines` | function | `(text) => readonly string[]` | Splits a tool result into its lines at each line feed, with or without a carriage return before it. |
1420
- | `renderLookupCall` | function | `(name, args) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1421
- | `renderStub` | function | `(name, args, state) => string` | Renders the tail stub of a lookup result from an earlier request. |
1422
- | `computeThinking` | function | `(message, completion) => number` | Computes the completion tokens attributable to a message's thinking. |
1423
- | `resolvePredict` | function | `(predict, capacity) => number` | Resolves the generation cap and checks it against the context capacity. |
1424
- | `fitSlope` | function | `(groups) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
1425
- | `collectLive` | function | `(input) => readonly string[]` | Collects the ids of the live messages in conversation order. |
1426
- | `placeMember` | function | `(input, links, amending, id, seen, settled?) => ReadonlySet<string>` | Places a message on the record keys it joins. |
1427
- | `buildLedgerRenderContext` | function | `(messages, lines, amendments) => LedgerRenderContext` | Derives complete source identities, first occurrences, and local references from the actual briefing lines. |
1428
- | `renderLedgerAnnotation` | function | `(line, context) => string` | Renders source framing and unresolved amendment scope at a source's first retained line. |
1429
- | `collectAmendments` | function | `(input, byId, live) => readonly LedgerAmendment[]` | Collects accepted direct amendments of live messages. |
1430
- | `buildLines` | function | `(input, byId, id, holders, system) => readonly LedgerLine[]` | Builds the record lines of one message. |
1393
+ | Name | Kind | Signature | Summary |
1394
+ | -------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
1395
+ | `splitSentences` | function | `(text: string) => readonly string[]` | Splits a message into its sentences. |
1396
+ | `extractTokens` | function | `(text: string) => LedgerTokenSet` | Reads the id-shaped tokens and the numbers of a text. |
1397
+ | `collectNames` | function | `(text: string) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
1398
+ | `identifyLookup` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string \| undefined` | Identifies a lookup reading for projection by its tool name and normalized arguments. |
1399
+ | `linkOwners` | function | `(readings: readonly LedgerLookupReading[], owners: ReadonlyMap<string, readonly string[]>) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
1400
+ | `collectRegistry` | function | `(readings: readonly LedgerLookupReading[]) => LedgerRegistry` | Collects the ids and the owner names the lookup readings named. |
1401
+ | `matchEntities` | function | `(registry: LedgerRegistry, text: string, partial: boolean) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
1402
+ | `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
1403
+ | `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
1404
+ | `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
1405
+ | `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
1406
+ | `scanAmendments` | function | `(amendments: ReadonlyMap<string, readonly string[]>, start: string, admit: (id: string) => boolean) => readonly string[]` | Scans admitted amendments in breadth-first order without revisiting a message. |
1407
+ | `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
1408
+ | `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
1409
+ | `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
1410
+ | `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
1411
+ | `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
1412
+ | `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a briefing source for removal before the next prompt. |
1413
+ | `renderLedgerRecord` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one record as a heading and one list item per line. |
1414
+ | `renderLedgerPinned` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one owner record under a `###` heading, which the briefing nests under its one `## Pinned` heading. |
1415
+ | `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
1416
+ | `cutListing` | function | `(entries: readonly string[], room: number) => string` | Cuts entries to a room and names how many it left out. |
1417
+ | `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
1418
+ | `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
1419
+ | `splitResultLines` | function | `(text: string) => readonly string[]` | Splits a tool result into its lines at each line feed, with or without a carriage return before it. |
1420
+ | `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1421
+ | `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState) => string` | Renders the tail stub of a lookup result from an earlier request. |
1422
+ | `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
1423
+ | `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
1424
+ | `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
1425
+ | `collectLive` | function | `(input: LedgerProjectionInput) => readonly string[]` | Collects the ids of the live messages in conversation order. |
1426
+ | `placeMember` | function | `(input: LedgerProjectionInput, links: ReadonlyMap<string, string>, amending: ReadonlyMap<string, readonly string[]>, id: string, seen: ReadonlySet<string>, settled?: Map<string, ReadonlySet<string>>) => ReadonlySet<string>` | Places a message on the record keys it joins. |
1427
+ | `buildLedgerRenderContext` | function | `(messages: readonly Message[], lines: readonly LedgerLine[], amendments: readonly LedgerAmendment[]) => LedgerRenderContext` | Derives complete source identities, first occurrences, and local references from the actual briefing lines. |
1428
+ | `renderLedgerAnnotation` | function | `(line: LedgerLine, context: LedgerRenderContext) => string` | Renders source framing and unresolved amendment scope at a source's first retained line. |
1429
+ | `collectAmendments` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, live: readonly string[]) => readonly LedgerAmendment[]` | Collects accepted direct amendments of live messages. |
1430
+ | `buildLines` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, id: string, holders: readonly string[], system: readonly string[]) => readonly LedgerLine[]` | Builds the record lines of one message. |
1431
1431
 
1432
1432
  The `Classifier` and `Gauge` classes the ledger composes are public, so a harness can file a conversation or price a prompt without a ledger. The following classifier files one rule, and the following gauge prices the calls of one request:
1433
1433