@sleep2agi/commhub-server 0.9.0-preview.217 → 0.9.0-preview.219

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.217",
3
+ "version": "0.9.0-preview.219",
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,8 @@ import {
12
12
  EDITABLE_CHANNELS,
13
13
  isAllowedToChangeFlag,
14
14
  computeApplyMode,
15
+ readOpencodeSnapshotFlags,
16
+ readConfigUpdateCapable,
15
17
  validatePatch,
16
18
  narrowChannelsPatch,
17
19
  } from "./config-apply-validate";
@@ -182,6 +184,67 @@ describe("computeApplyMode — tier classifier (RFC-024 §4)", () => {
182
184
  });
183
185
  });
184
186
 
187
+ // #3146 —— 客户端「切模型不必重启」。agent-node 从 OpenCode V2 共存起就能
188
+ // 在运行中的 TUI 会话里换模型,但 hub 把所有 `model` patch 一律判成
189
+ // restart,于是客户端显示「重启中」而节点永远不会重启。
190
+ describe("computeApplyMode — OpenCode V2 hot model switch (#3146)", () => {
191
+ const v2Copresence = {
192
+ runtime: "opencode-sdk",
193
+ opencodeGeneration: "v2" as const,
194
+ opencodeMode: "copresence",
195
+ };
196
+
197
+ test("model alone on an OpenCode V2 co-presence node → hot", () => {
198
+ expect(computeApplyMode("deepseek/deepseek-flash", {}, undefined, v2Copresence)).toBe("hot");
199
+ });
200
+
201
+ test("runtime spelling aliases all resolve to hot (opencode-cli / opencode / opencode-sdk)", () => {
202
+ for (const runtime of ["opencode-sdk", "opencode-cli", "opencode"]) {
203
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, runtime })).toBe("hot");
204
+ }
205
+ });
206
+
207
+ test("model alone without opts keeps the pre-#3146 restart answer", () => {
208
+ expect(computeApplyMode("deepseek/deepseek-flash", {})).toBe("restart");
209
+ });
210
+
211
+ test("v1 node → restart (no live V2 session to switch)", () => {
212
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeGeneration: "v1" })).toBe("restart");
213
+ });
214
+
215
+ test("unknown generation → restart", () => {
216
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeGeneration: null })).toBe("restart");
217
+ });
218
+
219
+ test("headless V2 node → restart (no co-presence session to drive)", () => {
220
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, opencodeMode: "headless" })).toBe("restart");
221
+ });
222
+
223
+ test("non-OpenCode runtime → restart", () => {
224
+ expect(computeApplyMode("m", {}, undefined, { ...v2Copresence, runtime: "codex-app-server-sdk" })).toBe("restart");
225
+ });
226
+
227
+ test("model + any flag → restart (mixed patch stays on the restart path)", () => {
228
+ expect(computeApplyMode("m", { maxTurns: 50 }, undefined, v2Copresence)).toBe("restart");
229
+ expect(computeApplyMode("m", { timeout: 60000 }, undefined, v2Copresence)).toBe("restart");
230
+ });
231
+
232
+ test("model + channels → restart", () => {
233
+ expect(computeApplyMode("m", {}, ["feishu"], v2Copresence)).toBe("restart");
234
+ });
235
+
236
+ test("readOpencodeSnapshotFlags parses text, object, and junk", () => {
237
+ expect(readOpencodeSnapshotFlags('{"flags":{"opencodeGeneration":"v2","opencodeMode":"copresence"}}'))
238
+ .toEqual({ opencodeGeneration: "v2", opencodeMode: "copresence" });
239
+ expect(readOpencodeSnapshotFlags({ flags: { opencodeGeneration: "v1" } }))
240
+ .toEqual({ opencodeGeneration: "v1", opencodeMode: null });
241
+ expect(readOpencodeSnapshotFlags("not json")).toEqual({ opencodeGeneration: null, opencodeMode: null });
242
+ expect(readOpencodeSnapshotFlags(null)).toEqual({ opencodeGeneration: null, opencodeMode: null });
243
+ expect(readOpencodeSnapshotFlags('{"flags":{"opencodeGeneration":"v9"}}'))
244
+ .toEqual({ opencodeGeneration: null, opencodeMode: null });
245
+ });
246
+ });
247
+
185
248
  describe("validatePatch — model field", () => {
186
249
  test("undefined model passes (no change)", () => {
187
250
  expect(validatePatch(undefined, {})).toBeNull();
@@ -391,3 +454,18 @@ describe("Codex config flags (#815)", () => {
391
454
  .toBe("flags.modelReasoningEffort");
392
455
  });
393
456
  });
457
+
458
+ // 裸起节点(无 supervisor)收到 restart-tier 变更会安静地死掉:
459
+ // 写配置 → ack restarting → exit 75 → 没人拉起 → 更新判 timeout,
460
+ // 而调用方只看到「超时」。这里锁住「把后果说在前面」的读法。
461
+ describe("readConfigUpdateCapable", () => {
462
+ test("true / false / absent / junk", () => {
463
+ expect(readConfigUpdateCapable('{"config_update_capable":true}')).toBe(true);
464
+ expect(readConfigUpdateCapable('{"config_update_capable":false}')).toBe(false);
465
+ expect(readConfigUpdateCapable('{"model":"x"}')).toBeNull();
466
+ expect(readConfigUpdateCapable("not json")).toBeNull();
467
+ expect(readConfigUpdateCapable(null)).toBeNull();
468
+ // 非布尔一律 unknown,不能当成 false —— 否则会给没上报的节点发警告
469
+ expect(readConfigUpdateCapable('{"config_update_capable":"false"}')).toBeNull();
470
+ });
471
+ });
@@ -149,6 +149,109 @@ 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
+
228
+ /**
229
+ * Read `config_update_capable` from `nodes.config_snapshot`.
230
+ *
231
+ * agent-node reports this as "this process runs under a supervisor wrapper that
232
+ * honours the sentinel-75 restart path" (agent-node/src/cli.ts report_status).
233
+ * A bare-spawn node (`nohup node cli.js …`, no pm2/anet wrapper) reports
234
+ * `false` — and a restart-tier patch on such a node writes the config, acks
235
+ * `restarting`, exits 75, and **nothing respawns it**. The update then sits in
236
+ * `pending`/`restarting` until the 60s reaper marks it `timeout`, so the caller
237
+ * only ever sees "timed out" and never learns that the node is now down.
238
+ *
239
+ * Absent/unparseable snapshot → `null` ("unknown"), never `false`: we must not
240
+ * warn on nodes that simply haven't reported it yet.
241
+ */
242
+ export function readConfigUpdateCapable(configSnapshot: unknown): boolean | null {
243
+ let parsed: any = null;
244
+ try {
245
+ parsed = typeof configSnapshot === "string"
246
+ ? (configSnapshot ? JSON.parse(configSnapshot) : null)
247
+ : configSnapshot;
248
+ } catch {
249
+ return null;
250
+ }
251
+ const value = parsed?.config_update_capable;
252
+ return typeof value === "boolean" ? value : null;
253
+ }
254
+
152
255
  /**
153
256
  * Classify the patch's required apply mode. Empty patch (model + flags
154
257
  * both empty, no channels) → "restart_only" (used by restart_node tool).
@@ -157,15 +260,34 @@ export function isAllowedToChangeFlag(
157
260
  * once at boot in agent-node/src/cli.ts and forks per-channel workers
158
261
  * from it, so a channel enable/disable takes effect on process restart
159
262
  * only — see #260 P5 wire discipline). Otherwise → "hot".
263
+ *
264
+ * `opts` carries the target node's runtime identity. Callers that omit
265
+ * it get the pre-#3146 behaviour (model ⇒ restart), which is the safe
266
+ * answer for any node we know nothing about.
160
267
  */
161
268
  export function computeApplyMode(
162
269
  model: string | undefined,
163
270
  flags: Record<string, unknown>,
164
271
  channels?: string[] | undefined,
272
+ opts?: {
273
+ runtime?: string | null;
274
+ opencodeGeneration?: "v1" | "v2" | null;
275
+ opencodeMode?: string | null;
276
+ },
165
277
  ): "hot" | "restart" | "restart_only" {
166
278
  const fieldCount = (model !== undefined ? 1 : 0) + Object.keys(flags).length + (channels !== undefined ? 1 : 0);
167
279
  if (fieldCount === 0) return "restart_only";
168
- if (model !== undefined) return "restart";
280
+ if (model !== undefined) {
281
+ if (isHotModelSwitchSupported(
282
+ model,
283
+ flags,
284
+ channels,
285
+ opts?.runtime,
286
+ opts?.opencodeGeneration ?? null,
287
+ opts?.opencodeMode ?? null,
288
+ )) return "hot";
289
+ return "restart";
290
+ }
169
291
  if (channels !== undefined) return "restart";
170
292
  for (const key of Object.keys(flags)) {
171
293
  if (RESTART_REQUIRED_FLAGS.has(key)) return "restart";
package/src/tools.ts CHANGED
@@ -98,6 +98,8 @@ import {
98
98
  SECURITY_SENSITIVE_FLAGS,
99
99
  EDITABLE_CHANNELS,
100
100
  computeApplyMode,
101
+ readOpencodeSnapshotFlags,
102
+ readConfigUpdateCapable,
101
103
  validatePatch,
102
104
  narrowChannelsPatch,
103
105
  isAllowedToChangeFlag,
@@ -3734,7 +3736,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3734
3736
 
3735
3737
  // Compute apply_mode + persist + push doorbell.
3736
3738
  const updateId = `cu_${uuidv4()}`;
3737
- const applyMode = computeApplyMode(model, flags, channels);
3739
+ // #3146 —— 把目标节点的 runtime 身份带进分类器。OpenCode V2 共存
3740
+ // 节点可以在 TUI 会话里就地换模型(agent-node 侧早就能,见
3741
+ // agent-node/src/runtime/config-apply.ts);不带这三个字段时
3742
+ // computeApplyMode 退回旧行为(model ⇒ restart),那正是客户端
3743
+ // 显示「重启中」却永远等不到重启的原因。
3744
+ const opencodeSnap = readOpencodeSnapshotFlags(node.config_snapshot);
3745
+ const applyMode = computeApplyMode(model, flags, channels, {
3746
+ runtime: node.runtime,
3747
+ opencodeGeneration: opencodeSnap.opencodeGeneration,
3748
+ opencodeMode: opencodeSnap.opencodeMode,
3749
+ });
3738
3750
  const patchJson = JSON.stringify({
3739
3751
  ...(model !== undefined ? { model } : {}),
3740
3752
  flags,
@@ -3748,10 +3760,29 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
3748
3760
 
3749
3761
  pushEvent(node.alias, { type: "config_update", update_id: updateId }, networkId);
3750
3762
 
3763
+ // 裸起节点(无 supervisor)收到 restart-tier 变更会 **安静地死掉**:
3764
+ // 它写配置 → ack restarting → exit 75,而没人拉起;
3765
+ // 更新停在 pending/restarting,60s 后被 reaper 判 timeout ——
3766
+ // 调用方看到的只有「超时」,永远学不到「这台节点现在是下线的」。
3767
+ // 不擅自拒绝(会破坏合法流程),但必须把后果说在前面。
3768
+ const configUpdateCapable = readConfigUpdateCapable(node.config_snapshot);
3769
+ const warnings = applyMode !== "hot" && configUpdateCapable === false
3770
+ ? [{
3771
+ code: "restart_requires_supervisor",
3772
+ message: "this node reports config_update_capable=false (bare spawn, no supervisor). "
3773
+ + "A restart-tier patch will make it exit 75 and nothing will respawn it — the update "
3774
+ + "will time out and the node will stay offline. Use Stop then Start, or a supervised "
3775
+ + "process (anet start / pm2) before sending restart-tier changes.",
3776
+ }]
3777
+ : undefined;
3778
+
3751
3779
  return {
3752
3780
  content: [{
3753
3781
  type: "text" as const,
3754
- text: JSON.stringify({ ok: true, update_id: updateId, apply_mode: applyMode }),
3782
+ text: JSON.stringify({
3783
+ ok: true, update_id: updateId, apply_mode: applyMode,
3784
+ ...(warnings ? { warnings } : {}),
3785
+ }),
3755
3786
  }],
3756
3787
  };
3757
3788
  },