@orkestrel/agent 0.0.40 → 0.0.42

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.
@@ -1,14 +1,14 @@
1
- import { ContractError, INTRINSICS, arrayOf, arrayShape, attempt, booleanShape, boundsOf, canonicalStringify, cloneJSONValue, createContract, describeFaults, errorToMessage, failure, holds, isArray, isBoolean, isError, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isPromiseLike, isRecord, isString, jsonShape, literalShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, optionalOf, optionalShape, parseJSON, parseJSONAs, parseJSONValue, preview, rawShape, recordOf, recordShape, schemaToShape, stringShape, success, unionOf, unionShape } from "@orkestrel/contract";
1
+ import { ContractError, INTRINSICS, admitValue, arrayOf, arrayShape, attempt, booleanShape, boundsOf, canonicalStringify, cloneJSONValue, createContract, describeFaults, errorToMessage, failure, holds, integerShape, isArray, isBoolean, isError, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isPromiseLike, isRecord, isString, jsonShape, literalOf, literalShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, optionalOf, optionalShape, parseJSON, parseJSONAs, parseJSONValue, preview, rawShape, recordOf, recordShape, refuseOptionKeys, schemaToParameters, schemaToShape, stringShape, success, unionOf, unionShape } from "@orkestrel/contract";
2
2
  import { createTokenBudget, createTokenMeter, isBudget, isBudgetAmount, isBudgetError, isTokenUsage } from "@orkestrel/budget";
3
- import { ToolManager, createTool, createToolManager, isToolCall, isToolError } from "@orkestrel/tool";
3
+ import { ToolError, ToolManager, createTool, createToolManager, isToolCall, isToolError } from "@orkestrel/tool";
4
4
  import { createNDJSONParser } from "@orkestrel/ndjson";
5
- import { Timeout, createTimeout } from "@orkestrel/timeout";
5
+ import { createAbort, linkSignal } from "@orkestrel/abort";
6
+ import { MAX_TIMEOUT_MS, Timeout, createTimeout } from "@orkestrel/timeout";
6
7
  import { createDatabase, createMemoryDriver } from "@orkestrel/database";
7
8
  import { Emitter } from "@orkestrel/emitter";
8
9
  import { WorkspaceManager, createFile, isBinary, isTextContent } from "@orkestrel/workspace";
9
10
  import { createQueue } from "@orkestrel/queue";
10
11
  import { createRunner } from "@orkestrel/workflow";
11
- import { createAbort } from "@orkestrel/abort";
12
12
  // src/core/constants.ts
13
13
  /**
14
14
  * Lists the roles any message can play, the built `system` head included, in the order the wire
@@ -725,6 +725,23 @@ function collectToolGroups(messages) {
725
725
  return [...groups, ...orphans];
726
726
  }
727
727
  /**
728
+ * Finds the call that owns a tool message within a collected tool group.
729
+ * @param group - The assistant leader followed by its tool results, as {@link collectToolGroups} returns it
730
+ * @param message - The tool result to pair; distinct leader ids pair by result id when any result has one
731
+ * @returns The call matching the result's call id, or its position when the leader repeats an id or every result lacks an id; undefined when unpaired
732
+ * @example
733
+ * ```ts
734
+ * findToolCall(group, result)?.arguments
735
+ * ```
736
+ */
737
+ function findToolCall(group, message) {
738
+ const [leader, ...results] = group;
739
+ const at = results.findIndex((result) => result.id === message.id);
740
+ if (message.role !== "tool" || at < 0) return void 0;
741
+ const calls = leader?.calls ?? [];
742
+ return !(new Set(calls.map((call) => call.id)).size !== calls.length) && results.some((result) => result.call !== void 0) ? calls.find((call) => call.id === message.call) : calls[at];
743
+ }
744
+ /**
728
745
  * Renders a value as the JSON text `JSON.stringify` produces, or `undefined` when JSON cannot
729
746
  * carry the value.
730
747
  *
@@ -1022,6 +1039,60 @@ var REFUSED_RELAY_STATUS = 422;
1022
1039
  var REFUSED_RELAY_CONTENT_TYPE = "text/plain; charset=utf-8";
1023
1040
  /** Names the System One decision endpoint shared by compatible servers. */
1024
1041
  var SYSTEM_ONE_PATH = "/v1/systemone";
1042
+ /** Lists the members `RelayOptions` declares, frozen — the keys `createRelay` admits. */
1043
+ var RELAY_OPTION_KEYS = Object.freeze([
1044
+ "provider",
1045
+ "authorize",
1046
+ "limit",
1047
+ "system",
1048
+ "tools"
1049
+ ]);
1050
+ /** Lists the members `RelayProviderOptions` declares, frozen — the keys the `RelayProvider` constructor admits. */
1051
+ var RELAY_PROVIDER_KEYS = Object.freeze([
1052
+ "url",
1053
+ "parser",
1054
+ "timeout",
1055
+ "replay",
1056
+ "fetch",
1057
+ "headers"
1058
+ ]);
1059
+ /** Lists the members `RelayStreamOptions` declares, frozen — the keys the `RelayStream` constructor admits. */
1060
+ var RELAY_STREAM_KEYS = Object.freeze([
1061
+ "provider",
1062
+ "request",
1063
+ "signal"
1064
+ ]);
1065
+ /** Lists the members `AgentProviderInput` declares, frozen — the keys the `AgentProvider` constructor admits. */
1066
+ var PROVIDER_INPUT_KEYS = Object.freeze([
1067
+ "url",
1068
+ "path",
1069
+ "split",
1070
+ "strict",
1071
+ "timeout",
1072
+ "replay",
1073
+ "fetch",
1074
+ "headers"
1075
+ ]);
1076
+ /** Lists the members `AgentJudgeInput` declares, frozen — the keys the `AgentJudge` constructor admits. */
1077
+ var JUDGE_INPUT_KEYS = Object.freeze([
1078
+ "url",
1079
+ "path",
1080
+ "model",
1081
+ "batch",
1082
+ "timeout",
1083
+ "fetch",
1084
+ "headers"
1085
+ ]);
1086
+ /** Lists the members `SystemOneJudgeOptions` declares, frozen — the keys the `SystemOneJudge` constructor admits. */
1087
+ var SYSTEM_ONE_OPTION_KEYS = Object.freeze([
1088
+ "url",
1089
+ "model",
1090
+ "timeout",
1091
+ "fetch",
1092
+ "headers"
1093
+ ]);
1094
+ /** Lists the members `ProviderStreamOptions` declares, frozen — the keys the `generate` and `stream` methods of an `AgentProvider` admits. */
1095
+ var STREAM_OPTION_KEYS = Object.freeze(["think", "schema"]);
1025
1096
  // src/core/providers/errors.ts
1026
1097
  /**
1027
1098
  * Reports a provider stream cancelled mid-flight by its bound signal — thrown by the
@@ -2038,6 +2109,7 @@ var RelayStream = class {
2038
2109
  #response;
2039
2110
  #settled = false;
2040
2111
  constructor(options) {
2112
+ refuseOptionKeys(options, RELAY_STREAM_KEYS, "RelayStream", "RelayStreamOptions");
2041
2113
  this.#replay = options.provider.replay ?? "none";
2042
2114
  this.#signal = options.signal;
2043
2115
  this.#listener = this.#abort.bind(this);
@@ -2304,6 +2376,7 @@ var AgentProvider = class {
2304
2376
  #split;
2305
2377
  #strict;
2306
2378
  constructor(input) {
2379
+ refuseOptionKeys(input, PROVIDER_INPUT_KEYS, "AgentProvider", "AgentProviderInput");
2307
2380
  this.#id = crypto.randomUUID();
2308
2381
  this.#replay = input.replay ?? "none";
2309
2382
  this.#url = input.url;
@@ -2351,10 +2424,11 @@ var AgentProvider = class {
2351
2424
  * is malformed or carries an upstream failure, or a strict stream ends without a settled result
2352
2425
  */
2353
2426
  async *stream(messages, signal, tools, options) {
2427
+ refuseOptionKeys(options, STREAM_OPTION_KEYS, "AgentProvider", "ProviderStreamOptions");
2354
2428
  if (signal.aborted) throw new ProviderAbortError({ content: "" });
2355
2429
  const timeout = new Timeout({ ms: this.#timeout });
2356
2430
  timeout.start();
2357
- const combined = AbortSignal.any([timeout.signal, signal]);
2431
+ const combined = linkSignal(timeout.signal, signal);
2358
2432
  try {
2359
2433
  const parser = this.#frame(combined);
2360
2434
  try {
@@ -2506,6 +2580,7 @@ var AgentProvider = class {
2506
2580
  var RelayProvider = class extends AgentProvider {
2507
2581
  #parser;
2508
2582
  constructor(options) {
2583
+ refuseOptionKeys(options, RELAY_PROVIDER_KEYS, "RelayProvider", "RelayProviderOptions");
2509
2584
  const { url, timeout, fetch, headers, replay } = options;
2510
2585
  super({
2511
2586
  url,
@@ -2638,6 +2713,7 @@ var AgentJudge = class {
2638
2713
  #headers;
2639
2714
  #batch;
2640
2715
  constructor(input) {
2716
+ refuseOptionKeys(input, JUDGE_INPUT_KEYS, "AgentJudge", "AgentJudgeInput");
2641
2717
  this.#id = crypto.randomUUID();
2642
2718
  this.#url = input.url;
2643
2719
  this.#path = input.path ?? "";
@@ -2702,7 +2778,7 @@ var AgentJudge = class {
2702
2778
  async #call(request, body, signal, completed) {
2703
2779
  const timeout = new Timeout({ ms: this.#timeout });
2704
2780
  timeout.start();
2705
- const combined = AbortSignal.any([timeout.signal, signal]);
2781
+ const combined = linkSignal(timeout.signal, signal);
2706
2782
  try {
2707
2783
  const headers = await buildProviderHeaders(this.#headers, combined);
2708
2784
  combined.throwIfAborted();
@@ -2803,6 +2879,7 @@ var AgentJudge = class {
2803
2879
  */
2804
2880
  var SystemOneJudge = class extends AgentJudge {
2805
2881
  constructor(options) {
2882
+ refuseOptionKeys(options, SYSTEM_ONE_OPTION_KEYS, "SystemOneJudge", "SystemOneJudgeOptions");
2806
2883
  super({
2807
2884
  ...options,
2808
2885
  path: SYSTEM_ONE_PATH,
@@ -2902,6 +2979,7 @@ var SystemOneJudge = class extends AgentJudge {
2902
2979
  * ```
2903
2980
  */
2904
2981
  function createRelay(options) {
2982
+ refuseOptionKeys(options, RELAY_OPTION_KEYS, "createRelay", "RelayOptions");
2905
2983
  const { provider, authorize, limit } = options;
2906
2984
  const system = { ...options.system };
2907
2985
  const { definitions, accept } = options.tools ?? {};
@@ -3056,6 +3134,43 @@ var DEFAULT_CONVERSATION_KEEP = 0;
3056
3134
  * because it interpolates the per-call provenance `label`).
3057
3135
  */
3058
3136
  var CONVERSATION_RECAP_PREFIX = "[Summary of earlier messages] ";
3137
+ /** Lists the members `ConversationOptions` declares, frozen — the keys the `Conversation` constructor admits. */
3138
+ var CONVERSATION_OPTION_KEYS = Object.freeze([
3139
+ "id",
3140
+ "on",
3141
+ "error",
3142
+ "summarize",
3143
+ "keep",
3144
+ "sections",
3145
+ "cumulative",
3146
+ "snapshot"
3147
+ ]);
3148
+ /** Lists the members `ConversationManagerOptions` declares, frozen — the keys the `ConversationManager` constructor admits. */
3149
+ var CONVERSATION_MANAGER_KEYS = Object.freeze([
3150
+ "summarize",
3151
+ "keep",
3152
+ "sections",
3153
+ "store"
3154
+ ]);
3155
+ /** Lists the members `ConversationInput` declares, frozen — the keys the `add` method of a `ConversationManager` admits. */
3156
+ var CONVERSATION_INPUT_KEYS = Object.freeze([
3157
+ "id",
3158
+ "summarize",
3159
+ "keep",
3160
+ "sections",
3161
+ "cumulative",
3162
+ "on",
3163
+ "error",
3164
+ "snapshot"
3165
+ ]);
3166
+ /** Lists the members `CompactOptions` declares, frozen — the keys the `compact` method of a `Conversation` admits. */
3167
+ var COMPACT_OPTION_KEYS = Object.freeze([
3168
+ "keep",
3169
+ "sections",
3170
+ "signal"
3171
+ ]);
3172
+ /** Lists the members `ConversationReferenceOptions` declares, frozen — the keys the `reference` method of a `Conversation` admits. */
3173
+ var REFERENCE_OPTION_KEYS = Object.freeze(["label", "messages"]);
3059
3174
  // src/core/conversations/errors.ts
3060
3175
  /**
3061
3176
  * Reports a conversation with no {@link ConversationSummaryHandler} to fold its messages with, a
@@ -3081,7 +3196,8 @@ var CONVERSATION_RECAP_PREFIX = "[Summary of earlier messages] ";
3081
3196
  * `'SUMMARY'`. A stored message plays a `ConversationRole`: `add` refuses any other role with
3082
3197
  * `'ROLE'` before it stores any message of the batch, a hydrating snapshot that holds one throws
3083
3198
  * `'ROLE'`, and an agent's selection that holds one becomes a `'ROLE'` fault. `add` refuses an input
3084
- * whose other members fail `isMessageInput` with `'MESSAGE'`, its `context` holding the `faults`,
3199
+ * that is not a plain record, before its role is read, or whose other members fail `isMessageInput`
3200
+ * with `'MESSAGE'`, its `context` holding the `faults`,
3085
3201
  * before it stores any message of the batch. A hydrating snapshot that fails
3086
3202
  * `isConversationSnapshot` or repeats an id, and a store row or written snapshot that does, throw
3087
3203
  * `'SNAPSHOT'`; a judgment the guard admits but JSON cannot carry still throws `'JUDGMENT'`. A
@@ -3089,7 +3205,7 @@ var CONVERSATION_RECAP_PREFIX = "[Summary of earlier messages] ";
3089
3205
  * {@link isConversationError} and branch on `error.code`.
3090
3206
  */
3091
3207
  var ConversationError = class extends Error {
3092
- /** Names the machine-readable condition — `'SUMMARIZER'`: a `compact()` with no summarizer; `'SECTIONS'`: a `sections` cap that is not a positive safe integer, or a cap combined with `cumulative`; `'JUDGMENT'`: a judgment or judge request that is not JSON; `'KEEP'`: a `keep` that is not a nonnegative safe integer; `'SUMMARY'`: a summarizer digest whose trimmed text is empty; `'ROLE'`: a stored or selected message whose role is not a `ConversationRole`; `'MESSAGE'`: a message input whose other members fail `isMessageInput`; `'SNAPSHOT'`: a snapshot that fails `isConversationSnapshot` or repeats an id; `'ID'`: a manager's `add` of an id it already holds. */
3208
+ /** Names the machine-readable condition — `'SUMMARIZER'`: a `compact()` with no summarizer; `'SECTIONS'`: a `sections` cap that is not a positive safe integer, or a cap combined with `cumulative`; `'JUDGMENT'`: a judgment or judge request that is not JSON; `'KEEP'`: a `keep` that is not a nonnegative safe integer; `'SUMMARY'`: a summarizer digest whose trimmed text is empty; `'ROLE'`: a stored or selected message whose role is not a `ConversationRole`; `'MESSAGE'`: a message input that is not a plain record or whose other members fail `isMessageInput`; `'SNAPSHOT'`: a snapshot that fails `isConversationSnapshot` or repeats an id; `'ID'`: a manager's `add` of an id it already holds. */
3093
3209
  code;
3094
3210
  /** Holds the values that locate the failure, such as the `question` id of a malformed question, or `undefined` when none were supplied. */
3095
3211
  context;
@@ -3224,13 +3340,17 @@ function isMessage(value) {
3224
3340
  return checked.success && checked.value;
3225
3341
  }
3226
3342
  /**
3227
- * Checks whether a value is a message input a conversation can store: a string `content`, and `calls`,
3228
- * `call`, `images`, and `thinking` absent or of their declared types.
3343
+ * Checks whether a value is a message input a conversation can store: a `ConversationRole`, a string
3344
+ * `content`, and `calls`, `call`, `images`, and `thinking` absent or of their declared types.
3229
3345
  *
3230
3346
  * @remarks
3231
- * A hand guard, because `add` checks every message: it reads the members once and composes no record
3232
- * guard. The role is `requireRole`'s to refuse, so its text can name the role received. Unknown members
3233
- * are left behind by the store. An unreadable member returns false.
3347
+ * An exact record, because a stored message is one: a value that is not a plain record, such as a
3348
+ * class instance or an object that inherits its `role`, returns false through `recordOf`'s own plain
3349
+ * record check, as does a member `MessageInput` does not declare or a declared optional member holding
3350
+ * `undefined`. Each tool call crosses `isToolCall` of
3351
+ * `@orkestrel/tool`, whose interface admits more members, so the store keeps `id`, `name`, and
3352
+ * `arguments` and leaves the rest. `add` reads the role through `requireRole` first, so its text can
3353
+ * name the role received. An unreadable member returns false.
3234
3354
  *
3235
3355
  * @param value - The unknown input candidate
3236
3356
  * @returns True if the input's members are valid; false otherwise
@@ -3240,14 +3360,19 @@ function isMessage(value) {
3240
3360
  * isMessageInput({ role: 'user' }) // false
3241
3361
  * ```
3242
3362
  */
3243
- function isMessageInput(value) {
3244
- const checked = attempt(() => {
3245
- if (!isRecord(value)) return false;
3246
- const { content, calls, call, images, thinking } = value;
3247
- return isString(content) && (calls === void 0 || arrayOf(isToolCall)(calls)) && (call === void 0 || isString(call)) && (images === void 0 || arrayOf(isString)(images)) && (thinking === void 0 || isString(thinking));
3248
- });
3249
- return checked.success && checked.value;
3250
- }
3363
+ var isMessageInput = recordOf({
3364
+ role: literalOf(CONVERSATION_ROLES),
3365
+ content: isString,
3366
+ calls: arrayOf(isToolCall),
3367
+ call: isString,
3368
+ images: arrayOf(isString),
3369
+ thinking: isString
3370
+ }, [
3371
+ "calls",
3372
+ "call",
3373
+ "images",
3374
+ "thinking"
3375
+ ]);
3251
3376
  /**
3252
3377
  * Checks whether a stored judgment carries a valid question and exactly one answer or refusal.
3253
3378
  *
@@ -3559,14 +3684,17 @@ function requireRole(role) {
3559
3684
  * Returns a message input after checking its role and its members, or throws a coded error.
3560
3685
  *
3561
3686
  * @remarks
3562
- * The role goes first, through {@link requireRole}, so its refusal names what it received. The members
3563
- * cross {@link isMessageInput}, and `audit` runs only after it refused, so a stored message costs one
3564
- * guard read. Tool-call arguments must also be JSON values before a message is stored.
3687
+ * A value that is not a plain record, such as a class instance or an object that inherits its
3688
+ * `role`, refuses first, through `isRecord` of `@orkestrel/contract`, with a text saying so. The role
3689
+ * goes next, through {@link requireRole}, so its refusal names what it received. The members
3690
+ * cross {@link isMessageInput}, an exact record guard, so a member `MessageInput` does not declare or a
3691
+ * declared member holding `undefined` refuses, and `audit` runs only after a refusal. Tool-call
3692
+ * arguments must also be JSON values before a message is stored.
3565
3693
  *
3566
3694
  * @param input - The message input to check
3567
3695
  * @param contract - The message input contract, whose `audit` is read only on a refusal
3568
3696
  * @returns The input, narrowed
3569
- * @throws ConversationError Thrown when the role is not a `ConversationRole` (code `'ROLE'`) or a member fails `isMessageInput` (code `'MESSAGE'`), with the faults under `context.faults`
3697
+ * @throws ConversationError Thrown when the input is not a plain record (code `'MESSAGE'`), when the role is not a `ConversationRole` (code `'ROLE'`), or when a member fails `isMessageInput`, an undeclared member included (code `'MESSAGE'`), with the faults under `context.faults`
3570
3698
  *
3571
3699
  * @example
3572
3700
  * ```ts
@@ -3575,10 +3703,11 @@ function requireRole(role) {
3575
3703
  * ```
3576
3704
  */
3577
3705
  function requireMessageInput(input, contract) {
3578
- requireRole(isRecord(input) ? input.role : void 0);
3706
+ if (!isRecord(input)) throw new ConversationError("MESSAGE", "a message input must be a plain record, an object literal or parsed JSON holding its role and content as its own members, not a class instance or an object that inherits them", { context: { faults: contract.audit(input) } });
3707
+ requireRole(input.role);
3579
3708
  if (isMessageInput(input) && (input.calls === void 0 || input.calls.every((call) => isJSONValue(call.arguments)))) return input;
3580
3709
  const faults = contract.audit(input);
3581
- throw new ConversationError("MESSAGE", `a message input must carry string content, and calls, call, images, and thinking of their declared types\n${describeFaults(faults, contract.schema)}`, { context: { faults } });
3710
+ throw new ConversationError("MESSAGE", `a message input must carry string content, calls, call, images, and thinking of their declared types, and no other member\n${describeFaults(faults, contract.schema)}`, { context: { faults } });
3582
3711
  }
3583
3712
  /**
3584
3713
  * Returns a conversation snapshot after checking its shape, its stored roles, and its ids, or
@@ -3956,6 +4085,7 @@ var Conversation = class {
3956
4085
  #judgments;
3957
4086
  #pending = /* @__PURE__ */ new Set();
3958
4087
  constructor(options) {
4088
+ refuseOptionKeys(options, CONVERSATION_OPTION_KEYS, "Conversation", "ConversationOptions");
3959
4089
  const supplied = options?.snapshot;
3960
4090
  const snapshot = supplied === void 0 ? void 0 : requireConversationSnapshot(supplied, conversationSnapshotContract);
3961
4091
  this.#judgments = new JudgmentManager(snapshot?.judgments);
@@ -4011,6 +4141,7 @@ var Conversation = class {
4011
4141
  return [...this.#sections.map((section) => buildRecapMessage(section)), ...this.#messages.values()];
4012
4142
  }
4013
4143
  async compact(options) {
4144
+ refuseOptionKeys(options, COMPACT_OPTION_KEYS, "Conversation", "CompactOptions");
4014
4145
  const summarize = this.#summarize;
4015
4146
  if (summarize === void 0) throw new ConversationError("SUMMARIZER", "cannot compact a conversation without a summarizer");
4016
4147
  const cap = requireSectionsCap(options?.sections ?? this.#cap);
@@ -4035,6 +4166,7 @@ var Conversation = class {
4035
4166
  return [...this.#sections.flatMap((section) => section.messages), ...this.#messages.values()].filter((message) => message.content.toLowerCase().includes(needle));
4036
4167
  }
4037
4168
  reference(options) {
4169
+ refuseOptionKeys(options, REFERENCE_OPTION_KEYS, "Conversation", "ConversationReferenceOptions");
4038
4170
  const label = options?.label ?? this.#id;
4039
4171
  const messages = options?.messages ?? [];
4040
4172
  return [`[Reference — conversation "${label}" — NOT part of this conversation]`, ...messages.length > 0 ? ["Relevant messages:", ...Array.from(messages, (message) => `- ${message.role}: ${message.content}`)] : []].join("\n");
@@ -4161,6 +4293,7 @@ var ConversationManager = class {
4161
4293
  #sections;
4162
4294
  #store;
4163
4295
  constructor(options) {
4296
+ refuseOptionKeys(options, CONVERSATION_MANAGER_KEYS, "ConversationManager", "ConversationManagerOptions");
4164
4297
  this.#summarize = options?.summarize;
4165
4298
  this.#keep = requireKeep(options?.keep ?? 0);
4166
4299
  this.#sections = options?.sections;
@@ -4179,6 +4312,7 @@ var ConversationManager = class {
4179
4312
  return [...this.#conversations.values()];
4180
4313
  }
4181
4314
  add(input) {
4315
+ refuseOptionKeys(input, CONVERSATION_INPUT_KEYS, "ConversationManager", "ConversationInput");
4182
4316
  const held = input?.id ?? input?.snapshot?.id;
4183
4317
  if (held !== void 0 && this.#conversations.has(held)) throw new ConversationError("ID", `conversation ${preview(held)} is already live; pick another id, or remove it first`, { context: { conversation: held } });
4184
4318
  const sections = input?.sections ?? this.#sections;
@@ -4642,6 +4776,16 @@ function createDatabaseConversationStore(driver = createMemoryDriver()) {
4642
4776
  */
4643
4777
  var WORKSPACE_SECTION_HEADER = "## Workspace";
4644
4778
  /**
4779
+ * Names the section header the loaded skills' bodies render under at the end of the system
4780
+ * message — `'## Loaded skills'`.
4781
+ */
4782
+ var LOADED_SECTION_HEADER = "## Loaded skills";
4783
+ /**
4784
+ * Names the section header the admitted workspace ids render under in the user context message —
4785
+ * `'## Workspaces'`, rendered only while a run can select a workspace.
4786
+ */
4787
+ var WORKSPACE_INDEX_HEADER = "## Workspaces";
4788
+ /**
4645
4789
  * Names the built-in section header a {@link import('./types.js').MemoManagerInterface} renders
4646
4790
  * its index under — `'## Memos'`, the `open` value when no `format.open` overrides it.
4647
4791
  *
@@ -4659,6 +4803,80 @@ var MEMO_SECTION_HEADER = "## Memos";
4659
4803
  * {@link import('./helpers.js').renderIndexEntry}.
4660
4804
  */
4661
4805
  var SKILL_SECTION_HEADER = "## Skills";
4806
+ /**
4807
+ * Lists the members `ScopeInput` declares, frozen — the keys a `Scope` is built from.
4808
+ *
4809
+ * @remarks
4810
+ * The `Scope` constructor passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an
4811
+ * own enumerable member outside it, a misspelled list included, refuses with a `ContractError`
4812
+ * coded `'structure'` instead of building a scope with no constraint.
4813
+ */
4814
+ var SCOPE_KEYS = Object.freeze([
4815
+ "name",
4816
+ "select",
4817
+ "instructions",
4818
+ "skills",
4819
+ "memos",
4820
+ "tools",
4821
+ "files",
4822
+ "workspaces"
4823
+ ]);
4824
+ /**
4825
+ * Lists the members `ScopeFilter` declares, frozen — the keys the `narrow` method of a scope admits.
4826
+ *
4827
+ * @remarks
4828
+ * The `narrow` method passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an own
4829
+ * enumerable member outside it refuses with a `ContractError` coded `'structure'`.
4830
+ */
4831
+ var SCOPE_FILTER_KEYS = Object.freeze([
4832
+ "instructions",
4833
+ "skills",
4834
+ "memos",
4835
+ "tools",
4836
+ "files",
4837
+ "workspaces"
4838
+ ]);
4839
+ /** Lists the members `AgentContextOptions` declares, frozen — the keys the `AgentContext` constructor admits. */
4840
+ var CONTEXT_OPTION_KEYS = Object.freeze([
4841
+ "system",
4842
+ "tools",
4843
+ "instructions",
4844
+ "skills",
4845
+ "memos",
4846
+ "workspaces",
4847
+ "scope",
4848
+ "conversations",
4849
+ "select"
4850
+ ]);
4851
+ /** Lists the members `ContextBuildOptions` declares, frozen — the keys the `build` method of an `AgentContext` admits. */
4852
+ var BUILD_OPTION_KEYS = Object.freeze([
4853
+ "selection",
4854
+ "scope",
4855
+ "disclosure",
4856
+ "switchable"
4857
+ ]);
4858
+ /** Lists the members `InstructionManagerOptions` declares, frozen — the keys the `InstructionManager` constructor admits. */
4859
+ var INSTRUCTION_MANAGER_KEYS = Object.freeze([
4860
+ "on",
4861
+ "error",
4862
+ "format"
4863
+ ]);
4864
+ /** Lists the members `MemoManagerOptions` declares, frozen — the keys the `MemoManager` constructor admits. */
4865
+ var MEMO_MANAGER_KEYS = Object.freeze([
4866
+ "id",
4867
+ "on",
4868
+ "error",
4869
+ "format",
4870
+ "snapshot"
4871
+ ]);
4872
+ /** Lists the members `ScopeManagerOptions` declares, frozen — the keys the `ScopeManager` constructor admits. */
4873
+ var SCOPE_MANAGER_KEYS = Object.freeze(["on", "error"]);
4874
+ /** Lists the members `SkillManagerOptions` declares, frozen — the keys the `SkillManager` constructor admits. */
4875
+ var SKILL_MANAGER_KEYS = Object.freeze([
4876
+ "on",
4877
+ "error",
4878
+ "format"
4879
+ ]);
4662
4880
  // src/core/contexts/errors.ts
4663
4881
  /**
4664
4882
  * Reports a context snapshot that `isMemoSnapshot` refuses, thrown by the construction of a
@@ -4720,132 +4938,84 @@ function isContextError(value) {
4720
4938
  return context === void 0 || isObject(context) || isFunction(context);
4721
4939
  });
4722
4940
  }
4723
- // src/core/contexts/instructions/Instruction.ts
4941
+ // src/core/contexts/shapers.ts
4942
+ /** Describes a stored memo revision exactly. */
4943
+ var memoShape = objectShape({
4944
+ id: stringShape(),
4945
+ name: stringShape(),
4946
+ description: stringShape(),
4947
+ content: stringShape(),
4948
+ time: numberShape(),
4949
+ origin: optionalShape(objectShape({
4950
+ conversation: stringShape(),
4951
+ message: optionalShape(stringShape())
4952
+ }))
4953
+ });
4724
4954
  /**
4725
- * Represents an immutable named directive — an {@link InstructionInterface} assembled once from
4726
- * its input (`name` / `content` and an optional `priority`), the `id` minted at
4727
- * construction. Default: `0` for `priority`.
4955
+ * Describes a stored memo set exactly: an unknown key refuses.
4728
4956
  *
4729
4957
  * @remarks
4730
- * A thin immutable value object (mirroring {@link import('@orkestrel/tool').Tool}): the
4731
- * constructor mints a fresh `id` (`crypto.randomUUID()`), copies the input's `name` /
4732
- * `content`, resolves `priority` to the input's value or `0`, and carries the input's
4733
- * per-item `override` value when supplied; otherwise that property is `undefined`.
4734
- * Never mutated after construction. An
4735
- * {@link import('./InstructionManager.js').InstructionManager} keys it by `name` and
4736
- * renders it (highest `priority` first) under its section header.
4958
+ * `isMemoSnapshot` is the door a hydrate and a store read, and this shape fills a refusal's faults. A
4959
+ * lockstep test holds that `is` implies the guard, and on the snapshot fixtures the converse.
4960
+ */
4961
+ var memoSnapshotShape = objectShape({
4962
+ id: stringShape(),
4963
+ memos: arrayShape(memoShape)
4964
+ });
4965
+ /**
4966
+ * Describes a memo input exactly: the members of a stored revision less the `id` and `time` the
4967
+ * manager mints, each taken from {@link memoShape}.
4737
4968
  *
4738
- * @example
4739
- * ```ts
4740
- * const instruction = new Instruction({ name: 'tone', content: 'Be concise.', priority: 5 })
4741
- * instruction.priority // 5
4742
- * ```
4969
+ * @remarks
4970
+ * An unknown member, a missing required member, and a declared member holding `undefined` refuse, so
4971
+ * a revision `add` stores is one its own snapshot hydrates.
4743
4972
  */
4744
- var Instruction = class {
4745
- id;
4746
- name;
4747
- content;
4748
- priority;
4749
- override;
4750
- constructor(input) {
4751
- this.id = crypto.randomUUID();
4752
- this.name = input.name;
4753
- this.content = input.content;
4754
- this.priority = input.priority ?? 0;
4755
- if (input.override !== void 0) this.override = input.override;
4756
- }
4757
- };
4758
- // src/core/contexts/instructions/InstructionManager.ts
4973
+ var memoInputShape = objectShape({
4974
+ name: memoShape.properties.name,
4975
+ description: memoShape.properties.description,
4976
+ content: memoShape.properties.content,
4977
+ origin: memoShape.properties.origin
4978
+ });
4759
4979
  /**
4760
- * Registers the immutable {@link Instruction} instances a richer context assembles a directives block
4761
- * from — keyed by `name` so adding an instruction whose name is already stored overwrites it,
4762
- * last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`.
4980
+ * Describes an instruction input exactly: a string `name` and `content`, and an optional finite
4981
+ * `priority` and string `override`.
4763
4982
  *
4764
4983
  * @remarks
4765
- * - **Registry.** Instructions live in an insertion-ordered `Map` keyed by `name`;
4766
- * `add` takes one {@link InstructionInput} or a batch, mints each instruction's
4767
- * `id`, and adding an instruction whose name is already stored overwrites it (last write wins).
4768
- * `count` is the map size, `instruction(name)` looks one up, and `instructions()` lists them sorted by
4769
- * descending `priority` (a stable sort, so equal priorities keep insertion order).
4770
- * - **Build contract (the whole format cascade).** `open` is the section header a context
4771
- * renders the instructions under, `render(instruction)` renders one instruction, and
4772
- * `close` is the line after them. Each resolves the cascade most-specific-first: `render`
4773
- * returns the instruction's {@link InstructionInput.override}, else the
4774
- * `InstructionManagerOptions.format` `render`, else its `content`; `open` returns the
4775
- * options `open`, else the built-in header; `close` returns the options `close`, else
4776
- * `undefined`. A context reads the three and frames the section from them (see
4777
- * {@link import('../AgentContext.js').AgentContext}).
4778
- * - **Removal.** `remove` drops one by name, or a batch — `true` only when every supplied
4779
- * name was removed; `clear` empties the registry.
4780
- * - **Observable.** The owned {@link emitter} ({@link InstructionManagerEventMap})
4781
- * carries `add` (the created instruction) / `remove` (the name) / `clear` for
4782
- * fire-and-forget observers. Every event is emitted directly, strictly after the map
4783
- * mutation completes; the emitter isolates a listener throw and routes it to its `error`
4784
- * handler (the `error` option), so a buggy observer can never corrupt a mutation.
4984
+ * An unknown member, a missing required member, and a declared member holding `undefined` refuse.
4985
+ */
4986
+ var instructionInputShape = objectShape({
4987
+ name: stringShape(),
4988
+ content: stringShape(),
4989
+ priority: optionalShape(numberShape()),
4990
+ override: optionalShape(stringShape())
4991
+ });
4992
+ /**
4993
+ * Describes a skill input exactly: a string `name`, `description`, and `content`, optional `tools`
4994
+ * names, and optional `files`.
4785
4995
  *
4786
- * @example
4787
- * ```ts
4788
- * const manager = new InstructionManager()
4789
- * manager.add([
4790
- * { name: 'tone', content: 'Be concise.', priority: 1 },
4791
- * { name: 'safety', content: 'Refuse unsafe requests.', priority: 10 },
4792
- * ])
4793
- * manager.instructions().map((one) => one.name) // ['safety', 'tone'] — highest priority first
4794
- * ```
4996
+ * @remarks
4997
+ * An unknown member, a missing required member, and a declared member holding `undefined` refuse.
4998
+ * Each file is the `FileInput` interface of `@orkestrel/workspace`, which publishes no guard for it,
4999
+ * so the shape admits any defined element and `createFile`, that package's own door, reads it.
4795
5000
  */
4796
- var InstructionManager = class {
4797
- #instructions = /* @__PURE__ */ new Map();
4798
- #emitter;
4799
- #format;
4800
- constructor(options) {
4801
- this.#emitter = new Emitter(options);
4802
- this.#format = options?.format;
4803
- }
4804
- get emitter() {
4805
- return this.#emitter;
4806
- }
4807
- get count() {
4808
- return this.#instructions.size;
4809
- }
4810
- get open() {
4811
- return this.#format?.open ?? "## Instructions";
4812
- }
4813
- get close() {
4814
- return this.#format?.close;
4815
- }
4816
- add(input) {
4817
- if (isArray(input)) return input.map((one) => this.#create(one));
4818
- return this.#create(input);
4819
- }
4820
- instruction(name) {
4821
- return this.#instructions.get(name);
4822
- }
4823
- instructions() {
4824
- return [...this.#instructions.values()].sort((a, b) => b.priority - a.priority);
4825
- }
4826
- render(instruction) {
4827
- return instruction.override ?? this.#format?.render?.(instruction) ?? instruction.content;
4828
- }
4829
- remove(names) {
4830
- if (isArray(names)) return removeEntries(names, (name) => this.#delete(name));
4831
- return this.#delete(names);
4832
- }
4833
- clear() {
4834
- this.#instructions.clear();
4835
- this.#emitter.emit("clear");
4836
- }
4837
- #create(input) {
4838
- const instruction = new Instruction(input);
4839
- this.#instructions.set(instruction.name, instruction);
4840
- this.#emitter.emit("add", instruction);
4841
- return instruction;
4842
- }
4843
- #delete(name) {
4844
- const removed = this.#instructions.delete(name);
4845
- if (removed) this.#emitter.emit("remove", name);
4846
- return removed;
4847
- }
4848
- };
5001
+ var skillInputShape = objectShape({
5002
+ name: stringShape(),
5003
+ description: stringShape(),
5004
+ content: stringShape(),
5005
+ tools: optionalShape(arrayShape(stringShape())),
5006
+ files: optionalShape(arrayShape(rawShape({})))
5007
+ });
5008
+ // src/core/contexts/contracts.ts
5009
+ /** Reads the faults of a refused memo revision. */
5010
+ var memoContract = createContract(memoShape);
5011
+ /** Reads the faults of a refused memo snapshot. */
5012
+ var memoSnapshotContract = createContract(memoSnapshotShape);
5013
+ /** Admits a memo input exactly, and reads the faults of a refused one. */
5014
+ var memoInputContract = createContract(memoInputShape);
5015
+ /** Admits an instruction input exactly, and reads the faults of a refused one. */
5016
+ var instructionInputContract = createContract(instructionInputShape);
5017
+ /** Admits a skill input exactly, and reads the faults of a refused one. */
5018
+ var skillInputContract = createContract(skillInputShape);
4849
5019
  // src/core/contexts/helpers.ts
4850
5020
  /**
4851
5021
  * Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line
@@ -5019,6 +5189,44 @@ function intersectKeys(parent, child) {
5019
5189
  return child.filter((key) => allowed.has(key));
5020
5190
  }
5021
5191
  /**
5192
+ * Intersects two scope filters list by list; an absent side constrains nothing.
5193
+ *
5194
+ * @remarks
5195
+ * Pure, and it can only tighten. Each list of the result is {@link intersectKeys} over the two
5196
+ * sides' lists, each read one time, in the order `instructions`, `skills`, `memos`, `tools`,
5197
+ * `files`, and `workspaces`. A list neither side constrains is omitted, and every returned list is
5198
+ * a fresh copy.
5199
+ * `Scope.narrow`, a run's build, and a ledger's answer-pass scope compose their layers through it.
5200
+ *
5201
+ * @param parent - The outer filter, such as the context scope (`undefined` ⇒ no constraint)
5202
+ * @param child - The inner filter, such as a run scope (`undefined` ⇒ no constraint)
5203
+ * @returns The intersected filter
5204
+ *
5205
+ * @example
5206
+ * ```ts
5207
+ * import { intersectFilters } from '@orkestrel/agent'
5208
+ *
5209
+ * intersectFilters({ tools: ['read', 'write'] }, { tools: ['write', 'admin'], files: [] })
5210
+ * // { tools: ['write'], files: [] }
5211
+ * ```
5212
+ */
5213
+ function intersectFilters(parent, child) {
5214
+ const instructions = intersectKeys(parent?.instructions, child?.instructions);
5215
+ const skills = intersectKeys(parent?.skills, child?.skills);
5216
+ const memos = intersectKeys(parent?.memos, child?.memos);
5217
+ const tools = intersectKeys(parent?.tools, child?.tools);
5218
+ const files = intersectKeys(parent?.files, child?.files);
5219
+ const workspaces = intersectKeys(parent?.workspaces, child?.workspaces);
5220
+ return {
5221
+ ...instructions === void 0 ? {} : { instructions },
5222
+ ...skills === void 0 ? {} : { skills },
5223
+ ...memos === void 0 ? {} : { memos },
5224
+ ...tools === void 0 ? {} : { tools },
5225
+ ...files === void 0 ? {} : { files },
5226
+ ...workspaces === void 0 ? {} : { workspaces }
5227
+ };
5228
+ }
5229
+ /**
5022
5230
  * Renders one index line for a memo or a skill — `- name: description`, the built-in `render` of
5023
5231
  * the memo and skill managers.
5024
5232
  *
@@ -5038,45 +5246,227 @@ function intersectKeys(parent, child) {
5038
5246
  * ```
5039
5247
  */
5040
5248
  function renderIndexEntry(entry) {
5041
- return `- ${entry.name}: ${entry.description}`.replace(/[\n\v\f\r\u0085\u2028\u2029]+/g, " ");
5249
+ return renderIndexLine(`${entry.name}: ${entry.description}`);
5042
5250
  }
5043
- // src/core/contexts/shapers.ts
5044
- /** Describes a stored memo revision exactly. */
5045
- var memoShape = objectShape({
5046
- id: stringShape(),
5047
- name: stringShape(),
5048
- description: stringShape(),
5049
- content: stringShape(),
5050
- time: numberShape(),
5051
- origin: optionalShape(objectShape({
5052
- conversation: stringShape(),
5053
- message: optionalShape(stringShape())
5054
- }))
5055
- });
5056
5251
  /**
5057
- * Describes a stored memo set exactly: an unknown key refuses.
5252
+ * Renders one index line from its text as `- text`, with each run of line-break code points as one
5253
+ * space.
5058
5254
  *
5059
5255
  * @remarks
5060
- * `isMemoSnapshot` is the door a hydrate and a store read, and this shape fills a refusal's faults. A
5061
- * lockstep test holds that `is` implies the guard, and on the snapshot fixtures the converse.
5062
- */
5063
- var memoSnapshotShape = objectShape({
5064
- id: stringShape(),
5065
- memos: arrayShape(memoShape)
5066
- });
5067
- // src/core/contexts/contracts.ts
5068
- /** Reads the faults of a refused memo revision. */
5069
- var memoContract = createContract(memoShape);
5070
- /** Reads the faults of a refused memo snapshot. */
5071
- var memoSnapshotContract = createContract(memoSnapshotShape);
5072
- // src/core/contexts/validators.ts
5073
- /**
5074
- * Checks whether a value is a memo's origin: a record with a string `conversation` and an optional
5075
- * string `message`.
5256
+ * Pure and total. The memo and skill index lines and the workspace index lines render through it,
5257
+ * so text in an index never opens another line or heading.
5076
5258
  *
5077
- * @remarks
5078
- * The guard is exact: an unknown member and an own `undefined` `message` return false. Malformed and
5079
- * unreadable inputs return false.
5259
+ * @param text - The line's text
5260
+ * @returns The index line
5261
+ *
5262
+ * @example
5263
+ * ```ts
5264
+ * import { renderIndexLine } from '@orkestrel/agent'
5265
+ *
5266
+ * renderIndexLine('orders') // '- orders'
5267
+ * ```
5268
+ */
5269
+ function renderIndexLine(text) {
5270
+ return `- ${text}`.replace(/[\n\v\f\r\u0085\u2028\u2029]+/g, " ");
5271
+ }
5272
+ /**
5273
+ * Renders one loaded skill's body: `### name`, a blank line, then its content.
5274
+ *
5275
+ * @remarks
5276
+ * Pure and total. The context build renders each shown skill through it under the loaded skills
5277
+ * header, last in the system message.
5278
+ *
5279
+ * @param skill - The skill whose name and content the body shows
5280
+ * @returns The body
5281
+ *
5282
+ * @example
5283
+ * ```ts
5284
+ * import { renderSkillBody } from '@orkestrel/agent'
5285
+ *
5286
+ * renderSkillBody({ name: 'refunds', content: 'Check the order first.' })
5287
+ * // '### refunds\n\nCheck the order first.'
5288
+ * ```
5289
+ */
5290
+ function renderSkillBody(skill) {
5291
+ return `### ${skill.name}\n\n${skill.content}`;
5292
+ }
5293
+ /**
5294
+ * Checks a stored record's input against its exact contract, and throws a `ContractError` coded
5295
+ * `'structure'` when it fails.
5296
+ *
5297
+ * @remarks
5298
+ * The input must pass the contract's `is` guard: a missing required member, a member the input type
5299
+ * does not declare, a declared member holding `undefined`, and a member of another type each refuse,
5300
+ * so nothing a refused input carries is stored. A class instance refuses, and the contract reads own
5301
+ * enumerable string keys alone, as every option door does. The contract's `audit` runs only after a refusal, and
5302
+ * the message names the owner, the input type, and every fault with the members to send. The
5303
+ * `context` holds the first fault's `path` and the input type as its `shape`.
5304
+ *
5305
+ * @param input - The input to check
5306
+ * @param contract - The input's compiled contract
5307
+ * @param owner - The entity named at the head of the refusal
5308
+ * @param shape - The input type named in the refusal and its `context`
5309
+ * @throws ContractError Thrown when the input fails the contract (code `'structure'`)
5310
+ *
5311
+ * @example
5312
+ * ```ts
5313
+ * import { memoInputContract, requireRecordInput } from '@orkestrel/agent'
5314
+ *
5315
+ * requireRecordInput({ name: 'tone', description: 'Prefers short replies.', content: 'Answer briefly.' }, memoInputContract, 'MemoManager', 'MemoInput') // returns
5316
+ * requireRecordInput({ name: 'tone', description: undefined, content: 'Answer briefly.' }, memoInputContract, 'MemoManager', 'MemoInput') // throws ContractError ('structure')
5317
+ * ```
5318
+ */
5319
+ function requireRecordInput(input, contract, owner, shape) {
5320
+ if (contract.is(input)) return;
5321
+ const faults = contract.audit(input);
5322
+ throw new ContractError(`${owner}: a ${shape} must hold each required member and no other, every member of its declared type\n${describeFaults(faults, contract.schema)}`, {
5323
+ code: "structure",
5324
+ context: {
5325
+ path: faults[0]?.path ?? [],
5326
+ shape
5327
+ }
5328
+ });
5329
+ }
5330
+ // src/core/contexts/instructions/Instruction.ts
5331
+ /**
5332
+ * Represents an immutable named directive — an {@link InstructionInterface} assembled once from
5333
+ * its input (`name` / `content` and an optional `priority`), the `id` minted at
5334
+ * construction. Default: `0` for `priority`.
5335
+ *
5336
+ * @remarks
5337
+ * A thin immutable value object (mirroring {@link import('@orkestrel/tool').Tool}): the
5338
+ * constructor mints a fresh `id` (`crypto.randomUUID()`), copies the input's `name` /
5339
+ * `content`, resolves `priority` to the input's value or `0`, and carries the input's
5340
+ * per-item `override` value when supplied; otherwise the instance owns no `override` member, so
5341
+ * its own keys and a JSON copy carry no member holding `undefined`. The input meets its exact
5342
+ * contract first, so a missing required member, an undeclared member, and a declared member holding
5343
+ * `undefined` refuse with a `ContractError` coded `'structure'`. Never mutated after construction. An
5344
+ * {@link import('./InstructionManager.js').InstructionManager} keys it by `name` and
5345
+ * renders it (highest `priority` first) under its section header.
5346
+ *
5347
+ * @example
5348
+ * ```ts
5349
+ * const instruction = new Instruction({ name: 'tone', content: 'Be concise.', priority: 5 })
5350
+ * instruction.priority // 5
5351
+ * ```
5352
+ */
5353
+ var Instruction = class {
5354
+ id;
5355
+ name;
5356
+ content;
5357
+ priority;
5358
+ constructor(input) {
5359
+ requireRecordInput(input, instructionInputContract, "Instruction", "InstructionInput");
5360
+ this.id = crypto.randomUUID();
5361
+ this.name = input.name;
5362
+ this.content = input.content;
5363
+ this.priority = input.priority ?? 0;
5364
+ if (input.override !== void 0) this.override = input.override;
5365
+ }
5366
+ };
5367
+ // src/core/contexts/instructions/InstructionManager.ts
5368
+ /**
5369
+ * Registers the immutable {@link Instruction} instances a richer context assembles a directives block
5370
+ * from — keyed by `name` so adding an instruction whose name is already stored overwrites it,
5371
+ * last write wins, and listed by descending `priority`, carrying the `open` / `render` / `close` build contract and an observable `emitter`.
5372
+ *
5373
+ * @remarks
5374
+ * - **Registry.** Instructions live in an insertion-ordered `Map` keyed by `name`;
5375
+ * `add` takes one {@link InstructionInput} or a batch, mints each instruction's
5376
+ * `id`, and adding an instruction whose name is already stored overwrites it (last write wins).
5377
+ * `count` is the map size, `instruction(name)` looks one up, and `instructions()` lists them sorted by
5378
+ * descending `priority` (a stable sort, so equal priorities keep insertion order).
5379
+ * - **Build contract (the whole format cascade).** `open` is the section header a context
5380
+ * renders the instructions under, `render(instruction)` renders one instruction, and
5381
+ * `close` is the line after them. Each resolves the cascade most-specific-first: `render`
5382
+ * returns the instruction's {@link InstructionInput.override}, else the
5383
+ * `InstructionManagerOptions.format` `render`, else its `content`; `open` returns the
5384
+ * options `open`, else the built-in header; `close` returns the options `close`, else
5385
+ * `undefined`. A context reads the three and frames the section from them (see
5386
+ * {@link import('../AgentContext.js').AgentContext}).
5387
+ * - **Removal.** `remove` drops one by name, or a batch — `true` only when every supplied
5388
+ * name was removed; `clear` empties the registry.
5389
+ * - **Observable.** The owned {@link emitter} ({@link InstructionManagerEventMap})
5390
+ * carries `add` (the created instruction) / `remove` (the name) / `clear` for
5391
+ * fire-and-forget observers. Every event is emitted directly, strictly after the map
5392
+ * mutation completes; the emitter isolates a listener throw and routes it to its `error`
5393
+ * handler (the `error` option), so a buggy observer can never corrupt a mutation.
5394
+ *
5395
+ * @example
5396
+ * ```ts
5397
+ * const manager = new InstructionManager()
5398
+ * manager.add([
5399
+ * { name: 'tone', content: 'Be concise.', priority: 1 },
5400
+ * { name: 'safety', content: 'Refuse unsafe requests.', priority: 10 },
5401
+ * ])
5402
+ * manager.instructions().map((one) => one.name) // ['safety', 'tone'] — highest priority first
5403
+ * ```
5404
+ */
5405
+ var InstructionManager = class {
5406
+ #instructions = /* @__PURE__ */ new Map();
5407
+ #emitter;
5408
+ #format;
5409
+ constructor(options) {
5410
+ refuseOptionKeys(options, INSTRUCTION_MANAGER_KEYS, "InstructionManager", "InstructionManagerOptions");
5411
+ this.#emitter = new Emitter(options);
5412
+ this.#format = options?.format;
5413
+ }
5414
+ get emitter() {
5415
+ return this.#emitter;
5416
+ }
5417
+ get count() {
5418
+ return this.#instructions.size;
5419
+ }
5420
+ get open() {
5421
+ return this.#format?.open ?? "## Instructions";
5422
+ }
5423
+ get close() {
5424
+ return this.#format?.close;
5425
+ }
5426
+ add(input) {
5427
+ if (isArray(input)) {
5428
+ input.forEach((one) => requireRecordInput(one, instructionInputContract, "Instruction", "InstructionInput"));
5429
+ return input.map((one) => this.#create(one));
5430
+ }
5431
+ return this.#create(input);
5432
+ }
5433
+ instruction(name) {
5434
+ return this.#instructions.get(name);
5435
+ }
5436
+ instructions() {
5437
+ return [...this.#instructions.values()].sort((a, b) => b.priority - a.priority);
5438
+ }
5439
+ render(instruction) {
5440
+ return instruction.override ?? this.#format?.render?.(instruction) ?? instruction.content;
5441
+ }
5442
+ remove(names) {
5443
+ if (isArray(names)) return removeEntries(names, (name) => this.#delete(name));
5444
+ return this.#delete(names);
5445
+ }
5446
+ clear() {
5447
+ this.#instructions.clear();
5448
+ this.#emitter.emit("clear");
5449
+ }
5450
+ #create(input) {
5451
+ const instruction = new Instruction(input);
5452
+ this.#instructions.set(instruction.name, instruction);
5453
+ this.#emitter.emit("add", instruction);
5454
+ return instruction;
5455
+ }
5456
+ #delete(name) {
5457
+ const removed = this.#instructions.delete(name);
5458
+ if (removed) this.#emitter.emit("remove", name);
5459
+ return removed;
5460
+ }
5461
+ };
5462
+ // src/core/contexts/validators.ts
5463
+ /**
5464
+ * Checks whether a value is a memo's origin: a record with a string `conversation` and an optional
5465
+ * string `message`.
5466
+ *
5467
+ * @remarks
5468
+ * The guard is exact: an unknown member and an own `undefined` `message` return false. Malformed and
5469
+ * unreadable inputs return false.
5080
5470
  *
5081
5471
  * @param value - The value to test
5082
5472
  * @returns True if `value` has the shape of a {@link MemoOrigin}; false otherwise
@@ -5149,6 +5539,35 @@ function isMemoSnapshot(value) {
5149
5539
  return isString(id) && arrayOf(isMemo)(memos);
5150
5540
  });
5151
5541
  }
5542
+ /**
5543
+ * Checks whether a value implements `ScopeInterface`; total, each member read one time, any
5544
+ * implementation admitted.
5545
+ *
5546
+ * @remarks
5547
+ * A scope is a string `id` and `name`, each of `instructions`, `skills`, `memos`, `tools`, `files`,
5548
+ * and `workspaces` absent or a dense array of strings, `select` absent or a function, and a `narrow`
5549
+ * function. The guard reads each of those members one time and never calls a method. It admits
5550
+ * unknown members, a class instance, and a transparent proxy, and returns false for a throwing
5551
+ * getter, a revoked proxy, and any other malformed input.
5552
+ *
5553
+ * @param value - The value to test
5554
+ * @returns True if `value` carries the members of a {@link ScopeInterface}; false otherwise
5555
+ *
5556
+ * @example
5557
+ * ```ts
5558
+ * import { createScope, isScope } from '@orkestrel/agent'
5559
+ *
5560
+ * isScope(createScope({ name: 'reader', tools: ['search'] })) // true
5561
+ * isScope({ id: 's1', name: 'reader' }) // false
5562
+ * ```
5563
+ */
5564
+ function isScope(value) {
5565
+ return holds(() => {
5566
+ if (!isObject(value)) return false;
5567
+ const list = optionalOf(arrayOf(isString));
5568
+ return isString(Reflect.get(value, "id")) && isString(Reflect.get(value, "name")) && list(Reflect.get(value, "instructions")) && list(Reflect.get(value, "skills")) && list(Reflect.get(value, "memos")) && list(Reflect.get(value, "tools")) && list(Reflect.get(value, "files")) && list(Reflect.get(value, "workspaces")) && optionalOf(isFunction)(Reflect.get(value, "select")) && isFunction(Reflect.get(value, "narrow"));
5569
+ });
5570
+ }
5152
5571
  // src/core/contexts/memos/MemoManager.ts
5153
5572
  /**
5154
5573
  * Registers the revisions of a memo set — durable facts keyed by `name`, where a same-name `add`
@@ -5196,6 +5615,7 @@ var MemoManager = class {
5196
5615
  * @throws {ContextError} Thrown when the `snapshot` option cannot be copied through JSON or its copy is not a memo snapshot (code `'SNAPSHOT'`); nothing is seated and nothing is emitted
5197
5616
  */
5198
5617
  constructor(options) {
5618
+ refuseOptionKeys(options, MEMO_MANAGER_KEYS, "MemoManager", "MemoManagerOptions");
5199
5619
  const supplied = options?.snapshot;
5200
5620
  const owned = supplied === void 0 ? void 0 : copyJSON(supplied);
5201
5621
  const snapshot = isMemoSnapshot(owned) ? owned : void 0;
@@ -5224,6 +5644,7 @@ var MemoManager = class {
5224
5644
  return this.#format?.close;
5225
5645
  }
5226
5646
  add(input) {
5647
+ (isArray(input) ? input : [input]).forEach((one) => requireRecordInput(one, memoInputContract, "MemoManager", "MemoInput"));
5227
5648
  if (isArray(input)) return input.map((one) => this.#append(one));
5228
5649
  return this.#append(input);
5229
5650
  }
@@ -5282,9 +5703,9 @@ var MemoManager = class {
5282
5703
  // src/core/contexts/scopes/Scope.ts
5283
5704
  /**
5284
5705
  * Represents a named, immutable filter over a richer context's items — an optional allow-list per
5285
- * category (`instructions` / `skills` / `memos` / `tools` / `files`), each keyed by that category's
5286
- * identity (an instruction's, a skill's, a memo's, or a tool's `name`, a workspace file's `path`)
5287
- * and read as an allow-list:
5706
+ * category (`instructions` / `skills` / `memos` / `tools` / `files` / `workspaces`), each keyed by
5707
+ * that category's identity (an instruction's, a skill's, a memo's, or a tool's `name`, a workspace
5708
+ * file's `path`, a workspace's `id`) and read as an allow-list:
5288
5709
  * `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed
5289
5710
  * keys alone. `narrow` composes a tighter child by set intersection.
5290
5711
  *
@@ -5302,6 +5723,10 @@ var MemoManager = class {
5302
5723
  * `undefined` with a list yields the list, and `undefined` with `undefined` stays
5303
5724
  * `undefined`. Narrowing can only tighten, never widen — a key excluded by a parent
5304
5725
  * can never be re-admitted by a child. The child keeps this scope's `name` and `select` handler.
5726
+ * - **Exact.** The constructor refuses an own enumerable member of its input outside
5727
+ * `SCOPE_KEYS`, and `narrow` one of its filter outside `SCOPE_FILTER_KEYS`, with a
5728
+ * `ContractError` coded `'structure'`, so a misspelled list never builds an open scope. A
5729
+ * declared member holding `undefined` reads as omitted.
5305
5730
  *
5306
5731
  * @example
5307
5732
  * ```ts
@@ -5321,8 +5746,10 @@ var Scope = class Scope {
5321
5746
  memos;
5322
5747
  tools;
5323
5748
  files;
5749
+ workspaces;
5324
5750
  select;
5325
5751
  constructor(input) {
5752
+ refuseOptionKeys(input, SCOPE_KEYS, "Scope", "ScopeInput");
5326
5753
  this.name = input.name;
5327
5754
  if (input.select !== void 0) this.select = input.select;
5328
5755
  if (input.instructions !== void 0) this.instructions = [...input.instructions];
@@ -5330,21 +5757,14 @@ var Scope = class Scope {
5330
5757
  if (input.memos !== void 0) this.memos = [...input.memos];
5331
5758
  if (input.tools !== void 0) this.tools = [...input.tools];
5332
5759
  if (input.files !== void 0) this.files = [...input.files];
5760
+ if (input.workspaces !== void 0) this.workspaces = [...input.workspaces];
5333
5761
  }
5334
5762
  narrow(config) {
5335
- const instructions = intersectKeys(this.instructions, config.instructions);
5336
- const skills = intersectKeys(this.skills, config.skills);
5337
- const memos = intersectKeys(this.memos, config.memos);
5338
- const tools = intersectKeys(this.tools, config.tools);
5339
- const files = intersectKeys(this.files, config.files);
5763
+ refuseOptionKeys(config, SCOPE_FILTER_KEYS, "Scope", "ScopeFilter");
5340
5764
  return new Scope({
5341
5765
  name: this.name,
5342
5766
  ...this.select === void 0 ? {} : { select: this.select },
5343
- ...instructions === void 0 ? {} : { instructions },
5344
- ...skills === void 0 ? {} : { skills },
5345
- ...memos === void 0 ? {} : { memos },
5346
- ...tools === void 0 ? {} : { tools },
5347
- ...files === void 0 ? {} : { files }
5767
+ ...intersectFilters(this, config)
5348
5768
  });
5349
5769
  }
5350
5770
  };
@@ -5381,6 +5801,7 @@ var ScopeManager = class {
5381
5801
  #scopes = /* @__PURE__ */ new Map();
5382
5802
  #emitter;
5383
5803
  constructor(options) {
5804
+ refuseOptionKeys(options, SCOPE_MANAGER_KEYS, "ScopeManager", "ScopeManagerOptions");
5384
5805
  this.#emitter = new Emitter(options);
5385
5806
  }
5386
5807
  get emitter() {
@@ -5454,6 +5875,7 @@ var SkillManager = class {
5454
5875
  #emitter;
5455
5876
  #format;
5456
5877
  constructor(options) {
5878
+ refuseOptionKeys(options, SKILL_MANAGER_KEYS, "SkillManager", "SkillManagerOptions");
5457
5879
  this.#emitter = new Emitter(options);
5458
5880
  this.#format = options?.format;
5459
5881
  }
@@ -5470,8 +5892,12 @@ var SkillManager = class {
5470
5892
  return this.#format?.close;
5471
5893
  }
5472
5894
  add(input) {
5473
- if (isArray(input)) return input.map((one) => this.#create(one));
5474
- return this.#create(input);
5895
+ if (isArray(input)) {
5896
+ const skills = input.map((one) => this.#mint(one));
5897
+ skills.forEach((skill) => this.#store(skill));
5898
+ return skills;
5899
+ }
5900
+ return this.#store(this.#mint(input));
5475
5901
  }
5476
5902
  skill(name) {
5477
5903
  return this.#skills.get(name);
@@ -5490,14 +5916,28 @@ var SkillManager = class {
5490
5916
  this.#skills.clear();
5491
5917
  this.#emitter.emit("clear");
5492
5918
  }
5493
- #create(input) {
5494
- const skill = {
5919
+ #mint(input) {
5920
+ const given = isRecord(input) ? input.tools : void 0;
5921
+ const tools = isArray(given) ? Array.from(given) : given;
5922
+ if (tools !== void 0 && !(isArray(tools) && tools.every(isString))) throw new ContractError("SkillManager: tools must be an array of tool names", {
5923
+ code: "placement",
5924
+ context: {
5925
+ path: ["input", "tools"],
5926
+ limit: "readonly string[]",
5927
+ received: preview(given)
5928
+ }
5929
+ });
5930
+ requireRecordInput(input, skillInputContract, "SkillManager", "SkillInput");
5931
+ return {
5495
5932
  id: crypto.randomUUID(),
5496
5933
  name: input.name,
5497
5934
  description: input.description,
5498
5935
  content: input.content,
5499
- files: (input.files ?? []).map((file) => createFile(file))
5936
+ files: (input.files ?? []).map((file) => createFile(file)),
5937
+ tools: tools === void 0 ? [] : tools
5500
5938
  };
5939
+ }
5940
+ #store(skill) {
5501
5941
  this.#skills.set(skill.name, skill);
5502
5942
  this.#emitter.emit("add", skill);
5503
5943
  return skill;
@@ -5694,8 +6134,9 @@ var DatabaseMemoStore = class {
5694
6134
  * {@link ConversationManagerInterface} message source whose active conversation is `messages`, the
5695
6135
  * {@link ToolManagerInterface} registry, and an active {@link ScopeInterface} changed through
5696
6136
  * {@link AgentContextInterface.apply}. `build()` folds the system prompt, the scoped instructions,
5697
- * and the skills index into one system message, the memos index and the active workspace's text into
5698
- * one `user` context message after it, then the conversation, and never reads `tools`.
6137
+ * the skills index, and the shown skills' bodies into one system message, the memos index and the
6138
+ * rendered workspace's text into one `user` context message after it, then the conversation, and
6139
+ * never reads `tools`.
5699
6140
  *
5700
6141
  * @remarks
5701
6142
  * - **Composition.** `system` is the optional system prompt; `instructions` / `skills` / `memos` /
@@ -5714,40 +6155,43 @@ var DatabaseMemoStore = class {
5714
6155
  * reference, no duplication), and `build()` with no selection folds that conversation's `view()`
5715
6156
  * (its per-section summaries + live tail) as the authoritative message inclusion — the scope does
5716
6157
  * not filter the conversation (it owns inclusion through compaction; scope filters only
5717
- * instructions / skills / memos / tools / workspace files). An agent run binds a conversation at
6158
+ * instructions / skills / memos / tools / workspace files / workspaces). An agent run binds a conversation at
5718
6159
  * its call, the active one unless the run names another, and builds through a selection over that
5719
6160
  * conversation, so `conversations.switch(id)` sets the next run's default at any moment and never
5720
6161
  * moves a live run; `select(conversation, request, signal)` checks the conversation it is given.
5721
6162
  * - **`build()` — the scoped assembly + the format cascade.** It folds, in order,
5722
6163
  * the system prompt, the scope-filtered instructions (a block: the section's `open` text,
5723
6164
  * each item's rendering, then any `close` text), then the scope-filtered skills index (a block
5724
- * whose entries join with a single newline) into one leading `system` message (prepended only
5725
- * when at least one part exists), then the scope-filtered memos index (the same block) and the
5726
- * active workspace's text files into one `user` context message (present only when the memos or
5727
- * workspace section renders), then
6165
+ * whose entries join with a single newline), then the shown skills' bodies, into one leading
6166
+ * `system` message (prepended only when at least one part exists), then the scope-filtered memos
6167
+ * index (the same block), the listed workspace ids, and the rendered workspace's text files into
6168
+ * one `user` context message (present only when one of those sections renders), then
5728
6169
  * appends the active conversation's `view()` (the conversation owns message inclusion through
5729
6170
  * compaction — the scope does not filter the conversation). The instruction manager resolves
5730
6171
  * each `open` / item / `close` most-specific-first: `open` = manager-options-override >
5731
6172
  * built-in; per item = item-override > manager-options-override > built-in; `close` =
5732
6173
  * manager-options-override (no built-in ⇒ no closing line when unset) (see
5733
6174
  * {@link AgentContextInterface.build}). With no override set, each section is its built-in
5734
- * header + items, no closing line. The active workspace's scoped-in image files' `base64` payload is attached to
6175
+ * header + items, no closing line. The rendered workspace's scoped-in image files' `base64` payload is attached to
5735
6176
  * the last user message (a vision provider reads images off a user turn); when no user message
5736
6177
  * exists the attachment is skipped. Built fresh each call (recomputed, never cached), so it
5737
- * always reflects the current managers / messages / scope / active workspace; it never mutates a
6178
+ * always reflects the current managers / messages / scope / workspaces; it never mutates a
5738
6179
  * manager or the stored messages. `build(selection)` adds at most one `system` message of its own
5739
6180
  * and reads the selection's messages as conversation parts without a role check; the select path
5740
6181
  * refuses a selected `system` role as a `'ROLE'` fault over `view()`; a host's direct
5741
6182
  * `build(selection)` is host-trusted, and a conversation a host implements itself whose `view()`
5742
6183
  * holds a `system` message is read as host-trusted too.
5743
- * - **The active workspace, rendered by carrier — the sole document/image context.**
5744
- * `workspaces.active` (when set) has its {@link import('@orkestrel/workspace').FileInterface} values scope-filtered by `scope.files`,
6184
+ * - **The rendered workspace, by carrier — the sole document/image context.**
6185
+ * The rendered workspace has its {@link import('@orkestrel/workspace').FileInterface} values scope-filtered by `scope.files`,
5745
6186
  * then split: text files fold into a dedicated `## Workspace` section (fenced reference blocks)
5746
6187
  * in the context message — a `user` message with a minted id, never stored — and image files'
5747
6188
  * `base64` payload attaches to the last user message of the conversation, never to the context
5748
6189
  * message. The `system` message holds host-authored text alone: the system prompt, the
5749
- * instructions, and the skills index. Active-only — never the other registered workspaces; with no
5750
- * active workspace nothing renders for workspaces. `build()` owns this render (a `Workspace` /
6190
+ * instructions, the skills index, and last the bodies of the skills `options.disclosure` shows.
6191
+ * One workspace renders: the one `options.disclosure` selects, else the active one, and only
6192
+ * while the scope's `workspaces` list admits it; with neither, nothing renders for workspaces.
6193
+ * `options.switchable` adds the admitted workspace ids to the context message, after the memos
6194
+ * index. `build()` never moves the active workspace, and it owns this render (a `Workspace` /
5751
6195
  * `WorkspaceManager` stays file-focused).
5752
6196
  * - **Tools are structural, not in the prompt.** The registry is advertised to the provider
5753
6197
  * through `tools.definitions()` (scope-filtered by the loop), never serialized into the
@@ -5774,6 +6218,7 @@ var AgentContext = class {
5774
6218
  #select;
5775
6219
  #scope;
5776
6220
  constructor(options) {
6221
+ refuseOptionKeys(options, CONTEXT_OPTION_KEYS, "AgentContext", "AgentContextOptions");
5777
6222
  this.#system = options?.system;
5778
6223
  this.#instructions = options?.instructions ?? new InstructionManager();
5779
6224
  this.#skills = options?.skills ?? new SkillManager();
@@ -5815,31 +6260,46 @@ var AgentContext = class {
5815
6260
  apply(scope) {
5816
6261
  this.#scope = scope;
5817
6262
  }
5818
- select(conversation, request, signal) {
5819
- const handler = this.#scope?.select ?? this.#select;
6263
+ select(conversation, request, signal, scope) {
6264
+ const handler = scope?.select ?? this.#scope?.select ?? this.#select;
5820
6265
  if (handler === void 0) return void 0;
5821
6266
  return this.#check(handler, conversation, request, signal);
5822
6267
  }
5823
- build(selection) {
5824
- const scope = this.#scope;
6268
+ build(options) {
6269
+ refuseOptionKeys(options, BUILD_OPTION_KEYS, "AgentContext", "ContextBuildOptions");
6270
+ const scope = intersectFilters(this.#scope, options?.scope);
5825
6271
  const parts = [];
5826
6272
  if (this.#system !== void 0) parts.push(this.#system);
5827
- const instructions = filterAllowList(scope?.instructions, this.#instructions.instructions(), (one) => one.name);
6273
+ const instructions = filterAllowList(scope.instructions, this.#instructions.instructions(), (one) => one.name);
5828
6274
  const instructed = renderSection(this.#instructions.open, instructions, (one) => this.#instructions.render(one), this.#instructions.close);
5829
6275
  if (instructed !== void 0) parts.push(instructed);
5830
- const skills = filterAllowList(scope?.skills, this.#skills.skills(), (one) => one.name);
6276
+ const skills = filterAllowList(scope.skills, this.#skills.skills(), (one) => one.name);
5831
6277
  const indexed = renderSection(this.#skills.open, skills.length === 0 ? [] : [skills.map((one) => this.#skills.render(one)).join("\n")], (block) => block, this.#skills.close);
5832
6278
  if (indexed !== void 0) parts.push(indexed);
5833
- const files = filterAllowList(scope?.files, this.#workspaces.active?.files() ?? [], (one) => one.path);
6279
+ const admitted = new Map(skills.map((one) => [one.name, one]));
6280
+ const bodies = renderSection(LOADED_SECTION_HEADER, [...new Set(options?.disclosure?.skills ?? [])].flatMap((name) => {
6281
+ const skill = admitted.get(name);
6282
+ return skill === void 0 || skill.content.trim() === "" ? [] : [skill];
6283
+ }), renderSkillBody, void 0);
6284
+ if (bodies !== void 0) parts.push(bodies);
6285
+ const selected = options?.disclosure?.workspace;
6286
+ const workspace = selected === void 0 ? this.#workspaces.active : this.#workspaces.workspace(selected);
6287
+ const shown = filterAllowList(scope.workspaces, workspace === void 0 ? [] : [workspace], (one) => one.id);
6288
+ const files = filterAllowList(scope.files, shown.flatMap((one) => one.files()), (one) => one.path);
5834
6289
  const documented = renderSection(WORKSPACE_SECTION_HEADER, files.flatMap((file) => isTextContent(file.content) ? [{
5835
6290
  path: file.path,
5836
6291
  language: file.content.language,
5837
6292
  text: file.content.text
5838
6293
  }] : []), (file) => renderFencedFile(file.path, file.language, file.text), void 0);
5839
- const memos = filterAllowList(scope?.memos, this.#memos.memos(), (one) => one.name);
6294
+ const memos = filterAllowList(scope.memos, this.#memos.memos(), (one) => one.name);
5840
6295
  const remembered = renderSection(this.#memos.open, memos.length === 0 ? [] : [memos.map((one) => this.#memos.render(one)).join("\n")], (block) => block, this.#memos.close);
5841
- const tail = attachUserImages(selection?.messages ?? this.#ensureConversation().view(), collectImageData(files));
5842
- const slots = [remembered, documented].filter((slot) => slot !== void 0);
6296
+ const tail = attachUserImages(options?.selection?.messages ?? this.#ensureConversation().view(), collectImageData(files));
6297
+ const switchable = options?.switchable === true ? filterAllowList(scope.workspaces, this.#workspaces.workspaces(), (one) => one.id) : [];
6298
+ const slots = [
6299
+ remembered,
6300
+ renderSection(WORKSPACE_INDEX_HEADER, switchable.length === 0 ? [] : [switchable.map((one) => renderIndexLine(one.id)).join("\n")], (block) => block, void 0),
6301
+ documented
6302
+ ].filter((slot) => slot !== void 0);
5843
6303
  const context = slots.length === 0 ? [] : [{
5844
6304
  id: crypto.randomUUID(),
5845
6305
  role: "user",
@@ -6160,6 +6620,17 @@ function createAgentContext(options) {
6160
6620
  */
6161
6621
  var DEFAULT_AGENT_LIMIT = 10;
6162
6622
  /**
6623
+ * Opens a job tree finding that refuses a whole job, which sets it apart from a finding that names an exceeded member.
6624
+ *
6625
+ * @remarks
6626
+ * The `scanJobTree` helper writes it before the path of a job the contract refuses or a member read
6627
+ * makes unreadable, and the `AgentFanout` class reads it to open its refusal with the rule that
6628
+ * finding breaks. An
6629
+ * exceeded member's finding opens with `job`, so text later in a finding cannot pass for this
6630
+ * prefix.
6631
+ */
6632
+ var JOB_REFUSAL_PREFIX = "refused ";
6633
+ /**
6163
6634
  * Holds the model-facing texts the loop writes after a tool name in a denial result — the
6164
6635
  * `denied` note for a deny with no reason, an evaluate throw, an invalid decision, or a tool
6165
6636
  * changed after its decision; the `refused` note for an ask the approver refused; and the
@@ -6171,8 +6642,74 @@ var AUTHORITY_NOTES = Object.freeze({
6171
6642
  unanswered: "it needs approval and none was given. Do not call it again; tell the user it needs approval."
6172
6643
  });
6173
6644
  /**
6645
+ * Holds the texts the built-ins return on success — `loaded`, `unloaded`, `remembered`, and
6646
+ * `switched` — frozen.
6647
+ *
6648
+ * @remarks
6649
+ * `loaded`, `unloaded`, and `switched` are the texts the conversation's stored tool messages are
6650
+ * matched against to derive what a run shows, so each is one fixed constant. A stored message
6651
+ * counts only under a call to a built-in the run enables.
6652
+ */
6653
+ var BUILTIN_NOTES = Object.freeze({
6654
+ loaded: "The skill is loaded. Its instructions and tools are yours from your next step.",
6655
+ unloaded: "The skill is unloaded. Its instructions and tools leave from your next step.",
6656
+ remembered: "The memo is saved. Continue with what you were doing.",
6657
+ switched: "The workspace is selected. Its files are yours from your next step."
6658
+ });
6659
+ /**
6660
+ * Caps each built-in argument in code points, as the built-in argument shapes count them — a `name`
6661
+ * (a skill name, a memo name, or a workspace id), a memo `description`, and a memo `content` — and
6662
+ * the `candidates` one refusal lists, frozen.
6663
+ */
6664
+ var BUILTIN_LIMITS = Object.freeze({
6665
+ name: 128,
6666
+ description: 200,
6667
+ content: 4e3,
6668
+ candidates: 20
6669
+ });
6670
+ /**
6671
+ * Declares each built-in tool's model-facing description and annotations, keyed by its
6672
+ * {@link AgentBuiltin} name, frozen.
6673
+ *
6674
+ * @remarks
6675
+ * `memo` is `pure` and `untrusted`, because it returns memo text a model can have written;
6676
+ * `remember` is `consequential`, so an `allow` verdict becomes an `ask`. A run's own tools and the
6677
+ * definitions `collectBuiltinDefinitions` returns both read their text and annotations here.
6678
+ */
6679
+ var BUILTIN_TOOLS = Object.freeze({
6680
+ load: Object.freeze({ description: "Loads one skill from the skills index, so its instructions join yours and its tools become callable from your next step. Example: {\"skill\":\"refunds\"}. Replies with a short acknowledgement, not the instructions; call unload when you no longer need the skill." }),
6681
+ unload: Object.freeze({ description: "Unloads one skill you loaded, so its instructions and tools leave from your next step. Example: {\"skill\":\"refunds\"}. Replies with a short acknowledgement." }),
6682
+ memo: Object.freeze({
6683
+ description: "Reads one memo from the memos index and replies with its full text. Example: {\"name\":\"tone\"}. Reading changes nothing; call remember to write a memo.",
6684
+ annotations: Object.freeze({
6685
+ pure: true,
6686
+ untrusted: true
6687
+ })
6688
+ }),
6689
+ remember: Object.freeze({
6690
+ description: "Saves one memo under a name you are allowed to write: a one-line description for the memos index, and the content. Example: {\"name\":\"tone\",\"description\":\"Reply tone\",\"content\":\"Keep replies brief, because the user asked for that.\"}. Replies with a short acknowledgement; call memo to read a memo back.",
6691
+ annotations: Object.freeze({ consequential: true })
6692
+ }),
6693
+ switch: Object.freeze({ description: "Selects one workspace from the workspaces index, so its files join your context from your next step. Example: {\"workspace\":\"orders\"}. Replies with a short acknowledgement." })
6694
+ });
6695
+ /**
6696
+ * Matches one control, format, line-separator, or paragraph-separator code point — the class
6697
+ * `renderArguments` encodes and a memo's one-line name and description may not hold, frozen.
6698
+ *
6699
+ * @remarks
6700
+ * Not global, so a `test` call keeps no state between calls; a global replace builds its own
6701
+ * global copy from `source`.
6702
+ */
6703
+ var ARGUMENT_CONTROL_PATTERN = Object.freeze(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u);
6704
+ /**
6705
+ * Matches a text that is blank: empty after white space and default-ignorable code points, such
6706
+ * as U+3164, are removed, frozen.
6707
+ */
6708
+ var ARGUMENT_BLANK_PATTERN = Object.freeze(/^[\p{White_Space}\p{Default_Ignorable_Code_Point}]*$/u);
6709
+ /**
6174
6710
  * Holds the model-facing text the loop writes after a tool name in the denial result of a call
6175
- * outside the active scope's tool allow-list or whose name no definition advertises this turn.
6711
+ * outside the turn's tool ceiling, the context scope's tool allow-list intersected with the run
6712
+ * scope's, or whose name no definition advertises this turn.
6176
6713
  */
6177
6714
  var SCOPE_NOTE = "it is not one of the listed tools. Use a listed tool or answer with what you have.";
6178
6715
  /**
@@ -6191,6 +6728,92 @@ var MESSAGE_TOKEN_OVERHEAD = 4;
6191
6728
  * exact count.
6192
6729
  */
6193
6730
  var IMAGE_TOKEN_ESTIMATE = 512;
6731
+ /**
6732
+ * Lists the members `AgentOptions` declares, frozen — the keys the `Agent` constructor admits.
6733
+ *
6734
+ * @remarks
6735
+ * The constructor passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an own
6736
+ * enumerable member outside it refuses with a `ContractError` coded `'structure'`.
6737
+ */
6738
+ var AGENT_OPTION_KEYS = Object.freeze([
6739
+ "on",
6740
+ "error",
6741
+ "system",
6742
+ "tools",
6743
+ "instructions",
6744
+ "skills",
6745
+ "memos",
6746
+ "workspaces",
6747
+ "scope",
6748
+ "limit",
6749
+ "timeout",
6750
+ "budget",
6751
+ "allowance",
6752
+ "scheduler",
6753
+ "signal",
6754
+ "authority",
6755
+ "conversations",
6756
+ "window",
6757
+ "strict",
6758
+ "select",
6759
+ "builtins",
6760
+ "workspace"
6761
+ ]);
6762
+ /**
6763
+ * Lists the members `AgentRunOptions` declares, frozen — the keys the `stream` and `generate`
6764
+ * methods admit.
6765
+ *
6766
+ * @remarks
6767
+ * The `stream` method passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an own
6768
+ * enumerable member outside it refuses with a `ContractError` coded `'structure'`.
6769
+ */
6770
+ var AGENT_RUN_KEYS = Object.freeze([
6771
+ "think",
6772
+ "schema",
6773
+ "limit",
6774
+ "timeout",
6775
+ "budget",
6776
+ "allowance",
6777
+ "signal",
6778
+ "conversation",
6779
+ "prompt",
6780
+ "scope",
6781
+ "workspace"
6782
+ ]);
6783
+ /** Lists the members `AuthorityOptions` declares, frozen — the keys the `Authority` constructor admits. */
6784
+ var AUTHORITY_OPTION_KEYS = Object.freeze([
6785
+ "rules",
6786
+ "fallback",
6787
+ "ask"
6788
+ ]);
6789
+ /** Lists the members `AgentRegistryOptions` declares, frozen — the keys the `AgentRegistry` constructor admits. */
6790
+ var REGISTRY_OPTION_KEYS = Object.freeze([
6791
+ "providers",
6792
+ "tools",
6793
+ "authorities",
6794
+ "schedulers",
6795
+ "store",
6796
+ "skills",
6797
+ "memos",
6798
+ "workspaces"
6799
+ ]);
6800
+ /** Lists the members `AgentQueueOptions` declares, frozen — the keys `createAgentQueue` admits. */
6801
+ var QUEUE_OPTION_KEYS = Object.freeze([
6802
+ "registry",
6803
+ "partial",
6804
+ "concurrency",
6805
+ "retries",
6806
+ "timeout",
6807
+ "store"
6808
+ ]);
6809
+ /** Lists the members `AgentRunnerOptions` declares, frozen — the keys `createAgentRunner` admits. */
6810
+ var RUNNER_OPTION_KEYS = Object.freeze([
6811
+ "registry",
6812
+ "partial",
6813
+ "concurrency",
6814
+ "retries",
6815
+ "timeout"
6816
+ ]);
6194
6817
  // src/core/agents/errors.ts
6195
6818
  /**
6196
6819
  * Reports an {@link AgentInterface} run that ended {@link AgentResult.partial} under a
@@ -6274,6 +6897,9 @@ function isAgentJobError(value) {
6274
6897
  * `'AUTHORITY'` reports an `Authority` built with no valid `fallback`, a rule with no valid `verdict`
6275
6898
  * (its `context` names the `rule` index), and an agent built with `tools` and no `authority`. Each
6276
6899
  * throws at construction, with the options a host passes to correct it in the message.
6900
+ * `'BUILTIN'` reports a `builtins` entry that is not a built-in or repeats one, `unload` enabled
6901
+ * without `load`, and a tool manager holding a tool under an enabled built-in's name, each thrown
6902
+ * at construction.
6277
6903
  * `'CONCURRENCY'` reports a run started while another run on the same agent is live, when the
6278
6904
  * agent carries a `window` (a shared context budget) or when the run's effective `budget` or
6279
6905
  * `allowance` is an instance a live run holds — the second run's `start()` would replace that
@@ -6282,18 +6908,18 @@ function isAgentJobError(value) {
6282
6908
  * `agent` id, and the `conversation` id for a shared conversation. For concurrent runs, use
6283
6909
  * separate agents, or one agent with no `window`, distinct budget and allowance instances per
6284
6910
  * run, and a distinct conversation per run.
6285
- * `'LIMIT'` reports a construction or per-run `limit` that is not a positive safe integer,
6286
- * including one a rehydrated job carries into `build`. `'REGISTRY'` reports a rehydration name
6287
- * absent from its registry pool, on `provider` / `tool` / `authority` / `scheduler` / `build`,
6288
- * whose `context` names the `category` and the `name`, and a job that names `tools` and no
6289
- * `authority` at `build`, whose `context` names the `tools`. `'WINDOW'` reports a `strict` run whose
6911
+ * `'LIMIT'` reports a construction or per-run `limit` that is not a positive safe integer.
6912
+ * `'REGISTRY'` reports a rehydration name absent from its registry pool, on `provider` / `tool` /
6913
+ * `authority` / `scheduler` / `build`, whose `context` names the `category` and the `name`, and a
6914
+ * job `build` refuses as a record, whose `context` holds the contract's `faults` or the
6915
+ * `refusals` lines `collectJobRefusals` returns. `'WINDOW'` reports a `strict` run whose
6290
6916
  * complete provider request is still over the `window` budget, equal to its `max` included, after
6291
6917
  * the one permitted fold or with no fold possible; it settles the run `error` before the provider
6292
6918
  * is called, and its `context` holds the `agent` id, the measured `consumed`, and the window `max`.
6293
6919
  * Narrow a caught value with {@link isAgentError} and branch on `error.code`.
6294
6920
  */
6295
6921
  var AgentError = class extends Error {
6296
- /** Names the machine-readable condition — `'APPROVER'`: an `ask` on an authority that has no approver, or one its approver refuses; `'AUTHORITY'`: an authority missing its fallback or a rule's verdict, or tools set with no authority; `'CONCURRENCY'`: a run sharing accounting or a conversation with a live run; `'LIMIT'`: a `limit` that is not a positive safe integer; `'REGISTRY'`: a rehydration name absent from its registry pool; `'WINDOW'`: a strict run whose complete request is still over its window budget. */
6922
+ /** Names the machine-readable condition — `'APPROVER'`: an `ask` on an authority that has no approver, or one its approver refuses; `'AUTHORITY'`: an authority missing its fallback or a rule's verdict, or tools set with no authority; `'BUILTIN'`: a built-in list the agent cannot serve; `'CONCURRENCY'`: a run sharing accounting or a conversation with a live run; `'LIMIT'`: a `limit` that is not a positive safe integer; `'REGISTRY'`: a rehydration name absent from its registry pool; `'WINDOW'`: a strict run whose complete request is still over its window budget. */
6297
6923
  code;
6298
6924
  /** Holds the values that locate the failure, such as the `agent` id of a refused run, or `undefined` when none were supplied. */
6299
6925
  context;
@@ -6332,7 +6958,7 @@ function isAgentError(value) {
6332
6958
  return holds(() => {
6333
6959
  if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.AgentError"))?.value === value)) return false;
6334
6960
  const code = INTRINSICS.reflect.read(value, "code");
6335
- if (!(code === "APPROVER" || code === "AUTHORITY" || code === "CONCURRENCY" || code === "LIMIT" || code === "REGISTRY" || code === "SCHEMA" || code === "WINDOW")) return false;
6961
+ if (!(code === "APPROVER" || code === "AUTHORITY" || code === "BUILTIN" || code === "CONCURRENCY" || code === "LIMIT" || code === "REGISTRY" || code === "SCHEMA" || code === "WINDOW")) return false;
6336
6962
  const context = INTRINSICS.reflect.read(value, "context");
6337
6963
  return context === void 0 || isObject(context) || isFunction(context);
6338
6964
  });
@@ -6343,20 +6969,45 @@ function isAgentError(value) {
6343
6969
  * refuses instead of running an agent without it.
6344
6970
  *
6345
6971
  * @remarks
6346
- * `children` holds JSON records, because each child crosses this shape at its own `build`. `limit`
6347
- * reads as a number here and as a positive safe integer at the agent's construction, which owns that
6348
- * refusal.
6972
+ * `children` holds JSON records, because each child crosses this shape at its own `build`. Each
6973
+ * bound states what the build reads: `limit` an integer from 1 through `Number.MAX_SAFE_INTEGER`,
6974
+ * `timeout` an integer from 0 through `MAX_TIMEOUT_MS`, and `budget` a number of at least 0. A seed
6975
+ * message plays a `ConversationRole`, so a `system` message refuses here. A `scope` holds the
6976
+ * `skills`, `memos`, and `workspaces` lists, each required, and no other member; `builtins` admits
6977
+ * only the names of `AgentBuiltin`, and `collectJobRefusals` reads what a list of them cannot state.
6349
6978
  */
6350
6979
  var agentJobShape = objectShape({
6351
6980
  provider: stringShape(),
6352
- messages: optionalShape(arrayShape(messageInputShape)),
6981
+ messages: optionalShape(arrayShape(objectShape({
6982
+ ...messageInputShape.properties,
6983
+ role: literalShape(CONVERSATION_ROLES)
6984
+ }))),
6353
6985
  system: optionalShape(stringShape()),
6354
6986
  tools: optionalShape(arrayShape(stringShape())),
6355
6987
  authority: optionalShape(stringShape()),
6356
6988
  scheduler: optionalShape(stringShape()),
6357
- limit: optionalShape(numberShape()),
6358
- timeout: optionalShape(numberShape()),
6359
- budget: optionalShape(numberShape()),
6989
+ limit: optionalShape(integerShape({
6990
+ min: 1,
6991
+ max: Number.MAX_SAFE_INTEGER
6992
+ })),
6993
+ timeout: optionalShape(integerShape({
6994
+ min: 0,
6995
+ max: MAX_TIMEOUT_MS
6996
+ })),
6997
+ budget: optionalShape(numberShape({ min: 0 })),
6998
+ scope: optionalShape(objectShape({
6999
+ skills: arrayShape(stringShape()),
7000
+ memos: arrayShape(stringShape()),
7001
+ workspaces: arrayShape(stringShape())
7002
+ })),
7003
+ workspace: optionalShape(stringShape()),
7004
+ builtins: optionalShape(arrayShape(literalShape([
7005
+ "load",
7006
+ "unload",
7007
+ "memo",
7008
+ "remember",
7009
+ "switch"
7010
+ ]))),
6360
7011
  children: optionalShape(arrayShape(recordShape(jsonShape())))
6361
7012
  });
6362
7013
  /**
@@ -6426,6 +7077,74 @@ var agentAnswerShape = objectShape({
6426
7077
  id: stringShape(),
6427
7078
  approved: booleanShape()
6428
7079
  });
7080
+ /**
7081
+ * Describes the arguments of the `load` and `unload` built-ins — one `skill` name, non-empty and
7082
+ * at most `BUILTIN_LIMITS.name` code points.
7083
+ *
7084
+ * @remarks
7085
+ * The tool's door refuses a missing, empty, over-long, or extra member before the handler runs,
7086
+ * and repairs a value that converts to a string without loss, such as a number. A value of white
7087
+ * space alone passes the door; the handler refuses it as it refuses any name it cannot use.
7088
+ */
7089
+ var loadToolShape = objectShape({ skill: stringShape({
7090
+ min: 1,
7091
+ max: BUILTIN_LIMITS.name,
7092
+ description: "A skill name from the skills index"
7093
+ }) });
7094
+ /**
7095
+ * Describes the arguments of the `memo` built-in — one memo `name`, non-empty and at most
7096
+ * `BUILTIN_LIMITS.name` code points.
7097
+ *
7098
+ * @remarks
7099
+ * The tool's door refuses a missing, empty, over-long, or extra member before the handler runs,
7100
+ * and repairs a value that converts to a string without loss, such as a number. A value of white
7101
+ * space alone passes the door; the handler refuses it as it refuses any name it cannot use.
7102
+ */
7103
+ var memoToolShape = objectShape({ name: stringShape({
7104
+ min: 1,
7105
+ max: BUILTIN_LIMITS.name,
7106
+ description: "A memo name from the memos index"
7107
+ }) });
7108
+ /**
7109
+ * Describes the arguments of the `remember` built-in — a memo `name`, the one-line `description`
7110
+ * the memos index shows, and the `content`, each non-empty and within its `BUILTIN_LIMITS` cap.
7111
+ *
7112
+ * @remarks
7113
+ * The tool's door refuses a missing, empty, over-long, or extra member before the handler runs,
7114
+ * and repairs a value that converts to a string without loss, such as a number. A value of white
7115
+ * space alone passes the door; the handler refuses it as it refuses any name it cannot use.
7116
+ */
7117
+ var rememberToolShape = objectShape({
7118
+ name: stringShape({
7119
+ min: 1,
7120
+ max: BUILTIN_LIMITS.name,
7121
+ description: "A memo name the host lists for you to write"
7122
+ }),
7123
+ description: stringShape({
7124
+ min: 1,
7125
+ max: BUILTIN_LIMITS.description,
7126
+ description: "One line the memos index shows"
7127
+ }),
7128
+ content: stringShape({
7129
+ min: 1,
7130
+ max: BUILTIN_LIMITS.content,
7131
+ description: "The fact, why it holds, and how to apply it"
7132
+ })
7133
+ });
7134
+ /**
7135
+ * Describes the arguments of the `switch` built-in — one `workspace` id, non-empty and at most
7136
+ * `BUILTIN_LIMITS.name` code points.
7137
+ *
7138
+ * @remarks
7139
+ * The tool's door refuses a missing, empty, over-long, or extra member before the handler runs,
7140
+ * and repairs a value that converts to a string without loss, such as a number. A value of white
7141
+ * space alone passes the door; the handler refuses it as it refuses any name it cannot use.
7142
+ */
7143
+ var switchToolShape = objectShape({ workspace: stringShape({
7144
+ min: 1,
7145
+ max: BUILTIN_LIMITS.name,
7146
+ description: "A workspace id from the workspaces index"
7147
+ }) });
6429
7148
  // src/core/agents/contracts.ts
6430
7149
  /** Validates and projects agent frames at a JSON wire boundary. */
6431
7150
  var agentFrameContract = createContract(agentFrameShape);
@@ -6435,131 +7154,64 @@ var agentPromptContract = createContract(agentPromptShape);
6435
7154
  var agentJobContract = createContract(agentJobShape);
6436
7155
  /** Validates and projects a page's answers to `ask` frames at a JSON wire boundary. */
6437
7156
  var agentAnswerContract = createContract(agentAnswerShape);
6438
- // src/core/agents/ChannelCell.ts
7157
+ /** Checks the arguments of the `load` and `unload` built-ins; its schema is the parameters they advertise. */
7158
+ var loadToolContract = createContract(loadToolShape);
7159
+ /** Checks the arguments of the `memo` built-in; its schema is the parameters it advertises. */
7160
+ var memoToolContract = createContract(memoToolShape);
7161
+ /** Checks the arguments of the `remember` built-in; its schema is the parameters it advertises. */
7162
+ var rememberToolContract = createContract(rememberToolShape);
7163
+ /** Checks the arguments of the `switch` built-in; its schema is the parameters it advertises. */
7164
+ var switchToolContract = createContract(switchToolShape);
7165
+ /**
7166
+ * Pairs each built-in's argument shape, which its tool's door compiles, with its compiled contract,
7167
+ * keyed by its {@link AgentBuiltin} name, frozen.
7168
+ *
7169
+ * @remarks
7170
+ * The one map from a built-in to its arguments: `createBuiltinTool` builds the door from `shape`,
7171
+ * and `collectBuiltinDefinitions` and `collectDisclosure` read `contract`, so the advertised
7172
+ * parameters, the door, and the derivation admit by one rule. The record declares no shape: each
7173
+ * `shape` is a reference to the one `shapers.ts` declares, held beside the contract compiled from
7174
+ * it, because the tool door takes a shape and the derivation takes a compiled contract. The record
7175
+ * is data, as the rest of this file is.
7176
+ */
7177
+ var builtinToolContracts = Object.freeze({
7178
+ load: Object.freeze({
7179
+ shape: loadToolShape,
7180
+ contract: loadToolContract
7181
+ }),
7182
+ unload: Object.freeze({
7183
+ shape: loadToolShape,
7184
+ contract: loadToolContract
7185
+ }),
7186
+ memo: Object.freeze({
7187
+ shape: memoToolShape,
7188
+ contract: memoToolContract
7189
+ }),
7190
+ remember: Object.freeze({
7191
+ shape: rememberToolShape,
7192
+ contract: rememberToolContract
7193
+ }),
7194
+ switch: Object.freeze({
7195
+ shape: switchToolShape,
7196
+ contract: switchToolContract
7197
+ })
7198
+ });
7199
+ // src/core/agents/validators.ts
6439
7200
  /**
6440
- * Holds one value a `Channel` buffers and the cell pushed after it.
7201
+ * Checks whether a value names a built-in: `load`, `unload`, `memo`, `remember`, or `switch`.
6441
7202
  *
6442
- * @remarks
6443
- * A `Channel` keeps its unread values as a chain of these cells, from its `#head` cell to its
6444
- * `#tail` cell, so no public signature names this class. The `#next` field is a latch: the
6445
- * `link` method sets it once, and a later call keeps the first cell.
6446
- */
6447
- var ChannelCell = class {
6448
- #value;
6449
- #next;
6450
- /**
6451
- * Holds a value with no next cell.
6452
- *
6453
- * @param value - The value the cell holds
6454
- */
6455
- constructor(value) {
6456
- this.#value = value;
6457
- }
6458
- /**
6459
- * Returns the value the cell holds.
6460
- *
6461
- * @returns The value
6462
- */
6463
- get value() {
6464
- return this.#value;
6465
- }
6466
- /**
6467
- * Returns the cell pushed after this one.
6468
- *
6469
- * @returns The next cell, or undefined before one is linked
6470
- */
6471
- get next() {
6472
- return this.#next;
6473
- }
6474
- /**
6475
- * Links the cell pushed after this one, once.
6476
- *
6477
- * @param cell - The cell pushed after this one
6478
- */
6479
- link(cell) {
6480
- this.#next ??= cell;
6481
- }
6482
- };
6483
- // src/core/agents/Channel.ts
6484
- /**
6485
- * Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`)
6486
- * and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live
6487
- * through the `drain` async-iterator. Decoupling write from read is what lets a producer make
6488
- * progress without a consumer pulling, and it is why an agent's `result` settles whether or not
6489
- * its `events` are drained.
6490
- *
6491
- * @remarks
6492
- * A waiting `drain` call parks its void resolver in the `#waiting` field. The `push` method links a
6493
- * cell after the `#tail` cell, and the `close` and `fail` methods flag the end; each then fires and
6494
- * clears every parked resolver, so each parked reader wakes, reads the `#head` cell, and either
6495
- * takes the next chunk, returns (on `close`), throws (on `fail`), or parks again when another
6496
- * reader took the chunk first. Taking a chunk reads its value and moves `#head` to the next cell
6497
- * synchronously, so each value reaches exactly one reader, a push and a take each cost constant
6498
- * time, and every taken cell but the newest is released at once; the `#tail` field holds the newest
6499
- * cell until the next push links after it, so a channel retains at most one taken value. A reader
6500
- * suspended at its `yield` expression holds only the value it took, never a cell, so the bound on
6501
- * retained values covers both the channel's fields and a suspended reader.
6502
- * A `return()` issued while a read is parked waits for the next `push`, `close`, or `fail`.
6503
- * The parked read takes a pushed value before that `return()` settles.
7203
+ * @param value - The unknown name candidate
7204
+ * @returns True if the value names a built-in; false otherwise
6504
7205
  *
6505
7206
  * @example
6506
7207
  * ```ts
6507
- * import { Channel } from '@orkestrel/agent'
6508
- *
6509
- * const channel = new Channel<number>()
6510
- * channel.push(1)
6511
- * channel.close()
6512
- * for await (const value of channel.drain()) {
6513
- * value // 1
6514
- * }
7208
+ * isAgentBuiltin('load') // true
7209
+ * isAgentBuiltin('open') // false
6515
7210
  * ```
6516
7211
  */
6517
- var Channel = class {
6518
- #head;
6519
- #tail;
6520
- #waiting = [];
6521
- #closed = false;
6522
- #failure;
6523
- push(value) {
6524
- const cell = new ChannelCell(value);
6525
- this.#tail?.link(cell);
6526
- this.#tail = cell;
6527
- this.#head ??= cell;
6528
- this.#signal();
6529
- }
6530
- close() {
6531
- this.#closed = true;
6532
- this.#signal();
6533
- }
6534
- fail(error) {
6535
- if (this.#failure === void 0) this.#failure = { error };
6536
- this.#closed = true;
6537
- this.#signal();
6538
- }
6539
- async *drain() {
6540
- for (;;) {
6541
- while (this.#head !== void 0) {
6542
- const value = this.#head.value;
6543
- this.#head = this.#head.next;
6544
- yield value;
6545
- }
6546
- if (this.#failure !== void 0) throw this.#failure.error;
6547
- if (this.#closed) return;
6548
- await this.#park();
6549
- }
6550
- }
6551
- #signal() {
6552
- const waiting = this.#waiting;
6553
- this.#waiting = [];
6554
- for (const wake of waiting) wake();
6555
- }
6556
- #park() {
6557
- return new Promise((resolve) => {
6558
- this.#waiting = [...this.#waiting, resolve];
6559
- });
6560
- }
6561
- };
6562
- // src/core/agents/validators.ts
7212
+ function isAgentBuiltin(value) {
7213
+ return value === "load" || value === "unload" || value === "memo" || value === "remember" || value === "switch";
7214
+ }
6563
7215
  /**
6564
7216
  * Checks whether a value is an authority verdict: `allow`, `ask`, or `deny`.
6565
7217
  *
@@ -7080,6 +7732,118 @@ function handleAgentQueueJob(registry, partial, input, context) {
7080
7732
  return settleAgentJob(registry.build(input, context.signal), partial);
7081
7733
  }
7082
7734
  /**
7735
+ * Collects the refusals a job the contract admitted would meet at its build: tools or built-ins with
7736
+ * no authority, a `builtins` list `requireBuiltins` refuses, and a built-in its own `tools` name.
7737
+ *
7738
+ * @remarks
7739
+ * Each line names the member first, then the refusal and its remedy. The `builtins` line of a list
7740
+ * `requireBuiltins` refuses carries that error's message; a job's tool manager holds exactly its
7741
+ * `tools`, so a built-in its `tools` list also names is the name a manager would already hold.
7742
+ * `AgentRegistry.build` refuses a job with any line, and `scanJobTree` refuses each such job of a
7743
+ * tree before anything spawns.
7744
+ *
7745
+ * @param job - The `tools`, `builtins`, and `authority` of a job `agentJobContract` admitted
7746
+ * @returns One line a refusal, in member order; empty when the job builds
7747
+ *
7748
+ * @example
7749
+ * ```ts
7750
+ * collectJobRefusals({ provider: 'main', tools: ['search'] })
7751
+ * // ["authority: a job that names tools or builtins and no authority cannot run them; add authority: 'NAME' to the job and register that NAME under authorities"]
7752
+ * ```
7753
+ */
7754
+ function collectJobRefusals(job) {
7755
+ const tools = job.tools ?? [];
7756
+ const builtins = job.builtins ?? [];
7757
+ const checked = attempt(() => requireBuiltins(job.builtins, { tool: () => void 0 }));
7758
+ const shared = builtins.filter((name) => tools.includes(name));
7759
+ return [
7760
+ (tools.length > 0 || builtins.length > 0) && job.authority === void 0 ? "authority: a job that names tools or builtins and no authority cannot run them; add authority: 'NAME' to the job and register that NAME under authorities" : void 0,
7761
+ checked.success ? void 0 : `builtins: ${errorToMessage(checked.error)}`,
7762
+ shared.length === 0 ? void 0 : `builtins: names ${shared.map((name) => preview(name)).join(", ")}, which its tools also name; rename that tool or leave the name out of builtins`
7763
+ ].filter((line) => line !== void 0);
7764
+ }
7765
+ /**
7766
+ * Scans every job under a root for a member that exceeds its own parent's; an empty result clears the tree.
7767
+ *
7768
+ * @remarks
7769
+ * The walk audits each job, the root included, through `agentJobContract` before it reads a member,
7770
+ * because a job's `children` cross that contract as JSON records, and then reads each job the
7771
+ * contract admits through `collectJobRefusals`. A job the contract refuses yields one finding with its
7772
+ * faults, or with an unreadable note when a member read throws; a job its build would refuse yields
7773
+ * one finding a refusal, its path, a dot, and the line; and the walk reads nothing under either. A
7774
+ * child is within its parent when each of
7775
+ * its `tools` is one its parent names (a parent with no `tools` names none), each of its `builtins`
7776
+ * is one its parent names (a parent with no `builtins` names none), each name in each list of its
7777
+ * `scope` is in its parent's same list (a job with no `scope` holds the three lists empty), its
7778
+ * `authority` and `scheduler` are absent or its parent's, its `provider` is its parent's, its `limit`
7779
+ * is at most its parent's (an absent `limit` reads `DEFAULT_AGENT_LIMIT`), and, where its parent
7780
+ * holds a `timeout` or a `budget`, it holds one no larger. `system`, `messages`, and `workspace` are
7781
+ * free: a `workspace` renders nothing its own `scope` omits. A refused job's finding
7782
+ * opens with `JOB_REFUSAL_PREFIX` and then the job's path from `job`; an exceeded member's opens
7783
+ * with that path, a dot, and the member. The walk is total: an unreadable job yields a finding,
7784
+ * never a throw. The `AgentFanout` class runs it on every attempt of a unit, before the unit spawns
7785
+ * or runs.
7786
+ *
7787
+ * @param root - The root job of the tree
7788
+ * @returns One finding per refused job and per exceeded member, in walk order
7789
+ *
7790
+ * @example
7791
+ * ```ts
7792
+ * scanJobTree({ provider: 'main', children: [{ provider: 'other' }] })
7793
+ * // ['job.children[0].provider: "other" differs from its parent\'s, which is "main"']
7794
+ * ```
7795
+ */
7796
+ function scanJobTree(root) {
7797
+ const findings = [];
7798
+ const pending = [[
7799
+ root,
7800
+ "job",
7801
+ void 0
7802
+ ]];
7803
+ for (const [job, path, parent] of pending) {
7804
+ if (!agentJobContract.is(job)) {
7805
+ const faults = attempt(() => agentJobContract.audit(job));
7806
+ findings.push(`${JOB_REFUSAL_PREFIX}${path}: ${faults.success ? describeFaults(faults.value, agentJobContract.schema) : "a member read threw, so the job cannot be read"}`);
7807
+ continue;
7808
+ }
7809
+ const refusals = collectJobRefusals(job);
7810
+ if (refusals.length > 0) {
7811
+ findings.push(...refusals.map((line) => `${JOB_REFUSAL_PREFIX}${path}.${line}`));
7812
+ continue;
7813
+ }
7814
+ if (parent !== void 0) {
7815
+ const held = parent.tools ?? [];
7816
+ const outside = (job.tools ?? []).filter((name) => !held.includes(name));
7817
+ const enabled = parent.builtins ?? [];
7818
+ const extra = (job.builtins ?? []).filter((name) => !enabled.includes(name));
7819
+ const unlisted = [
7820
+ "skills",
7821
+ "memos",
7822
+ "workspaces"
7823
+ ].map((list) => [list, (job.scope?.[list] ?? []).filter((name) => !(parent.scope?.[list] ?? []).includes(name))]);
7824
+ const limit = job.limit ?? 10;
7825
+ const bound = parent.limit ?? 10;
7826
+ findings.push(...[
7827
+ outside.length === 0 ? void 0 : `${path}.tools: names ${outside.map((name) => preview(name)).join(", ")}, which its parent does not hold`,
7828
+ extra.length === 0 ? void 0 : `${path}.builtins: names ${extra.map((name) => preview(name)).join(", ")}, which its parent does not hold`,
7829
+ ...unlisted.map(([list, names]) => names.length === 0 ? void 0 : `${path}.scope.${list}: names ${names.map((name) => preview(name)).join(", ")}, which its parent does not hold`),
7830
+ job.authority === void 0 || job.authority === parent.authority ? void 0 : `${path}.authority: ${preview(job.authority)} is neither absent nor its parent's, which is ${parent.authority === void 0 ? "none" : preview(parent.authority)}`,
7831
+ job.provider === parent.provider ? void 0 : `${path}.provider: ${preview(job.provider)} differs from its parent's, which is ${preview(parent.provider)}`,
7832
+ job.scheduler === void 0 || job.scheduler === parent.scheduler ? void 0 : `${path}.scheduler: ${preview(job.scheduler)} is neither absent nor its parent's, which is ${parent.scheduler === void 0 ? "none" : preview(parent.scheduler)}`,
7833
+ limit <= bound ? void 0 : `${path}.limit: ${job.limit === void 0 ? `none reads ${limit}, which exceeds` : `${limit} exceeds`} its parent's ${bound}`,
7834
+ parent.timeout === void 0 || job.timeout !== void 0 && job.timeout <= parent.timeout ? void 0 : `${path}.timeout: ${job.timeout ?? "none"} exceeds its parent's ${parent.timeout}`,
7835
+ parent.budget === void 0 || job.budget !== void 0 && job.budget <= parent.budget ? void 0 : `${path}.budget: ${job.budget ?? "none"} exceeds its parent's ${parent.budget}`
7836
+ ].filter((finding) => finding !== void 0));
7837
+ }
7838
+ for (const [index, child] of (job.children ?? []).entries()) pending.push([
7839
+ child,
7840
+ `${path}.children[${index}]`,
7841
+ job
7842
+ ]);
7843
+ }
7844
+ return findings;
7845
+ }
7846
+ /**
7083
7847
  * Assembles the settled {@link AgentResult} from a run's {@link AgentRunResult} — `thinking`,
7084
7848
  * `usage`, and `stop` are carried only when the run surfaced them, and the loop-internal
7085
7849
  * `exhausted` flag is left out.
@@ -7162,7 +7926,7 @@ function denyCall(call, reason) {
7162
7926
  function renderArguments(value) {
7163
7927
  const rendered = attempt(() => canonicalStringify(value));
7164
7928
  if (!rendered.success || rendered.value === void 0) return void 0;
7165
- return rendered.value.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (match) => Array.from({ length: match.length }, (_, index) => `\\u${match.charCodeAt(index).toString(16).padStart(4, "0")}`).join(""));
7929
+ return rendered.value.replace(new RegExp(ARGUMENT_CONTROL_PATTERN.source, "gu"), (match) => Array.from({ length: match.length }, (_, index) => `\\u${match.charCodeAt(index).toString(16).padStart(4, "0")}`).join(""));
7166
7930
  }
7167
7931
  /**
7168
7932
  * Applies the `consequential` floor to one {@link AuthorityDecision} — an `allow` for a tool
@@ -7381,6 +8145,37 @@ function requireConversation(value) {
7381
8145
  });
7382
8146
  }
7383
8147
  /**
8148
+ * Returns a scope a run can bind, or throws a `ContractError` coded `'placement'`; `undefined`
8149
+ * passes through.
8150
+ *
8151
+ * @remarks
8152
+ * The check is {@link isScope}, a total guard that reads each member one time and admits any
8153
+ * implementation of `ScopeInterface`. `undefined` passes, because an absent option leaves the
8154
+ * context scope alone as the run's ceiling. The error's `context` carries the option path, the
8155
+ * limit `'ScopeInterface'`, and a preview of the refused value.
8156
+ *
8157
+ * @param value - The run's `scope` option, or `undefined`
8158
+ * @returns The value unchanged
8159
+ * @throws {ContractError} Thrown when `value` is defined and does not implement `ScopeInterface` (code `'placement'`)
8160
+ *
8161
+ * @example
8162
+ * ```ts
8163
+ * requireScope(createScope({ name: 'reader', tools: ['search'] })) // the scope
8164
+ * requireScope({ id: 's1', name: 'reader' }) // throws ContractError ('placement')
8165
+ * ```
8166
+ */
8167
+ function requireScope(value) {
8168
+ if (value === void 0 || isScope(value)) return value;
8169
+ throw new ContractError("Agent: scope must implement ScopeInterface", {
8170
+ code: "placement",
8171
+ context: {
8172
+ path: ["options", "scope"],
8173
+ limit: "ScopeInterface",
8174
+ received: preview(value)
8175
+ }
8176
+ });
8177
+ }
8178
+ /**
7384
8179
  * Renders a tool's output as the string content of its tool message, or returns `undefined` when JSON
7385
8180
  * cannot carry it.
7386
8181
  *
@@ -7482,6 +8277,698 @@ function extractQueueOptions(options) {
7482
8277
  ...timeout === void 0 ? {} : { timeout }
7483
8278
  };
7484
8279
  }
8280
+ /**
8281
+ * Collects the definitions of the tools an agent serves itself, as a run advertises them.
8282
+ *
8283
+ * @remarks
8284
+ * Each definition carries the name, description, and annotations `BUILTIN_TOOLS` declares and the
8285
+ * parameters of the built-in's compiled contract in `builtinToolContracts`, in the order `builtins` lists them, so
8286
+ * it equals the definition of the tool `createBuiltinTool` creates. A relay server lists these
8287
+ * among its declared definitions to forward a page's built-ins. A name that is no built-in
8288
+ * contributes nothing.
8289
+ *
8290
+ * @param options - The agent options whose `builtins` to project
8291
+ * @returns The definitions, empty when `builtins` is absent
8292
+ *
8293
+ * @example
8294
+ * ```ts
8295
+ * collectBuiltinDefinitions({ builtins: ['load', 'unload'] }).map((definition) => definition.name) // ['load', 'unload']
8296
+ * ```
8297
+ */
8298
+ function collectBuiltinDefinitions(options) {
8299
+ return (options.builtins ?? []).filter(isAgentBuiltin).map((name) => {
8300
+ const declared = BUILTIN_TOOLS[name];
8301
+ const parameters = schemaToParameters(builtinToolContracts[name].contract.schema);
8302
+ return {
8303
+ name,
8304
+ description: declared.description,
8305
+ ...parameters === void 0 ? {} : { parameters },
8306
+ ...declared.annotations === void 0 ? {} : { annotations: declared.annotations }
8307
+ };
8308
+ });
8309
+ }
8310
+ /**
8311
+ * Returns an agent's `builtins` option as an owned, frozen list, or throws a coded error before the
8312
+ * agent is built.
8313
+ *
8314
+ * @remarks
8315
+ * `undefined` returns an empty list. The option must be an array of distinct {@link AgentBuiltin}
8316
+ * names; `unload` needs `load`, because only a loaded skill can be unloaded; and the host's tool
8317
+ * manager may hold no tool under an enabled name, because the run serves that name itself.
8318
+ *
8319
+ * @param value - The `builtins` option
8320
+ * @param tools - The host's tool manager
8321
+ * @returns The enabled names, in the order given
8322
+ * @throws {AgentError} Thrown when the option is not an array, names something that is no built-in, repeats a name, lists `unload` without `load`, or names a tool the manager holds (code `'BUILTIN'`)
8323
+ *
8324
+ * @example
8325
+ * ```ts
8326
+ * requireBuiltins(['load', 'unload'], createToolManager()) // ['load', 'unload']
8327
+ * requireBuiltins(['unload'], createToolManager()) // throws AgentError ('BUILTIN')
8328
+ * ```
8329
+ */
8330
+ function requireBuiltins(value, tools) {
8331
+ if (value === void 0) return Object.freeze([]);
8332
+ if (!isArray(value)) throw new AgentError("BUILTIN", `builtins must be an array; received ${preview(value)}`);
8333
+ const names = [...value].filter(isAgentBuiltin);
8334
+ if (names.length !== value.length) throw new AgentError("BUILTIN", "builtins lists a name that is no built-in; list only 'load', 'unload', 'memo', 'remember', and 'switch'", { context: { received: preview(value) } });
8335
+ if (new Set(names).size !== names.length) throw new AgentError("BUILTIN", "builtins lists a name more than once", { context: { builtins: names } });
8336
+ if (names.includes("unload") && !names.includes("load")) throw new AgentError("BUILTIN", "builtins lists 'unload' without 'load'; add 'load' too", { context: { builtins: names } });
8337
+ const taken = names.filter((name) => tools.tool(name) !== void 0);
8338
+ if (taken.length > 0) throw new AgentError("BUILTIN", `the tool manager holds a tool under the built-in name ${taken.map((name) => `'${name}'`).join(", ")}; rename that tool or leave the name out of builtins`, { context: {
8339
+ builtins: names,
8340
+ taken
8341
+ } });
8342
+ return Object.freeze(names);
8343
+ }
8344
+ /**
8345
+ * Returns a `workspace` option unchanged, or throws a `ContractError` coded `'placement'`;
8346
+ * `undefined` passes through.
8347
+ *
8348
+ * @remarks
8349
+ * The check is `isString`. An id the workspace registry does not hold, or the ceiling does not
8350
+ * admit, passes here and renders nothing. The error's `context` carries the option path, the limit
8351
+ * `'string'`, and a preview of the refused value.
8352
+ *
8353
+ * @param value - The `workspace` option of an agent, a run, or a ledger's agent, or `undefined`
8354
+ * @returns The value unchanged
8355
+ * @throws {ContractError} Thrown when `value` is defined and is not a string (code `'placement'`)
8356
+ *
8357
+ * @example
8358
+ * ```ts
8359
+ * requireWorkspace('orders') // 'orders'
8360
+ * requireWorkspace(7) // throws ContractError ('placement')
8361
+ * ```
8362
+ */
8363
+ function requireWorkspace(value) {
8364
+ if (value === void 0 || isString(value)) return value;
8365
+ throw new ContractError("Agent: workspace must be a string", {
8366
+ code: "placement",
8367
+ context: {
8368
+ path: ["options", "workspace"],
8369
+ limit: "string",
8370
+ received: preview(value)
8371
+ }
8372
+ });
8373
+ }
8374
+ /**
8375
+ * Returns the definitions a turn advertises from the allow-list, the registered skills, and the
8376
+ * shown skills.
8377
+ *
8378
+ * @remarks
8379
+ * The allow-list admits first, as `filterAllowList` does. When no skill is passed, or an allow-list
8380
+ * admits no `load` definition, the admitted list returns as it is. Otherwise a tool any registered
8381
+ * skill names is held back unless a shown skill names it too; `load` and `unload` are never held
8382
+ * back. A caller passes the registered skills only while `load` is enabled, so with no allow-list a
8383
+ * ceiling whose empty `skills` list withholds `load` from the candidates still holds the skills'
8384
+ * tools back. Holding a tool back is presentation, never authority: a call to it is denied as
8385
+ * outside the turn's scope.
8386
+ *
8387
+ * @param definitions - The candidate definitions, in advertisement order
8388
+ * @param names - The turn's `tools` allow-list (`undefined` ⇒ all, `[]` ⇒ none)
8389
+ * @param skills - The registered skills whose `tools` gate, or none while `load` is not enabled
8390
+ * @param shown - The names of the skills the turn shows
8391
+ * @returns The advertised definitions, in candidate order
8392
+ *
8393
+ * @example
8394
+ * ```ts
8395
+ * const skills = [{ id: '1', name: 'refunds', description: 'Refunds', content: '', tools: ['refund'], files: [] }]
8396
+ * filterAdvertisedTools([{ name: 'load' }, { name: 'refund' }], undefined, skills, []) // [{ name: 'load' }]
8397
+ * filterAdvertisedTools([{ name: 'load' }, { name: 'refund' }], undefined, skills, ['refunds']).length // 2
8398
+ * ```
8399
+ */
8400
+ function filterAdvertisedTools(definitions, names, skills, shown) {
8401
+ const admitted = filterAllowList(names, definitions, (definition) => definition.name);
8402
+ if (skills.length === 0) return admitted;
8403
+ if (names !== void 0 && !admitted.some((definition) => definition.name === "load")) return admitted;
8404
+ const held = new Set(skills.flatMap((skill) => skill.tools));
8405
+ const visible = new Set(shown);
8406
+ const open = new Set(skills.filter((skill) => visible.has(skill.name)).flatMap((skill) => skill.tools));
8407
+ return admitted.filter((definition) => definition.name === "load" || definition.name === "unload" || !held.has(definition.name) || open.has(definition.name));
8408
+ }
8409
+ /**
8410
+ * Returns the definitions a run offers before the allow-list, without `remember` unless the
8411
+ * ceiling's `memos` list names a memo, without `switch` unless its `workspaces` list names a
8412
+ * workspace, and without `load` and `unload` while its `skills` list is empty.
8413
+ *
8414
+ * @remarks
8415
+ * `remember` writes and `switch` selects only a name its list holds, so an absent list and an empty
8416
+ * list each leave the built-in nothing to act on, and it is not advertised. An absent `skills` list
8417
+ * admits every registered skill, so `load` and `unload` are withheld only when the list is empty.
8418
+ * Every other definition keeps its place.
8419
+ *
8420
+ * @param definitions - The candidate definitions, in advertisement order
8421
+ * @param ceiling - The turn's ceiling
8422
+ * @returns The definitions, in candidate order
8423
+ *
8424
+ * @example
8425
+ * ```ts
8426
+ * filterBuiltinCandidates([{ name: 'memo' }, { name: 'remember' }], { memos: [] }) // [{ name: 'memo' }]
8427
+ * filterBuiltinCandidates([{ name: 'memo' }, { name: 'remember' }], { memos: ['tone'] }).length // 2
8428
+ * ```
8429
+ */
8430
+ function filterBuiltinCandidates(definitions, ceiling) {
8431
+ const writable = (ceiling.memos ?? []).length > 0;
8432
+ const selectable = (ceiling.workspaces ?? []).length > 0;
8433
+ const loadable = ceiling.skills === void 0 || ceiling.skills.length > 0;
8434
+ return definitions.filter((definition) => (definition.name !== "remember" || writable) && (definition.name !== "switch" || selectable) && (definition.name !== "load" && definition.name !== "unload" || loadable));
8435
+ }
8436
+ /**
8437
+ * Returns the refusal that names a subject and at most `BUILTIN_LIMITS.candidates` of the names a
8438
+ * caller can use.
8439
+ *
8440
+ * @remarks
8441
+ * The subject reads after "No", so it names what the caller may use, such as `'skill you can load'`.
8442
+ * The text echoes no argument, so an absent name and a name outside the ceiling read byte for byte
8443
+ * the same. Each name is JSON-encoded and capped by `preview`, in the order given. Past the cap one
8444
+ * fixed sentence sends the reader to the index in its prompt.
8445
+ *
8446
+ * @param subject - What the caller may name, such as `'skill you can load'`
8447
+ * @param names - The names the caller can use, in registry order
8448
+ * @returns The refusal text
8449
+ *
8450
+ * @example
8451
+ * ```ts
8452
+ * describeCandidates('skill you can load', ['refunds', 'billing'])
8453
+ * // 'No skill you can load has that name. Use one of: "refunds", "billing".'
8454
+ * ```
8455
+ */
8456
+ function describeCandidates(subject, names) {
8457
+ if (names.length === 0) return `No ${subject} has that name, and none is available now.`;
8458
+ return `No ${subject} has that name. Use one of: ${names.slice(0, BUILTIN_LIMITS.candidates).map((name) => preview(name)).join(", ")}.${names.length > BUILTIN_LIMITS.candidates ? " The index in your prompt lists the others." : ""}`;
8459
+ }
8460
+ /**
8461
+ * Checks whether a text is one nonblank line: it holds a code point other than white space and
8462
+ * default-ignorable code points (`ARGUMENT_BLANK_PATTERN`), and no control, format, line-separator, or
8463
+ * paragraph-separator code point (`ARGUMENT_CONTROL_PATTERN`).
8464
+ *
8465
+ * @remarks
8466
+ * The class is the one `renderArguments` encodes. A memo's name and description render in the memos
8467
+ * index one line each, so `remember` refuses a value outside this check.
8468
+ *
8469
+ * @param text - The text to check
8470
+ * @returns True if the text is one nonblank line; false otherwise
8471
+ *
8472
+ * @example
8473
+ * ```ts
8474
+ * matchesPlainLine('Reply tone') // true
8475
+ * matchesPlainLine('Reply\ntone') // false
8476
+ * matchesPlainLine(' ') // false
8477
+ * ```
8478
+ */
8479
+ function matchesPlainLine(text) {
8480
+ return !ARGUMENT_BLANK_PATTERN.test(text) && !ARGUMENT_CONTROL_PATTERN.test(text);
8481
+ }
8482
+ /**
8483
+ * Checks whether two ceilings carry the same lists of what a head renders: `instructions`,
8484
+ * `skills`, `memos`, `files`, and `workspaces`.
8485
+ *
8486
+ * @remarks
8487
+ * Each list compares by its members in order, and an absent list equals only an absent list,
8488
+ * because `undefined` admits everything and `[]` admits nothing. The `tools` list is not compared:
8489
+ * it reaches the tools block, never the head.
8490
+ *
8491
+ * @param left - One ceiling's lists
8492
+ * @param right - The other ceiling's lists
8493
+ * @returns True if every compared list matches; false otherwise
8494
+ *
8495
+ * @example
8496
+ * ```ts
8497
+ * matchesHeadLists({ skills: ['refunds'] }, { skills: ['refunds'], tools: [] }) // true
8498
+ * matchesHeadLists({ skills: [] }, {}) // false
8499
+ * ```
8500
+ */
8501
+ function matchesHeadLists(left, right) {
8502
+ return [
8503
+ [left.instructions, right.instructions],
8504
+ [left.skills, right.skills],
8505
+ [left.memos, right.memos],
8506
+ [left.files, right.files],
8507
+ [left.workspaces, right.workspaces]
8508
+ ].every(([one, other]) => one === void 0 || other === void 0 ? one === other : one.length === other.length && one.every((key, index) => key === other[index]));
8509
+ }
8510
+ /**
8511
+ * Resolves what a turn shows: the conversation's record, and the given workspace, within the
8512
+ * ceiling and the registries.
8513
+ *
8514
+ * @remarks
8515
+ * The caller reads the ceiling, so a turn reads each scope list one time. The skills are those
8516
+ * {@link collectDisclosure} reads from the conversation, in load order, keeping each that the skill
8517
+ * registry holds and the ceiling's `skills` list admits; an unregistered or excluded name shows
8518
+ * nothing. The workspace is the conversation's last switch, else the given one, kept only when the
8519
+ * workspace registry holds it and the ceiling's `workspaces` list admits it. The record counts only
8520
+ * the built-ins in `builtins`, as {@link collectDisclosure} states.
8521
+ *
8522
+ * @param context - The agent's context, whose scope, skills, and workspaces it reads
8523
+ * @param conversation - The conversation whose record to read
8524
+ * @param workspace - The `workspace` option of the run or the agent, or `undefined`
8525
+ * @param ceiling - The ceiling the turn read: the context scope intersected with the run scope
8526
+ * @param builtins - The built-ins the run enables
8527
+ * @returns The shown skills, in order, and the shown workspace when one is
8528
+ *
8529
+ * @example
8530
+ * ```ts
8531
+ * resolveDisclosure(agent.context, agent.context.messages, 'orders', {}, []) // { skills: [], workspace: 'orders' } when orders is registered
8532
+ * ```
8533
+ */
8534
+ function resolveDisclosure(context, conversation, workspace, ceiling, builtins) {
8535
+ const recorded = collectDisclosure(conversation, builtins);
8536
+ const admitted = new Set(filterAllowList(ceiling.skills, context.skills.skills(), (skill) => skill.name).map((skill) => skill.name));
8537
+ const skills = recorded.skills.filter((name) => admitted.has(name));
8538
+ const selected = recorded.workspace ?? workspace;
8539
+ return selected !== void 0 && context.workspaces.workspace(selected) !== void 0 && filterAllowList(ceiling.workspaces, [selected], (id) => id).length > 0 ? {
8540
+ skills,
8541
+ workspace: selected
8542
+ } : { skills };
8543
+ }
8544
+ /**
8545
+ * Collects the loaded skills and the selected workspace a conversation's stored built-in calls
8546
+ * record, counting only the built-ins a run enables.
8547
+ *
8548
+ * @remarks
8549
+ * Pure. It reads each section's retained originals, oldest first, then the live tail, and pairs
8550
+ * each tool message with the call that owns it through {@link collectToolGroups} and
8551
+ * {@link findToolCall}. It then folds the pairs in message order: a `load` whose message content
8552
+ * equals `BUILTIN_NOTES.loaded` adds its `skill`, an `unload` with `BUILTIN_NOTES.unloaded` removes
8553
+ * it, and a `switch` with `BUILTIN_NOTES.switched` selects its `workspace`. Each call's arguments
8554
+ * are admitted through the built-in's contract in `builtinToolContracts`, lossless repairs
8555
+ * included, as its tool's door admits them, so a `{ skill: 1 }` the door repaired to `'1'` counts
8556
+ * as `'1'`; arguments the contract refuses change nothing. A skill loaded again while shown keeps
8557
+ * its place, and one loaded again after its unload goes last. Any other message and a denied or
8558
+ * refused call change nothing. The result holds `workspace` only when a switch succeeded.
8559
+ *
8560
+ * A record counts only while its built-in is in `builtins`, so a host tool that holds a built-in's
8561
+ * name on a run that does not enable it shows nothing; with none of `load`, `unload`, and `switch`
8562
+ * enabled, nothing is read. A stored record cannot tell its writer, so one a host tool wrote under a
8563
+ * built-in's name while that built-in was off counts after a run enables it, bounded by the registry
8564
+ * and the ceiling as every record is.
8565
+ *
8566
+ * @param conversation - The conversation whose stored messages record the calls
8567
+ * @param builtins - The built-ins the run enables
8568
+ * @returns The skills in load order and the last selected workspace
8569
+ *
8570
+ * @example
8571
+ * ```ts
8572
+ * import { collectDisclosure, createConversation } from '@orkestrel/agent'
8573
+ *
8574
+ * collectDisclosure(createConversation(), ['load', 'unload']) // { skills: [] }
8575
+ * ```
8576
+ */
8577
+ function collectDisclosure(conversation, builtins) {
8578
+ const counted = new Set(builtins.filter((name) => name === "load" || name === "unload" || name === "switch"));
8579
+ if (counted.size === 0) return { skills: [] };
8580
+ const stored = [...conversation.sections.flatMap((section) => section.messages), ...conversation.messages()];
8581
+ const owners = new Map(collectToolGroups(stored).flatMap((group) => group.flatMap((message) => {
8582
+ const call = findToolCall(group, message);
8583
+ return call === void 0 ? [] : [[message, call]];
8584
+ })));
8585
+ return stored.reduce((shown, message) => {
8586
+ const call = owners.get(message);
8587
+ const name = call?.name;
8588
+ if (call === void 0 || !isAgentBuiltin(name) || !counted.has(name)) return shown;
8589
+ const note = name === "load" ? BUILTIN_NOTES.loaded : name === "unload" ? BUILTIN_NOTES.unloaded : BUILTIN_NOTES.switched;
8590
+ if (message.content !== note) return shown;
8591
+ const admitted = admitValue(builtinToolContracts[name].contract, { ...call.arguments });
8592
+ const skill = admitted.success ? admitted.value.value["skill"] : void 0;
8593
+ const workspace = admitted.success ? admitted.value.value["workspace"] : void 0;
8594
+ if (name === "load") return !isString(skill) || shown.skills.includes(skill) ? shown : {
8595
+ ...shown,
8596
+ skills: [...shown.skills, skill]
8597
+ };
8598
+ if (name === "unload") return !isString(skill) ? shown : {
8599
+ ...shown,
8600
+ skills: shown.skills.filter((one) => one !== skill)
8601
+ };
8602
+ return !isString(workspace) ? shown : {
8603
+ skills: shown.skills,
8604
+ workspace
8605
+ };
8606
+ }, { skills: [] });
8607
+ }
8608
+ // src/core/agents/AgentRun.ts
8609
+ /**
8610
+ * Holds one agent run's own tools and the view its turns and builds share: the ceiling a turn
8611
+ * read, what it shows, what it advertises, and what the working head was built with.
8612
+ *
8613
+ * @remarks
8614
+ * `Agent` creates one per run, so no public signature names this class. The run's built-in tools
8615
+ * live in a tool manager the run owns and never changes after construction, so a tool a host
8616
+ * registers under a built-in's name is never read: `tool` and `execute` answer a built-in's name
8617
+ * from the run's manager and every other name from the host's. Each handler reads the ceiling when
8618
+ * it runs, the context scope intersected with the run scope at that moment, never a turn's copy.
8619
+ */
8620
+ var AgentRun = class {
8621
+ #context;
8622
+ #conversation;
8623
+ #scope;
8624
+ #workspace;
8625
+ #enabled;
8626
+ #builtins;
8627
+ #tools;
8628
+ #ceiling = {};
8629
+ #shown = { skills: [] };
8630
+ #ids = [];
8631
+ #advertised = [];
8632
+ #snapshot;
8633
+ #selection;
8634
+ #length = 0;
8635
+ #head;
8636
+ /**
8637
+ * Creates the run's own tools for the enabled built-ins.
8638
+ *
8639
+ * @param context - The agent's context
8640
+ * @param conversation - The conversation the run is bound to
8641
+ * @param scope - The run scope, or `undefined`
8642
+ * @param workspace - The workspace the run renders in place of the active one, already checked, or `undefined`
8643
+ * @param builtins - The enabled built-ins, already checked
8644
+ */
8645
+ constructor(context, conversation, scope, workspace, builtins) {
8646
+ this.#context = context;
8647
+ this.#conversation = conversation;
8648
+ this.#scope = scope;
8649
+ this.#workspace = workspace;
8650
+ this.#enabled = builtins;
8651
+ this.#builtins = new Set(builtins);
8652
+ this.#tools = createToolManager();
8653
+ this.#tools.add(builtins.map((name) => createBuiltinTool(name, (args) => this.#handle(name, args))));
8654
+ }
8655
+ /**
8656
+ * Returns the conversation the run is bound to.
8657
+ *
8658
+ * @returns The conversation
8659
+ */
8660
+ get conversation() {
8661
+ return this.#conversation;
8662
+ }
8663
+ /**
8664
+ * Returns the run scope.
8665
+ *
8666
+ * @returns The scope, or undefined when the run has none
8667
+ */
8668
+ get scope() {
8669
+ return this.#scope;
8670
+ }
8671
+ /**
8672
+ * Returns an owned scope holding the run scope's lists as the last `observe` read them, so a build
8673
+ * renders by the turn's one read and never reads the run scope again.
8674
+ *
8675
+ * @returns The owned scope, or undefined when the run has none
8676
+ */
8677
+ get snapshot() {
8678
+ return this.#snapshot;
8679
+ }
8680
+ /**
8681
+ * Returns the ceiling the last `observe` read: the context scope intersected with the run scope.
8682
+ *
8683
+ * @returns The ceiling's lists
8684
+ */
8685
+ get ceiling() {
8686
+ return this.#ceiling;
8687
+ }
8688
+ /**
8689
+ * Returns the definitions the last `observe` advertised.
8690
+ *
8691
+ * @returns The advertised definitions
8692
+ */
8693
+ get advertised() {
8694
+ return this.#advertised;
8695
+ }
8696
+ /**
8697
+ * Returns what a build renders from the last `observe`: the shown skills and workspace, or
8698
+ * undefined when it shows neither.
8699
+ *
8700
+ * @returns The shown value, or undefined
8701
+ */
8702
+ get disclosure() {
8703
+ return this.#shown.skills.length === 0 && this.#shown.workspace === void 0 ? void 0 : this.#shown;
8704
+ }
8705
+ /**
8706
+ * Returns whether the last `observe` advertised `switch`, which lists the workspaces in the head.
8707
+ *
8708
+ * @returns True if `switch` is advertised; false otherwise
8709
+ */
8710
+ get switchable() {
8711
+ return this.#advertised.some((definition) => definition.name === "switch");
8712
+ }
8713
+ /**
8714
+ * Returns the selection the working head rendered.
8715
+ *
8716
+ * @returns The selection, or undefined before the first build
8717
+ */
8718
+ get selection() {
8719
+ return this.#selection;
8720
+ }
8721
+ /**
8722
+ * Returns the length of the array the working head was built as.
8723
+ *
8724
+ * @returns The length, 0 before the first build
8725
+ */
8726
+ get length() {
8727
+ return this.#length;
8728
+ }
8729
+ /**
8730
+ * Reads the ceiling, resolves what the run shows within it, and computes what it advertises.
8731
+ *
8732
+ * @remarks
8733
+ * The ceiling's lists are each read one time. The conversation's record is read only while
8734
+ * `load`, `unload`, or `switch` is enabled, and only the records of an enabled built-in count.
8735
+ * Registered skills hold their tools back only while `load` is enabled. The view compared with
8736
+ * the working head's is the ceiling's `instructions`, `skills`, `memos`, `files`, and
8737
+ * `workspaces` lists, the shown skills by id, the shown workspace, and whether `switch` is
8738
+ * advertised.
8739
+ *
8740
+ * @returns True if the working head was built with another view and must be rebuilt; false otherwise
8741
+ */
8742
+ observe() {
8743
+ const lists = this.#scope === void 0 ? void 0 : intersectFilters(void 0, this.#scope);
8744
+ const ceiling = intersectFilters(this.#context.scope, lists);
8745
+ this.#snapshot = lists === void 0 ? void 0 : createScope({
8746
+ name: "run",
8747
+ ...lists
8748
+ });
8749
+ const shown = resolveDisclosure(this.#context, this.#conversation, this.#workspace, ceiling, this.#enabled);
8750
+ this.#ceiling = ceiling;
8751
+ this.#shown = shown;
8752
+ this.#ids = shown.skills.flatMap((name) => this.#context.skills.skill(name)?.id ?? []);
8753
+ this.#advertised = filterAdvertisedTools(this.#candidates(ceiling), ceiling.tools, this.#builtins.has("load") ? this.#context.skills.skills() : [], shown.skills);
8754
+ const head = this.#head;
8755
+ return head === void 0 || !matchesHeadLists(head.ceiling, ceiling) || head.ids.length !== this.#ids.length || head.ids.some((id, index) => id !== this.#ids[index]) || head.workspace !== shown.workspace || head.switchable !== this.switchable;
8756
+ }
8757
+ /**
8758
+ * Records what the working head was built with: the selection, the built array's length, and
8759
+ * the view the last `observe` resolved.
8760
+ *
8761
+ * @param selection - The selection the build rendered
8762
+ * @param length - The length of the built array
8763
+ */
8764
+ record(selection, length) {
8765
+ this.#selection = selection;
8766
+ this.#length = length;
8767
+ this.#head = {
8768
+ ceiling: this.#ceiling,
8769
+ ids: this.#ids,
8770
+ workspace: this.#shown.workspace,
8771
+ switchable: this.switchable
8772
+ };
8773
+ }
8774
+ /**
8775
+ * Finds the tool a call names: the run's own for a built-in's name, the host's for any other.
8776
+ *
8777
+ * @param name - The tool name
8778
+ * @returns The tool, or undefined when none is registered under the name
8779
+ */
8780
+ tool(name) {
8781
+ return this.#builtins.has(name) ? this.#tools.tool(name) : this.#context.tools.tool(name);
8782
+ }
8783
+ /**
8784
+ * Executes one call through the run's manager for a built-in's name, and the host's for any other.
8785
+ *
8786
+ * @param call - The call to execute
8787
+ * @param context - The execution context
8788
+ * @returns The correlated result
8789
+ */
8790
+ execute(call, context) {
8791
+ return this.#builtins.has(call.name) ? this.#tools.execute(call, context) : this.#context.tools.execute(call, context);
8792
+ }
8793
+ #candidates(ceiling) {
8794
+ return [...this.#context.tools.definitions().filter((one) => !this.#builtins.has(one.name)), ...filterBuiltinCandidates(this.#tools.definitions(), ceiling)];
8795
+ }
8796
+ #live() {
8797
+ return intersectFilters(this.#context.scope, this.#scope);
8798
+ }
8799
+ #handle(name, args) {
8800
+ switch (name) {
8801
+ case "load": return this.#load(args.skill);
8802
+ case "unload": return this.#unload(args.skill);
8803
+ case "memo": return this.#memo(args.name);
8804
+ case "remember": return this.#remember(args.name, args.description, args.content);
8805
+ case "switch": return this.#switch(args.workspace);
8806
+ }
8807
+ }
8808
+ #load(skill) {
8809
+ const admitted = filterAllowList(this.#live().skills, this.#context.skills.skills(), (one) => one.name).map((one) => one.name);
8810
+ if (!isString(skill) || !admitted.includes(skill)) throw new ToolError("ARGUMENTS", describeCandidates("skill you can load", admitted));
8811
+ return BUILTIN_NOTES.loaded;
8812
+ }
8813
+ #unload(skill) {
8814
+ const loaded = collectDisclosure(this.#conversation, this.#enabled).skills;
8815
+ if (!isString(skill) || !loaded.includes(skill)) throw new ToolError("ARGUMENTS", describeCandidates("skill you loaded", loaded));
8816
+ return BUILTIN_NOTES.unloaded;
8817
+ }
8818
+ #memo(name) {
8819
+ const admitted = filterAllowList(this.#live().memos, this.#context.memos.memos(), (one) => one.name);
8820
+ const memo = admitted.find((one) => one.name === name);
8821
+ if (memo === void 0) throw new ToolError("ARGUMENTS", describeCandidates("memo you can read", admitted.map((one) => one.name)));
8822
+ return memo.content;
8823
+ }
8824
+ #remember(name, description, content) {
8825
+ const allowed = this.#live().memos;
8826
+ if (allowed === void 0 || allowed.length === 0) throw new ToolError("ARGUMENTS", "No memo can be written here: the host lists no memo name you may write. Continue without saving it.");
8827
+ if (!isString(name) || !allowed.includes(name)) throw new ToolError("ARGUMENTS", describeCandidates("memo you may write", allowed));
8828
+ if (!isString(description) || !isString(content)) throw new ToolError("ARGUMENTS", "Send description and content as text.");
8829
+ if (!matchesPlainLine(name) || !matchesPlainLine(description)) throw new ToolError("ARGUMENTS", "The name and the description must each be one line of visible text, with no line break or control character. Send them again on one line.");
8830
+ const current = this.#context.memos.memo(name);
8831
+ if (current !== void 0 && current.origin?.conversation !== this.#conversation.id) throw new ToolError("ARGUMENTS", "A memo with that name exists and this conversation did not write it, so it stays as it is. Read it with memo, or write a name you created.");
8832
+ this.#context.memos.add({
8833
+ name,
8834
+ description,
8835
+ content,
8836
+ origin: { conversation: this.#conversation.id }
8837
+ });
8838
+ return BUILTIN_NOTES.remembered;
8839
+ }
8840
+ #switch(workspace) {
8841
+ const allowed = this.#live().workspaces;
8842
+ if (allowed === void 0 || allowed.length === 0) throw new ToolError("ARGUMENTS", "No workspace can be selected here: the host lists no workspace you may select. Continue with the workspace you have.");
8843
+ const admitted = filterAllowList(allowed, this.#context.workspaces.workspaces(), (one) => one.id).map((one) => one.id);
8844
+ if (!isString(workspace) || !admitted.includes(workspace)) throw new ToolError("ARGUMENTS", describeCandidates("workspace you can select", admitted));
8845
+ return BUILTIN_NOTES.switched;
8846
+ }
8847
+ };
8848
+ // src/core/agents/ChannelCell.ts
8849
+ /**
8850
+ * Holds one value a `Channel` buffers and the cell pushed after it.
8851
+ *
8852
+ * @remarks
8853
+ * A `Channel` keeps its unread values as a chain of these cells, from its `#head` cell to its
8854
+ * `#tail` cell, so no public signature names this class. The `#next` field is a latch: the
8855
+ * `link` method sets it once, and a later call keeps the first cell.
8856
+ */
8857
+ var ChannelCell = class {
8858
+ #value;
8859
+ #next;
8860
+ /**
8861
+ * Holds a value with no next cell.
8862
+ *
8863
+ * @param value - The value the cell holds
8864
+ */
8865
+ constructor(value) {
8866
+ this.#value = value;
8867
+ }
8868
+ /**
8869
+ * Returns the value the cell holds.
8870
+ *
8871
+ * @returns The value
8872
+ */
8873
+ get value() {
8874
+ return this.#value;
8875
+ }
8876
+ /**
8877
+ * Returns the cell pushed after this one.
8878
+ *
8879
+ * @returns The next cell, or undefined before one is linked
8880
+ */
8881
+ get next() {
8882
+ return this.#next;
8883
+ }
8884
+ /**
8885
+ * Links the cell pushed after this one, once.
8886
+ *
8887
+ * @param cell - The cell pushed after this one
8888
+ */
8889
+ link(cell) {
8890
+ this.#next ??= cell;
8891
+ }
8892
+ };
8893
+ // src/core/agents/Channel.ts
8894
+ /**
8895
+ * Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`)
8896
+ * and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live
8897
+ * through the `drain` async-iterator. Decoupling write from read is what lets a producer make
8898
+ * progress without a consumer pulling, and it is why an agent's `result` settles whether or not
8899
+ * its `events` are drained.
8900
+ *
8901
+ * @remarks
8902
+ * A waiting `drain` call parks its void resolver in the `#waiting` field. The `push` method links a
8903
+ * cell after the `#tail` cell, and the `close` and `fail` methods flag the end; each then fires and
8904
+ * clears every parked resolver, so each parked reader wakes, reads the `#head` cell, and either
8905
+ * takes the next chunk, returns (on `close`), throws (on `fail`), or parks again when another
8906
+ * reader took the chunk first. Taking a chunk reads its value and moves `#head` to the next cell
8907
+ * synchronously, so each value reaches exactly one reader, a push and a take each cost constant
8908
+ * time, and every taken cell but the newest is released at once; the `#tail` field holds the newest
8909
+ * cell until the next push links after it, so a channel retains at most one taken value. A reader
8910
+ * suspended at its `yield` expression holds only the value it took, never a cell, so the bound on
8911
+ * retained values covers both the channel's fields and a suspended reader.
8912
+ * A `return()` issued while a read is parked waits for the next `push`, `close`, or `fail`.
8913
+ * The parked read takes a pushed value before that `return()` settles.
8914
+ *
8915
+ * @example
8916
+ * ```ts
8917
+ * import { Channel } from '@orkestrel/agent'
8918
+ *
8919
+ * const channel = new Channel<number>()
8920
+ * channel.push(1)
8921
+ * channel.close()
8922
+ * for await (const value of channel.drain()) {
8923
+ * value // 1
8924
+ * }
8925
+ * ```
8926
+ */
8927
+ var Channel = class {
8928
+ #head;
8929
+ #tail;
8930
+ #waiting = [];
8931
+ #closed = false;
8932
+ #failure;
8933
+ push(value) {
8934
+ const cell = new ChannelCell(value);
8935
+ this.#tail?.link(cell);
8936
+ this.#tail = cell;
8937
+ this.#head ??= cell;
8938
+ this.#signal();
8939
+ }
8940
+ close() {
8941
+ this.#closed = true;
8942
+ this.#signal();
8943
+ }
8944
+ fail(error) {
8945
+ if (this.#failure === void 0) this.#failure = { error };
8946
+ this.#closed = true;
8947
+ this.#signal();
8948
+ }
8949
+ async *drain() {
8950
+ for (;;) {
8951
+ while (this.#head !== void 0) {
8952
+ const value = this.#head.value;
8953
+ this.#head = this.#head.next;
8954
+ yield value;
8955
+ }
8956
+ if (this.#failure !== void 0) throw this.#failure.error;
8957
+ if (this.#closed) return;
8958
+ await this.#park();
8959
+ }
8960
+ }
8961
+ #signal() {
8962
+ const waiting = this.#waiting;
8963
+ this.#waiting = [];
8964
+ for (const wake of waiting) wake();
8965
+ }
8966
+ #park() {
8967
+ return new Promise((resolve) => {
8968
+ this.#waiting = [...this.#waiting, resolve];
8969
+ });
8970
+ }
8971
+ };
7485
8972
  // src/core/agents/Agent.ts
7486
8973
  /**
7487
8974
  * Composes a {@link ProviderInterface}, an {@link AgentContext}, and a
@@ -7546,9 +9033,12 @@ var Agent = class {
7546
9033
  #window;
7547
9034
  #strict;
7548
9035
  #emitter;
9036
+ #builtins;
9037
+ #workspace;
7549
9038
  #settled = "idle";
7550
9039
  #runs = /* @__PURE__ */ new Map();
7551
9040
  constructor(provider, options) {
9041
+ refuseOptionKeys(options, AGENT_OPTION_KEYS, "Agent", "AgentOptions");
7552
9042
  if (options?.tools !== void 0 && options.authority === void 0) throw new AgentError("AUTHORITY", "tools are set and no authority is; pass authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }) to allow every call, or rules with a deny fallback");
7553
9043
  this.#limit = requireLimit(options?.limit ?? 10);
7554
9044
  this.#id = crypto.randomUUID();
@@ -7565,6 +9055,9 @@ var Agent = class {
7565
9055
  ...options?.conversations === void 0 ? {} : { conversations: options.conversations },
7566
9056
  ...options?.select === void 0 ? {} : { select: options.select }
7567
9057
  });
9058
+ this.#builtins = requireBuiltins(options?.builtins, this.#context.tools);
9059
+ if (this.#builtins.length > 0 && options?.authority === void 0) throw new AgentError("AUTHORITY", "builtins are set and no authority is; pass authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }) to allow every call, or rules with a deny fallback");
9060
+ this.#workspace = requireWorkspace(options?.workspace);
7568
9061
  this.#timeoutMs = options?.timeout;
7569
9062
  this.#budget = options?.budget;
7570
9063
  this.#allowance = options?.allowance;
@@ -7591,6 +9084,7 @@ var Agent = class {
7591
9084
  return this.stream(options).result;
7592
9085
  }
7593
9086
  stream(options) {
9087
+ refuseOptionKeys(options, AGENT_RUN_KEYS, "Agent", "AgentRunOptions");
7594
9088
  const prompt = options?.prompt;
7595
9089
  if (prompt !== void 0 && !agentPromptContract.is(prompt)) {
7596
9090
  const faults = attempt(() => describeFaults(agentPromptContract.audit(prompt), agentPromptContract.schema));
@@ -7603,11 +9097,13 @@ var Agent = class {
7603
9097
  }
7604
9098
  });
7605
9099
  }
9100
+ const workspace = requireWorkspace(options?.workspace) ?? this.#workspace;
7606
9101
  const limit = options?.limit === void 0 ? this.#limit : requireLimit(options.limit);
7607
9102
  const budget = requireBudget(options?.budget ?? this.#budget, "budget");
7608
9103
  const allowance = requireBudget(options?.allowance ?? this.#allowance, "allowance");
7609
9104
  const held = [budget, allowance].filter((one, index, all) => one !== void 0 && all.indexOf(one) === index);
7610
9105
  if (this.#runs.size > 0 && (this.#window !== void 0 || [...this.#runs.values()].some((live) => live.budgets.some((one) => held.includes(one))))) throw new AgentError("CONCURRENCY", "a live run on this agent holds the window or this budget or allowance instance; use separate agents or distinct instances per run", { context: { agent: this.#id } });
9106
+ const scope = requireScope(options?.scope);
7611
9107
  const conversation = requireConversation(options?.conversation) ?? this.#context.messages;
7612
9108
  if ([...this.#runs.values()].some((live) => live.conversation === conversation)) throw new AgentError("CONCURRENCY", "a live run on this agent holds this conversation; await it or bind the run to another conversation", { context: {
7613
9109
  agent: this.#id,
@@ -7631,7 +9127,8 @@ var Agent = class {
7631
9127
  this.#emitter.emit("start", this.id);
7632
9128
  const channel = new Channel();
7633
9129
  const settled = Promise.withResolvers();
7634
- this.#drive(abort, conversation, channel, options?.think, options?.schema, limit, budget, allowance).then((outcome) => this.#finish(abort, timeout, channel, settled, limit, outcome), (error) => this.#fail(abort, timeout, channel, settled, error));
9130
+ const run = new AgentRun(this.#context, conversation, scope, workspace, this.#builtins);
9131
+ this.#drive(abort, run, channel, options?.think, options?.schema, limit, budget, allowance).then((outcome) => this.#finish(abort, timeout, channel, settled, limit, outcome), (error) => this.#fail(abort, timeout, channel, settled, error));
7635
9132
  settled.promise.catch(() => {});
7636
9133
  return {
7637
9134
  events: this.#drainEvents(channel, abort),
@@ -7661,10 +9158,10 @@ var Agent = class {
7661
9158
  settled.reject(error);
7662
9159
  this.#emitter.emit("error", error);
7663
9160
  }
7664
- async #drive(abort, conversation, channel, think, schema, limit, budget, allowance) {
7665
- const run = this.#execute(abort, conversation, think, schema, limit, budget, allowance);
9161
+ async #drive(abort, run, channel, think, schema, limit, budget, allowance) {
9162
+ const steps = this.#execute(abort, run, think, schema, limit, budget, allowance);
7666
9163
  for (;;) {
7667
- const next = await run.next();
9164
+ const next = await steps.next();
7668
9165
  if (next.done === true) return next.value;
7669
9166
  channel.push(next.value);
7670
9167
  }
@@ -7676,15 +9173,16 @@ var Agent = class {
7676
9173
  abort.abort();
7677
9174
  }
7678
9175
  }
7679
- async *#execute(abort, conversation, think, schema, limit, budget, allowance) {
9176
+ async *#execute(abort, run, think, schema, limit, budget, allowance) {
9177
+ const conversation = run.conversation;
7680
9178
  const last = conversation.view().at(-1);
7681
9179
  const request = last?.role === "user" ? last : void 0;
7682
- const selection = this.#select(conversation, request, abort, budget);
9180
+ run.observe();
9181
+ const selection = this.#select(run, request, abort, budget);
7683
9182
  const entry = selection === void 0 ? {
7684
- messages: this.#build(conversation),
9183
+ messages: this.#build(run),
7685
9184
  usage: void 0
7686
9185
  } : await selection;
7687
- const tools = this.#context.tools;
7688
9186
  const options = think === void 0 && schema === void 0 ? void 0 : {
7689
9187
  ...think === void 0 ? {} : { think },
7690
9188
  ...schema === void 0 ? {} : { schema }
@@ -7693,14 +9191,14 @@ var Agent = class {
7693
9191
  const turns = [];
7694
9192
  while (turns.length < limit && (turns.at(-1)?.outcome ?? "tools") === "tools") {
7695
9193
  const index = turns.length;
7696
- const base = turns.at(-1)?.messages ?? entry.messages;
9194
+ const prior = turns.at(-1)?.messages ?? entry.messages;
7697
9195
  const futile = turns.at(-1)?.futile ?? false;
7698
9196
  const stopped = {
7699
9197
  content: "",
7700
9198
  thinking: void 0,
7701
9199
  usage: void 0,
7702
9200
  spent: void 0,
7703
- messages: base,
9201
+ messages: prior,
7704
9202
  outcome: "cancel",
7705
9203
  partial: true,
7706
9204
  futile,
@@ -7719,9 +9217,10 @@ var Agent = class {
7719
9217
  turns.push(stopped);
7720
9218
  continue;
7721
9219
  }
7722
- const names = this.#context.scope?.tools?.slice();
7723
- const advertised = filterAllowList(names, tools.definitions(), (definition) => definition.name);
7724
- const held = new Map(advertised.map((definition) => [definition.name, tools.tool(definition.name)]));
9220
+ const base = run.observe() ? this.#refresh(run, prior) : prior;
9221
+ const names = run.ceiling.tools;
9222
+ const advertised = run.advertised;
9223
+ const held = new Map(advertised.map((definition) => [definition.name, run.tool(definition.name)]));
7725
9224
  const definitions = advertised.length > 0 ? advertised : void 0;
7726
9225
  const composed = this.#compose(base, definitions, options);
7727
9226
  const admitted = this.#window === void 0 ? {
@@ -7729,7 +9228,7 @@ var Agent = class {
7729
9228
  messages: base,
7730
9229
  spent: void 0,
7731
9230
  futile
7732
- } : await this.#admit(this.#window, conversation, composed, base, request, index > 0, futile, abort, budget);
9231
+ } : await this.#admit(this.#window, run, composed, base, request, index > 0, futile, abort, budget);
7733
9232
  if (admitted.dispatch === void 0) {
7734
9233
  turns.push({
7735
9234
  ...stopped,
@@ -7739,12 +9238,25 @@ var Agent = class {
7739
9238
  });
7740
9239
  continue;
7741
9240
  }
9241
+ const dispatch = admitted.dispatch;
9242
+ Object.freeze(dispatch.messages);
9243
+ if (dispatch.tools !== void 0) Object.freeze(dispatch.tools);
9244
+ this.#emitter.emit("request", index, Object.freeze(dispatch), conversation);
9245
+ if (abort.signal.aborted) {
9246
+ turns.push({
9247
+ ...stopped,
9248
+ messages: admitted.messages,
9249
+ spent: admitted.spent,
9250
+ futile: admitted.futile
9251
+ });
9252
+ continue;
9253
+ }
7742
9254
  const streamed = [];
7743
9255
  const meter = allowance === void 0 ? void 0 : createTokenMeter({
7744
9256
  budget: allowance,
7745
9257
  estimator: estimateTokens
7746
9258
  });
7747
- const provided = yield* this.#provide(admitted.dispatch, abort.signal, streamed, meter);
9259
+ const provided = yield* this.#provide(dispatch, abort.signal, streamed, meter);
7748
9260
  const settled = this.#reconcile(provided, abort, streamed, admitted, meter, budget, allowance);
7749
9261
  if (!provided.success) {
7750
9262
  turns.push({
@@ -7767,8 +9279,8 @@ var Agent = class {
7767
9279
  if (result.tools !== void 0 && result.tools.length > 0) {
7768
9280
  const admittedCalls = filterAllowList(names, result.tools, (call) => call.name);
7769
9281
  const authorization = this.#authorize(result.tools, admittedCalls, advertised, held);
7770
- if (authorization.asked.length > 0 && !abort.signal.aborted) yield* this.#approve(tools, authorization, abort.signal);
7771
- if (!abort.signal.aborted) this.#confirm(tools, authorization, advertised);
9282
+ if (authorization.asked.length > 0 && !abort.signal.aborted) yield* this.#approve(run, authorization, abort.signal);
9283
+ if (!abort.signal.aborted) this.#confirm(run, authorization, advertised);
7772
9284
  if (abort.signal.aborted) {
7773
9285
  turns.push({
7774
9286
  ...settled,
@@ -7783,7 +9295,7 @@ var Agent = class {
7783
9295
  calls: result.tools,
7784
9296
  ...recorded
7785
9297
  });
7786
- const results = await this.#dispatch(tools, result.tools, abort.signal, authorization, advertised);
9298
+ const results = await this.#dispatch(run, result.tools, abort.signal, authorization, advertised);
7787
9299
  const replies = [];
7788
9300
  for (const [position, call] of result.tools.entries()) {
7789
9301
  const dispatched = results[position];
@@ -7879,11 +9391,11 @@ var Agent = class {
7879
9391
  #compose(messages, tools, options) {
7880
9392
  return {
7881
9393
  messages: [...stripThinking(messages, this.#replay)],
7882
- ...tools === void 0 ? {} : { tools },
9394
+ ...tools === void 0 ? {} : { tools: [...tools] },
7883
9395
  ...options === void 0 ? {} : { options }
7884
9396
  };
7885
9397
  }
7886
- async #admit(window, conversation, composed, messages, request, latch, futile, abort, budget) {
9398
+ async #admit(window, run, composed, messages, request, latch, futile, abort, budget) {
7887
9399
  window.clear();
7888
9400
  window.consume(composed);
7889
9401
  if (!window.exhausted) return {
@@ -7898,15 +9410,16 @@ var Agent = class {
7898
9410
  spent: void 0,
7899
9411
  futile
7900
9412
  };
9413
+ const conversation = run.conversation;
7901
9414
  if (!conversation.summarizable || futile) return {
7902
9415
  dispatch: this.#enforce(window, composed),
7903
9416
  messages,
7904
9417
  spent: void 0,
7905
9418
  futile
7906
9419
  };
7907
- return conversation.compact({ signal: abort.signal }).then((section) => this.#refold(section, window, conversation, composed, messages, request, latch, abort, budget), (error) => this.#unfold(error, composed, messages, abort));
9420
+ return conversation.compact({ signal: abort.signal }).then((section) => this.#refold(section, window, run, composed, messages, request, latch, abort, budget), (error) => this.#unfold(error, composed, messages, abort));
7908
9421
  }
7909
- async #refold(section, window, conversation, composed, messages, request, latch, abort, budget) {
9422
+ async #refold(section, window, run, composed, messages, request, latch, abort, budget) {
7910
9423
  if (abort.signal.aborted) return {
7911
9424
  dispatch: void 0,
7912
9425
  messages,
@@ -7919,9 +9432,9 @@ var Agent = class {
7919
9432
  spent: void 0,
7920
9433
  futile: latch
7921
9434
  };
7922
- const selection = this.#select(conversation, request, abort, budget);
9435
+ const selection = this.#select(run, request, abort, budget);
7923
9436
  const rebuilt = selection === void 0 ? {
7924
- messages: this.#build(conversation),
9437
+ messages: this.#build(run),
7925
9438
  usage: void 0
7926
9439
  } : await selection;
7927
9440
  if (abort.signal.aborted) return {
@@ -7970,47 +9483,61 @@ var Agent = class {
7970
9483
  } });
7971
9484
  return request;
7972
9485
  }
7973
- #select(conversation, request, abort, budget) {
7974
- const pending = request === void 0 ? void 0 : this.#context.select(conversation, request, abort.signal);
7975
- return pending === void 0 ? void 0 : pending.then((selection) => this.#adopt(conversation, selection, abort, budget), (error) => this.#reject(conversation, error, abort));
9486
+ #select(run, request, abort, budget) {
9487
+ const pending = request === void 0 ? void 0 : this.#context.select(run.conversation, request, abort.signal, run.scope);
9488
+ return pending === void 0 ? void 0 : pending.then((selection) => this.#adopt(run, selection, abort, budget), (error) => this.#reject(run, error, abort));
7976
9489
  }
7977
- #adopt(conversation, selection, abort, budget) {
9490
+ #adopt(run, selection, abort, budget) {
7978
9491
  const usage = selection.usage === void 0 ? void 0 : sanitizeUsage(selection.usage);
7979
9492
  if (usage !== void 0) chargeUsage(budget, usage, 0);
7980
9493
  if (abort.signal.aborted) return {
7981
- messages: this.#build(conversation),
9494
+ messages: this.#build(run),
7982
9495
  usage
7983
9496
  };
7984
9497
  if (selection.fault !== void 0) {
7985
9498
  this.#emitter.emit("fault", selection.fault);
7986
9499
  if (abort.signal.aborted) return {
7987
- messages: this.#build(conversation),
9500
+ messages: this.#build(run),
7988
9501
  usage
7989
9502
  };
7990
9503
  if (this.#strict) throw selection.fault;
7991
9504
  }
7992
- const messages = this.#build(conversation, selection);
9505
+ const messages = this.#build(run, selection);
7993
9506
  this.#emitter.emit("select", selection);
7994
9507
  return {
7995
9508
  messages,
7996
9509
  usage
7997
9510
  };
7998
9511
  }
7999
- #reject(conversation, error, abort) {
9512
+ #reject(run, error, abort) {
8000
9513
  if (!abort.signal.aborted) {
8001
9514
  this.#emitter.emit("fault", error);
8002
9515
  if (this.#strict && !abort.signal.aborted) throw error;
8003
9516
  }
8004
9517
  return {
8005
- messages: this.#build(conversation),
9518
+ messages: this.#build(run),
8006
9519
  usage: void 0
8007
9520
  };
8008
9521
  }
8009
- #build(conversation, selection) {
8010
- return this.#context.build(selection ?? {
8011
- messages: conversation.view(),
9522
+ #build(run, selection) {
9523
+ const rendered = selection ?? {
9524
+ messages: run.conversation.view(),
8012
9525
  judgments: []
9526
+ };
9527
+ const scope = run.snapshot;
9528
+ const disclosure = run.disclosure;
9529
+ const messages = this.#context.build({
9530
+ selection: rendered,
9531
+ ...scope === void 0 ? {} : { scope },
9532
+ ...disclosure === void 0 ? {} : { disclosure },
9533
+ ...run.switchable ? { switchable: true } : {}
8013
9534
  });
9535
+ run.record(rendered, messages.length);
9536
+ return messages;
9537
+ }
9538
+ #refresh(run, messages) {
9539
+ const added = messages.slice(run.length);
9540
+ return [...this.#build(run, run.selection), ...added];
8014
9541
  }
8015
9542
  #authorize(calls, admitted, advertised, held) {
8016
9543
  const allowed = /* @__PURE__ */ new Map();
@@ -8083,7 +9610,7 @@ var Agent = class {
8083
9610
  }
8084
9611
  return success(evaluated.value);
8085
9612
  }
8086
- async *#approve(tools, authorization, signal) {
9613
+ async *#approve(run, authorization, signal) {
8087
9614
  const authority = this.#authority;
8088
9615
  for (const { index, call, decision, tool } of authorization.asked) {
8089
9616
  if (signal.aborted) return;
@@ -8112,7 +9639,7 @@ var Agent = class {
8112
9639
  };
8113
9640
  const outcome = await raceSignal(answer, signal).catch(() => void 0);
8114
9641
  if (outcome === void 0 || signal.aborted) return;
8115
- if (outcome.approved && tools.tool(call.name) === tool) {
9642
+ if (outcome.approved && run.tool(call.name) === tool) {
8116
9643
  authorization.allowed.set(index, {
8117
9644
  call,
8118
9645
  tool
@@ -8124,29 +9651,29 @@ var Agent = class {
8124
9651
  }
8125
9652
  }
8126
9653
  }
8127
- #changed(tools, call, tool, advertised) {
9654
+ #changed(run, call, tool, advertised) {
8128
9655
  const same = attempt(() => {
8129
- const current = tools.tool(call.name);
9656
+ const current = run.tool(call.name);
8130
9657
  const definition = advertised.find((entry) => entry.name === call.name);
8131
9658
  return current === tool && current?.annotations?.consequential === true === (definition?.annotations?.consequential === true);
8132
9659
  });
8133
9660
  return !same.success || !same.value;
8134
9661
  }
8135
- #confirm(tools, authorization, advertised) {
9662
+ #confirm(run, authorization, advertised) {
8136
9663
  for (const [index, { call, tool }] of authorization.allowed) {
8137
- if (!this.#changed(tools, call, tool, advertised)) continue;
9664
+ if (!this.#changed(run, call, tool, advertised)) continue;
8138
9665
  authorization.allowed.delete(index);
8139
9666
  authorization.denials.set(index, denyCall(call, AUTHORITY_NOTES.denied));
8140
9667
  this.#emitter.emit("deny", call, `${call.name} changed after its decision`, void 0);
8141
- this.#confirm(tools, authorization, advertised);
9668
+ this.#confirm(run, authorization, advertised);
8142
9669
  return;
8143
9670
  }
8144
9671
  }
8145
- async #dispatch(tools, calls, signal, authorization, advertised) {
9672
+ async #dispatch(run, calls, signal, authorization, advertised) {
8146
9673
  const { allowed, denials } = authorization;
8147
9674
  const entries = [...allowed].sort(([left], [right]) => left - right);
8148
9675
  const started = entries.map(([, { call, tool }]) => {
8149
- if (!this.#changed(tools, call, tool, advertised)) return tools.execute(call, { signal });
9676
+ if (!this.#changed(run, call, tool, advertised)) return run.execute(call, { signal });
8150
9677
  this.#emitter.emit("deny", call, `${call.name} changed after its decision`, void 0);
8151
9678
  return denyCall(call, AUTHORITY_NOTES.denied);
8152
9679
  });
@@ -8215,6 +9742,17 @@ var Agent = class {
8215
9742
  * awaited inline, so a bounded runner frees the parent's slot for them. `createAgentRunner`
8216
9743
  * creates one instance per runner and binds its `execute` method as the runner's handler.
8217
9744
  *
9745
+ * A child job runs within its parent. Before a unit spawns or runs, on every attempt, the
9746
+ * `execute` method walks the whole tree under it through the `scanJobTree` helper and refuses the
9747
+ * unit when any job exceeds its own parent on `tools`, `builtins`, `scope`, `authority`,
9748
+ * `provider`, `scheduler`, `limit`, `timeout`, or `budget`, or when a job is malformed or its build
9749
+ * would refuse it (the lines `collectJobRefusals` returns), so nothing in a refused tree spawns, builds,
9750
+ * or runs. A child's `workspace` is free, because it renders nothing its own `scope`
9751
+ * omits. Each child is held within its parent alone, so the children of one parent can together
9752
+ * spend more than it. A job that needs another provider, another authority, a skill, memo,
9753
+ * workspace, or built-in its parent lacks, or more room than its parent is a root job the host
9754
+ * enqueues.
9755
+ *
8218
9756
  * @example
8219
9757
  * ```ts
8220
9758
  * import type { AgentJobInput, ProviderInterface } from '@orkestrel/agent'
@@ -8244,14 +9782,32 @@ var AgentFanout = class {
8244
9782
  this.#partial = partial;
8245
9783
  }
8246
9784
  /**
8247
- * Executes one unit: spawns its declared children unless an earlier attempt of the unit already
8248
- * did, then runs the rehydrated agent and settles it under the partial policy.
9785
+ * Executes one unit: refuses its tree when a job in it is malformed or exceeds its parent, spawns
9786
+ * its declared children unless an earlier attempt of the unit already did, then runs the
9787
+ * rehydrated agent and settles it under the partial policy.
9788
+ *
9789
+ * @remarks
9790
+ * The check runs on every attempt, before the unit spawns or runs, and throws synchronously. The
9791
+ * error's message opens with the rule each kind of finding breaks, a refused job's rule when a
9792
+ * finding opens with `JOB_REFUSAL_PREFIX` and the within-parent rule when a finding names an
9793
+ * exceeded member, then lists every finding, one a line. Its `context.findings` holds the same
9794
+ * findings in walk order.
8249
9795
  *
8250
9796
  * @param controller - The runner controller for this unit's attempt
8251
9797
  * @returns The settled agent result of the unit
9798
+ * @throws {AgentError} Thrown with code `'REGISTRY'` when a job in the unit's tree is malformed or exceeds its parent, or when the registry cannot rehydrate the unit
8252
9799
  * @throws {AgentJobError} Thrown when the run ended partial and the partial policy is `false`
8253
9800
  */
8254
9801
  execute(controller) {
9802
+ const findings = scanJobTree(controller.input);
9803
+ if (findings.length > 0) {
9804
+ const refused = findings.filter((finding) => finding.startsWith(JOB_REFUSAL_PREFIX));
9805
+ throw new AgentError("REGISTRY", [
9806
+ ...refused.length === 0 ? [] : ["every job in a tree must be readable, hold only the declared members of AgentJobInput, and build under its parent; correct each job a following finding names"],
9807
+ ...refused.length === findings.length ? [] : ["a child job must stay within its parent on tools, builtins, scope, authority, provider, scheduler, limit, timeout, and budget; enqueue a job that needs more as a root job"],
9808
+ ...findings
9809
+ ].join("\n"), { context: { findings } });
9810
+ }
8255
9811
  const children = controller.input.children;
8256
9812
  if (children !== void 0 && !this.#spawned.has(controller.id)) {
8257
9813
  this.#spawned = /* @__PURE__ */ new Set([...this.#spawned, controller.id]);
@@ -8305,6 +9861,7 @@ var Authority = class {
8305
9861
  #handler;
8306
9862
  constructor(options) {
8307
9863
  this.#fallback = requireFallback(options);
9864
+ refuseOptionKeys(options, AUTHORITY_OPTION_KEYS, "Authority", "AuthorityOptions");
8308
9865
  this.#rules = requireRules(options.rules);
8309
9866
  this.#handler = options.ask;
8310
9867
  }
@@ -8427,16 +9984,22 @@ var Approver = class {
8427
9984
  * the message `unknown <category>: <name>` when it is absent — an unknown name in a
8428
9985
  * rehydrated job is a programmer / config error that must fail loudly at build time, never
8429
9986
  * silently resolve to `undefined` and run an agent missing a dependency.
8430
- * - **`build` rehydrates.** Resolve the job's `provider`; assemble a fresh
8431
- * {@link ToolManager} from the `tools` names, which refuses with `code: 'REGISTRY'` when the job
8432
- * names no `authority`; rebuild the token `budget` from its
8433
- * ceiling (`createTokenBudget({ max })`); resolve the optional `authority` /
9987
+ * - **`build` rehydrates.** Refuse with `code: 'REGISTRY'` a job `agentJobContract` refuses,
9988
+ * its faults under `context.faults`, and a job `collectJobRefusals` refuses, its lines under
9989
+ * `context.refusals`: tools or built-ins with no `authority`, a `builtins` list an agent
9990
+ * refuses, and a built-in the job's `tools` also name. Then resolve the job's `provider`;
9991
+ * assemble a fresh {@link ToolManager} from the `tools` names; rebuild the token `budget` from
9992
+ * its ceiling (`createTokenBudget({ max })`); resolve the optional `authority` /
8434
9993
  * `scheduler` names; construct the {@link Agent} with `system` / `limit` / `timeout` /
8435
9994
  * the threaded `signal`; seed its context with the job's `messages`; return it. The
8436
9995
  * `signal` is the queue attempt's / runner unit's cancel, so a bounded abort propagates
8437
9996
  * into the agent (which commits a partial — the job's `partial` policy then
8438
- * decides success vs. retry). A job `limit` that is not a positive safe integer throws an
8439
- * {@link AgentError} carrying `code: 'LIMIT'` from the agent's construction.
9997
+ * decides success vs. retry). A job is a record, so a malformed `limit`, `timeout`, `budget`,
9998
+ * seed role, or `builtins` list refuses as one, with `code: 'REGISTRY'`.
9999
+ * - **A job holds what it names.** A job with a `scope` gets the registry's `skills`, `memos`, and
10000
+ * `workspaces` managers, which every scoped job shares, and a scope named `job` built from its
10001
+ * three lists; a job with no `scope` gets none of them. Its `workspace` and `builtins` pass to
10002
+ * the agent.
8440
10003
  * - **Event-free.** A pure resolver — no Emitter, no events.
8441
10004
  *
8442
10005
  * @example
@@ -8453,12 +10016,19 @@ var AgentRegistry = class {
8453
10016
  #authorities;
8454
10017
  #schedulers;
8455
10018
  #store;
10019
+ #skills;
10020
+ #memos;
10021
+ #workspaces;
8456
10022
  constructor(options) {
10023
+ refuseOptionKeys(options, REGISTRY_OPTION_KEYS, "AgentRegistry", "AgentRegistryOptions");
8457
10024
  this.#providers = new Map(Object.entries(options.providers));
8458
10025
  this.#tools = new Map(Object.entries(options.tools ?? {}));
8459
10026
  this.#authorities = new Map(Object.entries(options.authorities ?? {}));
8460
10027
  this.#schedulers = new Map(Object.entries(options.schedulers ?? {}));
8461
10028
  this.#store = options.store;
10029
+ this.#skills = options.skills;
10030
+ this.#memos = options.memos;
10031
+ this.#workspaces = options.workspaces;
8462
10032
  }
8463
10033
  provider(name) {
8464
10034
  return requireEntry(this.#providers, "provider", name);
@@ -8475,13 +10045,16 @@ var AgentRegistry = class {
8475
10045
  build(input, signal) {
8476
10046
  const faults = agentJobContract.audit(input);
8477
10047
  if (faults.length > 0) throw new AgentError("REGISTRY", `a job must hold only the declared members of AgentJobInput\n${describeFaults(faults, agentJobContract.schema)}`, { context: { faults } });
10048
+ const refusals = collectJobRefusals(input);
10049
+ if (refusals.length > 0) throw new AgentError("REGISTRY", ["a job must build as it is written; correct each member a following line names", ...refusals].join("\n"), { context: { refusals } });
8478
10050
  const agent = new Agent(this.provider(input.provider), this.#buildOptions(input, signal));
8479
10051
  for (const message of input.messages ?? []) agent.context.messages.add(message);
8480
10052
  return agent;
8481
10053
  }
8482
10054
  #buildOptions(input, signal) {
8483
10055
  const names = input.tools ?? [];
8484
- if (names.length > 0 && input.authority === void 0) throw new AgentError("REGISTRY", "a job that names tools and no authority cannot run them; add authority: 'NAME' to the job and register that NAME under authorities", { context: { tools: names } });
10056
+ const builtins = input.builtins ?? [];
10057
+ const scope = input.scope;
8485
10058
  const budget = input.budget === void 0 ? void 0 : createTokenBudget({ max: input.budget });
8486
10059
  return {
8487
10060
  ...names.length === 0 ? {} : { tools: this.#buildToolManager(names) },
@@ -8492,6 +10065,15 @@ var AgentRegistry = class {
8492
10065
  ...input.authority === void 0 ? {} : { authority: this.authority(input.authority) },
8493
10066
  ...input.scheduler === void 0 ? {} : { scheduler: this.scheduler(input.scheduler) },
8494
10067
  ...this.#store === void 0 ? {} : { conversations: new ConversationManager({ store: this.#store }) },
10068
+ ...scope === void 0 || this.#skills === void 0 ? {} : { skills: this.#skills },
10069
+ ...scope === void 0 || this.#memos === void 0 ? {} : { memos: this.#memos },
10070
+ ...scope === void 0 || this.#workspaces === void 0 ? {} : { workspaces: this.#workspaces },
10071
+ ...scope === void 0 ? {} : { scope: createScope({
10072
+ name: "job",
10073
+ ...scope
10074
+ }) },
10075
+ ...input.workspace === void 0 ? {} : { workspace: input.workspace },
10076
+ ...builtins.length === 0 ? {} : { builtins },
8495
10077
  ...signal === void 0 ? {} : { signal }
8496
10078
  };
8497
10079
  }
@@ -8726,6 +10308,7 @@ function createAgentRegistry(options) {
8726
10308
  * ```
8727
10309
  */
8728
10310
  function createAgentQueue(options) {
10311
+ refuseOptionKeys(options, QUEUE_OPTION_KEYS, "createAgentQueue", "AgentQueueOptions");
8729
10312
  const { registry, partial = false, store } = options;
8730
10313
  return createQueue({
8731
10314
  ...extractQueueOptions(options),
@@ -8772,6 +10355,7 @@ function createAgentQueue(options) {
8772
10355
  * ```
8773
10356
  */
8774
10357
  function createAgentRunner(options) {
10358
+ refuseOptionKeys(options, RUNNER_OPTION_KEYS, "createAgentRunner", "AgentRunnerOptions");
8775
10359
  const { registry, partial = false } = options;
8776
10360
  const fanout = new AgentFanout(registry, partial);
8777
10361
  return createRunner({
@@ -8779,6 +10363,38 @@ function createAgentRunner(options) {
8779
10363
  handler: fanout.execute.bind(fanout)
8780
10364
  });
8781
10365
  }
10366
+ /**
10367
+ * Creates the tool a run serves for one built-in: its description and annotations from
10368
+ * `BUILTIN_TOOLS`, its argument shape from `builtinToolContracts`, and the given handler.
10369
+ *
10370
+ * @remarks
10371
+ * The tool's door refuses a missing, empty, over-long, or extra argument before the handler runs,
10372
+ * and repairs a value that converts to a string without loss, such as a number, so the handler
10373
+ * reads only arguments the shape admits. Its definition equals the one `collectBuiltinDefinitions`
10374
+ * returns for the same name.
10375
+ *
10376
+ * @param name - The built-in to create
10377
+ * @param execute - The handler the door hands admitted arguments to
10378
+ * @returns The tool
10379
+ *
10380
+ * @example
10381
+ * ```ts
10382
+ * import { createBuiltinTool } from '@orkestrel/agent'
10383
+ *
10384
+ * const memo = createBuiltinTool('memo', (args) => `read ${String(args.name)}`)
10385
+ * memo.annotations // { pure: true, untrusted: true }
10386
+ * ```
10387
+ */
10388
+ function createBuiltinTool(name, execute) {
10389
+ const declared = BUILTIN_TOOLS[name];
10390
+ return createTool({
10391
+ name,
10392
+ description: declared.description,
10393
+ ...declared.annotations === void 0 ? {} : { annotations: declared.annotations },
10394
+ contract: builtinToolContracts[name].shape,
10395
+ execute
10396
+ });
10397
+ }
8782
10398
  // src/core/ledgers/constants.ts
8783
10399
  /**
8784
10400
  * Lists the categories the ledger files a message under, in the order the category question
@@ -8853,19 +10469,25 @@ var LEDGER_QUESTIONS = Object.freeze({
8853
10469
  /**
8854
10470
  * Supplies the text of each ledger note, worded for a model that answers in its final
8855
10471
  * message.
10472
+ *
10473
+ * @remarks
10474
+ * `overflow` names `unload` because a skill the thread shows is the room a model can give back: a
10475
+ * successful `unload` reopens every call the room denied in that request.
8856
10476
  */
8857
10477
  var LEDGER_NOTES = Object.freeze({
8858
10478
  cue: "Give your complete answer to the request now, from what you already have.",
8859
10479
  results: "Your lookups and recalls in this request returned:",
8860
10480
  repeat: "You already have this result earlier in this request; give your complete answer now as your final message.",
8861
- closure: "recall is closed for the rest of this request; give your final answer from what you have"
10481
+ closure: "recall is closed for the rest of this request; give your final answer from what you have",
10482
+ overflow: "there is no room left for it in this request. Unload a skill you no longer need before you call it again, or answer with what you have."
8862
10483
  });
8863
10484
  /**
8864
- * Supplies the default prompt and tail shares.
10485
+ * Supplies the default prompt, tail, and skills shares.
8865
10486
  */
8866
10487
  var DEFAULT_LEDGER_SHARE = Object.freeze({
8867
10488
  prompt: .7,
8868
- tail: .35
10489
+ tail: .35,
10490
+ skills: .5
8869
10491
  });
8870
10492
  /**
8871
10493
  * Caps the tool-iteration turns of a ledger's agent at 8 turns.
@@ -8902,6 +10524,85 @@ var LEDGER_SCALE_DRIFT = .06;
8902
10524
  var LEDGER_WORD = /[\p{L}\p{N}]+/gu;
8903
10525
  /** Matches the logprob decoding failure `invalid or duplicate top logprob token`, which the ledger holds for the ledger's life. */
8904
10526
  var DETERMINISTIC_JUDGE_ERROR = /invalid or duplicate top logprob token/;
10527
+ /**
10528
+ * Lists the members `LedgerOptions` declares, frozen — the keys the `Ledger` constructor admits.
10529
+ *
10530
+ * @remarks
10531
+ * The constructor passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an own
10532
+ * enumerable member outside it refuses with a `ContractError` coded `'structure'`.
10533
+ */
10534
+ var LEDGER_OPTION_KEYS = Object.freeze([
10535
+ "judge",
10536
+ "system",
10537
+ "topics",
10538
+ "questions",
10539
+ "thresholds",
10540
+ "capacity",
10541
+ "predict",
10542
+ "think",
10543
+ "gauge",
10544
+ "lookups",
10545
+ "writes",
10546
+ "share",
10547
+ "recall",
10548
+ "correction",
10549
+ "agent",
10550
+ "snapshot"
10551
+ ]);
10552
+ /**
10553
+ * Lists the members the `LedgerAgentOptions` pick declares, frozen — the keys a ledger's `agent`
10554
+ * option admits.
10555
+ *
10556
+ * @remarks
10557
+ * The `Ledger` constructor passes the list to `refuseOptionKeys` of `@orkestrel/contract`, so an
10558
+ * own enumerable member outside it, an `AgentOptions` member the pick leaves out included, refuses
10559
+ * with a `ContractError` coded `'structure'`.
10560
+ */
10561
+ var LEDGER_AGENT_KEYS = Object.freeze([
10562
+ "limit",
10563
+ "timeout",
10564
+ "on",
10565
+ "scheduler",
10566
+ "instructions",
10567
+ "skills",
10568
+ "memos",
10569
+ "workspaces",
10570
+ "strict",
10571
+ "authority",
10572
+ "builtins",
10573
+ "workspace"
10574
+ ]);
10575
+ /** Lists the members `ClassifierOptions` declares, frozen — the keys the `Classifier` constructor admits. */
10576
+ var CLASSIFIER_OPTION_KEYS = Object.freeze([
10577
+ "strict",
10578
+ "conversation",
10579
+ "judge",
10580
+ "questions",
10581
+ "topics",
10582
+ "thresholds",
10583
+ "assign",
10584
+ "entities",
10585
+ "correction",
10586
+ "scheduler"
10587
+ ]);
10588
+ /** Lists the members `GaugeOptions` declares, frozen — the keys the `Gauge` constructor admits. */
10589
+ var GAUGE_OPTION_KEYS = Object.freeze([
10590
+ "scale",
10591
+ "overhead",
10592
+ "capacity",
10593
+ "predict",
10594
+ "replay"
10595
+ ]);
10596
+ /**
10597
+ * Sets the 3 UTF-8 bytes one UTF-16 code unit encodes to at most, the divisor that sizes the
10598
+ * workspace text a calibration's third call carries.
10599
+ *
10600
+ * @remarks
10601
+ * A tokenizer that falls back to bytes charges at most one token a byte, so workspace text cut to the
10602
+ * capacity the call without definitions left, divided by this figure, in characters, reports at most
10603
+ * `capacity` apart from a template's few tokens for an added message.
10604
+ */
10605
+ var LEDGER_SAMPLE_BYTES = 3;
8905
10606
  // src/core/ledgers/errors.ts
8906
10607
  /**
8907
10608
  * Reports an invalid ledger configuration, failed calibration, or unowned request selection,
@@ -8910,7 +10611,9 @@ var DETERMINISTIC_JUDGE_ERROR = /invalid or duplicate top logprob token/;
8910
10611
  * @remarks
8911
10612
  * A threshold, share, capacity, limit, topic, lookup, write, question, or gauge outside its bounds is a
8912
10613
  * programmer error and throws this with the matching {@link LedgerErrorCode}. A calibration call that reports
8913
- * no prompt usage throws this with `'GAUGE'`. A snapshot option that `isLedgerSnapshot` refuses
10614
+ * no prompt usage, or a calibration call, with the tool definitions, without them, or with the workspace text, that reports a prompt
10615
+ * over `capacity`, the head included, throws this with `'GAUGE'`; the second holds `capacity` and
10616
+ * `prompt` in its `context`. A snapshot option that `isLedgerSnapshot` refuses
8914
10617
  * throws this with `'SNAPSHOT'`, its `context` holding the `faults`. Narrow a caught value with {@link isLedgerError} and
8915
10618
  * branch on `error.code`. A selection without an active `respond` call, for a conversation other
8916
10619
  * than the ledger's, or for a request other than that call's request or a ledger note, reports
@@ -8952,7 +10655,7 @@ function isLedgerError(value) {
8952
10655
  return holds(() => {
8953
10656
  if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.LedgerError"))?.value === value)) return false;
8954
10657
  const code = INTRINSICS.reflect.read(value, "code");
8955
- if (!(code === "REQUEST" || code === "THRESHOLD" || code === "SHARE" || code === "CAPACITY" || code === "LIMIT" || code === "TOPIC" || code === "LOOKUP" || code === "GAUGE" || code === "REFERENCE" || code === "SNAPSHOT" || code === "QUESTION" || code === "WRITE")) return false;
10658
+ if (!(code === "REQUEST" || code === "THRESHOLD" || code === "SHARE" || code === "CAPACITY" || code === "LIMIT" || code === "TOPIC" || code === "LOOKUP" || code === "GAUGE" || code === "REFERENCE" || code === "SNAPSHOT" || code === "QUESTION" || code === "WRITE" || code === "OVERFLOW")) return false;
8956
10659
  const context = INTRINSICS.reflect.read(value, "context");
8957
10660
  return context === void 0 || isObject(context) || isFunction(context);
8958
10661
  });
@@ -8988,9 +10691,10 @@ function digestLedgerWindow(exchanges, messages) {
8988
10691
  * Digests tool definitions as the JSON a provider request carries them, in order.
8989
10692
  *
8990
10693
  * @remarks
8991
- * A ledger stores this digest with its gauge, so a hydrate reuses the gauge only for the same
8992
- * definitions: an added, removed, reordered, or edited definition changes the digest. The digest is
8993
- * a {@link computeLedgerChecksum} checksum and makes no security claim.
10694
+ * A ledger stores this digest with its gauge and compares it at a hydrate and at each `respond`
10695
+ * call, so it reuses the gauge only for the same definitions: an added, removed, reordered, or
10696
+ * edited definition changes the digest. The digest is a {@link computeLedgerChecksum} checksum and
10697
+ * makes no security claim.
8994
10698
  *
8995
10699
  * @param definitions - The tool definitions, as a tool manager's `definitions` method returns them
8996
10700
  * @returns The 16-digit hexadecimal digest, or undefined when JSON cannot render the definitions
@@ -9004,6 +10708,82 @@ function digestLedgerTools(definitions) {
9004
10708
  return text === void 0 ? void 0 : computeLedgerChecksum(text);
9005
10709
  }
9006
10710
  /**
10711
+ * Computes the tokens one estimate unit of a definition costs beyond the calibrated set.
10712
+ *
10713
+ * @remarks
10714
+ * The larger of `scale` and the calibrated set's overhead per estimate unit, or `scale` for an
10715
+ * empty set or one that estimates 0. A set's estimate is `estimateTokens` over its JSON text.
10716
+ *
10717
+ * @param calibrated - The definitions the gauge's overhead priced
10718
+ * @param gauge - The gauge's scale and overhead
10719
+ * @returns The tokens one estimate unit of a definition costs
10720
+ * @example
10721
+ * ```ts
10722
+ * computeToolDensity([], { scale: 1.1, overhead: 400 }) // 1.1
10723
+ * ```
10724
+ */
10725
+ function computeToolDensity(calibrated, gauge) {
10726
+ const estimate = calibrated.length === 0 ? 0 : estimateTokens(JSON.stringify(calibrated));
10727
+ return estimate > 0 ? Math.max(gauge.scale, gauge.overhead / estimate) : gauge.scale;
10728
+ }
10729
+ /**
10730
+ * Computes what a call's advertised set spares of the calibrated overhead and adds beyond it.
10731
+ *
10732
+ * @remarks
10733
+ * Definitions compare by their JSON text, so a definition replaced under its name by another text
10734
+ * is both left out and added. An empty advertised set spares the whole overhead. Otherwise the
10735
+ * calibrated definitions the call leaves out spare the lower of `scale` and the calibrated set's
10736
+ * overhead per estimate unit, times their estimate, so a credit never exceeds their proportional
10737
+ * share of the overhead; the definitions it advertises beyond the calibrated set add
10738
+ * {@link computeToolDensity}, the higher of the two, times theirs. A set's estimate is
10739
+ * `estimateTokens` over its JSON text, 0 for an empty set. The call's price is
10740
+ * `overhead - spared + added`.
10741
+ *
10742
+ * @param calibrated - The definitions the gauge's overhead priced
10743
+ * @param advertised - The definitions the call advertises
10744
+ * @param gauge - The gauge's scale and overhead
10745
+ * @returns The tokens the call spares and adds
10746
+ * @example
10747
+ * ```ts
10748
+ * computeToolPrice([], [], { scale: 1.1, overhead: 400 }) // { spared: 400, added: 0 }
10749
+ * ```
10750
+ */
10751
+ function computeToolPrice(calibrated, advertised, gauge) {
10752
+ if (advertised.length === 0) return {
10753
+ spared: gauge.overhead,
10754
+ added: 0
10755
+ };
10756
+ const sent = new Set(advertised.map((definition) => JSON.stringify(definition)));
10757
+ const priced = new Set(calibrated.map((definition) => JSON.stringify(definition)));
10758
+ const hidden = calibrated.filter((definition) => !sent.has(JSON.stringify(definition)));
10759
+ const extra = advertised.filter((definition) => !priced.has(JSON.stringify(definition)));
10760
+ return {
10761
+ spared: hidden.length === 0 ? 0 : Math.min(gauge.scale, gauge.overhead / estimateTokens(JSON.stringify(calibrated))) * estimateTokens(JSON.stringify(hidden)),
10762
+ added: extra.length === 0 ? 0 : computeToolDensity(calibrated, gauge) * estimateTokens(JSON.stringify(extra))
10763
+ };
10764
+ }
10765
+ /**
10766
+ * Computes the tokens loading a skill adds: its body, and the definitions it names beyond an advertised set.
10767
+ *
10768
+ * @remarks
10769
+ * The body is the text `renderSkillBody` renders, priced at `scale`, and a blank `content` renders
10770
+ * no body. The caller passes the definitions the skill names that the turn does not advertise,
10771
+ * priced as {@link computeToolPrice} prices an addition.
10772
+ *
10773
+ * @param skill - The skill to load
10774
+ * @param added - The definitions the skill names that the advertised set leaves out
10775
+ * @param calibrated - The definitions the gauge's overhead priced
10776
+ * @param gauge - The gauge's scale and overhead
10777
+ * @returns The tokens the load adds
10778
+ * @example
10779
+ * ```ts
10780
+ * computeSkillPrice({ name: 'refunds', content: 'Check the order first.' }, [], [], { scale: 1, overhead: 0 }) // 9
10781
+ * ```
10782
+ */
10783
+ function computeSkillPrice(skill, added, calibrated, gauge) {
10784
+ return (skill.content.trim() === "" ? 0 : gauge.scale * estimateTokens(renderSkillBody(skill))) + computeToolPrice(calibrated, [...calibrated, ...added], gauge).added;
10785
+ }
10786
+ /**
9007
10787
  * Computes a checksum of text: two 32-bit FNV-1a lanes over its code points, as 16 hexadecimal digits.
9008
10788
  *
9009
10789
  * @remarks
@@ -9232,23 +11012,6 @@ function splitWords(part) {
9232
11012
  return part.split(/\s+/).map((word) => word.replace(/^[\p{P}\p{S}]+|[\p{P}\p{S}]+$/gu, "").toLowerCase()).filter((word) => word !== "");
9233
11013
  }
9234
11014
  /**
9235
- * Finds the call that owns a tool message within a collected tool group.
9236
- * @param group - The assistant leader followed by its tool results
9237
- * @param message - The tool result to pair; distinct leader ids pair by result id when any result has one
9238
- * @returns The call matching the result's call id, or its position when the leader repeats an id or every result lacks an id; undefined when unpaired
9239
- * @example
9240
- * ```ts
9241
- * findLedgerCall(group, result)?.arguments
9242
- * ```
9243
- */
9244
- function findLedgerCall(group, message) {
9245
- const [leader, ...results] = group;
9246
- const at = results.findIndex((result) => result.id === message.id);
9247
- if (message.role !== "tool" || at < 0) return void 0;
9248
- const calls = leader?.calls ?? [];
9249
- return !(new Set(calls.map((call) => call.id)).size !== calls.length) && results.some((result) => result.call !== void 0) ? calls.find((call) => call.id === message.call) : calls[at];
9250
- }
9251
- /**
9252
11015
  * Ranks a source the records render for removal before the next prompt.
9253
11016
  *
9254
11017
  * @param group - The planning group: 1 for a topic match, 2 for an off-topic rule or correction, or 3 for a name match
@@ -9942,23 +11705,34 @@ function matchesCutLine(line) {
9942
11705
  /**
9943
11706
  * Renders the tail stub of a lookup result from an earlier request.
9944
11707
  *
11708
+ * @remarks
11709
+ * A `hidden` stub names the `recall` call that finds its result, with the first string argument,
11710
+ * trimmed, or `its id` when no argument is a string or that one is blank, only while `offered` is `true`. The ledger plans the
11711
+ * tail with every stub naming `recall`, then renders the tail's stubs again after it admits a window
11712
+ * rung, with `offered` set to whether that rung offers `recall` and the scope admits it, so the
11713
+ * second render can only shorten a stub and raises no price. `offered` changes no other state.
11714
+ *
9945
11715
  * @param name - The lookup tool name
9946
11716
  * @param args - The arguments the call carried; arguments JSON cannot carry leave the call as its bare tool name, per {@link renderLookupCall}
9947
11717
  * @param state - What became of the result: `failed`, `empty`, `shown` in the records, or `hidden` from them
9948
11718
  * @param write - If `true`, the call is a write's, whose `empty` state reads `changed nothing`; if `false`, a lookup's, whose `empty` state reads `no record`. Default: `false`
11719
+ * @param offered - If `true`, a `hidden` result names the `recall` route; if `false`, because the admitted rung offers no `recall` or the scope excludes it, it reads `result not shown`. Default: `true`
9949
11720
  * @returns The stub text, which carries the call and its state
9950
11721
  *
9951
11722
  * @example
9952
11723
  * ```ts
9953
11724
  * renderStub('lookup_order', { id: 'BW-5512' }, 'hidden')
9954
11725
  * // 'lookup_order {"id":"BW-5512"}: result not shown; call recall with BW-5512'
11726
+ * renderStub('lookup_order', { id: 'BW-5512' }, 'hidden', false, false)
11727
+ * // 'lookup_order {"id":"BW-5512"}: result not shown'
9955
11728
  * ```
9956
11729
  */
9957
- function renderStub(name, args, state, write = false) {
11730
+ function renderStub(name, args, state, write = false, offered = true) {
9958
11731
  const head = renderLookupCall(name, args);
9959
11732
  if (state === "failed") return `${head}: failed`;
9960
11733
  if (state === "empty") return write ? `${head}: changed nothing` : `${head}: no record`;
9961
11734
  if (state === "shown") return `${head}: result shown under Records below`;
11735
+ if (!offered) return `${head}: result not shown`;
9962
11736
  return `${head}: result not shown; call recall with ${(Object.values(args).find(isString) ?? "").trim() || "its id"}`;
9963
11737
  }
9964
11738
  /**
@@ -10328,6 +12102,51 @@ function collectLedgerEvidence(messages, sources, amendments) {
10328
12102
  ]), { ...edge }]))
10329
12103
  };
10330
12104
  }
12105
+ /**
12106
+ * Cuts the workspace text a calibration sample adds over its head to a number of characters, or
12107
+ * returns `undefined` when the sample adds anything else.
12108
+ *
12109
+ * @remarks
12110
+ * The head and the shown sample are what a context's `build` returns for an empty turn without and
12111
+ * with the workspace: the shown sample holds the head's messages with the workspace section appended
12112
+ * to the context message, or one context message added where the head holds none. The cut keeps the
12113
+ * first `limit` characters of that added text and every other message as the sample holds it. A
12114
+ * sample whose messages differ from the head's in any other way, or that adds no text, returns
12115
+ * `undefined`.
12116
+ *
12117
+ * @param head - The head built with no workspace
12118
+ * @param shown - The head built with the workspace a request renders
12119
+ * @param limit - The characters of added text to keep
12120
+ * @returns The cut sample, or `undefined` when the sample adds no trailing text to one message
12121
+ *
12122
+ * @example
12123
+ * ```ts
12124
+ * import { cutWorkspaceSample } from '@orkestrel/agent'
12125
+ *
12126
+ * const head = [{ id: 's', role: 'system', content: 'Serve the desk.' }] as const
12127
+ * const shown = [...head, { id: 'c', role: 'user', content: '## Workspace\n\nFile: a.md' }] as const
12128
+ * cutWorkspaceSample(head, shown, 12)?.[1]?.content // '## Workspace'
12129
+ * ```
12130
+ */
12131
+ function cutWorkspaceSample(head, shown, limit) {
12132
+ const at = shown.findIndex((message, index) => message.role !== head[index]?.role || message.content !== head[index]?.content);
12133
+ const added = shown[at];
12134
+ const extended = shown.length === head.length ? head[at] : void 0;
12135
+ const prefix = extended?.content ?? "";
12136
+ const rest = shown.slice(at + 1);
12137
+ const held = head.slice(extended === void 0 ? at : at + 1);
12138
+ if (added === void 0 || shown.length - head.length > 1 || shown.length < head.length) return void 0;
12139
+ if (!added.content.startsWith(prefix) || added.content.length === prefix.length) return void 0;
12140
+ if (rest.length !== held.length || rest.some((message, index) => message.role !== held[index]?.role || message.content !== held[index]?.content)) return void 0;
12141
+ return [
12142
+ ...shown.slice(0, at),
12143
+ {
12144
+ ...added,
12145
+ content: prefix + added.content.slice(prefix.length, prefix.length + limit)
12146
+ },
12147
+ ...rest
12148
+ ];
12149
+ }
10331
12150
  // src/core/ledgers/Classifier.ts
10332
12151
  /**
10333
12152
  * Files messages through the conversation's judgment manager and reads their categories and corrections.
@@ -10348,6 +12167,7 @@ var Classifier = class {
10348
12167
  * @param options - The conversation, judge, questions, cutoffs, and handlers
10349
12168
  */
10350
12169
  constructor(options) {
12170
+ refuseOptionKeys(options, CLASSIFIER_OPTION_KEYS, "Classifier", "ClassifierOptions");
10351
12171
  this.#options = options;
10352
12172
  }
10353
12173
  /**
@@ -10724,6 +12544,7 @@ var Gauge = class {
10724
12544
  * @throws {LedgerError} Thrown when `predict` is not a nonnegative safe integer less than `capacity` (code `'CAPACITY'`)
10725
12545
  */
10726
12546
  constructor(options) {
12547
+ refuseOptionKeys(options, GAUGE_OPTION_KEYS, "Gauge", "GaugeOptions");
10727
12548
  if (!isFiniteNumber(options.scale) || options.scale <= 0) throw new LedgerError("GAUGE", "gauge scale must be finite and greater than 0");
10728
12549
  if (!isFiniteNumber(options.overhead) || options.overhead < 0) throw new LedgerError("GAUGE", "gauge overhead must be finite and at least 0");
10729
12550
  if (!isPositiveSafeInteger(options.capacity)) throw new LedgerError("CAPACITY", "gauge capacity must be a positive safe integer");
@@ -10754,7 +12575,7 @@ var Gauge = class {
10754
12575
  }
10755
12576
  remainder(calls) {
10756
12577
  const call = calls.at(-1);
10757
- const used = isFiniteNumber(call?.prompt) ? call.prompt + (call.completion ?? 0) - (this.#replay === "none" ? call.thinking ?? 0 : 0) : Math.max(0, this.#overhead - (call?.spared ?? 0)) + this.#scale * (call?.estimate ?? 0);
12578
+ const used = isFiniteNumber(call?.prompt) ? call.prompt + (call.completion ?? 0) - (this.#replay === "none" ? call.thinking ?? 0 : 0) : Math.max(0, this.#overhead - (call?.spared ?? 0)) + (call?.added ?? 0) + this.#scale * (call?.estimate ?? 0);
10758
12579
  return Math.max(0, this.#capacity - used);
10759
12580
  }
10760
12581
  reserve(calls, longest) {
@@ -10774,7 +12595,7 @@ var Gauge = class {
10774
12595
  }
10775
12596
  observe(calls, reply) {
10776
12597
  const first = calls[0];
10777
- if (first !== void 0 && isFiniteNumber(first.prompt) && first.estimate > 0 && ((first.spared ?? 0) === 0 || (first.spared ?? 0) >= this.#overhead)) {
12598
+ if (first !== void 0 && isFiniteNumber(first.prompt) && first.estimate > 0 && (first.added ?? 0) === 0 && ((first.spared ?? 0) === 0 || (first.spared ?? 0) >= this.#overhead)) {
10778
12599
  const priced = first.prompt - Math.max(0, this.#overhead - (first.spared ?? 0));
10779
12600
  if (priced > 0) this.#scale = priced / first.estimate;
10780
12601
  }
@@ -10982,6 +12803,7 @@ var LedgerRequest = class {
10982
12803
  #admitted = /* @__PURE__ */ new Set();
10983
12804
  #denials = /* @__PURE__ */ new Set();
10984
12805
  #listed = [];
12806
+ #commits = [];
10985
12807
  #recalls = 0;
10986
12808
  #closed = false;
10987
12809
  /**
@@ -11168,6 +12990,23 @@ var LedgerRequest = class {
11168
12990
  lines(result) {
11169
12991
  return this.#listed.findLast((listing) => listing.result === result)?.lines;
11170
12992
  }
12993
+ commit(price, skill) {
12994
+ this.#commits = [...this.#commits, {
12995
+ price,
12996
+ turn: this.calls.length,
12997
+ ...skill === void 0 ? {} : { skill }
12998
+ }];
12999
+ }
13000
+ get committed() {
13001
+ return this.#inflight().reduce((sum, entry) => sum + entry.price, 0);
13002
+ }
13003
+ get loads() {
13004
+ return this.#inflight().flatMap((entry) => entry.skill === void 0 ? [] : [entry.skill]);
13005
+ }
13006
+ #inflight() {
13007
+ const turn = this.calls.length;
13008
+ return this.#commits.filter((entry) => entry.turn === turn);
13009
+ }
11171
13010
  };
11172
13011
  // src/core/ledgers/LedgerScan.ts
11173
13012
  /**
@@ -11445,16 +13284,20 @@ var Ledger = class {
11445
13284
  #share;
11446
13285
  #conversation;
11447
13286
  #agent;
13287
+ #record;
13288
+ #builtins;
13289
+ #given;
11448
13290
  #classifier;
11449
13291
  #requests = /* @__PURE__ */ new Set();
11450
13292
  #annotations = /* @__PURE__ */ new Set();
11451
13293
  #results = /* @__PURE__ */ new Map();
11452
13294
  #pending = /* @__PURE__ */ new Map();
11453
- #live = /* @__PURE__ */ new Set();
13295
+ #live = /* @__PURE__ */ new Map();
11454
13296
  #scans = /* @__PURE__ */ new Set();
11455
13297
  #calibrations = /* @__PURE__ */ new Set();
11456
13298
  #gauge;
11457
- #digest;
13299
+ #measured;
13300
+ #refusal;
11458
13301
  #window = [];
11459
13302
  #evidence = collectLedgerEvidence([], /* @__PURE__ */ new Set(), []);
11460
13303
  /**
@@ -11469,6 +13312,8 @@ var Ledger = class {
11469
13312
  * @throws {ConversationError} Thrown when `isLedgerSnapshot` admits `snapshot` but its conversation holds a `system` message (code `'ROLE'`) or repeats an id (code `'SNAPSHOT'`)
11470
13313
  */
11471
13314
  constructor(provider, options) {
13315
+ refuseOptionKeys(options, LEDGER_OPTION_KEYS, "Ledger", "LedgerOptions");
13316
+ refuseOptionKeys(options.agent, LEDGER_AGENT_KEYS, "Ledger agent", "LedgerAgentOptions");
11472
13317
  for (const key of [
11473
13318
  "category",
11474
13319
  "topic",
@@ -11546,6 +13391,9 @@ var Ledger = class {
11546
13391
  }) }),
11547
13392
  execute: (args) => this.#recall(args)
11548
13393
  }));
13394
+ this.#builtins = requireBuiltins(options.agent?.builtins, tools);
13395
+ if (this.#builtins.length > 0 && host === void 0) throw new AgentError("AUTHORITY", "agent.builtins are set and no agent.authority is; pass authority: createAuthority({ fallback: { zone: 'default', verdict: 'allow' } }) to allow every call, or rules with a deny fallback");
13396
+ this.#given = requireWorkspace(options.agent?.workspace);
11549
13397
  const advertised = new Authority({
11550
13398
  rules: [{
11551
13399
  match: (context) => names.includes(context.call.name),
@@ -11564,17 +13412,14 @@ var Ledger = class {
11564
13412
  system: options.system,
11565
13413
  tools,
11566
13414
  authority: {
11567
- evaluate: (context) => this.#current()?.denied(context.call.name, context.call.arguments) === true ? {
11568
- zone: "ledger",
11569
- verdict: "deny",
11570
- reason: LEDGER_NOTES.repeat
11571
- } : host === void 0 || context.call.name === "recall" || !names.includes(context.call.name) ? advertised.evaluate(context) : host.evaluate(context),
13415
+ evaluate: (context) => this.#evaluate(context, host, advertised, names),
11572
13416
  ask: (context, decision, signal) => this.#current()?.denied(context.call.name, context.call.arguments) === true ? Promise.resolve(false) : host?.ask === void 0 ? advertised.ask(context, decision, signal) : host.ask(context, decision, signal)
11573
13417
  },
11574
13418
  limit: options.agent?.limit ?? 8,
11575
13419
  select: (conversation, request, signal) => this.#select(conversation, request, signal)
11576
13420
  });
11577
- const digest = digestLedgerTools(this.#agent.context.tools.definitions());
13421
+ const calibrated = this.#calibrated();
13422
+ const digest = digestLedgerTools(calibrated);
11578
13423
  const gauge = options.gauge ?? (snapshot?.gauge?.digest === digest ? snapshot?.gauge : void 0);
11579
13424
  if (gauge !== void 0) {
11580
13425
  this.#gauge = new Gauge({
@@ -11584,10 +13429,10 @@ var Ledger = class {
11584
13429
  predict: this.#predict,
11585
13430
  replay: this.#replay
11586
13431
  });
11587
- this.#digest = digest;
13432
+ this.#measured = calibrated;
11588
13433
  }
11589
13434
  this.#agent.emitter.on("deny", (call, _reason, decision) => {
11590
- if (decision !== void 0 && call.name !== "recall" && names.includes(call.name)) this.#current()?.deny(call.name, call.arguments);
13435
+ if (decision !== void 0 && decision.reason !== LEDGER_NOTES.overflow && call.name !== "recall" && (names.includes(call.name) || this.#enables(call.name))) this.#current()?.deny(call.name, call.arguments);
11591
13436
  });
11592
13437
  this.#agent.emitter.on("tool", (call, result) => {
11593
13438
  this.#flush();
@@ -11600,21 +13445,34 @@ var Ledger = class {
11600
13445
  const request = this.#current();
11601
13446
  if (request?.calls.at(-1)?.tools === 0) request.abort();
11602
13447
  this.#release(call, result);
13448
+ this.#reopen(call, result);
11603
13449
  });
11604
13450
  this.#agent.emitter.on("select", (selection) => {
11605
13451
  if (isLedgerError(selection.fault) && selection.fault.code === "REQUEST") return;
11606
13452
  this.#current()?.adopt(selection, this.#conversation.messages().length);
11607
13453
  });
11608
13454
  this.#agent.emitter.on("fault", (error) => this.#current()?.fault(error));
11609
- this.#agent.emitter.on("turn", () => this.#observeTurn());
13455
+ this.#agent.emitter.on("request", (index, sent) => {
13456
+ if (this.#gate(index, sent)) this.#observeRequest(sent);
13457
+ });
11610
13458
  this.#agent.emitter.on("usage", (usage) => this.#current()?.spend(usage));
13459
+ const agent = this.#agent;
13460
+ this.#record = Object.freeze({
13461
+ emitter: agent.emitter,
13462
+ id: agent.id,
13463
+ get status() {
13464
+ return agent.status;
13465
+ },
13466
+ context: agent.context,
13467
+ abort: (reason) => agent.abort(reason)
13468
+ });
11611
13469
  }
11612
13470
  /**
11613
- * Returns the owned request engine.
11614
- * @returns The engine serving this conversation
13471
+ * Returns the record of the owned request engine, which starts no run.
13472
+ * @returns The frozen record of the agent serving this conversation
11615
13473
  */
11616
13474
  get agent() {
11617
- return this.#agent;
13475
+ return this.#record;
11618
13476
  }
11619
13477
  /**
11620
13478
  * Returns the owned message history.
@@ -11635,9 +13493,10 @@ var Ledger = class {
11635
13493
  }
11636
13494
  /**
11637
13495
  * Measures message scale and tool overhead from provider prompt usage.
11638
- * @param signal - The signal bounding both calibration calls; an abort rejects with its reason
13496
+ * @param signal - The signal bounding every calibration call; an abort rejects with its reason
11639
13497
  * @returns The stored scale and overhead cost
11640
- * @throws {LedgerError} Thrown when either call reports no prompt usage, or a prompt usage of 0 or less (code `'GAUGE'`)
13498
+ * @throws {LedgerError} Thrown when a calibration call reports no prompt usage, or a prompt usage of 0 or less (code `'GAUGE'`)
13499
+ * @throws {LedgerError} Thrown when a calibration call, with the tool definitions, without them, or with the workspace text, reports a prompt over `capacity`, the head included (code `'GAUGE'`)
11641
13500
  * @throws {AgentError} Thrown when a request or calibration is active (code `'CONCURRENCY'`)
11642
13501
  */
11643
13502
  async calibrate(signal) {
@@ -11660,7 +13519,7 @@ var Ledger = class {
11660
13519
  const conversation = this.#conversation.snapshot();
11661
13520
  const ids = conversation.messages.map((message) => message.id);
11662
13521
  const gauge = this.gauge;
11663
- const priced = this.#digest;
13522
+ const priced = this.#digest();
11664
13523
  const window = {
11665
13524
  exchanges: this.#window.map((entry) => ({
11666
13525
  request: entry.request.id,
@@ -11694,13 +13553,15 @@ var Ledger = class {
11694
13553
  /**
11695
13554
  * Appends a request and serves it, recovering an unfinished or rejected first pass with one answer pass.
11696
13555
  * In either pass, a call the model makes in a turn that advertises no tools runs nothing and ends the pass after that generation, whatever the agent's `limit`, and when every call of that turn failed, the ledger stores the reply without its calls: a reply with text ends the pass complete, and one without text ends it partial with empty content.
11697
- * A calibration call that reports no prompt usage, or a prompt usage of 0 or less, rejects with `LedgerError` code `'GAUGE'`; a provider error during calibration rejects with that error.
13556
+ * A calibration call that reports no prompt usage, or a prompt usage of 0 or less, rejects with `LedgerError` code `'GAUGE'`; a provider error during calibration rejects with that error. A calibration call, with the tool definitions, without them, or with the workspace text, that reports a prompt over `capacity`, the head included, rejects with the same code and stores no request.
11698
13557
  * When the answer pass rejects, `respond` rejects with that error, and under the default `strict` a judge failure or another selection failure rejects it too. A rejection belongs to its own call: the ledger stays free, and the next call asks the judge again about whatever is still unanswered.
11699
13558
  * @param content - The request text
11700
13559
  * @param signal - The caller's cancellation signal; an abort during calibration rejects with its reason
11701
13560
  * @returns The final pass, the usage of every pass, and the filing attempts of this request alone
11702
13561
  * @throws {AgentError} Thrown when a request or calibration is active (code `'CONCURRENCY'`)
11703
13562
  * @throws {LedgerError} Thrown when a calibration call reports no prompt usage, or a prompt usage of 0 or less (code `'GAUGE'`)
13563
+ * @throws {LedgerError} Thrown when a calibration call, with the tool definitions, without them, or with the workspace text, reports a prompt over `capacity`, the head included (code `'GAUGE'`)
13564
+ * @throws {LedgerError} Thrown when the answer pass prices over `capacity - predict` with its note left out, or a host act after the note grows its request past that limit (code `'OVERFLOW'`)
11704
13565
  * @throws {ContractError} Thrown when `signal` is defined and is not a native `AbortSignal`
11705
13566
  */
11706
13567
  async respond(content, signal) {
@@ -11708,12 +13569,15 @@ var Ledger = class {
11708
13569
  const caller = createAbort({ ...signal === void 0 ? {} : { signal } }).signal;
11709
13570
  const request = new LedgerRequest(content, this.#options.recall?.limit);
11710
13571
  const scope = this.#agent.context.scope;
11711
- this.#live.add(request);
13572
+ this.#live.set(request, scope);
11712
13573
  try {
11713
- if (this.#gauge === void 0) await this.#measureGauge(caller);
13574
+ if (this.#gauge === void 0 || digestLedgerTools(this.#calibrated()) !== this.#digest()) {
13575
+ this.#gauge = void 0;
13576
+ await this.#measureGauge(caller);
13577
+ }
11714
13578
  const entered = request.enter(this.#conversation);
11715
13579
  this.#requests.add(entered.id);
11716
- const first = this.#dropStrayCalls(request, await this.#generatePass(request, caller, this.#options.think).catch((error) => {
13580
+ const first = this.#dropStrayCalls(request, await this.#generatePass(request, caller, this.#options.think, scope).catch((error) => {
11717
13581
  if (request.faulted(error)) throw error;
11718
13582
  return {
11719
13583
  content: "",
@@ -11732,13 +13596,12 @@ var Ledger = class {
11732
13596
  role: "user",
11733
13597
  content: LEDGER_NOTES.cue
11734
13598
  }).id);
11735
- const previous = this.#agent.context.scope;
13599
+ const filter = intersectFilters(scope, { tools: [] });
11736
13600
  const answer = createScope({
11737
- ...previous,
13601
+ ...filter,
11738
13602
  name: "answer",
11739
- tools: [],
11740
13603
  select: async (conversation, message, runSignal) => {
11741
- const selection = await this.#select(conversation, message, runSignal);
13604
+ const selection = await this.#select(conversation, message, runSignal, filter);
11742
13605
  if (selection.fault !== void 0) return selection;
11743
13606
  return {
11744
13607
  ...selection,
@@ -11746,12 +13609,9 @@ var Ledger = class {
11746
13609
  };
11747
13610
  }
11748
13611
  });
11749
- this.#agent.context.apply(answer);
11750
- try {
11751
- passes.push(this.#dropStrayCalls(request, await this.#generatePass(request, caller, false)));
11752
- } finally {
11753
- if (this.#agent.context.scope === answer) this.#agent.context.apply(previous);
11754
- }
13612
+ passes.push(this.#dropStrayCalls(request, await this.#generatePass(request, caller, false, answer)));
13613
+ const refusal = this.#refusal;
13614
+ if (refusal !== void 0 && !caller.aborted) throw refusal;
11755
13615
  }
11756
13616
  const last = passes.at(-1) ?? first;
11757
13617
  request.think(this.#conversation.messages());
@@ -11777,26 +13637,31 @@ var Ledger = class {
11777
13637
  }
11778
13638
  async #measureGauge(signal) {
11779
13639
  try {
11780
- const messages = stripThinking(this.#agent.context.build({
11781
- messages: [...this.#conversation.view(), {
11782
- id: "calibration",
11783
- role: "user",
11784
- content: ""
11785
- }],
11786
- judgments: []
11787
- }), this.#replay).slice(0, -1);
11788
- const definitions = this.#agent.context.tools.definitions();
13640
+ const messages = this.#agent.context.build({
13641
+ selection: {
13642
+ messages: [],
13643
+ judgments: []
13644
+ },
13645
+ scope: createScope({
13646
+ name: "calibration",
13647
+ workspaces: []
13648
+ })
13649
+ });
13650
+ const definitions = this.#calibrated();
11789
13651
  const priced = await this.#provider.generate(messages, signal, definitions, { think: false });
13652
+ this.#refuseOverCapacity("with", priced.usage?.prompt);
11790
13653
  const bare = await this.#provider.generate(messages, signal, void 0, { think: false });
11791
- if (!isFiniteNumber(priced.usage?.prompt) || priced.usage.prompt <= 0 || !isFiniteNumber(bare.usage?.prompt) || bare.usage.prompt <= 0) throw new LedgerError("GAUGE", "calibration requires prompt usage from both calls");
13654
+ this.#refuseOverCapacity("without", bare.usage?.prompt);
13655
+ if (!isFiniteNumber(priced.usage?.prompt) || priced.usage.prompt <= 0 || !isFiniteNumber(bare.usage?.prompt) || bare.usage.prompt <= 0) throw new LedgerError("GAUGE", "calibration requires prompt usage from each call");
13656
+ const scale = await this.#measureScale(messages, bare.usage.prompt, signal);
11792
13657
  this.#gauge = new Gauge({
11793
13658
  capacity: this.#options.capacity,
11794
13659
  predict: this.#predict,
11795
13660
  replay: this.#replay,
11796
- scale: bare.usage.prompt / estimateMessages(messages),
13661
+ scale,
11797
13662
  overhead: Math.max(0, priced.usage.prompt - bare.usage.prompt)
11798
13663
  });
11799
- this.#digest = digestLedgerTools(definitions);
13664
+ this.#measured = definitions;
11800
13665
  return {
11801
13666
  scale: this.#gauge.scale,
11802
13667
  overhead: this.#gauge.overhead
@@ -11806,13 +13671,53 @@ var Ledger = class {
11806
13671
  throw error;
11807
13672
  }
11808
13673
  }
11809
- async #generatePass(request, signal, think) {
13674
+ async #measureScale(head, bare, signal) {
13675
+ const rate = bare / estimateMessages(head);
13676
+ const workspace = this.#show(intersectFilters(this.#agent.context.scope, void 0)).workspace;
13677
+ const workspaces = this.#agent.context.workspaces;
13678
+ const files = ((workspace === void 0 ? workspaces.active : workspaces.workspace(workspace))?.files() ?? []).flatMap((file) => isTextContent(file.content) ? [file.path] : []);
13679
+ const shown = this.#agent.context.build({
13680
+ selection: {
13681
+ messages: [],
13682
+ judgments: []
13683
+ },
13684
+ scope: createScope({
13685
+ name: "calibration",
13686
+ files
13687
+ }),
13688
+ disclosure: {
13689
+ skills: [],
13690
+ ...workspace === void 0 ? {} : { workspace }
13691
+ }
13692
+ });
13693
+ const whole = estimateMessages(shown) - estimateMessages(head);
13694
+ const cut = cutWorkspaceSample(head, shown, Math.floor((this.#options.capacity - bare) / 3));
13695
+ const part = cut === void 0 ? 0 : estimateMessages(cut) - estimateMessages(head);
13696
+ if (cut === void 0 || whole <= 0 || part <= 0) return rate;
13697
+ const third = await this.#provider.generate(cut, signal, void 0, { think: false });
13698
+ this.#refuseOverCapacity("workspace", third.usage?.prompt);
13699
+ if (!isFiniteNumber(third.usage?.prompt) || third.usage.prompt <= 0) throw new LedgerError("GAUGE", "calibration requires prompt usage from each call");
13700
+ const tokens = bare + (third.usage.prompt - bare) * whole / part;
13701
+ return Math.max(rate, tokens / estimateMessages(shown));
13702
+ }
13703
+ #refuseOverCapacity(call, prompt) {
13704
+ const capacity = this.#options.capacity;
13705
+ const subject = call === "workspace" ? "with the workspace text" : `${call} the tool definitions`;
13706
+ const remedy = call === "workspace" ? "narrow what the scope shows of the workspace, or raise capacity" : "hold tools behind a skill with the `load` built-in, register fewer tools, or raise capacity";
13707
+ if (isFiniteNumber(prompt) && prompt > capacity) throw new LedgerError("GAUGE", `the calibration call ${subject} prices ${prompt} tokens, the head included, over the capacity ${capacity}; ${remedy}`, { context: {
13708
+ capacity,
13709
+ prompt
13710
+ } });
13711
+ }
13712
+ async #generatePass(request, signal, think, scope) {
13713
+ this.#refusal = void 0;
11810
13714
  request.open(this.#conversation.messages().length);
11811
13715
  const stop = request.signal;
11812
13716
  return await this.#agent.generate({
11813
- signal: stop === void 0 ? signal : AbortSignal.any([signal, stop]),
13717
+ signal: stop === void 0 ? signal : linkSignal(signal, stop),
11814
13718
  conversation: this.#conversation,
11815
- ...think === void 0 ? {} : { think }
13719
+ ...think === void 0 ? {} : { think },
13720
+ ...scope === void 0 ? {} : { scope }
11816
13721
  });
11817
13722
  }
11818
13723
  #dropStrayCalls(request, pass) {
@@ -11838,12 +13743,103 @@ var Ledger = class {
11838
13743
  };
11839
13744
  }
11840
13745
  #current() {
11841
- const [request] = this.#live;
13746
+ const [request] = this.#live.keys();
11842
13747
  return request?.message === void 0 ? void 0 : request;
11843
13748
  }
11844
13749
  #busy() {
11845
13750
  return this.#live.size > 0 || this.#calibrations.size > 0;
11846
13751
  }
13752
+ #evaluate(context, host, advertised, names) {
13753
+ const request = this.#current();
13754
+ const { name, arguments: args } = context.call;
13755
+ if (request?.denied(name, args) === true) return {
13756
+ zone: "ledger",
13757
+ verdict: "deny",
13758
+ reason: LEDGER_NOTES.repeat
13759
+ };
13760
+ if (this.#enables(name)) {
13761
+ const admitted = attempt(() => request?.admit(name, args));
13762
+ if (!admitted.success) {
13763
+ if (isError(admitted.error) && admitted.error.message === LEDGER_NOTES.repeat) return {
13764
+ zone: "ledger",
13765
+ verdict: "deny",
13766
+ reason: LEDGER_NOTES.repeat
13767
+ };
13768
+ throw admitted.error;
13769
+ }
13770
+ if (request !== void 0) {
13771
+ const commitment = this.#room(request, name, args);
13772
+ if (commitment === void 0) return {
13773
+ zone: "ledger",
13774
+ verdict: "deny",
13775
+ reason: LEDGER_NOTES.overflow
13776
+ };
13777
+ request.commit(commitment.price, commitment.skill);
13778
+ }
13779
+ return host === void 0 ? advertised.evaluate(context) : host.evaluate(context);
13780
+ }
13781
+ const decision = host === void 0 || name === "recall" || !names.includes(name) ? advertised.evaluate(context) : host.evaluate(context);
13782
+ if (request !== void 0 && decision.verdict !== "deny" && name !== "recall" && names.includes(name)) request.commit(this.#priceResult(request.calls));
13783
+ return decision;
13784
+ }
13785
+ #room(request, name, args) {
13786
+ if (name !== "load" && name !== "remember" && name !== "switch") return { price: 0 };
13787
+ const gauge = this.#gauge;
13788
+ if (gauge === void 0) return void 0;
13789
+ const room = gauge.remainder(request.calls) - this.#predict;
13790
+ const admitted = admitValue(builtinToolContracts[name].contract, { ...args });
13791
+ const values = admitted.success ? admitted.value.value : {};
13792
+ if (name === "remember") {
13793
+ const line = isString(values["name"]) && isString(values["description"]) ? renderIndexEntry({
13794
+ name: values["name"],
13795
+ description: values["description"]
13796
+ }) : "";
13797
+ const price = gauge.scale * estimateTokens(line);
13798
+ return (request.committed + price) * 1.06 > room ? void 0 : { price };
13799
+ }
13800
+ const ceiling = this.#ceiling(request);
13801
+ const shown = this.#show(ceiling);
13802
+ if (name === "switch") {
13803
+ const workspace = values["workspace"];
13804
+ const price = isString(workspace) ? gauge.scale * Math.max(0, this.#estimateHead(request, ceiling, {
13805
+ skills: shown.skills,
13806
+ workspace
13807
+ }) - this.#estimateHead(request, ceiling, shown)) : 0;
13808
+ return (request.committed + price) * 1.06 > room ? void 0 : { price };
13809
+ }
13810
+ const thread = [.../* @__PURE__ */ new Set([...shown.skills, ...request.loads])];
13811
+ const skill = filterAllowList(ceiling.skills, this.#agent.context.skills.skills(), (one) => one.name).find((one) => one.name === values["skill"]);
13812
+ if (skill === void 0 || thread.includes(skill.name)) return { price: 0 };
13813
+ const price = this.#priceSkill(skill, ceiling, this.#advertise(ceiling, thread));
13814
+ const budget = (this.#options.capacity - this.#predict) * this.#share.prompt;
13815
+ return (request.committed + price + this.#priceResult(request.calls)) * 1.06 > room || this.#priceShown({ skills: thread }, ceiling) + price > this.#share.skills * budget ? void 0 : {
13816
+ price,
13817
+ skill: skill.name
13818
+ };
13819
+ }
13820
+ #estimateHead(request, ceiling, shown) {
13821
+ return estimateMessages(stripThinking(this.#agent.context.build({
13822
+ ...request.selection === void 0 ? {} : { selection: request.selection },
13823
+ disclosure: shown,
13824
+ switchable: this.#advertise(ceiling, shown.skills).some((tool) => tool.name === "switch")
13825
+ }), this.#replay));
13826
+ }
13827
+ #reopen(call, result) {
13828
+ const request = this.#current();
13829
+ const entered = request?.message;
13830
+ if (request === void 0 || entered === void 0 || !result.success || !this.#enables(call.name)) return;
13831
+ const messages = this.#conversation.messages();
13832
+ const pairs = collectToolGroups(messages.slice(messages.findIndex((message) => message.id === entered.id) + 1)).flatMap((group) => group.slice(1).flatMap((message) => {
13833
+ const owner = findToolCall(group, message);
13834
+ return owner === void 0 ? [] : [{
13835
+ call: owner,
13836
+ content: message.content
13837
+ }];
13838
+ }));
13839
+ const key = canonicalStringify(call.arguments);
13840
+ const reopened = pairs.filter(({ call: earlier, content }) => call.name === "unload" ? earlier.name === "load" && earlier.arguments.skill === call.arguments.skill || content === settleToolResult(denyCall(earlier, LEDGER_NOTES.overflow)).content : call.name === "load" ? earlier.name === "unload" && earlier.arguments.skill === call.arguments.skill : call.name === "switch" ? earlier.name === "switch" && canonicalStringify(earlier.arguments) !== key : call.name === "remember" && earlier.name === "memo" && earlier.arguments.name === call.arguments.name);
13841
+ for (const { call: earlier } of reopened) request.release(earlier.name, earlier.arguments);
13842
+ }
11847
13843
  #flush() {
11848
13844
  if (this.#pending.size === 0) return;
11849
13845
  const messages = this.#conversation.messages();
@@ -11894,7 +13890,7 @@ var Ledger = class {
11894
13890
  for (const message of messages) {
11895
13891
  if (!snapshot.failures.includes(message.id)) continue;
11896
13892
  const group = groups.find((entries) => entries.some((one) => one.id === message.id));
11897
- const call = group === void 0 ? void 0 : findLedgerCall(group, message);
13893
+ const call = group === void 0 ? void 0 : findToolCall(group, message);
11898
13894
  this.#results.set(message.id, {
11899
13895
  success: false,
11900
13896
  id: call?.id ?? message.call ?? message.id,
@@ -11924,7 +13920,7 @@ var Ledger = class {
11924
13920
  #readLookups(messages) {
11925
13921
  this.#flush();
11926
13922
  return collectToolGroups(messages).flatMap((group) => group.slice(1).flatMap((message) => {
11927
- const call = findLedgerCall(group, message);
13923
+ const call = findToolCall(group, message);
11928
13924
  const lookup = this.#options.lookups?.find((one) => one.tool.name === call?.name);
11929
13925
  const write = this.#options.writes?.find((one) => one.tool.name === call?.name);
11930
13926
  if (call === void 0 || lookup === void 0 && write === void 0 || this.#results.get(message.id)?.success === false) return [];
@@ -11991,7 +13987,7 @@ var Ledger = class {
11991
13987
  const start = messages.findIndex((message) => message.id === request.id);
11992
13988
  return messages.slice(start + 1).filter((message) => message.role !== "assistant" || hasCalls(message) || message.content.trim() !== "");
11993
13989
  }
11994
- async #select(conversation, message, signal) {
13990
+ async #select(conversation, message, signal, filter) {
11995
13991
  const request = this.#current();
11996
13992
  const selected = request?.message;
11997
13993
  if (conversation !== this.#conversation || request === void 0 || selected === void 0 || message.id !== selected.id && !this.#annotations.has(message.id)) return this.#refuse(new LedgerError("REQUEST", "ledger selection requires a request owned by an active respond call"), { judgments: [] }, conversation);
@@ -12003,7 +13999,7 @@ var Ledger = class {
12003
13999
  const scanned = attempt(() => this.#scan(this.#conversation.messages()));
12004
14000
  if (scanned.success) this.#hold(scanned.value);
12005
14001
  try {
12006
- return await this.#classifier.classify(this.#requests, signal).then((classified) => this.#file(classified, request, selected, message), (error) => this.#refuse(error, { judgments: [] }, this.#conversation));
14002
+ return await this.#classifier.classify(this.#requests, signal).then((classified) => this.#file(classified, request, selected, message, filter ?? this.#live.get(request)), (error) => this.#refuse(error, { judgments: [] }, this.#conversation));
12007
14003
  } finally {
12008
14004
  const [scan] = this.#scans;
12009
14005
  if (scan !== void 0) this.#scans.delete(scan);
@@ -12025,11 +14021,11 @@ var Ledger = class {
12025
14021
  this.#hold(scan);
12026
14022
  return scan;
12027
14023
  }
12028
- #file(classified, request, selected, message) {
14024
+ #file(classified, request, selected, message, filter) {
12029
14025
  const { attempts, failure, ...filed } = classified;
12030
14026
  const planned = attempt(() => {
12031
14027
  if (filed.fault !== void 0) throw filed.fault;
12032
- const { draft, ...plan } = this.#plan(selected, this.#rescan());
14028
+ const { draft, ...plan } = this.#plan(selected, this.#rescan(), filter);
12033
14029
  return {
12034
14030
  draft,
12035
14031
  selection: {
@@ -12062,7 +14058,7 @@ var Ledger = class {
12062
14058
  const category = this.#classifier.category(source);
12063
14059
  return !(role === "user" && !this.#classifier.decisive(source)) && (category === "rule" || category === "correction");
12064
14060
  }
12065
- #plan(request, scan) {
14061
+ #plan(request, scan, filter) {
12066
14062
  const { input, projection } = this.#project(scan);
12067
14063
  const registry = scan.registry;
12068
14064
  const links = linkOwners(input.findings, registry.owners);
@@ -12074,10 +14070,20 @@ var Ledger = class {
12074
14070
  }),
12075
14071
  topics: [...near]
12076
14072
  });
12077
- const total = Math.max(0, (this.#options.capacity - this.#predict) * this.#share.prompt - (this.#gauge?.overhead ?? 0)) / (1 + LEDGER_SCALE_DRIFT);
14073
+ const lists = intersectFilters(void 0, filter);
14074
+ const bound = lists.tools;
14075
+ const disclosure = this.#show(lists);
14076
+ const advertised = this.#advertise(lists, disclosure.skills);
14077
+ const calibrated = this.#measuredSet();
14078
+ const price = computeToolPrice(calibrated, advertised, this.#priced());
14079
+ const total = Math.max(0, (this.#options.capacity - this.#predict) * this.#share.prompt - (this.#priced().overhead - price.spared + price.added) - this.#holdback(lists, disclosure, advertised, [])) / (1 + LEDGER_SCALE_DRIFT);
12078
14080
  const built = this.#agent.context.build({
12079
- messages: [request],
12080
- judgments: []
14081
+ selection: {
14082
+ messages: [request],
14083
+ judgments: []
14084
+ },
14085
+ disclosure,
14086
+ switchable: advertised.some((tool) => tool.name === "switch")
12081
14087
  });
12082
14088
  const tail = this.#selectTail(request, total, input, scan);
12083
14089
  const tailIds = new Set(tail.map((message) => message.id));
@@ -12186,23 +14192,24 @@ var Ledger = class {
12186
14192
  ...rung.window.flatMap((entry) => [entry.request, entry.reply]),
12187
14193
  buildRequestMessage(built.at(-1) ?? request, rung.rendered.text)
12188
14194
  ], this.#replay)]);
12189
- const names = this.#agent.context.scope?.tools;
12190
- const definitions = this.#agent.context.tools.definitions();
12191
14195
  const offered = rungs.map((rung) => hasHiddenRecall(input, request.id, this.#requests, this.#annotations, [...tail.slice(0, -1), ...rung.window.flatMap((entry) => [entry.request, entry.reply])], [...rung.window.flatMap((entry) => entry.lines), ...rung.rendered.lines]));
12192
14196
  const longest = this.#findLongest();
12193
14197
  const closed = probes.map((messages, at) => {
12194
- const tools = definitions.filter((tool) => (names === void 0 || names.includes(tool.name)) && (tool.name !== "recall" || offered[at]));
14198
+ const tools = advertised.filter((tool) => tool.name !== "recall" || offered[at]);
12195
14199
  const calls = [{
12196
14200
  estimate: estimateMessages(messages),
12197
14201
  tools: tools.length,
12198
- spared: this.#spared(tools)
14202
+ ...computeToolPrice(calibrated, tools, this.#priced())
12199
14203
  }];
12200
14204
  return offered[at] === true && this.#gauge !== void 0 && this.#gauge.remainder(calls) - this.#predict < 2 * this.#gauge.reserve(calls, longest);
12201
14205
  });
12202
14206
  const prices = probes.map((messages) => this.#price(messages));
12203
14207
  const admitted = rungs.find((_rung, at) => (prices[at] ?? Infinity) <= total && (closed[2] === true || closed[at] === false)) ?? empty;
12204
- if (offered[rungs.indexOf(admitted)] === false && (names === void 0 || names.includes("recall"))) {
12205
- const tools = definitions.filter((tool) => tool.name !== "recall").map((tool) => tool.name);
14208
+ const recall = offered[rungs.indexOf(admitted)] === true;
14209
+ const ceiling = intersectKeys(this.#agent.context.scope?.tools, bound);
14210
+ const admits = ceiling === void 0 || ceiling.includes("recall");
14211
+ if (!recall && admits) {
14212
+ const tools = this.#definitions().filter((tool) => tool.name !== "recall").map((tool) => tool.name);
12206
14213
  const narrowed = this.#agent.context.scope?.narrow({ tools }) ?? createScope({
12207
14214
  name: "ledger",
12208
14215
  tools
@@ -12225,10 +14232,11 @@ var Ledger = class {
12225
14232
  window: admitted.window
12226
14233
  };
12227
14234
  const shown = buildLedgerRenderContext(scan.messages, [...kept, ...admitted.rendered.lines], []).complete;
14235
+ const route = recall && admits;
12228
14236
  return {
12229
14237
  draft,
12230
14238
  messages: [
12231
- ...tail.slice(0, -1).map((message) => message.role === "tool" ? this.#renderTailStub(message, scan, shown) : message),
14239
+ ...tail.slice(0, -1).map((message) => message.role === "tool" ? this.#renderTailStub(message, scan, shown, route) : message),
12232
14240
  ...admitted.window.flatMap((entry) => [entry.request, entry.reply]),
12233
14241
  copy
12234
14242
  ]
@@ -12316,7 +14324,7 @@ var Ledger = class {
12316
14324
  return [{
12317
14325
  leader,
12318
14326
  kept: (leader.calls ?? []).flatMap((call) => {
12319
- const message = group.slice(1).find((result) => findLedgerCall(group, result) === call);
14327
+ const message = group.slice(1).find((result) => findToolCall(group, result) === call);
12320
14328
  const result = message === void 0 ? void 0 : this.#results.get(message.id);
12321
14329
  return message === void 0 || ![...this.#options.lookups ?? [], ...this.#options.writes ?? []].some((entry) => entry.tool.name === call.name) || result?.success === false && result.error === LEDGER_NOTES.repeat ? [] : [{
12322
14330
  call,
@@ -12361,16 +14369,16 @@ var Ledger = class {
12361
14369
  amendments: evidence.amendments
12362
14370
  };
12363
14371
  }
12364
- #renderTailStub(message, scan, shown) {
14372
+ #renderTailStub(message, scan, shown, offered = true) {
12365
14373
  const group = scan.group(message.id);
12366
- const call = group === void 0 ? void 0 : findLedgerCall(group, message);
14374
+ const call = group === void 0 ? void 0 : findToolCall(group, message);
12367
14375
  const write = this.#options.writes?.some((one) => one.tool.name === call?.name) === true;
12368
14376
  const finding = scan.finding(message.id);
12369
14377
  const hidden = renderStub(call?.name ?? "tool", call?.arguments ?? {}, "hidden");
12370
14378
  const visible = renderStub(call?.name ?? "tool", call?.arguments ?? {}, "shown");
12371
14379
  return {
12372
14380
  ...message,
12373
- content: renderStub(call?.name ?? "tool", call?.arguments ?? {}, this.#results.get(message.id)?.success === false ? "failed" : finding?.result === void 0 ? "empty" : shown === void 0 ? hidden.length > visible.length ? "hidden" : "shown" : scan.findings.some((other) => shown.has(other.id) && matchesLookup(finding, other)) ? "shown" : "hidden", write)
14381
+ content: renderStub(call?.name ?? "tool", call?.arguments ?? {}, this.#results.get(message.id)?.success === false ? "failed" : finding?.result === void 0 ? "empty" : shown === void 0 ? hidden.length > visible.length ? "hidden" : "shown" : scan.findings.some((other) => shown.has(other.id) && matchesLookup(finding, other)) ? "shown" : "hidden", write, offered)
12374
14382
  };
12375
14383
  }
12376
14384
  #release(call, result) {
@@ -12401,26 +14409,71 @@ var Ledger = class {
12401
14409
  }]);
12402
14410
  for (const finding of findings) if ((edges.get(finding.id) ?? []).includes(id) && this.#options.lookups?.some((lookup) => lookup.tool.name === finding.name) === true) request.release(finding.name, finding.arguments);
12403
14411
  }
12404
- #observeTurn() {
14412
+ #observeRequest(sent) {
12405
14413
  this.#flush();
12406
14414
  const request = this.#current();
12407
- const boundary = request?.boundary;
12408
- if (request === void 0 || boundary === void 0 || request.aborted) return;
12409
- const additions = this.#conversation.messages().slice(boundary);
12410
- const messages = this.#agent.context.build(request.selection);
12411
- const names = this.#agent.context.scope?.tools;
12412
- const tools = this.#agent.context.tools.definitions().filter((tool) => names === void 0 || names.includes(tool.name));
14415
+ if (request?.boundary === void 0) return;
14416
+ const tools = sent.tools ?? [];
12413
14417
  request.observe({
12414
- estimate: estimateMessages(stripThinking([...messages, ...additions], this.#replay)),
14418
+ estimate: estimateMessages(sent.messages),
12415
14419
  tools: tools.length,
12416
- spared: this.#spared(tools)
14420
+ ...computeToolPrice(this.#measuredSet(), tools, this.#priced())
12417
14421
  }, this.#conversation.messages().length);
12418
14422
  }
12419
- #spared(tools) {
12420
- const overhead = this.#gauge?.overhead ?? 0;
12421
- if (tools.length === 0) return overhead;
12422
- const missing = this.#agent.context.tools.definitions().filter((tool) => !tools.some((one) => one.name === tool.name));
12423
- return missing.length === 0 ? 0 : Math.min(overhead, estimateTokens(JSON.stringify(missing)) * (this.#gauge?.scale ?? 1));
14423
+ #priced() {
14424
+ return this.#gauge ?? {
14425
+ scale: 1,
14426
+ overhead: 0
14427
+ };
14428
+ }
14429
+ #measuredSet() {
14430
+ return this.#measured ?? this.#calibrated();
14431
+ }
14432
+ #digest() {
14433
+ return this.#measured === void 0 ? void 0 : digestLedgerTools(this.#measured);
14434
+ }
14435
+ #enables(name) {
14436
+ return this.#builtins.some((one) => one === name);
14437
+ }
14438
+ #definitions() {
14439
+ return [...this.#agent.context.tools.definitions().filter((tool) => !this.#enables(tool.name)), ...collectBuiltinDefinitions({ builtins: this.#builtins })];
14440
+ }
14441
+ #calibrated() {
14442
+ const definitions = this.#definitions();
14443
+ if (!this.#enables("load")) return definitions;
14444
+ const held = new Set(this.#agent.context.skills.skills().flatMap((skill) => skill.tools));
14445
+ return definitions.filter((tool) => !held.has(tool.name));
14446
+ }
14447
+ #show(ceiling) {
14448
+ return resolveDisclosure(this.#agent.context, this.#conversation, this.#given, ceiling, this.#builtins);
14449
+ }
14450
+ #advertise(ceiling, shown) {
14451
+ return filterAdvertisedTools(filterBuiltinCandidates(this.#definitions(), ceiling), ceiling.tools, this.#enables("load") ? this.#agent.context.skills.skills() : [], shown);
14452
+ }
14453
+ #ceiling(request) {
14454
+ return intersectFilters(this.#agent.context.scope, this.#live.get(request));
14455
+ }
14456
+ #priceSkill(skill, ceiling, advertised) {
14457
+ const sent = new Set(advertised.map((tool) => tool.name));
14458
+ return computeSkillPrice(skill, filterAllowList(ceiling.tools, this.#definitions().filter((tool) => skill.tools.includes(tool.name) && !sent.has(tool.name)), (tool) => tool.name), this.#measuredSet(), this.#priced());
14459
+ }
14460
+ #priceShown(shown, ceiling) {
14461
+ const skills = shown.skills.flatMap((name) => this.#agent.context.skills.skill(name) ?? []);
14462
+ const named = new Set(skills.flatMap((skill) => skill.tools));
14463
+ const definitions = filterAllowList(ceiling.tools, this.#definitions().filter((tool) => named.has(tool.name)), (tool) => tool.name);
14464
+ const calibrated = this.#measuredSet();
14465
+ const gauge = this.#priced();
14466
+ return skills.reduce((sum, skill) => sum + computeSkillPrice(skill, [], calibrated, gauge), 0) + computeToolPrice(calibrated, [...calibrated, ...definitions], gauge).added;
14467
+ }
14468
+ #priceResult(calls) {
14469
+ const longest = this.#conversation.messages().filter((message) => message.role === "tool").reduce((found, message) => found === void 0 || message.content.length > found.content.length ? message : found, void 0);
14470
+ const gauge = this.#gauge;
14471
+ return Math.max(this.#priced().scale * (longest === void 0 ? 0 : estimateMessages([longest])), gauge === void 0 ? 0 : gauge.reserve(calls, this.#findLongest()));
14472
+ }
14473
+ #holdback(ceiling, shown, advertised, calls) {
14474
+ if (!advertised.some((tool) => tool.name === "load")) return 0;
14475
+ const loadable = filterAllowList(ceiling.skills, this.#agent.context.skills.skills(), (skill) => skill.name).filter((skill) => !shown.skills.includes(skill.name));
14476
+ return loadable.length === 0 ? 0 : Math.max(...loadable.map((skill) => this.#priceSkill(skill, ceiling, advertised))) + this.#priceResult(calls);
12424
14477
  }
12425
14478
  #findLongest() {
12426
14479
  return this.#conversation.messages().filter((message) => message.role === "assistant").reduce((longest, message) => message.content.length > longest.length ? message.content : longest, "");
@@ -12448,12 +14501,7 @@ var Ledger = class {
12448
14501
  request?.recall();
12449
14502
  const guidance = `an owner name, an id, or one of ${renderTopicNames(this.#options.topics)}`;
12450
14503
  if (topic === "") throw new Error(`recall needs a topic: ${guidance}`);
12451
- const rate = this.#recallRate(request) * (1 + LEDGER_SCALE_DRIFT);
12452
- const call = calls.at(-1);
12453
- const carried = request === void 0 ? 0 : estimateMessages(stripThinking([...this.#agent.context.build(request.selection), ...this.#conversation.messages().slice(request.boundary)], this.#replay));
12454
- const completion = isFiniteNumber(call?.prompt) ? (call.completion ?? 0) - (this.#replay === "none" ? call.thinking ?? 0 : 0) : 0;
12455
- const extra = Math.max(0, (carried - (call?.estimate ?? carried)) * rate - completion);
12456
- const drift = isFiniteNumber(call?.prompt) ? 0 : Math.max(0, (call?.estimate ?? 0) * (rate - (gauge?.scale ?? rate)));
14504
+ const { rate, extra, slack: drift } = this.#carry(request, calls);
12457
14505
  const siblings = estimateMessages((request?.listings ?? []).filter((listing) => listing.turn === calls.length).map((listing) => ({
12458
14506
  id: "result",
12459
14507
  role: "tool",
@@ -12528,7 +14576,7 @@ var Ledger = class {
12528
14576
  this.#flush();
12529
14577
  const groups = [...new Set(this.#collectAfter(entered).flatMap((message) => {
12530
14578
  const result = this.#results.get(message.id);
12531
- if (message.role !== "tool" || result?.success !== true) return [];
14579
+ if (message.role !== "tool" || result?.success !== true || result.name !== "memo" && this.#enables(result.name)) return [];
12532
14580
  const recalled = result.name === "recall";
12533
14581
  if (recalled && /^nothing earlier on /.test(message.content)) return [];
12534
14582
  const listing = recalled ? request.listings.findLast((one) => one.result === message.content) : void 0;
@@ -12537,7 +14585,7 @@ var Ledger = class {
12537
14585
  const unique = groups.filter((group, at) => !splitResultLines(group).every((line) => groups.slice(0, at).some((earlier) => splitResultLines(earlier).includes(line))));
12538
14586
  const digest = unique.length === 0 ? void 0 : `${LEDGER_NOTES.results}\n${unique.join("\n")}`;
12539
14587
  const omitted = /* @__PURE__ */ new Set();
12540
- const rate = this.#recallRate(request) * (1 + LEDGER_SCALE_DRIFT);
14588
+ const rate = this.#capacityRate(request) * (1 + LEDGER_SCALE_DRIFT);
12541
14589
  const allowance = (this.#options.capacity - this.#predict) / rate;
12542
14590
  const after = this.#collectAfter(entered);
12543
14591
  const messages = [
@@ -12554,28 +14602,105 @@ var Ledger = class {
12554
14602
  role: "user",
12555
14603
  content: digest
12556
14604
  }];
14605
+ const shown = this.#show(this.#ceiling(request));
12557
14606
  if (this.#gauge === void 0 || estimateMessages(stripThinking(this.#agent.context.build({
12558
- messages: [...messages, ...note],
12559
- judgments: []
14607
+ selection: {
14608
+ messages: [...messages, ...note],
14609
+ judgments: []
14610
+ },
14611
+ disclosure: shown
12560
14612
  }), this.#replay)) <= allowance) return {
12561
14613
  digest,
12562
14614
  omitted
12563
14615
  };
12564
14616
  const partials = new Set(after.filter((message) => message.role === "assistant" && !hasCalls(message)).map((message) => message.id));
12565
- const fitted = cutListing(unique, allowance - estimateMessages(stripThinking(this.#agent.context.build({
12566
- messages: messages.filter((message) => !partials.has(message.id)),
12567
- judgments: []
12568
- }), this.#replay)) - estimateTokens(`${LEDGER_NOTES.results}\n`), "more", false);
14617
+ const base = estimateMessages(stripThinking(this.#agent.context.build({
14618
+ selection: {
14619
+ messages: messages.filter((message) => !partials.has(message.id)),
14620
+ judgments: []
14621
+ },
14622
+ disclosure: shown
14623
+ }), this.#replay));
14624
+ if (base > allowance) throw new LedgerError("OVERFLOW", `the answer pass prices ${Math.ceil(base * rate)} tokens with every cut made, over the capacity ${this.#options.capacity} less predict ${this.#predict}; shorten the request, narrow what the scope shows, or raise capacity`, { context: {
14625
+ capacity: this.#options.capacity,
14626
+ predict: this.#predict,
14627
+ price: base * rate
14628
+ } });
14629
+ const fitted = cutListing(unique, allowance - base - estimateTokens(`${LEDGER_NOTES.results}\n`), "more", false);
14630
+ const cut = fitted === "" ? void 0 : `${LEDGER_NOTES.results}\n${fitted}`;
12569
14631
  return {
12570
- digest: fitted === "" ? void 0 : `${LEDGER_NOTES.results}\n${fitted}`,
14632
+ digest: cut !== void 0 && base + estimateMessages([{
14633
+ id: "results",
14634
+ role: "user",
14635
+ content: cut
14636
+ }]) > allowance ? void 0 : cut,
12571
14637
  omitted: partials
12572
14638
  };
12573
14639
  }
14640
+ #carry(request, calls) {
14641
+ const rate = this.#recallRate(request) * (1 + LEDGER_SCALE_DRIFT);
14642
+ const ceiling = request === void 0 ? {} : this.#ceiling(request);
14643
+ const shown = this.#show(ceiling);
14644
+ const carried = request === void 0 ? 0 : estimateMessages(stripThinking([...this.#agent.context.build({
14645
+ ...request.selection === void 0 ? {} : { selection: request.selection },
14646
+ disclosure: shown,
14647
+ switchable: this.#advertise(ceiling, shown.skills).some((tool) => tool.name === "switch")
14648
+ }), ...this.#conversation.messages().slice(request.boundary)], this.#replay));
14649
+ return {
14650
+ rate,
14651
+ ...this.#terms(calls.at(-1), carried, rate)
14652
+ };
14653
+ }
14654
+ #terms(call, carried, rate) {
14655
+ const reply = isFiniteNumber(call?.prompt) ? (call.completion ?? 0) - (this.#replay === "none" ? call.thinking ?? 0 : 0) : 0;
14656
+ return {
14657
+ extra: Math.max(0, (carried - (call?.estimate ?? carried)) * rate - reply),
14658
+ slack: isFiniteNumber(call?.prompt) ? 0 : Math.max(0, (call?.estimate ?? 0) * (rate - (this.#gauge?.scale ?? rate)))
14659
+ };
14660
+ }
14661
+ #gate(index, sent) {
14662
+ const request = this.#current();
14663
+ if (request?.boundary === void 0) return true;
14664
+ const left = attempt(() => index === 0 ? this.#first(request, sent) : this.#next(request, sent));
14665
+ if (left.success && left.value >= 0) return true;
14666
+ const limit = this.#options.capacity - this.#predict;
14667
+ this.#refusal = new LedgerError("OVERFLOW", left.success ? `the request prices ${Math.ceil(limit - left.value)} tokens, over the capacity ${this.#options.capacity} less predict ${this.#predict}; shorten the request, narrow what the scope shows, or raise capacity` : `the request could not be priced against the capacity ${this.#options.capacity} less predict ${this.#predict}`, { context: {
14668
+ capacity: this.#options.capacity,
14669
+ predict: this.#predict,
14670
+ price: left.success ? limit - left.value : Number.POSITIVE_INFINITY
14671
+ } });
14672
+ this.#agent.abort("overflow");
14673
+ return false;
14674
+ }
14675
+ #first(request, sent) {
14676
+ const gauge = this.#gauge;
14677
+ if (gauge === void 0) throw new LedgerError("GAUGE", "the gate needs a gauge");
14678
+ const tools = computeToolPrice(this.#measuredSet(), sent.tools ?? [], gauge);
14679
+ const rate = request.calls.length === 0 ? gauge.scale : this.#capacityRate(request);
14680
+ return this.#options.capacity - this.#predict - (Math.max(0, gauge.overhead - tools.spared) + tools.added + rate * (1 + LEDGER_SCALE_DRIFT) * estimateMessages(sent.messages));
14681
+ }
14682
+ #next(request, sent) {
14683
+ request.think(this.#conversation.messages());
14684
+ const gauge = this.#gauge;
14685
+ if (gauge === void 0) throw new LedgerError("GAUGE", "the gate needs a gauge");
14686
+ const calls = request.calls;
14687
+ const last = calls.at(-1);
14688
+ if (last === void 0) throw new Error("a later request has no recorded call before it");
14689
+ const measured = this.#measuredSet();
14690
+ const rate = this.#capacityRate(request) * (1 + LEDGER_SCALE_DRIFT);
14691
+ const { extra, slack } = this.#terms(last, estimateMessages(sent.messages), rate);
14692
+ const tools = computeToolPrice(measured, sent.tools ?? [], gauge);
14693
+ const grown = (Math.min(gauge.overhead, Math.max(0, (last.spared ?? 0) - tools.spared) * computeToolDensity(measured, gauge) / gauge.scale) + Math.max(0, tools.added - (last.added ?? 0))) * (1 + LEDGER_SCALE_DRIFT);
14694
+ return gauge.remainder(calls) - this.#predict - extra - slack - grown;
14695
+ }
14696
+ #capacityRate(request) {
14697
+ return Math.max(this.#recallRate(request), this.#gauge?.scale ?? 1);
14698
+ }
12574
14699
  #recallRate(request) {
12575
14700
  const gauge = this.#gauge;
12576
14701
  if (gauge === void 0) return 1;
12577
14702
  const calls = request?.calls ?? [];
12578
- const last = calls.findLast((call) => isFiniteNumber(call.prompt));
14703
+ const last = calls.findLast((call) => isFiniteNumber(call.prompt) && (call.added ?? 0) === 0);
12579
14704
  const measured = last !== void 0 && isFiniteNumber(last.prompt) && last.estimate > 0 && ((last.spared ?? 0) === 0 || (last.spared ?? 0) >= gauge.overhead) ? (last.prompt - Math.max(0, gauge.overhead - (last.spared ?? 0))) / last.estimate : 0;
12580
14705
  return Math.max(gauge.rate(calls), measured);
12581
14706
  }
@@ -12596,6 +14721,6 @@ var Ledger = class {
12596
14721
  function createLedger(provider, options) {
12597
14722
  return new Ledger(provider, options);
12598
14723
  }
12599
- export { AUTHORITY_NOTES, Agent, AgentContext, AgentError, AgentFanout, AgentJobError, AgentJudge, AgentProvider, AgentRegistry, Approver, Authority, CONVERSATION_RECAP_PREFIX, CONVERSATION_ROLES, Channel, Classifier, ContextError, Conversation, ConversationError, ConversationManager, DECISIVE_CATEGORIES, DEFAULT_AGENT_LIMIT, DEFAULT_CONVERSATION_KEEP, DEFAULT_LEDGER_LIMIT, DEFAULT_LEDGER_SHARE, DEFAULT_PROVIDER_TIMEOUT, DEFAULT_RECALL_LIMIT, DEFAULT_RELAY_LIMIT, DETERMINISTIC_JUDGE_ERROR, DatabaseConversationStore, DatabaseMemoStore, Gauge, IMAGE_TOKEN_ESTIMATE, INVALID_RELAY_STATUS, Instruction, InstructionManager, JudgeAbortError, JudgeError, JudgmentManager, LEDGER_CATEGORIES, LEDGER_NOTES, LEDGER_OWNER_PREFIX, LEDGER_QUESTIONS, LEDGER_RECALL_LABELS, LEDGER_RULES_KEY, LEDGER_SCALE_DRIFT, LEDGER_SLICE, LEDGER_WORD, Ledger, LedgerError, LedgerRequest, MAX_ERROR_BODY_LENGTH, MEMO_SECTION_HEADER, MESSAGE_ROLES, MESSAGE_TOKEN_OVERHEAD, MemoManager, MemoryConversationStore, MemoryMemoStore, OVERSIZED_RELAY_STATUS, PLACED_CATEGORIES, ProviderAbortError, ProviderError, QUIET_CATEGORIES, REFUSED_RELAY_CONTENT_TYPE, REFUSED_RELAY_STATUS, RELAY_CONTENT_TYPE, RELAY_PROVIDER_MESSAGE, RelayProvider, RelayStream, SCOPE_NOTE, SKILL_SECTION_HEADER, SYSTEM_ONE_PATH, Scope, ScopeManager, SkillManager, SystemOneJudge, THINK_CLOSE, THINK_OPEN, ThinkSplitter, UNAUTHORIZED_RELAY_STATUS, UPSTREAM_RELAY_STATUS, WORKSPACE_SECTION_HEADER, agentAnswerContract, agentAnswerShape, agentChunkToFrame, agentFrameContract, agentFrameShape, agentJobContract, agentJobShape, agentPromptContract, agentPromptShape, agentResultToFrame, agentResultToJSON, agentStreamToFrames, armReaderAbort, assembleResult, attachImages, attachUserImages, buildJudgeResult, buildJudgments, buildLedgerCut, buildLedgerIndex, buildLedgerLineKey, buildLedgerRenderContext, buildLines, buildProviderHeaders, buildProviderResult, buildRecallMessage, buildRecapMessage, buildRecords, buildRelayRequest, buildRequestMessage, buildSummaryMessage, chargeUsage, collectAmendments, collectExchanges, collectImageData, collectLedgerEvidence, collectLedgerLines, collectLedgerReplies, collectLive, collectNames, collectProjectionIds, collectRecallMessages, collectRegistry, collectRetiredFindings, collectToolGroups, collectWriteSupersessions, computeLedgerChecksum, computeThinking, conversationSnapshotContract, conversationSnapshotShape, copyJSON, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createApprover, createAuthority, createChannel, createConversation, createConversationManager, createDatabaseConversationStore, createDatabaseMemoStore, createInstruction, createInstructionManager, createLedger, createMemoManager, createMemoryConversationStore, createMemoryMemoStore, createRelay, createRelayProvider, createScope, createScopeManager, createSkillManager, createSystemOneJudge, createThinkSplitter, cutListing, denyCall, describeQuestionRefusal, describeRelayRefusal, describeSnapshotRefusal, digestLedgerTools, digestLedgerWindow, estimateMessages, estimateRequest, estimateTokens, extractLiterals, extractQueueOptions, extractSystemOneAnswer, extractSystemOneUsage, extractWords, filterAllowList, findLedgerCall, findLedgerCut, fitSlope, freezeJSON, handleAgentQueueJob, hasCalls, hasHiddenRecall, identifyLookup, inferStop, intersectKeys, isAgentError, isAgentJobError, isAuthorityDecision, isAuthorityVerdict, isContextError, isConversation, isConversationError, isConversationSnapshot, isFraction, isJudgeAbortError, isJudgeAnswer, isJudgeEntry, isJudgeError, isJudgeQuestion, isJudgment, isLedgerError, isLedgerQuestion, isLedgerSnapshot, isLedgerWindowSnapshot, isMemo, isMemoOrigin, isMemoSnapshot, isMessage, isMessageInput, isNonNegativeSafeInteger, isPositiveSafeInteger, isProviderAbortError, isProviderError, isProviderResult, isSection, isSystemOneAnswer, isSystemOneResponse, joinThinking, judgeAnswerContract, judgeAnswerShape, judgeEntryShape, judgeQuestionContract, judgeQuestionShape, judgmentContract, judgmentShape, ledgerSnapshotContract, ledgerSnapshotShape, ledgerWindowContract, ledgerWindowShape, linkOwners, matchEntities, matchesCutLine, matchesJSON, matchesJudgment, matchesLookup, measureAnswer, measureMessage, measureRequest, memoContract, memoShape, memoSnapshotContract, memoSnapshotShape, mergeSupersessions, messageContract, messageInputContract, messageInputShape, messageShape, normalizeArgument, normalizeWord, placeMember, providerRequestContract, providerRequestShape, providerResultContract, providerResultShape, questionToSystemOne, raceSignal, rankLedgerCut, readBodyText, readChunks, readFailure, readJudgeOutcome, readProviderDelta, relayFrameContract, relayFrameShape, releaseReader, removeEntries, renderArguments, renderCauseChain, renderFencedFile, renderIndexEntry, renderJSON, renderLedgerAnnotation, renderLedgerPinned, renderLedgerRecord, renderLookupCall, renderSection, renderStub, renderToolValue, renderTopicNames, requestToRelay, requireAnswer, requireBudget, requireConversation, requireConversationSnapshot, requireCumulative, requireEntry, requireFallback, requireJudgeResult, requireJudgment, requireKeep, requireLimit, requireMessageInput, requireProviderResult, requireRole, requireRules, requireSectionsCap, requireSummary, resolveDecision, resolvePredict, sanitizeToken, sanitizeUsage, scanAmendments, scanJudgmentTies, scanProbability, sectionContract, sectionShape, selectRecords, settleAgentJob, settleToolResult, splitResultLines, splitSentences, splitTopic, splitWords, stripThinking, sumUsage, tokenUsageShape, tokenUsageToJSON, toolCallShape };
14724
+ export { AGENT_OPTION_KEYS, AGENT_RUN_KEYS, ARGUMENT_BLANK_PATTERN, ARGUMENT_CONTROL_PATTERN, AUTHORITY_NOTES, AUTHORITY_OPTION_KEYS, Agent, AgentContext, AgentError, AgentFanout, AgentJobError, AgentJudge, AgentProvider, AgentRegistry, Approver, Authority, BUILD_OPTION_KEYS, BUILTIN_LIMITS, BUILTIN_NOTES, BUILTIN_TOOLS, CLASSIFIER_OPTION_KEYS, COMPACT_OPTION_KEYS, CONTEXT_OPTION_KEYS, CONVERSATION_INPUT_KEYS, CONVERSATION_MANAGER_KEYS, CONVERSATION_OPTION_KEYS, CONVERSATION_RECAP_PREFIX, CONVERSATION_ROLES, Channel, Classifier, ContextError, Conversation, ConversationError, ConversationManager, DECISIVE_CATEGORIES, DEFAULT_AGENT_LIMIT, DEFAULT_CONVERSATION_KEEP, DEFAULT_LEDGER_LIMIT, DEFAULT_LEDGER_SHARE, DEFAULT_PROVIDER_TIMEOUT, DEFAULT_RECALL_LIMIT, DEFAULT_RELAY_LIMIT, DETERMINISTIC_JUDGE_ERROR, DatabaseConversationStore, DatabaseMemoStore, GAUGE_OPTION_KEYS, Gauge, IMAGE_TOKEN_ESTIMATE, INSTRUCTION_MANAGER_KEYS, INVALID_RELAY_STATUS, Instruction, InstructionManager, JOB_REFUSAL_PREFIX, JUDGE_INPUT_KEYS, JudgeAbortError, JudgeError, JudgmentManager, LEDGER_AGENT_KEYS, LEDGER_CATEGORIES, LEDGER_NOTES, LEDGER_OPTION_KEYS, LEDGER_OWNER_PREFIX, LEDGER_QUESTIONS, LEDGER_RECALL_LABELS, LEDGER_RULES_KEY, LEDGER_SAMPLE_BYTES, LEDGER_SCALE_DRIFT, LEDGER_SLICE, LEDGER_WORD, LOADED_SECTION_HEADER, Ledger, LedgerError, LedgerRequest, MAX_ERROR_BODY_LENGTH, MEMO_MANAGER_KEYS, MEMO_SECTION_HEADER, MESSAGE_ROLES, MESSAGE_TOKEN_OVERHEAD, MemoManager, MemoryConversationStore, MemoryMemoStore, OVERSIZED_RELAY_STATUS, PLACED_CATEGORIES, PROVIDER_INPUT_KEYS, ProviderAbortError, ProviderError, QUEUE_OPTION_KEYS, QUIET_CATEGORIES, REFERENCE_OPTION_KEYS, REFUSED_RELAY_CONTENT_TYPE, REFUSED_RELAY_STATUS, REGISTRY_OPTION_KEYS, RELAY_CONTENT_TYPE, RELAY_OPTION_KEYS, RELAY_PROVIDER_KEYS, RELAY_PROVIDER_MESSAGE, RELAY_STREAM_KEYS, RUNNER_OPTION_KEYS, RelayProvider, RelayStream, SCOPE_FILTER_KEYS, SCOPE_KEYS, SCOPE_MANAGER_KEYS, SCOPE_NOTE, SKILL_MANAGER_KEYS, SKILL_SECTION_HEADER, STREAM_OPTION_KEYS, SYSTEM_ONE_OPTION_KEYS, SYSTEM_ONE_PATH, Scope, ScopeManager, SkillManager, SystemOneJudge, THINK_CLOSE, THINK_OPEN, ThinkSplitter, UNAUTHORIZED_RELAY_STATUS, UPSTREAM_RELAY_STATUS, WORKSPACE_INDEX_HEADER, WORKSPACE_SECTION_HEADER, agentAnswerContract, agentAnswerShape, agentChunkToFrame, agentFrameContract, agentFrameShape, agentJobContract, agentJobShape, agentPromptContract, agentPromptShape, agentResultToFrame, agentResultToJSON, agentStreamToFrames, armReaderAbort, assembleResult, attachImages, attachUserImages, buildJudgeResult, buildJudgments, buildLedgerCut, buildLedgerIndex, buildLedgerLineKey, buildLedgerRenderContext, buildLines, buildProviderHeaders, buildProviderResult, buildRecallMessage, buildRecapMessage, buildRecords, buildRelayRequest, buildRequestMessage, buildSummaryMessage, builtinToolContracts, chargeUsage, collectAmendments, collectBuiltinDefinitions, collectDisclosure, collectExchanges, collectImageData, collectJobRefusals, collectLedgerEvidence, collectLedgerLines, collectLedgerReplies, collectLive, collectNames, collectProjectionIds, collectRecallMessages, collectRegistry, collectRetiredFindings, collectToolGroups, collectWriteSupersessions, computeLedgerChecksum, computeSkillPrice, computeThinking, computeToolDensity, computeToolPrice, conversationSnapshotContract, conversationSnapshotShape, copyJSON, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createApprover, createAuthority, createBuiltinTool, createChannel, createConversation, createConversationManager, createDatabaseConversationStore, createDatabaseMemoStore, createInstruction, createInstructionManager, createLedger, createMemoManager, createMemoryConversationStore, createMemoryMemoStore, createRelay, createRelayProvider, createScope, createScopeManager, createSkillManager, createSystemOneJudge, createThinkSplitter, cutListing, cutWorkspaceSample, denyCall, describeCandidates, describeQuestionRefusal, describeRelayRefusal, describeSnapshotRefusal, digestLedgerTools, digestLedgerWindow, estimateMessages, estimateRequest, estimateTokens, extractLiterals, extractQueueOptions, extractSystemOneAnswer, extractSystemOneUsage, extractWords, filterAdvertisedTools, filterAllowList, filterBuiltinCandidates, findLedgerCut, findToolCall, fitSlope, freezeJSON, handleAgentQueueJob, hasCalls, hasHiddenRecall, identifyLookup, inferStop, instructionInputContract, instructionInputShape, intersectFilters, intersectKeys, isAgentBuiltin, isAgentError, isAgentJobError, isAuthorityDecision, isAuthorityVerdict, isContextError, isConversation, isConversationError, isConversationSnapshot, isFraction, isJudgeAbortError, isJudgeAnswer, isJudgeEntry, isJudgeError, isJudgeQuestion, isJudgment, isLedgerError, isLedgerQuestion, isLedgerSnapshot, isLedgerWindowSnapshot, isMemo, isMemoOrigin, isMemoSnapshot, isMessage, isMessageInput, isNonNegativeSafeInteger, isPositiveSafeInteger, isProviderAbortError, isProviderError, isProviderResult, isScope, isSection, isSystemOneAnswer, isSystemOneResponse, joinThinking, judgeAnswerContract, judgeAnswerShape, judgeEntryShape, judgeQuestionContract, judgeQuestionShape, judgmentContract, judgmentShape, ledgerSnapshotContract, ledgerSnapshotShape, ledgerWindowContract, ledgerWindowShape, linkOwners, loadToolContract, loadToolShape, matchEntities, matchesCutLine, matchesHeadLists, matchesJSON, matchesJudgment, matchesLookup, matchesPlainLine, measureAnswer, measureMessage, measureRequest, memoContract, memoInputContract, memoInputShape, memoShape, memoSnapshotContract, memoSnapshotShape, memoToolContract, memoToolShape, mergeSupersessions, messageContract, messageInputContract, messageInputShape, messageShape, normalizeArgument, normalizeWord, placeMember, providerRequestContract, providerRequestShape, providerResultContract, providerResultShape, questionToSystemOne, raceSignal, rankLedgerCut, readBodyText, readChunks, readFailure, readJudgeOutcome, readProviderDelta, relayFrameContract, relayFrameShape, releaseReader, rememberToolContract, rememberToolShape, removeEntries, renderArguments, renderCauseChain, renderFencedFile, renderIndexEntry, renderIndexLine, renderJSON, renderLedgerAnnotation, renderLedgerPinned, renderLedgerRecord, renderLookupCall, renderSection, renderSkillBody, renderStub, renderToolValue, renderTopicNames, requestToRelay, requireAnswer, requireBudget, requireBuiltins, requireConversation, requireConversationSnapshot, requireCumulative, requireEntry, requireFallback, requireJudgeResult, requireJudgment, requireKeep, requireLimit, requireMessageInput, requireProviderResult, requireRecordInput, requireRole, requireRules, requireScope, requireSectionsCap, requireSummary, requireWorkspace, resolveDecision, resolveDisclosure, resolvePredict, sanitizeToken, sanitizeUsage, scanAmendments, scanJobTree, scanJudgmentTies, scanProbability, sectionContract, sectionShape, selectRecords, settleAgentJob, settleToolResult, skillInputContract, skillInputShape, splitResultLines, splitSentences, splitTopic, splitWords, stripThinking, sumUsage, switchToolContract, switchToolShape, tokenUsageShape, tokenUsageToJSON, toolCallShape };
12600
14725
 
12601
14726
  //# sourceMappingURL=index.js.map