@orkestrel/agent 0.0.32 → 0.0.34

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,12 +1,12 @@
1
- import { ContractError, arrayOf, arrayShape, attempt, booleanShape, boundsOf, canonicalStringify, cloneJSONValue, createContract, isArray, isBoolean, isError, isFiniteNumber, isInstance, isJSONValue, isNumber, isObject, isRecord, isString, jsonShape, literalShape, nullableOf, numberShape, objectOf, objectShape, optionalOf, optionalShape, parseJSON, parseJSONAs, parseJSONValue, preview, rawShape, recordOf, recordShape, stringShape, unionShape } from "@orkestrel/contract";
1
+ import { ContractError, INTRINSICS, arrayOf, arrayShape, attempt, booleanShape, boundsOf, canonicalStringify, cloneJSONValue, createContract, errorToMessage, holds, isArray, isBoolean, isError, isFiniteNumber, isFunction, isJSONValue, isNumber, isObject, isRecord, isString, jsonShape, literalShape, nullableOf, numberShape, objectOf, objectShape, optionalOf, optionalShape, parseJSON, parseJSONAs, parseJSONValue, preview, rawShape, recordOf, recordShape, stringShape, unionShape } from "@orkestrel/contract";
2
2
  import { createTokenBudget, createTokenMeter, isBudget, isBudgetError, isTokenUsage } from "@orkestrel/budget";
3
3
  import { Timeout, createTimeout } from "@orkestrel/timeout";
4
4
  import { createDatabase, createMemoryDriver } from "@orkestrel/database";
5
5
  import { Emitter } from "@orkestrel/emitter";
6
6
  import { ToolManager, createTool, createToolManager, isToolCall } from "@orkestrel/tool";
7
- import { WorkspaceManager, isBinary, isText } from "@orkestrel/workspace";
7
+ import { WorkspaceManager, isBinary, isTextContent } from "@orkestrel/workspace";
8
8
  import { createQueue } from "@orkestrel/queue";
9
- import { createRunner, errorToMessage } from "@orkestrel/workflow";
9
+ import { createRunner } from "@orkestrel/workflow";
10
10
  import { createAbort } from "@orkestrel/abort";
11
11
  // src/core/constants.ts
12
12
  /**
@@ -39,11 +39,12 @@ var JudgeAbortError = class extends Error {
39
39
  constructor(partial, options) {
40
40
  super("judge call aborted", options);
41
41
  this.name = "JudgeAbortError";
42
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.JudgeAbortError"), { value: this });
42
43
  this.partial = partial;
43
44
  }
44
45
  };
45
46
  /**
46
- * Narrows a caught value to a {@link JudgeAbortError} through `instanceof`, so a `catch` can
47
+ * Narrows a caught value to a {@link JudgeAbortError} through its identity brand and declared members, so a `catch` can
47
48
  * recover its `partial` result.
48
49
  *
49
50
  * @param value - The caught value
@@ -54,7 +55,27 @@ var JudgeAbortError = class extends Error {
54
55
  * ```
55
56
  */
56
57
  function isJudgeAbortError(value) {
57
- return isInstance(value, JudgeAbortError);
58
+ return holds(() => {
59
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.JudgeAbortError"))?.value === value)) return false;
60
+ if (!(INTRINSICS.reflect.read(value, "code") === "ABORT")) return false;
61
+ const partial = INTRINSICS.reflect.read(value, "partial");
62
+ if (!(isObject(partial) || isFunction(partial))) return false;
63
+ const answers = INTRINSICS.reflect.read(partial, "answers");
64
+ const refusals = INTRINSICS.reflect.read(partial, "refusals");
65
+ const usage = INTRINSICS.reflect.read(partial, "usage");
66
+ return isString(INTRINSICS.reflect.read(partial, "model")) && (usage === void 0 || (isObject(usage) || isFunction(usage)) && [
67
+ "prompt",
68
+ "completion",
69
+ "total"
70
+ ].every((key) => isNumber(INTRINSICS.reflect.read(usage, key)))) && (isObject(answers) || isFunction(answers)) && INTRINSICS.values(answers).every((answer) => {
71
+ if (!(isObject(answer) || isFunction(answer))) return false;
72
+ const form = INTRINSICS.reflect.read(answer, "form");
73
+ if (form === "noul") return isNumber(INTRINSICS.reflect.read(answer, "noul"));
74
+ const probabilities = INTRINSICS.reflect.read(answer, "probabilities");
75
+ if (form === "score") return arrayOf(isNumber)(probabilities);
76
+ return form === "choice" && (isObject(probabilities) || isFunction(probabilities)) && INTRINSICS.values(probabilities).every(isNumber);
77
+ }) && (refusals === void 0 || (isObject(refusals) || isFunction(refusals)) && INTRINSICS.values(refusals).every((refusal) => (isObject(refusal) || isFunction(refusal)) && arrayOf(isString)(INTRINSICS.reflect.read(refusal, "missing"))));
78
+ });
58
79
  }
59
80
  // src/core/shapers.ts
60
81
  /**
@@ -614,11 +635,12 @@ var ProviderAbortError = class extends Error {
614
635
  constructor(partial, options) {
615
636
  super("provider stream aborted", options);
616
637
  this.name = "ProviderAbortError";
638
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ProviderAbortError"), { value: this });
617
639
  this.partial = partial;
618
640
  }
619
641
  };
620
642
  /**
621
- * Narrows an unknown caught value to a {@link ProviderAbortError} through `instanceof`, so a
643
+ * Narrows an unknown caught value to a {@link ProviderAbortError} through its identity brand and declared members, so a
622
644
  * `catch` can recover its `partial` result.
623
645
  *
624
646
  * @param value - The value to test (typically a `catch` binding)
@@ -634,7 +656,19 @@ var ProviderAbortError = class extends Error {
634
656
  * ```
635
657
  */
636
658
  function isProviderAbortError(value) {
637
- return isInstance(value, ProviderAbortError);
659
+ return holds(() => {
660
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ProviderAbortError"))?.value === value)) return false;
661
+ if (!(INTRINSICS.reflect.read(value, "code") === "ABORT")) return false;
662
+ const partial = INTRINSICS.reflect.read(value, "partial");
663
+ if (!(isObject(partial) || isFunction(partial))) return false;
664
+ const usage = INTRINSICS.reflect.read(partial, "usage");
665
+ const tools = INTRINSICS.reflect.read(partial, "tools");
666
+ return isString(INTRINSICS.reflect.read(partial, "content")) && (INTRINSICS.reflect.read(partial, "thinking") === void 0 || isString(INTRINSICS.reflect.read(partial, "thinking"))) && (INTRINSICS.reflect.read(partial, "truncated") === void 0 || isBoolean(INTRINSICS.reflect.read(partial, "truncated"))) && (usage === void 0 || (isObject(usage) || isFunction(usage)) && [
667
+ "prompt",
668
+ "completion",
669
+ "total"
670
+ ].every((key) => isNumber(INTRINSICS.reflect.read(usage, key)))) && (tools === void 0 || arrayOf((tool) => (isObject(tool) || isFunction(tool)) && isString(INTRINSICS.reflect.read(tool, "id")) && isString(INTRINSICS.reflect.read(tool, "name")) && (isObject(INTRINSICS.reflect.read(tool, "arguments")) || isFunction(INTRINSICS.reflect.read(tool, "arguments"))))(tools));
671
+ });
638
672
  }
639
673
  /**
640
674
  * Reports a coded provider failure with its HTTP status and underlying cause when available.
@@ -653,12 +687,13 @@ var ProviderError = class extends Error {
653
687
  constructor(code, message, options) {
654
688
  super(message, options);
655
689
  this.name = "ProviderError";
690
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ProviderError"), { value: this });
656
691
  this.code = code;
657
692
  this.status = options?.status;
658
693
  }
659
694
  };
660
695
  /**
661
- * Narrows a caught value to the provider failure class through `instanceof`.
696
+ * Narrows a caught value to the provider failure class through its identity brand and declared members.
662
697
  *
663
698
  * @param value - The caught value
664
699
  * @returns True if the value is a provider failure; false otherwise
@@ -668,7 +703,13 @@ var ProviderError = class extends Error {
668
703
  * ```
669
704
  */
670
705
  function isProviderError(value) {
671
- return isInstance(value, ProviderError);
706
+ return holds(() => {
707
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ProviderError"))?.value === value)) return false;
708
+ const code = INTRINSICS.reflect.read(value, "code");
709
+ if (!(code === "HTTP" || code === "PROTOCOL" || code === "PROVIDER")) return false;
710
+ const status = INTRINSICS.reflect.read(value, "status");
711
+ return status === void 0 || isNumber(status);
712
+ });
672
713
  }
673
714
  /**
674
715
  * Reports a coded judge failure with its HTTP status and underlying cause when available.
@@ -687,12 +728,13 @@ var JudgeError = class extends Error {
687
728
  constructor(code, message, options) {
688
729
  super(message, options);
689
730
  this.name = "JudgeError";
731
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.JudgeError"), { value: this });
690
732
  this.code = code;
691
733
  this.status = options?.status;
692
734
  }
693
735
  };
694
736
  /**
695
- * Narrows a caught value to the judge failure class through `instanceof`.
737
+ * Narrows a caught value to the judge failure class through its identity brand and declared members.
696
738
  *
697
739
  * @param value - The caught value
698
740
  * @returns True if the value is a {@link JudgeError}; false otherwise
@@ -702,7 +744,13 @@ var JudgeError = class extends Error {
702
744
  * ```
703
745
  */
704
746
  function isJudgeError(value) {
705
- return isInstance(value, JudgeError);
747
+ return holds(() => {
748
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.JudgeError"))?.value === value)) return false;
749
+ const code = INTRINSICS.reflect.read(value, "code");
750
+ if (!(code === "HTTP" || code === "PROTOCOL" || code === "QUESTION")) return false;
751
+ const status = INTRINSICS.reflect.read(value, "status");
752
+ return status === void 0 || isNumber(status);
753
+ });
706
754
  }
707
755
  // src/core/providers/shapers.ts
708
756
  /**
@@ -874,7 +922,7 @@ async function readFailure(response, prefix, signal) {
874
922
  status
875
923
  };
876
924
  }
877
- return readText(body, MAX_ERROR_BODY_LENGTH, signal).then((read) => {
925
+ return readBodyText(body, MAX_ERROR_BODY_LENGTH, signal).then((read) => {
878
926
  signal.throwIfAborted();
879
927
  return {
880
928
  message: `${prefix} ${status}${read.text === "" ? "" : ` - ${read.text}`}`,
@@ -901,13 +949,13 @@ async function readFailure(response, prefix, signal) {
901
949
  * @returns The decoded prefix and whether EOF occurred within the byte budget
902
950
  * @example
903
951
  * ```ts
904
- * import { readText } from '@orkestrel/agent'
952
+ * import { readBodyText } from '@orkestrel/agent'
905
953
  *
906
954
  * const body = new Response('answer').body
907
- * if (body !== null) await readText(body, 3) // { text: 'ans', complete: false }
955
+ * if (body !== null) await readBodyText(body, 3) // { text: 'ans', complete: false }
908
956
  * ```
909
957
  */
910
- async function readText(body, limit, signal) {
958
+ async function readBodyText(body, limit, signal) {
911
959
  const reader = body.getReader();
912
960
  const decoder = new TextDecoder();
913
961
  try {
@@ -1931,7 +1979,7 @@ var AgentJudge = class {
1931
1979
  throw new JudgeError("HTTP", message, options);
1932
1980
  }
1933
1981
  if (response.body === null) throw new JudgeError("PROTOCOL", "judge error: no response body");
1934
- const text = await readText(response.body, void 0, combined);
1982
+ const text = await readBodyText(response.body, void 0, combined);
1935
1983
  combined.throwIfAborted();
1936
1984
  const value = parseJSON(text.text);
1937
1985
  if (value === void 0) throw new JudgeError("PROTOCOL", "judge error: invalid JSON body");
@@ -2153,7 +2201,7 @@ function createRelay(options) {
2153
2201
  return new Response(void 0, { status: 401 });
2154
2202
  }
2155
2203
  if (request.body === null) return new Response(void 0, { status: 400 });
2156
- const read = await readText(request.body, limit ?? 1048576, request.signal).catch(() => void 0);
2204
+ const read = await readBodyText(request.body, limit ?? 1048576, request.signal).catch(() => void 0);
2157
2205
  if (read === void 0) return new Response(void 0, { status: request.signal.aborted ? 413 : 400 });
2158
2206
  if (!read.complete) return new Response(void 0, { status: 413 });
2159
2207
  const parsed = parseJSONAs(read.text, providerRequestContract.is);
@@ -2328,12 +2376,13 @@ var ConversationError = class extends Error {
2328
2376
  constructor(code, message, options) {
2329
2377
  super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
2330
2378
  this.name = "ConversationError";
2379
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.ConversationError"), { value: this });
2331
2380
  this.code = code;
2332
2381
  this.context = options?.context;
2333
2382
  }
2334
2383
  };
2335
2384
  /**
2336
- * Narrows an unknown caught value to a {@link ConversationError} through `instanceof`, so a
2385
+ * Narrows an unknown caught value to a {@link ConversationError} through its identity brand and declared members, so a
2337
2386
  * `catch` can branch on its `code`.
2338
2387
  *
2339
2388
  * @param value - The value to test (typically a `catch` binding)
@@ -2349,7 +2398,13 @@ var ConversationError = class extends Error {
2349
2398
  * ```
2350
2399
  */
2351
2400
  function isConversationError(value) {
2352
- return isInstance(value, ConversationError);
2401
+ return holds(() => {
2402
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.ConversationError"))?.value === value)) return false;
2403
+ const code = INTRINSICS.reflect.read(value, "code");
2404
+ if (!(code === "SUMMARIZER" || code === "SECTIONS" || code === "JUDGMENT" || code === "KEEP")) return false;
2405
+ const context = INTRINSICS.reflect.read(value, "context");
2406
+ return context === void 0 || isObject(context) || isFunction(context);
2407
+ });
2353
2408
  }
2354
2409
  // src/core/conversations/validators.ts
2355
2410
  /**
@@ -4053,7 +4108,7 @@ var AgentContext = class {
4053
4108
  const instructed = renderSection(this.#instructions.open, instructions, (one) => this.#instructions.render(one), this.#instructions.close);
4054
4109
  if (instructed !== void 0) parts.push(instructed);
4055
4110
  const files = filterAllowList(scope?.files, this.#workspaces.active?.files() ?? [], (one) => one.path);
4056
- const documented = renderSection(WORKSPACE_SECTION_HEADER, files.flatMap((file) => isText(file.content) ? [{
4111
+ const documented = renderSection(WORKSPACE_SECTION_HEADER, files.flatMap((file) => isTextContent(file.content) ? [{
4057
4112
  path: file.path,
4058
4113
  language: file.content.language,
4059
4114
  text: file.content.text
@@ -4284,11 +4339,12 @@ var AgentJobError = class extends Error {
4284
4339
  constructor(message, partial) {
4285
4340
  super(message);
4286
4341
  this.name = "AgentJobError";
4342
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.AgentJobError"), { value: this });
4287
4343
  this.partial = partial;
4288
4344
  }
4289
4345
  };
4290
4346
  /**
4291
- * Narrows an unknown caught value to an {@link AgentJobError} through `instanceof`, so a
4347
+ * Narrows an unknown caught value to an {@link AgentJobError} through its identity brand and declared members, so a
4292
4348
  * `catch` can recover its `partial` result.
4293
4349
  *
4294
4350
  * @param value - The value to test (typically a `catch` binding or a rejected enqueue)
@@ -4304,7 +4360,30 @@ var AgentJobError = class extends Error {
4304
4360
  * ```
4305
4361
  */
4306
4362
  function isAgentJobError(value) {
4307
- return isInstance(value, AgentJobError);
4363
+ return holds(() => {
4364
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.AgentJobError"))?.value === value)) return false;
4365
+ if (!(INTRINSICS.reflect.read(value, "code") === "PARTIAL")) return false;
4366
+ const partial = INTRINSICS.reflect.read(value, "partial");
4367
+ if (!(isObject(partial) || isFunction(partial))) return false;
4368
+ const usage = INTRINSICS.reflect.read(partial, "usage");
4369
+ const stop = INTRINSICS.reflect.read(partial, "stop");
4370
+ if (stop !== void 0) {
4371
+ if (!(isObject(stop) || isFunction(stop))) return false;
4372
+ const layer = INTRINSICS.reflect.read(stop, "layer");
4373
+ const spent = INTRINSICS.reflect.read(stop, "usage");
4374
+ if (!isString(INTRINSICS.reflect.read(stop, "id")) || !(INTRINSICS.reflect.read(stop, "estimate") === void 0 || isNumber(INTRINSICS.reflect.read(stop, "estimate"))) || !(spent === void 0 || (isObject(spent) || isFunction(spent)) && [
4375
+ "prompt",
4376
+ "completion",
4377
+ "total"
4378
+ ].every((key) => isNumber(INTRINSICS.reflect.read(spent, key))))) return false;
4379
+ if (layer !== "model" && !((layer === "meter" || layer === "budget") && isNumber(INTRINSICS.reflect.read(stop, "max")) && isNumber(INTRINSICS.reflect.read(stop, "consumed")))) return false;
4380
+ }
4381
+ return isString(INTRINSICS.reflect.read(partial, "content")) && (INTRINSICS.reflect.read(partial, "thinking") === void 0 || isString(INTRINSICS.reflect.read(partial, "thinking"))) && isBoolean(INTRINSICS.reflect.read(partial, "partial")) && (usage === void 0 || (isObject(usage) || isFunction(usage)) && [
4382
+ "prompt",
4383
+ "completion",
4384
+ "total"
4385
+ ].every((key) => isNumber(INTRINSICS.reflect.read(usage, key))));
4386
+ });
4308
4387
  }
4309
4388
  /**
4310
4389
  * Reports a run sharing accounting with a live run, a `limit` that is not a nonnegative safe integer, a name absent from a registry pool, or a strict run whose request exceeds its window. Agent construction, the `stream` and `generate` methods, and registry accessors throw synchronously, before returning a handle or promise; a `'WINDOW'` refusal rejects the run's `result` instead. Await the call inside `try`/`catch` to catch it.
@@ -4340,12 +4419,13 @@ var AgentError = class extends Error {
4340
4419
  constructor(code, message, options) {
4341
4420
  super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
4342
4421
  this.name = "AgentError";
4422
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.AgentError"), { value: this });
4343
4423
  this.code = code;
4344
4424
  this.context = options?.context;
4345
4425
  }
4346
4426
  };
4347
4427
  /**
4348
- * Narrows an unknown caught value to an {@link AgentError} through `instanceof`, so a `catch`
4428
+ * Narrows an unknown caught value to an {@link AgentError} through its identity brand and declared members, so a `catch`
4349
4429
  * can branch on its `code`.
4350
4430
  *
4351
4431
  * @param value - The value to test (typically a `catch` binding)
@@ -4361,7 +4441,13 @@ var AgentError = class extends Error {
4361
4441
  * ```
4362
4442
  */
4363
4443
  function isAgentError(value) {
4364
- return isInstance(value, AgentError);
4444
+ return holds(() => {
4445
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.AgentError"))?.value === value)) return false;
4446
+ const code = INTRINSICS.reflect.read(value, "code");
4447
+ if (!(code === "CONCURRENCY" || code === "LIMIT" || code === "REGISTRY" || code === "WINDOW")) return false;
4448
+ const context = INTRINSICS.reflect.read(value, "context");
4449
+ return context === void 0 || isObject(context) || isFunction(context);
4450
+ });
4365
4451
  }
4366
4452
  // src/core/agents/Channel.ts
4367
4453
  /**
@@ -4660,7 +4746,7 @@ function estimateTokens(text) {
4660
4746
  function estimateMessages(messages) {
4661
4747
  return messages.reduce((sum, message) => {
4662
4748
  const measure = measureMessage(message);
4663
- return sum + measure.content + measure.framing + measure.calls + measure.thinking + measure.images;
4749
+ return sum + measure.content + measure.uniform + measure.calls + measure.thinking + measure.images;
4664
4750
  }, 0);
4665
4751
  }
4666
4752
  /**
@@ -4670,7 +4756,7 @@ function estimateMessages(messages) {
4670
4756
  * @remarks
4671
4757
  * The result is a structural estimate, not a tokenizer allocation. `id` and `role` are joins back to
4672
4758
  * the message, not token components, and a provider's template effects and the estimation error are
4673
- * not individually attributed. `content` is `ceil(length / 4)`, `framing` is
4759
+ * not individually attributed. `content` is `ceil(length / 4)`, `uniform` is
4674
4760
  * {@link import('./constants.js').MESSAGE_TOKEN_OVERHEAD}, `calls` is the estimate of the JSON-rendered
4675
4761
  * calls (`0` when the message carries none, the framing overhead when they cannot be rendered),
4676
4762
  * `thinking` is the estimate of the thinking (`0` when absent), and `images` is the attached image
@@ -4682,7 +4768,7 @@ function estimateMessages(messages) {
4682
4768
  * @example
4683
4769
  * ```ts
4684
4770
  * measureMessage({ id: '1', role: 'user', content: 'hello' })
4685
- * // { id: '1', role: 'user', content: 2, framing: 4, calls: 0, thinking: 0, images: 0 }
4771
+ * // { id: '1', role: 'user', content: 2, uniform: 4, calls: 0, thinking: 0, images: 0 }
4686
4772
  * ```
4687
4773
  */
4688
4774
  function measureMessage(message) {
@@ -4692,7 +4778,7 @@ function measureMessage(message) {
4692
4778
  id: message.id,
4693
4779
  role: message.role,
4694
4780
  content: estimateTokens(message.content),
4695
- framing: 4,
4781
+ uniform: 4,
4696
4782
  calls,
4697
4783
  thinking: message.thinking === void 0 ? 0 : estimateTokens(message.thinking),
4698
4784
  images: (message.images?.length ?? 0) * 512
@@ -4724,7 +4810,7 @@ function measureMessage(message) {
4724
4810
  */
4725
4811
  function estimateRequest(request) {
4726
4812
  const measure = measureRequest(request);
4727
- return measure.messages.reduce((sum, message) => sum + message.content + message.framing + message.calls + message.thinking + message.images, measure.tools + measure.schema);
4813
+ return measure.messages.reduce((sum, message) => sum + message.content + message.uniform + message.calls + message.thinking + message.images, measure.tools + measure.schema);
4728
4814
  }
4729
4815
  /**
4730
4816
  * Measures the disjoint estimate components of a complete provider request — each message through
@@ -4745,7 +4831,7 @@ function estimateRequest(request) {
4745
4831
  * @example
4746
4832
  * ```ts
4747
4833
  * measureRequest({ messages: [{ id: '1', role: 'user', content: 'hello' }] })
4748
- * // { messages: [{ id: '1', role: 'user', content: 2, framing: 4, calls: 0, thinking: 0, images: 0 }], tools: 0, schema: 0 }
4834
+ * // { messages: [{ id: '1', role: 'user', content: 2, uniform: 4, calls: 0, thinking: 0, images: 0 }], tools: 0, schema: 0 }
4749
4835
  * ```
4750
4836
  */
4751
4837
  function measureRequest(request) {
@@ -5196,7 +5282,7 @@ var Agent = class {
5196
5282
  this.#window?.clear();
5197
5283
  const cancelled = abort.signal.aborted;
5198
5284
  const turns = [];
5199
- while (turns.length < limit && (turns.at(-1)?.ending ?? "tools") === "tools") {
5285
+ while (turns.length < limit && (turns.at(-1)?.outcome ?? "tools") === "tools") {
5200
5286
  const index = turns.length;
5201
5287
  const base = turns.at(-1)?.messages ?? entry.messages;
5202
5288
  const futile = turns.at(-1)?.futile ?? false;
@@ -5206,7 +5292,7 @@ var Agent = class {
5206
5292
  usage: void 0,
5207
5293
  spent: void 0,
5208
5294
  messages: base,
5209
- ending: "cancel",
5295
+ outcome: "cancel",
5210
5296
  partial: true,
5211
5297
  futile,
5212
5298
  estimate: void 0,
@@ -5252,7 +5338,7 @@ var Agent = class {
5252
5338
  if (!provided.success) {
5253
5339
  turns.push({
5254
5340
  ...settled,
5255
- ending: "cancel",
5341
+ outcome: "cancel",
5256
5342
  partial: true
5257
5343
  });
5258
5344
  continue;
@@ -5274,7 +5360,7 @@ var Agent = class {
5274
5360
  if (abort.signal.aborted) {
5275
5361
  turns.push({
5276
5362
  ...settled,
5277
- ending: "cancel",
5363
+ outcome: "cancel",
5278
5364
  partial: true
5279
5365
  });
5280
5366
  continue;
@@ -5309,7 +5395,7 @@ var Agent = class {
5309
5395
  assistant,
5310
5396
  ...replies
5311
5397
  ],
5312
- ending: "tools",
5398
+ outcome: "tools",
5313
5399
  partial: true
5314
5400
  });
5315
5401
  continue;
@@ -5322,7 +5408,7 @@ var Agent = class {
5322
5408
  turns.push({
5323
5409
  ...settled,
5324
5410
  content: result.content,
5325
- ending: "answer",
5411
+ outcome: "answer",
5326
5412
  partial: abort.signal.aborted,
5327
5413
  truncated: result.truncated === true
5328
5414
  });
@@ -5330,7 +5416,7 @@ var Agent = class {
5330
5416
  const final = turns.at(-1);
5331
5417
  const thinkings = turns.flatMap((turn) => turn.thinking === void 0 ? [] : [turn.thinking]);
5332
5418
  return {
5333
- content: final?.ending === "answer" ? final.content : turns.map((turn) => turn.content).join(""),
5419
+ content: final?.outcome === "answer" ? final.content : turns.map((turn) => turn.content).join(""),
5334
5420
  thinking: thinkings.length === 0 ? void 0 : thinkings.join("\n\n"),
5335
5421
  usage: [
5336
5422
  ...turns.map((turn) => turn.usage),
@@ -5338,7 +5424,7 @@ var Agent = class {
5338
5424
  ...turns.map((turn) => turn.spent)
5339
5425
  ].reduce((total, one) => one === void 0 ? total : sumUsage(total, one), void 0),
5340
5426
  partial: final?.partial ?? cancelled,
5341
- exhausted: final?.ending === "tools" && !abort.signal.aborted,
5427
+ exhausted: final?.outcome === "tools" && !abort.signal.aborted,
5342
5428
  stop: inferStop(abort.signal.reason, allowance, budget, this.#provider.id, final)
5343
5429
  };
5344
5430
  }
@@ -6139,11 +6225,12 @@ var LedgerError = class extends Error {
6139
6225
  constructor(code, message) {
6140
6226
  super(message);
6141
6227
  this.name = "LedgerError";
6228
+ INTRINSICS.define(this, Symbol.for("@orkestrel/agent.LedgerError"), { value: this });
6142
6229
  this.code = code;
6143
6230
  }
6144
6231
  };
6145
6232
  /**
6146
- * Narrows an unknown caught value to a {@link LedgerError} through `instanceof`, so a `catch` can
6233
+ * Narrows an unknown caught value to a {@link LedgerError} through its identity brand and declared members, so a `catch` can
6147
6234
  * branch on its `code`.
6148
6235
  *
6149
6236
  * @param value - The value to test (typically a `catch` binding)
@@ -6155,7 +6242,12 @@ var LedgerError = class extends Error {
6155
6242
  * ```
6156
6243
  */
6157
6244
  function isLedgerError(value) {
6158
- return isInstance(value, LedgerError);
6245
+ return holds(() => {
6246
+ if (!(value instanceof Error && INTRINSICS.prototype(value) !== Error.prototype && INTRINSICS.describe(value, Symbol.for("@orkestrel/agent.LedgerError"))?.value === value)) return false;
6247
+ const code = INTRINSICS.reflect.read(value, "code");
6248
+ if (!(code === "REQUEST" || code === "THRESHOLD" || code === "SHARE" || code === "CAPACITY" || code === "LIMIT" || code === "TOPIC" || code === "LOOKUP" || code === "GAUGE" || code === "REFERENCE")) return false;
6249
+ return true;
6250
+ });
6159
6251
  }
6160
6252
  // src/core/ledgers/helpers.ts
6161
6253
  /**
@@ -8475,6 +8567,6 @@ var Ledger = class {
8475
8567
  function createLedger(provider, options) {
8476
8568
  return new Ledger(provider, options);
8477
8569
  }
8478
- export { Agent, AgentContext, AgentError, AgentFanout, AgentJobError, AgentJudge, AgentProvider, AgentRegistry, Authority, CONVERSATION_RECAP_PREFIX, Channel, Classifier, Conversation, ConversationError, ConversationManager, DECISIVE_CATEGORIES, DEFAULT_AGENT_LIMIT, DEFAULT_AUTHORITY_ZONE, DEFAULT_CONVERSATION_KEEP, DEFAULT_LEDGER_LIMIT, DEFAULT_LEDGER_SHARE, DEFAULT_PROVIDER_TIMEOUT, DEFAULT_RECALL_LIMIT, DEFAULT_RELAY_LIMIT, DETERMINISTIC_JUDGE_ERROR, DatabaseConversationStore, Gauge, IMAGE_TOKEN_ESTIMATE, INVALID_RELAY_STATUS, Instruction, InstructionManager, JudgeAbortError, JudgeError, JudgmentManager, LEDGER_CATEGORIES, LEDGER_NOTES, LEDGER_OWNER_PREFIX, LEDGER_QUESTIONS, LEDGER_RULES_KEY, LEDGER_SCALE_DRIFT, Ledger, LedgerError, LedgerRequest, MAX_ERROR_BODY_LENGTH, MESSAGE_ROLES, MESSAGE_TOKEN_OVERHEAD, MemoryConversationStore, OVERSIZED_RELAY_STATUS, PLACED_CATEGORIES, ProviderAbortError, ProviderError, QUIET_CATEGORIES, RELAY_CONTENT_TYPE, RELAY_PROVIDER_MESSAGE, RelayProvider, RelayStream, SYSTEM_ONE_PATH, Scope, ScopeManager, SystemOneJudge, THINK_CLOSE, THINK_OPEN, ThinkSplitter, UNAUTHORIZED_RELAY_STATUS, UPSTREAM_RELAY_STATUS, WORKSPACE_SECTION_HEADER, agentResultToJSON, armReaderAbort, assembleResult, attachImages, attachUserImages, buildJudgeResult, buildJudgments, buildLedgerRenderContext, buildLines, buildProviderHeaders, buildProviderResult, buildRecallMessage, buildRecapMessage, buildRecords, buildSummaryMessage, chargeUsage, collectAmendments, collectExchanges, collectImageData, collectLive, collectNames, collectProjectionIds, collectRegistry, collectToolGroups, computeReading, computeThinking, copyJSON, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createAuthority, createChannel, createConversation, createConversationManager, createDatabaseConversationStore, createInstruction, createInstructionManager, createLedger, createMemoryConversationStore, createRelay, createRelayProvider, createScope, createScopeManager, createSystemOneJudge, createThinkSplitter, cutListing, denyCall, estimateMessages, estimateRequest, estimateTokens, extractQueueOptions, extractSystemOneAnswer, extractSystemOneUsage, extractTokens, extractWords, filterAllowList, findLedgerCall, fitSlope, handleAgentQueueJob, hasCalls, identifyLookup, inferStop, intersectKeys, isAgentError, isAgentJobError, isConversationError, isConversationSnapshot, isFraction, isJudgeAbortError, isJudgeEntry, isJudgeError, isJudgeQuestion, isJudgment, isLedgerError, isMessage, isNonNegativeSafeInteger, isPositiveSafeInteger, isProviderAbortError, isProviderError, isSection, isSystemOneAnswer, isSystemOneResponse, joinThinking, linkOwners, matchEntities, matchesCutLine, matchesJudgment, measureMessage, measureRequest, messageContract, messageShape, normalizeArgument, placeMember, providerRequestContract, providerRequestShape, providerResultContract, providerResultShape, questionToSystemOne, raceSignal, rankLedgerCut, readChunks, readFailure, readText, relayFrameContract, relayFrameShape, releaseReader, removeEntries, renderCauseChain, renderFencedFile, renderJSON, renderLedgerAnnotation, renderLedgerPinned, renderLedgerRecord, renderLookupCall, renderSection, renderStub, renderToolValue, renderTopicNames, requestToRelay, requireBudget, requireEntry, requireJudgment, requireKeep, requireLimit, requireRolling, requireSectionsCap, resolvePredict, sanitizeToken, sanitizeUsage, scanAmendments, selectRecords, settleAgentJob, splitResultLines, splitSentences, splitTopic, splitWords, stripThinking, sumUsage, tokenUsageToJSON, toolCallShape };
8570
+ export { Agent, AgentContext, AgentError, AgentFanout, AgentJobError, AgentJudge, AgentProvider, AgentRegistry, Authority, CONVERSATION_RECAP_PREFIX, Channel, Classifier, Conversation, ConversationError, ConversationManager, DECISIVE_CATEGORIES, DEFAULT_AGENT_LIMIT, DEFAULT_AUTHORITY_ZONE, DEFAULT_CONVERSATION_KEEP, DEFAULT_LEDGER_LIMIT, DEFAULT_LEDGER_SHARE, DEFAULT_PROVIDER_TIMEOUT, DEFAULT_RECALL_LIMIT, DEFAULT_RELAY_LIMIT, DETERMINISTIC_JUDGE_ERROR, DatabaseConversationStore, Gauge, IMAGE_TOKEN_ESTIMATE, INVALID_RELAY_STATUS, Instruction, InstructionManager, JudgeAbortError, JudgeError, JudgmentManager, LEDGER_CATEGORIES, LEDGER_NOTES, LEDGER_OWNER_PREFIX, LEDGER_QUESTIONS, LEDGER_RULES_KEY, LEDGER_SCALE_DRIFT, Ledger, LedgerError, LedgerRequest, MAX_ERROR_BODY_LENGTH, MESSAGE_ROLES, MESSAGE_TOKEN_OVERHEAD, MemoryConversationStore, OVERSIZED_RELAY_STATUS, PLACED_CATEGORIES, ProviderAbortError, ProviderError, QUIET_CATEGORIES, RELAY_CONTENT_TYPE, RELAY_PROVIDER_MESSAGE, RelayProvider, RelayStream, SYSTEM_ONE_PATH, Scope, ScopeManager, SystemOneJudge, THINK_CLOSE, THINK_OPEN, ThinkSplitter, UNAUTHORIZED_RELAY_STATUS, UPSTREAM_RELAY_STATUS, WORKSPACE_SECTION_HEADER, agentResultToJSON, armReaderAbort, assembleResult, attachImages, attachUserImages, buildJudgeResult, buildJudgments, buildLedgerRenderContext, buildLines, buildProviderHeaders, buildProviderResult, buildRecallMessage, buildRecapMessage, buildRecords, buildSummaryMessage, chargeUsage, collectAmendments, collectExchanges, collectImageData, collectLive, collectNames, collectProjectionIds, collectRegistry, collectToolGroups, computeReading, computeThinking, copyJSON, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createAuthority, createChannel, createConversation, createConversationManager, createDatabaseConversationStore, createInstruction, createInstructionManager, createLedger, createMemoryConversationStore, createRelay, createRelayProvider, createScope, createScopeManager, createSystemOneJudge, createThinkSplitter, cutListing, denyCall, estimateMessages, estimateRequest, estimateTokens, extractQueueOptions, extractSystemOneAnswer, extractSystemOneUsage, extractTokens, extractWords, filterAllowList, findLedgerCall, fitSlope, handleAgentQueueJob, hasCalls, identifyLookup, inferStop, intersectKeys, isAgentError, isAgentJobError, isConversationError, isConversationSnapshot, isFraction, isJudgeAbortError, isJudgeEntry, isJudgeError, isJudgeQuestion, isJudgment, isLedgerError, isMessage, isNonNegativeSafeInteger, isPositiveSafeInteger, isProviderAbortError, isProviderError, isSection, isSystemOneAnswer, isSystemOneResponse, joinThinking, linkOwners, matchEntities, matchesCutLine, matchesJudgment, measureMessage, measureRequest, messageContract, messageShape, normalizeArgument, placeMember, providerRequestContract, providerRequestShape, providerResultContract, providerResultShape, questionToSystemOne, raceSignal, rankLedgerCut, readBodyText, readChunks, readFailure, relayFrameContract, relayFrameShape, releaseReader, removeEntries, renderCauseChain, renderFencedFile, renderJSON, renderLedgerAnnotation, renderLedgerPinned, renderLedgerRecord, renderLookupCall, renderSection, renderStub, renderToolValue, renderTopicNames, requestToRelay, requireBudget, requireEntry, requireJudgment, requireKeep, requireLimit, requireRolling, requireSectionsCap, resolvePredict, sanitizeToken, sanitizeUsage, scanAmendments, selectRecords, settleAgentJob, splitResultLines, splitSentences, splitTopic, splitWords, stripThinking, sumUsage, tokenUsageToJSON, toolCallShape };
8479
8571
 
8480
8572
  //# sourceMappingURL=index.js.map