@sema-agent/core 7.73.0 → 7.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/dist/agents/list-agents-tool.js +1 -1
  3. package/dist/agents/retain-ledger.js +3 -3
  4. package/dist/agents/send-message-tool.js +4 -4
  5. package/dist/brain/anthropic.d.ts +42 -1
  6. package/dist/brain/anthropic.js +54 -4
  7. package/dist/brain/failover.d.ts +5 -0
  8. package/dist/brain/failover.js +51 -22
  9. package/dist/brain/model-lane.d.ts +12 -3
  10. package/dist/brain/model-lane.js +5 -5
  11. package/dist/brain/open-responses.js +3 -3
  12. package/dist/brain/openai.js +1 -1
  13. package/dist/brain/route-adjudicator.d.ts +33 -4
  14. package/dist/brain/route-adjudicator.js +49 -12
  15. package/dist/brain/stream-engine.js +9 -7
  16. package/dist/brain/stream-shared.d.ts +4 -3
  17. package/dist/brain/stream-shared.js +2 -2
  18. package/dist/core/allow-entry.js +1 -1
  19. package/dist/core/ask-class.d.ts +2 -2
  20. package/dist/core/ask-headline.d.ts +1 -1
  21. package/dist/core/ask-origin.d.ts +44 -4
  22. package/dist/core/ask-origin.js +29 -10
  23. package/dist/core/background-agent-store.d.ts +1 -0
  24. package/dist/core/background-agent-store.js +49 -8
  25. package/dist/core/checkpoint-row-verdict.d.ts +1 -1
  26. package/dist/core/checkpoint-row-verdict.js +2 -2
  27. package/dist/core/checkpoint-store.d.ts +2 -0
  28. package/dist/core/checkpoint-store.js +8 -2
  29. package/dist/core/config-refusal-codes.d.ts +1 -1
  30. package/dist/core/config-refusal-codes.js +1 -0
  31. package/dist/core/cron.js +9 -1
  32. package/dist/core/deployment-shape.d.ts +7 -0
  33. package/dist/core/deployment-shape.js +19 -0
  34. package/dist/core/engine-capabilities.d.ts +9 -1
  35. package/dist/core/engine-capabilities.js +1 -1
  36. package/dist/core/engine-notice.d.ts +14 -9
  37. package/dist/core/engine-version.js +1 -1
  38. package/dist/core/gate-fold.js +5 -4
  39. package/dist/core/gate-lanes.js +8 -12
  40. package/dist/core/gate-outcome.d.ts +8 -2
  41. package/dist/core/gate-outcome.js +10 -3
  42. package/dist/core/governance-codes.d.ts +8 -2
  43. package/dist/core/governance-codes.js +9 -1
  44. package/dist/core/hook-condition.d.ts +37 -0
  45. package/dist/core/hook-condition.js +567 -0
  46. package/dist/core/hooks.d.ts +2 -0
  47. package/dist/core/mode-policy.d.ts +4 -0
  48. package/dist/core/mode-policy.js +18 -2
  49. package/dist/core/model-seat.d.ts +8 -5
  50. package/dist/core/model-shell.d.ts +129 -0
  51. package/dist/core/model-shell.js +249 -0
  52. package/dist/core/mods/kernel/digest.d.ts +4 -0
  53. package/dist/core/mods/kernel/digest.js +5 -0
  54. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  55. package/dist/core/mods/kernel/dispatch.js +15 -6
  56. package/dist/core/mods/kernel/events.d.ts +21 -5
  57. package/dist/core/mods/kernel/events.js +19 -10
  58. package/dist/core/mods/kernel/hash-mirror.d.ts +1 -0
  59. package/dist/core/mods/kernel/hash-mirror.js +55 -0
  60. package/dist/core/mods/kernel/index.d.ts +1 -0
  61. package/dist/core/mods/kernel/index.js +1 -0
  62. package/dist/core/mods/kernel/package-reader.d.ts +48 -0
  63. package/dist/core/mods/kernel/package-reader.js +149 -0
  64. package/dist/core/mods/kernel/site-rules.d.ts +4 -0
  65. package/dist/core/mods/kernel/site-rules.js +13 -0
  66. package/dist/core/mods/package.d.ts +7 -3
  67. package/dist/core/mods/package.js +47 -80
  68. package/dist/core/permission-rule-org.js +13 -3
  69. package/dist/core/permission-rules.js +4 -1
  70. package/dist/core/retain-seat.d.ts +42 -0
  71. package/dist/core/retain-seat.js +76 -0
  72. package/dist/core/rewind-refusal-codes.d.ts +8 -0
  73. package/dist/core/rewind-refusal-codes.js +12 -0
  74. package/dist/core/roles.d.ts +2 -2
  75. package/dist/core/roles.js +15 -1
  76. package/dist/core/rule-store-fault.d.ts +9 -7
  77. package/dist/core/rule-store-fault.js +8 -3
  78. package/dist/core/runner/checkpoint-scope.d.ts +1 -0
  79. package/dist/core/runner/checkpoint-scope.js +4 -2
  80. package/dist/core/runner/compact-session.js +1 -1
  81. package/dist/core/runner/construction-doors.js +2 -0
  82. package/dist/core/runner/cross-boundary-lane.d.ts +8 -1
  83. package/dist/core/runner/cross-boundary-lane.js +4 -0
  84. package/dist/core/runner/gate-exit.d.ts +7 -0
  85. package/dist/core/runner/gate-exit.js +2 -1
  86. package/dist/core/runner/model-lane-seat.d.ts +3 -0
  87. package/dist/core/runner/model-lane-seat.js +4 -0
  88. package/dist/core/runner/person-path-rows.d.ts +6 -0
  89. package/dist/core/runner/person-path-rows.js +13 -0
  90. package/dist/core/runner/prepare-config-doors.js +9 -5
  91. package/dist/core/runner/prepare-gate-stations.d.ts +6 -0
  92. package/dist/core/runner/prepare-gate-stations.js +3 -1
  93. package/dist/core/runner/prepare-hands-readface.js +3 -2
  94. package/dist/core/runner/prepare-offload-wrappers.js +1 -1
  95. package/dist/core/runner/prepare-task.js +6 -3
  96. package/dist/core/runner/prepare-wiring-manifest.js +3 -4
  97. package/dist/core/runner/resume-policy-outcome.js +5 -2
  98. package/dist/core/runner/role-seat-defaulted.d.ts +3 -3
  99. package/dist/core/runner/role-seat-defaulted.js +1 -1
  100. package/dist/core/runner/rule-store-unreadable-notice.d.ts +1 -1
  101. package/dist/core/runner/rule-store-unreadable-notice.js +3 -3
  102. package/dist/core/runner/run-harness-handlers.js +1 -1
  103. package/dist/core/runner/run-leg.js +2 -2
  104. package/dist/core/runner/shell-env-withheld.d.ts +3 -2
  105. package/dist/core/runner/shell-env-withheld.js +24 -1
  106. package/dist/core/runner/sub-agent-deny-lists.js +9 -5
  107. package/dist/core/runner/tool-end-body.d.ts +1 -1
  108. package/dist/core/runner/tool-not-executed.d.ts +27 -8
  109. package/dist/core/runner/tool-not-executed.js +22 -11
  110. package/dist/core/runner/write-protection-station.d.ts +1 -1
  111. package/dist/core/runner/write-protection-station.js +1 -1
  112. package/dist/core/runner-deps.d.ts +4 -0
  113. package/dist/core/secret-env.d.ts +8 -0
  114. package/dist/core/secret-env.js +5 -2
  115. package/dist/core/shell-read-silence.d.ts +40 -2
  116. package/dist/core/shell-read-silence.js +23 -4
  117. package/dist/core/task-event.d.ts +4 -4
  118. package/dist/core/task-notification.js +6 -1
  119. package/dist/core/task-registry-agent.d.ts +1 -0
  120. package/dist/core/task-registry-agent.js +1 -1
  121. package/dist/core/task-registry.d.ts +1 -0
  122. package/dist/core/task-registry.js +4 -3
  123. package/dist/core/task-result.d.ts +5 -3
  124. package/dist/core/task-spec-members.js +8 -0
  125. package/dist/core/tool-gate-phase.d.ts +6 -3
  126. package/dist/core/tool-gate-phase.js +1 -0
  127. package/dist/core/tool-mount-facts.d.ts +7 -3
  128. package/dist/core/tool-mount-facts.js +6 -2
  129. package/dist/core/tool-mount-plan.d.ts +1 -1
  130. package/dist/core/tool-mount-plan.js +4 -3
  131. package/dist/core/tool-result-store.d.ts +37 -1
  132. package/dist/core/tool-result-store.js +168 -23
  133. package/dist/core/trace.d.ts +3 -3
  134. package/dist/engine/execution-env/node-execution-env.d.ts +75 -1
  135. package/dist/engine/execution-env/node-execution-env.js +225 -13
  136. package/dist/engine/harness/types.d.ts +25 -0
  137. package/dist/engine/llm/types.d.ts +8 -0
  138. package/dist/engine/llm/validation.d.ts +8 -1
  139. package/dist/engine/llm/validation.js +31 -2
  140. package/dist/host-env.d.ts +10 -0
  141. package/dist/host-env.js +1 -0
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +9 -2
  144. package/dist/internal/harness-types.d.ts +1 -1
  145. package/dist/orchestration/goal.js +1 -1
  146. package/dist/orchestration/workflow-primitives.js +10 -1
  147. package/dist/orchestration/workflow-script-runner.d.ts +2 -2
  148. package/dist/orchestration/workflow.d.ts +1 -1
  149. package/dist/orchestration/workflow.js +2 -2
  150. package/dist/shell/lex.d.ts +2 -2
  151. package/dist/shell/lex.js +1 -1
  152. package/dist/tools/fs/bash-model-shell.d.ts +23 -0
  153. package/dist/tools/fs/bash-model-shell.js +25 -0
  154. package/dist/tools/fs/bash-readonly-classifier.d.ts +6 -0
  155. package/dist/tools/fs/bash-readonly-classifier.js +3 -0
  156. package/dist/tools/fs/fs-bash.js +13 -11
  157. package/dist/tools/fs/shell-read-argv.js +1 -0
  158. package/dist/tools/fs/shell-read-check.js +39 -9
  159. package/dist/tools/fs/shell-read-plan.d.ts +2 -3
  160. package/dist/tools/fs/shell-read-plan.js +8 -5
  161. package/dist/tools/fs/shell-read-word.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-word.js +13 -4
  163. package/dist/tools/monitor.js +12 -8
  164. package/dist/tools/scheduler-tools.d.ts +1 -0
  165. package/dist/tools/scheduler-tools.js +5 -2
  166. package/package.json +3 -2
  167. package/test/export-surface.snapshot.json +62 -3
  168. package/wire-changes/answers/core-stores-sql@7.74.0.json +7 -0
  169. package/wire-changes/answers/core@7.74.0.json +68 -0
  170. package/wire-changes/answers/mods-kernel@7.74.0.json +21 -0
  171. package/wire-changes/answers/primitives@7.74.0.json +7 -0
  172. package/wire-changes/answers/wiki-gate@7.74.0.json +8 -0
  173. package/wire-changes/core-stores-sql@7.74.0.json +143 -0
  174. package/wire-changes/core@7.74.0.json +2210 -0
  175. package/wire-changes/mods-kernel@7.74.0.json +421 -0
  176. package/wire-changes/primitives@7.74.0.json +174 -0
  177. package/wire-changes/wiki-gate@7.74.0.json +145 -0
@@ -8,8 +8,9 @@ import { admitToolCallId, providerResultIds, providerToolCallId, responseToolCal
8
8
  import { emitBrainTelemetry } from "./status-sink.js";
9
9
  import { DOCUMENT_OMITTED, errorResultMediaNote, IMAGE_OMITTED_NO_VISION, imageWithholdOf, reportImagesWithheld, sendableImages } from "./media-degrade.js";
10
10
  import { ANTHROPIC_RESERVED, OUTPUT_CAP_KEYS, applyExtraBody, declaredRequestValues, effectiveOutputCap, headerBagOnce, headerListEntries, lockHeader, mergeHeaders, takeHeaderSpellings } from "./request-params.js";
11
- import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, joinRequestUrl, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
11
+ import { admitRouteRequest, applyRouteCredentialHeaders, assertServableRequestRoot, brainConfigSnapshot, createBrainRouteJudge, dropBlankCredentialHeaders, joinRequestUrl, keyCarriedBy, resolveRequestRootOf, resolveRouteCredential } from "./route-adjudicator.js";
12
12
  import { requestRouteOf } from "./request-route.js";
13
+ import { authSchemeCredentials, httpTrimmed } from "../core/protocol-http-auth.js";
13
14
  import { NAMES_AS_WRITTEN, judgeInBandError, resolveProviderDialect, endpointToolNames } from "./provider-dialect.js";
14
15
  import { applyReasoningToRequest, mergeReasoningHeaders } from "./reasoning-request.js";
15
16
  import { applyFastModeToRequest, fastModeRouteOf, observeFastMode, requestSpeedOf } from "./fast-mode.js";
@@ -318,6 +319,50 @@ function readEvent(raw) {
318
319
  }
319
320
  export const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
320
321
  const ANTHROPIC_KEY_HEADER = "x-api-key";
322
+ const BEARER_CREDENTIAL_BETAS = Object.freeze([Object.freeze({ head: "sk-ant-oat", beta: "oauth-2025-04-20" })]);
323
+ const bearerCredentialRowOf = (credential) => BEARER_CREDENTIAL_BETAS.find((row) => credential.startsWith(row.head));
324
+ function anthropicKeyHeaderOf(apiKey, headers) {
325
+ const seatTaken = Object.keys(headers).some((name) => name.toLowerCase() === "authorization");
326
+ return !seatTaken && bearerCredentialRowOf(apiKey) !== undefined ? "authorization" : ANTHROPIC_KEY_HEADER;
327
+ }
328
+ function credentialBetaOf(headers) {
329
+ const carried = Object.entries(headers).filter(([name]) => name.toLowerCase() === "authorization");
330
+ if (carried.length !== 1 || typeof carried[0][1] !== "string")
331
+ return undefined;
332
+ const value = httpTrimmed(carried[0][1]);
333
+ const credentials = authSchemeCredentials(value);
334
+ if (credentials === undefined || value.slice(0, value.length - credentials.length).trim().toLowerCase() !== "bearer")
335
+ return undefined;
336
+ const row = bearerCredentialRowOf(credentials);
337
+ return row === undefined ? undefined : { "anthropic-beta": row.beta };
338
+ }
339
+ export function anthropicCredentialHeadersOf(input) {
340
+ const rawKey = input.apiKey;
341
+ const rawHeaders = input.headers;
342
+ const given = rawHeaders !== undefined && rawHeaders !== null && typeof rawHeaders === "object" ? Object.entries(rawHeaders) : [];
343
+ const stringValued = Object.create(null);
344
+ for (const [name, value] of given)
345
+ if (typeof value === "string")
346
+ stringValued[name] = value;
347
+ dropBlankCredentialHeaders(stringValued);
348
+ const outgoing = Object.create(null);
349
+ for (const [name, value] of given)
350
+ if (typeof value === "string" ? name in stringValued : true)
351
+ outgoing[name] = value;
352
+ const apiKey = typeof rawKey === "string" ? keyCarriedBy(rawKey) : undefined;
353
+ let key;
354
+ if (apiKey !== undefined) {
355
+ const header = anthropicKeyHeaderOf(apiKey, outgoing);
356
+ const value = header === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`;
357
+ key = { header, value };
358
+ lockHeader(outgoing, header, value);
359
+ }
360
+ const beta = credentialBetaOf(outgoing)?.["anthropic-beta"];
361
+ return {
362
+ ...(key !== undefined ? { key } : {}),
363
+ ...(beta !== undefined ? { beta } : {}),
364
+ };
365
+ }
321
366
  export function createAnthropicBrain(given = {}) {
322
367
  const config = brainConfigSnapshot(given, "createAnthropicBrain config");
323
368
  assertServableRequestRoot(config.baseUrl, "config.baseUrl");
@@ -411,8 +456,13 @@ export function createAnthropicBrain(given = {}) {
411
456
  mergeReasoningHeaders(headers, fastHeaders);
412
457
  lockHeader(headers, "content-type", "application/json");
413
458
  lockHeader(headers, "anthropic-version", config.version ?? "2023-06-01");
414
- if (apiKey !== undefined)
415
- lockHeader(headers, ANTHROPIC_KEY_HEADER, apiKey);
459
+ if (apiKey !== undefined) {
460
+ const keyHeader = anthropicKeyHeaderOf(apiKey, headers);
461
+ lockHeader(headers, keyHeader, keyHeader === ANTHROPIC_KEY_HEADER ? apiKey : `Bearer ${apiKey}`);
462
+ }
463
+ const credentialBeta = credentialBetaOf(headers);
464
+ if (credentialBeta !== undefined)
465
+ mergeReasoningHeaders(headers, credentialBeta);
416
466
  const builtThinkingRequested = reasoningBody.thinking !== undefined;
417
467
  const builtMaxTokens = reasoningBody.max_tokens;
418
468
  const builtMaxTokensLane = overrides?.maxOutputTokens !== undefined
@@ -611,7 +661,7 @@ export function createAnthropicBrain(given = {}) {
611
661
  }
612
662
  switch (evt.kind) {
613
663
  case "message_start": {
614
- noteResponseModel(partial, evt.model, model.id);
664
+ noteResponseModel(partial, evt.model, model.id, ctrl.providerWords);
615
665
  const u = evt.usage;
616
666
  if (u) {
617
667
  usageRaw.input_tokens = u.input_tokens;
@@ -17,6 +17,11 @@ import type { Brain } from "../core/types.js";
17
17
  * Every gateway moved off is listed on the answer (the model lane's left-behind list: `leftEntriesOf` / `carryLeftBehind`), with the
18
18
  * usage its own message reported — what a failed attempt cost is billed, at the request's model.
19
19
  *
20
+ * Each leg is asked before it is sent ({@link legRefusal}), on both faces and on the pass-through: a leg whose own judgment does
21
+ * not go ahead (it refuses, throws, or answers no verdict) is not called — never handed the request or its per-call credential.
22
+ * That is a clean failure of that leg before anything went out: the walk moves on; the last leg's (or the pass-through's) refusal
23
+ * is the answer; a leg not sent is not among the requests left behind.
24
+ *
20
25
  * Each underlying brain keeps its own retry policy (e.g. `createOpenAIBrain({ maxRetries })`);
21
26
  * failover is the cross-gateway layer on top.
22
27
  */
@@ -1,9 +1,14 @@
1
- import { createAssistantMessageEventStream } from "../internal/llm.js";
1
+ import { createAssistantMessageEventStream, } from "../internal/llm.js";
2
2
  import { abortLikeName, extractErrorCode } from "./errors.js";
3
3
  import { emitBrainTelemetry } from "./status-sink.js";
4
- import { carriesContent, carryLeftBehind, errorMessageOf, gateReadingOf, leftEntriesOf, passthroughStream, terminalMessage, terminalOf, } from "./model-lane.js";
4
+ import { carriesContent, carryLeftBehind, errorMessageOf, gateReadingOf, identityOf, leftEntriesOf, passthroughStream, refusalErrorOf, terminalMessage, terminalOf, } from "./model-lane.js";
5
5
  import { completeOf } from "./brain-faces.js";
6
+ import { readRouteJudgment, sayableModelId, settleUnread } from "./route-adjudicator.js";
6
7
  import { GATEWAY_HOP_GATE } from "../core/model-fallbacks.js";
8
+ function legRefusal(leg, model, options) {
9
+ const refusal = readRouteJudgment(() => leg.adjudicateRoute?.(model, identityOf(options)), model);
10
+ return refusal === undefined ? undefined : errorMessageOf(model, refusalErrorOf(sayableModelId(model), refusal), options?.signal?.aborted === true, false);
11
+ }
7
12
  export function createFailoverBrain(brains) {
8
13
  if (brains.length === 0) {
9
14
  throw new Error("createFailoverBrain: need at least one brain");
@@ -20,7 +25,18 @@ export function createFailoverBrain(brains) {
20
25
  };
21
26
  const stream = (model, context, options) => {
22
27
  if (options?.resilience?.allowFailover === false) {
23
- return passthroughStream(brains[0], model, context, options);
28
+ const primary = brains[0];
29
+ const askedPrimary = {
30
+ stream: (m, c, o) => {
31
+ const refused = legRefusal(primary, m, o);
32
+ if (refused === undefined)
33
+ return primary.stream(m, c, o);
34
+ const answered = createAssistantMessageEventStream();
35
+ answered.push(terminalOf(refused));
36
+ return answered;
37
+ },
38
+ };
39
+ return passthroughStream(askedPrimary, model, context, options);
24
40
  }
25
41
  const out = createAssistantMessageEventStream();
26
42
  void (async () => {
@@ -29,31 +45,39 @@ export function createFailoverBrain(brains) {
29
45
  try {
30
46
  for (const [i, brain] of brains.entries()) {
31
47
  const isLast = i === brains.length - 1;
32
- const inner = await brain.stream(model, context, options);
33
48
  let sawContent = false;
34
49
  let heldStart;
35
50
  let terminal;
36
- for await (const ev of inner) {
37
- if (ev.type === "done" || ev.type === "error") {
38
- terminal = ev;
39
- break;
40
- }
41
- if (ev.type === "start" && !sawContent) {
42
- heldStart = ev;
43
- continue;
44
- }
45
- if (!sawContent) {
46
- sawContent = true;
47
- if (heldStart)
48
- out.push(heldStart);
51
+ let message;
52
+ const refused = legRefusal(brain, model, options);
53
+ if (refused !== undefined) {
54
+ message = refused;
55
+ }
56
+ else {
57
+ const inner = await brain.stream(model, context, options);
58
+ for await (const ev of inner) {
59
+ if (ev.type === "done" || ev.type === "error") {
60
+ terminal = ev;
61
+ break;
62
+ }
63
+ if (ev.type === "start" && !sawContent) {
64
+ heldStart = ev;
65
+ continue;
66
+ }
67
+ if (!sawContent) {
68
+ sawContent = true;
69
+ if (heldStart)
70
+ out.push(heldStart);
71
+ }
72
+ out.push(ev);
49
73
  }
50
- out.push(ev);
74
+ message = await inner.result();
51
75
  }
52
- const message = await inner.result();
53
76
  const cleanUpfrontFailure = !sawContent && gateReadingOf(message, i, false, options?.signal?.aborted === true, GATEWAY_HOP_GATE) !== undefined;
54
77
  if (cleanUpfrontFailure && !isLast) {
55
78
  lastFailedCode = extractErrorCode(message.errorMessage);
56
- left.push(...leftEntriesOf(message, model.id));
79
+ if (refused === undefined)
80
+ left.push(...leftEntriesOf(message, model.id));
57
81
  continue;
58
82
  }
59
83
  reportServed(i, lastFailedCode);
@@ -80,8 +104,11 @@ export function createFailoverBrain(brains) {
80
104
  const left = [];
81
105
  for (let i = 0;; i++) {
82
106
  let message;
107
+ let refused;
83
108
  try {
84
- message = await completeOf(brains[i])(model, context, options);
109
+ const leg = brains[i];
110
+ refused = legRefusal(leg, model, options);
111
+ message = refused ?? (await completeOf(leg)(model, context, options));
85
112
  }
86
113
  catch (e) {
87
114
  const shell = errorMessageOf(model, e, options?.signal?.aborted === true || abortLikeName(e) !== undefined);
@@ -91,7 +118,8 @@ export function createFailoverBrain(brains) {
91
118
  const cleanUpfrontFailure = !carriesContent(message) && gateReadingOf(message, i, false, options?.signal?.aborted === true, GATEWAY_HOP_GATE) !== undefined;
92
119
  if (cleanUpfrontFailure && i < span - 1) {
93
120
  lastFailedCode = extractErrorCode(message.errorMessage);
94
- left.push(...leftEntriesOf(message, model.id));
121
+ if (refused === undefined)
122
+ left.push(...leftEntriesOf(message, model.id));
95
123
  continue;
96
124
  }
97
125
  reportServed(i, lastFailedCode);
@@ -106,6 +134,7 @@ export function createFailoverBrain(brains) {
106
134
  let verdict;
107
135
  try {
108
136
  verdict = b.adjudicateRoute?.(model, perModelAuth);
137
+ settleUnread(verdict);
109
138
  }
110
139
  catch (e) {
111
140
  firstRefusal ??= { threw: e };
@@ -45,9 +45,10 @@
45
45
  * every attempt is billed once, at its own model's price ({@link servedReadingOf}). The answer's own `usage` stays the answer's
46
46
  * (the context reading of the next request is that message's).
47
47
  */
48
- import { type AssistantMessage, type AssistantMessageDiagnostic, type AssistantMessageEvent, type Model, type Usage } from "../internal/llm.js";
48
+ import { type AssistantMessage, type AssistantMessageDiagnostic, type AssistantMessageEvent, type Model, type PerModelAuth, type SimpleStreamOptions, type Usage } from "../internal/llm.js";
49
49
  import type { Brain } from "../core/types.js";
50
- import { ROUTE_JUDGMENT_FAILED } from "./route-adjudicator.js";
50
+ import { BrainError } from "./errors.js";
51
+ import { ROUTE_JUDGMENT_FAILED, type JudgedRefusal } from "./route-adjudicator.js";
51
52
  import { type DegradeReason, type HopGate, type ReceivedModelFallbackPolicy } from "../core/model-fallbacks.js";
52
53
  export { DEGRADE_REASONS, type DegradeReason } from "../core/model-fallbacks.js";
53
54
  /** The `type` of the marker diagnostic a walked request's answer carries. */
@@ -158,7 +159,8 @@ export declare function servedReadingOf(requested: Model, msg: {
158
159
  /**
159
160
  * The terminal for a request whose Brain threw (or whose stream broke its protocol) instead of answering: the request was handed
160
161
  * to the Brain, so what it cost is unknown — the usage is a lower bound (`usageMissing`), never a known zero. A request refused
161
- * before it was dispatched (`sent: false`) cost nothing: its zero usage is a known zero.
162
+ * before it was dispatched (`sent: false`) cost nothing: its zero usage is a known zero. The model's id is read once, guarded
163
+ * ({@link sayableModelId}): an error terminal is minted for a model whose id will not read too.
162
164
  */
163
165
  export declare function errorMessageOf(model: Model, e: unknown, aborted: boolean, sent?: boolean): AssistantMessage;
164
166
  /** The terminal event of a message: an error frame for an error / aborted message, else `done`. */
@@ -178,6 +180,13 @@ export declare function carriesContent(msg: AssistantMessage): boolean;
178
180
  * guess).
179
181
  */
180
182
  export declare function gateReadingOf(msg: AssistantMessage, hop: number, expired: boolean, callerAborted: boolean, gate: HopGate): DegradeReason | "next" | undefined;
183
+ /** The per-call answer a hop is dispatched with, as the judgment is handed it — the whole {@link PerModelAuth} the request carries
184
+ * (its header bag already a copy read once: by the answer's one reader, `askPerModelAuth`, and in the main loop by the merge with
185
+ * the run's own bag):
186
+ * the options' `apiKey`, `headers`, `credentialOrigin` and the engine's `credentialOriginUnsettled` mark (none for a later hop —
187
+ * {@link hopOptionsOf} drops them); `undefined` when there is none. The judgment judges the request the Brain would build from it. */
188
+ export declare function identityOf(options: SimpleStreamOptions | undefined): PerModelAuth | undefined;
189
+ export declare function refusalErrorOf(id: string, refusal: JudgedRefusal): BrainError;
181
190
  /**
182
191
  * The model lane over a deployment Brain and a received fallback policy — one Brain per (Brain, policy) pair, so every read of
183
192
  * the seat answers the same object. A request whose model has no chain is judged, then the inner Brain's own call (its route
@@ -6,7 +6,7 @@ import { armBrainCallDeadline } from "./timeout.js";
6
6
  import { isExactCount, reasoningTokensOf } from "./usage-reasoning.js";
7
7
  import { markRefusedBeforeAnyStream, wasRefusedBeforeAnyStream } from "./usage-reading.js";
8
8
  import { readElements, readMember, readMemberOrUnreadable, thrownText } from "../core/thrown-value.js";
9
- import { readRouteJudgment, routeRefusalError, ROUTE_JUDGMENT_FAILED } from "./route-adjudicator.js";
9
+ import { readRouteJudgment, routeRefusalError, ROUTE_JUDGMENT_FAILED, sayableModelId } from "./route-adjudicator.js";
10
10
  import { requestModelOf } from "../core/model-receipt.js";
11
11
  import { isSpendRefusal } from "./spend-meter.js";
12
12
  import { ANY_HOP_FAILURE, DEFAULT_MODEL_FALLBACK_POLICY, hopGateAdmits, isDegradeReason, modelFallbackChainOf, } from "../core/model-fallbacks.js";
@@ -174,7 +174,7 @@ export function errorMessageOf(model, e, aborted, sent = true) {
174
174
  content: [{ type: "text", text: "" }],
175
175
  api: model.api,
176
176
  provider: model.provider,
177
- model: model.id,
177
+ model: sayableModelId(model),
178
178
  stopReason: aborted ? "aborted" : "error",
179
179
  errorMessage: thrownText(e),
180
180
  usage: ZERO_USAGE,
@@ -240,7 +240,7 @@ export function gateReadingOf(msg, hop, expired, callerAborted, gate) {
240
240
  }
241
241
  return hopGateAdmits(gate, reason) ? reason : undefined;
242
242
  }
243
- function identityOf(options) {
243
+ export function identityOf(options) {
244
244
  const { apiKey, headers, credentialOrigin, credentialOriginUnsettled } = options ?? {};
245
245
  const auth = {
246
246
  ...(apiKey !== undefined ? { apiKey } : {}),
@@ -255,7 +255,7 @@ function judgedHop(inner, hop, options, dispatch) {
255
255
  const cancelled = () => options?.signal?.aborted === true;
256
256
  if (cancelled())
257
257
  return { model };
258
- const refusal = readRouteJudgment(() => inner.adjudicateRoute?.(model, identityOf(options), { hop: dispatch }), hop.id);
258
+ const refusal = readRouteJudgment(() => inner.adjudicateRoute?.(model, identityOf(options), { hop: dispatch }), hop);
259
259
  if (refusal === undefined || cancelled())
260
260
  return { model };
261
261
  const { code, fixHint } = refusal;
@@ -267,7 +267,7 @@ function refusalMessageOf(requested, refused) {
267
267
  function cancelledMessageOf(requested, options) {
268
268
  return errorMessageOf(requested, options?.signal?.reason ?? "aborted", true, false);
269
269
  }
270
- function refusalErrorOf(id, refusal) {
270
+ export function refusalErrorOf(id, refusal) {
271
271
  if (refusal.verdict !== undefined)
272
272
  return routeRefusalError(refusal.verdict);
273
273
  if (refusal.code === ROUTE_JUDGMENT_FAILED && refusal.fixHint !== undefined)
@@ -435,7 +435,7 @@ export function createOpenResponsesBrain(given = {}) {
435
435
  if (env) {
436
436
  if (env.id !== undefined)
437
437
  responseId = env.id;
438
- noteResponseModel(partial, env.model, model.id);
438
+ noteResponseModel(partial, env.model, model.id, ctrl.providerWords);
439
439
  auditEcho(env);
440
440
  }
441
441
  return;
@@ -576,11 +576,11 @@ export function createOpenResponsesBrain(given = {}) {
576
576
  usageRaw = env.usage;
577
577
  if (env?.id !== undefined)
578
578
  responseId = env.id;
579
- noteResponseModel(partial, env?.model, model.id);
579
+ noteResponseModel(partial, env?.model, model.id, ctrl.providerWords);
580
580
  return;
581
581
  }
582
582
  case "response.failed": {
583
- noteResponseModel(partial, frame.response?.model, model.id);
583
+ noteResponseModel(partial, frame.response?.model, model.id, ctrl.providerWords);
584
584
  const err = frame.response?.error;
585
585
  if (err !== undefined && err !== null)
586
586
  ctrl.inBandFrame(err);
@@ -530,7 +530,7 @@ export function createOpenAIBrain(given = {}) {
530
530
  usageRaw = chunk.usage;
531
531
  if (chunk.usageUnreadable)
532
532
  usageUnreadable = true;
533
- noteResponseModel(partial, chunk.model, model.id);
533
+ noteResponseModel(partial, chunk.model, model.id, ctrl.providerWords);
534
534
  const choice = chunk.choice;
535
535
  if (terminalFrameSeen()) {
536
536
  if (choice !== undefined && choice.finish !== null && choice.finish !== finishReason)
@@ -1,4 +1,5 @@
1
1
  import type { Model, PerModelAuth } from "../internal/llm.js";
2
+ import type { AssertAllKeysHandled } from "../core/ask-origin.js";
2
3
  import type { RouteAdjudication, RouteCredential, RoutePairingConfig, RoutePairingPosture, RouteRefusalCode } from "../internal/llm.js";
3
4
  import type { Brain, EngineNotice } from "../core/types.js";
4
5
  import { BrainError } from "./errors.js";
@@ -226,16 +227,33 @@ export interface JudgedRefusal {
226
227
  ok: false;
227
228
  }>;
228
229
  }
230
+ /** Whether a route judgment's answer is a Promise (any object whose `then`, read once, is a function): a judgment answers
231
+ * synchronously, so a Promise is no verdict, and its own settlement belongs to nobody — it must not become an unhandled
232
+ * rejection. That very `then` is handed two empty reactions, called with the answer as `this` (a throw of the call is absorbed
233
+ * too). A plain answer is not touched beyond that one read; a `then` that will not read (a strict Proxy whose `get` throws) shows
234
+ * no `then`, so the answer is no Promise and is read by the `ok` it gives — as 7.73.0 read an answer whose members read the same at
235
+ * every read; reading `then` before `ok` is new (`KL-4241-d` (9)). */
236
+ export declare function settleUnread(answer: unknown): boolean;
237
+ /** What a sentence says for a model whose `id` will not read (an accessor that throws, a revoked proxy). */
238
+ export declare const UNREADABLE_MODEL_ID = "<unreadable model id>";
239
+ /** A model's id for a sentence about it: one guarded read; an id that will not read is said as {@link UNREADABLE_MODEL_ID}. */
240
+ export declare function sayableModelId(model: {
241
+ readonly id: string;
242
+ }): string;
229
243
  /**
230
244
  * THE reading of a route judgment's answer — every seat that asks the deployment Brain's `adjudicateRoute` reads the answer here,
231
245
  * once (the model lane before each hop, a derived seat's pre-flight): `undefined` when the route goes ahead — the judgment
232
246
  * admitted it (`ok: true`) or gave none (`undefined`: no judgment) — else the route as refused. `ok: false` is a refusal, read
233
247
  * member by member; ANY other answer is a judgment that failed ({@link ROUTE_JUDGMENT_FAILED}, the sentence saying how): it
234
- * threw, answered a Promise (a route judgment answers synchronously — a pending answer is no answer, and reading it as one would
235
- * admit every route it was asked about), answered a value that is not a verdict, or a verdict whose members would not read.
236
- * Never throws. `ask` is the call (so its throw is read here); `modelId` names the judged model in the sentence.
248
+ * threw, answered a Promise, whatever `ok` it carries (a route judgment answers synchronously — a pending answer is no answer, and
249
+ * reading it as one would admit every route it was asked about; its settlement is absorbed, {@link settleUnread}), answered a value that is not a verdict, or a verdict whose members would not read.
250
+ * Never throws. `ask` is the call (so its throw is read here); `judged` is the judged model, whose id names it in the sentence —
251
+ * read once, only when there is a refusal to say (a route that goes ahead costs no read of the model), and said as
252
+ * {@link UNREADABLE_MODEL_ID} when it will not read ({@link sayableModelId}).
237
253
  */
238
- export declare function readRouteJudgment(ask: () => unknown, modelId: string): JudgedRefusal | undefined;
254
+ export declare function readRouteJudgment(ask: () => unknown, judged: {
255
+ readonly id: string;
256
+ }): JudgedRefusal | undefined;
239
257
  /**
240
258
  * THE request gate of a first-party brain — the seat that binds a credential where it is first SENT (the table's other
241
259
  * writer is the host's explicit rebind, {@link rebindCredentialOrigin}, which sets a credential's origin by the host's
@@ -373,6 +391,13 @@ export declare function rebindCredentialOrigin(model: Pick<Model, "id" | "baseUr
373
391
  * not ride — the header half of the keyless door the blank key is ({@link keyCarriedBy}).
374
392
  */
375
393
  export declare function applyRouteCredentialHeaders(merged: Record<string, string>, credential: RouteCredential): void;
394
+ /**
395
+ * THE one reading of "a credential header whose value is blank is no credential and does not ride" ({@link isBlankCredential}):
396
+ * every header of `headers` whose name is a credential header ({@link isCredentialHeaderName}) and whose value is blank is deleted
397
+ * from it. Read by {@link applyRouteCredentialHeaders} on a request's merged bag, and by a judge that answers for the same bag
398
+ * before a request is built (`anthropicCredentialHeadersOf`). A credential header's value is a string.
399
+ */
400
+ export declare function dropBlankCredentialHeaders(headers: Record<string, string>): void;
376
401
  /** A brain's construction config, received ONCE by the engine's receipt law for caller objects
377
402
  * ({@link receiveOwnProperties}: a plain object, every own member read once): the request gate and the pre-flight
378
403
  * judge both read this frozen copy, so a config object mutated after construction moves neither and the two cannot
@@ -405,6 +430,10 @@ export declare function createBrainRouteJudge(config: {
405
430
  * built, so a value that is not a boolean is refused at construction rather than at the first request. */
406
431
  requireCredential?: boolean;
407
432
  }): (model: Model, perModelAuth?: PerModelAuth) => RouteAdjudication;
433
+ /** The words of {@link RoutePairingStatus}, spelled (the release manifest and a host's table read them): fenced both ways to the type below, so neither can gain a word the other lacks. */
434
+ export declare const ROUTE_PAIRING_STATUSES: readonly ["ok:per-model", "ok:paired", "ok:keyless", "broken:credential_mismatch", "broken:credential_missing", "broken:credential_origin_mismatch", "broken:credential_answer_conflict", "broken:protocol_plaintext_credentials", "broken:model_unavailable", "unknown"];
435
+ export type RoutePairingStatusesAllListed = AssertAllKeysHandled<Exclude<RoutePairingStatus, (typeof ROUTE_PAIRING_STATUSES)[number]>>;
436
+ export type RoutePairingStatusesAllWords = AssertAllKeysHandled<Exclude<(typeof ROUTE_PAIRING_STATUSES)[number], RoutePairingStatus>>;
408
437
  /**
409
438
  * Per-entry pairing status — the read-face predicate a roster/diagnostic surface annotates entries
410
439
  * with, so a torn pair is visible at configuration time instead of on the first real request.
@@ -9,7 +9,7 @@ import { deliverEngineNotice } from "../core/engine-notice.js";
9
9
  import { uuidv7 } from "../engine/session/uuid.js";
10
10
  import { CREDENTIAL_VOCABULARY, REDACTION_MARKS, isRedactionMark } from "@sema-agent/primitives";
11
11
  import { PROTOCOL_PLAINTEXT_CREDENTIALS_CODE, crossesNetworkInClear } from "../core/protocol-http-auth.js";
12
- import { thrownText } from "../core/thrown-value.js";
12
+ import { readMemberOrUnreadable, thrownText, UNREADABLE } from "../core/thrown-value.js";
13
13
  import { headerBagOnce } from "./request-params.js";
14
14
  const REDACTED_VALUE = REDACTION_MARKS.bare;
15
15
  const REDACTED_USERINFO = REDACTION_MARKS.userinfo;
@@ -553,8 +553,32 @@ const BOUND_BY_WORDS = { declaration: true, table: true, generation: true };
553
553
  function boundByOf(value) {
554
554
  return typeof value === "string" && Object.hasOwn(BOUND_BY_WORDS, value) ? value : undefined;
555
555
  }
556
- export function readRouteJudgment(ask, modelId) {
557
- const failed = (how) => ({ code: ROUTE_JUDGMENT_FAILED, fixHint: `the deployment Brain's route judgment for "${modelId}" ${how}` });
556
+ export function settleUnread(answer) {
557
+ if (typeof answer !== "object" || answer === null)
558
+ return false;
559
+ let then;
560
+ try {
561
+ then = answer.then;
562
+ }
563
+ catch {
564
+ return false;
565
+ }
566
+ if (typeof then !== "function")
567
+ return false;
568
+ Promise.resolve()
569
+ .then(() => Reflect.apply(then, answer, [() => undefined, () => undefined]))
570
+ .catch(() => undefined);
571
+ return true;
572
+ }
573
+ export const UNREADABLE_MODEL_ID = "<unreadable model id>";
574
+ export function sayableModelId(model) {
575
+ const id = readMemberOrUnreadable(model, "id");
576
+ return id === UNREADABLE ? UNREADABLE_MODEL_ID : id;
577
+ }
578
+ export function readRouteJudgment(ask, judged) {
579
+ let said;
580
+ const modelIdOf = () => (said ??= sayableModelId(judged));
581
+ const failed = (how) => ({ code: ROUTE_JUDGMENT_FAILED, fixHint: `the deployment Brain's route judgment for "${modelIdOf()}" ${how}` });
558
582
  let answer;
559
583
  try {
560
584
  answer = ask();
@@ -565,15 +589,13 @@ export function readRouteJudgment(ask, modelId) {
565
589
  if (answer === undefined)
566
590
  return undefined;
567
591
  try {
592
+ if (settleUnread(answer)) {
593
+ return failed("answered a Promise — a route judgment must answer synchronously (a verdict, or undefined for no judgment); nothing was sent");
594
+ }
568
595
  const ok = typeof answer === "object" && answer !== null ? answer.ok : undefined;
569
596
  if (ok === true)
570
597
  return undefined;
571
598
  if (ok !== false) {
572
- const then = typeof answer === "object" && answer !== null ? answer.then : undefined;
573
- if (typeof then === "function") {
574
- Promise.resolve(answer).catch(() => undefined);
575
- return failed("answered a Promise — a route judgment must answer synchronously (a verdict, or undefined for no judgment); nothing was sent");
576
- }
577
599
  return failed(`answered ${describeRejectedValue(answer)}${ok === undefined ? "" : ` whose ok is ${describeRejectedValue(ok)}`} — not a verdict (ok true or false) nor undefined; nothing was sent`);
578
600
  }
579
601
  const code = answer.code;
@@ -592,7 +614,7 @@ export function readRouteJudgment(ask, modelId) {
592
614
  const verdict = {
593
615
  ok: false,
594
616
  code,
595
- detail: { modelId: typeof named === "string" ? named : modelId, ...roots, ...(boundBy !== undefined ? { boundBy } : {}), fixHint },
617
+ detail: { modelId: typeof named === "string" ? named : modelIdOf(), ...roots, ...(boundBy !== undefined ? { boundBy } : {}), fixHint },
596
618
  };
597
619
  return { code, fixHint, verdict };
598
620
  }
@@ -785,9 +807,12 @@ export function applyRouteCredentialHeaders(merged, credential) {
785
807
  }
786
808
  Object.assign(merged, resolvedCredentialFacts.get(credential)?.headers);
787
809
  }
788
- for (const [k, value] of Object.entries(merged)) {
810
+ dropBlankCredentialHeaders(merged);
811
+ }
812
+ export function dropBlankCredentialHeaders(headers) {
813
+ for (const [k, value] of Object.entries(headers)) {
789
814
  if (isCredentialHeaderName(k) && isBlankCredential(value))
790
- delete merged[k];
815
+ delete headers[k];
791
816
  }
792
817
  }
793
818
  export function brainConfigSnapshot(given, subject) {
@@ -822,6 +847,18 @@ export function createBrainRouteJudge(config) {
822
847
  return adjudicateModelRoute(routed, credential, { baseUrl: config.baseUrl, laneDefault: config.laneDefault, requireCredential });
823
848
  };
824
849
  }
850
+ export const ROUTE_PAIRING_STATUSES = Object.freeze([
851
+ "ok:per-model",
852
+ "ok:paired",
853
+ "ok:keyless",
854
+ "broken:credential_mismatch",
855
+ "broken:credential_missing",
856
+ "broken:credential_origin_mismatch",
857
+ "broken:credential_answer_conflict",
858
+ "broken:protocol_plaintext_credentials",
859
+ "broken:model_unavailable",
860
+ "unknown",
861
+ ]);
825
862
  const BROKEN_PAIRING_STATUS = {
826
863
  "route.credential_mismatch": "broken:credential_mismatch",
827
864
  "route.credential_missing": "broken:credential_missing",
@@ -908,7 +945,7 @@ export async function adjudicateDerivedRoute(args) {
908
945
  clearTimeout(timer);
909
946
  }
910
947
  }
911
- return readRouteJudgment(() => judge(args.model, auth), args.model.id);
948
+ return readRouteJudgment(() => judge(args.model, auth), args.model);
912
949
  }
913
950
  export function sameRouteIdentity(a, b) {
914
951
  return a.id === b.id && routeKeyOf(a.baseUrl) === routeKeyOf(b.baseUrl);
@@ -251,6 +251,7 @@ function cutArmOf(snap, left) {
251
251
  return left.shared ? "resend" : "fail";
252
252
  }
253
253
  const WAIT_OUTCOME_OF_CUT = { whole: undefined, keep: "keep", resend_thinking: "retry", resend: "retry", fail: "fail" };
254
+ const WATCHDOG_CUT_CODE = "network";
254
255
  const THINKING_RETRY_BUDGET = 2;
255
256
  const EMPTY_USAGE = {
256
257
  input: 0,
@@ -725,6 +726,7 @@ export function runStreamingBrain(args) {
725
726
  const firstByteRetryLeft = () => firstByteStalls < firstByteRetryBudget;
726
727
  const streamCutOf = (snap) => cutArmOf(snap, { thinking: thinkingRetries < THINKING_RETRY_BUDGET, shared: attempt < maxRetries });
727
728
  const followedBy = (code) => (signal?.aborted !== true && code !== "auth" ? untried : undefined);
729
+ const forecastOfCut = (outcome) => (outcome === "fail" && followedBy(WATCHDOG_CUT_CODE) !== undefined ? "retry" : outcome);
728
730
  const fallBack = (failure) => {
729
731
  const next = followedBy(failure.code);
730
732
  if (next === undefined)
@@ -776,7 +778,7 @@ export function runStreamingBrain(args) {
776
778
  throw e;
777
779
  }
778
780
  const window = firstByteWindow(firstByteTimeoutMs, Buffer.byteLength(req.body), firstByteStalls);
779
- const headerWait = armWaitDisclosure(window.windowMs, "response_headers", () => (firstByteRetryLeft() ? "retry" : "fail"));
781
+ const headerWait = armWaitDisclosure(window.windowMs, "response_headers", () => forecastOfCut(firstByteRetryLeft() ? "retry" : "fail"));
780
782
  const cc = createAttemptController(window.windowMs, signal);
781
783
  let r;
782
784
  let netErr;
@@ -793,7 +795,7 @@ export function runStreamingBrain(args) {
793
795
  knob: "firstByteTimeoutMs",
794
796
  timeoutMs: window.windowMs,
795
797
  allowanceMs: window.allowanceMs,
796
- err: new BrainError("network", firstByteTimeoutMessage(firstByteWindowsWaited), undefined, { apiError: true }),
798
+ err: new BrainError(WATCHDOG_CUT_CODE, firstByteTimeoutMessage(firstByteWindowsWaited), undefined, { apiError: true }),
797
799
  };
798
800
  };
799
801
  try {
@@ -840,7 +842,7 @@ export function runStreamingBrain(args) {
840
842
  refusedOutright = (refusedOutright ?? true) && r !== undefined && refusedTheRequest(r.status);
841
843
  let errorBody;
842
844
  let speedRuled;
843
- if (!(r && r.ok && r.body) && followedBy(r !== undefined ? classifyHttp(r.status) : "network") !== undefined) {
845
+ if (!(r && r.ok && r.body) && followedBy(r !== undefined ? classifyHttp(r.status) : WATCHDOG_CUT_CODE) !== undefined) {
844
846
  cc.clearTimer();
845
847
  try {
846
848
  if (r !== undefined)
@@ -860,7 +862,7 @@ export function runStreamingBrain(args) {
860
862
  const stated = r !== undefined && namesTheFailure(r.status) ? judgeHttpFailure({ dialect, status: r.status, headers: r.headers, body: errorBody }) : undefined;
861
863
  const envelope = statedEnvelope(errorBody);
862
864
  fallBack({
863
- code: r !== undefined ? classifyHttp(r.status) : "network",
865
+ code: r !== undefined ? classifyHttp(r.status) : WATCHDOG_CUT_CODE,
864
866
  status: r?.status,
865
867
  statement: envelope !== undefined && shouldRetryHeaderVerdict(r) !== true ? { envelope, inputTooLong: stated?.inputTooLong === "yes" } : undefined,
866
868
  spent: undefined,
@@ -1055,7 +1057,7 @@ export function runStreamingBrain(args) {
1055
1057
  let ftTimer;
1056
1058
  let firstTokenWait = NO_WAIT_DISCLOSURE;
1057
1059
  let nextTokenWait = NO_WAIT_DISCLOSURE;
1058
- const cutOutcome = () => WAIT_OUTCOME_OF_CUT[streamCutOf(parser.snapshot())];
1060
+ const cutOutcome = () => forecastOfCut(WAIT_OUTCOME_OF_CUT[streamCutOf(parser.snapshot())]);
1059
1061
  const streamSuspend = connect.suspend;
1060
1062
  let suspendedInStream;
1061
1063
  const cutOnSuspend = (wait) => (sleptMs) => {
@@ -1289,7 +1291,7 @@ export function runStreamingBrain(args) {
1289
1291
  watchdog: "first-token",
1290
1292
  knob: "firstTokenTimeoutMs",
1291
1293
  timeoutMs: firedFirstTokenDeadlineMs,
1292
- err: new BrainError("network", `first-token timeout after ${firedFirstTokenDeadlineMs}ms`, undefined, { apiError: true }),
1294
+ err: new BrainError(WATCHDOG_CUT_CODE, `first-token timeout after ${firedFirstTokenDeadlineMs}ms`, undefined, { apiError: true }),
1293
1295
  };
1294
1296
  }
1295
1297
  if (!failure && firedIdleDeadlineMs !== undefined) {
@@ -1298,7 +1300,7 @@ export function runStreamingBrain(args) {
1298
1300
  watchdog: "stream idle",
1299
1301
  knob: "idleTimeoutMs",
1300
1302
  timeoutMs: firedIdleDeadlineMs,
1301
- err: new BrainError("network", `stream idle timeout after ${firedIdleDeadlineMs}ms`, undefined, { apiError: true }),
1303
+ err: new BrainError(WATCHDOG_CUT_CODE, `stream idle timeout after ${firedIdleDeadlineMs}ms`, undefined, { apiError: true }),
1302
1304
  };
1303
1305
  }
1304
1306
  if (fellBack || (failure !== undefined && !parser.snapshot().terminalFrameSeen && fellBackFromStream({ code: brainErrorCodeOf(failure.err), status: undefined, statement: undefined, spent: undefined }))) {
@@ -191,9 +191,10 @@ export declare function createRepetitionPoll(): RepetitionPoll;
191
191
  * `message_start.message.model` / `response.model`), WRITE twin of `providerReportedModel`
192
192
  * (`core/message-utils.ts`). The LAST frame that NAMES a model decides and the seat carries it only when it
193
193
  * differs; naming nothing (no name, or the empty string — {@link providerEchoReading}) is not an update, naming the
194
- * REQUESTED id RETRACTS an earlier substitution. A name outside {@link isProviderEchoShape} is dropped — not an
195
- * update — and counted once per response (`echo_dropped`, `field: "responseModel"`). */
194
+ * REQUESTED id RETRACTS an earlier substitution. A name outside {@link isProviderEchoShape}, or one the stream's mint
195
+ * (`providerWords`) would not leave as it is — it holds what the request was declared with, or a credential shape — is
196
+ * dropped, never rewritten — not an update — and counted once per response (`echo_dropped`, `field: "responseModel"`). */
196
197
  export declare function noteResponseModel(partial: {
197
198
  responseModel?: string;
198
- }, reported: unknown, requestedId: string): void;
199
+ }, reported: unknown, requestedId: string, providerWords: (words: string) => string): void;
199
200
  export {};
@@ -150,7 +150,7 @@ export function createRepetitionPoll() {
150
150
  };
151
151
  }
152
152
  const refusedModelCounted = new WeakSet();
153
- export function noteResponseModel(partial, reported, requestedId) {
153
+ export function noteResponseModel(partial, reported, requestedId, providerWords) {
154
154
  const reading = providerEchoReading(reported);
155
155
  if (reading === "absent")
156
156
  return;
@@ -158,7 +158,7 @@ export function noteResponseModel(partial, reported, requestedId) {
158
158
  delete partial.responseModel;
159
159
  return;
160
160
  }
161
- if (reading === "refused") {
161
+ if (reading === "refused" || providerWords(reported) !== reported) {
162
162
  if (!refusedModelCounted.has(partial)) {
163
163
  refusedModelCounted.add(partial);
164
164
  emitBrainTelemetry({ kind: "echo_dropped", field: "responseModel" });