@sema-agent/server 3.22.0 → 3.23.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.
@@ -1,4 +1,4 @@
1
- import { type ImageApiClient, type ChildSpawner, type HostOps } from "./runner.js";
1
+ import { type ImageApiClient, type ChildSpawner, type HostOps, type BakeRunnerLogger } from "./runner.js";
2
2
  interface RunnerEnv {
3
3
  imageApiBase: string;
4
4
  token: string;
@@ -14,7 +14,7 @@ interface RunnerEnv {
14
14
  declare function loadEnv(): RunnerEnv;
15
15
  /** The real image-api HTTP client. Authenticates claim/heartbeat with the runner bearer; ingest additionally
16
16
  * carries the per-bake ingest secret header (so image-api can reject a stale/rogue runner — §P2.4e). */
17
- declare function makeApiClient(env: RunnerEnv): ImageApiClient;
17
+ declare function makeApiClient(env: RunnerEnv, log: BakeRunnerLogger): ImageApiClient;
18
18
  /** The real child spawner: `setsid`-style detached process GROUP so a cancel/deadline kill signals the whole tree
19
19
  * (channel-close / a plain kill of the immediate child does NOT stop a detached build — §P2.11). */
20
20
  declare function makeSpawner(): ChildSpawner;
@@ -11,6 +11,7 @@ import { spawn, exec as execCb } from "node:child_process";
11
11
  import { readFile } from "node:fs/promises";
12
12
  import { promisify } from "node:util";
13
13
  import { createLogger } from "../observability/logger.js";
14
+ import { parseNumOrFailNonNegative } from "../config.js";
14
15
  import { BakeRunner, } from "./runner.js";
15
16
  const exec = promisify(execCb);
16
17
  function loadEnv() {
@@ -28,14 +29,22 @@ function loadEnv() {
28
29
  recipeDir: process.env.RECIPE_DIR || "/opt/recipes",
29
30
  buildShPath: process.env.BUILD_SH_PATH || "e2b-template/dev-sandbox/build.sh",
30
31
  dataDir: process.env.BAKE_DATA_DIR || "/data",
31
- heartbeatMs: Number(process.env.BAKE_HEARTBEAT_MS || "30000"),
32
- idlePollMs: Number(process.env.BAKE_IDLE_POLL_MS || "5000"),
33
- minFreeGb: Number(process.env.IMAGE_BAKE_MIN_FREE_GB || "20"),
32
+ // A2/E5 (gap-sweep 2026-08-01): these were bare `Number(process.env.X || default)` — a unit-suffixed or
33
+ // typo'd value (`"30s"`) silently became NaN, and NaN survives every downstream `??`/`?? default` guard
34
+ // (those only catch null/undefined). The fallout is a SILENT-LOOSENING pair: `clock.sleep(NaN)` resolves
35
+ // ~immediately (`setTimeout(fn, NaN)` behaves like a 0ms timer) turning the lease heartbeat into a tight
36
+ // POST loop against image-api, and `freeGb < NaN` is always false so the pre-flight disk guard silently
37
+ // never fires. `parseNumOrFailNonNegative` (config.ts, shared with leader/wire.ts's four resource knobs)
38
+ // fails loud at bake-runner startup instead — non-numeric OR negative both throw; unset/empty still falls
39
+ // back to the documented default (zero behavior change on the happy path).
40
+ heartbeatMs: parseNumOrFailNonNegative("BAKE_HEARTBEAT_MS", process.env.BAKE_HEARTBEAT_MS || "30000"),
41
+ idlePollMs: parseNumOrFailNonNegative("BAKE_IDLE_POLL_MS", process.env.BAKE_IDLE_POLL_MS || "5000"),
42
+ minFreeGb: parseNumOrFailNonNegative("IMAGE_BAKE_MIN_FREE_GB", process.env.IMAGE_BAKE_MIN_FREE_GB || "20"),
34
43
  };
35
44
  }
36
45
  /** The real image-api HTTP client. Authenticates claim/heartbeat with the runner bearer; ingest additionally
37
46
  * carries the per-bake ingest secret header (so image-api can reject a stale/rogue runner — §P2.4e). */
38
- function makeApiClient(env) {
47
+ function makeApiClient(env, log) {
39
48
  const auth = { authorization: `Bearer ${env.token}`, "content-type": "application/json" };
40
49
  return {
41
50
  // Long-poll claim (§P2.12): the bare `POST …/bakes/claim` finds the oldest queued bake AND leases it in one
@@ -46,13 +55,27 @@ function makeApiClient(env) {
46
55
  headers: auth,
47
56
  body: JSON.stringify({ runnerId: env.runnerId }),
48
57
  });
49
- if (res.status === 204 || res.status === 409)
50
- return null; // empty queue, or lost the single-flight CAS
51
- if (!res.ok)
58
+ if (res.status === 204)
59
+ return null; // empty queue the routine "nothing to do" case, no log line
60
+ // C6/C1 (2026-08-01): 401 (bad runner credential) / 409 (lost the single-flight CAS to another runner
61
+ // replica) / 5xx previously fell into this SAME silent-`null` branch as an empty queue — a misconfigured
62
+ // BAKE_RUNNER_TOKEN and a healthy idle runner were indistinguishable from the outside (both just idle-poll
63
+ // forever with zero log lines). `bake_claim_error` (loop()'s catch) only fires on a THROWN error — a non-ok
64
+ // HTTP response never throws — so this warn is the only trace a non-2xx claim response leaves anywhere.
65
+ if (!res.ok) {
66
+ log.warn("bake_claim_rejected", { status: res.status });
52
67
  return null;
68
+ }
53
69
  const c = (await res.json());
54
- if (!c.bakeId || !Array.isArray(c.argv) || !c.ingestSecret)
70
+ if (!c.bakeId || !Array.isArray(c.argv) || !c.ingestSecret) {
71
+ // A malformed 2xx body is worse than a rejection: image-api's claim call ATOMICALLY leases the bake
72
+ // server-side before returning it, so a shape we refuse to trust here is a bake already checked OUT
73
+ // from the queue that we are about to drop on the floor. We still can't safely act on an untrusted
74
+ // shape (no bakeId ⇒ no way to release/fail it), so this warn is the only surfacing point until
75
+ // image-api's stale-lease reaper reclaims it (§P2.7) — see runner.ts module doc for the reaper backstop.
76
+ log.warn("bake_claim_malformed", { status: res.status, bakeId: typeof c.bakeId === "string" ? c.bakeId : undefined });
55
77
  return null;
78
+ }
56
79
  return {
57
80
  bakeId: c.bakeId,
58
81
  argv: c.argv.map(String),
@@ -223,7 +246,7 @@ async function main() {
223
246
  minFreeGb: env.minFreeGb,
224
247
  }); // NB: the token + per-bake ingest secret are NEVER logged (§P2.4e)
225
248
  const runner = new BakeRunner({
226
- api: makeApiClient(env),
249
+ api: makeApiClient(env, log),
227
250
  spawner: makeSpawner(),
228
251
  host: makeHostOps(env),
229
252
  clock: makeClock(),
@@ -180,7 +180,7 @@ export async function applyCenterPlugins(baseline, eff, opts) {
180
180
  }
181
181
  if (!rootCheck.dir)
182
182
  continue; // 无 skills 目录:合法(commands-only 插件,cli 壳的半场)
183
- const loaded = loadSkills(rootCheck.dir);
183
+ const loaded = loadSkills(rootCheck.dir, { confineTo: liveDir }); // 不可信 lane:逐条目约束在 clone root 内(根守卫只守了 skills 根,根下 symlink 可逃逸) // 不可信 lane:逐条目约束在 clone root 内(根守卫只守了 skills 根,根下 symlink 可逃逸) // 不可信 lane:逐条目约束在 clone root 内(根守卫只守了 skills 根,根下 symlink 可逃逸)
184
184
  for (const skill of loaded) {
185
185
  if (taken.has(skill.spec.name)) {
186
186
  // 收紧④:plugin 让位(方向与 center-wins 相反,理由见模块顶注)。
@@ -31,7 +31,18 @@ export interface LoadedSkill {
31
31
  /** Scenarios this skill applies to; empty = global (every scenario). */
32
32
  scenarios: string[];
33
33
  }
34
- export declare function loadSkills(dir: string): LoadedSkill[];
34
+ /** 加载 lane 的信任级。缺席(受控 lane:烤制进镜像的 skills 目录)= 维持既有语义,symlink 照跟
35
+ * ——那个便利是有意的(`foo.md -> 共享文件`)。`confineTo` 在场(**不可信 lane**:第三方 git checkout,
36
+ * 见 center-plugins 的 plugin 装载)= 每个被读条目 realpath 后必须仍在该根之内,逃逸即抛。
37
+ * 🔴 为什么信任级必须是**参数**而不是注释里的假设:本函数的头注原写着「skills dir 全受控」,而
38
+ * center-plugins 把它原样复用在 attacker-controlled 的 git checkout 上——git 原样保留仓里的 symlink,
39
+ * 于是 checkout 里某个 skill 条目(`任意 .md -> /宿主/任意文件`)会被读进 spec.files 进入提示词。resolvePluginSkillsRoot
40
+ * 只 realpath 守了 skills **根**,根下逐条目没守。 */
41
+ export interface LoadSkillsOptions {
42
+ /** 不可信 lane 的约束根(通常=clone root)。缺席=受控 lane,不做逐条目约束。 */
43
+ confineTo?: string;
44
+ }
45
+ export declare function loadSkills(dir: string, opts?: LoadSkillsOptions): LoadedSkill[];
35
46
  /** Skills applicable to a scenario: those tagged with it, plus untagged (global) ones. */
36
47
  export declare function skillsForScenario(loaded: LoadedSkill[], scenario: string): SkillSpec[];
37
48
  export declare function parseFrontmatter(raw: string): {
@@ -1,6 +1,20 @@
1
- import { readdirSync, readFileSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- export function loadSkills(dir) {
1
+ import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { join, sep } from "node:path";
3
+ /** `p` 的 realpath 必须落在 `rootReal` 之内(含自身),否则抛。`sep` 边界判定防 `/a/root-evil` 撞
4
+ * `/a/root` 前缀。目标不存在 ⇒ realpath 抛 ENOENT,同样是拒绝(悬空链接不该被读)。 */
5
+ function assertConfined(p, rootReal) {
6
+ let real;
7
+ try {
8
+ real = realpathSync(p);
9
+ }
10
+ catch (e) {
11
+ throw new Error(`skill entry ${p} is unreadable (dangling symlink or missing): ${e instanceof Error ? e.message : String(e)}`);
12
+ }
13
+ if (real !== rootReal && !real.startsWith(rootReal + sep)) {
14
+ throw new Error(`skill entry ${p} escapes the plugin root (resolves outside ${rootReal}) — untrusted checkouts may not link to host files`);
15
+ }
16
+ }
17
+ export function loadSkills(dir, opts) {
4
18
  let entries;
5
19
  try {
6
20
  entries = readdirSync(dir, { withFileTypes: true });
@@ -21,17 +35,22 @@ export function loadSkills(dir) {
21
35
  // sort 保证加载顺序稳定(冲突报错的"先到者"也因此确定)。dotfile/dot 目录跳过(.DS_Store/.git 类
22
36
  // 环境杂物,不是 skill 内容);isFileLike 兼容 symlink(Dirent.isFile() 对 symlink 恒 false,而旧扁平
23
37
  // 实现 readFileSync 是跟链接的——不兼容会让 skills 目录下 `foo.md -> 共享文件` 这种软链无声消失)。
38
+ const confineRoot = opts?.confineTo !== undefined ? realpathSync(opts.confineTo) : undefined;
24
39
  const isFileLike = (entry, p) => entry.isFile() || (entry.isSymbolicLink() && statSync(p).isFile());
25
40
  const isDirLike = (entry, p) => entry.isDirectory() || (entry.isSymbolicLink() && statSync(p).isDirectory());
26
41
  for (const entry of entries.slice().sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
27
42
  if (entry.name.startsWith("."))
28
43
  continue;
29
44
  if (isFileLike(entry, join(dir, entry.name)) && entry.name.endsWith(".md")) {
45
+ if (confineRoot !== undefined)
46
+ assertConfined(join(dir, entry.name), confineRoot);
30
47
  const raw = readFileSync(join(dir, entry.name), "utf8");
31
48
  push(parseSkill(raw, entry.name.replace(/\.md$/, "")), join(dir, entry.name));
32
49
  }
33
50
  else if (isDirLike(entry, join(dir, entry.name))) {
34
51
  const skillDir = join(dir, entry.name);
52
+ if (confineRoot !== undefined)
53
+ assertConfined(skillDir, confineRoot);
35
54
  let raw;
36
55
  try {
37
56
  raw = readFileSync(join(skillDir, "SKILL.md"), "utf8");
@@ -41,8 +60,10 @@ export function loadSkills(dir) {
41
60
  // 整个 skill 无声丢掉 → fail-loud
42
61
  throw new Error(`skill directory ${skillDir} has no SKILL.md`);
43
62
  }
63
+ if (confineRoot !== undefined)
64
+ assertConfined(join(skillDir, "SKILL.md"), confineRoot);
44
65
  const skill = parseSkill(raw, entry.name);
45
- const files = collectAttachments(skillDir, "");
66
+ const files = collectAttachments(skillDir, "", confineRoot);
46
67
  if (files.length > 0)
47
68
  skill.spec.files = files;
48
69
  push(skill, join(skillDir, "SKILL.md"));
@@ -53,7 +74,7 @@ export function loadSkills(dir) {
53
74
  /** 目录形态附件:递归收 SKILL.md 之外的一切文件,path=相对 skill 目录(posix 斜杠),sort 稳定。
54
75
  * dotfile/dot 目录跳过(交叉评审 M3):skill 目录若从别的 checkout 整拷,.git/config、.env 类隐藏物
55
76
  * 会连凭据一起进 spec.files 变成提示词可见附件——附件只收显式内容文件。symlink 跟链接(同扁平兼容)。 */
56
- function collectAttachments(skillDir, rel) {
77
+ function collectAttachments(skillDir, rel, confineRoot) {
57
78
  const files = [];
58
79
  const here = rel === "" ? skillDir : join(skillDir, rel);
59
80
  for (const entry of readdirSync(here, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
@@ -64,9 +85,13 @@ function collectAttachments(skillDir, rel) {
64
85
  const dirLike = entry.isDirectory() || (entry.isSymbolicLink() && statSync(abs).isDirectory());
65
86
  const fileLike = entry.isFile() || (entry.isSymbolicLink() && statSync(abs).isFile());
66
87
  if (dirLike) {
67
- files.push(...collectAttachments(skillDir, relPath));
88
+ if (confineRoot !== undefined)
89
+ assertConfined(abs, confineRoot);
90
+ files.push(...collectAttachments(skillDir, relPath, confineRoot));
68
91
  }
69
92
  else if (fileLike && relPath !== "SKILL.md") {
93
+ if (confineRoot !== undefined)
94
+ assertConfined(abs, confineRoot);
70
95
  files.push({ path: relPath, content: readFileSync(abs, "utf8") });
71
96
  }
72
97
  }
package/dist/config.d.ts CHANGED
@@ -25,6 +25,18 @@ export declare function numEnv(name: string, fallback: string): number;
25
25
  * `undefined`/空串 ⇒ 交给调用方的 fallback 语义处理(本函数只判「给了值但不是数」)。
26
26
  */
27
27
  export declare function parseNumOrFail(name: string, raw: string | undefined): number;
28
+ /**
29
+ * `parseNumOrFail` layered with a non-negative floor — the SAME judgment `leader/wire.ts`'s (private,
30
+ * file-local) `parseNumOrFailNonNegative` already applies to its four resource knobs, exported here so a
31
+ * second call site (bake-runner's heartbeat/idle-poll/disk-guard knobs, gap-sweep 2026-08-01) can reuse the
32
+ * one shared primitive instead of re-deriving its own "reject a bad number" scheme. A negative value is
33
+ * JS-truthy, so a bare `|| default` fallback lets it straight through; for a duration knob that means
34
+ * `clock.sleep(-N)` fires ~immediately (the same tight-loop failure NaN causes), and for a threshold knob
35
+ * (`freeGb < minFreeGb`) a negative floor makes the comparison vacuously true/false depending on sign —
36
+ * either way the guard it configures goes silently slack. `undefined`/unset stays NaN (unchanged) so
37
+ * existing `|| fallback` chains built on `parseNumOrFail` are untouched by this stricter sibling.
38
+ */
39
+ export declare function parseNumOrFailNonNegative(name: string, raw: string | undefined): number;
28
40
  export declare function drainConfigWarnings(): Array<{
29
41
  env: string;
30
42
  raw: string;
package/dist/config.js CHANGED
@@ -94,6 +94,23 @@ export function parseNumOrFail(name, raw) {
94
94
  throw new Error(`env ${name}="${raw}" must be a number`);
95
95
  return n;
96
96
  }
97
+ /**
98
+ * `parseNumOrFail` layered with a non-negative floor — the SAME judgment `leader/wire.ts`'s (private,
99
+ * file-local) `parseNumOrFailNonNegative` already applies to its four resource knobs, exported here so a
100
+ * second call site (bake-runner's heartbeat/idle-poll/disk-guard knobs, gap-sweep 2026-08-01) can reuse the
101
+ * one shared primitive instead of re-deriving its own "reject a bad number" scheme. A negative value is
102
+ * JS-truthy, so a bare `|| default` fallback lets it straight through; for a duration knob that means
103
+ * `clock.sleep(-N)` fires ~immediately (the same tight-loop failure NaN causes), and for a threshold knob
104
+ * (`freeGb < minFreeGb`) a negative floor makes the comparison vacuously true/false depending on sign —
105
+ * either way the guard it configures goes silently slack. `undefined`/unset stays NaN (unchanged) so
106
+ * existing `|| fallback` chains built on `parseNumOrFail` are untouched by this stricter sibling.
107
+ */
108
+ export function parseNumOrFailNonNegative(name, raw) {
109
+ const n = parseNumOrFail(name, raw);
110
+ if (n < 0)
111
+ throw new Error(`env ${name}=${n} must not be negative`);
112
+ return n;
113
+ }
97
114
  /** Numeric env with a [min,max] bound (BL-17): an out-of-range value FAILS at startup instead of being
98
115
  * silently clamped/applied (e.g. a multi-hour MCP_ELICITATION_TTL_MS would silently never expire). */
99
116
  function numEnvBounded(name, fallback, min, max) {
@@ -203,9 +203,12 @@ export function fleetRunPublisher(bus, run) {
203
203
  elapsedDonor.add(cid);
204
204
  const elapsed = elapsedDonor.has(cid) ? Date.now() - childStartedAt.get(cid) : undefined;
205
205
  if (donorName !== undefined || elapsed !== undefined) {
206
+ // cli [2297]①:donorName 只进 `name` 位。run-leg tick 手上没有独立的类型名([1364]③/core 1.350:
207
+ // name=display 标签、agentType=类型名),把 display 值同时写进 agentType 会让 fleet 的 TYPE 列显示
208
+ // description。缺源的键不铸(与「匿名行不铸假名」同一条原则);BCE 行自己的帧带真 agentType 时自然补上。
206
209
  bus.publishTask({
207
210
  id: bceRowId,
208
- ...(donorName !== undefined ? { name: donorName, agentType: donorName } : {}),
211
+ ...(donorName !== undefined ? { name: donorName } : {}),
209
212
  ...(elapsed !== undefined ? { elapsedMs: elapsed } : {}),
210
213
  });
211
214
  }
@@ -160,7 +160,7 @@ export function createHookLlm(deps) {
160
160
  text = j.choices?.[0]?.message?.content ?? undefined;
161
161
  }
162
162
  metrics.inc("hook_llm_calls_total", { type: "prompt" });
163
- return typeof text === "string" ? { ok: true, text } : { ok: false, error: "hook llm returned no content" };
163
+ return typeof text === "string" ? { ok: true, text } : { ok: false, error: "hook llm returned no content", code: "no_content" };
164
164
  }
165
165
  catch (e) {
166
166
  // 网络层失败原样只有 "TypeError: fetch failed"(不是人话):带上端点与 cause(ECONNREFUSED 等),
@@ -91,7 +91,11 @@ export type HookLlmCall = (opts: {
91
91
  } | {
92
92
  ok: false;
93
93
  error: string;
94
+ code?: HookLlmFailureCode;
94
95
  }>;
96
+ /** 失败判别码(B8:判别一律走码,禁按 error 文案分支——v3.1 批2,统检第二波 high)。error 仍是给人看的
97
+ * 自由文本;code 是给控制流的。缺席=未分类失败(不重试、不特判)。 */
98
+ export type HookLlmFailureCode = "no_content" | "hard_timeout";
95
99
  /**
96
100
  * 阶段三a:`http` 条目——契约语义 = POST hook 输入 JSON 到 `url`;headers 里的 `$NAME` 仅当 NAME 列在
97
101
  * `allowedEnvVars` 才从 worker 进程 env 插值(配置本身绝不携带密钥值,契约同边界)。
@@ -383,7 +383,7 @@ async function runLlmHook(entry, payload, ctx, extra) {
383
383
  // 顺序是承重的 —— 包装句逐字预设会话在上文,放反了那句话本身就是在骗模型。
384
384
  const prompt = extra ? `${extra.transcript}\n\n---\n\n${wrapCondition("Stop", substituted)}` : substituted;
385
385
  // 载体外再包一层硬顶:契约说载体自己兜超时,但一个部署组装 bug 不该能挂死工具门(纵深)。
386
- const hardTop = new Promise((r) => setTimeout(() => r({ ok: false, error: "__hook_llm_hard_timeout__" }), timeoutMs + 5_000).unref?.());
386
+ const hardTop = new Promise((r) => setTimeout(() => r({ ok: false, error: "hook llm hard-timeout backstop fired (carrier did not settle within timeoutMs+5s — deployment assembly bug)", code: "hard_timeout" }), timeoutMs + 5_000).unref?.());
387
387
  const invoke = () => Promise.race([
388
388
  call({
389
389
  prompt,
@@ -397,17 +397,17 @@ async function runLlmHook(entry, payload, ctx, extra) {
397
397
  // 🔴 **"一个字都没吐出来"重试一次**(仅 CC 评估者路)。这个失败形的后果是**判词被丢弃 ⇒ fail-open**
398
398
  // (该拦没拦),而它是**瞬态**的(推理档模型偶尔把额度用在 thinking 上)。
399
399
  // ⚠️ 只重试**无内容**,不重试"有内容但读不懂" —— 后者重试一次多半还是读不懂,而且那一格按设计就该放行。
400
- if (extra && !res.ok && res.error.includes("returned no content")) {
400
+ if (extra && !res.ok && res.code === "no_content") { // B8:判别走码不走文案(v3.1 批2)
401
401
  ctx.logger.warn("hook_llm_no_content_retry", { event: "Stop" });
402
402
  res = await invoke();
403
403
  // 重试之后**仍然**没有内容 ⇒ 这一轮的守卫确实没能评估。发观测帧(纯 observe,不改变运行)——
404
404
  // 方向仍是 fail-open,但用户/壳侧要能知道「这轮没看住」,否则那个放行与「已达成」无法区分。
405
- if (!res.ok && res.error.includes("returned no content")) {
405
+ if (!res.ok && res.code === "no_content") {
406
406
  ctx.onHookNotice?.({ kind: "hook_decision_unavailable", event: "Stop", reason: "no_content", detail: "carrier returned no content (after one retry)" });
407
407
  }
408
408
  }
409
409
  if (!res.ok) {
410
- return res.error === "__hook_llm_hard_timeout__"
410
+ return res.code === "hard_timeout"
411
411
  ? { code: null, stdout: "", stderr: "", timedOut: true }
412
412
  : { code: null, stdout: "", stderr: "", timedOut: false, spawnError: clip(res.error, 500) };
413
413
  }
@@ -1134,7 +1134,12 @@ async function handleRunVerbsBody(req, res, url, ctx, miss) {
1134
1134
  const parkArbiterUnreachable = details?.error === "park_arbiter_unreachable";
1135
1135
  const parkResumeWon = details?.error === "park_resume_won";
1136
1136
  const stillParked = details?.error === "parked_pending_approval" || details?.status === "parked";
1137
- if (stopVerb && details?.error !== undefined && (details.status === "running" || stillParked || parkResumeWon || parkArbiterUnreachable)) {
1137
+ // v3.1 批2(统检第二波 high):判别方向翻转——旧形是 (status,error) 的**失败白名单**(status==="running"
1138
+ // || 三个具名码),core 新增失败码且行状态不在 {running,parked} 时整个分支被跳过落 200,与上面注释自陈
1139
+ // 的不变量(kill 没落地绝不读成功)正相悖(B5 联合非穷尽的 default-放行形;not_local/park 族/arbiter
1140
+ // 三次历史新增全靠人追认)。新形:stop 动词的 error **在场即失败**(not_found 已在上方早退),具名臂
1141
+ // 保留各自 errorCode,未知码落 stop.not_landed 兜底 409——新失败码默认可见,不默认成功。
1142
+ if (stopVerb && details?.error !== undefined) {
1138
1143
  // 1.250:durable 回落臂(core stopTask agentStore 分支)对他实例 running 行应答 error="not_local"
1139
1144
  // (没有 kill 被尝试)——与「kill 尝试了没落地」(stop.not_landed)是不同的失败形,各给各的
1140
1145
  // errorCode(同 409 家族,additive)。
@@ -1671,16 +1671,20 @@ export function createHttpServer(rawDeps) {
1671
1671
  if (!rs || !taskId)
1672
1672
  return;
1673
1673
  const t = e.type;
1674
+ // C2/C5(v3.1 批2):写失败留痕——同函数 onTaskNotification 的 park-enqueue 早按 2026-07-11
1675
+ // 对抗评审补了 warn(false park 指纹),这三处同构 fire-and-forget 此前裸吞:子代 tool 生命周期
1676
+ // 事件从 durable log 永久消失且零信号。结构上仍不能 await(同步回调),留痕不改调用形。
1677
+ const warnAppend = (kind) => (err) => deps.logger?.warn?.("forward_event_append_failed", { type: kind, taskId, err: err instanceof Error ? err.message : String(err) });
1674
1678
  if (t === "task_progress") {
1675
- void append("task_progress", taskProgressEventData(e)).catch(() => undefined);
1679
+ void append("task_progress", taskProgressEventData(e)).catch(warnAppend(t));
1676
1680
  }
1677
1681
  else if (t === "tool_start") {
1678
1682
  // C1 (core 1.219): a delegated child's forwarded tool lifecycle — durable via the SAME shared
1679
1683
  // whitelist+redact builders as the top stream (parity with the bg leg; deltas not persisted per-chunk).
1680
- void append("tool_start", toolStartEventData(e)).catch(() => undefined);
1684
+ void append("tool_start", toolStartEventData(e)).catch(warnAppend(t));
1681
1685
  }
1682
1686
  else if (t === "tool_end") {
1683
- void append("tool_end", toolEndEventData(e)).catch(() => undefined);
1687
+ void append("tool_end", toolEndEventData(e)).catch(warnAppend(t));
1684
1688
  }
1685
1689
  },
1686
1690
  // background-completion observer — flip the child's fleet row +
@@ -2559,7 +2563,7 @@ function cors(res, req, origins, principalHeader) {
2559
2563
  // 后五项都是**真被 handler 读**的自定义头:`idempotency-key`(tasks/runs/images)、
2560
2564
  // `x-detach-on-disconnect`(tasks 断连不中止)、direct-door 决策证明三件套(approvals /decide 的
2561
2565
  // crypto 绑定腿 —— 缺了它,direct-door worker 上的 web 审批面在浏览器里根本用不了)。
2562
- res.setHeader("access-control-allow-headers", `content-type, authorization, last-event-id, ${principalHeader}, idempotency-key, x-detach-on-disconnect, x-approval-principal-token, x-approval-mac, x-approval-mac-kid`);
2566
+ res.setHeader("access-control-allow-headers", `content-type, authorization, last-event-id, ${principalHeader}, idempotency-key, x-detach-on-disconnect, x-approval-principal-token, x-approval-mac, x-approval-mac-kid, if-none-match`);
2563
2567
  // 🔴 expose-headers 此前**整个缺席** ⇒ fetch 类客户端读不到 `X-Task-Id`(routes/tasks.ts 经 sseHeaders
2564
2568
  // 下发的 durable rewind handle)。tasks.ts 的 G15 meta 帧注释把这归因为「EventSource 与部分代理读不到
2565
2569
  // 响应头」—— 对 EventSource 成立,但对 fetch 客户端真因是这里缺 expose,meta 帧只是绕过。
@@ -26,7 +26,16 @@ const TOKEN = process.env.LSP_TOKEN || '';
26
26
  const MAX = 50 * 1024 * 1024;
27
27
  const HEARTBEAT_MS = Number(process.env.LSP_HEARTBEAT_MS || 30000);
28
28
  const wss = new WebSocketServer({ host: '0.0.0.0', port: PORT });
29
+ // A zero-listener 'error' on ANY EventEmitter throws and crashes the process (Node default). Without this, a
30
+ // bind failure (e.g. EADDRINUSE — a second bridge start racing the same port) took down the WHOLE bridge
31
+ // process, killing every language's LSP session in the sandbox, not just the one that failed to start (HRD-LSP-4).
32
+ // Exit loud + explicit instead of an uncaught-exception dump so the failure is at least attributable.
33
+ wss.on('error', (err) => { console.error('lsp-bridge wss error', err && err.message); process.exit(1); });
29
34
  wss.on('connection', (ws, req) => {
35
+ // Same zero-listener 'error' hazard as wss above, but per-connection: registered FIRST, before anything else
36
+ // touches this socket. Close (don't crash) — the heartbeat reaper's own ws.terminate() below is a routine
37
+ // source of a socket 'error' on an already-half-open connection (HRD-LSP-4).
38
+ ws.on('error', () => { try { ws.terminate(); } catch {} });
30
39
  const q = ((req && req.url) || '').split('?')[1] || '';
31
40
  if (TOKEN && new URLSearchParams(q).get('token') !== TOKEN) { ws.close(); return; } // auth (council #4)
32
41
  ws.isAlive = true;
@@ -37,7 +46,11 @@ wss.on('connection', (ws, req) => {
37
46
  const decode = makeFrameDecoder(MAX);
38
47
  child.stdout.on('data', (d) => { for (const f of decode(d)) ws.send(f); });
39
48
  ws.on('message', (data) => { const p = Buffer.from(data.toString(), 'utf8'); child.stdin.write('Content-Length: ' + p.length + '\r\n\r\n'); child.stdin.write(p); });
40
- ws.on('close', () => child.kill());
49
+ // pid guard: the child 'error' handler above routes spawn FAILURES (missing binary — pid never assigned)
50
+ // through ws.close() → this 'close' handler. Killing a child whose pid was never assigned can signal the
51
+ // CALLER's process group instead of the (nonexistent) child (HRD-LSP-4; same hazard class as bake-runner's
52
+ // spawner, src/bake-runner/main.ts).
53
+ ws.on('close', () => { if (child.pid !== undefined) child.kill(); });
41
54
  child.on('exit', () => { try { ws.close(); } catch {} });
42
55
  });
43
56
  // Reap half-open connections: the E2B proxy kills a WS at ~60-75s and the kill can be SILENT on THIS side too —
@@ -8,9 +8,11 @@ export interface E2bLspOptions {
8
8
  attempts: number;
9
9
  delayMs: number;
10
10
  };
11
- /** Bridge auth token override. The manager pins ONE token per env+language: on a RE-open (transport heal
12
- * after the E2B proxy idle-killed the WS) the original bridge process is still listening with the FIRST
13
- * token a fresh random token would be rejected and the reconnect would always fail. */
11
+ /** Bridge auth token override. The manager pins ONE token per env+PORT the bridge RESOURCE, not the
12
+ * language (`portForLanguage` maps several languages, e.g. typescript/javascript, onto the SAME port/process
13
+ * — see `createE2bLspManager`). On a RE-open (transport heal after the E2B proxy idle-killed the WS) the
14
+ * original bridge process is still listening with the FIRST token — a fresh random token would be rejected
15
+ * and the reconnect would always fail. */
14
16
  token?: string;
15
17
  /** WS scheme for the bridge URL. E2B's `getHost` returns a public TLS proxy host → `wss` (default);
16
18
  * the k8s adapter returns a cluster-internal `podIP:port` → plain `ws` (no TLS on the pod network;
@@ -19,7 +21,9 @@ export interface E2bLspOptions {
19
21
  /** Observability hook (open/heal/degrade events) — prod wires the service logger. */
20
22
  log?: (event: string, fields: Record<string, unknown>) => void;
21
23
  }
22
- /** Start (+ install on a non-baked template) the language server + bridge inside THIS env's sandbox, then connect. */
24
+ /** Start (+ install on a non-baked template) the language server + bridge inside THIS env's sandbox, then connect.
25
+ * Every call starts (or re-starts) the bridge unconditionally — the one production caller is
26
+ * `createE2bLspManager`, which de-dupes per env+port before ever reaching here (see its doc). */
23
27
  export declare function openE2bLspTransport(language: string, env: LspCapableEnv, opts?: E2bLspOptions): Promise<LspTransport | undefined>;
24
28
  /** The single shared `LspServerManager` for the deployment (`RunnerDeps.lspManager`). */
25
29
  export declare function createE2bLspManager(opts?: E2bLspOptions): E2bLspManager;
@@ -12,19 +12,28 @@ import { randomUUID } from "node:crypto";
12
12
  import { connectWsLspTransport } from "./ws-transport.js";
13
13
  import { E2bLspManager } from "./manager.js";
14
14
  import { BRIDGE_DIR, BRIDGE_SOURCE, lspInstallCommand, lspStartCommand, portForLanguage, SERVER_CMD } from "./e2b-bridge.js";
15
- /** Start (+ install on a non-baked template) the language server + bridge inside THIS env's sandbox, then connect. */
16
- export async function openE2bLspTransport(language, env, opts) {
17
- if (!SERVER_CMD[language])
18
- return undefined; // no server for this language graceful degrade
19
- const connect = opts?.connect ?? connectWsLspTransport;
20
- const retry = opts?.retry ?? { attempts: 6, delayMs: 1500 };
21
- const port = portForLanguage(language);
15
+ /** Write bridge.cjs + (foreground) install the language server, then start the bridge as a TRUE background
16
+ * command. Returns whether the bridge is now up-or-starting (`false` only when the foreground install failed).
17
+ * A single-shot primitive: it does NOT check whether a bridge is already listening on `port` — a caller that
18
+ * can have two languages share one port (`createE2bLspManager`, since `portForLanguage` maps typescript AND
19
+ * javascript onto 8123 off the same `SERVER_CMD`) MUST call this at most ONCE per env+port itself. A second
20
+ * `node bridge.cjs` on an already-bound port surfaces as an EADDRINUSE `wss` 'error' (e2b-bridge.ts D6
21
+ * hardening keeps that from crashing the sandbox, but the second attempt still fails and wastes a sandbox
22
+ * round-trip for nothing — HRD-LSP-4). */
23
+ async function startE2bBridge(language, env, port, token) {
22
24
  await env.writeFile(`${BRIDGE_DIR}/bridge.cjs`, BRIDGE_SOURCE).catch(() => undefined);
23
25
  const installed = await env.exec(lspInstallCommand(language)).catch(() => undefined);
24
26
  if (!installed || !installed.ok)
25
- return undefined;
26
- const token = opts?.token ?? randomUUID(); // per-session bridge auth — the getHost URL is public (council #4)
27
+ return false;
27
28
  await env.startBackground(lspStartCommand(language, port, token)).catch(() => undefined);
29
+ return true;
30
+ }
31
+ /** Connect (with retry) to an already-started bridge. Each call opens its OWN WS connection — the bridge spawns
32
+ * a FRESH child language-server process per connection (e2b-bridge.ts `wss.on('connection', …)`), so two
33
+ * languages sharing one bridge port each still get an isolated language-server instance. */
34
+ async function connectE2bLspBridge(env, port, token, opts) {
35
+ const connect = opts?.connect ?? connectWsLspTransport;
36
+ const retry = opts?.retry ?? { attempts: 6, delayMs: 1500 };
28
37
  const root = env.workspaceHandle().mountPath;
29
38
  // the bridge starts as a background command → retry the WS connect (with the auth token) while it comes up
30
39
  const scheme = opts?.scheme ?? "wss";
@@ -39,26 +48,49 @@ export async function openE2bLspTransport(language, env, opts) {
39
48
  }
40
49
  return undefined;
41
50
  }
51
+ /** Start (+ install on a non-baked template) the language server + bridge inside THIS env's sandbox, then connect.
52
+ * Every call starts (or re-starts) the bridge unconditionally — the one production caller is
53
+ * `createE2bLspManager`, which de-dupes per env+port before ever reaching here (see its doc). */
54
+ export async function openE2bLspTransport(language, env, opts) {
55
+ if (!SERVER_CMD[language])
56
+ return undefined; // no server for this language → graceful degrade
57
+ const port = portForLanguage(language);
58
+ const token = opts?.token ?? randomUUID(); // per-session bridge auth — the getHost URL is public (council #4)
59
+ const started = await startE2bBridge(language, env, port, token);
60
+ if (!started)
61
+ return undefined;
62
+ return connectE2bLspBridge(env, port, token, opts);
63
+ }
42
64
  /** The single shared `LspServerManager` for the deployment (`RunnerDeps.lspManager`). */
43
65
  export function createE2bLspManager(opts) {
44
- // One bridge token per env+language, pinned across re-opens (heal after an idle-killed WS): the original
45
- // bridge keeps listening with the first token, so the reconnect must present the SAME one. WeakMap → a
46
- // destroyed task's tokens are collectible with its env.
47
- const tokens = new WeakMap();
66
+ // One bridge PROCESS + token per env+PORT not per env+language. `portForLanguage` maps typescript and
67
+ // javascript onto the SAME port (they share `SERVER_CMD`): keying by language minted two auth tokens for the
68
+ // one listening bridge (HRD-LSP-4) and re-invoked `startBackground` on an already-bound port on every open.
69
+ // WeakMap a destroyed task's bridge bookkeeping is collectible with its env.
70
+ const bridges = new WeakMap();
48
71
  return new E2bLspManager({
49
72
  log: opts?.log,
50
- transportFactory: (language, env) => {
51
- let perLang = tokens.get(env);
52
- if (!perLang) {
53
- perLang = new Map();
54
- tokens.set(env, perLang);
73
+ transportFactory: async (language, env) => {
74
+ if (!SERVER_CMD[language])
75
+ return undefined; // no server for this language → graceful degrade (mirrors
76
+ // openE2bLspTransport's own guard; MUST run before touching `bridges` — `portForLanguage` falls back to
77
+ // port 8123 for an unmapped language, which would otherwise silently borrow typescript's live bridge)
78
+ const port = portForLanguage(language);
79
+ let perPort = bridges.get(env);
80
+ if (!perPort) {
81
+ perPort = new Map();
82
+ bridges.set(env, perPort);
55
83
  }
56
- let token = perLang.get(language);
57
- if (!token) {
58
- token = opts?.token ?? randomUUID();
59
- perLang.set(language, token);
84
+ let bridge = perPort.get(port);
85
+ if (!bridge) {
86
+ const token = opts?.token ?? randomUUID();
87
+ bridge = { token, ready: startE2bBridge(language, env, port, token) };
88
+ perPort.set(port, bridge); // synchronous — no await above (run-to-completion dedupe guard, see E2bBridgeHandle.ready doc)
60
89
  }
61
- return openE2bLspTransport(language, env, { ...opts, token });
90
+ const started = await bridge.ready;
91
+ if (!started)
92
+ return undefined;
93
+ return connectE2bLspBridge(env, port, bridge.token, opts);
62
94
  },
63
95
  });
64
96
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/server",
3
- "version": "3.22.0",
3
+ "version": "3.23.0",
4
4
  "description": "Sema Server — the server/API implementation layer for Sema, wiring core, registry, model providers, and cloud agent execution. Built on @sema-agent/core.",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",