@sema-agent/server 7.131.0 → 7.132.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 (256) hide show
  1. package/MIGRATION.md +309 -0
  2. package/README.md +5 -1
  3. package/README.zh-CN.md +3 -1
  4. package/USAGE.md +163 -54
  5. package/dist/approval-card.d.ts +3 -1
  6. package/dist/approval-card.js +2 -3
  7. package/dist/audit.d.ts +7 -10
  8. package/dist/auth-bridge.d.ts +4 -0
  9. package/dist/auth-bridge.js +10 -11
  10. package/dist/boot/deployment-mods.d.ts +31 -0
  11. package/dist/boot/deployment-mods.js +26 -0
  12. package/dist/boot/execution-env.d.ts +1 -1
  13. package/dist/boot/execution-env.js +19 -6
  14. package/dist/boot/memory-boundary.d.ts +2 -2
  15. package/dist/boot/read-deny-anchor-audit.d.ts +17 -0
  16. package/dist/boot/read-deny-anchor-audit.js +36 -0
  17. package/dist/boot/resolve-spec.d.ts +1 -5
  18. package/dist/boot/resolve-spec.js +19 -47
  19. package/dist/boot/runner-deps.d.ts +19 -8
  20. package/dist/boot/runner-deps.js +14 -2
  21. package/dist/boot/session-faces.d.ts +1 -7
  22. package/dist/boot/stage-03-store-backend.d.ts +1 -1
  23. package/dist/boot/stage-03-store-backend.js +2 -2
  24. package/dist/boot/stage-04-stores.d.ts +1 -1
  25. package/dist/boot/stage-05-execution-env.d.ts +4 -4
  26. package/dist/boot/stage-05-execution-env.js +7 -10
  27. package/dist/boot/stage-06-runners.d.ts +2 -2
  28. package/dist/boot/stage-06-runners.js +5 -4
  29. package/dist/boot/stage-07-capability-layer.d.ts +2 -2
  30. package/dist/boot/stage-07-capability-layer.js +3 -3
  31. package/dist/boot/stage-08-reapers.d.ts +2 -2
  32. package/dist/boot/stage-09-leader.d.ts +3 -9
  33. package/dist/boot/stage-10-http-server.d.ts +3 -9
  34. package/dist/boot/stage-10-http-server.js +6 -7
  35. package/dist/boot/stores.d.ts +1 -1
  36. package/dist/boot/stores.js +5 -6
  37. package/dist/boot/web-admin.d.ts +0 -3
  38. package/dist/boot/web-admin.js +35 -35
  39. package/dist/brain.js +17 -22
  40. package/dist/budget.js +5 -4
  41. package/dist/caller-text-echo.d.ts +20 -0
  42. package/dist/caller-text-echo.js +24 -0
  43. package/dist/capabilities/brand-identity.d.ts +26 -0
  44. package/dist/capabilities/brand-identity.js +27 -0
  45. package/dist/capabilities/center-plugins.js +1 -1
  46. package/dist/capabilities/center-prompts.d.ts +32 -59
  47. package/dist/capabilities/center-prompts.js +18 -32
  48. package/dist/capabilities/engine-capabilities.js +2 -1
  49. package/dist/capabilities/hands-lane.d.ts +9 -6
  50. package/dist/capabilities/hands-lane.js +1 -1
  51. package/dist/capabilities/mcp-probe.d.ts +14 -1
  52. package/dist/capabilities/mcp-probe.js +22 -133
  53. package/dist/capabilities/scenarios.d.ts +34 -40
  54. package/dist/capabilities/scenarios.js +16 -33
  55. package/dist/capabilities/skills.d.ts +19 -4
  56. package/dist/capabilities/skills.js +30 -10
  57. package/dist/config-catalog.js +6 -6
  58. package/dist/config-lkg.d.ts +9 -9
  59. package/dist/config-lkg.js +20 -4
  60. package/dist/config-provider.d.ts +3 -1
  61. package/dist/config-provider.js +12 -4
  62. package/dist/config-types.d.ts +7 -9
  63. package/dist/config.js +17 -4
  64. package/dist/device-ws-protocol.d.ts +1 -1
  65. package/dist/device-ws-protocol.js +1 -0
  66. package/dist/env-name-allowlist-knobs.d.ts +12 -2
  67. package/dist/env-name-allowlist-knobs.js +5 -4
  68. package/dist/exec-bounds.d.ts +15 -3
  69. package/dist/exec-bounds.js +4 -0
  70. package/dist/execution-lane-caps.d.ts +9 -2
  71. package/dist/execution-lane-caps.js +11 -0
  72. package/dist/hooks/classic-stations.d.ts +86 -0
  73. package/dist/hooks/classic-stations.js +27 -0
  74. package/dist/hooks/hook-llm.d.ts +8 -5
  75. package/dist/hooks/hook-llm.js +78 -35
  76. package/dist/hooks/hook-runner.d.ts +232 -80
  77. package/dist/hooks/hook-runner.js +218 -312
  78. package/dist/http/admission.d.ts +8 -2
  79. package/dist/http/admission.js +101 -57
  80. package/dist/http/approval-sweeps.js +57 -16
  81. package/dist/http/checkpoint-ctx.d.ts +25 -8
  82. package/dist/http/checkpoint-ctx.js +11 -7
  83. package/dist/http/claimed-run.d.ts +13 -0
  84. package/dist/http/claimed-run.js +15 -0
  85. package/dist/http/device-placement.js +5 -10
  86. package/dist/http/dispatch.d.ts +0 -4
  87. package/dist/http/dispatch.js +5 -9
  88. package/dist/http/durable-run-leg.d.ts +2 -1
  89. package/dist/http/durable-run-leg.js +5 -3
  90. package/dist/http/health-self-report.d.ts +7 -5
  91. package/dist/http/health-self-report.js +4 -18
  92. package/dist/http/principal-gate.d.ts +23 -6
  93. package/dist/http/principal-gate.js +24 -5
  94. package/dist/http/refusal-body.d.ts +21 -0
  95. package/dist/http/refusal-body.js +4 -0
  96. package/dist/http/request-guards.d.ts +27 -0
  97. package/dist/http/request-guards.js +24 -3
  98. package/dist/http/resume-legs.d.ts +25 -0
  99. package/dist/http/resume-legs.js +43 -22
  100. package/dist/http/routes/capabilities.js +1 -1
  101. package/dist/http/routes/diagnostics.js +1 -1
  102. package/dist/http/routes/rules.js +2 -2
  103. package/dist/http/routes/runs.js +7 -7
  104. package/dist/http/routes/session-sync.js +4 -2
  105. package/dist/http/routes/sessions.js +1 -1
  106. package/dist/http/routes/shared-memory.js +2 -13
  107. package/dist/http/routes/side-query.js +2 -3
  108. package/dist/http/routes/tasks.js +19 -9
  109. package/dist/http/send.d.ts +9 -7
  110. package/dist/http/send.js +7 -2
  111. package/dist/http/server.d.ts +21 -11
  112. package/dist/http/server.js +28 -2
  113. package/dist/http/submit-ctx.d.ts +25 -0
  114. package/dist/http/submit-ctx.js +39 -0
  115. package/dist/http/wire-types.d.ts +1 -1
  116. package/dist/index.d.ts +1 -1
  117. package/dist/index.js +1 -1
  118. package/dist/lane-home-probe.d.ts +43 -0
  119. package/dist/lane-home-probe.js +35 -0
  120. package/dist/limit-refusal.d.ts +47 -0
  121. package/dist/limit-refusal.js +12 -0
  122. package/dist/main.js +1 -1
  123. package/dist/mcp-assertion-header.d.ts +1 -9
  124. package/dist/mcp-assertion-header.js +0 -6
  125. package/dist/mcp-tool-faces.d.ts +5 -0
  126. package/dist/mcp-tool-faces.js +5 -1
  127. package/dist/memory-scope.d.ts +1 -1
  128. package/dist/model-provider.d.ts +39 -12
  129. package/dist/model-provider.js +19 -2
  130. package/dist/model-route-endpoint.d.ts +1 -1
  131. package/dist/model-route-endpoint.js +5 -5
  132. package/dist/observability/cost-taxonomy.d.ts +7 -7
  133. package/dist/observability/fail-open.d.ts +42 -6
  134. package/dist/observability/fail-open.js +42 -6
  135. package/dist/observability/metrics.js +3 -1
  136. package/dist/observability/prompt-manifest.d.ts +47 -82
  137. package/dist/observability/prompt-manifest.js +119 -17
  138. package/dist/observability/run-terminal.js +14 -6
  139. package/dist/observability/secret-env-scrub.d.ts +13 -1
  140. package/dist/observability/secret-env-scrub.js +13 -1
  141. package/dist/observability/tool-trace.d.ts +16 -21
  142. package/dist/observability/tool-trace.js +51 -42
  143. package/dist/per-task-image.d.ts +7 -1
  144. package/dist/per-task-image.js +3 -3
  145. package/dist/plain-string-record.d.ts +25 -0
  146. package/dist/plain-string-record.js +32 -0
  147. package/dist/plugins/blob-backend.d.ts +68 -13
  148. package/dist/plugins/blob-backend.js +53 -10
  149. package/dist/plugins/checkpoint-store-sql.d.ts +14 -4
  150. package/dist/plugins/checkpoint-store-sql.js +39 -26
  151. package/dist/plugins/k8s-bg-scripts.d.ts +11 -0
  152. package/dist/plugins/k8s-bg-scripts.js +22 -0
  153. package/dist/plugins/local-checkpoint-store.js +5 -2
  154. package/dist/plugins/local-session-store.js +1 -1
  155. package/dist/plugins/one-time-migrations.d.ts +137 -90
  156. package/dist/plugins/one-time-migrations.js +356 -207
  157. package/dist/plugins/permission-rule-store-sql.d.ts +13 -7
  158. package/dist/plugins/permission-rule-store-sql.js +4 -18
  159. package/dist/plugins/pg-session-storage.d.ts +4 -5
  160. package/dist/plugins/pg-session-storage.js +7 -17
  161. package/dist/plugins/remote-env-adb.d.ts +6 -0
  162. package/dist/plugins/remote-env-adb.js +9 -4
  163. package/dist/plugins/remote-env-device.js +3 -0
  164. package/dist/plugins/remote-env-e2b.d.ts +1 -1
  165. package/dist/plugins/remote-env-e2b.js +21 -9
  166. package/dist/plugins/remote-env-host.d.ts +9 -9
  167. package/dist/plugins/remote-env-host.js +10 -32
  168. package/dist/plugins/remote-env-k8s.d.ts +95 -26
  169. package/dist/plugins/remote-env-k8s.js +265 -90
  170. package/dist/plugins/remote-env-local-docker.d.ts +20 -1
  171. package/dist/plugins/remote-env-local-docker.js +77 -9
  172. package/dist/plugins/remote-env-ssh.d.ts +15 -0
  173. package/dist/plugins/remote-env-ssh.js +109 -3
  174. package/dist/plugins/remote-shell.d.ts +0 -1
  175. package/dist/plugins/remote-shell.js +1 -2
  176. package/dist/plugins/retention-store-sql.js +6 -2
  177. package/dist/plugins/schema-consistency.d.ts +54 -0
  178. package/dist/plugins/schema-consistency.js +52 -0
  179. package/dist/plugins/session-epoch-anchor.d.ts +13 -0
  180. package/dist/plugins/session-epoch-anchor.js +23 -0
  181. package/dist/plugins/shared-memory-store-sql.d.ts +9 -3
  182. package/dist/plugins/shared-memory-store-sql.js +5 -16
  183. package/dist/plugins/sql-driver.d.ts +141 -0
  184. package/dist/plugins/sql-driver.js +115 -1
  185. package/dist/plugins/sql-errors.d.ts +41 -0
  186. package/dist/plugins/sql-errors.js +36 -0
  187. package/dist/plugins/store-backend.js +2 -1
  188. package/dist/plugins/tidb-session-storage.d.ts +7 -11
  189. package/dist/plugins/tidb-session-storage.js +6 -16
  190. package/dist/plugins/tidb-session-store.js +1 -1
  191. package/dist/prompts-domain-validate.d.ts +17 -61
  192. package/dist/prompts-domain-validate.js +9 -119
  193. package/dist/request-key-closure.d.ts +2 -2
  194. package/dist/request-key-closure.js +2 -4
  195. package/dist/rule-entry-list.d.ts +12 -9
  196. package/dist/rule-entry-list.js +37 -21
  197. package/dist/run-local.js +19 -19
  198. package/dist/runs.d.ts +6 -0
  199. package/dist/runs.js +16 -0
  200. package/dist/server-secret-env.d.ts +44 -18
  201. package/dist/server-secret-env.js +49 -8
  202. package/dist/session-incarnation.d.ts +15 -5
  203. package/dist/session-incarnation.js +16 -9
  204. package/dist/session-titler.js +12 -2
  205. package/dist/spec-fields.d.ts +28 -16
  206. package/dist/spec-fields.js +46 -53
  207. package/dist/sql-engine-posture.d.ts +29 -4
  208. package/dist/sql-engine-posture.js +36 -1
  209. package/dist/stored-request-tool-axes-m19.d.ts +19 -4
  210. package/dist/stored-request-tool-axes-m19.js +30 -2
  211. package/dist/task-a2a.d.ts +9 -1
  212. package/dist/task-a2a.js +73 -47
  213. package/dist/task-mcp.d.ts +46 -58
  214. package/dist/task-mcp.js +99 -65
  215. package/dist/task-settings.d.ts +7 -21
  216. package/dist/task-settings.js +7 -36
  217. package/dist/text-bidi.d.ts +3 -46
  218. package/dist/text-bidi.js +3 -3
  219. package/dist/tool-approval.d.ts +1 -1
  220. package/dist/trace/core-keyset-guard.d.ts +24 -4
  221. package/dist/trace/engine-notice-wire.d.ts +11 -3
  222. package/dist/trace/engine-notice-wire.js +8 -1
  223. package/dist/trace/ledger-events.d.ts +3 -1
  224. package/dist/trace/ledger-sink.js +4 -1
  225. package/dist/trace/model-segment.js +1 -1
  226. package/dist/trace/project.d.ts +19 -6
  227. package/dist/trace/project.js +57 -22
  228. package/dist/trace/wire-projection-faces.d.ts +79 -1
  229. package/dist/trace/wire-projection-faces.js +22 -0
  230. package/dist/web-admin-client/candidate-gate.d.ts +6 -6
  231. package/dist/web-admin-client/candidate-gate.js +3 -3
  232. package/dist/web-admin-client/http-client.js +0 -6
  233. package/dist/web-admin-client/read-warnings.d.ts +13 -0
  234. package/dist/web-admin-client/read-warnings.js +10 -0
  235. package/dist/web-admin-client/skills-mcp.d.ts +3 -0
  236. package/dist/web-admin-client/skills-mcp.js +9 -6
  237. package/dist/web-admin-client/types.d.ts +2 -3
  238. package/dist/workspace-cache.d.ts +35 -0
  239. package/dist/workspace-cache.js +36 -0
  240. package/dist/workspace-space.d.ts +3 -2
  241. package/dist/workspace-space.js +2 -0
  242. package/docs/DEVICE-EXECUTOR-PROTOCOL.md +8 -1
  243. package/package.json +4 -4
  244. package/scripts/drain-check-local.mjs +34 -1
  245. package/scripts/drain-check.mysql.sql +30 -2
  246. package/scripts/drain-check.pg.sql +29 -2
  247. package/dist/capabilities/memory-notice.d.ts +0 -138
  248. package/dist/capabilities/memory-notice.js +0 -64
  249. package/dist/capabilities/prompt.d.ts +0 -17
  250. package/dist/capabilities/prompt.js +0 -6
  251. package/dist/mcp-content-origin.d.ts +0 -34
  252. package/dist/mcp-content-origin.js +0 -10
  253. package/dist/tool-axis-words.d.ts +0 -27
  254. package/dist/tool-axis-words.js +0 -9
  255. package/dist/wire-name-bound.d.ts +0 -14
  256. package/dist/wire-name-bound.js +0 -13
@@ -0,0 +1,27 @@
1
+ export const CLASSIC_STATION_ROLE = {
2
+ "classic.PreToolUse": "chain",
3
+ "classic.PostToolUse": "chain",
4
+ "classic.PostToolUseFailure": "chain",
5
+ "classic.PostToolBatch": "chain",
6
+ "classic.UserPromptSubmit": "chain",
7
+ "classic.Stop": "chain",
8
+ "classic.SubagentStop": "chain",
9
+ "classic.StopFailure": "observe",
10
+ "classic.PreCompact": "chain",
11
+ "classic.PostCompact": "observe",
12
+ "classic.PermissionDenied": "observe",
13
+ };
14
+ export function hangClassic(on, station, answer) {
15
+ if (CLASSIC_STATION_ROLE[station] === "observe") {
16
+ observeClassic(on, station, async (e) => void (await answer(e)));
17
+ return;
18
+ }
19
+ on(station, async (_$, e, next) => (await answer(e)) ?? next(e));
20
+ }
21
+ export function observeClassic(on, station, watch) {
22
+ on(station, async (_$, e) => {
23
+ await watch(e);
24
+ return undefined;
25
+ }, { observe: true });
26
+ }
27
+ //# sourceMappingURL=classic-stations.js.map
@@ -1,6 +1,6 @@
1
1
  import type { ModelKeyRef } from "../key-resolver.js";
2
2
  import type { ServiceConfig } from "../config-types.js";
3
- import type { HookLlmCall } from "./hook-runner.js";
3
+ import type { HookLlmCall, HookLlmFailureCode } from "./hook-runner.js";
4
4
  /**
5
5
  * hookLlm(prompt 条目/session titler 的模型载体)= 直连一次非流式 completion,从 main.ts 抽出成可注入
6
6
  * 单元(fetchImpl/keyResolver 可假),因为这条 wire 在每个默认部署上都活(titler),必须可单测。
@@ -16,13 +16,13 @@ import type { HookLlmCall } from "./hook-runner.js";
16
16
  *
17
17
  * 🔴 **选线 = 引擎主路由同一只判词**(S-1630):「这只模型走 openai-completions 还是 anthropic-messages」不是本面的事,
18
18
  * 是引擎主路由的事 —— `brain.ts` 按 `model.provider` 在「anthropic 路由(仅当 ANTHROPIC 凭据把它装上)/ 网关栈」之间选,
19
- * 路由没装时整台机器只有网关这一只 brain,**连 `provider:"anthropic"` 的模型也落网关**(`dispatchBrainLane` 的合取,
19
+ * 路由没装时整台机器只有网关这一只 brain,**连 `provider:"anthropic"` 的模型也落网关**(判词 `brainLaneFor` = 引擎 `brainLaneOf` 对装上的路由表的答案,
20
20
  * 端点判官 / 降级腿 / 启动摘要读的是同一只)。本面此前自己按 `provider === "anthropic"` / `api === "anthropic-messages"`
21
21
  * 字面判线 ⇒ 在 `MODEL_PROVIDER=anthropic` 而只配了网关的部署上,主请求去网关、标题与 hooks 的 llm 面却要找一条没装的
22
22
  * anthropic 路由,整条拒发(零请求,只落 fail-open 标签)。现在本面只问那一只判词,不留第二个读法 —— 含 `api` 词:
23
23
  * 引擎不按 `api` 选线(core 的 `createRoutingBrain` 缺省按 `provider` 键),settings-schema 的 `ModelEntry` 又强制两个词同真同假。
24
- * (core 目前只导出 `createRoutingBrain` 这个组合子,没有「给定模型与已装路由 → 哪条腿 / 哪个根」的判官;它导出之日,
25
- * `dispatchBrainLane` 连同本调用点一并改为问它。)
24
+ * (S-1630 的 (a) 路已兑现:core 7.53.0 #1842 根导出了那只判官 `brainLaneOf(model, routes)` —— `createRoutingBrain` 对每个请求问的就是它;
25
+ * 本仓自写的合取 `dispatchBrainLane` 随之退役,本调用点与另三处一并改问它。)
26
26
  */
27
27
  export type HookModelPick = {
28
28
  ok: true;
@@ -30,9 +30,12 @@ export type HookModelPick = {
30
30
  providerModelId: string;
31
31
  baseUrl: string;
32
32
  api: "openai-completions" | "anthropic-messages";
33
- } | {
33
+ }
34
+ /** 选不出来的那一臂自带失败码(S-1635):两个载体(prompt 直连 / agent 子代理)共用这一只选模闸,同一只判词同一个码。 */
35
+ | {
34
36
  ok: false;
35
37
  error: string;
38
+ code: Extract<HookLlmFailureCode, "model_unresolved">;
36
39
  };
37
40
  /**
38
41
  * 🔴 **hook 失败展示文本的唯一铸点**(S-494;`build*` = 返回纯数据的一只纯函数)。
@@ -1,10 +1,11 @@
1
- import { adjudicateModelRoute, joinRequestUrl, resolveRouteCredential, routeKeyOf, routeRefusalText } from "@sema-agent/core";
1
+ import { admitRouteRequest, BrainError, joinRequestUrl, resolveRouteCredential, routeKeyOf } from "@sema-agent/core";
2
2
  import { matchCatalogModel, refusedCatalogEntry, servedModelTableLeg } from "../model-select.js";
3
3
  import { modelUnavailableMessage } from "../model-entry-refusal.js";
4
4
  import { resolveOpenaiRouteEndpoint } from "../model-route-endpoint.js";
5
- import { dispatchBrainLane } from "../model-provider.js";
5
+ import { anthropicRouteRoot, brainLaneFor, routeTableOf } from "../model-provider.js";
6
6
  import { egressRedirectRefusal } from "../egress-redirect.js";
7
7
  import { buildDisplaySafeRefusal, redactSecrets } from "../trace/redact.js";
8
+ const unresolvedPick = (error) => ({ ok: false, error, code: "model_unresolved" });
8
9
  export function buildHookFailureText(raw) {
9
10
  if (raw === "")
10
11
  return raw;
@@ -15,68 +16,86 @@ export function buildHookFailureText(raw) {
15
16
  return `[hook failure text withheld: redactor threw ${err instanceof Error ? err.name : typeof err}]`;
16
17
  }
17
18
  }
19
+ const ROUTE_REFUSAL_CODES = {
20
+ "route.credential_mismatch": true,
21
+ "route.credential_missing": true,
22
+ "route.credential_origin_mismatch": true,
23
+ "route.credential_answer_conflict": true,
24
+ };
25
+ const ROUTE_REFUSAL_LEAD = "[invalid_request] ";
26
+ function gateRefusal(pick, e, declaredRoot) {
27
+ const raw = e instanceof Error ? e.message : String(e);
28
+ const text = e instanceof BrainError && raw.startsWith(ROUTE_REFUSAL_LEAD) ? raw.slice(ROUTE_REFUSAL_LEAD.length) : raw;
29
+ const code = Object.keys(ROUTE_REFUSAL_CODES).find((c) => text.startsWith(`${c}:`)) ?? "unclassified";
30
+ return {
31
+ ok: false,
32
+ code: "route_refused",
33
+ error: `hook model "${pick.catalogRef}" cannot be routed (${code}) — ` + buildDisplaySafeRefusal(text, [pick.baseUrl, declaredRoot ?? ""]),
34
+ };
35
+ }
18
36
  export function createHookLlm(deps) {
19
37
  const { config, metrics } = deps;
20
- const anthropicRouteBaseUrl = () => config.anthropic?.baseUrl || "https://api.anthropic.com";
21
- const shapeFrom = (catalogRef, m, providerModelId) => {
22
- const lane = dispatchBrainLane(m?.provider, config.anthropic !== undefined);
38
+ const anthropicRouteBaseUrl = () => anthropicRouteRoot(config.anthropic ?? {});
39
+ const shapeFrom = (m, providerModelId = m.id) => {
40
+ const catalogRef = m.name;
41
+ const lane = brainLaneFor(m.provider, routeTableOf(config));
23
42
  switch (lane) {
24
43
  case "anthropic":
25
- return { ok: true, catalogRef, providerModelId, baseUrl: m?.baseUrl || anthropicRouteBaseUrl(), api: "anthropic-messages" };
44
+ return { ok: true, catalogRef, providerModelId, baseUrl: m.baseUrl || anthropicRouteBaseUrl(), api: "anthropic-messages" };
26
45
  case "gateway": {
27
46
  const endpoint = resolveOpenaiRouteEndpoint(catalogRef, m, config.gatewayBaseUrl, servedModelTableLeg(config));
28
- return endpoint.ok ? { ok: true, catalogRef, providerModelId, baseUrl: endpoint.baseUrl, api: "openai-completions" } : { ok: false, error: endpoint.refusal };
47
+ return endpoint.ok ? { ok: true, catalogRef, providerModelId, baseUrl: endpoint.baseUrl, api: "openai-completions" } : unresolvedPick(endpoint.refusal);
29
48
  }
30
49
  }
31
50
  };
32
51
  const hookModelFor = (requested) => {
33
- const shape = (ref) => shapeFrom(ref, config.models[ref], config.models[ref]?.id ?? ref);
52
+ const ownEntry = (ref) => (Object.hasOwn(config.models, ref) ? config.models[ref] : undefined);
34
53
  const unavailable = (field, ref) => {
35
- if (config.models[ref] !== undefined)
54
+ if (ownEntry(ref) !== undefined)
36
55
  return undefined;
37
56
  const hit = refusedCatalogEntry(ref, config.modelRefusals);
38
- return hit === undefined ? undefined : { ok: false, error: modelUnavailableMessage(field, ref, hit.name, hit.refusal) };
57
+ return hit === undefined ? undefined : unresolvedPick(modelUnavailableMessage(field, ref, hit.name, hit.refusal));
39
58
  };
40
59
  if (requested === undefined) {
41
60
  const sum = config.roles.summarize;
42
61
  const roleModel = typeof sum === "string" ? sum : sum && typeof sum === "object" && "model" in sum && typeof sum.model === "string" ? sum.model : undefined;
43
- if (roleModel !== undefined)
44
- return unavailable("summarize role model", roleModel) ?? (config.models[roleModel] ? shape(roleModel) : shapeFrom(config.model.id, config.model, roleModel));
45
- return shapeFrom(config.model.id, config.model, config.model.id);
62
+ if (roleModel !== undefined) {
63
+ const entry = ownEntry(roleModel);
64
+ return unavailable("summarize role model", roleModel) ?? (entry ? shapeFrom(entry) : shapeFrom(config.model, roleModel));
65
+ }
66
+ return shapeFrom(config.model);
46
67
  }
47
- if (config.models[requested])
48
- return shape(requested);
68
+ const matchedKey = matchCatalogModel(requested, config.models, config.modelRefusals);
69
+ if (matchedKey !== undefined)
70
+ return shapeFrom(config.models[matchedKey]);
49
71
  if (Object.hasOwn(config.modelRefusals ?? {}, requested))
50
72
  return unavailable("hook model", requested);
51
- const byId = matchCatalogModel(requested, config.models, config.modelRefusals);
52
- if (byId !== undefined)
53
- return shape(byId);
54
73
  if (requested === config.model.id)
55
- return shapeFrom(requested, config.model, requested);
56
- return unavailable("hook model", requested) ?? { ok: false, error: `hook model "${requested}" is not in this deployment's catalog` };
74
+ return shapeFrom(config.model);
75
+ return unavailable("hook model", requested) ?? unresolvedPick(`hook model "${requested}" is not in this deployment's catalog`);
57
76
  };
58
77
  const judgeRoute = (pick, perModelKey, deploymentKey, declaredRoot) => {
59
78
  const credential = resolveRouteCredential({
60
79
  ...(perModelKey !== undefined ? { optionsApiKey: perModelKey } : {}),
61
80
  ...(deploymentKey !== undefined ? { configApiKey: deploymentKey } : {}),
62
81
  });
63
- const verdict = adjudicateModelRoute({ id: pick.catalogRef, baseUrl: pick.baseUrl }, credential, { ...(declaredRoot !== undefined ? { baseUrl: declaredRoot } : {}) });
64
- if (!verdict.ok) {
65
- return {
66
- ok: false,
67
- error: `hook model "${pick.catalogRef}" cannot be routed (${verdict.code}) — ` +
68
- buildDisplaySafeRefusal(routeRefusalText(verdict), [pick.baseUrl, declaredRoot ?? ""]),
69
- };
82
+ let admission;
83
+ try {
84
+ admission = admitRouteRequest({ id: pick.catalogRef, baseUrl: pick.baseUrl }, credential, { ...(declaredRoot !== undefined ? { baseUrl: declaredRoot } : {}) });
70
85
  }
71
- if (verdict.posture === "keyless" && routeKeyOf(pick.baseUrl) !== routeKeyOf(declaredRoot)) {
86
+ catch (e) {
87
+ return gateRefusal(pick, e, declaredRoot);
88
+ }
89
+ if (credential.source === "absent" && routeKeyOf(pick.baseUrl) !== routeKeyOf(declaredRoot)) {
72
90
  return {
73
91
  ok: false,
92
+ code: "route_refused",
74
93
  error: `hook model "${pick.catalogRef}" points at ${pick.baseUrl}, which this deployment did not declare as its own endpoint, ` +
75
94
  `and no per-model credential resolved — refusing to send the prompt there (it embeds user content; an unauthenticated ` +
76
95
  `request still hands that content to whoever operates that URL)`,
77
96
  };
78
97
  }
79
- return { ok: true, credential };
98
+ return { ok: true, credential, admission };
80
99
  };
81
100
  const fetchImpl = deps.fetchImpl ?? fetch;
82
101
  const callLlm = async ({ prompt, model, timeoutMs, system, maxOutputTokens }) => {
@@ -85,6 +104,7 @@ export function createHookLlm(deps) {
85
104
  return pick;
86
105
  const ac = new AbortController();
87
106
  const t = setTimeout(() => ac.abort(), timeoutMs);
107
+ let phase = "assemble";
88
108
  try {
89
109
  const keyResolver = deps.getKeyResolver();
90
110
  let perModelKey;
@@ -93,17 +113,21 @@ export function createHookLlm(deps) {
93
113
  perModelKey = (await keyResolver({ name: pick.catalogRef }))?.apiKey;
94
114
  }
95
115
  catch (e) {
96
- return { ok: false, error: `per-model key resolution for "${pick.catalogRef}" failed — refusing to fall back to the shared route credential (${String(e)})` };
116
+ return { ok: false, error: `per-model key resolution for "${pick.catalogRef}" failed — refusing to fall back to the shared route credential (${String(e)})`, code: "credential_custody_failed" };
97
117
  }
98
118
  }
99
119
  let url;
100
120
  let headers;
101
121
  let body;
122
+ let admitted;
123
+ let declaredRoot;
102
124
  if (pick.api === "anthropic-messages") {
103
125
  const routeBase = anthropicRouteBaseUrl();
126
+ declaredRoot = routeBase;
104
127
  const routed = judgeRoute(pick, perModelKey, config.anthropic?.authToken ?? config.anthropic?.apiKey, routeBase);
105
128
  if (!routed.ok)
106
129
  return routed;
130
+ admitted = routed.admission;
107
131
  url = joinRequestUrl(pick.baseUrl, "/v1/messages");
108
132
  headers = {
109
133
  "content-type": "application/json",
@@ -121,29 +145,47 @@ export function createHookLlm(deps) {
121
145
  body = JSON.stringify({ model: pick.providerModelId, max_tokens: maxTokens, ...(system ? { system } : {}), messages: [{ role: "user", content: prompt }] });
122
146
  }
123
147
  else {
148
+ declaredRoot = config.gatewayBaseUrl;
124
149
  const routed = judgeRoute(pick, perModelKey, config.gatewayApiKey, config.gatewayBaseUrl);
125
150
  if (!routed.ok)
126
151
  return routed;
152
+ admitted = routed.admission;
127
153
  const hookKey = routed.credential.apiKey;
128
154
  url = joinRequestUrl(pick.baseUrl, "/chat/completions");
129
155
  headers = { "content-type": "application/json", ...(hookKey ? { authorization: `Bearer ${hookKey}` } : {}) };
130
156
  body = JSON.stringify({ model: pick.providerModelId, ...(maxOutputTokens !== undefined ? { max_tokens: maxOutputTokens } : {}), messages: [...(system ? [{ role: "system", content: system }] : []), { role: "user", content: prompt }], stream: false });
131
157
  }
158
+ try {
159
+ admitted();
160
+ }
161
+ catch (e) {
162
+ return gateRefusal(pick, e, declaredRoot);
163
+ }
164
+ phase = "transport";
132
165
  const r = await fetchImpl(url, { method: "POST", headers, body, signal: ac.signal, redirect: "manual" });
133
166
  const redirected = egressRedirectRefusal(r, "declare the final endpoint as this route's base URL");
134
167
  if (redirected !== undefined)
135
168
  return { ok: false, error: `hook llm ${redirected}`, code: "redirect_refused" };
136
169
  if (!r.ok)
137
- return { ok: false, error: `hook llm HTTP ${r.status}` };
170
+ return { ok: false, error: `hook llm HTTP ${r.status}`, code: "bad_response" };
171
+ let answered;
172
+ try {
173
+ answered = await r.json();
174
+ }
175
+ catch (e) {
176
+ if (ac.signal.aborted || e?.name !== "SyntaxError")
177
+ throw e;
178
+ return { ok: false, error: "hook llm answered with a body that is not JSON", code: "bad_response" };
179
+ }
138
180
  let text;
139
181
  if (pick.api === "anthropic-messages") {
140
- const j = (await r.json());
141
- const parts = (Array.isArray(j.content) ? j.content : []).filter((b) => b?.type === "text" && typeof b.text === "string").map((b) => b.text);
182
+ const j = answered;
183
+ const parts = (Array.isArray(j?.content) ? j.content : []).filter((b) => b?.type === "text" && typeof b.text === "string").map((b) => b.text);
142
184
  text = parts.length > 0 ? parts.join("") : undefined;
143
185
  }
144
186
  else {
145
- const j = (await r.json());
146
- text = j.choices?.[0]?.message?.content ?? undefined;
187
+ const j = answered;
188
+ text = j?.choices?.[0]?.message?.content ?? undefined;
147
189
  }
148
190
  metrics.inc("hook_llm_calls_total", { type: "prompt" });
149
191
  return typeof text === "string" ? { ok: true, text } : { ok: false, error: "hook llm returned no content", code: "no_content" };
@@ -153,6 +195,7 @@ export function createHookLlm(deps) {
153
195
  return {
154
196
  ok: false,
155
197
  error: ac.signal.aborted ? "hook llm timeout" : `hook llm request to ${pick.baseUrl} failed: ${String(e)}${cause ? ` (${String(cause)})` : ""}`,
198
+ code: ac.signal.aborted || phase === "transport" ? "unreachable" : "route_refused",
156
199
  };
157
200
  }
158
201
  finally {