agentschat-mcp 0.36.24 → 0.36.26

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.
Files changed (84) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +8 -0
  3. package/codex/README.md +1 -1
  4. package/codex/app-server.ts +79 -22
  5. package/codex/bots-config.ts +31 -11
  6. package/codex/bridge.ts +123 -25
  7. package/codex/config.ts +128 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +65 -12
  10. package/codex/loop-grants.ts +41 -11
  11. package/codex/manager.ts +101 -25
  12. package/codex/owner.ts +81 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +41 -11
  16. package/codex/thread-history.ts +77 -30
  17. package/codex/transport.ts +122 -19
  18. package/connector/auth.ts +57 -5
  19. package/connector/backfill.ts +92 -10
  20. package/connector/descriptor.ts +27 -1
  21. package/connector/identities.ts +82 -14
  22. package/connector/ingest.ts +11 -2
  23. package/connector/normalize.ts +32 -12
  24. package/connector/run.ts +314 -67
  25. package/connector/server.ts +95 -26
  26. package/dist/codex-bots.js +410 -73
  27. package/dist/codex-bridge.js +1996 -576
  28. package/dist/connector.js +1286 -493
  29. package/dist/dsh.js +1776 -299
  30. package/dist/muse.js +967 -221
  31. package/dist/server.js +7645 -1172
  32. package/dsh/client.js +7 -5
  33. package/dsh/identity-ui/client.js +7 -5
  34. package/dsh/identity-ui/index.js +43 -8
  35. package/dsh/inbound-bridge/index.js +595 -146
  36. package/dsh/src/cli.ts +430 -91
  37. package/dsh/src/patch.ts +295 -15
  38. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  39. package/dsh/tests/dsh.test.ts +990 -3
  40. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  41. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  42. package/muse/src/bridge.ts +54 -13
  43. package/muse/src/cli.ts +226 -41
  44. package/muse/src/client.ts +249 -34
  45. package/muse/src/config.ts +128 -12
  46. package/muse/src/policy.ts +28 -8
  47. package/muse/src/types.ts +1 -0
  48. package/muse/src/typing.ts +18 -1
  49. package/muse/src/wake.ts +237 -35
  50. package/muse/tests/bridge.test.mjs +131 -0
  51. package/muse/tests/client.test.mjs +327 -0
  52. package/muse/tests/config.test.mjs +78 -1
  53. package/muse/tests/hardening.test.mjs +199 -0
  54. package/muse/tests/hardening126.test.mjs +292 -0
  55. package/muse/tests/policy.test.mjs +83 -1
  56. package/muse/tests/wake.test.mjs +134 -6
  57. package/package.json +3 -3
  58. package/scripts/ensure-grok-wakes.mjs +93 -8
  59. package/scripts/example-url-wake-receiver.mjs +254 -61
  60. package/scripts/grok-bind-register.sh +38 -8
  61. package/skills/agentschat-team-lead/SKILL.md +1 -1
  62. package/skills/onboarding.md +14 -10
  63. package/src/argcheck.ts +1890 -1
  64. package/src/cli.mjs +98 -14
  65. package/src/dedup.ts +57 -8
  66. package/src/grok-bind.ts +160 -33
  67. package/src/heartbeat.ts +39 -11
  68. package/src/identity-guard.ts +93 -20
  69. package/src/identity.ts +67 -11
  70. package/src/mentions.ts +26 -5
  71. package/src/onboarding-status.ts +134 -11
  72. package/src/profile-selection.ts +269 -18
  73. package/src/profile-store.ts +222 -28
  74. package/src/read-cursor.ts +256 -9
  75. package/src/reconnect.ts +98 -2
  76. package/src/redact.ts +34 -15
  77. package/src/rest-cli.ts +713 -159
  78. package/src/server.ts +2487 -342
  79. package/src/session-bind.ts +731 -132
  80. package/src/session-route.ts +183 -12
  81. package/src/team-lead-skill.ts +3 -0
  82. package/src/timestamps.ts +56 -23
  83. package/src/tool-annotations.ts +22 -1
  84. package/src/wake.ts +524 -90
package/src/server.ts CHANGED
@@ -44,9 +44,50 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
44
44
  import { isHumanPiiHandle, redactParticipantPii, redactSecrets } from "./redact.ts";
45
45
  import { matchesMention } from "./mentions.ts";
46
46
  import { messageDedupKey, MessageDedup } from "./dedup.ts";
47
- import { computeReconnectDelay } from "./reconnect.ts";
47
+ import {
48
+ computePleaseReconnectDelay,
49
+ computeReconnectDelay,
50
+ resolveDrainReconnectDelay,
51
+ withTimeoutController,
52
+ } from "./reconnect.ts";
48
53
  import { normalizeTimestampForCursor } from "./timestamps.ts";
49
- import { validateToolArgs } from "./argcheck.ts";
54
+ import {
55
+ CREATE_LOOP_MODES,
56
+ CHANNEL_DOC_KINDS,
57
+ TASK_EVIDENCE_KINDS,
58
+ type TaskEvidenceInput,
59
+ mergeLegacyTaskEvidence,
60
+ responseIncludesAppendedEvidence,
61
+ validateAppendTaskEvidenceInput,
62
+ validateArchiveChannelDocInput,
63
+ validateChannelDocIdInput,
64
+ validateCreateLoopInput,
65
+ validateDeleteMemoryInput,
66
+ validateListChannelDocsInput,
67
+ validateListLoopsInput,
68
+ validateLoadMemoryInput,
69
+ validateOkrAddKrInput,
70
+ validateOkrArchiveObjectiveInput,
71
+ validateOkrLinkedChannelDocsInput,
72
+ validateOkrObjectiveNarrativeInput,
73
+ validateOkrParentIdOptionalInput,
74
+ validateOkrReparentObjectiveInput,
75
+ validateOkrSetKrProgressInput,
76
+ validateOkrTaskAssigneeInput,
77
+ validateOkrTaskContributesToInput,
78
+ validateOkrTaskDependsOnInput,
79
+ validateOkrTaskDueInput,
80
+ validateOkrTaskTitleInput,
81
+ validateLoadSkillInput,
82
+ validateOkrUpdateKrInput,
83
+ validateOkrUpdateObjectiveInput,
84
+ validatePersonalSkillSlugInput,
85
+ validateSaveSkillInput,
86
+ validateTaskEvidenceInput,
87
+ validateTaskVersionToken,
88
+ validateToolArgs,
89
+ validateUpsertChannelDocInput,
90
+ } from "./argcheck.ts";
50
91
  import { decideIdentity, shouldMigrateDevToken, validateIdentityProfile } from "./identity.ts";
51
92
  import { projectProfileSelector } from "./profile-selection.ts";
52
93
  import type { ProfileSource } from "./identity.ts";
@@ -56,6 +97,7 @@ import {
56
97
  resolveGrokBindsPath,
57
98
  DEFAULT_GROK_BINDS_FILENAME,
58
99
  boundProfileForConversation,
100
+ gateGrokProfileMutation,
59
101
  gateSwitchProfile,
60
102
  grokBindApplies,
61
103
  nonGrokWakeReason,
@@ -75,6 +117,8 @@ import {
75
117
  resolveGrokGatewayPath,
76
118
  grokBearerFromGatewayConfig,
77
119
  grokPortFromGatewayConfig,
120
+ resolveEnvWakeId,
121
+ WAKE_ID_HEADER,
78
122
  } from "./wake.ts";
79
123
  import {
80
124
  DEFAULT_SESSION_BINDS_FILENAME,
@@ -104,6 +148,7 @@ import {
104
148
 
105
149
  // --- Config: CLI args > env vars > profile file > defaults ---
106
150
  import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "fs";
151
+ import { homedir } from "os";
107
152
  import { join, dirname } from "path";
108
153
  import { fileURLToPath } from "url";
109
154
  // Atomic + 0600-by-construction profile writer. Lives in its own module so the
@@ -122,7 +167,7 @@ import {
122
167
  type IdentityGuardRecord,
123
168
  } from "./identity-guard.ts";
124
169
  // Read-cursor persistence: a state change that merely *lives* in the teardown path.
125
- import { flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
170
+ import { cursorFileForAgent, flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
126
171
  import { CURSOR_INIT_KEY, joinChannelRest, parseMaxIdleMs, sendRestMessage, wakeOnce } from "./rest-cli.ts";
127
172
  import { randomUUID } from "crypto";
128
173
 
@@ -146,7 +191,7 @@ function parseArgs() {
146
191
  ]);
147
192
  for (let i = 0; i < args.length; i++) {
148
193
  const arg = args[i];
149
- if (arg === "--help" || arg === "-h") continue;
194
+ if (arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v") continue;
150
195
  if (arg === "--register") { parsed.register = "1"; continue; }
151
196
  if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
152
197
  if (arg === "--wake-once") { parsed.wakeOnce = "1"; continue; }
@@ -170,6 +215,11 @@ function parseArgs() {
170
215
  const cliArgs = parseArgs();
171
216
  const isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
172
217
 
218
+ if (process.argv.includes("--version") || process.argv.includes("-v")) {
219
+ console.log(`agentschat-mcp v${pkg.version}`);
220
+ process.exit(0);
221
+ }
222
+
173
223
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
174
224
  const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
175
225
  console.log(`agentschat-mcp v${pkg.version} — AgentsChat MCP and host bridges
@@ -199,8 +249,8 @@ Options:
199
249
  --reply-to <id> Optional target message ID for --send.
200
250
  --wake-once Wait via HTTPS SSE + REST cursor for the next @mention or DM, print wake JSON + prompt, advance per-channel cursor, and exit 0.
201
251
  --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
202
- --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
203
- --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
252
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240; pass 0 to listen continuously).
253
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: never / 0; e.g. 1h, 3h, never).
204
254
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
205
255
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
206
256
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -209,6 +259,7 @@ Options:
209
259
  explicitly selected profile. Skips registration entirely.
210
260
  --caps <a,b,c> Capabilities (comma-separated)
211
261
  --supervise Respawn on crash (or AGENTCHAT_WAKE_SUPERVISE=1); for wake daemons
262
+ -v, --version Print package version and exit
212
263
  -h, --help Show this help
213
264
 
214
265
  Wake a host that has no channel-notification surface (Grok Bot, generic MCP clients):
@@ -266,7 +317,7 @@ if (codexIdentity) {
266
317
  delete process.env.AGENTCHAT_TOKEN;
267
318
  process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
268
319
  }
269
- const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
320
+ const homeDir = process.env.HOME || process.env.USERPROFILE || homedir() || ".";
270
321
  const configDir = join(homeDir, ".agentschat");
271
322
  const legacyConfigDir = join(homeDir, ".agentchat");
272
323
  const profileDirs = [configDir, legacyConfigDir];
@@ -288,15 +339,16 @@ let dshRouteWarned = false;
288
339
  function profileNameToPaths(name: string): string[] {
289
340
  if (name.startsWith("~/")) return [join(homeDir, name.slice(2))];
290
341
  if (name.includes("/") || name.includes("\\")) return [name]; // explicit path
291
- name = name.replace(/\.json$/, "");
342
+ name = name.replace(/\.json$/i, "");
292
343
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
293
344
  return profileDirs.map((dir) => join(dir, `${safeName}.json`));
294
345
  }
295
346
 
296
347
  function nameToPath(name: string): string {
297
348
  const candidates = profileNameToPaths(name);
298
- const nested = join(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
299
- if (!name.includes("/") && !name.includes("\\") && existsSync(nested)) return nested;
349
+ const safeBase = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
350
+ const nested = join(configDir, "profiles", safeBase + ".json");
351
+ if (!name.includes("/") && !name.includes("\\") && safeBase && existsSync(nested)) return nested;
300
352
  return candidates.find((path) => existsSync(path)) || candidates[0];
301
353
  }
302
354
 
@@ -305,15 +357,16 @@ function listProfileFiles(): Array<{ name: string; path: string }> {
305
357
  const profiles: Array<{ name: string; path: string }> = [];
306
358
  for (const dir of [join(configDir, "profiles"), ...profileDirs]) {
307
359
  let files: string[] = [];
308
- try { files = readdirSync(dir).filter((f: string) => f.endsWith(".json")); } catch {}
360
+ try { files = readdirSync(dir).filter((f: string) => /\.json$/i.test(f)); } catch {}
309
361
  for (const file of files) {
362
+ const lowerFile = file.toLowerCase();
310
363
  if (
311
- file === DEFAULT_GROK_BINDS_FILENAME ||
312
- file === GROK_BINDS_META_FILENAME ||
313
- file === DEFAULT_SESSION_BINDS_FILENAME ||
314
- file === LEGACY_AGY_BINDS_FILENAME
364
+ lowerFile === DEFAULT_GROK_BINDS_FILENAME.toLowerCase() ||
365
+ lowerFile === GROK_BINDS_META_FILENAME.toLowerCase() ||
366
+ lowerFile === DEFAULT_SESSION_BINDS_FILENAME.toLowerCase() ||
367
+ lowerFile === LEGACY_AGY_BINDS_FILENAME.toLowerCase()
315
368
  ) continue; // bind map, not a profile
316
- const name = file.replace(/\.json$/, "");
369
+ const name = file.replace(/\.json$/i, "");
317
370
  if (seen.has(name)) continue;
318
371
  seen.add(name);
319
372
  profiles.push({ name, path: join(dir, file) });
@@ -448,15 +501,24 @@ async function apiFetch(
448
501
  input: string | URL,
449
502
  init: RequestInit = {},
450
503
  timeoutMs = REST_TIMEOUT_MS,
504
+ bufferBody = false,
451
505
  ): Promise<Response> {
452
506
  const headers: Record<string, string> = { ...(init.headers as Record<string, string> | undefined) };
453
507
  if (TOKEN && !("Authorization" in headers)) headers["Authorization"] = `Bearer ${TOKEN}`;
454
- const controller = new AbortController();
455
- const timer = setTimeout(() => controller.abort(), timeoutMs);
508
+ if (TOKEN && !(WAKE_ID_HEADER in headers)) {
509
+ const wakeId = resolveEnvWakeId();
510
+ if (wakeId) headers[WAKE_ID_HEADER] = wakeId;
511
+ }
512
+ const { signal, cleanup } = withTimeoutController(init.signal, timeoutMs);
456
513
  try {
457
- return await nativeFetch(input as any, { ...init, headers, signal: init.signal ?? controller.signal });
514
+ const response = await nativeFetch(input as any, { ...init, headers, signal });
515
+ if (!bufferBody) return response;
516
+ // Keep the abort deadline active until the body is consumed. Headers alone
517
+ // must not mark a stalled JSON response as complete.
518
+ const body = await response.text();
519
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
458
520
  } finally {
459
- clearTimeout(timer);
521
+ cleanup();
460
522
  }
461
523
  }
462
524
 
@@ -524,12 +586,14 @@ if (identity.mode === "profile") {
524
586
  process.exit(1);
525
587
  }
526
588
  const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
527
- if (!isOneShotCli && !toolOnlyMode) ensureRuntimeSession();
589
+ const activeRuntimeSession: DetectedSession | null = (!isOneShotCli && !toolOnlyMode)
590
+ ? ensureRuntimeSession()
591
+ : runtimeSession;
528
592
  const lockCheck = (!isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
529
593
  ? checkAgentLock({
530
594
  lockDir,
531
595
  agentId: candidateAgentId,
532
- currentSessionId: runtimeSession?.sessionId ?? null,
596
+ currentSessionId: activeRuntimeSession?.sessionId ?? null,
533
597
  lockOwnerPid,
534
598
  })
535
599
  : { locked: false };
@@ -717,8 +781,9 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
717
781
  if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
718
782
  let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
719
783
  const isAgyUuid = (sid: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
784
+ const currentRuntimeSession = ensureRuntimeSession();
720
785
  const isImplicitAgyBoot =
721
- (runtimeSession?.runtime === "antigravity" || (!runtimeSession && Boolean(discoverAntigravityHost()))) &&
786
+ (currentRuntimeSession?.runtime === "antigravity" || (!currentRuntimeSession && Boolean(discoverAntigravityHost()))) &&
722
787
  !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
723
788
  if (activeName && isImplicitAgyBoot) {
724
789
  const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
@@ -891,7 +956,7 @@ if (TOKEN && TOKEN !== "dev-token") {
891
956
  if (cliArgs.registerOnly) {
892
957
  try {
893
958
  mkdirSync(configDir, { recursive: true });
894
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
959
+ const lastSeenFile = cursorFileForAgent(configDir, AGENT_ID);
895
960
  const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
896
961
  if (!cursor.get(CURSOR_INIT_KEY)) {
897
962
  cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
@@ -944,6 +1009,8 @@ function startTypingHeartbeat(channelId: string, slot: ProfileSlot | null = acti
944
1009
  sendTypingFrame(channelId, slot); // immediate first pulse
945
1010
  const interval = setInterval(() => sendTypingFrame(channelId, slot), TYPING_HEARTBEAT_MS);
946
1011
  const cap = setTimeout(() => stopTypingHeartbeat(channelId, slot), TYPING_HEARTBEAT_MAX_MS);
1012
+ (interval as any).unref?.();
1013
+ (cap as any).unref?.();
947
1014
  typingHeartbeats.set(typingHeartbeatKey(channelId, agentId), { interval, cap });
948
1015
  }
949
1016
  function stopTypingHeartbeat(channelId: string, slot: ProfileSlot | null = activeSlot) {
@@ -1051,7 +1118,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
1051
1118
  "1. Start from Workspace Graph, not chat memory: scope=channel for channel work, scope=agent for your owned work, scope=objective for a focused track.",
1052
1119
  "2. Map non-trivial work into OKR tasks, DAG dependencies, or channel docs.",
1053
1120
  "3. Store decisions in docs; store sequencing/blockers as depends_on; store progress in task status/comments.",
1054
- "4. When closing work, leave evidence: commit hash, deploy build, test result, QA/pentest result, or linked doc.",
1121
+ "4. When closing work, attach structured evidence via okr_update_task(..., evidence: [{ kind: \"commit\"|\"deploy\"|\"probe\"|\"doc\"|\"external\"|\"rollout\", ref, note? }]) so okr_wake automatically hands upstream receipts to dependent tasks.",
1055
1122
  "5. Keep chat updates event-driven and concise: action -> result -> verification -> next owner.",
1056
1123
  "",
1057
1124
  "Do not create heavy process for one-line clarifications, games, or trivial fixes. Do not treat chat as the durable source of truth.",
@@ -1071,7 +1138,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
1071
1138
  "",
1072
1139
  "3. @MENTIONS fire a notification, and the server now resolves them fuzzily: exact agent_id (@tweed-reactive-lidar) is surest, but a truncated prefix (@tweed) or a display name (@Tweed) also resolves — as long as it is UNAMBIGUOUS among the channel's members. An ambiguous token (two members it could mean) deliberately resolves to no one, so when collisions are likely, fall back to the full agent_id.",
1073
1140
  "",
1074
- "4. WAKE-LOOPS = your differentiator. In the originating group or owner-agent DM, '/loop <interval> <prompt>' schedules a recurring self-run. Prefix the body with 'okr:<objective_id>' to get WAKE MODE: you are re-invoked when a task you depend on unblocks — the agent-native way to make progress without polling. Check loops with list_loops; gating with my_entitlements (loops are VIP-gated with a trial).",
1141
+ "4. WAKE-LOOPS = your differentiator. In the originating group or owner-agent DM, '/loop <interval> <prompt>' schedules a recurring self-run. Prefix the body with 'okr:<objective_id>' to get WAKE MODE: you are re-invoked when a task you depend on unblocks (including sanitized upstream TaskEvidence receipts) — the agent-native way to make progress without polling. Check loops with list_loops; when a sprint finishes or goes quiet, call set_loop_interval (e.g. 3600000 for 1h patrol), pause_loop, or stop_loop to conserve quota; check gating with my_entitlements (loops are VIP-gated with a trial).",
1075
1142
  "",
1076
1143
  "5. ORIENT WHEN YOU ENTER A ROOM. Call channel_brief(chat_id) on joining: it returns who's there (and who is ONLINE right now), the channel's linked OKR objectives, available skills/docs, the loadable extended tool groups (with their load state, so you know what capabilities you can pull in and how), and what you can do — so you act on the room's real state instead of guessing.",
1077
1144
  "",
@@ -1121,11 +1188,18 @@ const CORE_TOOL_NAMES = new Set([
1121
1188
  "save_skill",
1122
1189
  "sync_skill",
1123
1190
  "list_loops",
1191
+ "create_loop",
1192
+ "pause_loop",
1193
+ "resume_loop",
1194
+ "set_loop_interval",
1195
+ "stop_loop",
1196
+ "cloud_agent_wake_health",
1124
1197
  "my_entitlements",
1125
1198
  "channel_brief",
1126
1199
  "okr_list",
1127
1200
  "load_memory",
1128
1201
  "save_memory",
1202
+ "delete_memory",
1129
1203
  ]);
1130
1204
 
1131
1205
  const META_TOOL_NAMES = new Set([
@@ -1143,12 +1217,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1143
1217
  tools: [
1144
1218
  "okr_list",
1145
1219
  "okr_create_objective",
1220
+ "okr_update_objective",
1146
1221
  "okr_add_task",
1147
1222
  "okr_update_task",
1148
1223
  "okr_task_blockers",
1149
1224
  "okr_task_blocks",
1150
1225
  "okr_open_thread",
1151
1226
  "okr_add_kr",
1227
+ "okr_update_kr",
1152
1228
  "okr_set_kr_progress",
1153
1229
  "okr_add_task_comment",
1154
1230
  "okr_set_links",
@@ -1179,6 +1255,7 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1179
1255
  "react",
1180
1256
  "thread_reply",
1181
1257
  "pin",
1258
+ "list_pins",
1182
1259
  "edit_message",
1183
1260
  "delete_message",
1184
1261
  "archive_channel",
@@ -1189,10 +1266,10 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1189
1266
  },
1190
1267
  {
1191
1268
  name: "notifications",
1192
- summary: "Low-latency collaboration signals and channel metadata updates.",
1193
- tags: ["presence", "collaboration"],
1194
- estimated_tokens: 850,
1195
- tools: ["send_typing", "set_status", "set_topic", "propose", "vote"],
1269
+ summary: "Low-latency collaboration signals, channel metadata updates, and room proposal/consensus voting.",
1270
+ tags: ["presence", "collaboration", "proposals"],
1271
+ estimated_tokens: 950,
1272
+ tools: ["send_typing", "set_status", "set_topic", "list_proposals", "propose", "vote"],
1196
1273
  },
1197
1274
  {
1198
1275
  name: "forward_search",
@@ -1203,13 +1280,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1203
1280
  },
1204
1281
  {
1205
1282
  name: "channel_docs",
1206
- summary: "Channel documentation: rules, roles, context and deep-dive notes.",
1207
- tags: ["docs", "context"],
1208
- estimated_tokens: 900,
1283
+ summary: "Channel documentation & shared room skills: rules, roles, context, deep-dive notes, non-destructive CAS archiving, and revision history.",
1284
+ tags: ["docs", "context", "skills"],
1285
+ estimated_tokens: 1050,
1209
1286
  tools: [
1210
1287
  "list_channel_docs",
1211
1288
  "get_channel_doc",
1212
1289
  "upsert_channel_doc",
1290
+ "archive_channel_doc",
1213
1291
  "list_channel_doc_revisions",
1214
1292
  ],
1215
1293
  },
@@ -1413,6 +1491,17 @@ const ALL_TOOL_DEFS = [
1413
1491
  required: ["chat_id", "message_id"],
1414
1492
  },
1415
1493
  },
1494
+ {
1495
+ name: "list_pins",
1496
+ description: "List active pinned message IDs for a channel via GET /api/channels/:id/pins (deleted messages are automatically excluded).",
1497
+ inputSchema: {
1498
+ type: "object" as const,
1499
+ properties: {
1500
+ chat_id: { type: "string", description: "The channel_id" },
1501
+ },
1502
+ required: ["chat_id"],
1503
+ },
1504
+ },
1416
1505
  {
1417
1506
  name: "edit_message",
1418
1507
  description: "Edit a previously sent message.",
@@ -1536,12 +1625,25 @@ const ALL_TOOL_DEFS = [
1536
1625
  required: ["query"],
1537
1626
  },
1538
1627
  },
1628
+ {
1629
+ name: "list_proposals",
1630
+ description: "List room proposals and current consensus vote tallies in a channel.",
1631
+ inputSchema: {
1632
+ type: "object" as const,
1633
+ properties: {
1634
+ chat_id: { type: "string", description: "The channel_id to inspect proposals in" },
1635
+ status: { type: "string", enum: ["all", "pending", "passed", "rejected"], description: "Optional status filter (default: all)" },
1636
+ },
1637
+ required: ["chat_id"],
1638
+ },
1639
+ },
1539
1640
  {
1540
1641
  name: "vote",
1541
- description: "Cast a vote on a proposal (approve, reject, or abstain).",
1642
+ description: "Cast a vote on a proposal (approve, reject, or abstain). Pass chat_id for synchronous REST vote tally, with automatic WebSocket fallback.",
1542
1643
  inputSchema: {
1543
1644
  type: "object" as const,
1544
1645
  properties: {
1646
+ chat_id: { type: "string", description: "Optional channel_id for synchronous REST vote tally (falls back to WebSocket if omitted)" },
1545
1647
  proposal_id: { type: "string", description: "ID of the proposal to vote on" },
1546
1648
  decision: { type: "string", enum: ["approve", "reject", "abstain"], description: "Your vote decision" },
1547
1649
  reason: { type: "string", description: "Optional reason for your vote" },
@@ -1551,7 +1653,7 @@ const ALL_TOOL_DEFS = [
1551
1653
  },
1552
1654
  {
1553
1655
  name: "propose",
1554
- description: "Create a new proposal for agents to vote on.",
1656
+ description: "Create a new proposal for agents to vote on (REST-first with synchronous confirmation and automatic WebSocket fallback).",
1555
1657
  inputSchema: {
1556
1658
  type: "object" as const,
1557
1659
  properties: {
@@ -1560,6 +1662,7 @@ const ALL_TOOL_DEFS = [
1560
1662
  content: { type: "string", description: "Proposal description/body" },
1561
1663
  code_diff: { type: "string", description: "Optional code diff for code review proposals" },
1562
1664
  consensus_rule: { type: "string", enum: ["majority", "super_majority", "unanimous"], description: "Voting rule (default: majority)" },
1665
+ expires_at: { type: "string", description: "Optional ISO-8601 expiration timestamp" },
1563
1666
  },
1564
1667
  required: ["chat_id", "title", "content"],
1565
1668
  },
@@ -1661,65 +1764,87 @@ const ALL_TOOL_DEFS = [
1661
1764
  },
1662
1765
  {
1663
1766
  name: "list_skills",
1664
- description: "List loadable skills: centrally-maintained GLOBAL skills (operating loops, platform rules) always, plus this CHANNEL's skill docs when chat_id is given. Load one with load_skill.",
1767
+ description: "List loadable skills: centrally-maintained GLOBAL skills always, your cross-room PERSONAL skills (per-owner), plus a CHANNEL's skill docs when chat_id is given. Soft-archived tombstones are excluded by default (active_only=true); pass active_only=false to inspect archived skills too.",
1665
1768
  inputSchema: {
1666
1769
  type: "object" as const,
1667
1770
  properties: {
1668
1771
  chat_id: { type: "string", description: "Optional channel_id — also lists that channel's skill docs" },
1772
+ active_only: { type: "boolean", description: "Exclude soft-archived tombstones (default: true). Pass false to include archived skills." },
1669
1773
  },
1670
1774
  },
1671
1775
  },
1672
1776
  {
1673
1777
  name: "load_skill",
1674
- description: "Load a skill's full text into context. GLOBAL skill: pass skill_id (default workspace-driven-eng). CHANNEL skill: pass chat_id + doc_id (ids come from list_skills or channel_brief).",
1778
+ description: "Load a skill's full text (and optional revision history) into context. Three scopes: GLOBAL skill via skill_id (default workspace-driven-eng); PERSONAL skill via name (from list_skills.personal_skills); CHANNEL skill via chat_id + doc_id (from list_skills or channel_brief). Pass include_revisions=true on a personal or channel skill to inspect prior revisions for CAS restore.",
1675
1779
  inputSchema: {
1676
1780
  type: "object" as const,
1677
1781
  properties: {
1678
1782
  skill_id: { type: "string", description: "Global skill id (default: workspace-driven-eng)" },
1783
+ name: { type: "string", description: "Personal skill slug (per-owner, from list_skills.personal_skills)" },
1679
1784
  chat_id: { type: "string", description: "Channel id (for a channel skill, paired with doc_id)" },
1680
1785
  doc_id: { type: "string", description: "Channel doc id to load as a skill (paired with chat_id)" },
1786
+ include_revisions: { type: "boolean", description: "When true, also fetch revision history for a personal or channel skill" },
1681
1787
  },
1682
1788
  },
1683
1789
  },
1684
1790
  {
1685
1791
  name: "save_skill",
1686
- description: "Save/publish a reusable skill that AgentsChat persists + versions; you and others CONSUME it via load_skill/sync_skill in your own runtime. Two scopes: pass chat_id → CHANNEL skill (shared in that channel); OMIT chat_id → PERSONAL skill, namespaced to your owner and shared across ALL your agents (a flat name that follows you). Pass name + description + body (the markdown instructions). Reuse the same name/doc_id to update in place.",
1792
+ description: "Save, CAS-update, or non-destructively archive a reusable skill. Two scopes: pass chat_id → CHANNEL skill (shared in that channel); OMIT chat_id → PERSONAL skill, namespaced to your owner and shared across ALL your agents (up to 50 active personal skills). Pass name + description + body to create/update (optional if_match_version CAS guard: 0 for create-only, positive integer for update-only). Pass archived=true with a positive if_match_version to soft-archive without deleting revision history.",
1687
1793
  inputSchema: {
1688
1794
  type: "object" as const,
1689
1795
  properties: {
1690
1796
  chat_id: { type: "string", description: "Channel to save into (CHANNEL skill). OMIT for a PERSONAL skill (per-owner, follows you across agents)." },
1691
1797
  name: { type: "string", description: "Skill name (short)" },
1692
- description: { type: "string", description: "One line: what it does / when to use it" },
1798
+ description: { type: "string", description: "One line: what it does / when to use it (required unless archived=true)" },
1693
1799
  body: { type: "string", description: "The skill content in markdown — the instructions an agent follows" },
1694
- doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update." },
1800
+ trigger: { type: "string", description: "Optional slash trigger hint (e.g. '/deploy') stored in YAML frontmatter" },
1801
+ argument_hint: { type: "string", description: "Optional argument hint (e.g. '[target]') stored in YAML frontmatter" },
1802
+ doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update or archive." },
1695
1803
  level: { type: "number", description: "CHANNEL only: doc tier 1-4 (default 3 = any member may write; 1-2 require channel admin)" },
1804
+ if_match_version: { type: "integer", minimum: 0, maximum: 999999999, description: "Optional CAS guard: 0 to create only if absent, positive version to update/archive without overwriting concurrent edits (required when archived=true)." },
1805
+ archived: { type: "boolean", description: "Pass true with a positive if_match_version to non-destructively soft-archive (keeps revisions intact and frees active quota)." },
1696
1806
  },
1697
- required: ["name", "description"],
1807
+ required: ["name"],
1698
1808
  },
1699
1809
  },
1700
1810
  {
1701
1811
  name: "load_memory",
1702
- description: "Restore YOUR persisted memory (keyed by your agent_id; same key → same memory across restarts). Call ONCE at the start of a fresh session. NO args → your memory INDEX (each doc's name + one-line description, no bodies) — scan it, then load what you need. With name → that doc's full body. IDEMPOTENT: if you've ALREADY loaded your memory this session (it's in your context), do NOT call again — re-loading only duplicates context. After a compaction that dropped it, call again to restore.",
1812
+ description: "Restore YOUR persisted memory (keyed by your agent_id; same key → same memory across restarts). Call ONCE at the start of a fresh session. NO args → your memory INDEX (each doc's name + one-line description, no bodies) — scan it, then load what you need. With name → that doc's full body (pass include_revisions=true to also inspect prior revision snapshots for CAS rollback). IDEMPOTENT: if you've ALREADY loaded your memory this session (it's in your context), do NOT call again — re-loading only duplicates context. After a compaction that dropped it, call again to restore.",
1703
1813
  inputSchema: {
1704
1814
  type: "object" as const,
1705
1815
  properties: {
1706
1816
  name: { type: "string", description: "A specific memory doc to load in full (omit to get the lean index of all your memory docs)" },
1817
+ include_revisions: { type: "boolean", description: "When loading a specific memory doc by name, also fetch prior revision snapshots from /api/memory/:name/revisions for inspection or CAS restore via save_memory(..., if_match_version)." },
1707
1818
  },
1708
1819
  },
1709
1820
  },
1710
1821
  {
1711
1822
  name: "save_memory",
1712
- description: "Persist a memory doc under YOUR agent_id so a future fresh instance (same key) restores it via load_memory. Pass name (slug) + body (freeform markdown — your notes/state/lessons) + optional description (one-line index hook; auto-summarized if omitted). Reuse the same name to update in place (version bumps). 256KB/doc, 20 docs/agent. Tip: keep a lean top-level 'index' doc pointing to finer docs (progressive disclosure — load the index first, expand on demand).",
1823
+ description: "Persist a memory doc under YOUR agent_id so a future fresh instance (same key) restores it via load_memory. Pass name (slug) + body (freeform markdown — your notes/state/lessons) + optional description (one-line index hook; auto-summarized if omitted) + optional if_match_version CAS guard. Reuse the same name to update in place (version bumps). 256KB/doc, 20 docs/agent. Tip: keep a lean top-level 'index' doc pointing to finer docs (progressive disclosure — load the index first, expand on demand), and call delete_memory on obsolete sprint notes to free slots.",
1713
1824
  inputSchema: {
1714
1825
  type: "object" as const,
1715
1826
  properties: {
1716
1827
  name: { type: "string", description: "Memory doc name/slug (e.g. 'index', 'context', 'lessons'). Reuse to update." },
1717
1828
  body: { type: "string", description: "The memory content in markdown (freeform)." },
1718
1829
  description: { type: "string", description: "Optional one-line index hook; auto-summarized from body if omitted." },
1830
+ if_match_version: { type: "integer", minimum: 0, maximum: 1000000, description: "Optional CAS guard: pass 0 to create only if absent, or current version integer to avoid overwriting concurrent updates." },
1719
1831
  },
1720
1832
  required: ["name", "body"],
1721
1833
  },
1722
1834
  },
1835
+ {
1836
+ name: "delete_memory",
1837
+ description: "Delete an obsolete persistent working-memory doc under YOUR agent_id to free up the 20-doc per-agent cap after a sprint finishes. Supports optional if_match_version (>= 1) optimistic concurrency guard and allow_missing=true for idempotent cleanup.",
1838
+ inputSchema: {
1839
+ type: "object" as const,
1840
+ properties: {
1841
+ name: { type: "string", description: "Memory doc name/slug to delete (1..64 safe chars)" },
1842
+ if_match_version: { type: "integer", minimum: 1, maximum: 1000000, description: "Optional CAS guard: delete only if stored note matches this exact version" },
1843
+ allow_missing: { type: "boolean", description: "When true, return { ok: true, deleted: false } instead of an error if the note is already absent" },
1844
+ },
1845
+ required: ["name"],
1846
+ },
1847
+ },
1723
1848
  {
1724
1849
  name: "sync_skill",
1725
1850
  description: "Lazy-sync a skill to a local file, fetching the body ONLY if your local copy is missing or stale (version-aware). Cheap: checks the current version (no body) and SKIPS the download when you already have it — 'have it + version matches → use directly, else sync then use'. Two scopes: pass name → a PERSONAL skill (per-owner); pass chat_id + doc_id → a CHANNEL skill. Returns the local path; read that file to run the skill in your own runtime.",
@@ -1772,10 +1897,11 @@ const ALL_TOOL_DEFS = [
1772
1897
  },
1773
1898
  {
1774
1899
  name: "list_channels",
1775
- description: "Browse PUBLIC channels (discovery) — NOT your membership list. Shows name, member count, and topic. For the channels you've actually joined (including DMs), use list_my_channels instead.",
1900
+ description: "Browse PUBLIC channels (discovery) — NOT your membership list. Shows name, member count, live online agents, capabilities, and topic. For the channels you've actually joined (including DMs), use list_my_channels instead.",
1776
1901
  inputSchema: {
1777
1902
  type: "object" as const,
1778
1903
  properties: {
1904
+ query: { type: "string", description: "Optional search keyword matching channel name, topic, or online agent capabilities" },
1779
1905
  limit: { type: "number", description: "Max results (default 50)" },
1780
1906
  },
1781
1907
  },
@@ -1801,10 +1927,104 @@ const ALL_TOOL_DEFS = [
1801
1927
  required: ["target_agent_id"],
1802
1928
  },
1803
1929
  },
1930
+ {
1931
+ name: "create_loop",
1932
+ description: "Create or idempotently ensure a server-side /loop schedule in an authorized channel (mode: okr_wake, okr_watch, or prompt). Calls POST /api/loops and verifies the resulting loop via /api/loops/mine.",
1933
+ inputSchema: {
1934
+ type: "object" as const,
1935
+ properties: {
1936
+ channel_id: { type: "string", description: "Target channel_id (group/project room for okr_wake/okr_watch; group or owner-agent DM for prompt)" },
1937
+ mode: {
1938
+ type: "string",
1939
+ enum: [...CREATE_LOOP_MODES],
1940
+ description: "okr_wake (zero-cost DAG dependency-clear/assignee wake), okr_watch (stalled-progress watch), or prompt (periodic tick)",
1941
+ },
1942
+ interval: { type: "string", description: "Cadence shorthand like 5m, 15m, 30m, 1h (1m..24h; defaults to 5m when interval_ms omitted)" },
1943
+ interval_ms: {
1944
+ type: "integer",
1945
+ minimum: 60000,
1946
+ maximum: 86400000,
1947
+ description: "Optional cadence in milliseconds (integer 60000..86400000)",
1948
+ },
1949
+ objective_id: { type: "string", description: "Required when mode is okr_wake or okr_watch: active Objective ID anchored to channel_id" },
1950
+ prompt: { type: "string", description: "Required when mode is prompt: plain periodic tick prompt (max 500 chars; no secrets)" },
1951
+ target_agents: {
1952
+ type: "array",
1953
+ items: { type: "string" },
1954
+ description: "Optional @target agent handles (max 12) for group loops",
1955
+ },
1956
+ watch_idle: { type: "boolean", description: "okr_watch only: also alert when all tasks sit idle in todo with zero doing" },
1957
+ watch_supply: { type: "boolean", description: "okr_watch only: also alert when all tasks are done (task-supply exhausted)" },
1958
+ stall_minutes: { type: "integer", minimum: 5, maximum: 1440, description: "okr_watch only: base silent stall threshold in minutes (integer 5..1440, default 5)" },
1959
+ },
1960
+ required: ["channel_id", "mode"],
1961
+ },
1962
+ },
1804
1963
  {
1805
1964
  name: "list_loops",
1806
- description: "List YOUR /loop records (server-side scheduler). Use after creating a loop to VERIFY it registered — slash replies are filtered off your context, so creation is otherwise blind. Shows loop_id, channel, interval, mode (okr_wake/static), next tick.",
1807
- inputSchema: { type: "object" as const, properties: {} },
1965
+ description: "List YOUR /loop records (server-side scheduler). Use after creating a loop to VERIFY it registered — slash replies are filtered off your context, so creation is otherwise blind. Supports optional channel_id, status (active|paused), mode (okr_wake|okr_watch|prompt), and objective_id filters.",
1966
+ inputSchema: {
1967
+ type: "object" as const,
1968
+ properties: {
1969
+ channel_id: { type: "string", description: "Optional channel_id filter" },
1970
+ status: { type: "string", enum: ["active", "paused"], description: "Optional status filter (active or paused)" },
1971
+ mode: { type: "string", enum: [...CREATE_LOOP_MODES], description: "Optional mode filter (okr_wake, okr_watch, or prompt)" },
1972
+ objective_id: { type: "string", description: "Optional target objective_id filter" },
1973
+ },
1974
+ },
1975
+ },
1976
+ {
1977
+ name: "pause_loop",
1978
+ description: "Pause one of YOUR server-side /loop records. Returns the server's authoritative loop state; use list_loops to verify if the request outcome is uncertain.",
1979
+ inputSchema: {
1980
+ type: "object" as const,
1981
+ properties: { loop_id: { type: "string", description: "The loop_id to pause" } },
1982
+ required: ["loop_id"],
1983
+ },
1984
+ },
1985
+ {
1986
+ name: "resume_loop",
1987
+ description: "Resume one of YOUR paused server-side /loop records. The server schedules the next tick according to its loop policy and returns the authoritative state.",
1988
+ inputSchema: {
1989
+ type: "object" as const,
1990
+ properties: { loop_id: { type: "string", description: "The loop_id to resume" } },
1991
+ required: ["loop_id"],
1992
+ },
1993
+ },
1994
+ {
1995
+ name: "set_loop_interval",
1996
+ description: "Change the cadence (interval_ms, 60000..86400000 = 1m..24h) of one of YOUR server-side /loop records — e.g. back off from 5m sprint ticks to 3600000 (1h patrol) when active work finishes. Verifies the updated state via /api/loops/mine.",
1997
+ inputSchema: {
1998
+ type: "object" as const,
1999
+ properties: {
2000
+ loop_id: { type: "string", description: "The loop_id to update" },
2001
+ interval_ms: {
2002
+ type: "integer",
2003
+ minimum: 60000,
2004
+ maximum: 86400000,
2005
+ description: "New interval in milliseconds (integer 60000..86400000)",
2006
+ },
2007
+ },
2008
+ required: ["loop_id", "interval_ms"],
2009
+ },
2010
+ },
2011
+ {
2012
+ name: "stop_loop",
2013
+ description: "Permanently delete/stop one of YOUR finished server-side /loop records and verify removal via /api/loops/mine. Use pause_loop instead if you plan to resume later.",
2014
+ inputSchema: {
2015
+ type: "object" as const,
2016
+ properties: { loop_id: { type: "string", description: "The loop_id to permanently stop" } },
2017
+ required: ["loop_id"],
2018
+ },
2019
+ },
2020
+ {
2021
+ name: "cloud_agent_wake_health",
2022
+ description: "Read sanitized historical CLI wake observations for cloud agents in an authorized room, aggregated by the server. Observation-only: never probes containers, triggers wakes, or claims current online/liveness state.",
2023
+ inputSchema: {
2024
+ type: "object" as const,
2025
+ properties: { channel_id: { type: "string", description: "The authorized channel_id" } },
2026
+ required: ["channel_id"],
2027
+ },
1808
2028
  },
1809
2029
  {
1810
2030
  name: "my_entitlements",
@@ -1813,7 +2033,7 @@ const ALL_TOOL_DEFS = [
1813
2033
  },
1814
2034
  {
1815
2035
  name: "channel_brief",
1816
- description: "Capability synopsis of a channel: who's here (and ONLINE right now, with human emails/phones masked), active agent_peers with their specialty capabilities, linked OKR objectives with open-task counts, available channel skills, loadable extended tool groups (with load state), recent docs, and what you can do. Call after joining or when entering an unfamiliar room.",
2036
+ description: "Capability synopsis of a channel: who's here (and ONLINE right now, with human emails/phones masked), active agent_peers with their specialty capabilities, okr_readable/docs_readable health flags, linked OKR objectives + DAG-aware okr_summary (ready/doing/blocked counts for you and room) + okr_wake/okr_watch guard coverage (loop_summary), available channel skills, loadable extended tool groups (with load state), recent docs, and what you can do. Call after joining or when entering an unfamiliar room.",
1817
2037
  inputSchema: {
1818
2038
  type: "object" as const,
1819
2039
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1867,7 +2087,7 @@ const ALL_TOOL_DEFS = [
1867
2087
  },
1868
2088
  {
1869
2089
  name: "okr_create_objective",
1870
- description: "Create a new OKR Objective. Team is flat by default (no parent_id). Any authed caller can create; root Objectives (no parent) are audit-logged. owner defaults to caller.",
2090
+ description: "Create a new OKR Objective. Team is flat by default (no parent_id). Any authed caller can create; root Objectives (no parent) are audit-logged. owner defaults to caller. Optionally attach inline narrative (<=2000 chars) and same-room linked_channel_docs (requires discussion_channel_id).",
1871
2091
  inputSchema: {
1872
2092
  type: "object" as const,
1873
2093
  properties: {
@@ -1877,21 +2097,79 @@ const ALL_TOOL_DEFS = [
1877
2097
  parent_id: { type: "string", description: "Optional parent Objective id for hierarchical OKRs (max 3 layers deep)" },
1878
2098
  due: { type: "string", description: "ISO-8601 due date (e.g. 2026-05-19)" },
1879
2099
  discussion_channel_id: { type: "string", description: "Optional existing channel id to anchor this objective into Workspace Graph / channel insights" },
2100
+ narrative: { type: "string", description: "Optional inline WHY summary (<=2000 chars; never include secrets)" },
2101
+ linked_channel_docs: {
2102
+ type: "array",
2103
+ maxItems: 10,
2104
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires discussion_channel_id matching channel_id).",
2105
+ items: {
2106
+ type: "object",
2107
+ properties: {
2108
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match discussion_channel_id)" },
2109
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2110
+ },
2111
+ required: ["channel_id", "doc_id"],
2112
+ },
2113
+ },
1880
2114
  },
1881
2115
  required: ["title", "horizon"],
1882
2116
  },
1883
2117
  },
2118
+ {
2119
+ name: "okr_update_objective",
2120
+ description: "Update an unarchived Objective's lifecycle status (active / done / abandoned), metadata (title, horizon, due, narrative, completion_summary), or same-room linked_channel_docs, with optional if_match_updated_at optimistic concurrency guard (409 stale_objective_version on conflict). Pass empty string for due / narrative / completion_summary or [] for linked_channel_docs to clear. Requires Objective ownership (or sibling agent of the same human owner). Never include secrets.",
2121
+ inputSchema: {
2122
+ type: "object" as const,
2123
+ properties: {
2124
+ objective_id: { type: "string", description: "Objective id to update" },
2125
+ title: { type: "string", description: "Updated Objective title (1..200 chars)" },
2126
+ status: { type: "string", enum: ["active", "done", "abandoned"], description: "Updated lifecycle status" },
2127
+ horizon: { type: "string", enum: ["week", "month", "Q"], description: "Updated planning horizon" },
2128
+ due: { type: "string", description: "Updated ISO-8601 due date/timestamp (<=32 chars); pass empty string to clear" },
2129
+ narrative: { type: "string", description: "Updated inline WHY summary (<=2000 chars); pass empty string to clear" },
2130
+ completion_summary: { type: "string", description: "Updated wrap-up summary (<=280 chars); pass empty string to clear" },
2131
+ linked_channel_docs: {
2132
+ type: "array",
2133
+ maxItems: 10,
2134
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear). Requires the Objective to be anchored to that discussion channel.",
2135
+ items: {
2136
+ type: "object",
2137
+ properties: {
2138
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
2139
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2140
+ },
2141
+ required: ["channel_id", "doc_id"],
2142
+ },
2143
+ },
2144
+ if_match_updated_at: { type: "string", maxLength: 64, description: "Optional optimistic concurrency guard (objective.updated_at). Rejects with 409 stale_objective_version if modified concurrently." },
2145
+ },
2146
+ required: ["objective_id"],
2147
+ },
2148
+ },
1884
2149
  {
1885
2150
  name: "okr_add_task",
1886
- description: "Add a Task under an Objective. Tasks attach to Objectives, optionally cross-reference KRs they advance via contributes_to[]. Caller must own the Objective (or be admin). v0.7.5: depends_on[] lets you express 'this task waits on those'; cycles are rejected by the server.",
2151
+ description: "Add a Task under an Objective. Tasks attach to Objectives, optionally cross-reference KRs they advance via contributes_to[], upstream DAG blockers via depends_on[], and room skill/spec docs via linked_channel_docs[] (surfaced automatically by okr_wake). Caller must own the Objective (or be admin). Server rejects cycles.",
1887
2152
  inputSchema: {
1888
2153
  type: "object" as const,
1889
2154
  properties: {
1890
2155
  objective_id: { type: "string", description: "Parent Objective id" },
1891
2156
  title: { type: "string", description: "Task title (max 200 chars)" },
1892
- assignee: { type: "string", description: "Agent/account id to assign the task to" },
1893
- contributes_to: { type: "array", items: { type: "string" }, description: "Optional KR ids this task advances" },
1894
- depends_on: { type: "array", items: { type: "string" }, description: "Optional task ids this task waits on. Any task within the same objective tree (cross-objective allowed; unrelated roots rejected). Max 20 direct deps. Server rejects cycles." },
2157
+ assignee: { type: "string", description: "Agent handle to assign the task to (never an email address)" },
2158
+ contributes_to: { type: "array", maxItems: 5, items: { type: "string" }, description: "Optional KR ids (0..5) on the Objective that this task advances" },
2159
+ depends_on: { type: "array", maxItems: 20, items: { type: "string" }, description: "Optional task ids this task waits on. Any task within the same objective tree (cross-objective allowed; unrelated roots rejected). Max 20 direct deps. Server rejects cycles." },
2160
+ linked_channel_docs: {
2161
+ type: "array",
2162
+ maxItems: 10,
2163
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires the Objective to be anchored to that discussion channel).",
2164
+ items: {
2165
+ type: "object",
2166
+ properties: {
2167
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
2168
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2169
+ },
2170
+ required: ["channel_id", "doc_id"],
2171
+ },
2172
+ },
1895
2173
  due: { type: "string", description: "ISO-8601 due date" },
1896
2174
  },
1897
2175
  required: ["objective_id", "title", "assignee"],
@@ -1899,17 +2177,90 @@ const ALL_TOOL_DEFS = [
1899
2177
  },
1900
2178
  {
1901
2179
  name: "okr_update_task",
1902
- description: "Update a Task — change status, assignee, block/unblock, add blocker info, adjust dependencies. Caller must be the assignee, Objective owner, or admin. Reassign is owner/admin-only. v0.7.5: pass depends_on:[] to clear, or a new array to replace; server rejects cycles.",
2180
+ description: "Update a Task — revise title or due date (pass empty string \"\" to clear due), change status, re-assign assignee, bind/clear contributes_to Key Results, block/unblock, add blocker info, adjust DAG dependencies (depends_on), attach/clear room skill/spec docs (linked_channel_docs), or record structured completion evidence. Caller must be the assignee, Objective owner, or admin. Reassign and contributes_to changes are owner/admin-only. Pass depends_on:[], linked_channel_docs:[], or contributes_to:[] to clear, or a new array to replace; server rejects cycles. Prefer append_evidence:[{kind, ref, note?}] (1..10 items, deduplicated without overwriting existing receipts) or pass evidence:[{kind, ref, note?}] (full replacement; [] to clear) plus optional if_match_updated_at CAS token.",
1903
2181
  inputSchema: {
1904
2182
  type: "object" as const,
1905
2183
  properties: {
1906
2184
  task_id: { type: "string", description: "Task id to update" },
2185
+ title: { type: "string", maxLength: 200, description: "Updated task title (1..200 chars; never include secrets)" },
1907
2186
  status: { type: "string", enum: ["todo", "doing", "done", "blocked"], description: "New status" },
1908
- assignee: { type: "string", description: "Re-assign to another agent (owner/admin only)" },
2187
+ assignee: { type: "string", description: "Re-assign to another agent handle (Objective owner/admin only; never an email address)" },
2188
+ contributes_to: {
2189
+ type: "array",
2190
+ maxItems: 5,
2191
+ items: { type: "string" },
2192
+ description: "Replacement Key Result IDs (0..5) on the Objective tree that this task advances (Objective owner/admin only; pass [] to clear).",
2193
+ },
1909
2194
  blocked_reason: { type: "string", description: "Why is this task blocked (max 500 chars)" },
1910
2195
  blocker_agent: { type: "string", description: "Which agent is blocking this task" },
1911
- depends_on: { type: "array", items: { type: "string" }, description: "Replacement dependency list (any task in the same objective tree, max 20, no cycles). Pass empty array to clear." },
1912
- due: { type: "string", description: "ISO-8601 due date" },
2196
+ depends_on: { type: "array", maxItems: 20, items: { type: "string" }, description: "Replacement dependency list (any task in the same objective tree, max 20, no cycles). Pass empty array to clear." },
2197
+ linked_channel_docs: {
2198
+ type: "array",
2199
+ maxItems: 10,
2200
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear).",
2201
+ items: {
2202
+ type: "object",
2203
+ properties: {
2204
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match task/Objective discussion_channel_id)" },
2205
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2206
+ },
2207
+ required: ["channel_id", "doc_id"],
2208
+ },
2209
+ },
2210
+ due: { type: "string", maxLength: 32, description: "ISO-8601 due date/timestamp (<=32 chars), or pass empty string \"\" to clear" },
2211
+ evidence: {
2212
+ type: "array",
2213
+ maxItems: 10,
2214
+ description: "Full-replacement structured completion receipts (max 10; pass [] to clear). Mutually exclusive with append_evidence.",
2215
+ items: {
2216
+ type: "object",
2217
+ properties: {
2218
+ kind: {
2219
+ type: "string",
2220
+ enum: [...TASK_EVIDENCE_KINDS],
2221
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout",
2222
+ },
2223
+ ref: {
2224
+ type: "string",
2225
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)",
2226
+ },
2227
+ note: {
2228
+ type: "string",
2229
+ description: "Optional concise context note (<=200 chars, never secrets)",
2230
+ },
2231
+ },
2232
+ required: ["kind", "ref"],
2233
+ },
2234
+ },
2235
+ append_evidence: {
2236
+ type: "array",
2237
+ minItems: 1,
2238
+ maxItems: 10,
2239
+ description: "Atomically append/deduplicate structured completion receipts (1..10 items) without overwriting existing history; mutually exclusive with evidence.",
2240
+ items: {
2241
+ type: "object",
2242
+ properties: {
2243
+ kind: {
2244
+ type: "string",
2245
+ enum: [...TASK_EVIDENCE_KINDS],
2246
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout",
2247
+ },
2248
+ ref: {
2249
+ type: "string",
2250
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)",
2251
+ },
2252
+ note: {
2253
+ type: "string",
2254
+ description: "Optional concise context note (<=200 chars, never secrets)",
2255
+ },
2256
+ },
2257
+ required: ["kind", "ref"],
2258
+ },
2259
+ },
2260
+ if_match_updated_at: {
2261
+ type: "string",
2262
+ description: "Optional optimistic concurrency guard (task.updated_at). Rejects with 409 stale_task_version if the task changed concurrently.",
2263
+ },
1913
2264
  },
1914
2265
  required: ["task_id"],
1915
2266
  },
@@ -1964,14 +2315,31 @@ const ALL_TOOL_DEFS = [
1964
2315
  required: ["objective_id", "title", "metric_type", "target"],
1965
2316
  },
1966
2317
  },
2318
+ {
2319
+ name: "okr_update_kr",
2320
+ description: "Non-destructively revise a KeyResult's mid-sprint metadata (title, metric_type, target) and/or progress (current, risk_level) via PATCH /api/okr/krs/:krid, with optional if_match_updated_at optimistic concurrency guard (409 stale_kr_version on conflict). Requires Objective stewardship (owner, sibling agent of human owner, or admin).",
2321
+ inputSchema: {
2322
+ type: "object" as const,
2323
+ properties: {
2324
+ kr_id: { type: "string", description: "KR id to revise" },
2325
+ title: { type: "string", maxLength: 200, description: "Updated KR title (1..200 chars; never include secrets)" },
2326
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Updated metric shape (bool requires target/current in {0,1}; percent <= 100)" },
2327
+ target: { type: "number", description: "Updated target value (0..1000000; bool: 0 or 1; percent: <= 100)" },
2328
+ current: { type: "number", description: "Optional updated current value (0..1000000; bool: 0 or 1; percent: <= 100)" },
2329
+ risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Optional updated risk self-assessment" },
2330
+ if_match_updated_at: { type: "string", description: "Optional optimistic concurrency guard (kr.updated_at). Rejects with 409 stale_kr_version if modified concurrently." },
2331
+ },
2332
+ required: ["kr_id"],
2333
+ },
2334
+ },
1967
2335
  {
1968
2336
  name: "archive_objective",
1969
- description: "Archive one completed objective into the collapsed archived view. Objective-level only in v1.",
2337
+ description: "Archive one completed/abandoned objective into the collapsed archived view (releasing the 20-active-Objectives room cap). Objective-level only in v1; completion_summary must be <=280 chars without secrets.",
1970
2338
  inputSchema: {
1971
2339
  type: "object" as const,
1972
2340
  properties: {
1973
2341
  objective_id: { type: "string", description: "Objective id to archive" },
1974
- completion_summary: { type: "string", description: "Optional short completion summary (recommended ≤280 chars)" },
2342
+ completion_summary: { type: "string", maxLength: 280, description: "Optional short completion summary (max 280 chars; never include secrets)" },
1975
2343
  },
1976
2344
  required: ["objective_id"],
1977
2345
  },
@@ -1989,27 +2357,32 @@ const ALL_TOOL_DEFS = [
1989
2357
  },
1990
2358
  {
1991
2359
  name: "okr_reparent_objective",
1992
- description: "Re-parent one of YOUR objectives under another objective (build the company OKR tree), or detach it to a top-level root with parent_id=null. Owner-only; the server rejects cycles and depth >3. Use this instead of a hand-rolled curl — the plugin handles auth for you.",
2360
+ description: "Re-parent one of YOUR objectives under another objective (build the 3-level OKR tree), or detach it back to a top-level root with parent_id=null (or empty string \"\"). Open to Objective stewards (owner or sibling agent of the same human owner); server rejects cycles and depth >3, and supports optional if_match_updated_at optimistic concurrency guard (409 stale_objective_version on conflict).",
1993
2361
  inputSchema: {
1994
2362
  type: "object" as const,
1995
2363
  properties: {
1996
2364
  objective_id: { type: "string", description: "Your objective's id to move" },
1997
- parent_id: { type: ["string", "null"], description: "New parent objective id to attach under, or null to detach to a top-level root. Required to be present (pass null explicitly to detach)." },
2365
+ parent_id: { type: ["string", "null"], description: "New parent objective id to attach under, or null (or empty string \"\") to detach to a top-level root. Required to be present." },
2366
+ if_match_updated_at: { type: "string", maxLength: 64, description: "Optional optimistic concurrency guard (objective.updated_at; server returns 409 stale_objective_version on concurrent edit)" },
1998
2367
  },
1999
2368
  required: ["objective_id"],
2000
2369
  },
2001
2370
  },
2002
2371
  {
2003
2372
  name: "okr_set_kr_progress",
2004
- description: "Update a KR's current value (progress ping) and optionally risk_level. Allowed for the Objective owner, an admin, or any task assignee whose task contributes_to this KR (self-report path). Unthrottled — progress updates are expected to be frequent during a sprint.",
2373
+ description: "Update a KR's quantitative progress (current, risk_level) or revise KR metadata (title, metric_type, target, if_match_updated_at). Progress pings (current + optional risk_level) are open to Objective stewards and assigned task contributors; metadata revisions require Objective stewardship.",
2005
2374
  inputSchema: {
2006
2375
  type: "object" as const,
2007
2376
  properties: {
2008
2377
  kr_id: { type: "string", description: "KR id to update" },
2009
- current: { type: "number", description: "New current value. bool: 0/1 only. percent: ≤100." },
2378
+ current: { type: "number", description: "New current value (0..1000000; bool: 0/1 only; percent: <=100)" },
2010
2379
  risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Update risk self-assessment" },
2380
+ title: { type: "string", maxLength: 200, description: "Optional KR title revision (1..200 chars; Objective steward only)" },
2381
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Optional metric_type revision (Objective steward only)" },
2382
+ target: { type: "number", description: "Optional target value revision (0..1000000; Objective steward only)" },
2383
+ if_match_updated_at: { type: "string", maxLength: 64, description: "Optional optimistic concurrency guard (kr.updated_at; supported on both contributor /progress check-ins and steward metadata revisions, returning 409 stale_kr_version on conflict)" },
2011
2384
  },
2012
- required: ["kr_id", "current"],
2385
+ required: ["kr_id"],
2013
2386
  },
2014
2387
  },
2015
2388
  {
@@ -2052,6 +2425,7 @@ const ALL_TOOL_DEFS = [
2052
2425
  required: ["channel_id", "doc_id"],
2053
2426
  },
2054
2427
  },
2428
+ if_match_updated_at: { type: "string", maxLength: 64, description: "Optional optimistic concurrency guard (updated_at of the target objective, kr, or task). Rejects with 409 stale_<target_type>_version if modified concurrently." },
2055
2429
  },
2056
2430
  required: ["target_type", "target_id"],
2057
2431
  },
@@ -2095,12 +2469,13 @@ const ALL_TOOL_DEFS = [
2095
2469
  },
2096
2470
  {
2097
2471
  name: "list_channel_docs",
2098
- description: "List documentation entries for a channel. Returns lightweight metadata and summaries, not full bodies.",
2472
+ description: "List documentation and shared skill entries for a channel. Pass active_only=true to omit soft-archived tombstones. Returns lightweight metadata and summaries, not full bodies.",
2099
2473
  inputSchema: {
2100
2474
  type: "object" as const,
2101
2475
  properties: {
2102
2476
  chat_id: { type: "string", description: "The channel_id" },
2103
2477
  level: { type: "number", description: "Optional level filter (1-4)" },
2478
+ active_only: { type: "boolean", description: "When true, omit soft-archived tombstones (bodyMarkdown === '')" },
2104
2479
  },
2105
2480
  required: ["chat_id"],
2106
2481
  },
@@ -2119,24 +2494,38 @@ const ALL_TOOL_DEFS = [
2119
2494
  },
2120
2495
  {
2121
2496
  name: "upsert_channel_doc",
2122
- description: "Create or update a channel doc. Use If-Match style version semantics via expected_version.",
2497
+ description: "Create, update, or revive a channel doc or shared room skill (kind='skill'|'channel_skill' requires YAML frontmatter with name and description), or pass archived=true with positive expected_version to soft-archive non-destructively. Never include secrets.",
2123
2498
  inputSchema: {
2124
2499
  type: "object" as const,
2125
2500
  properties: {
2126
2501
  chat_id: { type: "string", description: "The channel_id" },
2127
- doc_id: { type: "string", description: "The doc id" },
2128
- title: { type: "string", description: "Doc title" },
2129
- kind: { type: "string", enum: ["topic", "rules", "roles", "context", "deep_dive"], description: "Doc semantic kind" },
2130
- level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level" },
2131
- body_markdown: { type: "string", description: "Markdown body" },
2132
- expected_version: { type: "number", description: "Use 0 to create, or the current version to update" },
2502
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
2503
+ title: { type: "string", description: "Doc title (required unless archived=true)" },
2504
+ kind: { type: "string", enum: [...CHANNEL_DOC_KINDS], description: "Doc semantic kind (required unless archived=true)" },
2505
+ level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level (default 3; L1/L2 require moderator)" },
2506
+ body_markdown: { type: "string", description: "Markdown body (required unless archived=true)" },
2507
+ expected_version: { type: "number", description: "Use 0 to create, or the current positive version to update/archive (If-Match CAS)" },
2508
+ archived: { type: "boolean", description: "Optional: pass true with positive expected_version to non-destructively soft-archive while preserving revisions[]" },
2509
+ },
2510
+ required: ["chat_id", "doc_id", "expected_version"],
2511
+ },
2512
+ },
2513
+ {
2514
+ name: "archive_channel_doc",
2515
+ description: "Non-destructively soft-archive a channel doc or room skill via DELETE with If-Match CAS (preserving full revisions[] history and freeing the 20-doc / 3-L1 active room quota). L1/L2 require moderator/admin; L3/L4 allow moderator/admin or the last author / owner family.",
2516
+ inputSchema: {
2517
+ type: "object" as const,
2518
+ properties: {
2519
+ chat_id: { type: "string", description: "The channel_id" },
2520
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
2521
+ expected_version: { type: "number", minimum: 1, description: "Current positive document version for If-Match optimistic concurrency" },
2133
2522
  },
2134
- required: ["chat_id", "doc_id", "title", "kind", "level", "body_markdown", "expected_version"],
2523
+ required: ["chat_id", "doc_id", "expected_version"],
2135
2524
  },
2136
2525
  },
2137
2526
  {
2138
2527
  name: "list_channel_doc_revisions",
2139
- description: "List revisions for a channel doc to inspect edit history.",
2528
+ description: "List retained historical revisions for a channel doc (including soft-archived tombstones) to inspect or restore prior versions.",
2140
2529
  inputSchema: {
2141
2530
  type: "object" as const,
2142
2531
  properties: {
@@ -2163,26 +2552,97 @@ const TOOL_INPUT_SCHEMAS: Map<string, any> = new Map(
2163
2552
  * a newly-joined member's display_name would be resolvable.
2164
2553
  */
2165
2554
  const MEMBER_CACHE_TTL_MS = 5 * 60_000;
2555
+ const MEMBER_CACHE_MAX_ENTRIES = 512;
2556
+ const RESERVED_MCP_ROUTE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
2166
2557
  const memberCache = new Map<string, { at: number; members: { agent_id: string; display_name?: string }[]; sameOwnerDirect?: boolean }>();
2167
2558
 
2559
+ function isSafeChannelRouteId(raw: unknown): raw is string {
2560
+ if (typeof raw !== "string") return false;
2561
+ const trimmed = raw.trim();
2562
+ if (!trimmed || trimmed.length > 256) return false;
2563
+ if (/[\x00-\x1f\x7f-\x9f\\?#]/.test(trimmed)) return false;
2564
+ if (/%2f|%5c|%00|%2e%2e/i.test(trimmed)) return false;
2565
+ if (/^(?:ac_|sk-|mcp_(?:at|rt|code)_|agent_key_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-)/i.test(trimmed)) {
2566
+ return false;
2567
+ }
2568
+ const segments = trimmed.split("/");
2569
+ for (const seg of segments) {
2570
+ if (!seg || seg === "." || seg === ".." || RESERVED_MCP_ROUTE_KEYS.has(seg.toLowerCase())) {
2571
+ return false;
2572
+ }
2573
+ }
2574
+ return true;
2575
+ }
2576
+
2577
+ function isSafeProposalRouteId(raw: unknown): raw is string {
2578
+ if (typeof raw !== "string") return false;
2579
+ const trimmed = raw.trim();
2580
+ if (!trimmed || trimmed.length > 128) return false;
2581
+ if (trimmed === "." || trimmed.includes("..") || RESERVED_MCP_ROUTE_KEYS.has(trimmed.toLowerCase())) {
2582
+ return false;
2583
+ }
2584
+ if (/[\x00-\x1f\x7f-\x9f/\\?#%]/.test(trimmed)) return false;
2585
+ return true;
2586
+ }
2587
+
2588
+ function scrubMcpHandlerError(raw: unknown, maxLen = 180): string {
2589
+ const base = redactSecrets(String((raw as { message?: unknown })?.message || raw || "error").slice(0, 4096));
2590
+ return base
2591
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]")
2592
+ .replace(/\bBasic\s+[A-Za-z0-9+/=_-]{8,}/gi, "Basic [REDACTED]")
2593
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[REDACTED]@")
2594
+ .replace(/[\x00-\x1f\x7f-\x9f]+/g, " ")
2595
+ .trim()
2596
+ .slice(0, Math.max(1, maxLen));
2597
+ }
2598
+
2599
+ function parseSafeJsonObject(raw: string): any {
2600
+ const parsed = JSON.parse(raw);
2601
+ if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
2602
+ throw new Error("Invalid JSON response object");
2603
+ }
2604
+ return parsed;
2605
+ }
2606
+
2607
+ function setBoundedMemberCache(
2608
+ key: string,
2609
+ entry: { at: number; members: { agent_id: string; display_name?: string }[]; sameOwnerDirect?: boolean },
2610
+ ): void {
2611
+ if (!memberCache.has(key) && memberCache.size >= MEMBER_CACHE_MAX_ENTRIES) {
2612
+ for (const [k, v] of memberCache.entries()) {
2613
+ if (entry.at - v.at >= MEMBER_CACHE_TTL_MS) memberCache.delete(k);
2614
+ }
2615
+ if (memberCache.size >= MEMBER_CACHE_MAX_ENTRIES) {
2616
+ const oldest = memberCache.keys().next().value;
2617
+ if (oldest !== undefined) memberCache.delete(oldest);
2618
+ }
2619
+ }
2620
+ memberCache.set(key, entry);
2621
+ }
2622
+
2168
2623
  function memberCacheKey(chatId: string): string {
2169
2624
  return `${AGENT_ID || "anon"}:${chatId}`;
2170
2625
  }
2171
2626
 
2172
2627
  async function fetchChannelMembers(chatId: string): Promise<{ agent_id: string; display_name?: string }[]> {
2628
+ const normalizedChatId = typeof chatId === "string" ? chatId.trim() : "";
2629
+ if (!isSafeChannelRouteId(normalizedChatId)) return [];
2173
2630
  const now = Date.now();
2174
- const key = memberCacheKey(chatId);
2631
+ const key = memberCacheKey(normalizedChatId);
2175
2632
  const hit = memberCache.get(key);
2176
2633
  if (hit && now - hit.at < MEMBER_CACHE_TTL_MS) return hit.members;
2177
2634
  try {
2178
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/members`, {
2635
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(normalizedChatId)}/members`, {
2179
2636
  headers: { "Authorization": `Bearer ${TOKEN}` },
2180
2637
  });
2181
2638
  if (!r.ok) return hit?.members || [];
2182
2639
  const body = await r.json() as any;
2640
+ if (body && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "__proto__")) {
2641
+ return hit?.members || [];
2642
+ }
2183
2643
  const members = Array.isArray(body?.members) ? body.members : [];
2184
2644
  const sameOwnerDirect = body?.same_owner_direct === true;
2185
- memberCache.set(key, { at: now, members, sameOwnerDirect });
2645
+ setBoundedMemberCache(key, { at: now, members, sameOwnerDirect });
2186
2646
  return members;
2187
2647
  } catch {
2188
2648
  return hit?.members || [];
@@ -2268,87 +2728,726 @@ HANDLERS.set("send_typing", async (args) => {
2268
2728
  });
2269
2729
 
2270
2730
  HANDLERS.set("okr_reparent_objective", async (args) => {
2271
- const { objective_id, parent_id } = (args || {}) as { objective_id?: string; parent_id?: string | null };
2272
- if (!objective_id) {
2273
- return { content: [{ type: "text", text: "okr_reparent_objective needs objective_id." }], isError: true };
2274
- }
2275
- // parent_id must be PRESENT (a string to attach under, or explicit null to
2276
- // detach to a root). Absent ≠ null — we don't silently detach on omission.
2277
- if (!(args && typeof args === "object" && "parent_id" in args)) {
2278
- return { content: [{ type: "text", text: "okr_reparent_objective needs parent_id (an objective id to attach under, or null to detach to a top-level root)." }], isError: true };
2731
+ const validated = validateOkrReparentObjectiveInput(args);
2732
+ if (!validated.ok) {
2733
+ return { content: [{ type: "text", text: `okr_reparent_objective invalid arguments: ${validated.error}` }], isError: true };
2279
2734
  }
2735
+ const { objective_id, body } = validated.value;
2280
2736
  try {
2281
2737
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/parent`, {
2282
2738
  method: "PATCH",
2283
2739
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2284
- body: JSON.stringify({ parent_id: parent_id ?? null }),
2740
+ body: JSON.stringify(body),
2285
2741
  });
2286
2742
  const text = await r.text();
2287
2743
  if (!r.ok) {
2288
- return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2744
+ return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2289
2745
  }
2290
2746
  return { content: [{ type: "text", text: `Reparented: ${text}` }] };
2291
2747
  } catch (e: any) {
2292
- return { content: [{ type: "text", text: `okr_reparent_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2748
+ return { content: [{ type: "text", text: `okr_reparent_objective network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2293
2749
  }
2294
2750
  });
2295
2751
 
2296
- // list_my_channels — the caller's actual membership (channels + DMs) from
2297
- // /api/channels/mine, distinct from list_channels (public discovery). Registered
2298
- // here per the frozen-registry policy; new tools never join the legacy if-chain.
2299
- HANDLERS.set("list_my_channels", async (args) => {
2300
- const filter = (((args || {}) as { type?: string }).type || "all").toLowerCase();
2752
+ async function setLoopPaused(args: any, action: "pause" | "resume") {
2753
+ const loopId = String(args?.loop_id || "").trim();
2754
+ if (!isSafeLoopIdentifier(loopId)) {
2755
+ return { content: [{ type: "text", text: `${action}_loop needs a valid loop_id.` }], isError: true };
2756
+ }
2301
2757
  try {
2302
- const r = await apiFetch(`${REST_URL}/api/channels/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
2303
- if (!r.ok) return { content: [{ type: "text", text: `Failed to list your channels (${r.status})` }], isError: true };
2304
- const data = await r.json() as any;
2305
- let channels = Array.isArray(data?.channels) ? data.channels : [];
2306
- if (filter === "channel") channels = channels.filter((c: any) => c?.type !== "direct");
2307
- else if (filter === "direct") channels = channels.filter((c: any) => c?.type === "direct");
2308
- if (channels.length === 0) {
2309
- return { content: [{ type: "text", text: filter === "all" ? "You haven't joined any channels yet." : `No ${filter} channels in your memberships.` }] };
2758
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/${action}`, {
2759
+ method: "POST",
2760
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2761
+ });
2762
+ const text = await r.text();
2763
+ if (!r.ok) {
2764
+ return { content: [{ type: "text", text: `${action}_loop failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2310
2765
  }
2311
- const list = channels.map((ch: any) =>
2312
- `• [${ch?.type === "direct" ? "DM" : "channel"}] ${ch?.name || ch?.id} (${ch?.id})${ch?.member_count != null ? ` — ${ch.member_count} members` : ""}`
2313
- ).join("\n");
2314
- return { content: [{ type: "text", text: `${channels.length} joined:\n${list}` }] };
2766
+ parseSafeJsonObject(text);
2767
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2768
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2769
+ });
2770
+ if (!verified.ok) {
2771
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2772
+ }
2773
+ const state = await verified.json() as any;
2774
+ const loop = Array.isArray(state?.loops)
2775
+ ? state.loops.find((candidate: any) => candidate?.loop_id === loopId)
2776
+ : undefined;
2777
+ if (!loop) {
2778
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but loop ${loopId} was absent from state verification; use list_loops before retrying.` }], isError: true };
2779
+ }
2780
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2781
+ const active = loop.paused === false || loop.paused_at === null;
2782
+ return {
2783
+ content: [{
2784
+ type: "text",
2785
+ text: JSON.stringify({
2786
+ ok: true,
2787
+ loop_id: loop.loop_id || loopId,
2788
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2789
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2790
+ }),
2791
+ }],
2792
+ };
2315
2793
  } catch (e: any) {
2316
- return { content: [{ type: "text", text: `Error listing your channels: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2794
+ return { content: [{ type: "text", text: `${action}_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2317
2795
  }
2318
- });
2319
-
2320
- // ── media (T6, obj_mr9hu1v4) — send_image / send_voice ───────────────────────
2321
- // Agents can't build multipart bodies, so these take a local file `path` and do
2322
- // the /api/upload multipart here (MCP-server side), or accept an already-hosted
2323
- // proxy `url`. The message is posted with an orthogonal attachments[] entry per
2324
- // the T1 wire contract; the server's sanitizeAttachments normalizes the url to a
2325
- // relative /api/file/uploads/* path and drops anything off-whitelist/off-host.
2326
- const MEDIA_MIME_BY_EXT: Record<string, string> = {
2327
- jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
2328
- webp: "image/webp", heic: "image/heic", heif: "image/heif", avif: "image/avif",
2329
- mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", webm: "video/webm", "3gp": "video/3gpp",
2330
- m4a: "audio/mp4", aac: "audio/aac", mp3: "audio/mpeg",
2331
- wav: "audio/wav", weba: "audio/webm", ogg: "audio/ogg", oga: "audio/ogg",
2332
- };
2333
- function mimeFromPath(p: string, kindHint?: "image" | "video" | "audio"): string {
2334
- const ext = p.split(".").pop()?.toLowerCase() ?? "";
2335
- if (kindHint === "audio" && ext === "mp4") return "audio/mp4";
2336
- if (kindHint === "audio" && ext === "webm") return "audio/webm";
2337
- return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
2338
2796
  }
2339
- // Upload a local file via multipart POST /api/upload → { url, mime, size }.
2340
- async function uploadLocalFile(path: string, kindHint?: "image" | "video" | "audio"): Promise<{ url: string; mime: string; size: number }> {
2341
- // node:fs (not Bun.file) so this runs on plain Node too — Bun supports node:fs
2342
- // identically, and the Node path is what registry introspection (Glama) uses.
2343
- if (!existsSync(path)) throw new Error(`file not found: ${path}`);
2344
- const mime = mimeFromPath(path, kindHint);
2345
- const buf = readFileSync(path);
2346
- const name = path.split("/").pop() || "upload";
2347
- const form = new FormData();
2348
- form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
2349
- // No Content-Type header → fetch derives the multipart boundary itself.
2350
- const r = await apiFetch(`${REST_URL}/api/upload`, { method: "POST", headers: { "Authorization": `Bearer ${TOKEN}` }, body: form });
2351
- const text = await r.text();
2797
+
2798
+ HANDLERS.set("create_loop", async (args) => {
2799
+ const checked = validateCreateLoopInput(args);
2800
+ if (!checked.ok) {
2801
+ return { content: [{ type: "text", text: checked.error }], isError: true };
2802
+ }
2803
+ try {
2804
+ const r = await apiFetch(`${REST_URL}/api/loops`, {
2805
+ method: "POST",
2806
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2807
+ body: JSON.stringify(checked.value),
2808
+ });
2809
+ const text = await r.text();
2810
+ if (!r.ok) {
2811
+ return { content: [{ type: "text", text: `create_loop failed (${r.status}): ${scrubMcpHandlerError(text, 220)}` }], isError: true };
2812
+ }
2813
+ const createdPayload = parseSafeJsonObject(text) as any;
2814
+ const createdLoopId = String(createdPayload?.loop?.loop_id || "").trim();
2815
+ if (!isSafeLoopIdentifier(createdLoopId)) {
2816
+ return {
2817
+ content: [{ type: "text", text: "create_loop returned an invalid loop_id; use list_loops before retrying." }],
2818
+ isError: true,
2819
+ };
2820
+ }
2821
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2822
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2823
+ });
2824
+ if (!verified.ok) {
2825
+ return {
2826
+ content: [{ type: "text", text: `create_loop was accepted (${createdLoopId}), but state verification failed (${verified.status}); use list_loops before retrying.` }],
2827
+ isError: true,
2828
+ };
2829
+ }
2830
+ const state = await verified.json() as any;
2831
+ if (!Array.isArray(state?.loops)) {
2832
+ return {
2833
+ content: [{ type: "text", text: "create_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }],
2834
+ isError: true,
2835
+ };
2836
+ }
2837
+ const loop = state.loops.find((candidate: any) => candidate?.loop_id === createdLoopId);
2838
+ if (!loop) {
2839
+ return {
2840
+ content: [{ type: "text", text: `create_loop was accepted, but loop ${createdLoopId} was absent from state verification; use list_loops before retrying.` }],
2841
+ isError: true,
2842
+ };
2843
+ }
2844
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2845
+ const active = loop.paused === false || loop.paused_at === null;
2846
+ return {
2847
+ content: [{
2848
+ type: "text",
2849
+ text: JSON.stringify({
2850
+ ok: true,
2851
+ deduplicated: Boolean(createdPayload?.deduplicated),
2852
+ loop: {
2853
+ loop_id: loop.loop_id || createdLoopId,
2854
+ channel_id: loop.channel_id || checked.value.channel_id,
2855
+ mode: loop.mode || (checked.value.mode === "prompt" ? "static" : checked.value.mode),
2856
+ ...(loop.objective_id ? { objective_id: loop.objective_id } : {}),
2857
+ interval_ms: loop.interval_ms,
2858
+ ...(Array.isArray(loop.target_agents) ? { target_agents: loop.target_agents } : {}),
2859
+ ...(typeof loop.watch_idle === "boolean" ? { watch_idle: loop.watch_idle } : {}),
2860
+ ...(typeof loop.watch_supply === "boolean" ? { watch_supply: loop.watch_supply } : {}),
2861
+ ...(typeof loop.stall_minutes === "number" ? { stall_minutes: loop.stall_minutes } : {}),
2862
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2863
+ paused,
2864
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2865
+ },
2866
+ }),
2867
+ }],
2868
+ };
2869
+ } catch (e: any) {
2870
+ return { content: [{ type: "text", text: `create_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2871
+ }
2872
+ });
2873
+
2874
+ HANDLERS.set("pause_loop", (args) => setLoopPaused(args, "pause"));
2875
+ HANDLERS.set("resume_loop", (args) => setLoopPaused(args, "resume"));
2876
+
2877
+ const LOOP_INTERVAL_MIN_MS = 60_000;
2878
+ const LOOP_INTERVAL_MAX_MS = 86_400_000;
2879
+
2880
+ function isSafeLoopIdentifier(loopId: string): boolean {
2881
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(loopId)) return false;
2882
+ if (loopId === "." || loopId.includes("..")) return false;
2883
+ return !RESERVED_MCP_ROUTE_KEYS.has(loopId.toLowerCase());
2884
+ }
2885
+
2886
+ HANDLERS.set("set_loop_interval", async (args) => {
2887
+ const loopId = String(args?.loop_id || "").trim();
2888
+ const intervalMs = args?.interval_ms;
2889
+ if (!isSafeLoopIdentifier(loopId)) {
2890
+ return { content: [{ type: "text", text: "set_loop_interval needs a valid loop_id." }], isError: true };
2891
+ }
2892
+ if (!Number.isSafeInteger(intervalMs) || intervalMs < LOOP_INTERVAL_MIN_MS || intervalMs > LOOP_INTERVAL_MAX_MS) {
2893
+ return {
2894
+ content: [{ type: "text", text: `set_loop_interval needs integer interval_ms in ${LOOP_INTERVAL_MIN_MS}..${LOOP_INTERVAL_MAX_MS} (1m..24h).` }],
2895
+ isError: true,
2896
+ };
2897
+ }
2898
+ try {
2899
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/interval`, {
2900
+ method: "POST",
2901
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2902
+ body: JSON.stringify({ interval_ms: intervalMs }),
2903
+ });
2904
+ const text = await r.text();
2905
+ if (!r.ok) {
2906
+ return { content: [{ type: "text", text: `set_loop_interval failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2907
+ }
2908
+ parseSafeJsonObject(text);
2909
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2910
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2911
+ });
2912
+ if (!verified.ok) {
2913
+ return { content: [{ type: "text", text: `set_loop_interval was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2914
+ }
2915
+ const state = await verified.json() as any;
2916
+ const loop = Array.isArray(state?.loops)
2917
+ ? state.loops.find((candidate: any) => candidate?.loop_id === loopId)
2918
+ : undefined;
2919
+ if (!loop) {
2920
+ return { content: [{ type: "text", text: `set_loop_interval was accepted, but loop ${loopId} was absent from state verification; use list_loops before retrying.` }], isError: true };
2921
+ }
2922
+ if (loop.interval_ms !== intervalMs) {
2923
+ return { content: [{ type: "text", text: `set_loop_interval verification mismatch (expected ${intervalMs}, got ${loop.interval_ms}); use list_loops before retrying.` }], isError: true };
2924
+ }
2925
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2926
+ const active = loop.paused === false || loop.paused_at === null;
2927
+ return {
2928
+ content: [{
2929
+ type: "text",
2930
+ text: JSON.stringify({
2931
+ ok: true,
2932
+ loop_id: loop.loop_id || loopId,
2933
+ interval_ms: loop.interval_ms,
2934
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2935
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2936
+ }),
2937
+ }],
2938
+ };
2939
+ } catch (e: any) {
2940
+ return { content: [{ type: "text", text: `set_loop_interval error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2941
+ }
2942
+ });
2943
+
2944
+ HANDLERS.set("stop_loop", async (args) => {
2945
+ const loopId = String(args?.loop_id || "").trim();
2946
+ if (!isSafeLoopIdentifier(loopId)) {
2947
+ return { content: [{ type: "text", text: "stop_loop needs a valid loop_id." }], isError: true };
2948
+ }
2949
+ try {
2950
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/stop`, {
2951
+ method: "POST",
2952
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2953
+ });
2954
+ const text = await r.text();
2955
+ if (!r.ok) {
2956
+ return { content: [{ type: "text", text: `stop_loop failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2957
+ }
2958
+ parseSafeJsonObject(text);
2959
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2960
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2961
+ });
2962
+ if (!verified.ok) {
2963
+ return { content: [{ type: "text", text: `stop_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2964
+ }
2965
+ const state = await verified.json() as any;
2966
+ if (!Array.isArray(state?.loops)) {
2967
+ return { content: [{ type: "text", text: "stop_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }], isError: true };
2968
+ }
2969
+ const stillPresent = state.loops.some((candidate: any) => candidate?.loop_id === loopId);
2970
+ if (stillPresent) {
2971
+ return { content: [{ type: "text", text: `stop_loop was accepted, but loop ${loopId} is still present in state verification; use list_loops before retrying.` }], isError: true };
2972
+ }
2973
+ return {
2974
+ content: [{
2975
+ type: "text",
2976
+ text: JSON.stringify({
2977
+ ok: true,
2978
+ stopped: loopId,
2979
+ }),
2980
+ }],
2981
+ };
2982
+ } catch (e: any) {
2983
+ return { content: [{ type: "text", text: `stop_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2984
+ }
2985
+ });
2986
+
2987
+ HANDLERS.set("delete_memory", async (args) => {
2988
+ const checked = validateDeleteMemoryInput(args);
2989
+ if (!checked.ok) {
2990
+ return { content: [{ type: "text", text: checked.error }], isError: true };
2991
+ }
2992
+ try {
2993
+ const qs = checked.value.if_match_version !== undefined
2994
+ ? `?if_match_version=${checked.value.if_match_version}`
2995
+ : "";
2996
+ const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(checked.value.name)}${qs}`, {
2997
+ method: "DELETE",
2998
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2999
+ });
3000
+ const text = await r.text();
3001
+ if (!r.ok) {
3002
+ return {
3003
+ content: [{ type: "text", text: `delete_memory failed (${r.status}): ${scrubMcpHandlerError(text, 240)}` }],
3004
+ isError: true,
3005
+ };
3006
+ }
3007
+ const resp = parseSafeJsonObject(text) as any;
3008
+ const deleted = Boolean(resp?.deleted);
3009
+ if (!deleted && !checked.value.allow_missing) {
3010
+ return {
3011
+ content: [{
3012
+ type: "text",
3013
+ text: `delete_memory: memory "${checked.value.name}" does not exist (pass allow_missing=true for idempotent cleanup).`,
3014
+ }],
3015
+ isError: true,
3016
+ };
3017
+ }
3018
+ return {
3019
+ content: [{
3020
+ type: "text",
3021
+ text: JSON.stringify({
3022
+ ok: true,
3023
+ name: typeof resp?.name === "string" && resp.name ? resp.name : checked.value.name,
3024
+ deleted,
3025
+ }),
3026
+ }],
3027
+ };
3028
+ } catch (e: any) {
3029
+ return { content: [{ type: "text", text: `delete_memory network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3030
+ }
3031
+ });
3032
+
3033
+ HANDLERS.set("okr_update_kr", async (args) => {
3034
+ const validated = validateOkrUpdateKrInput(args);
3035
+ if (!validated.ok) {
3036
+ return { content: [{ type: "text", text: `okr_update_kr invalid arguments: ${validated.error}` }], isError: true };
3037
+ }
3038
+ const { kr_id, body } = validated.value;
3039
+ try {
3040
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}`, {
3041
+ method: "PATCH",
3042
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
3043
+ body: JSON.stringify(body),
3044
+ });
3045
+ const text = await r.text();
3046
+ if (!r.ok) {
3047
+ return { content: [{ type: "text", text: `okr_update_kr failed (${r.status}): ${scrubMcpHandlerError(text, 160)}` }], isError: true };
3048
+ }
3049
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
3050
+ } catch (e: any) {
3051
+ return { content: [{ type: "text", text: `okr_update_kr network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3052
+ }
3053
+ });
3054
+
3055
+ function redactCloudAgentDisplayName(name: string): string {
3056
+ const preScrubbed = name
3057
+ .replace(/\bsk-(?:ant|proj|live|test)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]")
3058
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, "[REDACTED]")
3059
+ .replace(/\bAIza[0-9A-Za-z_-]{30,}\b/g, "[REDACTED]");
3060
+ const safe = redactSecrets(preScrubbed);
3061
+ return redactParticipantPii(safe).slice(0, 128);
3062
+ }
3063
+
3064
+ function projectWakeHealthPayload(channelId: string, data: any): { channel_id: string; observation_only: true; agents: any[]; summary: Record<string, number>; untrusted: true } | null {
3065
+ if (!data || data.channel_id !== channelId || data.observation_only !== true || !Array.isArray(data.agents)) {
3066
+ return null;
3067
+ }
3068
+ const agents = data.agents.map((item: any) => {
3069
+ if (!item || typeof item.agent_id !== "string" || !/^[\w.-]{1,128}$/.test(item.agent_id) || isHumanPiiHandle(item.agent_id)) return null;
3070
+ const rawStatus = item.wake?.status ?? item.last_wake_status;
3071
+ const rawAt = item.wake?.last_wake_at ?? item.last_wake_at;
3072
+ const rawDur = item.wake?.last_duration_ms ?? item.last_duration_ms;
3073
+ const validWake = rawStatus === "ok" || rawStatus === "auth_required" || rawStatus === "timeout" || rawStatus === "error";
3074
+ const wake = validWake && typeof rawAt === "string" && Number.isSafeInteger(rawDur) && rawDur >= 0
3075
+ ? { status: rawStatus, last_wake_at: rawAt, last_duration_ms: rawDur }
3076
+ : null;
3077
+ return {
3078
+ agent_id: item.agent_id,
3079
+ ...(typeof item.name === "string" && item.name ? { name: redactCloudAgentDisplayName(item.name) } : {}),
3080
+ runtime: String(item.runtime || "unknown").slice(0, 32),
3081
+ cloud_status: String(item.cloud_status || "unknown").slice(0, 32),
3082
+ wake,
3083
+ };
3084
+ }).filter(Boolean).slice(0, 64) as any[];
3085
+ const summary = { total: agents.length, ok: 0, auth_required: 0, timeout: 0, error: 0, unobserved: 0 };
3086
+ for (const agent of agents) {
3087
+ if (agent.wake) summary[agent.wake.status as "ok" | "auth_required" | "timeout" | "error"]++;
3088
+ else summary.unobserved++;
3089
+ }
3090
+ return { channel_id: channelId, observation_only: true, agents, summary, untrusted: true };
3091
+ }
3092
+
3093
+ HANDLERS.set("cloud_agent_wake_health", async (args) => {
3094
+ const channelId = String(args?.channel_id || "").trim();
3095
+ if (!isSafeChannelRouteId(channelId)) {
3096
+ return { content: [{ type: "text", text: "cloud_agent_wake_health needs channel_id." }], isError: true };
3097
+ }
3098
+ const reqHeaders = {
3099
+ "Authorization": `Bearer ${TOKEN}`,
3100
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3101
+ };
3102
+ try {
3103
+ const r = await apiFetch(`${REST_URL}/mcp`, {
3104
+ method: "POST",
3105
+ headers: { ...reqHeaders, "Content-Type": "application/json" },
3106
+ body: JSON.stringify({
3107
+ jsonrpc: "2.0", id: 1, method: "tools/call",
3108
+ params: { name: "agentschat_cloud_agent_wake_health", arguments: { channel_id: channelId } },
3109
+ }),
3110
+ }, 5000, true);
3111
+ let rpcErrorCode: unknown = null;
3112
+ let rpcErrorMsg = "";
3113
+ if (r.ok) {
3114
+ const rpc = await r.json() as any;
3115
+ if (!rpc?.error && !rpc?.result?.isError) {
3116
+ let data = rpc?.result?.structuredContent;
3117
+ if (!data && typeof rpc?.result?.content?.[0]?.text === "string") data = parseSafeJsonObject(rpc.result.content[0].text);
3118
+ const projected = projectWakeHealthPayload(channelId, data);
3119
+ if (!projected) return { content: [{ type: "text", text: "cloud_agent_wake_health returned an invalid response" }], isError: true };
3120
+ return { content: [{ type: "text", text: JSON.stringify(projected) }] };
3121
+ }
3122
+ rpcErrorCode = rpc?.error?.code ?? "remote_error";
3123
+ rpcErrorMsg = typeof rpc?.error?.message === "string" ? rpc.error.message : "";
3124
+ }
3125
+ // Fallback to REST /api/channels/:id/wake-health (with legacy /cloud-wake-health fallback)
3126
+ // when /mcp predates the tool (-32601/-32602 Unknown tool or 404/405).
3127
+ const canFallback = (!r.ok && (r.status === 404 || r.status === 405)) ||
3128
+ ((rpcErrorCode === -32601 || rpcErrorCode === -32602) && !/denied|forbidden|invalid cloud wake health/i.test(rpcErrorMsg));
3129
+ if (canFallback) {
3130
+ let restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/wake-health`, {
3131
+ headers: reqHeaders,
3132
+ }, 5000, true);
3133
+ if (restRes.status === 404 || restRes.status === 405) {
3134
+ restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/cloud-wake-health`, {
3135
+ headers: reqHeaders,
3136
+ }, 5000, true);
3137
+ }
3138
+ if (restRes.ok) {
3139
+ const projected = projectWakeHealthPayload(channelId, await restRes.json());
3140
+ if (projected) return { content: [{ type: "text", text: JSON.stringify(projected) }] };
3141
+ }
3142
+ }
3143
+ if (!r.ok) return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${r.status})` }], isError: true };
3144
+ const safeDetail = rpcErrorMsg ? `: ${scrubMcpHandlerError(redactParticipantPii(rpcErrorMsg), 80)}` : "";
3145
+ return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${rpcErrorCode}${safeDetail})` }], isError: true };
3146
+ } catch (e: any) {
3147
+ return { content: [{ type: "text", text: `cloud_agent_wake_health error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3148
+ }
3149
+ });
3150
+
3151
+ function sanitizeProposalItem(p: any): any {
3152
+ if (!p || typeof p !== "object") return null;
3153
+ const votes = Array.isArray(p.votes)
3154
+ ? p.votes.map((v: any) => ({
3155
+ voter_id: typeof v?.voter_id === "string" ? redactParticipantPii(v.voter_id) : "unknown",
3156
+ voter_type: v?.voter_type === "human" ? "human" : "agent",
3157
+ decision: v?.decision,
3158
+ ...(typeof v?.reason === "string" && v.reason
3159
+ ? { reason: redactSecrets(v.reason.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ").trim()).slice(0, 500) }
3160
+ : {}),
3161
+ }))
3162
+ : [];
3163
+ return {
3164
+ id: String(p.id || ""),
3165
+ channel_id: String(p.channel_id || ""),
3166
+ sender_id: typeof p.sender_id === "string" ? redactParticipantPii(p.sender_id) : "unknown",
3167
+ title: typeof p.title === "string" ? redactSecrets(p.title).slice(0, 500) : "",
3168
+ content: typeof p.content === "string" ? redactSecrets(p.content).slice(0, 4000) : "",
3169
+ ...(typeof p.code_diff === "string" ? { code_diff: redactSecrets(p.code_diff).slice(0, 8000) } : {}),
3170
+ consensus_rule: p.consensus_rule || "majority",
3171
+ ...(typeof p.expires_at === "string" && p.expires_at ? { expires_at: p.expires_at } : {}),
3172
+ timestamp: String(p.timestamp || ""),
3173
+ status: String(p.status || "pending"),
3174
+ total_voters: typeof p.total_voters === "number" ? p.total_voters : 1,
3175
+ votes,
3176
+ ...(p.vote_result && typeof p.vote_result === "object" ? { vote_result: p.vote_result } : {}),
3177
+ };
3178
+ }
3179
+
3180
+ HANDLERS.set("list_pins", async (args) => {
3181
+ const chatId = String(args?.chat_id || "").trim();
3182
+ if (!isSafeChannelRouteId(chatId)) {
3183
+ return { content: [{ type: "text", text: "list_pins needs a valid chat_id." }], isError: true };
3184
+ }
3185
+ try {
3186
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/pins`, {
3187
+ headers: {
3188
+ "Authorization": `Bearer ${TOKEN}`,
3189
+ "Cache-Control": "no-store",
3190
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3191
+ },
3192
+ });
3193
+ const text = await r.text();
3194
+ if (!r.ok) {
3195
+ return { content: [{ type: "text", text: `list_pins failed (${r.status}): ${scrubMcpHandlerError(text, 180)}` }], isError: true };
3196
+ }
3197
+ const body = parseSafeJsonObject(text) as any;
3198
+ const seen = new Set<string>();
3199
+ const pinnedMessages: string[] = [];
3200
+ if (Array.isArray(body?.pinned_messages)) {
3201
+ for (const rawId of body.pinned_messages) {
3202
+ if (typeof rawId !== "string") continue;
3203
+ const cleaned = rawId.trim().slice(0, 128);
3204
+ if (!cleaned || /[\x00-\x1f\x7f]/.test(cleaned) || seen.has(cleaned)) continue;
3205
+ seen.add(cleaned);
3206
+ pinnedMessages.push(cleaned);
3207
+ }
3208
+ }
3209
+ return {
3210
+ content: [{
3211
+ type: "text",
3212
+ text: JSON.stringify({
3213
+ channel_id: chatId,
3214
+ count: pinnedMessages.length,
3215
+ pinned_messages: pinnedMessages,
3216
+ }),
3217
+ }],
3218
+ };
3219
+ } catch (e: any) {
3220
+ return { content: [{ type: "text", text: `list_pins error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3221
+ }
3222
+ });
3223
+
3224
+ HANDLERS.set("list_proposals", async (args) => {
3225
+ const chatId = String(args?.chat_id || "").trim();
3226
+ const statusFilter = String(args?.status || "all").trim().toLowerCase();
3227
+ if (!isSafeChannelRouteId(chatId)) {
3228
+ return { content: [{ type: "text", text: "list_proposals needs chat_id." }], isError: true };
3229
+ }
3230
+ if (!["all", "pending", "passed", "rejected"].includes(statusFilter)) {
3231
+ return { content: [{ type: "text", text: "list_proposals status must be all, pending, passed, or rejected." }], isError: true };
3232
+ }
3233
+ try {
3234
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
3235
+ headers: {
3236
+ "Authorization": `Bearer ${TOKEN}`,
3237
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3238
+ },
3239
+ });
3240
+ const text = await r.text();
3241
+ if (!r.ok) {
3242
+ return { content: [{ type: "text", text: `list_proposals failed (${r.status}): ${scrubMcpHandlerError(text, 180)}` }], isError: true };
3243
+ }
3244
+ const body = parseSafeJsonObject(text) as any;
3245
+ let proposals = (Array.isArray(body?.proposals) ? body.proposals : []).map(sanitizeProposalItem).filter(Boolean);
3246
+ if (statusFilter !== "all") {
3247
+ proposals = proposals.filter((p: any) => p.status === statusFilter);
3248
+ }
3249
+ return { content: [{ type: "text", text: JSON.stringify({ channel_id: chatId, count: proposals.length, proposals, untrusted: true }) }] };
3250
+ } catch (e: any) {
3251
+ return { content: [{ type: "text", text: `list_proposals error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3252
+ }
3253
+ });
3254
+
3255
+ HANDLERS.set("propose", async (args) => {
3256
+ const { chat_id, title, content, code_diff, consensus_rule, expires_at } = (args || {}) as any;
3257
+ const chatId = typeof chat_id === "string" ? chat_id.trim() : "";
3258
+ if (!isSafeChannelRouteId(chatId) || typeof title !== "string" || !title.trim() || typeof content !== "string") {
3259
+ return { content: [{ type: "text", text: "Error: chat_id, non-empty title, and content (strings) required" }], isError: true };
3260
+ }
3261
+ const rule = consensus_rule || "majority";
3262
+ if (!["majority", "super_majority", "unanimous"].includes(rule)) {
3263
+ return { content: [{ type: "text", text: "Error: consensus_rule must be majority, super_majority, or unanimous" }], isError: true };
3264
+ }
3265
+ const proposalId = crypto.randomUUID();
3266
+ const effectiveExpiresAt = typeof expires_at === "string" && expires_at.trim()
3267
+ ? expires_at.trim()
3268
+ : new Date(Date.now() + 86400_000).toISOString();
3269
+ if (TOKEN) {
3270
+ try {
3271
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
3272
+ method: "POST",
3273
+ headers: {
3274
+ "Authorization": `Bearer ${TOKEN}`,
3275
+ "Content-Type": "application/json",
3276
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3277
+ },
3278
+ body: JSON.stringify({
3279
+ id: proposalId,
3280
+ ...(AGENT_ID ? { sender_id: AGENT_ID } : {}),
3281
+ title,
3282
+ content,
3283
+ ...(typeof code_diff === "string" ? { code_diff } : {}),
3284
+ consensus_rule: rule,
3285
+ expires_at: effectiveExpiresAt,
3286
+ }),
3287
+ });
3288
+ if (r.ok) {
3289
+ const data = await r.json() as any;
3290
+ const proposal = sanitizeProposalItem(data?.proposal ?? data);
3291
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal }) }] };
3292
+ }
3293
+ if (r.status !== 404 && r.status !== 405 && r.status !== 501) {
3294
+ const errText = await r.text();
3295
+ return { content: [{ type: "text", text: `propose failed (${r.status}): ${scrubMcpHandlerError(errText, 180)}` }], isError: true };
3296
+ }
3297
+ } catch {
3298
+ // Network/pre-deploy fallback to WebSocket below when open.
3299
+ }
3300
+ }
3301
+ if (ws && ws.readyState === WebSocket.OPEN) {
3302
+ ws.send(JSON.stringify({
3303
+ type: "proposal", id: proposalId, channel_id: chatId,
3304
+ sender_id: AGENT_ID, title, content, code_diff,
3305
+ consensus_rule: rule,
3306
+ expires_at: effectiveExpiresAt,
3307
+ timestamp: new Date().toISOString(),
3308
+ }));
3309
+ return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject — verify via next inbound event` }] };
3310
+ }
3311
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
3312
+ });
3313
+
3314
+ HANDLERS.set("vote", async (args) => {
3315
+ const { chat_id, channel_id, proposal_id, decision, reason } = (args || {}) as any;
3316
+ if (!isSafeProposalRouteId(proposal_id) || typeof decision !== "string") {
3317
+ return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }], isError: true };
3318
+ }
3319
+ if (!["approve", "reject", "abstain"].includes(decision)) {
3320
+ return { content: [{ type: "text", text: "Error: decision must be approve, reject, or abstain" }], isError: true };
3321
+ }
3322
+ const propId = proposal_id.trim();
3323
+ const chatId = typeof chat_id === "string" && chat_id.trim()
3324
+ ? chat_id.trim()
3325
+ : (typeof channel_id === "string" && channel_id.trim() ? channel_id.trim() : "");
3326
+ if (chatId && !isSafeChannelRouteId(chatId)) {
3327
+ return { content: [{ type: "text", text: "Error: invalid chat_id" }], isError: true };
3328
+ }
3329
+ if (chatId && TOKEN) {
3330
+ try {
3331
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals/${encodeURIComponent(propId)}/votes`, {
3332
+ method: "POST",
3333
+ headers: {
3334
+ "Authorization": `Bearer ${TOKEN}`,
3335
+ "Content-Type": "application/json",
3336
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3337
+ },
3338
+ body: JSON.stringify({
3339
+ ...(AGENT_ID ? { voter_id: AGENT_ID } : {}),
3340
+ decision,
3341
+ ...(typeof reason === "string" ? { reason } : {}),
3342
+ }),
3343
+ });
3344
+ if (r.ok) {
3345
+ const data = await r.json() as any;
3346
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal_id: data?.proposal_id ?? propId, vote_result: data?.vote_result }) }] };
3347
+ }
3348
+ const errText = await r.text();
3349
+ // Only fall back to WS when the server build predates the REST route (404 with HTML/route missing, not Proposal not found JSON).
3350
+ const isProposal404 = r.status === 404 && /proposal not found|channel not found/i.test(errText);
3351
+ if ((r.status !== 404 && r.status !== 405 && r.status !== 501) || isProposal404) {
3352
+ return { content: [{ type: "text", text: `vote failed (${r.status}): ${scrubMcpHandlerError(errText, 180)}` }], isError: true };
3353
+ }
3354
+ } catch {
3355
+ // Fall back to WS below if open.
3356
+ }
3357
+ }
3358
+ if (ws && ws.readyState === WebSocket.OPEN) {
3359
+ ws.send(JSON.stringify({
3360
+ type: "vote", proposal_id: propId, voter_id: AGENT_ID,
3361
+ voter_type: "agent", decision, reason,
3362
+ }));
3363
+ return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${propId.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
3364
+ }
3365
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
3366
+ });
3367
+
3368
+ HANDLERS.set("list_channels", async (args) => {
3369
+ const { query, limit = 50 } = (args || {}) as { query?: string; limit?: number };
3370
+ const clamped = Math.max(1, Math.min(Number(limit) || 50, 500));
3371
+ const qs = new URLSearchParams({ limit: String(clamped) });
3372
+ if (typeof query === "string" && query.trim()) qs.set("q", query.trim());
3373
+ try {
3374
+ const r = await apiFetch(`${REST_URL}/api/channels/discover?${qs.toString()}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3375
+ if (r.ok) {
3376
+ const data = await r.json() as any;
3377
+ const channels = (data.channels || []);
3378
+ if (channels.length === 0) return { content: [{ type: "text", text: "No public channels found." }] };
3379
+ const list = channels.map((ch: any) => {
3380
+ const onlineBadge = typeof ch.online_agent_count === "number" && ch.online_agent_count > 0 ? `, 🟢 ${ch.online_agent_count} online` : "";
3381
+ const caps = Array.isArray(ch.capabilities) && ch.capabilities.length > 0 ? ` [${ch.capabilities.slice(0, 6).join(", ")}]` : "";
3382
+ const topic = ch.topic
3383
+ ? ` — ${redactSecrets(String(ch.topic).replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ").trim()).slice(0, 60)}`
3384
+ : "";
3385
+ return `• ${ch.name || ch.id} (${ch.id}) — ${ch.member_count || "?"} members${onlineBadge}${caps}${topic}`;
3386
+ }).join("\n");
3387
+ return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
3388
+ }
3389
+ return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
3390
+ } catch (e) {
3391
+ return { content: [{ type: "text", text: `Error: ${e}` }] };
3392
+ }
3393
+ });
3394
+
3395
+ // list_my_channels — the caller's actual membership (channels + DMs) from
3396
+ // /api/channels/mine, distinct from list_channels (public discovery). Registered
3397
+ // here per the frozen-registry policy; new tools never join the legacy if-chain.
3398
+ HANDLERS.set("list_my_channels", async (args) => {
3399
+ const filter = (((args || {}) as { type?: string }).type || "all").toLowerCase();
3400
+ try {
3401
+ const r = await apiFetch(`${REST_URL}/api/channels/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3402
+ if (!r.ok) return { content: [{ type: "text", text: `Failed to list your channels (${r.status})` }], isError: true };
3403
+ const data = await r.json() as any;
3404
+ let channels = Array.isArray(data?.channels) ? data.channels : [];
3405
+ if (filter === "channel") channels = channels.filter((c: any) => c?.type !== "direct");
3406
+ else if (filter === "direct") channels = channels.filter((c: any) => c?.type === "direct");
3407
+ if (channels.length === 0) {
3408
+ return { content: [{ type: "text", text: filter === "all" ? "You haven't joined any channels yet." : `No ${filter} channels in your memberships.` }] };
3409
+ }
3410
+ const list = channels.map((ch: any) =>
3411
+ `• [${ch?.type === "direct" ? "DM" : "channel"}] ${ch?.name || ch?.id} (${ch?.id})${ch?.member_count != null ? ` — ${ch.member_count} members` : ""}`
3412
+ ).join("\n");
3413
+ return { content: [{ type: "text", text: `${channels.length} joined:\n${list}` }] };
3414
+ } catch (e: any) {
3415
+ return { content: [{ type: "text", text: `Error listing your channels: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3416
+ }
3417
+ });
3418
+
3419
+ // ── media (T6, obj_mr9hu1v4) — send_image / send_voice ───────────────────────
3420
+ // Agents can't build multipart bodies, so these take a local file `path` and do
3421
+ // the /api/upload multipart here (MCP-server side), or accept an already-hosted
3422
+ // proxy `url`. The message is posted with an orthogonal attachments[] entry per
3423
+ // the T1 wire contract; the server's sanitizeAttachments normalizes the url to a
3424
+ // relative /api/file/uploads/* path and drops anything off-whitelist/off-host.
3425
+ const MEDIA_MIME_BY_EXT: Record<string, string> = {
3426
+ jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
3427
+ webp: "image/webp", heic: "image/heic", heif: "image/heif", avif: "image/avif",
3428
+ mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", webm: "video/webm", "3gp": "video/3gpp",
3429
+ m4a: "audio/mp4", aac: "audio/aac", mp3: "audio/mpeg",
3430
+ wav: "audio/wav", weba: "audio/webm", ogg: "audio/ogg", oga: "audio/ogg",
3431
+ };
3432
+ function mimeFromPath(p: string, kindHint?: "image" | "video" | "audio"): string {
3433
+ const ext = p.split(".").pop()?.toLowerCase() ?? "";
3434
+ if (kindHint === "audio" && ext === "mp4") return "audio/mp4";
3435
+ if (kindHint === "audio" && ext === "webm") return "audio/webm";
3436
+ return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
3437
+ }
3438
+ // Upload a local file via multipart POST /api/upload → { url, mime, size }.
3439
+ async function uploadLocalFile(path: string, kindHint?: "image" | "video" | "audio"): Promise<{ url: string; mime: string; size: number }> {
3440
+ // node:fs (not Bun.file) so this runs on plain Node too — Bun supports node:fs
3441
+ // identically, and the Node path is what registry introspection (Glama) uses.
3442
+ if (!existsSync(path)) throw new Error(`file not found: ${path}`);
3443
+ const mime = mimeFromPath(path, kindHint);
3444
+ const buf = readFileSync(path);
3445
+ const name = path.split("/").pop() || "upload";
3446
+ const form = new FormData();
3447
+ form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
3448
+ // No Content-Type header → fetch derives the multipart boundary itself.
3449
+ const r = await apiFetch(`${REST_URL}/api/upload`, { method: "POST", headers: { "Authorization": `Bearer ${TOKEN}` }, body: form });
3450
+ const text = await r.text();
2352
3451
  if (!r.ok) throw new Error(`upload failed (${r.status}): ${text.slice(0, 160)}`);
2353
3452
  let data: any;
2354
3453
  try { data = JSON.parse(text); } catch { throw new Error(`upload returned non-JSON: ${text.slice(0, 120)}`); }
@@ -2572,7 +3671,7 @@ function createProfileSlot(opts: {
2572
3671
  capabilities: string[];
2573
3672
  runtimeSession: DetectedSession | null;
2574
3673
  }): ProfileSlot {
2575
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
3674
+ const lastSeenFile = cursorFileForAgent(configDir, opts.agentId);
2576
3675
  const slot: ProfileSlot = {
2577
3676
  profileName: opts.profileName,
2578
3677
  profileFile: opts.profileFile,
@@ -2608,8 +3707,9 @@ function createProfileSlot(opts: {
2608
3707
  ws = null;
2609
3708
  sessionId = null;
2610
3709
  }
2611
- slot.wsReconnectAttempt = 0;
2612
- scheduleReconnect(500, slot);
3710
+ slot.wsReconnectAttempt++;
3711
+ const delay = slot.wsReconnectAttempt === 1 ? 500 : computeReconnectDelay(slot.wsReconnectAttempt);
3712
+ scheduleReconnect(delay, slot);
2613
3713
  },
2614
3714
  getReadyState: () => slot.ws?.readyState ?? WS_CLOSED,
2615
3715
  }, 15_000, 45_000, 30_000);
@@ -2895,12 +3995,22 @@ async function registerAndConnectProfile(
2895
3995
  if (!cleanName) {
2896
3996
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
2897
3997
  }
2898
- const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
2899
- if (safeBase.toLowerCase() === "profile") {
3998
+ const safeBase = cleanName.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
3999
+ const reservedRegisterBases = new Set([
4000
+ "profile",
4001
+ "grok-binds",
4002
+ "grok-binds_meta",
4003
+ "session-binds",
4004
+ "agy-session-binds",
4005
+ "__proto__",
4006
+ "constructor",
4007
+ "prototype",
4008
+ ]);
4009
+ if (!safeBase || reservedRegisterBases.has(safeBase.toLowerCase())) {
2900
4010
  return {
2901
4011
  content: [{
2902
4012
  type: "text",
2903
- text: 'Error: "profile" (profile.json) is reserved and cannot be registered as a named agent profile. Choose a distinct profile name (e.g. "Antigravity", "Claude_Work", "Codex_Dev").',
4013
+ text: `Error: "${safeBase || cleanName}" is reserved and cannot be registered as a named agent profile. Choose a distinct profile name (e.g. "Antigravity", "Claude_Work", "Codex_Dev").`,
2904
4014
  }],
2905
4015
  isError: true,
2906
4016
  };
@@ -2997,7 +4107,28 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
2997
4107
  conversation_id?: string;
2998
4108
  };
2999
4109
 
4110
+ // Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
4111
+ // when set, or via current profile when Cursor stdio started with --profile
4112
+ // and no CURSOR_CONVERSATION_ID. Refuse switches, disconnects, and fresh
4113
+ // registrations that leave the locked identity. No-op allowed.
4114
+ // Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
4115
+ // profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
4116
+ const switchBinds = loadGrokBinds();
4117
+ const bindApplies = currentGrokBindApplicability(switchBinds);
4118
+ const currentBoundProfile = profileNameFromPath(activeProfileFile);
4119
+
3000
4120
  if (disconnect) {
4121
+ if (bindApplies.applies) {
4122
+ const discGate = gateGrokProfileMutation({
4123
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4124
+ binds: switchBinds,
4125
+ currentProfileName: currentBoundProfile,
4126
+ action: "disconnect",
4127
+ });
4128
+ if (discGate.kind === "locked") {
4129
+ return { content: [{ type: "text", text: discGate.message }], isError: true };
4130
+ }
4131
+ }
3001
4132
  const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
3002
4133
  return {
3003
4134
  content: [{
@@ -3011,6 +4142,18 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
3011
4142
 
3012
4143
  const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
3013
4144
  if (typeof register_name === "string" && register_name.trim()) {
4145
+ if (bindApplies.applies) {
4146
+ const regGate = gateGrokProfileMutation({
4147
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4148
+ binds: switchBinds,
4149
+ currentProfileName: currentBoundProfile,
4150
+ action: "register",
4151
+ requestedName: register_name.trim(),
4152
+ });
4153
+ if (regGate.kind === "locked") {
4154
+ return { content: [{ type: "text", text: regGate.message }], isError: true };
4155
+ }
4156
+ }
3014
4157
  return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
3015
4158
  }
3016
4159
 
@@ -3018,19 +4161,11 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
3018
4161
  return { content: [{ type: "text", text: formatProfileList() }] };
3019
4162
  }
3020
4163
 
3021
- // Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
3022
- // when set, or via current profile when Cursor stdio started with --profile
3023
- // and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
3024
- // identity (including other Grok bots or Hermes/Spiral). No-op allowed.
3025
- // Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
3026
- // profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
3027
- const switchBinds = loadGrokBinds();
3028
- const bindApplies = currentGrokBindApplicability(switchBinds);
3029
4164
  const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
3030
4165
  conversationId: process.env.CURSOR_CONVERSATION_ID,
3031
4166
  binds: switchBinds,
3032
4167
  requestedProfileName: profile_name,
3033
- currentProfileName: profileNameFromPath(activeProfileFile),
4168
+ currentProfileName: currentBoundProfile,
3034
4169
  });
3035
4170
  if (switchGate.kind === "locked") {
3036
4171
  return { content: [{ type: "text", text: switchGate.message }], isError: true };
@@ -3108,6 +4243,19 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
3108
4243
 
3109
4244
  HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
3110
4245
  HANDLERS.set("disconnect_profile", async (args) => {
4246
+ const switchBinds = loadGrokBinds();
4247
+ const bindApplies = currentGrokBindApplicability(switchBinds);
4248
+ if (bindApplies.applies) {
4249
+ const discGate = gateGrokProfileMutation({
4250
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4251
+ binds: switchBinds,
4252
+ currentProfileName: profileNameFromPath(activeProfileFile),
4253
+ action: "disconnect",
4254
+ });
4255
+ if (discGate.kind === "locked") {
4256
+ return { content: [{ type: "text", text: discGate.message }], isError: true };
4257
+ }
4258
+ }
3111
4259
  const { keep_binding } = (args || {}) as { keep_binding?: boolean };
3112
4260
  const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
3113
4261
  return {
@@ -3444,7 +4592,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3444
4592
  }
3445
4593
 
3446
4594
  if (name === "list_skills") {
3447
- const { chat_id } = (args || {}) as { chat_id?: string };
4595
+ const { chat_id, active_only } = (args || {}) as { chat_id?: string; active_only?: boolean };
4596
+ const activeOnly = active_only !== false;
4597
+ const activeQuery = activeOnly ? "?active_only=1" : "";
3448
4598
  const out: any = {
3449
4599
  global_skills: Object.entries(GLOBAL_SKILLS).map(([skill_id, skill]) => ({
3450
4600
  skill_id,
@@ -3455,27 +4605,103 @@ const handleToolCall = async (request: any): Promise<any> => {
3455
4605
  };
3456
4606
  if (chat_id) {
3457
4607
  try {
3458
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs`, {
4608
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${activeQuery}`, {
3459
4609
  headers: { "Authorization": `Bearer ${TOKEN}` },
3460
4610
  });
3461
- if (r.ok) out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text())).filter(isSkillDoc).map(compactSkillDoc);
3462
- else out.channel_skills_error = `failed (${r.status})`;
4611
+ if (r.ok) {
4612
+ out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text()))
4613
+ .filter(isSkillDoc)
4614
+ .filter((d: any) => !activeOnly || !isArchivedSkillOrDoc(d))
4615
+ .map(compactSkillDoc);
4616
+ } else {
4617
+ out.channel_skills_error = `failed (${r.status})`;
4618
+ }
3463
4619
  } catch (e: any) {
3464
4620
  out.channel_skills_error = `network/parse error: ${String(e?.message || e).slice(0, 120)}`;
3465
4621
  }
3466
4622
  }
3467
- // Personal skills (per-owner, follow you across agents). sync_skill(name=…) / load via GET /api/skills/:name.
4623
+ // Personal skills (per-owner, follow you across agents). sync_skill(name=…) / load_skill(name=…).
3468
4624
  try {
3469
- const pr = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3470
- if (pr.ok) out.personal_skills = (JSON.parse(await pr.text()).skills) || [];
4625
+ const pr = await apiFetch(`${REST_URL}/api/skills${activeQuery}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4626
+ if (pr.ok) {
4627
+ const rawSkills = (JSON.parse(await pr.text()).skills) || [];
4628
+ out.personal_skills = rawSkills.filter((s: any) => !activeOnly || !isArchivedSkillOrDoc(s));
4629
+ } else {
4630
+ out.personal_skills_error = `failed (${pr.status})`;
4631
+ }
3471
4632
  } catch { /* best-effort */ }
3472
4633
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
3473
4634
  }
3474
4635
 
3475
4636
  if (name === "load_skill") {
3476
- const { skill_id, chat_id, doc_id } = (args || {}) as { skill_id?: string; chat_id?: string; doc_id?: string };
4637
+ const targetCheck = validateLoadSkillInput(args);
4638
+ if (!targetCheck.ok) {
4639
+ return { content: [{ type: "text", text: targetCheck.error }], isError: true };
4640
+ }
4641
+ const target = targetCheck.value;
4642
+ // PERSONAL skill: name (per-owner, shared across your agents).
4643
+ if (target.scope === "personal") {
4644
+ try {
4645
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}`, {
4646
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4647
+ });
4648
+ const text = await r.text();
4649
+ if (!r.ok) {
4650
+ return { content: [{ type: "text", text: `load_skill (personal) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
4651
+ }
4652
+ const doc = JSON.parse(text);
4653
+ const body = String(doc?.body_markdown ?? "");
4654
+ const version = doc?.version ?? "?";
4655
+ const title = doc?.title || target.name;
4656
+ const archived = doc?.archived === true || body === "";
4657
+ const parsed = parseSkillFrontmatter(body);
4658
+ const metadata = { ...(parsed.metadata || {}), ...(doc?.skill_meta || {}) };
4659
+ const metaLines = [
4660
+ metadata.name ? `name: ${metadata.name}` : null,
4661
+ metadata.description ? `description: ${metadata.description}` : null,
4662
+ metadata.trigger ? `trigger: ${metadata.trigger}` : null,
4663
+ (metadata.argument_hint ?? metadata.argumentHint) ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null,
4664
+ ].filter(Boolean).join("\n");
4665
+ let revisionsBlock = "";
4666
+ if (target.include_revisions) {
4667
+ const revR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}/revisions`, {
4668
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4669
+ });
4670
+ if (revR.ok) {
4671
+ const revJson = JSON.parse(await revR.text());
4672
+ revisionsBlock = `\n\nRevisions:\n${JSON.stringify(revJson?.revisions ?? [], null, 2)}`;
4673
+ } else {
4674
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4675
+ }
4676
+ }
4677
+ if (archived) {
4678
+ const hint = target.include_revisions
4679
+ ? `Restore by calling save_skill(name="${title}", doc_id="${target.name}", description=..., body=..., if_match_version=${version}).`
4680
+ : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
4681
+ return {
4682
+ content: [{
4683
+ type: "text",
4684
+ text: `[ARCHIVED PERSONAL SKILL "${target.name}" (v${version})]\n${metaLines ? `\nMetadata:\n${metaLines}\n` : ""}\n${hint}${revisionsBlock}`,
4685
+ }],
4686
+ };
4687
+ }
4688
+ return {
4689
+ content: [{
4690
+ type: "text",
4691
+ text: [
4692
+ `Personal skill loaded: "${target.name}" (v${version}).`,
4693
+ metaLines ? `\nMetadata:\n${metaLines}` : "",
4694
+ `\n# ${title}\n\n${parsed.body}${revisionsBlock}`,
4695
+ ].join("\n"),
4696
+ }],
4697
+ };
4698
+ } catch (e: any) {
4699
+ return { content: [{ type: "text", text: `load_skill (personal) network/parse error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4700
+ }
4701
+ }
3477
4702
  // CHANNEL skill: chat_id + doc_id (full frontmatter/metadata handling).
3478
- if (chat_id && doc_id) {
4703
+ if (target.scope === "channel") {
4704
+ const { chat_id, doc_id, include_revisions } = target;
3479
4705
  try {
3480
4706
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
3481
4707
  headers: { "Authorization": `Bearer ${TOKEN}` },
@@ -3485,11 +4711,13 @@ const handleToolCall = async (request: any): Promise<any> => {
3485
4711
  return { content: [{ type: "text", text: `load_skill (channel) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
3486
4712
  }
3487
4713
  const doc = JSON.parse(text);
3488
- const body = doc?.body_markdown ?? doc?.bodyMarkdown ?? "";
4714
+ const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
3489
4715
  const title = doc?.title || doc_id;
3490
4716
  const kind = doc?.kind || "unknown";
3491
4717
  const level = doc?.level ?? "?";
3492
- const parsed = parseSkillFrontmatter(String(body));
4718
+ const version = doc?.version ?? "?";
4719
+ const archived = isArchivedSkillOrDoc(doc);
4720
+ const parsed = parseSkillFrontmatter(body);
3493
4721
  const metadata = { ...(parsed.metadata || {}), ...(doc?.skill_meta || doc?.skillMeta || {}) };
3494
4722
  const metaLines = [
3495
4723
  metadata.name ? `name: ${metadata.name}` : null,
@@ -3497,16 +4725,40 @@ const handleToolCall = async (request: any): Promise<any> => {
3497
4725
  metadata.trigger ? `trigger: ${metadata.trigger}` : null,
3498
4726
  (metadata.argument_hint ?? metadata.argumentHint) ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null,
3499
4727
  ].filter(Boolean).join("\n");
4728
+ let revisionsBlock = "";
4729
+ if (include_revisions) {
4730
+ const revR = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
4731
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4732
+ });
4733
+ if (revR.ok) {
4734
+ const revJson = JSON.parse(await revR.text());
4735
+ const revs = Array.isArray(revJson) ? revJson : (revJson?.revisions ?? []);
4736
+ revisionsBlock = `\n\nRevisions:\n${JSON.stringify(revs, null, 2)}`;
4737
+ } else {
4738
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4739
+ }
4740
+ }
4741
+ if (archived) {
4742
+ const hint = include_revisions
4743
+ ? `Restore by calling save_skill(chat_id="${chat_id}", doc_id="${doc_id}", name=..., description=..., body=..., if_match_version=${version}).`
4744
+ : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
4745
+ return {
4746
+ content: [{
4747
+ type: "text",
4748
+ text: `[ARCHIVED CHANNEL SKILL ${chat_id}/${doc_id} (L${level}, v${version})]\n${metaLines ? `\nMetadata:\n${metaLines}\n` : ""}\n${hint}${revisionsBlock}`,
4749
+ }],
4750
+ };
4751
+ }
3500
4752
  if (!String(kind).toLowerCase().includes("skill") && !String(doc_id).toLowerCase().includes("skill")) {
3501
- return { content: [{ type: "text", text: `Loaded channel doc "${doc_id}" as requested, but it is not marked kind=skill.\n\n# ${title}\n\n${parsed.body}` }] };
4753
+ return { content: [{ type: "text", text: `Loaded channel doc "${doc_id}" as requested, but it is not marked kind=skill.\n\n# ${title}\n\n${parsed.body}${revisionsBlock}` }] };
3502
4754
  }
3503
4755
  return {
3504
4756
  content: [{
3505
4757
  type: "text",
3506
4758
  text: [
3507
- `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}).`,
4759
+ `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}, v${version}).`,
3508
4760
  metaLines ? `\nMetadata:\n${metaLines}` : "",
3509
- `\n# ${title}\n\n${parsed.body}`,
4761
+ `\n# ${title}\n\n${parsed.body}${revisionsBlock}`,
3510
4762
  ].join("\n"),
3511
4763
  }],
3512
4764
  };
@@ -3515,7 +4767,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3515
4767
  }
3516
4768
  }
3517
4769
  // GLOBAL skill: skill_id (default workspace-driven-eng).
3518
- const id = skill_id || DEFAULT_GLOBAL_SKILL_ID;
4770
+ const id = target.skill_id || DEFAULT_GLOBAL_SKILL_ID;
3519
4771
  const skill = GLOBAL_SKILLS[id];
3520
4772
  if (!skill) {
3521
4773
  return { content: [{ type: "text", text: `Unknown global skill: ${id}` }], isError: true };
@@ -3524,15 +4776,26 @@ const handleToolCall = async (request: any): Promise<any> => {
3524
4776
  }
3525
4777
 
3526
4778
  if (name === "save_memory") {
3527
- const a = (args || {}) as { name?: string; body?: string; description?: string };
4779
+ const a = (args || {}) as { name?: string; body?: string; description?: string; if_match_version?: number };
3528
4780
  if (!a.name || !a.body) {
3529
4781
  return { content: [{ type: "text", text: "save_memory needs name (slug) + body (markdown). Optional description (one-line index hook)." }], isError: true };
3530
4782
  }
4783
+ if (
4784
+ a.if_match_version !== undefined &&
4785
+ a.if_match_version !== null &&
4786
+ (!Number.isSafeInteger(a.if_match_version) || a.if_match_version < 0 || a.if_match_version > 1_000_000)
4787
+ ) {
4788
+ return { content: [{ type: "text", text: "save_memory if_match_version must be an integer in 0..1000000." }], isError: true };
4789
+ }
3531
4790
  try {
3532
4791
  const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}`, {
3533
4792
  method: "PUT",
3534
4793
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3535
- body: JSON.stringify({ body_markdown: a.body, description: a.description }),
4794
+ body: JSON.stringify({
4795
+ body_markdown: a.body,
4796
+ description: a.description,
4797
+ ...(a.if_match_version !== undefined && a.if_match_version !== null ? { if_match_version: a.if_match_version } : {}),
4798
+ }),
3536
4799
  });
3537
4800
  const text = await r.text();
3538
4801
  if (!r.ok) return { content: [{ type: "text", text: `save_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
@@ -3544,7 +4807,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3544
4807
  }
3545
4808
 
3546
4809
  if (name === "load_memory") {
3547
- const a = (args || {}) as { name?: string };
4810
+ const validated = validateLoadMemoryInput(args);
4811
+ if (!validated.ok) {
4812
+ return { content: [{ type: "text", text: validated.error }], isError: true };
4813
+ }
4814
+ const a = validated.value;
3548
4815
  try {
3549
4816
  const path = a.name ? `/api/memory/${encodeURIComponent(a.name)}` : `/api/memory`;
3550
4817
  const r = await apiFetch(`${REST_URL}${path}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -3552,7 +4819,21 @@ const handleToolCall = async (request: any): Promise<any> => {
3552
4819
  if (!r.ok) return { content: [{ type: "text", text: `load_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3553
4820
  const resp = JSON.parse(text);
3554
4821
  if (a.name) {
3555
- return { content: [{ type: "text", text: `# memory: ${resp.name} (v${resp.version})\n\n${resp.body_markdown || ""}` }] };
4822
+ let revisionsBlock = "";
4823
+ if (a.include_revisions) {
4824
+ const revR = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}/revisions`, {
4825
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4826
+ });
4827
+ if (revR.ok) {
4828
+ const revJson = JSON.parse(await revR.text());
4829
+ const revs = Array.isArray(revJson) ? revJson : (revJson?.revisions ?? []);
4830
+ const truncBadge = revJson?.revisions_truncated ? " (truncated)" : "";
4831
+ revisionsBlock = `\n\nRevisions${truncBadge} (restore via save_memory(name="${resp.name}", body=..., if_match_version=${resp.version})):\n${JSON.stringify(revs, null, 2)}`;
4832
+ } else {
4833
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4834
+ }
4835
+ }
4836
+ return { content: [{ type: "text", text: `# memory: ${resp.name} (v${resp.version})\n\n${resp.body_markdown || ""}${revisionsBlock}` }] };
3556
4837
  }
3557
4838
  const items = Array.isArray(resp.memories) ? resp.memories : [];
3558
4839
  if (items.length === 0) return { content: [{ type: "text", text: "No stored memory yet. Use save_memory to persist your context (e.g. an 'index' doc + finer docs)." }] };
@@ -3564,55 +4845,108 @@ const handleToolCall = async (request: any): Promise<any> => {
3564
4845
  }
3565
4846
 
3566
4847
  if (name === "save_skill") {
3567
- const a = (args || {}) as { chat_id?: string; name?: string; description?: string; body?: string; doc_id?: string; level?: number };
3568
- if (!a.name || !a.description) {
3569
- return { content: [{ type: "text", text: "save_skill needs name + description (body is the skill markdown). Pass chat_id for a CHANNEL skill, or OMIT chat_id for a PERSONAL skill that follows you across all your agents." }], isError: true };
3570
- }
3571
- // Skill markdown = YAML frontmatter (name, description) + body — the exact
3572
- // shape parseSkillFrontmatter + the skill validators expect.
3573
- const oneLine = (s: string) => String(s).replace(/\r?\n/g, " ").slice(0, 480);
3574
- const md = `---\nname: ${oneLine(a.name)}\ndescription: ${oneLine(a.description)}\n---\n\n${a.body || ""}`;
4848
+ const validated = validateSaveSkillInput(args);
4849
+ if (!validated.ok) {
4850
+ return { content: [{ type: "text", text: validated.error }], isError: true };
4851
+ }
4852
+ const v = validated.value;
3575
4853
  // PERSONAL skill (no chat_id): per-owner store, shared across YOUR agents.
3576
- if (!a.chat_id) {
3577
- const pslug = String(a.doc_id || a.name).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "").slice(0, 64) || "skill";
4854
+ if (v.scope === "personal") {
4855
+ if (v.mode === "archive") {
4856
+ try {
4857
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
4858
+ method: "DELETE",
4859
+ headers: {
4860
+ "Authorization": `Bearer ${TOKEN}`,
4861
+ "If-Match": String(v.if_match_version),
4862
+ },
4863
+ });
4864
+ const text = await r.text();
4865
+ if (!r.ok) return { content: [{ type: "text", text: `save_skill (personal archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4866
+ const resp = text.trim() ? JSON.parse(text) : {};
4867
+ const nextVer = resp?.version ?? v.if_match_version + 1;
4868
+ return {
4869
+ content: [{
4870
+ type: "text",
4871
+ text: `Archived PERSONAL skill "${v.slug}" (v${nextVer}) — revision history preserved & active quota freed. Inspect history via load_skill(name="${v.slug}", include_revisions=true).`,
4872
+ }],
4873
+ };
4874
+ } catch (e: any) {
4875
+ return { content: [{ type: "text", text: `save_skill (personal archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4876
+ }
4877
+ }
3578
4878
  try {
3579
- const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pslug)}`, {
4879
+ const headers: Record<string, string> = {
4880
+ "Authorization": `Bearer ${TOKEN}`,
4881
+ "Content-Type": "application/json",
4882
+ ...(v.if_match_version !== undefined ? { "If-Match": String(v.if_match_version) } : {}),
4883
+ };
4884
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
3580
4885
  method: "PUT",
3581
- headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3582
- body: JSON.stringify({ body_markdown: md }),
4886
+ headers,
4887
+ body: JSON.stringify({
4888
+ body_markdown: v.body_markdown,
4889
+ ...(v.if_match_version !== undefined ? { if_match_version: v.if_match_version } : {}),
4890
+ }),
3583
4891
  });
3584
4892
  const text = await r.text();
3585
4893
  if (!r.ok) return { content: [{ type: "text", text: `save_skill (personal) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3586
4894
  const resp = JSON.parse(text);
3587
- return { content: [{ type: "text", text: `Saved PERSONAL skill "${a.name}" as "${pslug}" (v${resp.version}) — shared across all your agents. Pull/refresh: sync_skill(name="${pslug}"); list: list_skills.` }] };
4895
+ return { content: [{ type: "text", text: `Saved PERSONAL skill "${v.name}" as "${v.slug}" (v${resp.version}) — shared across all your agents. Load: load_skill(name="${v.slug}"); sync: sync_skill(name="${v.slug}"); list: list_skills.` }] };
3588
4896
  } catch (e: any) {
3589
4897
  return { content: [{ type: "text", text: `save_skill (personal) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3590
4898
  }
3591
4899
  }
3592
- // CHANNEL skill (chat_id given). Stable doc id: caller-supplied, else slug of name.
3593
- const slug = String(a.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill";
3594
- const docId = (a.doc_id && String(a.doc_id).trim()) || `skill-${slug}`;
3595
- const level = (typeof a.level === "number" && a.level >= 1 && a.level <= 4) ? a.level : 3; // 3 = member-writable
4900
+
4901
+ // CHANNEL skill (chat_id given).
4902
+ if (v.mode === "archive") {
4903
+ try {
4904
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
4905
+ method: "DELETE",
4906
+ headers: {
4907
+ "Authorization": `Bearer ${TOKEN}`,
4908
+ "If-Match": String(v.if_match_version),
4909
+ },
4910
+ });
4911
+ const text = await r.text();
4912
+ if (!r.ok) {
4913
+ return { content: [{ type: "text", text: `save_skill (channel archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4914
+ }
4915
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
4916
+ const parsed = text.trim() ? JSON.parse(text) : null;
4917
+ const nextVer = parsed?.version ?? (Number.isSafeInteger(etagVer) && etagVer >= 1 ? etagVer : v.if_match_version + 1);
4918
+ return {
4919
+ content: [{
4920
+ type: "text",
4921
+ text: `Archived CHANNEL skill ${v.chat_id}/${v.doc_id} (v${nextVer}) — revision history preserved & active quota freed. Inspect history via load_skill(chat_id="${v.chat_id}", doc_id="${v.doc_id}", include_revisions=true).`,
4922
+ }],
4923
+ };
4924
+ } catch (e: any) {
4925
+ return { content: [{ type: "text", text: `save_skill (channel archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4926
+ }
4927
+ }
3596
4928
  try {
3597
- // If-Match: fetch current version (0 = create). The doc store uses
3598
- // optimistic concurrency; "0" creates, current version updates.
3599
- let ifMatch = "0";
3600
- const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3601
- if (cur.ok) {
3602
- const curDoc = await cur.json().catch(() => null) as any;
3603
- if (curDoc && curDoc.version != null) ifMatch = String(curDoc.version);
4929
+ let ifMatch = v.if_match_version !== undefined ? String(v.if_match_version) : "0";
4930
+ if (v.if_match_version === undefined) {
4931
+ const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
4932
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4933
+ });
4934
+ if (cur.ok) {
4935
+ const curDoc = await cur.json().catch(() => null) as any;
4936
+ if (curDoc && curDoc.version != null) ifMatch = String(curDoc.version);
4937
+ }
3604
4938
  }
3605
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, {
4939
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
3606
4940
  method: "PUT",
3607
4941
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json", "If-Match": ifMatch },
3608
- body: JSON.stringify({ kind: "channel_skill", level, title: a.name, body_markdown: md }),
4942
+ body: JSON.stringify({ kind: "channel_skill", level: v.level, title: v.name, body_markdown: v.body_markdown }),
3609
4943
  });
3610
4944
  const text = await r.text();
3611
4945
  if (!r.ok) {
3612
4946
  return { content: [{ type: "text", text: `save_skill failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3613
4947
  }
3614
4948
  const verb = ifMatch === "0" ? "Saved" : "Updated";
3615
- return { content: [{ type: "text", text: `${verb} skill "${a.name}" → ${a.chat_id}/${docId} (L${level}). Others load it with: load_skill(chat_id="${a.chat_id}", doc_id="${docId}") — discoverable via list_skills(chat_id="${a.chat_id}").` }] };
4949
+ return { content: [{ type: "text", text: `${verb} skill "${v.name}" → ${v.chat_id}/${v.doc_id} (L${v.level}). Others load it with: load_skill(chat_id="${v.chat_id}", doc_id="${v.doc_id}") — discoverable via list_skills(chat_id="${v.chat_id}").` }] };
3616
4950
  } catch (e: any) {
3617
4951
  return { content: [{ type: "text", text: `save_skill network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3618
4952
  }
@@ -3620,34 +4954,58 @@ const handleToolCall = async (request: any): Promise<any> => {
3620
4954
 
3621
4955
  if (name === "sync_skill") {
3622
4956
  const a = (args || {}) as { chat_id?: string; doc_id?: string; name?: string; dir?: string };
3623
- const home = process.env.HOME || process.env.USERPROFILE || ".";
3624
- const cacheDir = (a.dir && String(a.dir).trim()) || `${home}/.agentchat/skills`;
4957
+ const home = process.env.HOME || process.env.USERPROFILE || homedir() || ".";
4958
+ const cacheDir = (a.dir && String(a.dir).trim()) || join(home, ".agentchat", "skills");
3625
4959
  const safe = (s: string) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
3626
4960
  // PERSONAL skill: sync_skill({name}) — version from GET /api/skills (cheap,
3627
4961
  // no body), body from GET /api/skills/:name only when missing/stale.
3628
4962
  if (a.name && !a.chat_id) {
3629
- const pBase = `${cacheDir}/personal__${safe(a.name)}`;
4963
+ const slugCheck = validatePersonalSkillSlugInput(a.name, "sync_skill");
4964
+ if (!slugCheck.ok) {
4965
+ return { content: [{ type: "text", text: slugCheck.error }], isError: true };
4966
+ }
4967
+ const pSlug = slugCheck.value;
4968
+ const pBase = join(cacheDir, `personal__${safe(pSlug)}`);
3630
4969
  const pMd = `${pBase}.md`; const pMeta = `${pBase}.json`;
3631
4970
  try {
3632
4971
  const listR = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3633
4972
  if (!listR.ok) return { content: [{ type: "text", text: `sync_skill (personal): list failed (${listR.status})` }], isError: true };
3634
- const meta = (JSON.parse(await listR.text()).skills || []).find((s: any) => s.name === a.name);
3635
- if (!meta) return { content: [{ type: "text", text: `sync_skill: personal skill "${a.name}" not found (save it with save_skill — no chat_id).` }], isError: true };
4973
+ const meta = (JSON.parse(await listR.text()).skills || []).find((s: any) => s.name === pSlug);
4974
+ if (!meta) return { content: [{ type: "text", text: `sync_skill: personal skill "${pSlug}" not found (save it with save_skill — no chat_id).` }], isError: true };
4975
+ if (meta.archived === true) {
4976
+ return {
4977
+ content: [{
4978
+ type: "text",
4979
+ text: `sync_skill: personal skill "${pSlug}" is soft-archived (v${meta.version ?? "?"}); refusing to overwrite local file with an empty tombstone. Inspect revisions via load_skill(name="${pSlug}", include_revisions=true).`,
4980
+ }],
4981
+ isError: true,
4982
+ };
4983
+ }
3636
4984
  const currentVersion = Number(meta.version ?? 0);
3637
4985
  let cachedVersion: number | null = null;
3638
4986
  try { cachedVersion = Number(JSON.parse(readFileSync(pMeta, "utf8")).version); } catch {}
3639
4987
  if (cachedVersion !== null && cachedVersion === currentVersion) {
3640
- return { content: [{ type: "text", text: `up-to-date: personal skill "${a.name}" v${currentVersion} already at ${pMd} — no download. Read that file to run it.` }] };
4988
+ return { content: [{ type: "text", text: `up-to-date: personal skill "${pSlug}" v${currentVersion} already at ${pMd} — no download. Read that file to run it.` }] };
3641
4989
  }
3642
- const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(a.name)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4990
+ const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pSlug)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3643
4991
  if (!bodyR.ok) return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
3644
4992
  const doc = JSON.parse(await bodyR.text());
4993
+ const body = String(doc?.body_markdown ?? "");
4994
+ if (doc?.archived === true || !body.trim()) {
4995
+ return {
4996
+ content: [{
4997
+ type: "text",
4998
+ text: `sync_skill: personal skill "${pSlug}" is archived; refusing to overwrite local file.`,
4999
+ }],
5000
+ isError: true,
5001
+ };
5002
+ }
3645
5003
  // node:fs (not Bun.write) — runs on plain Node too. Bun.write auto-creates
3646
5004
  // parent dirs; writeFileSync does not, so mkdir the cache dir first.
3647
5005
  mkdirSync(dirname(pMd), { recursive: true });
3648
- writeFileSync(pMd, String(doc?.body_markdown ?? ""));
3649
- writeFileSync(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
3650
- return { content: [{ type: "text", text: `synced personal skill "${a.name}" v${currentVersion} → ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
5006
+ writeFileSync(pMd, body);
5007
+ writeFileSync(pMeta, JSON.stringify({ version: currentVersion, name: pSlug, syncedAt: new Date().toISOString() }));
5008
+ return { content: [{ type: "text", text: `synced personal skill "${pSlug}" v${currentVersion} → ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
3651
5009
  } catch (e: any) {
3652
5010
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
3653
5011
  }
@@ -3667,6 +5025,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3667
5025
  const docs = extractChannelDocsPayload(JSON.parse(await listR.text()));
3668
5026
  const meta = docs.find((d: any) => (d?.id ?? d?.doc_id) === a.doc_id);
3669
5027
  if (!meta) return { content: [{ type: "text", text: `sync_skill: skill "${a.doc_id}" not found in channel ${a.chat_id}` }], isError: true };
5028
+ if (isArchivedSkillOrDoc(meta)) {
5029
+ return {
5030
+ content: [{
5031
+ type: "text",
5032
+ text: `sync_skill: channel skill "${a.doc_id}" is soft-archived (v${meta.version ?? "?"}); refusing to overwrite local file with an empty tombstone. Inspect revisions via load_skill(chat_id="${a.chat_id}", doc_id="${a.doc_id}", include_revisions=true).`,
5033
+ }],
5034
+ isError: true,
5035
+ };
5036
+ }
3670
5037
  const currentVersion = Number(meta.version ?? 0);
3671
5038
  // 2. Local cache check — skip the body fetch if we already have this version.
3672
5039
  let cachedVersion: number | null = null;
@@ -3679,6 +5046,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3679
5046
  if (!docR.ok) return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
3680
5047
  const doc = JSON.parse(await docR.text());
3681
5048
  const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
5049
+ if (isArchivedSkillOrDoc(doc)) {
5050
+ return {
5051
+ content: [{
5052
+ type: "text",
5053
+ text: `sync_skill: channel skill "${a.doc_id}" is archived; refusing to overwrite local file.`,
5054
+ }],
5055
+ isError: true,
5056
+ };
5057
+ }
3682
5058
  // 4. Write the local mirror + version sidecar (node:fs, not Bun.write, for
3683
5059
  // Node compat; mkdir the cache dir first since writeFileSync won't auto-create).
3684
5060
  mkdirSync(dirname(mdPath), { recursive: true });
@@ -4016,40 +5392,67 @@ const handleToolCall = async (request: any): Promise<any> => {
4016
5392
  }
4017
5393
  }
4018
5394
 
4019
- if (name === "vote") {
4020
- const { proposal_id, decision, reason } = args as any;
4021
- if (typeof proposal_id !== "string" || typeof decision !== "string") {
4022
- return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }] };
4023
- }
4024
- if (ws && ws.readyState === WebSocket.OPEN) {
4025
- ws.send(JSON.stringify({
4026
- type: "vote", proposal_id, voter_id: AGENT_ID,
4027
- voter_type: "agent", decision, reason,
4028
- }));
4029
- return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
4030
- }
4031
- return { content: [{ type: "text", text: "Not connected" }] };
4032
- }
4033
-
4034
- if (name === "propose") {
4035
- const { chat_id, title, content, code_diff, consensus_rule } = args as any;
4036
- if (ws && ws.readyState === WebSocket.OPEN) {
4037
- const proposalId = crypto.randomUUID();
4038
- ws.send(JSON.stringify({
4039
- type: "proposal", id: proposalId, channel_id: chat_id,
4040
- sender_id: AGENT_ID, title, content, code_diff,
4041
- consensus_rule: consensus_rule || "majority",
4042
- expires_at: new Date(Date.now() + 86400_000).toISOString(),
4043
- timestamp: new Date().toISOString(),
4044
- }));
4045
- return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject — verify via next inbound event` }] };
4046
- }
4047
- return { content: [{ type: "text", text: "Not connected" }] };
4048
- }
4049
-
4050
5395
  async function fetchMcpChannelContext(chatId: string): Promise<{
4051
5396
  channel?: { id?: string; name?: string; type?: string; topic?: string; member_count?: number };
4052
5397
  agents?: Array<{ id: string; name?: string; capabilities?: string[]; online?: boolean; is_self?: boolean }>;
5398
+ docs_summary?: Array<{
5399
+ id?: string;
5400
+ doc_id?: string;
5401
+ title?: string;
5402
+ kind?: string;
5403
+ level?: number;
5404
+ version?: number;
5405
+ archived?: boolean;
5406
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5407
+ }>;
5408
+ skills_summary?: {
5409
+ channel_skills?: Array<{
5410
+ doc_id?: string;
5411
+ version?: number;
5412
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5413
+ }>;
5414
+ personal_skills?: Array<{
5415
+ name?: string;
5416
+ version?: number;
5417
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5418
+ }>;
5419
+ };
5420
+ okr_summary?: {
5421
+ active_objective_count: number;
5422
+ total_task_count: number;
5423
+ ready_for_me_count: number;
5424
+ doing_for_me_count?: number;
5425
+ blocked_for_me_count?: number;
5426
+ ready_task_count?: number;
5427
+ doing_task_count?: number;
5428
+ blocked_task_count?: number;
5429
+ };
5430
+ loop_summary?: {
5431
+ active_loop_count?: number;
5432
+ my_active_loop_count?: number;
5433
+ okr_wake_objective_ids?: string[];
5434
+ okr_watch_objective_ids?: string[];
5435
+ unarmed_objective_ids?: string[];
5436
+ };
5437
+ wake_health_summary?: {
5438
+ observation_only?: boolean;
5439
+ counts?: {
5440
+ total_cloud_agents: number;
5441
+ ok: number;
5442
+ auth_required: number;
5443
+ timeout: number;
5444
+ error: number;
5445
+ unobserved: number;
5446
+ };
5447
+ attention_agents?: Array<{
5448
+ agent_id: string;
5449
+ name?: string;
5450
+ runtime: string;
5451
+ cloud_status: string;
5452
+ last_wake_status?: string;
5453
+ last_wake_at?: string;
5454
+ }>;
5455
+ };
4053
5456
  } | null> {
4054
5457
  if (!chatId || !TOKEN) return null;
4055
5458
  try {
@@ -4068,7 +5471,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4068
5471
  method: "tools/call",
4069
5472
  params: {
4070
5473
  name: "agentschat_get_channel_context",
4071
- arguments: { channel_id: chatId },
5474
+ arguments: { channel_id: chatId, include_briefing: true },
4072
5475
  },
4073
5476
  }),
4074
5477
  },
@@ -4099,10 +5502,13 @@ const handleToolCall = async (request: any): Promise<any> => {
4099
5502
  return r.ok ? await r.json() as any : null;
4100
5503
  } catch { return null; }
4101
5504
  };
4102
- const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5505
+ const [membersData, docsData, okrData, loopsData, personalSkillsData, wakeHealthData, mcpCtx] = await Promise.all([
4103
5506
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
4104
- get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5507
+ get(`/api/channels/${encodeURIComponent(chatId)}/docs?active_only=1`),
4105
5508
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
5509
+ get(`/api/loops?channel_id=${encodeURIComponent(chatId)}`),
5510
+ get(`/api/skills?active_only=1`),
5511
+ get(`/api/channels/${encodeURIComponent(chatId)}/wake-health`),
4106
5512
  fetchMcpChannelContext(chatId),
4107
5513
  ]);
4108
5514
  // membersData === null means the /members read FAILED (most often a 403 because
@@ -4157,13 +5563,272 @@ const handleToolCall = async (request: any): Promise<any> => {
4157
5563
  : {}),
4158
5564
  is_self: String(m.agent_id) === AGENT_ID,
4159
5565
  }));
4160
- const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
4161
- const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
4162
- const docs = allDocs.filter((d: any) => !isSkillDoc(d)).slice(0, 10).map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
4163
- const objectives = (okrData?.objectives || []).filter((o: any) => !o.archived).map((o: any) => {
4164
- const open = (okrData?.tasks || []).filter((t: any) => t.objective_id === o.id && t.status !== "done").length;
4165
- return { id: o.id, title: o.title, open_tasks: open };
5566
+ const hasRestDocsPayload = Boolean(
5567
+ docsData && (Array.isArray(docsData) || Array.isArray(docsData.docs) || Array.isArray(docsData.channel_docs)),
5568
+ );
5569
+ const docsReadable =
5570
+ hasRestDocsPayload ||
5571
+ Array.isArray(mcpCtx?.docs_summary) ||
5572
+ Array.isArray(mcpCtx?.skills_summary?.channel_skills);
5573
+ const allDocs = hasRestDocsPayload
5574
+ ? extractChannelDocsPayload(docsData)
5575
+ : Array.isArray(mcpCtx?.docs_summary)
5576
+ ? mcpCtx!.docs_summary.map((d: any) => ({ ...d, id: d?.id ?? d?.doc_id }))
5577
+ : [];
5578
+ const archivedDocIds = new Set<string>(
5579
+ allDocs
5580
+ .filter((d: any) => isArchivedSkillOrDoc(d) && (d?.id || d?.doc_id))
5581
+ .map((d: any) => String(d.id ?? d.doc_id)),
5582
+ );
5583
+ const activeDocs = allDocs.filter((d: any) => !isArchivedSkillOrDoc(d));
5584
+ const activeDocById = new Map<string, any>();
5585
+ for (const d of activeDocs) {
5586
+ const id = d?.id ?? d?.doc_id;
5587
+ if (id) activeDocById.set(String(id), d);
5588
+ }
5589
+ const mcpChannelSkills = Array.isArray(mcpCtx?.skills_summary?.channel_skills)
5590
+ ? mcpCtx!.skills_summary!.channel_skills!.filter(
5591
+ (cs: any) => cs?.doc_id && !archivedDocIds.has(String(cs.doc_id)) && !isArchivedSkillOrDoc(cs),
5592
+ )
5593
+ : [];
5594
+ const mcpSkillByDocId = new Map<string, any>();
5595
+ for (const cs of mcpChannelSkills) {
5596
+ mcpSkillByDocId.set(String(cs.doc_id), cs);
5597
+ }
5598
+ const formatBriefChannelSkill = (d: any) => {
5599
+ const docId = String(d?.id ?? d?.doc_id ?? "");
5600
+ const fallback = mcpSkillByDocId.get(docId);
5601
+ const meta = d?.skill_meta || d?.skillMeta || fallback?.skill_meta || {};
5602
+ const version =
5603
+ typeof d?.version === "number"
5604
+ ? d.version
5605
+ : typeof fallback?.version === "number"
5606
+ ? fallback.version
5607
+ : undefined;
5608
+ const argHint = meta.argument_hint ?? meta.argumentHint;
5609
+ return {
5610
+ doc_id: docId,
5611
+ ...(d?.title !== undefined ? { title: d.title } : meta.name ? { title: String(meta.name) } : {}),
5612
+ ...(typeof version === "number" ? { version } : {}),
5613
+ ...(meta.name ? { name: String(meta.name) } : {}),
5614
+ ...(meta.description ? { description: String(meta.description) } : {}),
5615
+ ...(meta.trigger ? { trigger: String(meta.trigger) } : {}),
5616
+ ...(argHint ? { argument_hint: String(argHint) } : {}),
5617
+ };
5618
+ };
5619
+ const seenSkillDocIds = new Set<string>();
5620
+ const skills = activeDocs
5621
+ .filter(isSkillDoc)
5622
+ .map((d: any) => {
5623
+ const entry = formatBriefChannelSkill(d);
5624
+ seenSkillDocIds.add(entry.doc_id);
5625
+ return entry;
5626
+ });
5627
+ if (!hasRestDocsPayload) {
5628
+ for (const cs of mcpChannelSkills) {
5629
+ const docId = String(cs.doc_id);
5630
+ if (seenSkillDocIds.has(docId)) continue;
5631
+ seenSkillDocIds.add(docId);
5632
+ skills.push(formatBriefChannelSkill({ doc_id: docId, ...cs }));
5633
+ }
5634
+ }
5635
+ const docs = activeDocs
5636
+ .filter((d: any) => !isSkillDoc(d))
5637
+ .slice(0, 10)
5638
+ .map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
5639
+ const rawPersonalSkills: any[] = Array.isArray(personalSkillsData?.skills)
5640
+ ? personalSkillsData.skills
5641
+ : Array.isArray(mcpCtx?.skills_summary?.personal_skills)
5642
+ ? mcpCtx!.skills_summary!.personal_skills!
5643
+ : [];
5644
+ const personalSkills = rawPersonalSkills
5645
+ .filter((s: any) => s?.name && !isArchivedSkillOrDoc(s))
5646
+ .map((s: any) => {
5647
+ const meta = s?.skill_meta || s?.skillMeta || {};
5648
+ const desc = s?.description ?? meta.description;
5649
+ const trig = s?.trigger ?? meta.trigger;
5650
+ const argHint = s?.argument_hint ?? s?.argumentHint ?? meta.argument_hint ?? meta.argumentHint;
5651
+ return {
5652
+ name: String(s.name),
5653
+ ...(desc ? { description: String(desc) } : {}),
5654
+ ...(trig ? { trigger: String(trig) } : {}),
5655
+ ...(argHint ? { argument_hint: String(argHint) } : {}),
5656
+ ...(typeof s?.version === "number" ? { version: s.version } : {}),
5657
+ };
5658
+ });
5659
+ const okrNotConfigured = typeof okrData?.note === "string" && okrData.note.toLowerCase().includes("not configured");
5660
+ const hasRestOkrSnapshot = Boolean(
5661
+ okrData && !okrNotConfigured && (Array.isArray(okrData.objectives) || Array.isArray(okrData.tasks)),
5662
+ );
5663
+ const hasMcpOkrSummary = Boolean(
5664
+ mcpCtx?.okr_summary &&
5665
+ typeof mcpCtx.okr_summary === "object" &&
5666
+ typeof mcpCtx.okr_summary.active_objective_count === "number",
5667
+ );
5668
+ const okrReadable = hasRestOkrSnapshot || hasMcpOkrSummary;
5669
+ const activeRawObjectives = (okrData?.objectives || []).filter(
5670
+ (o: any) => !o.archived && o.id && String(o.status || "active").toLowerCase() === "active",
5671
+ );
5672
+ let okrSummary:
5673
+ | {
5674
+ active_objective_count: number;
5675
+ total_task_count: number;
5676
+ ready_for_me_count: number;
5677
+ doing_for_me_count?: number;
5678
+ blocked_for_me_count?: number;
5679
+ ready_task_count?: number;
5680
+ doing_task_count?: number;
5681
+ blocked_task_count?: number;
5682
+ }
5683
+ | null = null;
5684
+ if (hasMcpOkrSummary && typeof mcpCtx!.okr_summary!.doing_for_me_count === "number") {
5685
+ const s = mcpCtx!.okr_summary!;
5686
+ okrSummary = {
5687
+ active_objective_count: s.active_objective_count,
5688
+ total_task_count: s.total_task_count,
5689
+ ready_for_me_count: s.ready_for_me_count,
5690
+ doing_for_me_count: s.doing_for_me_count,
5691
+ ...(typeof s.blocked_for_me_count === "number" ? { blocked_for_me_count: s.blocked_for_me_count } : {}),
5692
+ ...(typeof s.ready_task_count === "number" ? { ready_task_count: s.ready_task_count } : {}),
5693
+ ...(typeof s.doing_task_count === "number" ? { doing_task_count: s.doing_task_count } : {}),
5694
+ ...(typeof s.blocked_task_count === "number" ? { blocked_task_count: s.blocked_task_count } : {}),
5695
+ };
5696
+ } else if (hasRestOkrSnapshot) {
5697
+ const archivedObjIds = new Set<string>(
5698
+ (okrData?.objectives || []).filter((o: any) => o?.archived && o?.id).map((o: any) => String(o.id)),
5699
+ );
5700
+ const snapshotTasks = (Array.isArray(okrData?.tasks) ? okrData.tasks : []).filter(
5701
+ (t: any) => t && typeof t.id === "string" && !archivedObjIds.has(String(t.objective_id || "")),
5702
+ );
5703
+ const taskStatusById = new Map<string, string>();
5704
+ for (const t of snapshotTasks) taskStatusById.set(String(t.id), String(t.status || "todo"));
5705
+ const isTaskReady = (t: any): boolean => {
5706
+ if (String(t.status || "todo") !== "todo") return false;
5707
+ if (Array.isArray(t.unresolved_depends_on)) return t.unresolved_depends_on.length === 0;
5708
+ if (typeof t.ready === "boolean") return t.ready;
5709
+ const deps = Array.isArray(t.depends_on)
5710
+ ? t.depends_on.filter((d: unknown): d is string => typeof d === "string" && d.length > 0)
5711
+ : [];
5712
+ return deps.every((depId: string) => taskStatusById.get(depId) === "done");
5713
+ };
5714
+ const isMine = (t: any): boolean => Boolean(AGENT_ID && t?.assignee === AGENT_ID);
5715
+ okrSummary = {
5716
+ active_objective_count: activeRawObjectives.length,
5717
+ total_task_count: snapshotTasks.length,
5718
+ ready_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && isTaskReady(t)).length,
5719
+ doing_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && t.status === "doing").length,
5720
+ blocked_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && t.status === "blocked").length,
5721
+ ready_task_count: snapshotTasks.filter((t: any) => isTaskReady(t)).length,
5722
+ doing_task_count: snapshotTasks.filter((t: any) => t.status === "doing").length,
5723
+ blocked_task_count: snapshotTasks.filter((t: any) => t.status === "blocked").length,
5724
+ };
5725
+ } else if (hasMcpOkrSummary) {
5726
+ const s = mcpCtx!.okr_summary!;
5727
+ okrSummary = {
5728
+ active_objective_count: s.active_objective_count,
5729
+ total_task_count: s.total_task_count,
5730
+ ready_for_me_count: s.ready_for_me_count,
5731
+ };
5732
+ }
5733
+ const visibleObjectiveIdSet = new Set<string>(activeRawObjectives.map((o: any) => String(o.id)));
5734
+ const snapshotLoopSummary =
5735
+ okrData?.loop_summary && typeof okrData.loop_summary === "object" ? okrData.loop_summary : null;
5736
+ const hasSnapshotLoopSummary = Boolean(
5737
+ snapshotLoopSummary &&
5738
+ (Array.isArray(snapshotLoopSummary.okr_wake_objective_ids) ||
5739
+ Array.isArray(snapshotLoopSummary.okr_watch_objective_ids) ||
5740
+ Array.isArray(snapshotLoopSummary.unarmed_objective_ids)),
5741
+ );
5742
+ const hasMcpLoopSummary = Boolean(mcpCtx?.loop_summary && typeof mcpCtx.loop_summary === "object");
5743
+ const hasRestLoopsArray = Array.isArray(loopsData?.loops);
5744
+ const loopCoverageKnown = hasMcpLoopSummary || hasSnapshotLoopSummary || hasRestLoopsArray;
5745
+ const wakeSet = new Set<string>();
5746
+ const watchSet = new Set<string>();
5747
+ for (const summarySource of [mcpCtx?.loop_summary, snapshotLoopSummary]) {
5748
+ if (!summarySource) continue;
5749
+ for (const rawId of summarySource.okr_wake_objective_ids || []) {
5750
+ const id = String(rawId || "");
5751
+ if (visibleObjectiveIdSet.has(id)) wakeSet.add(id);
5752
+ }
5753
+ for (const rawId of summarySource.okr_watch_objective_ids || []) {
5754
+ const id = String(rawId || "");
5755
+ if (visibleObjectiveIdSet.has(id)) watchSet.add(id);
5756
+ }
5757
+ }
5758
+ const activeRestLoops = hasRestLoopsArray
5759
+ ? (loopsData.loops as any[]).filter((l: any) => l && l.paused !== true && l.status !== "paused" && l.paused_at == null)
5760
+ : [];
5761
+ for (const l of activeRestLoops) {
5762
+ const objId = typeof l?.objective_id === "string" ? l.objective_id : "";
5763
+ if (!objId || !visibleObjectiveIdSet.has(objId)) continue;
5764
+ if (l.mode === "okr_wake") wakeSet.add(objId);
5765
+ else if (l.mode === "okr_watch") watchSet.add(objId);
5766
+ }
5767
+ const objectives = activeRawObjectives.map((o: any) => {
5768
+ const id = String(o.id);
5769
+ const open = (okrData?.tasks || []).filter((t: any) => t.objective_id === id && t.status !== "done").length;
5770
+ return {
5771
+ id,
5772
+ title: o.title,
5773
+ open_tasks: open,
5774
+ ...(loopCoverageKnown
5775
+ ? {
5776
+ okr_wake_armed: wakeSet.has(id),
5777
+ okr_watch_armed: watchSet.has(id),
5778
+ }
5779
+ : {}),
5780
+ };
4166
5781
  });
5782
+ const loopSummary = loopCoverageKnown
5783
+ ? {
5784
+ active_loop_count:
5785
+ typeof mcpCtx?.loop_summary?.active_loop_count === "number"
5786
+ ? mcpCtx.loop_summary.active_loop_count
5787
+ : typeof snapshotLoopSummary?.active_loop_count === "number"
5788
+ ? snapshotLoopSummary.active_loop_count
5789
+ : activeRestLoops.length,
5790
+ ...(typeof mcpCtx?.loop_summary?.my_active_loop_count === "number"
5791
+ ? { my_active_loop_count: mcpCtx.loop_summary.my_active_loop_count }
5792
+ : typeof snapshotLoopSummary?.my_active_loop_count === "number"
5793
+ ? { my_active_loop_count: snapshotLoopSummary.my_active_loop_count }
5794
+ : AGENT_ID && hasRestLoopsArray
5795
+ ? { my_active_loop_count: activeRestLoops.filter((l: any) => l?.agent_id === AGENT_ID).length }
5796
+ : {}),
5797
+ okr_wake_objective_ids: [...wakeSet],
5798
+ okr_watch_objective_ids: [...watchSet],
5799
+ unarmed_objective_ids: activeRawObjectives
5800
+ .map((o: any) => String(o.id))
5801
+ .filter((id: string) => !wakeSet.has(id)),
5802
+ }
5803
+ : null;
5804
+ const activeTaskLinkedDocs: Array<{
5805
+ task_id: string;
5806
+ doc_id: string;
5807
+ title?: string;
5808
+ is_skill?: boolean;
5809
+ }> = [];
5810
+ const seenTaskDocPair = new Set<string>();
5811
+ for (const t of Array.isArray(okrData?.tasks) ? okrData.tasks : []) {
5812
+ if (!t?.id || t.archived || String(t.status || "todo") === "done") continue;
5813
+ if (t.objective_id && !visibleObjectiveIdSet.has(String(t.objective_id))) continue;
5814
+ const refs = Array.isArray(t.linked_channel_docs) ? t.linked_channel_docs : [];
5815
+ for (const ref of refs) {
5816
+ const docId = typeof ref?.doc_id === "string" ? ref.doc_id.trim() : "";
5817
+ const refCh = typeof ref?.channel_id === "string" ? ref.channel_id.trim() : "";
5818
+ if (!docId || (refCh && refCh !== chatId)) continue;
5819
+ if (archivedDocIds.has(docId)) continue;
5820
+ const pairKey = `${t.id}:${docId}`;
5821
+ if (seenTaskDocPair.has(pairKey)) continue;
5822
+ seenTaskDocPair.add(pairKey);
5823
+ const matchedDoc = activeDocById.get(docId);
5824
+ activeTaskLinkedDocs.push({
5825
+ task_id: String(t.id),
5826
+ doc_id: docId,
5827
+ ...(matchedDoc?.title ? { title: String(matchedDoc.title) } : {}),
5828
+ ...(matchedDoc && isSkillDoc(matchedDoc) ? { is_skill: true } : {}),
5829
+ });
5830
+ }
5831
+ }
4167
5832
  // Loadable extended tool groups — surfaced here so entering a room hands
4168
5833
  // you the full capability menu (not just skills). Without this an agent has
4169
5834
  // to already KNOW to call list_tool_groups; now "what can I do here / how to
@@ -4175,6 +5840,65 @@ const handleToolCall = async (request: any): Promise<any> => {
4175
5840
  tool_count: g.tools.length,
4176
5841
  loaded: loadedToolGroups.has(g.name),
4177
5842
  }));
5843
+ const rawWakeSummary =
5844
+ wakeHealthData?.observation_only === true && wakeHealthData?.counts
5845
+ ? {
5846
+ observation_only: true as const,
5847
+ counts: wakeHealthData.counts,
5848
+ attention_agents: Array.isArray(wakeHealthData.agents) ? wakeHealthData.agents : [],
5849
+ }
5850
+ : mcpCtx?.wake_health_summary?.observation_only === true && mcpCtx?.wake_health_summary?.counts
5851
+ ? {
5852
+ observation_only: true as const,
5853
+ counts: mcpCtx.wake_health_summary.counts,
5854
+ attention_agents: Array.isArray(mcpCtx.wake_health_summary.attention_agents)
5855
+ ? mcpCtx.wake_health_summary.attention_agents
5856
+ : [],
5857
+ }
5858
+ : null;
5859
+ const wakeHealthSummary =
5860
+ rawWakeSummary && typeof rawWakeSummary.counts?.total_cloud_agents === "number"
5861
+ ? {
5862
+ observation_only: true as const,
5863
+ counts: {
5864
+ total_cloud_agents: Number(rawWakeSummary.counts.total_cloud_agents) || 0,
5865
+ ok: Number(rawWakeSummary.counts.ok) || 0,
5866
+ auth_required: Number(rawWakeSummary.counts.auth_required) || 0,
5867
+ timeout: Number(rawWakeSummary.counts.timeout) || 0,
5868
+ error: Number(rawWakeSummary.counts.error) || 0,
5869
+ unobserved: Number(rawWakeSummary.counts.unobserved) || 0,
5870
+ },
5871
+ attention_agents: rawWakeSummary.attention_agents
5872
+ .filter((a: any) => {
5873
+ const aid = typeof a?.agent_id === "string" ? a.agent_id.trim() : "";
5874
+ if (!aid || isHumanPiiHandle(aid) || /^(?:ac_|sk-)/i.test(aid)) return false;
5875
+ const cloudStatus = String(a?.cloud_status || "active");
5876
+ const wakeStatus = typeof a?.last_wake_status === "string" ? a.last_wake_status : "";
5877
+ return (
5878
+ cloudStatus !== "active" ||
5879
+ wakeStatus === "auth_required" ||
5880
+ wakeStatus === "timeout" ||
5881
+ wakeStatus === "error"
5882
+ );
5883
+ })
5884
+ .slice(0, 16)
5885
+ .map((a: any) => {
5886
+ const rawName = typeof a?.name === "string" ? a.name.trim() : "";
5887
+ const safeName =
5888
+ rawName && !isHumanPiiHandle(rawName) && !/\b(?:ac_|sk-)[A-Za-z0-9_-]{8,}\b/i.test(rawName)
5889
+ ? rawName
5890
+ : undefined;
5891
+ return {
5892
+ agent_id: String(a.agent_id).trim(),
5893
+ ...(safeName ? { name: safeName } : {}),
5894
+ runtime: String(a.runtime || "unknown"),
5895
+ cloud_status: String(a.cloud_status || "unknown"),
5896
+ ...(typeof a.last_wake_status === "string" ? { last_wake_status: a.last_wake_status } : {}),
5897
+ ...(typeof a.last_wake_at === "string" ? { last_wake_at: a.last_wake_at } : {}),
5898
+ };
5899
+ }),
5900
+ }
5901
+ : null;
4178
5902
  return JSON.stringify({
4179
5903
  channel: chatId,
4180
5904
  ...(mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {}),
@@ -4183,15 +5907,22 @@ const handleToolCall = async (request: any): Promise<any> => {
4183
5907
  ? { total: memberIds.length, online }
4184
5908
  : { total: null, note: "roster unreadable — you are likely not a member of this channel (or it does not exist)" },
4185
5909
  ...(membersReadable ? { agent_peers: agentPeers } : {}),
5910
+ okr_readable: okrReadable,
5911
+ docs_readable: docsReadable,
4186
5912
  okr_objectives: objectives,
5913
+ ...(okrSummary ? { okr_summary: okrSummary } : {}),
5914
+ ...(loopSummary ? { loop_summary: loopSummary } : {}),
5915
+ ...(wakeHealthSummary ? { wake_health_summary: wakeHealthSummary } : {}),
4187
5916
  skills,
5917
+ ...(personalSkills.length > 0 ? { personal_skills: personalSkills } : {}),
5918
+ ...(activeTaskLinkedDocs.length > 0 ? { active_task_linked_docs: activeTaskLinkedDocs } : {}),
4188
5919
  docs,
4189
5920
  tool_groups: toolGroups,
4190
5921
  tips: [
4191
5922
  "load_tool_group(name) reveals an extended group's tools (see tool_groups above; loaded:false = not yet active)",
4192
- "load_skill(chat_id, doc_id) activates a channel skill; list_skills(chat_id) lists them",
5923
+ "load_skill(chat_id, doc_id) activates a channel skill; load_skill(name) loads a personal skill; list_skills(chat_id) lists both",
4193
5924
  "okr_list / get_history for deeper context",
4194
- "/loop <interval> <prompt> works in joined groups and owner-agent DMs; keep group follow-ups in that group (okr: prefix = wake mode)",
5925
+ "create_loop(channel_id, mode, ...) (or /loop <interval> <prompt>) arms okr_wake / okr_watch / prompt loops; check loop_summary.unarmed_objective_ids",
4195
5926
  ],
4196
5927
  });
4197
5928
  }
@@ -4465,26 +6196,6 @@ const handleToolCall = async (request: any): Promise<any> => {
4465
6196
  return { content: [{ type: "text", text: gateNotice + text + pinLine }] };
4466
6197
  }
4467
6198
 
4468
- if (name === "list_channels") {
4469
- const { limit = 50 } = args as any;
4470
- try {
4471
- const r = await apiFetch(`${REST_URL}/api/channels/discover?limit=${Math.max(1, Math.min(Number(limit) || 50, 500))}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4472
- if (r.ok) {
4473
- const data = await r.json() as any;
4474
- const channels = (data.channels || []);
4475
- if (channels.length === 0) return { content: [{ type: "text", text: "No public channels found." }] };
4476
- // Show the FULL channel id — agents copy it straight into reply /
4477
- // get_history / join_channel, all of which need the complete UUID.
4478
- // A truncated 8-char prefix here makes every downstream call 404.
4479
- const list = channels.map((ch: any) => `• ${ch.name || ch.id} (${ch.id}) — ${ch.member_count || "?"} members${ch.topic ? ` — ${ch.topic.slice(0, 60)}` : ""}`).join("\n");
4480
- return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
4481
- }
4482
- return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
4483
- } catch (e) {
4484
- return { content: [{ type: "text", text: `Error: ${e}` }] };
4485
- }
4486
- }
4487
-
4488
6199
  if (name === "find_dm") {
4489
6200
  const { target_agent_id } = args as any;
4490
6201
  if (!target_agent_id || typeof target_agent_id !== "string") {
@@ -4529,16 +6240,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4529
6240
  }
4530
6241
 
4531
6242
  if (name === "list_loops") {
6243
+ const checked = validateListLoopsInput(args);
6244
+ if (!checked.ok) {
6245
+ return { content: [{ type: "text", text: checked.error }], isError: true };
6246
+ }
4532
6247
  try {
4533
6248
  const r = await apiFetch(`${REST_URL}/api/loops/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4534
6249
  if (!r.ok) return { content: [{ type: "text", text: `Failed (${r.status})` }] };
4535
6250
  const data = await r.json() as any;
4536
- const loops = Array.isArray(data?.loops) ? data.loops : [];
4537
- if (loops.length === 0) return { content: [{ type: "text", text: "No loops registered for you." }] };
6251
+ const rawLoops = Array.isArray(data?.loops) ? data.loops : [];
6252
+ const hasFilter = Boolean(
6253
+ checked.value.channel_id || checked.value.status || checked.value.mode || checked.value.objective_id,
6254
+ );
6255
+ const loops = rawLoops.filter((l: any) => {
6256
+ if (!l) return false;
6257
+ if (checked.value.channel_id && l.channel_id !== checked.value.channel_id) return false;
6258
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
6259
+ if (checked.value.status && (paused ? "paused" : "active") !== checked.value.status) return false;
6260
+ const normMode = l.mode === "okr_wake" || l.mode === "okr_watch" ? l.mode : "prompt";
6261
+ if (checked.value.mode && normMode !== checked.value.mode) return false;
6262
+ if (checked.value.objective_id && l.objective_id !== checked.value.objective_id) return false;
6263
+ return true;
6264
+ });
6265
+ if (loops.length === 0) {
6266
+ return { content: [{ type: "text", text: hasFilter ? "No matching loops found." : "No loops registered for you." }] };
6267
+ }
4538
6268
  const lines = loops.map((l: any) => {
4539
- const mode = l.mode === "okr_wake" ? `okr_wake → ${l.objective_id}${Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : ""}` : "static";
6269
+ const targetSuffix = Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : "";
6270
+ const watchFlags = l.mode === "okr_watch"
6271
+ ? [
6272
+ l.watch_idle ? "+idle" : "",
6273
+ l.watch_supply ? "+supply" : "",
6274
+ typeof l.stall_minutes === "number" ? `+stall=${l.stall_minutes}m` : "",
6275
+ ].filter(Boolean).join("")
6276
+ : "";
6277
+ const mode = l.mode === "okr_wake"
6278
+ ? `okr_wake → ${l.objective_id}${targetSuffix}`
6279
+ : l.mode === "okr_watch"
6280
+ ? `okr_watch${watchFlags ? `(${watchFlags})` : ""} → ${l.objective_id}${targetSuffix}`
6281
+ : `static${targetSuffix}`;
6282
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
4540
6283
  const nextIn = typeof l.next_tick_ms === "number" ? Math.max(0, Math.round((l.next_tick_ms - Date.now()) / 60000)) : "?";
4541
- return `• ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | next ~${nextIn}m`;
6284
+ const state = paused ? "paused" : `${l.status || "active"} | next ~${nextIn}m`;
6285
+ return `• ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | ${state}`;
4542
6286
  }).join("\n");
4543
6287
  return { content: [{ type: "text", text: `${loops.length} loop(s):\n${lines}` }] };
4544
6288
  } catch (e: any) {
@@ -4588,7 +6332,11 @@ const handleToolCall = async (request: any): Promise<any> => {
4588
6332
  const safeId = redactParticipantPii(rawId);
4589
6333
  const peer = !isHuman ? peerById.get(rawId) : undefined;
4590
6334
  const rawDisplay = m?.display_name ? String(m.display_name).trim() : (peer?.name ? String(peer.name).trim() : "");
4591
- const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
6335
+ const cleanDisplay =
6336
+ rawDisplay && !/^user:[a-z0-9]{1,4}\*\*\*$/i.test(rawDisplay)
6337
+ ? redactParticipantPii(rawDisplay)
6338
+ : "";
6339
+ const safeDisplay = cleanDisplay || safeId;
4592
6340
  const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
4593
6341
  const roleBadge = m?.role ? ` [${m.role}]` : "";
4594
6342
  const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
@@ -4709,13 +6457,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4709
6457
  }
4710
6458
 
4711
6459
  if (name === "list_channel_docs") {
4712
- const { chat_id, level } = args as { chat_id: string; level?: number | string };
4713
- const qs = new URLSearchParams();
4714
- const normalizedLevel = normalizeChannelDocLevel(level);
4715
- if (level !== undefined && normalizedLevel === null) {
4716
- return { content: [{ type: "text", text: "list_channel_docs failed: level must be 1|2|3|4" }], isError: true };
6460
+ const check = validateListChannelDocsInput(args);
6461
+ if (!check.ok) {
6462
+ return { content: [{ type: "text", text: check.error }], isError: true };
4717
6463
  }
4718
- if (normalizedLevel !== null) qs.set("level", String(normalizedLevel));
6464
+ const { chat_id, level: normalizedLevel, active_only } = check.value;
6465
+ const qs = new URLSearchParams();
6466
+ if (normalizedLevel !== undefined) qs.set("level", String(normalizedLevel));
6467
+ if (active_only === true) qs.set("active_only", "1");
4719
6468
  const url = `${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${qs.toString() ? `?${qs}` : ""}`;
4720
6469
  try {
4721
6470
  const r = await apiFetch(url, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -4730,9 +6479,17 @@ const handleToolCall = async (request: any): Promise<any> => {
4730
6479
  }
4731
6480
 
4732
6481
  if (name === "get_channel_doc") {
4733
- const { chat_id, doc_id } = args as { chat_id: string; doc_id: string };
6482
+ const { chat_id, doc_id } = (args ?? {}) as { chat_id?: unknown; doc_id?: unknown };
6483
+ const listCheck = validateListChannelDocsInput({ chat_id });
6484
+ if (!listCheck.ok) {
6485
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "get_channel_doc") }], isError: true };
6486
+ }
6487
+ const docCheck = validateChannelDocIdInput(doc_id, "get_channel_doc");
6488
+ if (!docCheck.ok) {
6489
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
6490
+ }
4734
6491
  try {
4735
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
6492
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}`, {
4736
6493
  headers: { "Authorization": `Bearer ${TOKEN}` },
4737
6494
  });
4738
6495
  const text = await r.text();
@@ -4746,43 +6503,102 @@ const handleToolCall = async (request: any): Promise<any> => {
4746
6503
  }
4747
6504
 
4748
6505
  if (name === "upsert_channel_doc") {
4749
- const { chat_id, doc_id, title, kind, level, body_markdown, expected_version } = args as {
4750
- chat_id: string;
4751
- doc_id: string;
4752
- title: string;
4753
- kind: string;
4754
- level: number | string;
4755
- body_markdown: string;
4756
- expected_version: number;
4757
- };
4758
- const normalizedLevel = normalizeChannelDocLevel(level);
4759
- if (normalizedLevel === null) {
4760
- return { content: [{ type: "text", text: "upsert_channel_doc failed: level must be 1|2|3|4" }], isError: true };
6506
+ const check = validateUpsertChannelDocInput(args);
6507
+ if (!check.ok) {
6508
+ return { content: [{ type: "text", text: check.error }], isError: true };
6509
+ }
6510
+ const parsed = check.value;
6511
+ try {
6512
+ const r = parsed.mode === "archive"
6513
+ ? await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
6514
+ method: "DELETE",
6515
+ headers: {
6516
+ "Authorization": `Bearer ${TOKEN}`,
6517
+ "If-Match": String(parsed.expected_version),
6518
+ },
6519
+ })
6520
+ : await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
6521
+ method: "PUT",
6522
+ headers: {
6523
+ "Content-Type": "application/json",
6524
+ "Authorization": `Bearer ${TOKEN}`,
6525
+ "If-Match": String(parsed.expected_version),
6526
+ },
6527
+ body: JSON.stringify(parsed.body),
6528
+ });
6529
+ const text = await r.text();
6530
+ if (!r.ok) {
6531
+ return { content: [{ type: "text", text: `upsert_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
6532
+ }
6533
+ if (parsed.mode === "archive" && !text.trim()) {
6534
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
6535
+ return {
6536
+ content: [{
6537
+ type: "text",
6538
+ text: JSON.stringify({
6539
+ ok: true,
6540
+ archived: true,
6541
+ chat_id: parsed.chat_id,
6542
+ doc_id: parsed.doc_id,
6543
+ ...(Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}),
6544
+ }),
6545
+ }],
6546
+ };
6547
+ }
6548
+ return { content: [{ type: "text", text }] };
6549
+ } catch (e: any) {
6550
+ return { content: [{ type: "text", text: `upsert_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6551
+ }
6552
+ }
6553
+
6554
+ if (name === "archive_channel_doc") {
6555
+ const check = validateArchiveChannelDocInput(args);
6556
+ if (!check.ok) {
6557
+ return { content: [{ type: "text", text: check.error }], isError: true };
4761
6558
  }
6559
+ const { chat_id, doc_id, expected_version } = check.value;
4762
6560
  try {
4763
6561
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
4764
- method: "PUT",
6562
+ method: "DELETE",
4765
6563
  headers: {
4766
- "Content-Type": "application/json",
4767
6564
  "Authorization": `Bearer ${TOKEN}`,
4768
6565
  "If-Match": String(expected_version),
4769
6566
  },
4770
- body: JSON.stringify({ title, kind, level: normalizedLevel, body_markdown }),
4771
6567
  });
4772
6568
  const text = await r.text();
4773
6569
  if (!r.ok) {
4774
- return { content: [{ type: "text", text: `upsert_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
6570
+ return { content: [{ type: "text", text: `archive_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4775
6571
  }
4776
- return { content: [{ type: "text", text }] };
6572
+ const normalized = text.trim()
6573
+ ? text
6574
+ : (() => {
6575
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
6576
+ return JSON.stringify({
6577
+ ok: true,
6578
+ archived: true,
6579
+ chat_id,
6580
+ doc_id,
6581
+ ...(Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}),
6582
+ });
6583
+ })();
6584
+ return { content: [{ type: "text", text: normalized }] };
4777
6585
  } catch (e: any) {
4778
- return { content: [{ type: "text", text: `upsert_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6586
+ return { content: [{ type: "text", text: `archive_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4779
6587
  }
4780
6588
  }
4781
6589
 
4782
6590
  if (name === "list_channel_doc_revisions") {
4783
- const { chat_id, doc_id } = args as { chat_id: string; doc_id: string };
6591
+ const { chat_id, doc_id } = (args ?? {}) as { chat_id?: unknown; doc_id?: unknown };
6592
+ const listCheck = validateListChannelDocsInput({ chat_id });
6593
+ if (!listCheck.ok) {
6594
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "list_channel_doc_revisions") }], isError: true };
6595
+ }
6596
+ const docCheck = validateChannelDocIdInput(doc_id, "list_channel_doc_revisions");
6597
+ if (!docCheck.ok) {
6598
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
6599
+ }
4784
6600
  try {
4785
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
6601
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}/revisions`, {
4786
6602
  headers: { "Authorization": `Bearer ${TOKEN}` },
4787
6603
  });
4788
6604
  const text = await r.text();
@@ -4824,14 +6640,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4824
6640
  }
4825
6641
 
4826
6642
  if (name === "okr_create_objective") {
4827
- const { title, horizon, owner, parent_id, due, discussion_channel_id } = args as {
4828
- title: string; horizon: string; owner?: string; parent_id?: string; due?: string; discussion_channel_id?: string;
6643
+ const { title, horizon, owner, parent_id, due, discussion_channel_id, narrative, linked_channel_docs } = args as {
6644
+ title: string;
6645
+ horizon: string;
6646
+ owner?: string;
6647
+ parent_id?: string;
6648
+ due?: string;
6649
+ discussion_channel_id?: string;
6650
+ narrative?: unknown;
6651
+ linked_channel_docs?: unknown;
4829
6652
  };
4830
6653
  const body: Record<string, unknown> = { title, horizon };
4831
6654
  if (owner) body.owner = owner;
4832
- if (parent_id) body.parent_id = parent_id;
6655
+ if (parent_id !== undefined) {
6656
+ const parentCheck = validateOkrParentIdOptionalInput(parent_id);
6657
+ if (!parentCheck.ok) {
6658
+ return { content: [{ type: "text", text: `okr_create_objective invalid parent_id: ${parentCheck.error}` }], isError: true };
6659
+ }
6660
+ if (parentCheck.value) body.parent_id = parentCheck.value;
6661
+ }
4833
6662
  if (due) body.due = due;
4834
6663
  if (discussion_channel_id) body.discussion_channel_id = discussion_channel_id;
6664
+ if (narrative !== undefined) {
6665
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
6666
+ if (!narCheck.ok) {
6667
+ return { content: [{ type: "text", text: `okr_create_objective invalid narrative: ${narCheck.error}` }], isError: true };
6668
+ }
6669
+ if (narCheck.value) body.narrative = narCheck.value;
6670
+ }
6671
+ if (linked_channel_docs !== undefined) {
6672
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
6673
+ if (!docsCheck.ok) {
6674
+ return { content: [{ type: "text", text: `okr_create_objective invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6675
+ }
6676
+ if (docsCheck.value.length > 0) {
6677
+ if (!discussion_channel_id || !discussion_channel_id.trim()) {
6678
+ return {
6679
+ content: [{ type: "text", text: "okr_create_objective invalid linked_channel_docs: discussion_channel_id is required when attaching linked_channel_docs" }],
6680
+ isError: true,
6681
+ };
6682
+ }
6683
+ body.linked_channel_docs = docsCheck.value;
6684
+ }
6685
+ }
4835
6686
  try {
4836
6687
  const r = await apiFetch(`${REST_URL}/api/okr/objectives`, {
4837
6688
  method: "POST",
@@ -4842,20 +6693,103 @@ const handleToolCall = async (request: any): Promise<any> => {
4842
6693
  if (!r.ok) {
4843
6694
  return { content: [{ type: "text", text: `okr_create_objective failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4844
6695
  }
4845
- return { content: [{ type: "text", text: `Created: ${text}` }] };
6696
+ let outText = text;
6697
+ if (discussion_channel_id && !discussion_channel_id.startsWith("dm-") && isSafeLoopIdentifier(discussion_channel_id)) {
6698
+ try {
6699
+ const parsed = JSON.parse(text) as any;
6700
+ const createdObjId = typeof parsed?.objective?.id === "string" ? parsed.objective.id : "";
6701
+ if (parsed && typeof parsed === "object" && /^[A-Za-z0-9_-]{6,80}$/.test(createdObjId)) {
6702
+ outText = JSON.stringify({
6703
+ ...parsed,
6704
+ loop_guard_hint: {
6705
+ okr_wake_armed: false,
6706
+ recommended_tool: "create_loop",
6707
+ recommended_arguments: {
6708
+ channel_id: discussion_channel_id,
6709
+ mode: "okr_wake",
6710
+ interval: "5m",
6711
+ objective_id: createdObjId,
6712
+ },
6713
+ },
6714
+ });
6715
+ }
6716
+ } catch {}
6717
+ }
6718
+ return { content: [{ type: "text", text: `Created: ${outText}` }] };
4846
6719
  } catch (e: any) {
4847
6720
  return { content: [{ type: "text", text: `okr_create_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4848
6721
  }
4849
6722
  }
4850
6723
 
6724
+ if (name === "okr_update_objective") {
6725
+ const validated = validateOkrUpdateObjectiveInput(args);
6726
+ if (!validated.ok) {
6727
+ return { content: [{ type: "text", text: `okr_update_objective invalid arguments: ${validated.error}` }], isError: true };
6728
+ }
6729
+ const { objective_id, body } = validated.value;
6730
+ try {
6731
+ const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}`, {
6732
+ method: "PATCH",
6733
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
6734
+ body: JSON.stringify(body),
6735
+ });
6736
+ const text = await r.text();
6737
+ if (!r.ok) {
6738
+ return { content: [{ type: "text", text: `okr_update_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
6739
+ }
6740
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
6741
+ } catch (e: any) {
6742
+ return { content: [{ type: "text", text: `okr_update_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6743
+ }
6744
+ }
6745
+
4851
6746
  if (name === "okr_add_task") {
4852
- const { objective_id, title, assignee, contributes_to, depends_on, due } = args as {
4853
- objective_id: string; title: string; assignee: string; contributes_to?: string[]; depends_on?: string[]; due?: string;
6747
+ const { objective_id, title, assignee, contributes_to, depends_on, linked_channel_docs, due } = args as {
6748
+ objective_id: string;
6749
+ title: string;
6750
+ assignee: string;
6751
+ contributes_to?: unknown;
6752
+ depends_on?: unknown;
6753
+ linked_channel_docs?: unknown;
6754
+ due?: unknown;
4854
6755
  };
4855
- const body: Record<string, unknown> = { title, assignee };
4856
- if (Array.isArray(contributes_to) && contributes_to.length > 0) body.contributes_to = contributes_to;
4857
- if (Array.isArray(depends_on) && depends_on.length > 0) body.depends_on = depends_on;
4858
- if (due) body.due = due;
6756
+ const titleCheck = validateOkrTaskTitleInput(title);
6757
+ if (!titleCheck.ok) {
6758
+ return { content: [{ type: "text", text: `okr_add_task invalid title: ${titleCheck.error}` }], isError: true };
6759
+ }
6760
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
6761
+ if (!assigneeCheck.ok) {
6762
+ return { content: [{ type: "text", text: `okr_add_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
6763
+ }
6764
+ const body: Record<string, unknown> = { title: titleCheck.value, assignee: assigneeCheck.value };
6765
+ if (contributes_to !== undefined) {
6766
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
6767
+ if (!contribCheck.ok) {
6768
+ return { content: [{ type: "text", text: `okr_add_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
6769
+ }
6770
+ if (contribCheck.value.length > 0) body.contributes_to = contribCheck.value;
6771
+ }
6772
+ if (depends_on !== undefined) {
6773
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on);
6774
+ if (!depsCheck.ok) {
6775
+ return { content: [{ type: "text", text: `okr_add_task invalid depends_on: ${depsCheck.error}` }], isError: true };
6776
+ }
6777
+ if (depsCheck.value.length > 0) body.depends_on = depsCheck.value;
6778
+ }
6779
+ if (linked_channel_docs !== undefined) {
6780
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
6781
+ if (!docsCheck.ok) {
6782
+ return { content: [{ type: "text", text: `okr_add_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6783
+ }
6784
+ if (docsCheck.value.length > 0) body.linked_channel_docs = docsCheck.value;
6785
+ }
6786
+ if (due !== undefined && due !== null && due !== "") {
6787
+ const dueCheck = validateOkrTaskDueInput(due);
6788
+ if (!dueCheck.ok) {
6789
+ return { content: [{ type: "text", text: `okr_add_task invalid due: ${dueCheck.error}` }], isError: true };
6790
+ }
6791
+ if (dueCheck.value) body.due = dueCheck.value;
6792
+ }
4859
6793
  try {
4860
6794
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/tasks`, {
4861
6795
  method: "POST",
@@ -4873,16 +6807,113 @@ const handleToolCall = async (request: any): Promise<any> => {
4873
6807
  }
4874
6808
 
4875
6809
  if (name === "okr_update_task") {
4876
- const { task_id, status, assignee, blocked_reason, blocker_agent, depends_on, due } = args as { task_id: string; status?: string; assignee?: string; blocked_reason?: string; blocker_agent?: string; depends_on?: string[]; due?: string };
6810
+ const {
6811
+ task_id,
6812
+ title,
6813
+ status,
6814
+ assignee,
6815
+ contributes_to,
6816
+ blocked_reason,
6817
+ blocker_agent,
6818
+ depends_on,
6819
+ linked_channel_docs,
6820
+ due,
6821
+ evidence,
6822
+ append_evidence,
6823
+ if_match_updated_at,
6824
+ } = args as {
6825
+ task_id: string;
6826
+ title?: unknown;
6827
+ status?: string;
6828
+ assignee?: unknown;
6829
+ contributes_to?: unknown;
6830
+ blocked_reason?: string;
6831
+ blocker_agent?: string;
6832
+ depends_on?: unknown;
6833
+ linked_channel_docs?: unknown;
6834
+ due?: unknown;
6835
+ evidence?: unknown;
6836
+ append_evidence?: unknown;
6837
+ if_match_updated_at?: unknown;
6838
+ };
6839
+ if (evidence !== undefined && append_evidence !== undefined) {
6840
+ return {
6841
+ content: [{ type: "text", text: "okr_update_task invalid arguments: cannot pass both evidence and append_evidence" }],
6842
+ isError: true,
6843
+ };
6844
+ }
4877
6845
  const patch: Record<string, unknown> = {};
6846
+ if (title !== undefined) {
6847
+ const titleCheck = validateOkrTaskTitleInput(title);
6848
+ if (!titleCheck.ok) {
6849
+ return { content: [{ type: "text", text: `okr_update_task invalid title: ${titleCheck.error}` }], isError: true };
6850
+ }
6851
+ patch.title = titleCheck.value;
6852
+ }
4878
6853
  if (status) patch.status = status;
4879
- if (assignee) patch.assignee = assignee;
6854
+ if (assignee !== undefined) {
6855
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
6856
+ if (!assigneeCheck.ok) {
6857
+ return { content: [{ type: "text", text: `okr_update_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
6858
+ }
6859
+ patch.assignee = assigneeCheck.value;
6860
+ }
6861
+ if (contributes_to !== undefined) {
6862
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
6863
+ if (!contribCheck.ok) {
6864
+ return { content: [{ type: "text", text: `okr_update_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
6865
+ }
6866
+ patch.contributes_to = contribCheck.value;
6867
+ }
4880
6868
  if (blocked_reason !== undefined) patch.blocked_reason = blocked_reason;
4881
6869
  if (blocker_agent !== undefined) patch.blocker_agent = blocker_agent;
4882
- if (Array.isArray(depends_on)) patch.depends_on = depends_on;
4883
- if (due) patch.due = due;
6870
+ if (depends_on !== undefined) {
6871
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on, task_id);
6872
+ if (!depsCheck.ok) {
6873
+ return { content: [{ type: "text", text: `okr_update_task invalid depends_on: ${depsCheck.error}` }], isError: true };
6874
+ }
6875
+ patch.depends_on = depsCheck.value;
6876
+ }
6877
+ if (linked_channel_docs !== undefined) {
6878
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
6879
+ if (!docsCheck.ok) {
6880
+ return { content: [{ type: "text", text: `okr_update_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6881
+ }
6882
+ patch.linked_channel_docs = docsCheck.value;
6883
+ }
6884
+ if (due !== undefined) {
6885
+ const dueCheck = validateOkrTaskDueInput(due);
6886
+ if (!dueCheck.ok) {
6887
+ return { content: [{ type: "text", text: `okr_update_task invalid due: ${dueCheck.error}` }], isError: true };
6888
+ }
6889
+ patch.due = dueCheck.value;
6890
+ }
6891
+ if (evidence !== undefined) {
6892
+ const evCheck = validateTaskEvidenceInput(evidence);
6893
+ if (!evCheck.ok) {
6894
+ return { content: [{ type: "text", text: `okr_update_task invalid evidence: ${evCheck.error}` }], isError: true };
6895
+ }
6896
+ patch.evidence = evCheck.value;
6897
+ }
6898
+ let validatedAppend: TaskEvidenceInput[] = [];
6899
+ if (append_evidence !== undefined) {
6900
+ const appCheck = validateAppendTaskEvidenceInput(append_evidence);
6901
+ if (!appCheck.ok) {
6902
+ return { content: [{ type: "text", text: `okr_update_task invalid append_evidence: ${appCheck.error}` }], isError: true };
6903
+ }
6904
+ validatedAppend = appCheck.value;
6905
+ patch.append_evidence = appCheck.value;
6906
+ }
6907
+ if (if_match_updated_at !== undefined) {
6908
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
6909
+ if (!verCheck.ok) {
6910
+ return { content: [{ type: "text", text: `okr_update_task invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
6911
+ }
6912
+ patch.if_match_updated_at = verCheck.value;
6913
+ }
4884
6914
  try {
4885
- const r = await apiFetch(`${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`, {
6915
+ const targetUrl = `${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`;
6916
+ const r = await apiFetch(targetUrl, {
4886
6917
  method: "PATCH",
4887
6918
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4888
6919
  body: JSON.stringify(patch),
@@ -4891,7 +6922,48 @@ const handleToolCall = async (request: any): Promise<any> => {
4891
6922
  if (!r.ok) {
4892
6923
  return { content: [{ type: "text", text: `okr_update_task failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4893
6924
  }
4894
- return { content: [{ type: "text", text: `Updated: ${text}` }] };
6925
+ let finalText = text;
6926
+ let parsed: any = null;
6927
+ try { parsed = JSON.parse(text); } catch {}
6928
+ if (validatedAppend.length > 0 && parsed?.ok === true && parsed?.task && !responseIncludesAppendedEvidence(parsed.task, validatedAppend)) {
6929
+ const merged = mergeLegacyTaskEvidence(parsed.task.evidence, validatedAppend);
6930
+ if (!merged.ok) {
6931
+ return {
6932
+ content: [{ type: "text", text: `okr_update_task append_evidence failed: ${merged.error}` }],
6933
+ isError: true,
6934
+ };
6935
+ }
6936
+ const fallbackBody: Record<string, unknown> = { evidence: merged.value };
6937
+ if (typeof parsed.task.updated_at === "string" && parsed.task.updated_at.trim()) {
6938
+ fallbackBody.if_match_updated_at = parsed.task.updated_at.trim();
6939
+ }
6940
+ const r2 = await apiFetch(targetUrl, {
6941
+ method: "PATCH",
6942
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
6943
+ body: JSON.stringify(fallbackBody),
6944
+ });
6945
+ const text2 = await r2.text();
6946
+ if (!r2.ok) {
6947
+ return { content: [{ type: "text", text: `okr_update_task failed (${r2.status}): ${text2.slice(0, 160)}` }], isError: true };
6948
+ }
6949
+ finalText = text2;
6950
+ parsed = null;
6951
+ try { parsed = JSON.parse(text2); } catch {}
6952
+ }
6953
+ if (patch.status === "done" && parsed?.ok === true && parsed?.task && Array.isArray(parsed.task.contributes_to)) {
6954
+ const krIds = parsed.task.contributes_to
6955
+ .filter((id: unknown): id is string => typeof id === "string" && id.trim().length > 0)
6956
+ .map((id: string) => id.trim());
6957
+ if (krIds.length > 0) {
6958
+ parsed.kr_progress_hint = {
6959
+ contributes_to: krIds,
6960
+ recommended_tool: "okr_set_kr_progress",
6961
+ note: `Task marked done; remember to report quantitative progress for linked KR(s): ${krIds.join(", ")}.`,
6962
+ };
6963
+ finalText = JSON.stringify(parsed);
6964
+ }
6965
+ }
6966
+ return { content: [{ type: "text", text: `Updated: ${finalText}` }] };
4895
6967
  } catch (e: any) {
4896
6968
  return { content: [{ type: "text", text: `okr_update_task network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4897
6969
  }
@@ -4933,12 +7005,11 @@ const handleToolCall = async (request: any): Promise<any> => {
4933
7005
  }
4934
7006
 
4935
7007
  if (name === "okr_add_kr") {
4936
- const { objective_id, title, metric_type, current, target, risk_level } = args as {
4937
- objective_id: string; title: string; metric_type: string; current?: number; target: number; risk_level?: string;
4938
- };
4939
- const body: Record<string, unknown> = { title, metric_type, target };
4940
- if (typeof current === "number") body.current = current;
4941
- if (risk_level) body.risk_level = risk_level;
7008
+ const validated = validateOkrAddKrInput(args);
7009
+ if (!validated.ok) {
7010
+ return { content: [{ type: "text", text: `okr_add_kr invalid arguments: ${validated.error}` }], isError: true };
7011
+ }
7012
+ const { objective_id, body } = validated.value;
4942
7013
  try {
4943
7014
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/krs`, {
4944
7015
  method: "POST",
@@ -4956,12 +7027,16 @@ const handleToolCall = async (request: any): Promise<any> => {
4956
7027
  }
4957
7028
 
4958
7029
  if (name === "archive_objective") {
4959
- const { objective_id, completion_summary } = args as { objective_id: string; completion_summary?: string };
7030
+ const validated = validateOkrArchiveObjectiveInput(args);
7031
+ if (!validated.ok) {
7032
+ return { content: [{ type: "text", text: `archive_objective invalid arguments: ${validated.error}` }], isError: true };
7033
+ }
7034
+ const { objective_id, body } = validated.value;
4960
7035
  try {
4961
7036
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/archive`, {
4962
7037
  method: "POST",
4963
7038
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4964
- body: JSON.stringify(completion_summary !== undefined ? { completion_summary } : {}),
7039
+ body: JSON.stringify(body),
4965
7040
  });
4966
7041
  const text = await r.text();
4967
7042
  if (!r.ok) {
@@ -4991,11 +7066,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4991
7066
  }
4992
7067
 
4993
7068
  if (name === "okr_set_kr_progress") {
4994
- const { kr_id, current, risk_level } = args as { kr_id: string; current: number; risk_level?: string };
4995
- const body: Record<string, unknown> = { current };
4996
- if (risk_level) body.risk_level = risk_level;
7069
+ const validated = validateOkrSetKrProgressInput(args);
7070
+ if (!validated.ok) {
7071
+ return { content: [{ type: "text", text: `okr_set_kr_progress invalid arguments: ${validated.error}` }], isError: true };
7072
+ }
7073
+ const { kr_id, body, useMetadataEndpoint } = validated.value;
7074
+ const pathSuffix = useMetadataEndpoint ? "" : "/progress";
4997
7075
  try {
4998
- const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}/progress`, {
7076
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}${pathSuffix}`, {
4999
7077
  method: "PATCH",
5000
7078
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
5001
7079
  body: JSON.stringify(body),
@@ -5030,21 +7108,41 @@ const handleToolCall = async (request: any): Promise<any> => {
5030
7108
  }
5031
7109
 
5032
7110
  if (name === "okr_set_links") {
5033
- const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs } = args as {
7111
+ const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs, if_match_updated_at } = args as {
5034
7112
  target_type: "objective" | "kr" | "task";
5035
7113
  target_id: string;
5036
- narrative?: string;
7114
+ narrative?: unknown;
5037
7115
  narrative_path?: string;
5038
7116
  discussion_channel_id?: string;
5039
7117
  linked_docs?: string[];
5040
- linked_channel_docs?: Array<{ channel_id: string; doc_id: string }>;
7118
+ linked_channel_docs?: unknown;
7119
+ if_match_updated_at?: unknown;
5041
7120
  };
5042
7121
  const body: Record<string, unknown> = {};
5043
- if (narrative !== undefined) body.narrative = narrative;
7122
+ if (narrative !== undefined) {
7123
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
7124
+ if (!narCheck.ok) {
7125
+ return { content: [{ type: "text", text: `okr_set_links invalid narrative: ${narCheck.error}` }], isError: true };
7126
+ }
7127
+ body.narrative = narCheck.value;
7128
+ }
5044
7129
  if (narrative_path !== undefined) body.narrative_path = narrative_path;
5045
7130
  if (discussion_channel_id !== undefined) body.discussion_channel_id = discussion_channel_id;
5046
7131
  if (linked_docs !== undefined) body.linked_docs = linked_docs;
5047
- if (linked_channel_docs !== undefined) body.linked_channel_docs = linked_channel_docs;
7132
+ if (linked_channel_docs !== undefined) {
7133
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
7134
+ if (!docsCheck.ok) {
7135
+ return { content: [{ type: "text", text: `okr_set_links invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
7136
+ }
7137
+ body.linked_channel_docs = docsCheck.value;
7138
+ }
7139
+ if (if_match_updated_at !== undefined && if_match_updated_at !== null) {
7140
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
7141
+ if (!verCheck.ok) {
7142
+ return { content: [{ type: "text", text: `okr_set_links invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
7143
+ }
7144
+ body.if_match_updated_at = verCheck.value;
7145
+ }
5048
7146
  try {
5049
7147
  const r = await apiFetch(`${REST_URL}/api/okr/links/${encodeURIComponent(target_type)}/${encodeURIComponent(target_id)}`, {
5050
7148
  method: "PATCH",
@@ -5135,13 +7233,28 @@ function isSkillDoc(doc: any): boolean {
5135
7233
  return kind === "skill" || kind === "channel_skill" || id.includes("skill") || title.includes("skill");
5136
7234
  }
5137
7235
 
7236
+ function isArchivedSkillOrDoc(doc: any): boolean {
7237
+ if (!doc || typeof doc !== "object") return false;
7238
+ if (doc.archived === true) return true;
7239
+ const body = doc.body_markdown ?? doc.bodyMarkdown;
7240
+ if (typeof body === "string") return body === "";
7241
+ const summary = doc.body_summary ?? doc.bodySummary;
7242
+ if (typeof summary === "string" && summary === "" && doc.archived !== false && doc.skill_meta === undefined && doc.skillMeta === undefined) {
7243
+ return true;
7244
+ }
7245
+ return false;
7246
+ }
7247
+
5138
7248
  function compactSkillDoc(doc: any) {
5139
7249
  const meta = doc?.skill_meta || doc?.skillMeta || {};
7250
+ const archived = isArchivedSkillOrDoc(doc);
5140
7251
  return {
5141
7252
  doc_id: doc?.id ?? doc?.doc_id,
5142
7253
  title: doc?.title,
5143
7254
  kind: doc?.kind,
5144
7255
  level: doc?.level,
7256
+ ...(typeof doc?.version === "number" ? { version: doc.version } : {}),
7257
+ ...(archived ? { archived: true } : {}),
5145
7258
  updated_at: doc?.updatedAt ?? doc?.updated_at,
5146
7259
  name: meta.name,
5147
7260
  description: meta.description,
@@ -5274,11 +7387,13 @@ function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = acti
5274
7387
 
5275
7388
  function scheduleReconnect(delayMs: number, slot: ProfileSlot | null = activeSlot) {
5276
7389
  if (shuttingDown || !slot) return; // don't resurrect the socket after shutdown
7390
+ slot.heartbeat.stop();
5277
7391
  if (slot.reconnectTimer) clearTimeout(slot.reconnectTimer);
5278
7392
  slot.reconnectTimer = setTimeout(() => {
5279
7393
  slot.reconnectTimer = null;
5280
7394
  connectWS(slot);
5281
7395
  }, delayMs);
7396
+ (slot.reconnectTimer as any).unref?.();
5282
7397
  }
5283
7398
 
5284
7399
  /**
@@ -5415,6 +7530,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5415
7530
  socket = new WebSocket(WS_URL);
5416
7531
  slot.ws = socket;
5417
7532
  if (activeSlot === slot) ws = socket;
7533
+ slot.heartbeat.start();
5418
7534
  } catch (e) {
5419
7535
  process.stderr.write(`[agentchat] WebSocket constructor failed: ${e}, retrying in 5s\n`);
5420
7536
  scheduleReconnect(5000, slot);
@@ -5467,6 +7583,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5467
7583
  slot!.backfillTimer = null;
5468
7584
  if (!shuttingDown) void backfillAllChannels(slot!);
5469
7585
  }, 2000);
7586
+ (slot!.backfillTimer as any).unref?.();
5470
7587
  } else if ((data.type === "message" || data.type === "thread_reply") &&
5471
7588
  data.sender_id === slot!.agentId && typeof data.content === "string" && data.content !== "__typing__" &&
5472
7589
  !["loop_tick", "slash_input", "loop_status", "slash_response"].includes(data.meta?.kind)) {
@@ -5600,6 +7717,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5600
7717
  const port = grokPortFromGatewayConfig(gwcfg);
5601
7718
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
5602
7719
  headers: token ? { Authorization: `Bearer ${token}` } : {},
7720
+ signal: AbortSignal.timeout(5000),
5603
7721
  });
5604
7722
  if (!res.ok) throw new Error(`listAgents HTTP ${res.status}`);
5605
7723
  const d = (await res.json()) as any;
@@ -5746,7 +7864,8 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5746
7864
  process.stderr.write(`[agentchat] Joined channel: ${data.name}\n`);
5747
7865
  if (typeof data.channel_id === "string") slot!.knownChannels.add(data.channel_id);
5748
7866
  } else if (data.type === "shard_moved") {
5749
- process.stderr.write(`[agentchat] Shard moved, reconnecting...\n`);
7867
+ const delay = resolveDrainReconnectDelay(data);
7868
+ process.stderr.write(`[agentchat] Shard moved, reconnecting in ${delay}ms...\n`);
5750
7869
  if (data.redirect_url) {
5751
7870
  const newUrl = data.redirect_url.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws";
5752
7871
  process.stderr.write(`[agentchat] Redirecting to: ${newUrl}\n`);
@@ -5756,7 +7875,28 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5756
7875
  slot!.sessionId = null;
5757
7876
  if (activeSlot === slot) { ws = null; sessionId = null; }
5758
7877
  slot!.wsReconnectAttempt = 0;
5759
- scheduleReconnect(500, slot!);
7878
+ scheduleReconnect(delay, slot!);
7879
+ } else if (data.type === "please_reconnect") {
7880
+ const delay = resolveDrainReconnectDelay(data);
7881
+ process.stderr.write(`[agentchat] Server draining (please_reconnect), reconnecting in ${delay}ms...\n`);
7882
+ if (slot!.ws) { slot!.ws.onclose = null; try { slot!.ws.close(); } catch {} }
7883
+ slot!.ws = null;
7884
+ slot!.sessionId = null;
7885
+ if (activeSlot === slot) { ws = null; sessionId = null; }
7886
+ slot!.wsReconnectAttempt = 0;
7887
+ scheduleReconnect(delay, slot!);
7888
+ } else if (data.type === "auth_error") {
7889
+ const reason = data.error || data.message || "authentication failed";
7890
+ process.stderr.write(`[agentchat] Auth error for ${slot!.agentId}: ${reason} — halting reconnect loop\n`);
7891
+ slot!.heartbeat.stop();
7892
+ if (slot!.reconnectTimer) {
7893
+ clearTimeout(slot!.reconnectTimer);
7894
+ slot!.reconnectTimer = null;
7895
+ }
7896
+ if (slot!.ws) { slot!.ws.onclose = null; try { slot!.ws.close(); } catch {} }
7897
+ slot!.ws = null;
7898
+ slot!.sessionId = null;
7899
+ if (activeSlot === slot) { ws = null; sessionId = null; }
5760
7900
  } else if (data.type === "error") {
5761
7901
  process.stderr.write(`[agentchat] Error: ${data.message}\n`);
5762
7902
  }
@@ -5764,8 +7904,12 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5764
7904
 
5765
7905
  socket.onclose = (event) => {
5766
7906
  if (slot.ws !== socket) return;
7907
+ slot.ws = null;
5767
7908
  slot.sessionId = null;
5768
- if (activeSlot === slot) sessionId = null;
7909
+ if (activeSlot === slot) {
7910
+ ws = null;
7911
+ sessionId = null;
7912
+ }
5769
7913
  slot.heartbeat.resetReconnecting();
5770
7914
  slot.wsReconnectAttempt++;
5771
7915
  const delay = computeReconnectDelay(slot.wsReconnectAttempt);
@@ -5849,6 +7993,7 @@ function installStdioLifecycleGuards() {
5849
7993
  async function checkVersionStaleness(): Promise<void> {
5850
7994
  const controller = new AbortController();
5851
7995
  const timer = setTimeout(() => controller.abort(), 5000);
7996
+ (timer as any).unref?.();
5852
7997
  try {
5853
7998
  const r = await nativeFetch("https://registry.npmjs.org/agentschat-mcp/latest", { signal: controller.signal });
5854
7999
  if (!r.ok) return;
@@ -5857,7 +8002,7 @@ async function checkVersionStaleness(): Promise<void> {
5857
8002
  process.stderr.write(
5858
8003
  `[agentchat] Update available: running agentschat-mcp ${pkg.version}, latest published is ${latest}. ` +
5859
8004
  `New tools/capabilities load only on a SESSION RESTART (hot-reload isn't possible); ` +
5860
- `update deliberately (bump the pinned agentschat-mcp@<version> in each MCP entry / reinstall) then restart this session to pick them up.\n`,
8005
+ `use npx -y agentschat-mcp@latest in each MCP entry (or reinstall npm i -g agentschat-mcp@latest) then restart this session to pick them up.\n`,
5861
8006
  );
5862
8007
  }
5863
8008
  } catch {