@sleep2agi/commhub-server 0.9.0-preview.216 → 0.9.0-preview.218

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.216",
3
+ "version": "0.9.0-preview.218",
4
4
  "description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -12,6 +12,7 @@ import {
12
12
  EDITABLE_CHANNELS,
13
13
  isAllowedToChangeFlag,
14
14
  computeApplyMode,
15
+ readOpencodeSnapshotFlags,
15
16
  validatePatch,
16
17
  narrowChannelsPatch,
17
18
  } from "./config-apply-validate";
@@ -182,6 +183,67 @@ describe("computeApplyMode — tier classifier (RFC-024 §4)", () => {
182
183
  });
183
184
  });
184
185
 
186
+ // #3146 —— 客户端「切模型不必重启」。agent-node 从 OpenCode V2 共存起就能
187
+ // 在运行中的 TUI 会话里换模型,但 hub 把所有 `model` patch 一律判成
188
+ // restart,于是客户端显示「重启中」而节点永远不会重启。
189
+ describe("computeApplyMode — OpenCode V2 hot model switch (#3146)", () => {
190
+ const v2Copresence = {
191
+ runtime: "opencode-sdk",
192
+ opencodeGeneration: "v2" as const,
193
+ opencodeMode: "copresence",
194
+ };
195
+
196
+ test("model alone on an OpenCode V2 co-presence node → hot", () => {
197
+ expect(computeApplyMode("deepseek/deepseek-flash", {}, undefined, v2Copresence)).toBe("hot");
198
+ });
199
+
200
+ test("runtime spelling aliases all resolve to hot (opencode-cli / opencode / opencode-sdk)", () => {
201
+ for (const runtime of ["opencode-sdk", "opencode-cli", "opencode"]) {
202
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, runtime })).toBe("hot");
203
+ }
204
+ });
205
+
206
+ test("model alone without opts keeps the pre-#3146 restart answer", () => {
207
+ expect(computeApplyMode("deepseek/deepseek-flash", {})).toBe("restart");
208
+ });
209
+
210
+ test("v1 node → restart (no live V2 session to switch)", () => {
211
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeGeneration: "v1" })).toBe("restart");
212
+ });
213
+
214
+ test("unknown generation → restart", () => {
215
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeGeneration: null })).toBe("restart");
216
+ });
217
+
218
+ test("headless V2 node → restart (no co-presence session to drive)", () => {
219
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeMode: "headless" })).toBe("restart");
220
+ });
221
+
222
+ test("non-OpenCode runtime → restart", () => {
223
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, runtime: "codex-app-server-sdk" })).toBe("restart");
224
+ });
225
+
226
+ test("model + any flag → restart (mixed patch stays on the restart path)", () => {
227
+ expect(computeApplyMode("m", { maxTurns: 50 }, undefined, v2Copresence)).toBe("restart");
228
+ expect(computeApplyMode("m", { timeout: 60000 }, undefined, v2Copresence)).toBe("restart");
229
+ });
230
+
231
+ test("model + channels → restart", () => {
232
+ expect(computeApplyMode("m", {}, ["feishu"], v2Copresence)).toBe("restart");
233
+ });
234
+
235
+ test("readOpencodeSnapshotFlags parses text, object, and junk", () => {
236
+ expect(readOpencodeSnapshotFlags('{"flags":{"opencodeGeneration":"v2","opencodeMode":"copresence"}}'))
237
+ .toEqual({ opencodeGeneration: "v2", opencodeMode: "copresence" });
238
+ expect(readOpencodeSnapshotFlags({ flags: { opencodeGeneration: "v1" } }))
239
+ .toEqual({ opencodeGeneration: "v1", opencodeMode: null });
240
+ expect(readOpencodeSnapshotFlags("not json")).toEqual({ opencodeGeneration: null, opencodeMode: null });
241
+ expect(readOpencodeSnapshotFlags(null)).toEqual({ opencodeGeneration: null, opencodeMode: null });
242
+ expect(readOpencodeSnapshotFlags('{"flags":{"opencodeGeneration":"v9"}}'))
243
+ .toEqual({ opencodeGeneration: null, opencodeMode: null });
244
+ });
245
+ });
246
+
185
247
  describe("validatePatch — model field", () => {
186
248
  test("undefined model passes (no change)", () => {
187
249
  expect(validatePatch(undefined, {})).toBeNull();
@@ -149,6 +149,82 @@ export function isAllowedToChangeFlag(
149
149
  return null;
150
150
  }
151
151
 
152
+ /**
153
+ * Runtime families the hub treats as "OpenCode". `nodes.runtime` is
154
+ * written from report_status and carries the legacy `-sdk` bucket
155
+ * (`opencode-sdk`) for older CLI builds, while newer callers pass the
156
+ * config-level spelling (`opencode-cli` / `opencode`). All three mean
157
+ * the same agent-node runtime, so the hot-model-switch gate below must
158
+ * accept every spelling — otherwise the same node flips between hot
159
+ * and restart depending on which build reported last.
160
+ */
161
+ const OPENCODE_RUNTIME_LABELS = new Set<string>(["opencode-sdk", "opencode-cli", "opencode"]);
162
+
163
+ /**
164
+ * Read the OpenCode knobs the hub persists in `nodes.config_snapshot`.
165
+ * Both are reported by agent-node (see buildConfigSnapshot in
166
+ * agent-node/src/runtime/config-apply.ts) and are the only two fields
167
+ * the apply-mode decision needs.
168
+ *
169
+ * Snapshot is stored as text but older rows hold objects; a parse
170
+ * failure means "this cell is empty" (never an exception) — same
171
+ * fail-shape as the api-nodes projection.
172
+ */
173
+ export function readOpencodeSnapshotFlags(configSnapshot: unknown): {
174
+ opencodeGeneration: "v1" | "v2" | null;
175
+ opencodeMode: string | null;
176
+ } {
177
+ let parsed: any = null;
178
+ try {
179
+ parsed = typeof configSnapshot === "string"
180
+ ? (configSnapshot ? JSON.parse(configSnapshot) : null)
181
+ : configSnapshot;
182
+ } catch {
183
+ parsed = null;
184
+ }
185
+ const flags = parsed?.flags;
186
+ const generation = flags?.opencodeGeneration;
187
+ const mode = flags?.opencodeMode;
188
+ return {
189
+ opencodeGeneration: generation === "v1" || generation === "v2" ? generation : null,
190
+ opencodeMode: typeof mode === "string" && mode.length <= 32 ? mode : null,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * True when the node can swap the live model without a process restart.
196
+ *
197
+ * Mirrors `computeApplyMode` in agent-node/src/runtime/config-apply.ts
198
+ * (#3146). The node has been able to do this since OpenCode V2
199
+ * co-presence shipped, but the hub classified every `model` patch as
200
+ * `restart`, so the client showed "restarting" and waited for a
201
+ * restart that the node deliberately never performed. Hub and node now
202
+ * agree on the same three conditions:
203
+ *
204
+ * runtime ∈ OpenCode · opencodeGeneration === "v2" · mode === "copresence"
205
+ *
206
+ * `copresence` is required because the hot switch drives the running
207
+ * TUI session (`opencodeCopresenceSession.setSelectedModel`); a
208
+ * headless V2 node has no such session and must restart. Only a
209
+ * model-ONLY patch qualifies — adding flags or channels drags in
210
+ * restart-tier fields, and the node would restart anyway.
211
+ */
212
+ export function isHotModelSwitchSupported(
213
+ model: string | undefined,
214
+ flags: Record<string, unknown>,
215
+ channels: string[] | undefined,
216
+ runtime: string | null | undefined,
217
+ opencodeGeneration: "v1" | "v2" | null,
218
+ opencodeMode: string | null,
219
+ ): boolean {
220
+ if (model === undefined) return false;
221
+ if (Object.keys(flags).length !== 0) return false;
222
+ if (channels !== undefined) return false;
223
+ if (!runtime || !OPENCODE_RUNTIME_LABELS.has(runtime)) return false;
224
+ if (opencodeGeneration !== "v2") return false;
225
+ return opencodeMode === "copresence";
226
+ }
227
+
152
228
  /**
153
229
  * Classify the patch's required apply mode. Empty patch (model + flags
154
230
  * both empty, no channels) → "restart_only" (used by restart_node tool).
@@ -157,15 +233,34 @@ export function isAllowedToChangeFlag(
157
233
  * once at boot in agent-node/src/cli.ts and forks per-channel workers
158
234
  * from it, so a channel enable/disable takes effect on process restart
159
235
  * only — see #260 P5 wire discipline). Otherwise → "hot".
236
+ *
237
+ * `opts` carries the target node's runtime identity. Callers that omit
238
+ * it get the pre-#3146 behaviour (model ⇒ restart), which is the safe
239
+ * answer for any node we know nothing about.
160
240
  */
161
241
  export function computeApplyMode(
162
242
  model: string | undefined,
163
243
  flags: Record<string, unknown>,
164
244
  channels?: string[] | undefined,
245
+ opts?: {
246
+ runtime?: string | null;
247
+ opencodeGeneration?: "v1" | "v2" | null;
248
+ opencodeMode?: string | null;
249
+ },
165
250
  ): "hot" | "restart" | "restart_only" {
166
251
  const fieldCount = (model !== undefined ? 1 : 0) + Object.keys(flags).length + (channels !== undefined ? 1 : 0);
167
252
  if (fieldCount === 0) return "restart_only";
168
- if (model !== undefined) return "restart";
253
+ if (model !== undefined) {
254
+ if (isHotModelSwitchSupported(
255
+ model,
256
+ flags,
257
+ channels,
258
+ opts?.runtime,
259
+ opts?.opencodeGeneration ?? null,
260
+ opts?.opencodeMode ?? null,
261
+ )) return "hot";
262
+ return "restart";
263
+ }
169
264
  if (channels !== undefined) return "restart";
170
265
  for (const key of Object.keys(flags)) {
171
266
  if (RESTART_REQUIRED_FLAGS.has(key)) return "restart";
@@ -358,6 +358,8 @@ describe("#698 atomic peer reply", () => {
358
358
  expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM tasks WHERE parent_task_id = ?1", taskId)?.n).toBe(0);
359
359
  });
360
360
 
361
+ // #3259 收口 —— 迟到通道只对「终态但没成功交付过回复」的任务开放;
362
+ // `replied` 的任务再补就是重复投递,仍然必须以 reply_task_terminal 拒绝。
361
363
  test("terminal replay is rejected and cannot deliver twice", async () => {
362
364
  const taskId = await dispatch(A, B, "idempotent work");
363
365
  const handler = toolsFor(B).send_peer_reply;
@@ -204,7 +204,11 @@ describe("#464 stuck timeout", () => {
204
204
  const inboxBefore = db.get<any>("SELECT COUNT(*) AS n FROM inbox WHERE network_id = ?1", NET).n;
205
205
  const out = await nodeReply({ alias: "scheduler", text: "late answer", in_reply_to: first.taskId, status: "replied", from_session: ALIAS });
206
206
  expect(out.ok).toBe(false);
207
- expect(out.error).toBe("reply_task_terminal");
207
+ // #3259 / .216 —— 到期任务不再以 reply_task_terminal 一刀切拒绝:迟到的回复
208
+ // 会进入「迟到结果」通道(task_late_replies,任务行保持 expired)。而这条通道
209
+ // 只对**执行节点**开放,这里是从 from_session 的路由回执,因此被按节点令牌拦下。
210
+ // 结论不变:这次回复什么都没改(下面几条断言仍然检查这一点)。
211
+ expect(out.error).toBe("late_reply_node_token_required");
208
212
  expect(out.reply_queued).toBe(false);
209
213
  expect(taskRow(first.taskId!).status).toBe("expired");
210
214
  expect(runRow(first.runId).status).toBe("expired");
@@ -235,8 +235,10 @@ describe("#519 at 72h", () => {
235
235
  withHours("72", () => patrol());
236
236
  expect(taskRow(a.id).status).toBe("expired");
237
237
  const r = await tool(nodes.target.token, "send_reply", { in_reply_to: a.id, text: "late answer", status: "replied", network_id: NET });
238
- expect(r.ok).toBe(false);
239
- expect(r.error).toBe("reply_task_terminal");
238
+ // #3259 / .216 —— 执行节点的迟到结果不再被 reply_task_terminal 拒绝:
239
+ // 它作为 task_late_replies 追加,任务行**保持 expired**(迟到 ≠ 追认成功)。
240
+ expect(r.ok).toBe(true);
241
+ expect(r.late).toBe(true);
240
242
  expect(taskRow(a.id).status).toBe("expired");
241
243
  });
242
244
 
package/src/tools.ts CHANGED
@@ -98,6 +98,7 @@ import {
98
98
  SECURITY_SENSITIVE_FLAGS,
99
99
  EDITABLE_CHANNELS,
100
100
  computeApplyMode,
101
+ readOpencodeSnapshotFlags,
101
102
  validatePatch,
102
103
  narrowChannelsPatch,
103
104
  isAllowedToChangeFlag,
@@ -2536,7 +2537,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
2536
2537
  let lateSql = "SELECT status,from_name,to_node_id,thread_id,turn_id FROM tasks WHERE task_id=?1";
2537
2538
  lateSql = addScope(lateSql, lateParams, effectiveNetId);
2538
2539
  const lateCandidate = db.get<LateTask>(lateSql, ...lateParams) ?? null;
2539
- if (lateCandidate && !["created", "delivered", "acked", "running"].includes(lateCandidate.status)) {
2540
+ // #3259 收口 —— 迟到通道只对「终态但**没有成功交付回复**」的任务开放。
2541
+ // `replied` 的任务发送方已经拿到了结果,再补一次就是重复投递
2542
+ // (#698 的 idempotency 测试就是这条:replay 不能变成第二条 inbox 回复)。
2543
+ if (lateCandidate && lateCandidate.status !== "replied"
2544
+ && !["created", "delivered", "acked", "running"].includes(lateCandidate.status)) {
2540
2545
  if (workSignal.outcome) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "scheduled_work_outcome_terminal", reply_queued: false }) }] };
2541
2546
  // Old runtimes do not send turn identity and retain the old result.
2542
2547
  // #3061 续 —— 任务**从未记下 turn 上下文**时,不该再要求调用方凭空给出 id。
@@ -3730,7 +3735,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3730
3735
 
3731
3736
  // Compute apply_mode + persist + push doorbell.
3732
3737
  const updateId = `cu_${uuidv4()}`;
3733
- const applyMode = computeApplyMode(model, flags, channels);
3738
+ // #3146 —— 把目标节点的 runtime 身份带进分类器。OpenCode V2 共存
3739
+ // 节点可以在 TUI 会话里就地换模型(agent-node 侧早就能,见
3740
+ // agent-node/src/runtime/config-apply.ts);不带这三个字段时
3741
+ // computeApplyMode 退回旧行为(model ⇒ restart),那正是客户端
3742
+ // 显示「重启中」却永远等不到重启的原因。
3743
+ const opencodeSnap = readOpencodeSnapshotFlags(node.config_snapshot);
3744
+ const applyMode = computeApplyMode(model, flags, channels, {
3745
+ runtime: node.runtime,
3746
+ opencodeGeneration: opencodeSnap.opencodeGeneration,
3747
+ opencodeMode: opencodeSnap.opencodeMode,
3748
+ });
3734
3749
  const patchJson = JSON.stringify({
3735
3750
  ...(model !== undefined ? { model } : {}),
3736
3751
  flags,