@botlearn-course/daemon 0.0.31 → 0.0.32-beta.2

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.
package/README.md CHANGED
@@ -61,6 +61,10 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
61
61
  未提供对应二进制路径时跳过该项。2026-09-08 的进程内系统指令刷新门禁在 `0.8.39`
62
62
  和 `0.9.12` 均失败,详见[历史实测报告](../../docs/qa/2026-09-08-pi-runtime-and-deepseek-upgrade.md)。
63
63
  该结果不能作为新版升级验收通过的证据。
64
+ 2026-11-25 在本机 macOS arm64 复测:`0.9.12` 与 `0.10.4` 的兼容性、系统提示词刷新两项均通过,
65
+ `0.10.4` 恢复 `0.9.12` 创建的会话也通过。反向不兼容:`0.9.12` 启动时读到 `0.10.4` 写过的
66
+ 运行目录会直接退出(`Turn schema v6 is newer than supported v2`),回退版本前需先确定运行目录处理方案。冷线程预热(见下文)需要先 PATCH 再加载,
67
+ 否则 `0.9.12` 会沿用旧系统提示词。
64
68
 
65
69
  ## 环境变量
66
70
 
@@ -137,25 +141,71 @@ major、minor 或 prerelease 时才填写精确 SemVer(例如 `1.0.0` 或 `1.1
137
141
 
138
142
  ## 托管 Codewhale 代理凭据
139
143
 
140
- `deepseek-tui` 流式事件解析同时支持 0.8.39 和 0.9.12,以及既有平铺事件格式。
141
- 0.9.12 的外层 `kind` 表示事件名;推理类型从内层 `payload.kind` 或
144
+ `deepseek-tui` 流式事件解析同时支持 0.8.39、0.9.12 和 0.10.4,以及既有平铺事件格式。
145
+ 0.9.x 起外层 `kind` 表示事件名;推理类型从内层 `payload.kind` 或
142
146
  `payload.item.kind` 读取。推理增量持续推送并按段保存,完成摘要不重复追加正文。
143
147
 
144
148
  托管启动前为 DeepSeek 0.8 的 `.deepseek` 与 Codewhale 0.9 的 `.codewhale`
145
149
  准备状态目录。目录通过 `1770` 权限允许运行组创建任务状态;临时配置根目录保持
146
150
  `0750`,配置文件保持 `0640`。重复初始化保留已有状态,不改写课程进度或工作区文件。
147
151
 
148
- 托管 `deepseek-tui` 每轮从 activation 的 `DEEPSEEK_BASE_URL` 生成临时
149
- `[providers.deepseek]` 路由,并用 `api_key_env = "DEEPSEEK_API_KEY"` 显式绑定当轮凭据。
150
- 子进程不再接收 URL 环境覆盖,避免 Codewhale 0.9.12 将其判定为未绑定的新路由。
151
- 未启用视觉模型时同样生成该配置;配置随本轮进程清理,凭据不会写入供应商路由或命令行。
152
+ activation 下发的模型代理授权只留在 daemon 内存。`AgentServiceSandbox` 持有本机凭据中继
153
+ (`src/model-credential-relay.ts`,只监听 `127.0.0.1`)。托管 `deepseek-tui` 拿到的
154
+ `DEEPSEEK_BASE_URL` 是中继地址,`DEEPSEEK_API_KEY` 是绑定当前 RuntimeSession 的随机本地令牌。
155
+ 适配器据此生成 `[providers.deepseek]` 路由,用 `api_key_env = "DEEPSEEK_API_KEY"` 绑定本地令牌;
156
+ 视觉模型的 `api_key` 与 `base_url` 同样指向本地令牌和中继 `/v1`。授权因此不出现在 serve 环境、
157
+ `config.toml`、命令行或日志中。子进程不接收 URL 环境覆盖,避免 Codewhale 0.9.12 将其判定为
158
+ 未绑定的新路由。
159
+
160
+ 中继只放行 `POST /v1/chat/completions` 和 `GET /v1/models`(与 Agent Service 模型代理白名单一致),
161
+ 其他请求或畸形请求行返回 400;本地令牌不符返回 401;该会话没有当前 activation 时返回 503,且不转发。
162
+ 请求体上限为代码常量 `MODEL_RELAY_MAX_REQUEST_BYTES`(64 MiB),等于 Agent Service
163
+ `AGENT_SERVICE_MODEL_PROXY_MAX_REQUEST_BYTES` 允许的最大值(默认 16 MiB 由 Agent Service 执行),
164
+ 所以中继不会拒绝代理可能接受的请求。`Content-Length` 超限和流式实际字节超限都返回 413。
165
+ 有当前 activation 时,中继把本地令牌换成该 activation 的授权并流式转发。activation 清理、
166
+ 换会话、关闭会话、换代和 daemon 停止时撤销授权并中断在途上游请求;会话释放后旧令牌返回 401。
167
+ 同一运行用户的学员命令在 activation 期间仍可经本地令牌调用模型,范围限于当次授权。
152
168
  托管进程固定关闭 Codewhale 自带遥测,BotLearn 原有执行事实记录继续使用既有通道。
169
+ 托管进程固定 `CODEWHALE_STREAM_OPEN_TIMEOUT_SECS=45`。0.10 默认等待模型响应头 180 秒并重发一次,
170
+ 固定后失败上界与 0.9.12 相同(45 秒、一次重试);0.8.39 忽略该变量。
153
171
  这些规则由适配器代码拥有,更新 daemon 后生效,无需新增部署配置或数据库迁移。
154
172
 
173
+ 托管服务进程的寿命归 RuntimeSession,规则见
174
+ [daemon WebSocket 规范 §9.2](../../docs/specs/agent-service-sandbox-daemon-websocket.md#92-帧类型)。
175
+ 实现上:进程键为 RuntimeSession 与代次、二进制路径与版本、`config.toml` 内容、运行目录和本地令牌
176
+ 摘要;0.9.12 等未验证 PATCH 刷新提示的版本另加系统提示摘要。AgentRun 结束不停止进程,托管进程
177
+ 也不用 daemon 空闲计时;本地 BYOA 进程保留 5 分钟空闲回收。课程技能工具处理和技能事件回调每轮新建,
178
+ stderr 尾部每轮清空。0.9.12 与 0.10.4 的 serve 令牌经 `CODEWHALE_RUNTIME_TOKEN` 传入,不放在命令行。
179
+
180
+ 替换或释放进程前,适配器确认旧进程退出:直接子进程已退出且进程组为空。超过 15 秒预算的一半仍未退出时,
181
+ 本地进程发 `SIGKILL`,托管进程调用启动器 cgroup quiesce。预算用尽不启动新进程,本轮以
182
+ `runtime_previous_process_not_released` 失败,旧句柄保留到下次再查。`AgentServiceSandbox` 在换会话、
183
+ 关闭会话、drain、停止和换代时调用 `releaseDeepseekRuntime`。
184
+
185
+ 已有线程在当前进程中首次使用,或线程设置(系统提示、模型)变化后,适配器先 PATCH 线程设置,再调用
186
+ `POST /v1/threads/{id}/resume` 加载历史,然后才执行压缩或提交本轮。加载受本轮超时信号和
187
+ 120 秒上限约束;返回 404/410 时沿用缺失线程回退。压缩与提交仍使用 5 秒窗口取得 turn id,
188
+ 超时报错写明“可能已被接受”,不自动重发。日志 `deepseek-tui.thread-prewarm` 记录线程 ID、
189
+ 结果、耗时和是否新进程,不含提示词或文件内容。0.10 在设置变化时重建已加载引擎,
190
+ 所以设置变化后重新预热。0.9.12 在本机 700 轮线程上加载约 9 秒,
191
+ 未预热时提交超过 5 秒;0.10.4 同一线程加载约 0.05 秒。
192
+
155
193
  镜像内的真实二进制回归入口是 `scripts/smoke-codewhale-managed.mjs`:构建 daemon 后,
156
194
  以 `0:2000` 运行并挂载整个包目录,添加 `--network none` 和
157
- `--add-host model-proxy.test:127.0.0.1`。验证非 localhost 代理、凭据轮换、UID 1001
158
- 文件写入、会话恢复和第二轮系统提示词更新;模型使用本地确定性替身。
195
+ `--add-host model-proxy.test:127.0.0.1`。验证同一会话两轮共用一个服务进程、经中继访问非 localhost
196
+ 代理与授权轮换、UID 1001 文件写入、会话恢复、第二轮系统提示词更新和会话释放后清理;模型使用本地确定性替身。
197
+ 0.10.4 两轮共用一个进程;0.9.x 因提示变化替换进程,脚本断言旧进程已退出、旧 profile 已清理。
198
+ 包目录只读挂载到 `/work/pkg`,`/work` 用容器内 tmpfs:macOS 宿主机挂载目录不支持 Codewhale 的私有 socket。
199
+
200
+ 本机真实二进制门控测试(未设置变量时跳过,跳过不算通过):
201
+
202
+ ```bash
203
+ BOTLEARN_TEST_DEEPSEEK_BIN=/absolute/path/to/codewhale \
204
+ pnpm exec vitest run src/runtimes/__tests__/process-reuse-binaries.test.ts
205
+ ```
206
+
207
+ 覆盖跨运行授权与提示隔离、空窗期零上游请求、每轮技能隔离、在途请求截断,以及卡住的旧进程
208
+ (SIGSTOP)在本地模式被 SIGKILL 后替换、在模拟托管模式下明确失败。
159
209
 
160
210
 
161
211
  ### 文件元数据批量登记
@@ -41,6 +41,8 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
41
41
  private readonly turnScopes;
42
42
  /** activation-scoped 模型短凭据;只保存在内存中,绝不进入 state.json。 */
43
43
  private readonly activationContexts;
44
+ /** 本机凭据中继:runtime 进程只拿本地令牌,短凭据只在 daemon 内存中替换注入。 */
45
+ private readonly modelRelay;
44
46
  private readonly activationCleanupTasks;
45
47
  private readonly pendingAcks;
46
48
  private readonly pendingFileReports;
@@ -119,7 +121,14 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
119
121
  private isCurrentDrainFence;
120
122
  private runIdsForSession;
121
123
  private deactivateSession;
124
+ /**
125
+ * Stops the RuntimeSession's runtime process and every writer of its activations. The
126
+ * runtime process lives across AgentRuns, so this is where it ends. False means the
127
+ * process did not confirm exit; the caller must not expose another workspace.
128
+ */
122
129
  private terminateSessionWriters;
130
+ /** Releases every runtime process before a sandbox-wide quiesce (drain, stop, generation). */
131
+ private releaseRuntimeProcesses;
123
132
  private sameTurnScope;
124
133
  private matchesTurnScope;
125
134
  private assertTurnScope;
@@ -8,6 +8,8 @@ import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFra
8
8
  import { log as defaultLog, setOperationalLogSink, } from "./log.js";
9
9
  import { availableRunCapabilities, runtimeSupportsCourseSkills, } from "./runtime-capabilities.js";
10
10
  import { activationRuntimeEnv, runtimeChildEnv } from "./runtime-env.js";
11
+ import { ModelCredentialRelay } from "./model-credential-relay.js";
12
+ import { reapPreviousDeepseekRuntime, releaseDeepseekRuntime } from "./runtimes/deepseek-tui.js";
11
13
  import { redactSecretString } from "./redaction.js";
12
14
  import { parseRuntimeSkillProviderGrantSet, prepareRuntimeSkillProvider, RuntimeSkillProviderError, } from "./runtime-skills.js";
13
15
  import { RunDispatcher, } from "./run-dispatcher.js";
@@ -253,6 +255,10 @@ function normalizeNativeSessions(value) {
253
255
  }
254
256
  return sessions;
255
257
  }
258
+ /** One RuntimeSession in one sandbox generation; the unit that owns a runtime process. */
259
+ function runtimeSessionKey(sessionId, sandboxGeneration) {
260
+ return `${sessionId}:g${sandboxGeneration}`;
261
+ }
256
262
  function nativeSessionKey(payload) {
257
263
  const key = payload.runtime.native_session_key;
258
264
  return typeof key === "string" && key ? key : COURSE_NATIVE_SESSION_KEY;
@@ -375,6 +381,8 @@ export class AgentServiceSandboxClient {
375
381
  turnScopes = new Map();
376
382
  /** activation-scoped 模型短凭据;只保存在内存中,绝不进入 state.json。 */
377
383
  activationContexts = new Map();
384
+ /** 本机凭据中继:runtime 进程只拿本地令牌,短凭据只在 daemon 内存中替换注入。 */
385
+ modelRelay;
378
386
  activationCleanupTasks = new Map();
379
387
  pendingAcks = new Map();
380
388
  pendingFileReports = new Map();
@@ -415,6 +423,7 @@ export class AgentServiceSandboxClient {
415
423
  this.prepareSkillProvider =
416
424
  options.prepareSkillProvider ?? ((raw) => prepareRuntimeSkillProvider(raw));
417
425
  this.state = loadState(options.sandboxId, options.sandboxToken);
426
+ this.modelRelay = new ModelCredentialRelay({ log: this.log });
418
427
  this.dispatcher = new RunDispatcher(this, options.runtimes, {
419
428
  persistentSession: this,
420
429
  });
@@ -446,12 +455,21 @@ export class AgentServiceSandboxClient {
446
455
  delete runtimeEnv.BOTLEARN_MODEL_API_KEY;
447
456
  delete runtimeEnv.BOTLEARN_MODEL_BASE_URL;
448
457
  Object.assign(runtimeEnv, activation.runtimeEnv);
458
+ const grant = activation.runtimeEnv.DEEPSEEK_API_KEY;
459
+ const proxyBaseUrl = activation.runtimeEnv.DEEPSEEK_BASE_URL;
460
+ if (grant && proxyBaseUrl) {
461
+ // The runtime process may outlive this activation; it only gets the local relay.
462
+ const local = this.modelRelay.activate(runtimeSessionKey(scope.sessionId, this.sandboxGeneration), scope.activationId, proxyBaseUrl, grant);
463
+ runtimeEnv.DEEPSEEK_BASE_URL = local.baseUrl;
464
+ runtimeEnv.DEEPSEEK_API_KEY = local.token;
465
+ }
449
466
  runtimeEnv.BOTLEARN_AGENT_SERVICE_ACTIVATION_ID = scope.activationId;
450
467
  validateRuntimePrompt(payload.runtime_prompt, activation.skillProvider?.catalog.map((entry) => entry.ref) ?? []);
451
468
  return {
452
469
  workspaceDir: prepared.workspaceDir,
453
470
  transcriptFile: prepared.transcriptFile,
454
471
  runtimeStateDir: prepared.rootDir,
472
+ runtimeSessionKey: runtimeSessionKey(scope.sessionId, this.sandboxGeneration),
455
473
  nativeSessionId: session.nativeSessions[this.currentTurnNativeKey] ?? null,
456
474
  contextRevision,
457
475
  runtimeEnv,
@@ -531,6 +549,7 @@ export class AgentServiceSandboxClient {
531
549
  if (activation?.activationId === pending.activationId) {
532
550
  this.activationContexts.delete(sessionId);
533
551
  }
552
+ this.modelRelay.deactivate(pending.activationId);
534
553
  if (!session.completedActivations.includes(pending.activationId)) {
535
554
  // Session-close/generation-rotate are the retention bounds. Never evict an
536
555
  // activation tombstone while the session is alive: activation IDs are opaque, so
@@ -580,6 +599,13 @@ export class AgentServiceSandboxClient {
580
599
  }
581
600
  }
582
601
  async run() {
602
+ // A previous daemon process may have died while its runtime server kept the runtime
603
+ // lock. Unconfirmed, it stays tracked and every new server start fails explicitly.
604
+ if (!await reapPreviousDeepseekRuntime()) {
605
+ this.log.error("runtime process of a previous daemon did not exit", {
606
+ sandboxId: this.options.sandboxId,
607
+ });
608
+ }
583
609
  let failures = 0;
584
610
  let authFailures = 0;
585
611
  while (!this.stopped && !this.permanentFailure) {
@@ -629,6 +655,7 @@ export class AgentServiceSandboxClient {
629
655
  revokeRuntimeSessionWorkspace(sessionId, this.sandboxGeneration, session.workspaceId ?? sessionId);
630
656
  }
631
657
  this.activationContexts.clear();
658
+ void this.modelRelay.close();
632
659
  this.activeSessionId = null;
633
660
  this.currentTurnSessionId = null;
634
661
  this.persist();
@@ -638,6 +665,7 @@ export class AgentServiceSandboxClient {
638
665
  }
639
666
  async stopGracefully() {
640
667
  this.dispatcher.cancelAll();
668
+ await this.releaseRuntimeProcesses("shutdown");
641
669
  await quiesceRuntimeWriters(null);
642
670
  await flushWorkspaceFilesystem();
643
671
  this.stop();
@@ -646,6 +674,7 @@ export class AgentServiceSandboxClient {
646
674
  if (!(await this.dispatcher.drain(10_000)) || !this.isCurrentDrainFence(fence)) {
647
675
  return;
648
676
  }
677
+ await this.releaseRuntimeProcesses("drain");
649
678
  await quiesceRuntimeWriters(null);
650
679
  await flushWorkspaceFilesystem();
651
680
  if (!this.isCurrentDrainFence(fence))
@@ -733,7 +762,15 @@ export class AgentServiceSandboxClient {
733
762
  resolve: resolveAck,
734
763
  reject: rejectAck,
735
764
  });
736
- timer = setTimeout(() => rejectAck(new RuntimeExecutionError("Agent event receipt timed out", "timeout")), EVENT_ACK_TIMEOUT_MS);
765
+ timer = setTimeout(() => {
766
+ this.log.warn("agent_event_ack_timeout", {
767
+ agent_run_id: agentRunId, runtime_session_id: scope.sessionId,
768
+ worker_attempt: scope.workerAttempt, sandbox_id: this.options.sandboxId,
769
+ sandbox_generation: frame.sandbox_generation, connection_epoch: frame.connection_epoch,
770
+ frame_id: frame.frame_id, event_type: event.type, wait_timeout_ms: EVENT_ACK_TIMEOUT_MS,
771
+ });
772
+ rejectAck(new RuntimeExecutionError("Agent event receipt timed out", "timeout"));
773
+ }, EVENT_ACK_TIMEOUT_MS);
737
774
  signal?.addEventListener("abort", abort, { once: true });
738
775
  if (signal?.aborted)
739
776
  abort();
@@ -902,6 +939,7 @@ export class AgentServiceSandboxClient {
902
939
  if (frame.sandbox_generation !== this.state.sandboxGeneration) {
903
940
  // Generation change wipes every session shard (contract §1.4).
904
941
  this.dispatcher.cancelAll();
942
+ await this.releaseRuntimeProcesses("generation_changed");
905
943
  await quiesceRuntimeWriters(null);
906
944
  this.rejectPending(new Error("Agent Service sandbox generation changed"));
907
945
  for (const [sessionId, session] of Object.entries(this.state.sessions)) {
@@ -1369,6 +1407,8 @@ export class AgentServiceSandboxClient {
1369
1407
  return;
1370
1408
  }
1371
1409
  }
1410
+ if (runtimeEnv.DEEPSEEK_API_KEY)
1411
+ await this.modelRelay.start();
1372
1412
  session.runtimeId = runtimeId;
1373
1413
  session.contextRevision = contextRevision;
1374
1414
  session.activationId = activationId;
@@ -1546,12 +1586,15 @@ export class AgentServiceSandboxClient {
1546
1586
  this.resolvePendingEventAcksForSession(sessionId);
1547
1587
  this.rejectPendingFilesForSession(sessionId, new Error("Agent Service runtime session was closed"));
1548
1588
  this.activationContexts.delete(sessionId);
1589
+ this.modelRelay.releaseSession(runtimeSessionKey(sessionId, this.sandboxGeneration));
1549
1590
  for (const runId of runIds)
1550
1591
  this.dispatcher.cancel(runId);
1551
1592
  if (!await this.dispatcher.waitForRuns(runIds, 10_000)) {
1552
1593
  throw new Error(`runtime session ${sessionId} did not stop before close`);
1553
1594
  }
1554
- await this.terminateSessionWriters(session);
1595
+ if (!await this.terminateSessionWriters(sessionId, session)) {
1596
+ throw new Error(`runtime session ${sessionId} did not release its runtime process`);
1597
+ }
1555
1598
  session.activationId = null;
1556
1599
  const workspaceId = session.workspaceId ?? sessionId;
1557
1600
  const sharedWorkspaceIsOpen = Object.entries(this.state.sessions).some(([otherSessionId, other]) => otherSessionId !== sessionId && (other.workspaceId ?? otherSessionId) === workspaceId);
@@ -1711,8 +1754,12 @@ export class AgentServiceSandboxClient {
1711
1754
  if (!session)
1712
1755
  return true;
1713
1756
  const runIds = this.runIdsForSession(sessionId);
1757
+ const activation = this.activationContexts.get(sessionId);
1714
1758
  this.activationContexts.delete(sessionId);
1759
+ if (activation)
1760
+ this.modelRelay.deactivate(activation.activationId);
1715
1761
  if (terminateWriters) {
1762
+ this.modelRelay.releaseSession(runtimeSessionKey(sessionId, this.sandboxGeneration));
1716
1763
  revokeRuntimeSessionWorkspace(sessionId, this.sandboxGeneration, session.workspaceId ?? sessionId);
1717
1764
  }
1718
1765
  if (this.activeSessionId === sessionId)
@@ -1720,15 +1767,21 @@ export class AgentServiceSandboxClient {
1720
1767
  for (const runId of runIds)
1721
1768
  this.dispatcher.cancel(runId);
1722
1769
  this.persist();
1723
- const stopped = await this.dispatcher.waitForRuns(runIds, 10_000);
1770
+ let stopped = await this.dispatcher.waitForRuns(runIds, 10_000);
1724
1771
  if (stopped && terminateWriters) {
1725
- await this.terminateSessionWriters(session);
1772
+ stopped = await this.terminateSessionWriters(sessionId, session);
1726
1773
  }
1727
1774
  session.activationId = null;
1728
1775
  this.persist();
1729
1776
  return stopped;
1730
1777
  }
1731
- async terminateSessionWriters(session) {
1778
+ /**
1779
+ * Stops the RuntimeSession's runtime process and every writer of its activations. The
1780
+ * runtime process lives across AgentRuns, so this is where it ends. False means the
1781
+ * process did not confirm exit; the caller must not expose another workspace.
1782
+ */
1783
+ async terminateSessionWriters(sessionId, session) {
1784
+ const released = await releaseDeepseekRuntime(runtimeSessionKey(sessionId, this.sandboxGeneration));
1732
1785
  const activationIds = new Set([
1733
1786
  ...session.completedActivations,
1734
1787
  ...(session.activationId ? [session.activationId] : []),
@@ -1739,6 +1792,15 @@ export class AgentServiceSandboxClient {
1739
1792
  for (const activationId of activationIds) {
1740
1793
  await quiesceRuntimeWriters(activationId);
1741
1794
  }
1795
+ return released;
1796
+ }
1797
+ /** Releases every runtime process before a sandbox-wide quiesce (drain, stop, generation). */
1798
+ async releaseRuntimeProcesses(reason) {
1799
+ this.modelRelay.releaseSession(null);
1800
+ if (!await releaseDeepseekRuntime(null)) {
1801
+ // The following sandbox-wide quiesce force-stops it; the next spawn checks again.
1802
+ this.log.warn("runtime process did not confirm exit before quiesce", { reason });
1803
+ }
1742
1804
  }
1743
1805
  sameTurnScope(left, right) {
1744
1806
  return left.sessionId === right.sessionId &&
@@ -0,0 +1,54 @@
1
+ import { type Logger } from "./log.js";
2
+ /**
3
+ * Loopback model credential relay owned by the sandbox daemon.
4
+ *
5
+ * A runtime process receives only this relay's address and a random local token bound to
6
+ * one RuntimeSession. While that session has a current activation, the relay replaces the
7
+ * local token with the activation's short-lived model proxy grant and forwards the request.
8
+ * Without a current activation it answers 503 and forwards nothing. Deactivation aborts
9
+ * in-flight upstream requests. The grant never enters the runtime environment, config files,
10
+ * command line or logs, so a runtime process can outlive one AgentRun.
11
+ */
12
+ /**
13
+ * Request body cap. Agent Service enforces its configured model proxy limit
14
+ * (`AGENT_SERVICE_MODEL_PROXY_MAX_REQUEST_BYTES`, default 16 MiB); this is that setting's
15
+ * maximum (64 MiB), so the relay never rejects what the proxy may accept and still bounds
16
+ * what a runtime can push through the daemon.
17
+ */
18
+ export declare const MODEL_RELAY_MAX_REQUEST_BYTES: number;
19
+ export interface ModelRelayEndpoint {
20
+ /** Provider base URL for the runtime; requests go to `${baseUrl}/v1/...`. */
21
+ baseUrl: string;
22
+ /** Local token for this RuntimeSession; it is not a model credential. */
23
+ token: string;
24
+ }
25
+ export interface ModelCredentialRelayOptions {
26
+ fetchFn?: typeof fetch;
27
+ log?: Logger;
28
+ /** 测试注入:请求体上限;缺省为 MODEL_RELAY_MAX_REQUEST_BYTES。 */
29
+ maxRequestBytes?: number;
30
+ }
31
+ export declare class ModelCredentialRelay {
32
+ private readonly fetchFn;
33
+ private readonly log;
34
+ private readonly maxRequestBytes;
35
+ private readonly sessions;
36
+ private server;
37
+ private starting;
38
+ private port;
39
+ constructor(options?: ModelCredentialRelayOptions);
40
+ /** Starts listening on 127.0.0.1 with an ephemeral port. Idempotent. */
41
+ start(): Promise<void>;
42
+ /**
43
+ * Makes `grant` the credential for `sessionKey` until `deactivate`. A previous
44
+ * activation of the same session is aborted first. Returns the session's local endpoint.
45
+ */
46
+ activate(sessionKey: string, activationId: string, upstreamBaseUrl: string, grant: string): ModelRelayEndpoint;
47
+ /** Stops using `activationId`; new requests get 503 and in-flight requests are cut. */
48
+ deactivate(activationId: string): void;
49
+ /** Revokes the local token of one RuntimeSession, or of all sessions when null. */
50
+ releaseSession(sessionKey: string | null): void;
51
+ close(): Promise<void>;
52
+ private sessionForAuthorization;
53
+ private handle;
54
+ }
@@ -0,0 +1,270 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import http from "node:http";
3
+ import { Readable } from "node:stream";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { log as defaultLog } from "./log.js";
6
+ /**
7
+ * Loopback model credential relay owned by the sandbox daemon.
8
+ *
9
+ * A runtime process receives only this relay's address and a random local token bound to
10
+ * one RuntimeSession. While that session has a current activation, the relay replaces the
11
+ * local token with the activation's short-lived model proxy grant and forwards the request.
12
+ * Without a current activation it answers 503 and forwards nothing. Deactivation aborts
13
+ * in-flight upstream requests. The grant never enters the runtime environment, config files,
14
+ * command line or logs, so a runtime process can outlive one AgentRun.
15
+ */
16
+ /**
17
+ * Request body cap. Agent Service enforces its configured model proxy limit
18
+ * (`AGENT_SERVICE_MODEL_PROXY_MAX_REQUEST_BYTES`, default 16 MiB); this is that setting's
19
+ * maximum (64 MiB), so the relay never rejects what the proxy may accept and still bounds
20
+ * what a runtime can push through the daemon.
21
+ */
22
+ export const MODEL_RELAY_MAX_REQUEST_BYTES = 64 * 1024 * 1024;
23
+ class RequestTooLargeError extends Error {
24
+ }
25
+ /** Same operations as the Agent Service model proxy allowlist. */
26
+ const ALLOWED_OPERATIONS = new Set(["POST /v1/chat/completions", "GET /v1/models"]);
27
+ const FORWARDED_REQUEST_HEADERS = ["content-type", "accept"];
28
+ const DROPPED_RESPONSE_HEADERS = new Set([
29
+ "connection",
30
+ "keep-alive",
31
+ "transfer-encoding",
32
+ "upgrade",
33
+ "proxy-authenticate",
34
+ "proxy-authorization",
35
+ "te",
36
+ "trailer",
37
+ // fetch() already decoded the body, so the original length and encoding no longer apply.
38
+ "content-length",
39
+ "content-encoding",
40
+ ]);
41
+ export class ModelCredentialRelay {
42
+ fetchFn;
43
+ log;
44
+ maxRequestBytes;
45
+ sessions = new Map();
46
+ server = null;
47
+ starting = null;
48
+ port = 0;
49
+ constructor(options = {}) {
50
+ this.fetchFn = options.fetchFn ?? fetch;
51
+ this.log = options.log ?? defaultLog;
52
+ this.maxRequestBytes = options.maxRequestBytes ?? MODEL_RELAY_MAX_REQUEST_BYTES;
53
+ }
54
+ /** Starts listening on 127.0.0.1 with an ephemeral port. Idempotent. */
55
+ async start() {
56
+ if (this.server)
57
+ return;
58
+ this.starting ??= new Promise((resolve, reject) => {
59
+ const server = http.createServer((req, res) => {
60
+ // A request from the runtime must never crash the daemon.
61
+ this.handle(req, res).catch((error) => {
62
+ this.log.warn("model credential relay request failed", { reason: errorName(error) });
63
+ deny(res, 400, "model_relay_request_invalid");
64
+ });
65
+ });
66
+ server.once("error", reject);
67
+ server.listen(0, "127.0.0.1", () => {
68
+ server.off("error", reject);
69
+ server.unref();
70
+ this.port = server.address().port;
71
+ this.server = server;
72
+ resolve();
73
+ });
74
+ }).finally(() => {
75
+ this.starting = null;
76
+ });
77
+ await this.starting;
78
+ }
79
+ /**
80
+ * Makes `grant` the credential for `sessionKey` until `deactivate`. A previous
81
+ * activation of the same session is aborted first. Returns the session's local endpoint.
82
+ */
83
+ activate(sessionKey, activationId, upstreamBaseUrl, grant) {
84
+ if (!this.server)
85
+ throw new Error("model credential relay is not started");
86
+ const upstream = parseUpstreamBaseUrl(upstreamBaseUrl);
87
+ let session = this.sessions.get(sessionKey);
88
+ if (!session) {
89
+ session = { token: randomBytes(32), activation: null };
90
+ this.sessions.set(sessionKey, session);
91
+ }
92
+ if (session.activation?.activationId !== activationId) {
93
+ session.activation?.abort.abort();
94
+ session.activation = { activationId, upstream, grant, abort: new AbortController() };
95
+ }
96
+ return {
97
+ baseUrl: `http://127.0.0.1:${this.port}`,
98
+ token: `blr_${session.token.toString("base64url")}`,
99
+ };
100
+ }
101
+ /** Stops using `activationId`; new requests get 503 and in-flight requests are cut. */
102
+ deactivate(activationId) {
103
+ for (const session of this.sessions.values()) {
104
+ if (session.activation?.activationId !== activationId)
105
+ continue;
106
+ session.activation.abort.abort();
107
+ session.activation = null;
108
+ }
109
+ }
110
+ /** Revokes the local token of one RuntimeSession, or of all sessions when null. */
111
+ releaseSession(sessionKey) {
112
+ for (const [key, session] of this.sessions) {
113
+ if (sessionKey !== null && key !== sessionKey)
114
+ continue;
115
+ session.activation?.abort.abort();
116
+ this.sessions.delete(key);
117
+ }
118
+ }
119
+ async close() {
120
+ this.releaseSession(null);
121
+ const server = this.server;
122
+ this.server = null;
123
+ if (!server)
124
+ return;
125
+ server.closeAllConnections();
126
+ await new Promise((resolve) => server.close(() => resolve()));
127
+ }
128
+ sessionForAuthorization(header) {
129
+ const match = /^Bearer blr_([A-Za-z0-9_-]{43})$/u.exec(header ?? "");
130
+ if (!match)
131
+ return null;
132
+ const presented = Buffer.from(match[1], "base64url");
133
+ for (const session of this.sessions.values()) {
134
+ if (presented.length === session.token.length && timingSafeEqual(presented, session.token)) {
135
+ return session;
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ async handle(req, res) {
141
+ const session = this.sessionForAuthorization(req.headers.authorization);
142
+ if (!session) {
143
+ deny(res, 401, "model_relay_token_invalid");
144
+ return;
145
+ }
146
+ const pathname = requestPathname(req.url);
147
+ if (pathname === null || !ALLOWED_OPERATIONS.has(`${req.method} ${pathname}`)) {
148
+ deny(res, 400, "model_relay_operation_unsupported");
149
+ return;
150
+ }
151
+ const activation = session.activation;
152
+ if (!activation || activation.abort.signal.aborted) {
153
+ deny(res, 503, "model_relay_activation_inactive");
154
+ return;
155
+ }
156
+ const declared = req.headers["content-length"];
157
+ if (declared !== undefined && !(Number(declared) <= this.maxRequestBytes)) {
158
+ deny(res, 413, "model_relay_request_too_large");
159
+ req.resume();
160
+ return;
161
+ }
162
+ const clientGone = new AbortController();
163
+ res.once("close", () => clientGone.abort());
164
+ const signal = AbortSignal.any([activation.abort.signal, clientGone.signal]);
165
+ const headers = { authorization: `Bearer ${activation.grant}` };
166
+ for (const name of FORWARDED_REQUEST_HEADERS) {
167
+ const value = req.headers[name];
168
+ if (typeof value === "string")
169
+ headers[name] = value;
170
+ }
171
+ const target = new URL(activation.upstream);
172
+ target.pathname = `${activation.upstream.pathname.replace(/\/+$/u, "")}${pathname}`;
173
+ let upstream;
174
+ try {
175
+ upstream = await this.fetchFn(target, {
176
+ method: req.method,
177
+ headers,
178
+ ...(req.method === "POST"
179
+ ? { body: Readable.toWeb(Readable.from(boundedBody(req, this.maxRequestBytes))), duplex: "half" }
180
+ : {}),
181
+ redirect: "manual",
182
+ signal,
183
+ });
184
+ }
185
+ catch (error) {
186
+ if (error instanceof RequestTooLargeError
187
+ || (error instanceof Error && error.cause instanceof RequestTooLargeError)) {
188
+ deny(res, 413, "model_relay_request_too_large");
189
+ req.resume();
190
+ return;
191
+ }
192
+ if (activation.abort.signal.aborted)
193
+ deny(res, 503, "model_relay_activation_inactive");
194
+ else
195
+ deny(res, 502, "model_relay_upstream_unavailable");
196
+ this.log.warn("model credential relay upstream request failed", {
197
+ reason: activation.abort.signal.aborted ? "deactivated" : errorName(error),
198
+ });
199
+ return;
200
+ }
201
+ const responseHeaders = {};
202
+ upstream.headers.forEach((value, name) => {
203
+ if (!DROPPED_RESPONSE_HEADERS.has(name))
204
+ responseHeaders[name] = value;
205
+ });
206
+ res.writeHead(upstream.status, responseHeaders);
207
+ if (!upstream.body) {
208
+ res.end();
209
+ return;
210
+ }
211
+ try {
212
+ await pipeline(Readable.fromWeb(upstream.body), res);
213
+ }
214
+ catch {
215
+ // Deactivation or a client disconnect ends the stream; the client sees a truncated body.
216
+ res.destroy();
217
+ }
218
+ }
219
+ }
220
+ /** Streams the request body and fails once it exceeds the cap, whatever Content-Length said. */
221
+ async function* boundedBody(req, maxBytes) {
222
+ let total = 0;
223
+ for await (const chunk of req) {
224
+ const buffer = chunk;
225
+ total += buffer.length;
226
+ if (total > maxBytes)
227
+ throw new RequestTooLargeError();
228
+ yield buffer;
229
+ }
230
+ }
231
+ function requestPathname(target) {
232
+ try {
233
+ return new URL(target ?? "/", "http://relay").pathname.replace(/\/+$/u, "");
234
+ }
235
+ catch {
236
+ return null;
237
+ }
238
+ }
239
+ function parseUpstreamBaseUrl(value) {
240
+ let url;
241
+ try {
242
+ url = new URL(value);
243
+ }
244
+ catch {
245
+ throw new Error("invalid model proxy base URL");
246
+ }
247
+ if (!["http:", "https:"].includes(url.protocol)
248
+ || url.username
249
+ || url.password
250
+ || url.search
251
+ || url.hash) {
252
+ throw new Error("invalid model proxy base URL");
253
+ }
254
+ return url;
255
+ }
256
+ function deny(res, status, code) {
257
+ if (res.headersSent) {
258
+ res.destroy();
259
+ return;
260
+ }
261
+ const body = JSON.stringify({ error: { code, message: code } });
262
+ res.writeHead(status, {
263
+ "content-type": "application/json",
264
+ "content-length": String(Buffer.byteLength(body)),
265
+ });
266
+ res.end(body);
267
+ }
268
+ function errorName(error) {
269
+ return error instanceof Error ? error.name : "unknown";
270
+ }
@@ -13,6 +13,7 @@ export interface PreparedPersistentTurn {
13
13
  workspaceDir: string;
14
14
  transcriptFile: string;
15
15
  runtimeStateDir?: string;
16
+ runtimeSessionKey?: string;
16
17
  nativeSessionId: string | null;
17
18
  contextRevision: number;
18
19
  runtimeEnv?: NodeJS.ProcessEnv;
@@ -810,6 +810,9 @@ export class RunDispatcher {
810
810
  ...(persistentTurn.runtimeStateDir
811
811
  ? { runtimeStateDir: persistentTurn.runtimeStateDir }
812
812
  : {}),
813
+ ...(persistentTurn.runtimeSessionKey
814
+ ? { runtimeSessionKey: persistentTurn.runtimeSessionKey }
815
+ : {}),
813
816
  nativeSessionId: activeNativeSessionId,
814
817
  contextRevision: persistentTurn.contextRevision,
815
818
  ...(persistentTurn.runtimeEnv