@sleep2agi/commhub-server 0.9.0-preview.1 → 0.9.0-preview.13

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/src/tools.ts CHANGED
@@ -1,8 +1,48 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod/v4";
3
- import { db, uuidv4, logTaskEvent, chainReplyToParent } from "./db.js";
3
+ import { db, uuidv4, logTaskEvent, chainReplyToParent, hashToken, generateId, generateNetworkToken } from "./db.js";
4
4
  import { pushEvent } from "./push.js";
5
- import { getUserNetworkRole } from "./auth.js";
5
+ import { assertNodeActive } from "./lifecycle-guard.js";
6
+ import { getUserNetworkRole, createNetworkTokenForNode } from "./auth.js";
7
+ import {
8
+ buildAnetArgs as _unused_buildAnetArgs, // ensure module is loaded
9
+ validateName as validateChildName,
10
+ validateRuntime,
11
+ validateModel,
12
+ validateChannelsP1,
13
+ validateEnvRefs,
14
+ FLAG_KEYS,
15
+ validateFlagValue,
16
+ ValidationError,
17
+ } from "./create-node-validate.js";
18
+ import {
19
+ putPendingEnvBlob,
20
+ takePendingEnvBlob,
21
+ newRequestId,
22
+ finalizeCreateOnFirstRegister,
23
+ startPendingEnvGcTimer,
24
+ startSweeperTimer,
25
+ auditCreateNode,
26
+ auditCreateNodeStrict,
27
+ resolveCallerDaemonTokenBound as _resolveCallerDaemonTokenBound,
28
+ } from "./create-node.js";
29
+ import {
30
+ vaultUpsert, vaultGet, vaultListKeys, vaultDelete,
31
+ VaultError,
32
+ } from "./vault.js";
33
+ import { stripHostLocalPathsForCrossHostSafe } from "./uploads.js";
34
+ import {
35
+ validateBaseUrl as _validateBaseUrl,
36
+ SUPPORTED_VENDORS,
37
+ ProbeValidationError,
38
+ } from "./probe-validate.js";
39
+ import {
40
+ putPendingProbeSecret,
41
+ newProbeId,
42
+ finalizeProbeAck,
43
+ startPendingProbeGcTimer,
44
+ startProbeSweeperTimer,
45
+ } from "./probe.js";
6
46
  import { canonicalAliasExists, cleanupRenamedAliasSession, resolveCanonicalAlias } from "./rename.js";
7
47
  import {
8
48
  ALLOWED_FLAGS,
@@ -24,7 +64,12 @@ function parseMetaJson(value: unknown): unknown | null {
24
64
 
25
65
  function normalizeMetaJson(meta: unknown): string | null {
26
66
  if (!meta || typeof meta !== "object") return null;
27
- try { return JSON.stringify(meta); } catch { return null; }
67
+ // #222 cross-host safety — strip `path` from meta.attachments[] when
68
+ // `file_id` is also present. Shared helper lives in uploads.ts so the
69
+ // REST handler in index.ts can apply the identical sanitization
70
+ // (otherwise REST and MCP transports would have different meta_json
71
+ // shapes for the same send).
72
+ try { return JSON.stringify(stripHostLocalPathsForCrossHostSafe(meta)); } catch { return null; }
28
73
  }
29
74
 
30
75
  export function registerTools(server: McpServer, clientIP?: string, enforceNetworkId?: string | null, enforceUserId?: string | null, callerAlias?: string | null, callerTokenIsNetwork = false, callerTokenId?: string | null) {
@@ -104,6 +149,14 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
104
149
  return { networkId: null, networkIds: getReadableNetworkIds() };
105
150
  };
106
151
 
152
+ // RFC-027 §2.3 race-free invariant — assertNodeActive lives in
153
+ // server/src/lifecycle-guard.ts so REST handlers in server/src/index.ts
154
+ // can use the SAME code path. PR1.1 had it inline here; PR1.2a
155
+ // (#346 review catch) extracted because the closure scope made it
156
+ // unreachable from REST and left the §2.3 race open on dashboard
157
+ // Dispatch (POST /api/task + /api/broadcast). Per
158
+ // [[feedback_grep_all_sites_before_apply_guard]].
159
+
107
160
  const addReadScope = (sql: string, params: any[], scope: ReadScope, column = "network_id"): string => {
108
161
  if (scope.networkId) {
109
162
  sql += ` AND ${column} = ?${params.length + 1}`;
@@ -257,6 +310,21 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
257
310
  flags: z.record(z.unknown()).optional(),
258
311
  config_revision: z.number().int().min(0).optional(),
259
312
  config_update_capable: z.boolean().optional(),
313
+ // RFC-026 P2 / #338 — daemon role surfaced for hub /api/nodes
314
+ // discovery (#337 extracts this field). "host_supervisor" =
315
+ // anet daemon. Default-stripping zod would drop this otherwise.
316
+ role: z.string().max(64).optional().nullable(),
317
+ // RFC-026 §9.3 / #338 PR3 — daemon self-declare nested under
318
+ // `daemon_capabilities` (canonical shape per existing hub reads
319
+ // at tools.ts:2010/2075 — PR1/PR2 placed these top-level, hub
320
+ // never saw them, max_concurrent_children stayed default + the
321
+ // allowlists stayed unenforced. PR3 nit ① per 通信龙).
322
+ // Soft caps avoid abuse via attacker daemon.
323
+ daemon_capabilities: z.object({
324
+ runtimes_supported: z.array(z.string().max(64)).max(16).optional(),
325
+ allowed_secret_keys: z.array(z.string().max(64)).max(64).optional(),
326
+ max_concurrent_children: z.number().int().min(1).max(1000).optional(),
327
+ }).optional(),
260
328
  }).optional().describe("RFC-024 — masked node config snapshot"),
261
329
  },
262
330
  async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, version: ver, tmux_name: tmux, node_id, session_id, config_path, channels, model: mdl, node_name: nn, network_id: netId, host, process_telemetry: proc, config_snapshot: cfgSnap }) => {
@@ -815,6 +883,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
815
883
  return { content: [{ type: "text" as const, text: JSON.stringify(payload) }] };
816
884
  }
817
885
 
886
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 1/6).
887
+ {
888
+ const lc = assertNodeActive(targetAlias, effectiveNetId ?? null);
889
+ if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
890
+ }
891
+
818
892
  console.log(`[${ts()}] ${from_session} → send_task → ${targetAlias}: ${task.slice(0, 60)}${priority === "high" ? " [HIGH]" : ""}${canonical.renamed ? ` [renamed from ${alias}]` : ""}`);
819
893
  const id = uuidv4();
820
894
  const fromNodeId = resolveNodeIdForAlias(from_session, effectiveNetId);
@@ -910,6 +984,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
910
984
  const targetAlias = canonical.alias;
911
985
  const target = resolveDeliveryTarget(targetAlias, effectiveNetId);
912
986
  if (target.state === "not_found") return deliveryTargetReply(target)!;
987
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 2/6).
988
+ {
989
+ const lc = assertNodeActive(targetAlias, effectiveNetId ?? null);
990
+ if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
991
+ }
913
992
  console.log(`[${ts()}] ${from_session} → send_message → ${targetAlias}: ${message.slice(0, 60)}${canonical.renamed ? ` [renamed from ${alias}]` : ""}`);
914
993
  const id = uuidv4();
915
994
  db.run(
@@ -1001,6 +1080,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1001
1080
  }
1002
1081
  }
1003
1082
  const replyTargetNodeId = resolveNodeIdForAlias(alias, effectiveNetId);
1083
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 3/6).
1084
+ {
1085
+ const lc = assertNodeActive(alias, effectiveNetId ?? null);
1086
+ if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
1087
+ }
1004
1088
  const replyLogged = db.transaction(() => {
1005
1089
  db.run(
1006
1090
  `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
@@ -1135,6 +1219,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1135
1219
  if (!["failed", "expired", "cancelled"].includes(task.status)) {
1136
1220
  return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: `task status is ${task.status}, not retryable` }) }] };
1137
1221
  }
1222
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 4/6).
1223
+ {
1224
+ const lc = assertNodeActive(task.to_name, effectiveNetId ?? task.network_id ?? null);
1225
+ if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
1226
+ }
1138
1227
  db.transaction(() => {
1139
1228
  // Reset task status
1140
1229
  const updateParams: any[] = [task_id];
@@ -1282,6 +1371,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1282
1371
  const reassignedAlias = canonical.alias;
1283
1372
  const target = resolveDeliveryTarget(reassignedAlias, effectiveNetId ?? task.network_id ?? null);
1284
1373
  const newNodeId = target.state === "not_found" ? null : (target.session?.node_id ?? null);
1374
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 5/6).
1375
+ {
1376
+ const lc = assertNodeActive(reassignedAlias, effectiveNetId ?? task.network_id ?? null);
1377
+ if (!lc.ok) return { content: [{ type: "text" as const, text: JSON.stringify(lc) }] };
1378
+ }
1285
1379
  db.transaction(() => {
1286
1380
  // Ack old inbox to prevent original agent from picking it up
1287
1381
  const inboxParams: any[] = [task_id];
@@ -1327,6 +1421,12 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1327
1421
  const ids: string[] = [];
1328
1422
 
1329
1423
  for (const t of targets) {
1424
+ // RFC-027 §2.3 inbox-enqueue lifecycle guard (PR1.1 site 6/6).
1425
+ // Broadcast skips non-active recipients silently rather than
1426
+ // failing the entire send — broadcast semantics are best-effort
1427
+ // per-recipient and a stopped node simply gets nothing.
1428
+ const lc = assertNodeActive(t.alias, effectiveNetId ?? t.network_id ?? null);
1429
+ if (!lc.ok) continue;
1330
1430
  const id = uuidv4();
1331
1431
  db.run(
1332
1432
  `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, network_id)
@@ -1418,7 +1518,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1418
1518
  callerNetworkId: string | null,
1419
1519
  ): { row: any | null; sec1Ok: boolean } => {
1420
1520
  const row = db.get<any>(
1421
- "SELECT node_id, alias, network_id, config_revision FROM nodes WHERE node_id = ?1",
1521
+ "SELECT node_id, alias, network_id, config_revision, config_snapshot FROM nodes WHERE node_id = ?1",
1422
1522
  nodeId,
1423
1523
  );
1424
1524
  if (!row) return { row: null, sec1Ok: false };
@@ -1741,16 +1841,1513 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
1741
1841
  }
1742
1842
  const updateId = `cu_${uuidv4()}`;
1743
1843
  const networkId = node.network_id || "default";
1744
- db.run(
1745
- `INSERT INTO node_config_updates (update_id, node_id, network_id, patch_json, apply_mode, base_revision, status, created_at, created_by_token) VALUES (?1, ?2, ?3, '{}', 'restart_only', ?4, 'pending', ?5, ?6)`,
1746
- [updateId, nodeId, networkId, node.config_revision || 0, Date.now(), callerTokenId || "unknown"],
1747
- );
1844
+ // RFC-027 PR1.2a latent fix (#346 ack): restart_node must reset
1845
+ // lifecycle_state to 'active'. Otherwise a node that was previously
1846
+ // stop_node'd → 'stopped' would, after restart, stay marked
1847
+ // 'stopped' in the nodes table → the 6 MCP + 2 REST inbox guards
1848
+ // would refuse every routing attempt → node silently unreachable
1849
+ // (no error to operator, just no traffic). Pair the schema flip
1850
+ // with the config_updates INSERT inside one tx so we don't
1851
+ // half-commit if the dispatch INSERT throws.
1852
+ db.transaction(() => {
1853
+ db.run(
1854
+ `INSERT INTO node_config_updates (update_id, node_id, network_id, patch_json, apply_mode, base_revision, status, created_at, created_by_token) VALUES (?1, ?2, ?3, '{}', 'restart_only', ?4, 'pending', ?5, ?6)`,
1855
+ [updateId, nodeId, networkId, node.config_revision || 0, Date.now(), callerTokenId || "unknown"],
1856
+ );
1857
+ db.run(
1858
+ `UPDATE nodes SET lifecycle_state = 'active' WHERE node_id = ?1`,
1859
+ [nodeId],
1860
+ );
1861
+ });
1748
1862
  pushEvent(node.alias, { type: "restart", update_id: updateId }, networkId);
1749
1863
  return {
1750
1864
  content: [{ type: "text" as const, text: JSON.stringify({ ok: true, update_id: updateId, apply_mode: "restart_only" }) }],
1751
1865
  };
1752
1866
  },
1753
1867
  );
1868
+
1869
+ // ── RFC-026 P1 — create-node + host-daemon (3 MCP tools) ──────────
1870
+ // Background timers (GC + sweeper) are idempotent + cheap; safe to
1871
+ // call on every registerTools invocation (statless mode re-registers
1872
+ // per request). They unref themselves so don't hold the event loop.
1873
+ startPendingEnvGcTimer();
1874
+ startSweeperTimer();
1875
+
1876
+ // §4.1.4 C2 — caller daemon resolved via token-bound identity (NOT
1877
+ // alias). Thin closure over the module-level helper so callers in
1878
+ // this scope can use the captured request-level vars. The pure
1879
+ // helper lives in create-node.ts so unit tests call exactly the
1880
+ // same code path the tools do (per 通信龙 PR #299 nit 1 — no inline-
1881
+ // mirror SQL in tests).
1882
+ const resolveCallerDaemonTokenBound = () =>
1883
+ _resolveCallerDaemonTokenBound({ callerTokenIsNetwork, callerTokenId, enforceNetworkId });
1884
+
1885
+ // Helper — map a ValidationError thrown from create-node-validate
1886
+ // into the MCP-tool-call JSON reply shape.
1887
+ const validationFailReply = (e: unknown) => {
1888
+ if (e instanceof ValidationError) {
1889
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: e.code, ...(e.detail || {}) }) }] };
1890
+ }
1891
+ throw e;
1892
+ };
1893
+
1894
+ // RFC-026 §9.2.1 / #338 PR2 — list_host_supervisors.
1895
+ // Surfaces host_supervisor daemons in the caller's network with
1896
+ // online flag + declared capabilities. Replaces the prior `node_daemon_`
1897
+ // prefix heuristic (dashboard /api/anet/node-create) + the role-extract
1898
+ // path on /api/nodes (#337). Member脱敏 strips host_telemetry IP /
1899
+ // cpu / mem (per RFC-026 §6 #3 — daemons can leak internal topology
1900
+ // to non-admin readers). Revoked daemon ntoks filtered out via
1901
+ // join on api_tokens.revoked_at.
1902
+ server.tool(
1903
+ "list_host_supervisors",
1904
+ "List host_supervisor daemon nodes in the caller's network (online status + runtimes_supported + allowed_secret_keys + telemetry; member-脱敏). RFC-026 §9.2.1.",
1905
+ {
1906
+ network_id: z.string().max(200).optional(),
1907
+ },
1908
+ async ({ network_id: clientNetId }) => {
1909
+ // SEC-1 — use resolveReadScope, NOT getNetworkId. getNetworkId is
1910
+ // for write-tool helpers and pairs with `canWrite`; READ tools that
1911
+ // bypass canWrite and trust getNetworkId leak across tenants
1912
+ // (PR2 v1 BLOCKER per 通信龙 audit — utok_ caller with
1913
+ // enforceNetworkId=null could pass any network_id and read daemon
1914
+ // names + allowed_secret_keys for tenants they're not a member of).
1915
+ // resolveReadScope checks network_members for the user + denies
1916
+ // on non-membership, mirroring REST resolveRestNetworkScope.
1917
+ const readScope = resolveReadScope(clientNetId);
1918
+ if (readScope.denied) {
1919
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
1920
+ }
1921
+ // Caller role for 脱敏 decision (admin/owner = full, others = masked).
1922
+ // Use the resolved scope's networkId (the verified one), not the
1923
+ // unchecked clientNetId.
1924
+ const scopedNetId = readScope.networkId ?? null;
1925
+ const callerRole = enforceUserId && scopedNetId
1926
+ ? getUserNetworkRole(enforceUserId, scopedNetId)
1927
+ : null;
1928
+ // Network-bound tokens get full telemetry within their bound network
1929
+ // (already gate-locked by enforceNetworkId path of resolveReadScope).
1930
+ const isPrivileged = callerRole === "admin" || callerRole === "owner" || (!enforceUserId);
1931
+
1932
+ // Pull candidate daemons. Active-token EXISTS subquery handles BOTH
1933
+ // revoked daemon ntoks (revoked_at set) AND DELETEd token rows
1934
+ // (the standard revokeToken path deletes the row, not flagging
1935
+ // revoked_at — PR2 v1 SHOULD-FIX per 通信龙 audit). EXISTS naturally
1936
+ // dedupes if a daemon ever had multiple tokens (e.g. rotation; nit ⚪).
1937
+ let sql = `
1938
+ SELECT
1939
+ n.node_id, n.alias, n.hostname, n.network_id,
1940
+ n.runtimes_supported, n.allowed_secret_keys,
1941
+ n.created_at, n.updated_at,
1942
+ s.last_seen_at AS session_last_seen,
1943
+ s.status AS session_status,
1944
+ s.cpu_cores AS session_cpu_cores,
1945
+ s.mem_total_gb AS session_mem_total_gb,
1946
+ s.ip AS session_ip,
1947
+ n.config_snapshot
1948
+ FROM nodes n
1949
+ LEFT JOIN sessions s ON s.alias = n.alias AND (s.network_id = n.network_id OR s.network_id IS NULL)
1950
+ WHERE EXISTS (
1951
+ SELECT 1 FROM api_tokens t
1952
+ WHERE t.network_id = n.network_id
1953
+ AND t.name = 'node:' || n.alias
1954
+ AND t.revoked_at IS NULL
1955
+ )
1956
+ `;
1957
+ const sqlParams: any[] = [];
1958
+ sql = addReadScope(sql, sqlParams, readScope, "n.network_id");
1959
+ sql += ` ORDER BY n.updated_at DESC`;
1960
+ const rows = db.all<Record<string, any>>(sql, ...sqlParams);
1961
+
1962
+ // Filter to role=host_supervisor (read from config_snapshot;
1963
+ // schema-promoted columns runtimes_supported/allowed_secret_keys
1964
+ // are pre-extracted but role isn't a first-class column).
1965
+ const nowMs = Date.now();
1966
+ const ONLINE_MS = 60_000;
1967
+ const daemons = rows
1968
+ .map(r => {
1969
+ let snapRole: string | null = null;
1970
+ if (r.config_snapshot) {
1971
+ try {
1972
+ const parsed = typeof r.config_snapshot === "string" ? JSON.parse(r.config_snapshot) : r.config_snapshot;
1973
+ snapRole = typeof parsed?.role === "string" ? parsed.role : null;
1974
+ } catch { /* malformed snapshot — role stays null */ }
1975
+ }
1976
+ return { row: r, role: snapRole };
1977
+ })
1978
+ .filter(({ role }) => role === "host_supervisor")
1979
+ .map(({ row: r }) => {
1980
+ // online = sessions.last_seen_at within ONLINE_MS
1981
+ let online = false;
1982
+ let lastSeenAt: string | null = null;
1983
+ if (r.session_last_seen) {
1984
+ lastSeenAt = r.session_last_seen;
1985
+ const t = Date.parse(r.session_last_seen);
1986
+ if (!isNaN(t)) online = (nowMs - t) <= ONLINE_MS;
1987
+ }
1988
+ // Parse self-declare arrays (default to [] for pre-PR2 daemons)
1989
+ let runtimes: string[] = [];
1990
+ let secrets: string[] = [];
1991
+ try {
1992
+ if (r.runtimes_supported) {
1993
+ const parsed = JSON.parse(r.runtimes_supported);
1994
+ runtimes = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
1995
+ }
1996
+ } catch { /* malformed — empty */ }
1997
+ try {
1998
+ if (r.allowed_secret_keys) {
1999
+ const parsed = JSON.parse(r.allowed_secret_keys);
2000
+ secrets = Array.isArray(parsed) ? parsed.filter((s: unknown) => typeof s === "string") : [];
2001
+ }
2002
+ } catch { /* malformed — empty */ }
2003
+ // host_telemetry — member脱敏 drops IP/cpu/mem
2004
+ const telemetry: Record<string, unknown> = {
2005
+ alert_level: online ? "green" : "gray",
2006
+ };
2007
+ if (isPrivileged) {
2008
+ telemetry.cpu_cores = r.session_cpu_cores ?? null;
2009
+ telemetry.mem_gb = r.session_mem_total_gb ?? null;
2010
+ telemetry.ip_internal = r.session_ip ?? null;
2011
+ }
2012
+ return {
2013
+ daemon_node_id: r.node_id,
2014
+ alias: r.alias,
2015
+ hostname: r.hostname,
2016
+ online,
2017
+ last_seen_at: lastSeenAt,
2018
+ runtimes_supported: runtimes,
2019
+ allowed_secret_keys: secrets,
2020
+ host_telemetry: telemetry,
2021
+ };
2022
+ });
2023
+
2024
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, daemons, count: daemons.length }) }] };
2025
+ },
2026
+ );
2027
+
2028
+ // §2.5 step 1+2 — dashboard-facing tool. Validates spec, mint
2029
+ // child-ntok, stash env_blob in pendingEnvBlobs Map, write request
2030
+ // row (metadata only — no env_blob in SQL), pushEvent doorbell.
2031
+ server.tool(
2032
+ "create_node",
2033
+ "Create a node on a host-daemon and start it. Daemon forks `anet node create + start` on the target machine; child reports back to hub. RFC-026.",
2034
+ {
2035
+ daemon_node_id: z.string().min(1).max(200),
2036
+ node_spec: z.object({
2037
+ name: z.string().min(1).max(64),
2038
+ runtime: z.string().min(1).max(64),
2039
+ model: z.string().min(1).max(100),
2040
+ flags: z.record(z.unknown()).optional(),
2041
+ env_refs: z.array(z.string().max(64)).optional(),
2042
+ channels: z.array(z.unknown()).optional(),
2043
+ }),
2044
+ network_id: z.string().max(200).optional(),
2045
+ },
2046
+ async ({ daemon_node_id, node_spec, network_id: clientNetId }) => {
2047
+ const effectiveNetId = getNetworkId(clientNetId);
2048
+ if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
2049
+
2050
+ // §4.1.1 — admin+ for create_node (creating a node = pulling new
2051
+ // resource + burning API quota, one level above edit single flag)
2052
+ const callerRole = enforceUserId && effectiveNetId
2053
+ ? getUserNetworkRole(enforceUserId, effectiveNetId)
2054
+ : null;
2055
+ if (callerRole !== "admin" && callerRole !== "owner") {
2056
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "insufficient_role_for_create_node", required_role: "admin", caller_role: callerRole }) }] };
2057
+ }
2058
+
2059
+ // Daemon must exist + must be in caller's network + must be
2060
+ // online with role=host_supervisor capability.
2061
+ const { row: daemon, sec1Ok } = resolveTargetNode(daemon_node_id, effectiveNetId);
2062
+ if (!daemon) {
2063
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "daemon_not_found", daemon_node_id }) }] };
2064
+ }
2065
+ if (!sec1Ok) {
2066
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_node" }) }] };
2067
+ }
2068
+
2069
+ // Read daemon's host_supervisor capability + allowlist from its
2070
+ // last reported config_snapshot. PR3 (#338) canonical path is
2071
+ // `daemon_capabilities.runtimes_supported` (RFC-026 §9.3).
2072
+ // Pre-PR3 daemons (preview.10 and earlier) place these at the
2073
+ // TOP level of the snapshot rather than nested — those reads
2074
+ // return undefined here and `daemonAllowedRuntimes` stays null
2075
+ // (permissive — no allowlist enforcement); they fall back to
2076
+ // §4.2.2 structural validation only, identical to pre-PR3
2077
+ // behavior. No regression on in-flight daemons.
2078
+ let daemonAllowList = new Set<string>();
2079
+ let daemonAllowedRuntimes: string[] | null = null;
2080
+ try {
2081
+ const snap = daemon.config_snapshot ? JSON.parse(daemon.config_snapshot) : null;
2082
+ const caps = snap?.daemon_capabilities;
2083
+ if (Array.isArray(caps?.allowed_secret_keys)) {
2084
+ daemonAllowList = new Set(caps.allowed_secret_keys);
2085
+ }
2086
+ if (Array.isArray(caps?.runtimes_supported)) {
2087
+ daemonAllowedRuntimes = caps.runtimes_supported;
2088
+ }
2089
+ } catch { /* permissive fallback */ }
2090
+
2091
+ // §4.2.2 — structural validation (catches name/runtime/model/
2092
+ // flag injection at the hub edge). Daemon repeats this; double
2093
+ // layer per RFC §4.2.2.
2094
+ try {
2095
+ validateChildName(node_spec.name);
2096
+ validateRuntime(node_spec.runtime);
2097
+ validateModel(node_spec.model);
2098
+ validateChannelsP1((node_spec as any).channels);
2099
+ for (const [k, v] of Object.entries(node_spec.flags || {})) {
2100
+ if (!(FLAG_KEYS as readonly string[]).includes(k)) throw new ValidationError("flag_key_unknown", { field: k });
2101
+ validateFlagValue(k, v);
2102
+ }
2103
+ } catch (e) {
2104
+ return validationFailReply(e);
2105
+ }
2106
+
2107
+ // P1 daemon-side allowlist: if daemon publishes allowed_runtimes,
2108
+ // enforce at hub for fast-fail; daemon repeats.
2109
+ if (daemonAllowedRuntimes && !daemonAllowedRuntimes.includes(node_spec.runtime)) {
2110
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "runtime_not_in_local_allowlist", runtime: node_spec.runtime, allowed: daemonAllowedRuntimes }) }] };
2111
+ }
2112
+
2113
+ // §4.4.7 — env_refs strict (7-step gate) + resolve to env_blob.
2114
+ let envBlob: Record<string, string> = {};
2115
+ const envRefs = (node_spec as any).env_refs;
2116
+ try {
2117
+ envBlob = validateEnvRefs(envRefs, {
2118
+ callerNetworkId: effectiveNetId || "default",
2119
+ daemonAllowList,
2120
+ networkSecretsGet: (_net: string, _key: string) => undefined, // P1: no vault yet — see note below
2121
+ });
2122
+ } catch (e) {
2123
+ return validationFailReply(e);
2124
+ }
2125
+ // P1 NOTE — network_secrets vault is RFC §4.4 / §2.4 future
2126
+ // work. For now if dashboard sends env_refs we'll reject as
2127
+ // not-in-vault (above). When the vault lands, replace the
2128
+ // `networkSecretsGet: () => undefined` line with the real DB
2129
+ // lookup; nothing else in this tool needs to change.
2130
+
2131
+ // Single-flight per (daemon, child_name): partial unique index
2132
+ // uniq_ncr_inflight already prevents racing INSERT, but we
2133
+ // surface a friendly error rather than letting the DB constraint
2134
+ // raise.
2135
+ const existing = db.get<{ request_id: string; status: string }>(
2136
+ `SELECT request_id, status FROM node_create_requests WHERE daemon_node_id = ?1 AND child_name = ?2 AND status IN ('pending', 'delivered') ORDER BY created_at DESC LIMIT 1`,
2137
+ daemon_node_id, node_spec.name,
2138
+ );
2139
+ if (existing) {
2140
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "node_name_conflict", existing_request_id: existing.request_id, existing_status: existing.status }) }] };
2141
+ }
2142
+
2143
+ // §4.2.4 — daemon_max_children backpressure (best-effort: count
2144
+ // currently-active children for this daemon).
2145
+ const maxChildren = (() => {
2146
+ try {
2147
+ const snap = daemon.config_snapshot ? JSON.parse(daemon.config_snapshot) : null;
2148
+ const m = snap?.daemon_capabilities?.max_concurrent_children;
2149
+ return (typeof m === "number" && m > 0) ? m : 20;
2150
+ } catch { return 20; }
2151
+ })();
2152
+ const childCount = db.get<{ n: number }>(
2153
+ `SELECT COUNT(*) AS n FROM node_create_requests WHERE daemon_node_id = ?1 AND status IN ('pending', 'delivered', 'succeeded')`,
2154
+ daemon_node_id,
2155
+ )?.n || 0;
2156
+ if (childCount >= maxChildren) {
2157
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "daemon_max_children", current: childCount, max: maxChildren }) }] };
2158
+ }
2159
+
2160
+ // §2.5 step 2 + §4.4 F1 — mint child-ntok + stash env_blob in
2161
+ // Map (NOT in DB). Token row marked role='child' + request_id
2162
+ // for sweeper traceability per §4.4.8 impl note.
2163
+ const childToken = generateNetworkToken();
2164
+ const childTokenId = generateId("tok");
2165
+ const networkIdForChild = daemon.network_id || effectiveNetId || "default";
2166
+ const requestId = newRequestId();
2167
+ // Use the dashboard caller's user_id as the token's user_id so
2168
+ // resolveToken returns sane role / network on the child's side
2169
+ // (audit trail = whoever created it).
2170
+ if (!enforceUserId) {
2171
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "auth_required" }) }] };
2172
+ }
2173
+ db.run(
2174
+ `INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, role, request_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
2175
+ [childTokenId, hashToken(childToken), enforceUserId, networkIdForChild, `node:${node_spec.name}`, "network", "child", requestId]
2176
+ );
2177
+
2178
+ putPendingEnvBlob({
2179
+ request_id: requestId,
2180
+ daemon_node_id,
2181
+ env_blob: envBlob,
2182
+ child_token: childToken,
2183
+ child_token_id: childTokenId,
2184
+ });
2185
+
2186
+ // Write metadata-only row. env_blob field deliberately ABSENT
2187
+ // from the schema (see db.ts CREATE TABLE) — F1 lock.
2188
+ const envKeys = Object.keys(envBlob);
2189
+ db.run(
2190
+ `INSERT INTO node_create_requests
2191
+ (request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token)
2192
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', ?9, ?10, ?11)`,
2193
+ [
2194
+ requestId, daemon_node_id, node_spec.name, networkIdForChild,
2195
+ node_spec.runtime, node_spec.model, JSON.stringify(node_spec.flags || {}),
2196
+ JSON.stringify(envKeys), childTokenId, Date.now(), callerTokenId || "unknown",
2197
+ ],
2198
+ );
2199
+
2200
+ // SSE doorbell — daemon will pull via get_create_request.
2201
+ // Payload carries ONLY request_id (no secret); daemon current
2202
+ // SSE handler resolves the rest via MCP call.
2203
+ pushEvent(daemon.alias, { type: "create_node", request_id: requestId }, networkIdForChild);
2204
+
2205
+ // §4.5 audit — dispatch succeeded
2206
+ auditCreateNode({
2207
+ action: "create_node_dispatched",
2208
+ user_id: enforceUserId,
2209
+ network_id: networkIdForChild,
2210
+ target_id: requestId,
2211
+ detail: {
2212
+ daemon_node_id,
2213
+ child_name: node_spec.name,
2214
+ runtime: node_spec.runtime,
2215
+ model: node_spec.model,
2216
+ flag_keys: Object.keys(node_spec.flags || {}),
2217
+ env_keys: envKeys,
2218
+ },
2219
+ });
2220
+
2221
+ return {
2222
+ content: [{ type: "text" as const, text: JSON.stringify({ ok: true, request_id: requestId }) }],
2223
+ };
2224
+ },
2225
+ );
2226
+
2227
+ // §2.5 step 3 — daemon-facing pull. Returns full spec + env_blob +
2228
+ // child_ntok in one shot. Map evicted on take (one-shot consume).
2229
+ //
2230
+ // §4.1.4 C2 token-bound daemon resolution (PR #299 BLOCKER #1, 通信牛):
2231
+ // We MUST resolve the caller daemon via token-bound identity, NOT
2232
+ // alias. alias is NOT a security boundary — two daemons with the same
2233
+ // alias in different networks (or attacker-named-itself-the-same)
2234
+ // would otherwise resolve to the wrong row. Same class as the prior
2235
+ // report_status cross-tenant re-home bug.
2236
+ //
2237
+ // Resolution chain: caller's ntok (callerTokenId + callerTokenIsNetwork)
2238
+ // → api_tokens row → joins to nodes via name='node:<alias>' AND
2239
+ // network_id matches → unique daemon node row scoped to caller's
2240
+ // network. If the ntok isn't bound to a node, or the joined node
2241
+ // isn't a host_supervisor, reject.
2242
+ server.tool(
2243
+ "get_create_request",
2244
+ "Daemon pulls a pending create-node request (called when SSE create_node doorbell arrives). RFC-026.",
2245
+ {
2246
+ request_id: z.string().min(1).max(200),
2247
+ },
2248
+ async ({ request_id }) => {
2249
+ const callerDaemon = resolveCallerDaemonTokenBound();
2250
+ if (!callerDaemon.ok) {
2251
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
2252
+ }
2253
+
2254
+ const row = db.get<{ request_id: string; daemon_node_id: string; status: string; child_token_id: string | null; network_id: string }>(
2255
+ `SELECT request_id, daemon_node_id, status, child_token_id, network_id FROM node_create_requests WHERE request_id = ?1`,
2256
+ request_id,
2257
+ );
2258
+ if (!row) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_not_found" }) }] };
2259
+ // §4.1.4 — strict daemon binding by token-derived node_id.
2260
+ if (row.daemon_node_id !== callerDaemon.daemonNodeId) {
2261
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "not_your_request" }) }] };
2262
+ }
2263
+ // Additional network-scope guard (defense in depth: row's
2264
+ // network_id MUST equal caller's network).
2265
+ if (row.network_id !== callerDaemon.networkId) {
2266
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_request" }) }] };
2267
+ }
2268
+ if (row.status !== "pending") {
2269
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_not_pending", current_status: row.status }) }] };
2270
+ }
2271
+
2272
+ // Take env_blob from Map; this is the one-shot consume per F1.
2273
+ // takePendingEnvBlob ALSO checks daemon binding (belt+braces).
2274
+ const blob = takePendingEnvBlob(request_id, callerDaemon.daemonNodeId);
2275
+ if (!blob) {
2276
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "env_blob_unavailable" }) }] };
2277
+ }
2278
+ // Hydrate spec from row.
2279
+ const specRow = db.get<{ child_name: string; runtime: string; model: string; flags_json: string }>(
2280
+ `SELECT child_name, runtime, model, flags_json FROM node_create_requests WHERE request_id = ?1`,
2281
+ request_id,
2282
+ );
2283
+ if (!specRow) {
2284
+ // Should never happen given the earlier row read.
2285
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_vanished" }) }] };
2286
+ }
2287
+ // Mark delivered (so sweeper distinguishes F-1 from F-2).
2288
+ db.run(
2289
+ `UPDATE node_create_requests SET status = 'delivered', delivered_at = ?1 WHERE request_id = ?2 AND status = 'pending'`,
2290
+ [Date.now(), request_id],
2291
+ );
2292
+
2293
+ return {
2294
+ content: [{ type: "text" as const, text: JSON.stringify({
2295
+ ok: true,
2296
+ request_id,
2297
+ node_spec: {
2298
+ name: specRow.child_name,
2299
+ runtime: specRow.runtime,
2300
+ model: specRow.model,
2301
+ flags: JSON.parse(specRow.flags_json),
2302
+ channels: [],
2303
+ },
2304
+ child_token: blob.child_token,
2305
+ env_blob: blob.env_blob,
2306
+ }) }],
2307
+ };
2308
+ },
2309
+ );
2310
+
2311
+ // §2.5 step 4 — daemon reports outcome. Note: 'succeeded' is set
2312
+ // automatically by hub when the child first registers (content-match
2313
+ // in upsertNodeWithSec1Guard); daemon's ack here is for explicit
2314
+ // failures (fork crashed, etc.). Daemon should still call this on
2315
+ // success too — it's a useful idempotent confirmation + lets hub
2316
+ // record fork-side info.
2317
+ server.tool(
2318
+ "ack_create_request",
2319
+ "Daemon acks a create-node request (called after fork). status='started' | 'failed' | 'rejected' | 'runtime_capability_check_failed'. RFC-026 §9.3 D2.",
2320
+ {
2321
+ request_id: z.string().min(1).max(200),
2322
+ // RFC-026 §9.3 D2 — runtime_capability_check_failed signals the
2323
+ // daemon spawned the child OK but it died within FAIL_FAST_MS
2324
+ // (5s in agent-node v2.5.0-preview.11+), indicating a
2325
+ // declaration↔reality gap on this daemon's runtimes_supported.
2326
+ // Treated terminal like 'failed' but fires a distinct audit_log
2327
+ // action so dashboards can highlight "lying daemons" separately
2328
+ // from generic spawn failures.
2329
+ status: z.enum(["started", "failed", "rejected", "runtime_capability_check_failed"]),
2330
+ error: z.string().max(1000).optional(),
2331
+ child_pid: z.number().int().optional(),
2332
+ runtime: z.string().max(64).optional(), // populated by daemon when status=runtime_capability_check_failed
2333
+ },
2334
+ async ({ request_id, status, error: ackError, child_pid: _pid, runtime: ackRuntime }) => {
2335
+ const callerDaemon = resolveCallerDaemonTokenBound();
2336
+ if (!callerDaemon.ok) {
2337
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
2338
+ }
2339
+ const row = db.get<{ daemon_node_id: string; status: string; child_token_id: string | null; network_id: string }>(
2340
+ `SELECT daemon_node_id, status, child_token_id, network_id FROM node_create_requests WHERE request_id = ?1`,
2341
+ request_id,
2342
+ );
2343
+ if (!row) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_not_found" }) }] };
2344
+ if (row.daemon_node_id !== callerDaemon.daemonNodeId) {
2345
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "not_your_request" }) }] };
2346
+ }
2347
+ if (row.network_id !== callerDaemon.networkId) {
2348
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_request" }) }] };
2349
+ }
2350
+ const ackedAt = Date.now();
2351
+ if (status === "started") {
2352
+ // Don't flip to 'succeeded' here — that happens via content-
2353
+ // match when the child actually registers. We just stamp ack.
2354
+ db.run(
2355
+ `UPDATE node_create_requests SET acked_at = ?1 WHERE request_id = ?2 AND status IN ('delivered', 'pending')`,
2356
+ [ackedAt, request_id],
2357
+ );
2358
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, status: "awaiting_register" }) }] };
2359
+ }
2360
+ // failed / rejected / runtime_capability_check_failed — revoke
2361
+ // child-ntok + mark request terminal.
2362
+ if (row.child_token_id) {
2363
+ db.run(`UPDATE api_tokens SET revoked_at = datetime('now') WHERE token_id = ?1 AND revoked_at IS NULL`, [row.child_token_id]);
2364
+ }
2365
+ db.run(
2366
+ `UPDATE node_create_requests SET status = ?1, error = ?2, acked_at = ?3 WHERE request_id = ?4 AND status IN ('pending', 'delivered')`,
2367
+ [status, ackError || null, ackedAt, request_id],
2368
+ );
2369
+ // RFC-026 §9.3 D2 — surface declaration↔reality gap on a
2370
+ // distinct audit_log action so dashboards / operators can spot
2371
+ // chronically-lying daemons separate from generic spawn-failed.
2372
+ if (status === "runtime_capability_check_failed") {
2373
+ auditCreateNode({
2374
+ action: "daemon_capability_lied",
2375
+ user_id: null,
2376
+ network_id: row.network_id,
2377
+ target_id: request_id,
2378
+ detail: {
2379
+ daemon_node_id: row.daemon_node_id,
2380
+ runtime: ackRuntime || null,
2381
+ error: ackError ? ackError.slice(0, 500) : null,
2382
+ acked_at: ackedAt,
2383
+ },
2384
+ });
2385
+ }
2386
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, status }) }] };
2387
+ },
2388
+ );
2389
+
2390
+ // ─── RFC-027 §2 — stop/delete node lifecycle ───────────────────────
2391
+ //
2392
+ // Two user-facing MCP tools (stop_node, delete_node) + two daemon-
2393
+ // facing tools (get_stop_request, ack_stop_request). State machine
2394
+ // per §2.3 — nodes.lifecycle_state ∈ {active, stopping, stopped,
2395
+ // deleting}. row-gone implies deleted. Security per §4:
2396
+ // §4.1 SEC-1: trust-root SQL join, not getNetworkId
2397
+ // §4.2 D6: delete_node refuses target.role==host_supervisor
2398
+ // §4.3 D4: in-flight inbox default-refuse + force+audit
2399
+ // §4.4 D7: daemon writes backup chmod 700, sweeper真删
2400
+ // §4.5 D8: audit_log in same SQLite tx as state UPDATE
2401
+ //
2402
+ // The dispatcher logic shared by stop_node + delete_node lives in
2403
+ // dispatchStopOrDelete; the two tool handlers thin-wrap it with
2404
+ // their respective action discriminator.
2405
+ type DispatchAction = "stop" | "delete";
2406
+ type DispatchArgs = {
2407
+ action: DispatchAction;
2408
+ child_node_id: string;
2409
+ daemon_node_id: string;
2410
+ force: boolean;
2411
+ grace_seconds: number;
2412
+ delete_config: boolean;
2413
+ confirm_alias?: string;
2414
+ };
2415
+ // RFC-027 PR2 prereq — auto-resolve daemon_node_id from child_node_id.
2416
+ // The dashboard (and most callers of stop_node / delete_node) shouldn't
2417
+ // need to track the daemon→child mapping themselves; the hub has it on
2418
+ // node_create_requests at child creation time. Returns null when no
2419
+ // creation record exists (orphan node row OR pre-RFC-026 node) — caller
2420
+ // must then pass daemon_node_id explicitly. node_id derivation:
2421
+ // `node_${request_id.replace(/^cr_/,"")}` (see create-node-daemon.ts
2422
+ // and PR1 BLOCKER-1 fix), so we reverse it: `cr_${node_id.slice(5)}`.
2423
+ const resolveDaemonForChild = (child_node_id: string): string | null => {
2424
+ if (!child_node_id.startsWith("node_")) return null;
2425
+ const requestId = `cr_${child_node_id.slice(5)}`;
2426
+ const row = db.get<{ daemon_node_id: string }>(
2427
+ `SELECT daemon_node_id FROM node_create_requests WHERE request_id = ?1`,
2428
+ requestId,
2429
+ );
2430
+ return row?.daemon_node_id ?? null;
2431
+ };
2432
+
2433
+ const dispatchStopOrDelete = (args: DispatchArgs, clientNetId?: string | null) => {
2434
+ // §4.1 — SEC-1 trust-root join: resolve target node row WITHIN the
2435
+ // caller's scope. resolveReadScope returns 'denied' if the caller
2436
+ // doesn't belong to clientNetId; for the row-existence test we
2437
+ // re-join with member's networks so an attacker can't probe by
2438
+ // node_id from a network they don't belong to.
2439
+ const scope = resolveReadScope(clientNetId);
2440
+ if (scope.denied) {
2441
+ return { ok: false, error: "forbidden_cross_tenant", message: scope.denied };
2442
+ }
2443
+ const nodeQ: any[] = [args.child_node_id];
2444
+ let nodeSql = `SELECT node_id, alias, network_id, lifecycle_state, config_snapshot, runtimes_supported
2445
+ FROM nodes WHERE node_id = ?1`;
2446
+ nodeSql = addReadScope(nodeSql, nodeQ, scope);
2447
+ const node = db.get<{
2448
+ node_id: string;
2449
+ alias: string;
2450
+ network_id: string;
2451
+ lifecycle_state: string | null;
2452
+ config_snapshot: string | null;
2453
+ }>(nodeSql, ...nodeQ);
2454
+ if (!node) return { ok: false, error: "forbidden_cross_tenant", message: "node not found in your networks" };
2455
+
2456
+ // Caller must hold a write-capable role on the resolved network
2457
+ // (admin/owner/member; viewer denied). canWrite walks getUserNetworkRole.
2458
+ if (!canWrite(node.network_id)) {
2459
+ return { ok: false, error: "permission_denied", message: "viewer role cannot stop/delete nodes" };
2460
+ }
2461
+
2462
+ // §4.2 D6 — delete refuses targets whose role is host_supervisor.
2463
+ // Stop is allowed against any node per RFC table (host_supervisor's
2464
+ // stop is functionally a no-op anyway: the daemon's children_map
2465
+ // only tracks its child nodes, never the daemon itself).
2466
+ //
2467
+ // PR1 SF-4 (#345 review) — fail-CLOSED on role read. The first cut
2468
+ // parsed config_snapshot and treated parse-fail / missing-field as
2469
+ // role=null which slipped through the gate. A daemon row with a
2470
+ // corrupt snapshot would then be deletable via delete_node. Fix:
2471
+ // - read role via two independent paths (snapshot.role + the
2472
+ // indexed `runtimes_supported` column whose presence ≈ daemon)
2473
+ // - if EITHER path indicates host_supervisor → refuse
2474
+ // - if snapshot parsed but role missing AND the node has any
2475
+ // daemon-shape evidence (non-null runtimes_supported column,
2476
+ // present in any node_create_requests as daemon_node_id) →
2477
+ // refuse defensively. The defense-in-depth daemon-side
2478
+ // children_map miss is the second layer; the hub gate must
2479
+ // itself fail-closed when role is ambiguous.
2480
+ if (args.action === "delete") {
2481
+ let role: string | null = null;
2482
+ let snapshotParseFailed = false;
2483
+ try {
2484
+ const snap = node.config_snapshot ? JSON.parse(node.config_snapshot) : null;
2485
+ role = typeof snap?.role === "string" ? snap.role : null;
2486
+ } catch { snapshotParseFailed = true; }
2487
+ const ambiguous = snapshotParseFailed || (role == null);
2488
+ // Independent corroborating check: nodes flagged as daemons by
2489
+ // create_node dispatchers will show up as daemon_node_id in
2490
+ // node_create_requests. Costs one indexed query.
2491
+ let looksLikeDaemon = false;
2492
+ if (ambiguous) {
2493
+ const m = db.get<{ n: number }>(
2494
+ `SELECT COUNT(*) AS n FROM node_create_requests WHERE daemon_node_id = ?1`,
2495
+ node.node_id,
2496
+ );
2497
+ if ((m?.n ?? 0) > 0) looksLikeDaemon = true;
2498
+ }
2499
+ if (role === "host_supervisor" || (ambiguous && looksLikeDaemon)) {
2500
+ return {
2501
+ ok: false, error: "cannot_delete_daemon_via_delete_node",
2502
+ message: snapshotParseFailed
2503
+ ? "node config_snapshot unreadable; node is referenced as a daemon — refuse delete defensively (use delete_daemon path)"
2504
+ : "host_supervisor daemons must be removed via the dedicated delete_daemon path (RFC-027.5)",
2505
+ };
2506
+ }
2507
+ }
2508
+
2509
+ // delete_node confirm_alias gate: dashboard's二次确认 input must
2510
+ // match the actual alias byte-for-byte. Hub rejects mismatched
2511
+ // input even if dashboard UI claims it's disabled.
2512
+ if (args.action === "delete") {
2513
+ if (typeof args.confirm_alias !== "string" || args.confirm_alias !== node.alias) {
2514
+ return { ok: false, error: "confirm_alias_mismatch", message: "confirm_alias must equal the node's alias" };
2515
+ }
2516
+ }
2517
+
2518
+ // Daemon must exist + be in the same network. We do NOT enforce
2519
+ // daemon.role==host_supervisor here: a child whose creator daemon
2520
+ // got demoted should still be stoppable. The daemon will refuse
2521
+ // with noop_not_my_child if children_map doesn't know it.
2522
+ //
2523
+ // PR1.2 e2e catch (BLOCKER): pushEvent keys SSE by clientKey ≈
2524
+ // `${networkId}:${sessionName}`, and agent-node registers its SSE
2525
+ // connection under its ALIAS (not its node_id). The create_node
2526
+ // doorbell at line ~2197 correctly pushes via `daemon.alias`;
2527
+ // stop_node was pushing via `daemon_node_id` so every doorbell
2528
+ // missed every SSE client → daemon never woke up → request_id
2529
+ // stayed 'pending' forever → child never reaped. The 24 unit tests
2530
+ // in stop-delete-node.test.ts all mock pushEvent and inject the
2531
+ // post-doorbell handler call directly, so single-unit coverage
2532
+ // couldn't surface this — exactly the failure class 通信龙 said
2533
+ // the docker e2e gate exists to catch (BLOCKER-1 同源). Load the
2534
+ // alias along with node_id + network_id and dispatch to the alias.
2535
+ const daemon = db.get<{ node_id: string; alias: string; network_id: string }>(
2536
+ `SELECT node_id, alias, network_id FROM nodes WHERE node_id = ?1`, args.daemon_node_id,
2537
+ );
2538
+ if (!daemon) return { ok: false, error: "daemon_not_found" };
2539
+ if (daemon.network_id !== node.network_id) {
2540
+ // Cross-tenant child↔daemon mismatch shouldn't be possible in
2541
+ // normal flow but is a SEC-1 hardening — refuse loud.
2542
+ return { ok: false, error: "daemon_cross_tenant", message: "daemon and child are in different networks" };
2543
+ }
2544
+
2545
+ // State machine gate.
2546
+ const state = node.lifecycle_state ?? "active";
2547
+ if (args.action === "stop" && state !== "active") {
2548
+ return { ok: false, error: state === "stopping" ? "node_already_stopping" : "node_not_active", current_state: state };
2549
+ }
2550
+ if (args.action === "delete" && state === "deleting") {
2551
+ return { ok: false, error: "node_already_deleting", current_state: state };
2552
+ }
2553
+ if (args.action === "delete" && state === "stopping") {
2554
+ // Can't start delete while a stop is mid-flight — race-prone.
2555
+ return { ok: false, error: "node_stopping_in_progress", current_state: state };
2556
+ }
2557
+
2558
+ // §4.3 D4 — in-flight inbox check. Count unacked tasks routed to
2559
+ // this node's alias (inbox routing uses session_name == alias).
2560
+ // Default refuse with the count surfaced; force=true overrides
2561
+ // and triggers the forced_stop_with_in_flight audit row.
2562
+ // SF-5 (#345 review): legacy inbox rows may have network_id=NULL
2563
+ // and would silently miss a network_id=?2 strict equality match.
2564
+ // Use COALESCE so a NULL inbox row is counted against the same
2565
+ // network as the target node (which is the only safe default
2566
+ // — pre-multi-network rows existed in single-network mode).
2567
+ const inFlightRow = db.get<{ n: number }>(
2568
+ `SELECT COUNT(*) AS n FROM inbox WHERE session_name = ?1 AND acked = 0
2569
+ AND COALESCE(network_id, ?2) = ?2`,
2570
+ node.alias, node.network_id,
2571
+ );
2572
+ const inFlight = inFlightRow?.n ?? 0;
2573
+ if (inFlight > 0 && !args.force) {
2574
+ return { ok: false, error: "node_busy_in_flight", in_flight_count: inFlight, hint: "set force=true to override (audit logged)" };
2575
+ }
2576
+
2577
+ // ── all gates passed; create request + transition state + push doorbell, transactionally ──
2578
+ const requestId = generateId("sr");
2579
+ const now = Date.now();
2580
+ const newState = args.action === "stop" ? "stopping" : "deleting";
2581
+
2582
+ // §4.5 D8 — lifecycle UPDATE + audit INSERTs + request INSERT atomic.
2583
+ // PR1.1: use db.transaction() (SQLiteAdapter wraps better-sqlite3's
2584
+ // native transaction; PgAdapter ships a real BEGIN/COMMIT/ROLLBACK
2585
+ // shim). Lets us drop the open-coded BEGIN/COMMIT + makes the
2586
+ // SF-2 failure-injection test (mock db.run throw inside callback)
2587
+ // reliable across both backends.
2588
+ try {
2589
+ db.transaction(() => {
2590
+ db.run(
2591
+ `INSERT INTO node_stop_requests
2592
+ (request_id, network_id, daemon_node_id, child_node_id, child_alias, action,
2593
+ delete_config, grace_seconds, force, in_flight_at_dispatch, created_by_token,
2594
+ status, created_at)
2595
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'pending', ?12)`,
2596
+ [
2597
+ requestId, node.network_id, args.daemon_node_id, node.node_id, node.alias, args.action,
2598
+ args.delete_config ? 1 : 0, args.grace_seconds, args.force ? 1 : 0, inFlight,
2599
+ callerTokenId || "unknown", now,
2600
+ ],
2601
+ );
2602
+ db.run(
2603
+ `UPDATE nodes SET lifecycle_state = ?1 WHERE node_id = ?2`,
2604
+ [newState, node.node_id],
2605
+ );
2606
+ // §4.5 D8 — audit dispatch action. Uses the STRICT variant so a
2607
+ // failed audit INSERT propagates and triggers ROLLBACK (PR1 SF-2
2608
+ // review catch — auditCreateNode's swallow-and-warn would have
2609
+ // committed the lifecycle UPDATE without an audit row, leaving
2610
+ // exactly the "deleted but no audit" window §4.5 closes).
2611
+ auditCreateNodeStrict({
2612
+ action: args.action === "stop" ? "stop_node_dispatched" : "delete_node_dispatched",
2613
+ user_id: enforceUserId, network_id: node.network_id, target_id: requestId,
2614
+ detail: {
2615
+ child_node_id: node.node_id, child_alias: node.alias,
2616
+ daemon_node_id: args.daemon_node_id, action: args.action,
2617
+ force: args.force, delete_config: args.delete_config,
2618
+ grace_seconds: args.grace_seconds, in_flight_at_dispatch: inFlight,
2619
+ lifecycle_state_before: state, lifecycle_state_after: newState,
2620
+ ts_request: now,
2621
+ },
2622
+ });
2623
+ if (args.force && inFlight > 0) {
2624
+ auditCreateNodeStrict({
2625
+ action: "forced_stop_with_in_flight",
2626
+ user_id: enforceUserId, network_id: node.network_id, target_id: requestId,
2627
+ detail: { in_flight_count: inFlight, child_alias: node.alias },
2628
+ });
2629
+ }
2630
+ }); // end db.transaction
2631
+ } catch (e: any) {
2632
+ return { ok: false, error: "dispatch_tx_failed", message: e?.message || String(e) };
2633
+ }
2634
+
2635
+ // SSE doorbell — daemon will pull via get_stop_request.
2636
+ // PR1.2 e2e fix: route by daemon.alias (see SELECT above for the
2637
+ // BLOCKER explanation). Mirrors create_node's pushEvent target at
2638
+ // line ~2197.
2639
+ pushEvent(daemon.alias, { type: "stop_node", request_id: requestId }, node.network_id);
2640
+ return {
2641
+ ok: true, request_id: requestId, action: args.action,
2642
+ lifecycle_state: newState, in_flight_at_dispatch: inFlight,
2643
+ };
2644
+ };
2645
+
2646
+ server.tool(
2647
+ "stop_node",
2648
+ "Stop the agent-node child process; keep config dir intact. Reversible via restart_node. RFC-027 §2.2. daemon_node_id is auto-resolved from child_node_id when omitted (looked up in node_create_requests).",
2649
+ {
2650
+ child_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/),
2651
+ // PR2 prereq: dashboard rarely knows daemon_node_id directly.
2652
+ // When omitted, hub resolves from the original creation record
2653
+ // (node_create_requests.daemon_node_id keyed by this child).
2654
+ daemon_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/).optional(),
2655
+ force: z.boolean().optional().default(false),
2656
+ grace_seconds: z.number().int().min(5).max(60).optional().default(10),
2657
+ network_id: z.string().max(200).optional(),
2658
+ },
2659
+ async ({ child_node_id, daemon_node_id, force, grace_seconds, network_id: clientNetId }) => {
2660
+ const resolved = daemon_node_id ?? resolveDaemonForChild(child_node_id);
2661
+ if (!resolved) {
2662
+ return { content: [{ type: "text" as const, text: JSON.stringify({
2663
+ ok: false, error: "daemon_not_resolvable",
2664
+ message: "no node_create_requests row found for this child_node_id; pass daemon_node_id explicitly",
2665
+ }) }] };
2666
+ }
2667
+ const r = dispatchStopOrDelete(
2668
+ { action: "stop", child_node_id, daemon_node_id: resolved, force: force ?? false,
2669
+ grace_seconds: grace_seconds ?? 10, delete_config: false },
2670
+ clientNetId,
2671
+ );
2672
+ return { content: [{ type: "text" as const, text: JSON.stringify(r) }] };
2673
+ },
2674
+ );
2675
+
2676
+ server.tool(
2677
+ "delete_node",
2678
+ "Stop child + revoke ntok + delete hub row + (default) backup config to ~/.anet/deleted/<ts>-<alias>/ for 30d. confirm_alias must equal the node's alias. daemon_node_id is auto-resolved when omitted. RFC-027 §2.2.",
2679
+ {
2680
+ child_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/),
2681
+ daemon_node_id: z.string().min(1).max(200).regex(/^node_[a-z0-9_-]+$/).optional(),
2682
+ confirm_alias: z.string().min(1).max(200),
2683
+ force: z.boolean().optional().default(false),
2684
+ grace_seconds: z.number().int().min(5).max(60).optional().default(10),
2685
+ delete_config: z.boolean().optional().default(true),
2686
+ network_id: z.string().max(200).optional(),
2687
+ },
2688
+ async ({ child_node_id, daemon_node_id, confirm_alias, force, grace_seconds, delete_config, network_id: clientNetId }) => {
2689
+ const resolved = daemon_node_id ?? resolveDaemonForChild(child_node_id);
2690
+ if (!resolved) {
2691
+ return { content: [{ type: "text" as const, text: JSON.stringify({
2692
+ ok: false, error: "daemon_not_resolvable",
2693
+ message: "no node_create_requests row found for this child_node_id; pass daemon_node_id explicitly",
2694
+ }) }] };
2695
+ }
2696
+ const r = dispatchStopOrDelete(
2697
+ { action: "delete", child_node_id, daemon_node_id: resolved, force: force ?? false,
2698
+ grace_seconds: grace_seconds ?? 10, delete_config: delete_config ?? true, confirm_alias },
2699
+ clientNetId,
2700
+ );
2701
+ return { content: [{ type: "text" as const, text: JSON.stringify(r) }] };
2702
+ },
2703
+ );
2704
+
2705
+ server.tool(
2706
+ "get_stop_request",
2707
+ "Daemon pulls a pending stop/delete request (called when SSE stop_node doorbell arrives). RFC-027 §2.4.",
2708
+ {
2709
+ request_id: z.string().min(1).max(200),
2710
+ },
2711
+ async ({ request_id }) => {
2712
+ const callerDaemon = resolveCallerDaemonTokenBound();
2713
+ if (!callerDaemon.ok) {
2714
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
2715
+ }
2716
+ const row = db.get<{
2717
+ daemon_node_id: string; status: string; network_id: string;
2718
+ child_node_id: string; child_alias: string; action: string;
2719
+ delete_config: number; grace_seconds: number; force: number;
2720
+ }>(`SELECT daemon_node_id, status, network_id, child_node_id, child_alias, action,
2721
+ delete_config, grace_seconds, force
2722
+ FROM node_stop_requests WHERE request_id = ?1`, request_id);
2723
+ if (!row) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_not_found" }) }] };
2724
+ if (row.daemon_node_id !== callerDaemon.daemonNodeId) {
2725
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "not_your_request" }) }] };
2726
+ }
2727
+ if (row.network_id !== callerDaemon.networkId) {
2728
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_request" }) }] };
2729
+ }
2730
+ // Stamp delivered_at on first pull (idempotent — only if still pending).
2731
+ db.run(
2732
+ `UPDATE node_stop_requests SET status = 'delivered', delivered_at = ?1
2733
+ WHERE request_id = ?2 AND status = 'pending'`,
2734
+ [Date.now(), request_id],
2735
+ );
2736
+ return { content: [{ type: "text" as const, text: JSON.stringify({
2737
+ ok: true,
2738
+ request_id,
2739
+ child_node_id: row.child_node_id,
2740
+ child_alias: row.child_alias,
2741
+ action: row.action,
2742
+ delete_config: row.delete_config === 1,
2743
+ grace_seconds: row.grace_seconds,
2744
+ force: row.force === 1,
2745
+ }) }] };
2746
+ },
2747
+ );
2748
+
2749
+ server.tool(
2750
+ "ack_stop_request",
2751
+ "Daemon reports stop/delete completion (or per-status failure). On 'stopped' status finalizes the lifecycle: stop→stopped + keep config; delete→DB row gone + revoke ntok. RFC-027 §2.3 + §4.5.",
2752
+ {
2753
+ request_id: z.string().min(1).max(200),
2754
+ status: z.enum(["stopped", "stop_failed", "noop_not_my_child"]),
2755
+ exit_signal: z.string().max(16).optional(),
2756
+ backup_path: z.string().max(500).optional(),
2757
+ error: z.string().max(1000).optional(),
2758
+ },
2759
+ async ({ request_id, status, exit_signal, backup_path, error: ackError }) => {
2760
+ const callerDaemon = resolveCallerDaemonTokenBound();
2761
+ if (!callerDaemon.ok) {
2762
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
2763
+ }
2764
+ const row = db.get<{
2765
+ daemon_node_id: string; status: string; network_id: string;
2766
+ child_node_id: string; child_alias: string; action: string;
2767
+ in_flight_at_dispatch: number; force: number;
2768
+ }>(`SELECT daemon_node_id, status, network_id, child_node_id, child_alias, action,
2769
+ in_flight_at_dispatch, force
2770
+ FROM node_stop_requests WHERE request_id = ?1`, request_id);
2771
+ if (!row) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "request_not_found" }) }] };
2772
+ if (row.daemon_node_id !== callerDaemon.daemonNodeId) {
2773
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "not_your_request" }) }] };
2774
+ }
2775
+ if (row.network_id !== callerDaemon.networkId) {
2776
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_request" }) }] };
2777
+ }
2778
+ const now = Date.now();
2779
+
2780
+ // §4.5 D8 — lifecycle UPDATE + request UPDATE + audit INSERT
2781
+ // (+ DELETE for delete action) atomic via db.transaction().
2782
+ // PR1.1: replaces hand-rolled BEGIN..COMMIT so PG adapter and
2783
+ // SQLite both get correct rollback semantics from one code path.
2784
+ try {
2785
+ db.transaction(() => {
2786
+ db.run(
2787
+ `UPDATE node_stop_requests SET status = ?1, error = ?2, exit_signal = ?3,
2788
+ backup_path = ?4, acked_at = ?5
2789
+ WHERE request_id = ?6`,
2790
+ [status, ackError || null, exit_signal || null, backup_path || null, now, request_id],
2791
+ );
2792
+ if (status === "stopped" && row.action === "stop") {
2793
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopped' WHERE node_id = ?1`, [row.child_node_id]);
2794
+ auditCreateNodeStrict({
2795
+ action: "stop_node_completed",
2796
+ user_id: null, network_id: row.network_id, target_id: request_id,
2797
+ detail: {
2798
+ child_node_id: row.child_node_id, child_alias: row.child_alias,
2799
+ exit_signal: exit_signal || null, ts_daemon_ack: now,
2800
+ lifecycle_state_after: "stopped",
2801
+ },
2802
+ });
2803
+ } else if (status === "stopped" && row.action === "delete") {
2804
+ // Revoke the child's ntok (name='node:<alias>') in the daemon's
2805
+ // network, then DELETE the nodes row. Token revoke pattern mirrors
2806
+ // ack_create_request's terminal path.
2807
+ db.run(
2808
+ `UPDATE api_tokens SET revoked_at = datetime('now')
2809
+ WHERE network_id = ?1 AND name = ?2 AND revoked_at IS NULL`,
2810
+ [row.network_id, `node:${row.child_alias}`],
2811
+ );
2812
+ db.run(`DELETE FROM nodes WHERE node_id = ?1`, [row.child_node_id]);
2813
+ auditCreateNodeStrict({
2814
+ action: "delete_node_completed",
2815
+ user_id: null, network_id: row.network_id, target_id: request_id,
2816
+ detail: {
2817
+ child_node_id: row.child_node_id, child_alias: row.child_alias,
2818
+ exit_signal: exit_signal || null, backup_path: backup_path || null,
2819
+ ts_daemon_ack: now, lifecycle_state_after: "deleted",
2820
+ },
2821
+ });
2822
+ } else if (status === "stop_failed") {
2823
+ db.run(`UPDATE nodes SET lifecycle_state = 'stop_failed' WHERE node_id = ?1`, [row.child_node_id]);
2824
+ // No completion audit; the failure error is on the request row.
2825
+ }
2826
+ // noop_not_my_child: leave lifecycle_state as-is; the hub-side
2827
+ // sweeper / next reconciliation will pick it up. Don't transition.
2828
+ });
2829
+ } catch (e: any) {
2830
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "finalize_tx_failed", message: e?.message || String(e) }) }] };
2831
+ }
2832
+
2833
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, status }) }] };
2834
+ },
2835
+ );
2836
+
2837
+ // RFC-027 PR1.1 — list_my_children: daemon-only query. Returns the
2838
+ // {child_node_id, alias, lifecycle_state} tuples for nodes whose
2839
+ // active create-request has this daemon as daemon_node_id. Used at
2840
+ // daemon boot to rebuild the in-memory childrenMap (PR1 dropped
2841
+ // every entry on daemon restart → stop/delete silently no-op'd).
2842
+ //
2843
+ // Network-scope is the daemon's own (resolveCallerDaemonTokenBound
2844
+ // already binds tokenIsNetwork to a single network). No SEC-1 leak:
2845
+ // returns ONLY children whose request landed under this daemon's
2846
+ // token + network.
2847
+ server.tool(
2848
+ "list_my_children",
2849
+ "Daemon pulls the alias + node_id list of children it spawned (for childrenMap rebuild after restart). RFC-027 PR1.1.",
2850
+ {},
2851
+ async () => {
2852
+ const callerDaemon = resolveCallerDaemonTokenBound();
2853
+ if (!callerDaemon.ok) {
2854
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
2855
+ }
2856
+ // node_create_requests carries the canonical authoritative
2857
+ // child→daemon mapping (the row id IS the request, and the
2858
+ // child node_id derives from it deterministically via
2859
+ // `node_${request_id.replace(/^cr_/, "")}`). Filter to children
2860
+ // that completed registration (have a nodes row) so we don't
2861
+ // ask the daemon to pgrep for children that never came up.
2862
+ const rows = db.all<{ request_id: string; child_name: string; child_node_id: string; lifecycle_state: string | null }>(
2863
+ `SELECT ncr.request_id, ncr.child_name,
2864
+ ('node_' || substr(ncr.request_id, 4)) AS child_node_id,
2865
+ n.lifecycle_state
2866
+ FROM node_create_requests ncr
2867
+ LEFT JOIN nodes n ON n.node_id = ('node_' || substr(ncr.request_id, 4))
2868
+ WHERE ncr.daemon_node_id = ?1
2869
+ AND ncr.network_id = ?2
2870
+ AND ncr.status IN ('succeeded', 'delivered')
2871
+ AND n.node_id IS NOT NULL
2872
+ AND COALESCE(n.lifecycle_state, 'active') NOT IN ('stopped', 'stop_failed')`,
2873
+ callerDaemon.daemonNodeId, callerDaemon.networkId,
2874
+ );
2875
+ const children = rows.map(r => ({
2876
+ child_node_id: r.child_node_id,
2877
+ alias: r.child_name,
2878
+ lifecycle_state: r.lifecycle_state ?? "active",
2879
+ }));
2880
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, count: children.length, children }) }] };
2881
+ },
2882
+ );
2883
+
2884
+ // ── RFC-028 P1 — Provider & Model Registry + connectivity probe ──
2885
+ // Background timers (probe GC + sweeper) idempotent; safe to call
2886
+ // per registerTools.
2887
+ startPendingProbeGcTimer();
2888
+ startProbeSweeperTimer();
2889
+
2890
+ // Helper: zod to JSON-RPC reply for ProbeValidationError + VaultError
2891
+ const probeFailReply = (e: unknown) => {
2892
+ if (e instanceof ProbeValidationError) {
2893
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: e.code, ...(e.detail || {}) }) }] };
2894
+ }
2895
+ if (e instanceof VaultError) {
2896
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: e.code, message: e.message }) }] };
2897
+ }
2898
+ throw e;
2899
+ };
2900
+
2901
+ // §2.3.4 — upsert_network_secret (OWNER-ONLY; vault write).
2902
+ server.tool(
2903
+ "upsert_network_secret",
2904
+ "Write or replace a secret value in the network's vault (AES-GCM encrypted at rest). OWNER-only. RFC-028.",
2905
+ {
2906
+ key: z.string().min(1).max(64).regex(/^[A-Z][A-Z0-9_]{0,63}$/),
2907
+ value: z.string().min(1).max(16 * 1024),
2908
+ network_id: z.string().max(200).optional(),
2909
+ },
2910
+ async ({ key, value, network_id: clientNetId }) => {
2911
+ const effectiveNetId = getNetworkId(clientNetId);
2912
+ if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
2913
+ const callerRole = enforceUserId && effectiveNetId
2914
+ ? getUserNetworkRole(enforceUserId, effectiveNetId)
2915
+ : null;
2916
+ if (callerRole !== "owner") {
2917
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "secret_owner_only", required_role: "owner", caller_role: callerRole }) }] };
2918
+ }
2919
+ try {
2920
+ vaultUpsert(effectiveNetId || "default", key, value);
2921
+ auditCreateNode({
2922
+ action: "create_node_dispatched", // reusing audit_log shape (provider follow-up logs)
2923
+ user_id: enforceUserId, network_id: effectiveNetId, target_id: null,
2924
+ detail: { op: "vault_upsert", key, network_id: effectiveNetId },
2925
+ });
2926
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, key }) }] };
2927
+ } catch (e) {
2928
+ return probeFailReply(e);
2929
+ }
2930
+ },
2931
+ );
2932
+
2933
+ // §2.3.4b — list_network_secrets (key names only; viewer+).
2934
+ server.tool(
2935
+ "list_network_secrets",
2936
+ "List vault key NAMES (NEVER values) for a network. RFC-028.",
2937
+ { network_id: z.string().max(200).optional() },
2938
+ async ({ network_id: clientNetId }) => {
2939
+ const effectiveNetId = getNetworkId(clientNetId);
2940
+ if (!canWrite(effectiveNetId) && enforceUserId) {
2941
+ // viewer-level: allow if caller has any role in network
2942
+ const role = getUserNetworkRole(enforceUserId, effectiveNetId || "default");
2943
+ if (!role) return writeDeniedReply(effectiveNetId, "read");
2944
+ }
2945
+ const keys = vaultListKeys(effectiveNetId || "default");
2946
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, keys }) }] };
2947
+ },
2948
+ );
2949
+
2950
+ // §2.3.1 — upsert_provider (admin+).
2951
+ server.tool(
2952
+ "upsert_provider",
2953
+ "Create or update a provider (vendor + base_url + secret_key_ref + initial models). Admin+. RFC-028.",
2954
+ {
2955
+ name: z.string().min(1).max(100),
2956
+ vendor: z.string().min(1).max(64),
2957
+ base_url: z.string().min(1).max(500),
2958
+ secret_key_ref: z.string().min(1).max(64),
2959
+ models: z.array(z.object({
2960
+ model_name: z.string().min(1).max(100),
2961
+ display_name: z.string().max(100).optional(),
2962
+ context_window: z.number().int().min(0).optional(),
2963
+ supports_vision: z.boolean().optional(),
2964
+ })).optional(),
2965
+ network_id: z.string().max(200).optional(),
2966
+ },
2967
+ async ({ name, vendor, base_url, secret_key_ref, models, network_id: clientNetId }) => {
2968
+ const effectiveNetId = getNetworkId(clientNetId);
2969
+ if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
2970
+ const callerRole = enforceUserId && effectiveNetId
2971
+ ? getUserNetworkRole(enforceUserId, effectiveNetId)
2972
+ : null;
2973
+ if (callerRole !== "admin" && callerRole !== "owner") {
2974
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "insufficient_role_for_provider", required_role: "admin", caller_role: callerRole }) }] };
2975
+ }
2976
+ try {
2977
+ _validateBaseUrl(vendor, base_url);
2978
+ } catch (e) {
2979
+ return probeFailReply(e);
2980
+ }
2981
+ // Verify vault key exists (best-effort; just lists names)
2982
+ const vaultKeys = vaultListKeys(effectiveNetId || "default");
2983
+ if (!vaultKeys.includes(secret_key_ref)) {
2984
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "secret_not_in_vault", key: secret_key_ref, hint: "upsert_network_secret first" }) }] };
2985
+ }
2986
+ const providerId = `prov_${uuidv4()}`;
2987
+ try {
2988
+ db.run(
2989
+ `INSERT INTO providers (provider_id, network_id, name, vendor, base_url, secret_key_ref, created_at, created_by, enabled)
2990
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 1)`,
2991
+ [providerId, effectiveNetId || "default", name, vendor, base_url, secret_key_ref, Date.now(), enforceUserId || "unknown"],
2992
+ );
2993
+ } catch (e: any) {
2994
+ if (/UNIQUE constraint failed/.test(e?.message || "")) {
2995
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "provider_name_conflict", name }) }] };
2996
+ }
2997
+ throw e;
2998
+ }
2999
+ const modelIds: string[] = [];
3000
+ if (models) {
3001
+ for (const m of models) {
3002
+ const mid = `pm_${uuidv4()}`;
3003
+ db.run(
3004
+ `INSERT INTO provider_models (model_id, provider_id, model_name, display_name, context_window, supports_vision, enabled, created_at)
3005
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, ?7)`,
3006
+ [mid, providerId, m.model_name, m.display_name ?? null, m.context_window ?? null, m.supports_vision ? 1 : 0, Date.now()],
3007
+ );
3008
+ modelIds.push(mid);
3009
+ }
3010
+ }
3011
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, provider_id: providerId, model_ids: modelIds }) }] };
3012
+ },
3013
+ );
3014
+
3015
+ // §2.3.2 — update_provider (admin+; patch semantics). RFC-028 P1.5.
3016
+ // Single tool for editing existing providers — patch model: name/base_url/
3017
+ // models/enabled all optional, at least one required. Vendor and
3018
+ // secret_key_ref are IMMUTABLE via this tool (vendor change = create+delete;
3019
+ // secret change goes through upsert_network_secret first). network_id is
3020
+ // immutable (cross-tenant move forbidden).
3021
+ //
3022
+ // base_url change re-runs validateBaseUrl with vendor read from DB row
3023
+ // (NOT from patch) — defends against trying to widen host allowlist by
3024
+ // smuggling a new vendor name. zod .strict() on the wrapping object
3025
+ // surfaces extras as -32602 at MCP boundary (R3 lock, same as
3026
+ // ack_probe_request per #308 fold-in).
3027
+ //
3028
+ // Audit: every successful update writes audit_log with before/after diff
3029
+ // of the changed fields ONLY (no secret values — secret isn't a patch
3030
+ // field, no leak path).
3031
+ server.registerTool(
3032
+ "update_provider",
3033
+ {
3034
+ description: "Edit existing provider (name/base_url/models/enabled). Patch semantics — at least one field. Vendor/secret/network_id immutable. Admin+. RFC-028 P1.5.",
3035
+ inputSchema: z.object({
3036
+ provider_id: z.string().regex(/^prov_[a-zA-Z0-9_-]+$/).max(200),
3037
+ network_id: z.string().max(200).optional(),
3038
+ patch: z.object({
3039
+ name: z.string().min(1).max(100).optional(),
3040
+ base_url: z.string().min(1).max(500).optional(),
3041
+ models: z.array(z.object({
3042
+ model_name: z.string().min(1).max(100),
3043
+ display_name: z.string().max(100).optional(),
3044
+ context_window: z.number().int().min(0).optional(),
3045
+ supports_vision: z.boolean().optional(),
3046
+ })).optional(),
3047
+ enabled: z.boolean().optional(),
3048
+ }).strict(),
3049
+ }).strict() as any,
3050
+ },
3051
+ async (args: any) => {
3052
+ const { provider_id, network_id: clientNetId, patch } = args;
3053
+ const effectiveNetId = getNetworkId(clientNetId);
3054
+ if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
3055
+ const callerRole = enforceUserId && effectiveNetId
3056
+ ? getUserNetworkRole(enforceUserId, effectiveNetId)
3057
+ : null;
3058
+ if (callerRole !== "admin" && callerRole !== "owner") {
3059
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "insufficient_role_for_provider", required_role: "admin", caller_role: callerRole }) }] };
3060
+ }
3061
+
3062
+ // Empty patch — surface noop_no_changes (don't silently succeed)
3063
+ const patchKeys = Object.keys(patch || {});
3064
+ if (patchKeys.length === 0) {
3065
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "noop_no_changes", hint: "patch must include at least one of: name, base_url, models, enabled" }) }] };
3066
+ }
3067
+
3068
+ // SEC-1: row must exist within caller's network (SQL-level enforcement)
3069
+ const row = db.get<{ provider_id: string; vendor: string; name: string; base_url: string; enabled: number }>(
3070
+ `SELECT provider_id, vendor, name, base_url, enabled FROM providers WHERE provider_id = ?1 AND network_id = ?2`,
3071
+ provider_id, effectiveNetId || "default",
3072
+ );
3073
+ if (!row) {
3074
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "provider_not_found", provider_id }) }] };
3075
+ }
3076
+
3077
+ // base_url change → re-run validateBaseUrl with vendor from DB (not patch)
3078
+ if (patch.base_url !== undefined && patch.base_url !== row.base_url) {
3079
+ try {
3080
+ _validateBaseUrl(row.vendor, patch.base_url);
3081
+ } catch (e) {
3082
+ return probeFailReply(e);
3083
+ }
3084
+ }
3085
+
3086
+ // Diff staging — collect before/after for audit (NO secret values; secret
3087
+ // isn't a patch field). Skip fields that didn't actually change.
3088
+ const diff: Record<string, { before: unknown; after: unknown }> = {};
3089
+ const sets: string[] = [];
3090
+ const params: unknown[] = [];
3091
+ let paramIdx = 1;
3092
+ if (patch.name !== undefined && patch.name !== row.name) {
3093
+ sets.push(`name = ?${paramIdx++}`); params.push(patch.name);
3094
+ diff.name = { before: row.name, after: patch.name };
3095
+ }
3096
+ if (patch.base_url !== undefined && patch.base_url !== row.base_url) {
3097
+ sets.push(`base_url = ?${paramIdx++}`); params.push(patch.base_url);
3098
+ diff.base_url = { before: row.base_url, after: patch.base_url };
3099
+ }
3100
+ if (patch.enabled !== undefined) {
3101
+ const newEnabled = patch.enabled ? 1 : 0;
3102
+ if (newEnabled !== row.enabled) {
3103
+ sets.push(`enabled = ?${paramIdx++}`); params.push(newEnabled);
3104
+ diff.enabled = { before: row.enabled === 1, after: patch.enabled };
3105
+ }
3106
+ }
3107
+
3108
+ // Replace models list (if supplied) atomically with the providers UPDATE
3109
+ const willReplaceModels = patch.models !== undefined;
3110
+ const newModelIds: string[] = [];
3111
+
3112
+ // No-op early return (通信牛 nit): all patch fields matched the
3113
+ // existing row values + no models supplied → no real change to
3114
+ // persist. Returning here means we don't write an empty-diff
3115
+ // audit row (audit noise). Audit_log INSERT must only fire when
3116
+ // something actually changed.
3117
+ if (sets.length === 0 && !willReplaceModels) {
3118
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, provider_id, no_changes: true, hint: "patch fields matched existing row, no-op" }) }] };
3119
+ }
3120
+
3121
+ try {
3122
+ db.exec("BEGIN");
3123
+ if (sets.length > 0) {
3124
+ params.push(provider_id);
3125
+ try {
3126
+ db.run(`UPDATE providers SET ${sets.join(", ")} WHERE provider_id = ?${paramIdx}`, params);
3127
+ } catch (e: any) {
3128
+ if (/UNIQUE constraint failed/.test(e?.message || "")) {
3129
+ db.exec("ROLLBACK");
3130
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "provider_name_conflict", name: patch.name }) }] };
3131
+ }
3132
+ throw e;
3133
+ }
3134
+ }
3135
+ if (willReplaceModels) {
3136
+ db.run(`DELETE FROM provider_models WHERE provider_id = ?1`, [provider_id]);
3137
+ for (const m of patch.models) {
3138
+ const mid = `pm_${uuidv4()}`;
3139
+ db.run(
3140
+ `INSERT INTO provider_models (model_id, provider_id, model_name, display_name, context_window, supports_vision, enabled, created_at)
3141
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, ?7)`,
3142
+ [mid, provider_id, m.model_name, m.display_name ?? null, m.context_window ?? null, m.supports_vision ? 1 : 0, Date.now()],
3143
+ );
3144
+ newModelIds.push(mid);
3145
+ }
3146
+ diff.models = { before: "(prior list)", after: `${patch.models.length} models replaced` };
3147
+ }
3148
+ db.run(
3149
+ `INSERT INTO audit_log (user_id, username, action, target_type, target_id, detail, network_id)
3150
+ VALUES (?1, ?2, 'update_provider', 'provider', ?3, ?4, ?5)`,
3151
+ [enforceUserId || null, callerAlias || null, provider_id, JSON.stringify({ diff, fields_changed: Object.keys(diff) }), effectiveNetId || null],
3152
+ );
3153
+ db.exec("COMMIT");
3154
+ } catch (e: any) {
3155
+ try { db.exec("ROLLBACK"); } catch { /* ok */ }
3156
+ throw e;
3157
+ }
3158
+
3159
+ return { content: [{ type: "text" as const, text: JSON.stringify({
3160
+ ok: true, provider_id,
3161
+ fields_changed: Object.keys(diff),
3162
+ models_replaced: willReplaceModels ? newModelIds.length : null,
3163
+ }) }] };
3164
+ },
3165
+ );
3166
+
3167
+ // §2.3.3 — list_providers (viewer+; never returns secret VALUES).
3168
+ server.tool(
3169
+ "list_providers",
3170
+ "List providers + models in the caller's network. Never returns secret VALUES. RFC-028.",
3171
+ { network_id: z.string().max(200).optional() },
3172
+ async ({ network_id: clientNetId }) => {
3173
+ const effectiveNetId = getNetworkId(clientNetId);
3174
+ // viewer access: caller must be member of network (read access)
3175
+ if (enforceUserId) {
3176
+ const role = getUserNetworkRole(enforceUserId, effectiveNetId || "default");
3177
+ if (!role) return writeDeniedReply(effectiveNetId, "read");
3178
+ }
3179
+ const providers = db.all<any>(
3180
+ `SELECT provider_id, name, vendor, base_url, secret_key_ref, enabled FROM providers WHERE network_id = ?1 AND enabled = 1 ORDER BY name`,
3181
+ effectiveNetId || "default",
3182
+ );
3183
+ const out = providers.map(p => {
3184
+ const models = db.all<any>(
3185
+ `SELECT model_id, model_name, display_name, context_window, supports_vision, enabled FROM provider_models WHERE provider_id = ?1 AND enabled = 1 ORDER BY model_name`,
3186
+ p.provider_id,
3187
+ );
3188
+ return { ...p, in_vault: true, models }; // in_vault: true since we required it on upsert
3189
+ });
3190
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, providers: out }) }] };
3191
+ },
3192
+ );
3193
+
3194
+ // §2.3.5 — probe_provider_model (admin+; dispatches to daemon).
3195
+ server.tool(
3196
+ "probe_provider_model",
3197
+ "Dispatch a connectivity probe to a daemon. Mints ephemeral secret blob; daemon pulls via get_probe_request. Admin+. RFC-028.",
3198
+ {
3199
+ provider_id: z.string().min(1).max(200),
3200
+ model_name: z.string().min(1).max(100),
3201
+ daemon_node_id: z.string().min(1).max(200),
3202
+ network_id: z.string().max(200).optional(),
3203
+ },
3204
+ async ({ provider_id, model_name, daemon_node_id, network_id: clientNetId }) => {
3205
+ const effectiveNetId = getNetworkId(clientNetId);
3206
+ if (!canWrite(effectiveNetId)) return writeDeniedReply(effectiveNetId, "write");
3207
+ const callerRole = enforceUserId && effectiveNetId
3208
+ ? getUserNetworkRole(enforceUserId, effectiveNetId)
3209
+ : null;
3210
+ if (callerRole !== "admin" && callerRole !== "owner") {
3211
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "insufficient_role_for_probe", required_role: "admin", caller_role: callerRole }) }] };
3212
+ }
3213
+ // Resolve provider + model (network-scoped). Distinguish "not found"
3214
+ // from "disabled" so the dashboard can render the right error
3215
+ // (P1.5 dashboard编辑/停用 needs this to explain why probe rejected).
3216
+ const provider = db.get<any>(
3217
+ `SELECT provider_id, vendor, base_url, secret_key_ref, enabled FROM providers WHERE provider_id = ?1 AND network_id = ?2`,
3218
+ provider_id, effectiveNetId || "default",
3219
+ );
3220
+ if (!provider) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "provider_not_found", provider_id }) }] };
3221
+ if (provider.enabled !== 1) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "provider_disabled", provider_id, hint: "update_provider with enabled:true to re-enable" }) }] };
3222
+ const model = db.get<any>(
3223
+ `SELECT model_id, model_name FROM provider_models WHERE provider_id = ?1 AND model_name = ?2 AND enabled = 1`,
3224
+ provider_id, model_name,
3225
+ );
3226
+ if (!model) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "model_not_found", model_name }) }] };
3227
+ // Resolve daemon (must be in caller network)
3228
+ const { row: daemon, sec1Ok } = resolveTargetNode(daemon_node_id, effectiveNetId);
3229
+ if (!daemon) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "daemon_not_found" }) }] };
3230
+ if (!sec1Ok) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "cross_network_node" }) }] };
3231
+ // Vault decrypt the API key (may throw VaultError)
3232
+ let apiKey: string;
3233
+ try {
3234
+ const v = vaultGet(effectiveNetId || "default", provider.secret_key_ref);
3235
+ if (!v) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "secret_not_in_vault", key: provider.secret_key_ref }) }] };
3236
+ apiKey = v;
3237
+ } catch (e) { return probeFailReply(e); }
3238
+ // Mint probe row + stash ephemeral blob
3239
+ const probeId = newProbeId();
3240
+ db.run(
3241
+ `INSERT INTO probe_results (probe_id, provider_id, model_name, daemon_node_id, network_id, status, probed_at, probed_by_user)
3242
+ VALUES (?1, ?2, ?3, ?4, ?5, 'pending', ?6, ?7)`,
3243
+ [probeId, provider_id, model_name, daemon_node_id, effectiveNetId || "default", Date.now(), enforceUserId || null],
3244
+ );
3245
+ putPendingProbeSecret({
3246
+ probe_id: probeId,
3247
+ daemon_node_id,
3248
+ provider_id,
3249
+ vendor: provider.vendor,
3250
+ base_url: provider.base_url,
3251
+ model_name,
3252
+ api_key: apiKey,
3253
+ network_id: effectiveNetId || "default",
3254
+ });
3255
+ pushEvent(daemon.alias, { type: "probe_provider", probe_id: probeId }, daemon.network_id || effectiveNetId || "default");
3256
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, probe_id: probeId }) }] };
3257
+ },
3258
+ );
3259
+
3260
+ // §2.3.6 — get_probe_results (viewer+; matrix renderer source).
3261
+ server.tool(
3262
+ "get_probe_results",
3263
+ "Query probe history (optionally filtered by provider/model/daemon). Used by dashboard reachability matrix. RFC-028.",
3264
+ {
3265
+ provider_id: z.string().max(200).optional(),
3266
+ model_name: z.string().max(100).optional(),
3267
+ daemon_node_id: z.string().max(200).optional(),
3268
+ limit: z.number().int().min(1).max(500).optional(),
3269
+ network_id: z.string().max(200).optional(),
3270
+ },
3271
+ async ({ provider_id, model_name, daemon_node_id, limit, network_id: clientNetId }) => {
3272
+ const effectiveNetId = getNetworkId(clientNetId);
3273
+ if (enforceUserId) {
3274
+ const role = getUserNetworkRole(enforceUserId, effectiveNetId || "default");
3275
+ if (!role) return writeDeniedReply(effectiveNetId, "read");
3276
+ }
3277
+ const where: string[] = ["network_id = ?1"];
3278
+ const params: any[] = [effectiveNetId || "default"];
3279
+ if (provider_id) { where.push(`provider_id = ?${params.length + 1}`); params.push(provider_id); }
3280
+ if (model_name) { where.push(`model_name = ?${params.length + 1}`); params.push(model_name); }
3281
+ if (daemon_node_id) { where.push(`daemon_node_id = ?${params.length + 1}`); params.push(daemon_node_id); }
3282
+ const sql = `SELECT probe_id, provider_id, model_name, daemon_node_id, status, latency_ms, error_label, probed_at, raw_status_code FROM probe_results WHERE ${where.join(" AND ")} ORDER BY probed_at DESC LIMIT ${limit ?? 100}`;
3283
+ const rows = db.all<any>(sql, ...params);
3284
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, results: rows }) }] };
3285
+ },
3286
+ );
3287
+
3288
+ // §2.3.7 daemon-facing — get_probe_request.
3289
+ server.tool(
3290
+ "get_probe_request",
3291
+ "Daemon pulls a pending probe request (called when SSE probe_provider doorbell arrives). RFC-028.",
3292
+ { probe_id: z.string().min(1).max(200) },
3293
+ async ({ probe_id }) => {
3294
+ const callerDaemon = _resolveCallerDaemonTokenBound({ callerTokenIsNetwork, callerTokenId, enforceNetworkId });
3295
+ if (!callerDaemon.ok) {
3296
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
3297
+ }
3298
+ // takePendingProbeSecret enforces daemon binding + evicts
3299
+ const blob = (await import("./probe.js")).takePendingProbeSecret(probe_id, callerDaemon.daemonNodeId);
3300
+ if (!blob) {
3301
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "probe_request_unavailable", reason: "not_found_or_wrong_daemon_or_expired" }) }] };
3302
+ }
3303
+ return { content: [{ type: "text" as const, text: JSON.stringify({
3304
+ ok: true,
3305
+ probe_id: blob.probe_id,
3306
+ vendor: blob.vendor,
3307
+ base_url: blob.base_url,
3308
+ model_name: blob.model_name,
3309
+ api_key: blob.api_key, // ephemeral; daemon writes to .env.local or in-memory only
3310
+ }) }] };
3311
+ },
3312
+ );
3313
+
3314
+ // §2.3.8 daemon-facing — ack_probe_request (STRICT whitelist via zod).
3315
+ // R3 LOCK (RFC-028 v3): ack payload has EXACTLY 4 keys. We pass a
3316
+ // ZodObject with .strict() so the MCP SDK's validateToolInput surfaces
3317
+ // any extra field (e.g. an attacker smuggling `error_message` to leak a
3318
+ // secret) as a -32602 Invalid params error at the protocol boundary
3319
+ // BEFORE our handler runs. The SDK invokes z.object(shape) by default
3320
+ // which is strip-mode; passing a fully-constructed strict object
3321
+ // bypasses that and enforces unknownKeys='strict'.
3322
+ server.registerTool(
3323
+ "ack_probe_request",
3324
+ {
3325
+ description: "Daemon acks a probe. Schema is STRICT whitelist (no error_message; v3 R3 LOCK). RFC-028.",
3326
+ // Strict-mode ZodObject so the MCP SDK's validateToolInput surfaces
3327
+ // any extra field as a -32602 Invalid params error BEFORE the
3328
+ // handler runs. server.tool() accepts only ZodRawShape (default
3329
+ // strip-mode); registerTool() accepts a constructed ZodObject and
3330
+ // honors its unknownKeys policy.
3331
+ inputSchema: z.object({
3332
+ probe_id: z.string().min(1).max(200),
3333
+ status: z.enum(["ok", "auth_fail", "quota", "rate_limit", "network_error", "timeout", "redirect_forbidden", "vendor_5xx", "other_4xx", "tls_error", "probe_resolve_unsafe_ip", "probe_target_forbidden"]),
3334
+ raw_status_code: z.number().int().min(100).max(599).optional(),
3335
+ latency_ms: z.number().int().min(0).max(60_000),
3336
+ }).strict() as any,
3337
+ },
3338
+ async (args: any) => {
3339
+ const callerDaemon = _resolveCallerDaemonTokenBound({ callerTokenIsNetwork, callerTokenId, enforceNetworkId });
3340
+ if (!callerDaemon.ok) {
3341
+ return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: callerDaemon.error }) }] };
3342
+ }
3343
+ try {
3344
+ const r = finalizeProbeAck(args, { network_id: callerDaemon.networkId, daemon_node_id: callerDaemon.daemonNodeId });
3345
+ return { content: [{ type: "text" as const, text: JSON.stringify(r) }] };
3346
+ } catch (e) {
3347
+ return probeFailReply(e);
3348
+ }
3349
+ },
3350
+ );
1754
3351
  }
1755
3352
 
1756
3353
  // ────────────────────────────────────────────────────────────────────
@@ -1839,10 +3436,144 @@ export function upsertNodeWithSec1Guard(input: UpsertNodeWithSec1GuardInput): Up
1839
3436
  ],
1840
3437
  );
1841
3438
  if (input.config_snapshot) {
3439
+ // RFC-026 §9.3 / #338 PR2+PR3 — promote daemon self-declare fields
3440
+ // to first-class indexable columns alongside the snapshot blob.
3441
+ // The snapshot stays the source of truth for non-list reads; the
3442
+ // columns exist so `list_host_supervisors` doesn't JSON.parse on
3443
+ // every call. typeof-narrow per
3444
+ // [[feedback_typeof_narrow_extracted_fields]] — zod narrowed but
3445
+ // input.config_snapshot is typed `unknown` here.
3446
+ //
3447
+ // PR3 nit ①: read from nested `daemon_capabilities.*` (canonical
3448
+ // per RFC §9.3 + matches existing hub create_node reads at
3449
+ // tools.ts:2010/2075). PR2 ate from top-level keys, which the
3450
+ // hub create_node path never read → max_concurrent_children
3451
+ // backpressure was dead config + allowlist enforcement bypassed.
3452
+ const snap = input.config_snapshot as Record<string, unknown> | null;
3453
+ const caps = (snap?.daemon_capabilities ?? null) as Record<string, unknown> | null;
3454
+ const runtimesRaw = caps?.runtimes_supported;
3455
+ const allowedRaw = caps?.allowed_secret_keys;
3456
+ const runtimesJson = Array.isArray(runtimesRaw) && runtimesRaw.every(s => typeof s === "string")
3457
+ ? JSON.stringify(runtimesRaw)
3458
+ : null;
3459
+ const allowedJson = Array.isArray(allowedRaw) && allowedRaw.every(s => typeof s === "string")
3460
+ ? JSON.stringify(allowedRaw)
3461
+ : null;
1842
3462
  db.run(
1843
- `UPDATE nodes SET config_snapshot = ?1 WHERE node_id = ?2`,
1844
- [JSON.stringify(input.config_snapshot), input.node_id],
3463
+ `UPDATE nodes SET config_snapshot = ?1, runtimes_supported = ?2, allowed_secret_keys = ?3 WHERE node_id = ?4`,
3464
+ [JSON.stringify(input.config_snapshot), runtimesJson, allowedJson, input.node_id],
1845
3465
  );
3466
+ // RFC-024 — finalize any pending/restarting update whose target
3467
+ // patch is now reflected in the snapshot. Closes the
3468
+ // restart-required-never-reaches-applied gap that 通信牛 caught:
3469
+ // the old child acks `restarting` + exits 75; the new child boots,
3470
+ // reads the new config, reports status — but never had the
3471
+ // update_id to call ack_config_update(applied) itself. Hub does
3472
+ // it on the new child's behalf by content-matching the patch
3473
+ // against the reported snapshot.
3474
+ finalizePendingMatchingUpdates(input.node_id, input.config_snapshot);
3475
+ }
3476
+ // RFC-026 §2.5 step 4 — on every register/report_status, opportunistically
3477
+ // close out any pending create_node request whose child_name matches
3478
+ // this incoming alias. Same content-match pattern as RFC-024's
3479
+ // finalizePendingMatchingUpdates; the new child doesn't have the
3480
+ // request_id, so hub does the matching on its behalf.
3481
+ try {
3482
+ finalizeCreateOnFirstRegister({
3483
+ node_id: input.node_id,
3484
+ alias: input.alias || input.node_name || "",
3485
+ network_id: input.callerNetworkId ?? null,
3486
+ });
3487
+ } catch (e: any) {
3488
+ // create-node finalize is best-effort — never block report_status
3489
+ // on it. Log + continue.
3490
+ console.warn(`[commhub] create-node finalize on report_status failed: ${e?.message || e}`);
1846
3491
  }
1847
3492
  return { result: existing ? "updated" : "inserted", node_id: input.node_id };
1848
3493
  }
3494
+
3495
+ /**
3496
+ * RFC-024 restart-finalize (Option A per 通信牛 final review).
3497
+ *
3498
+ * Called from `upsertNodeWithSec1Guard` after writing a fresh
3499
+ * `config_snapshot` for the node. For each pending/restarting update
3500
+ * row, parse the patch and compare every field against the snapshot.
3501
+ * If everything in the patch is now reflected in the live snapshot,
3502
+ * mark the update applied + bump `nodes.config_revision`. The new
3503
+ * child doesn't need to know the update_id — content-matching against
3504
+ * the live state IS the proof that the apply landed.
3505
+ *
3506
+ * Edge cases:
3507
+ * - Empty patch (apply_mode=restart_only from `restart_node` tool) →
3508
+ * ANY snapshot matches (the restart itself was the goal).
3509
+ * - Patch field absent from snapshot → not a match (snapshot
3510
+ * post-dates the apply only when every requested field shows up).
3511
+ * - Multiple concurrent pending rows → impossible by single-flight,
3512
+ * but defensive: finalize OLDEST first so the chain stays linear.
3513
+ *
3514
+ * Pure-ish: takes a snapshot blob (TS shape, see config-snapshot type)
3515
+ * and runs only db.run / db.get. No external IO.
3516
+ */
3517
+ export function finalizePendingMatchingUpdates(
3518
+ nodeId: string,
3519
+ snapshot: any,
3520
+ ): { finalizedCount: number; finalizedIds: string[] } {
3521
+ const pending = db.all<{
3522
+ update_id: string;
3523
+ patch_json: string;
3524
+ apply_mode: string;
3525
+ base_revision: number;
3526
+ }>(
3527
+ "SELECT update_id, patch_json, apply_mode, base_revision FROM node_config_updates WHERE node_id = ?1 AND status IN ('pending', 'restarting') ORDER BY created_at ASC",
3528
+ nodeId,
3529
+ );
3530
+ if (pending.length === 0) return { finalizedCount: 0, finalizedIds: [] };
3531
+
3532
+ const snapModel: string | null | undefined = snapshot?.model;
3533
+ const snapFlags: Record<string, unknown> = (snapshot?.flags && typeof snapshot.flags === "object") ? snapshot.flags : {};
3534
+
3535
+ const finalizedIds: string[] = [];
3536
+
3537
+ for (const row of pending) {
3538
+ let patch: any = {};
3539
+ try { patch = JSON.parse(row.patch_json); } catch { continue; }
3540
+
3541
+ let matches = true;
3542
+ // restart_only / empty patch → any snapshot proves the restart
3543
+ // happened, finalize unconditionally.
3544
+ if (row.apply_mode !== "restart_only") {
3545
+ if (patch.model !== undefined) {
3546
+ if (snapModel !== patch.model) { matches = false; }
3547
+ }
3548
+ if (matches && patch.flags && typeof patch.flags === "object") {
3549
+ for (const [k, v] of Object.entries(patch.flags as Record<string, unknown>)) {
3550
+ // Canonical-key fallback for legacy aliases. The dashboard
3551
+ // schema uses `budget` and `timeout`; node-side config may
3552
+ // also carry the older `maxBudgetUsd` / `claudeTimeoutMs` /
3553
+ // `codexTimeoutMs` keys. agent-node's buildConfigSnapshot
3554
+ // only reports the canonical key, so we just compare on `k`.
3555
+ if (snapFlags[k] !== v) { matches = false; break; }
3556
+ }
3557
+ }
3558
+ }
3559
+
3560
+ if (!matches) continue;
3561
+
3562
+ // Promote nodes.config_revision atomically with the update row.
3563
+ const nextRev = (db.get<{ config_revision: number }>(
3564
+ "SELECT config_revision FROM nodes WHERE node_id = ?1",
3565
+ nodeId,
3566
+ )?.config_revision || 0) + 1;
3567
+ db.run(
3568
+ "UPDATE node_config_updates SET status = 'applied', acked_at = ?1, new_revision = ?2 WHERE update_id = ?3 AND status IN ('pending', 'restarting')",
3569
+ [Date.now(), nextRev, row.update_id],
3570
+ );
3571
+ db.run("UPDATE nodes SET config_revision = ?1 WHERE node_id = ?2", [nextRev, nodeId]);
3572
+ finalizedIds.push(row.update_id);
3573
+ console.log(
3574
+ `[commhub] ✓ finalize update ${row.update_id} via report_status content-match: node=${nodeId} new_revision=${nextRev} apply_mode=${row.apply_mode}`,
3575
+ );
3576
+ }
3577
+
3578
+ return { finalizedCount: finalizedIds.length, finalizedIds };
3579
+ }