agentschat-mcp 0.36.23 → 0.36.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -46,7 +46,43 @@ import { matchesMention } from "./mentions.ts";
46
46
  import { messageDedupKey, MessageDedup } from "./dedup.ts";
47
47
  import { computeReconnectDelay } from "./reconnect.ts";
48
48
  import { normalizeTimestampForCursor } from "./timestamps.ts";
49
- import { validateToolArgs } from "./argcheck.ts";
49
+ import {
50
+ CREATE_LOOP_MODES,
51
+ CHANNEL_DOC_KINDS,
52
+ TASK_EVIDENCE_KINDS,
53
+ type TaskEvidenceInput,
54
+ mergeLegacyTaskEvidence,
55
+ responseIncludesAppendedEvidence,
56
+ validateAppendTaskEvidenceInput,
57
+ validateArchiveChannelDocInput,
58
+ validateChannelDocIdInput,
59
+ validateCreateLoopInput,
60
+ validateDeleteMemoryInput,
61
+ validateListChannelDocsInput,
62
+ validateListLoopsInput,
63
+ validateLoadMemoryInput,
64
+ validateOkrAddKrInput,
65
+ validateOkrArchiveObjectiveInput,
66
+ validateOkrLinkedChannelDocsInput,
67
+ validateOkrObjectiveNarrativeInput,
68
+ validateOkrParentIdOptionalInput,
69
+ validateOkrReparentObjectiveInput,
70
+ validateOkrSetKrProgressInput,
71
+ validateOkrTaskAssigneeInput,
72
+ validateOkrTaskContributesToInput,
73
+ validateOkrTaskDependsOnInput,
74
+ validateOkrTaskDueInput,
75
+ validateOkrTaskTitleInput,
76
+ validateLoadSkillInput,
77
+ validateOkrUpdateKrInput,
78
+ validateOkrUpdateObjectiveInput,
79
+ validatePersonalSkillSlugInput,
80
+ validateSaveSkillInput,
81
+ validateTaskEvidenceInput,
82
+ validateTaskVersionToken,
83
+ validateToolArgs,
84
+ validateUpsertChannelDocInput,
85
+ } from "./argcheck.ts";
50
86
  import { decideIdentity, shouldMigrateDevToken, validateIdentityProfile } from "./identity.ts";
51
87
  import { projectProfileSelector } from "./profile-selection.ts";
52
88
  import type { ProfileSource } from "./identity.ts";
@@ -75,6 +111,8 @@ import {
75
111
  resolveGrokGatewayPath,
76
112
  grokBearerFromGatewayConfig,
77
113
  grokPortFromGatewayConfig,
114
+ resolveEnvWakeId,
115
+ WAKE_ID_HEADER,
78
116
  } from "./wake.ts";
79
117
  import {
80
118
  DEFAULT_SESSION_BINDS_FILENAME,
@@ -123,17 +161,33 @@ import {
123
161
  } from "./identity-guard.ts";
124
162
  // Read-cursor persistence: a state change that merely *lives* in the teardown path.
125
163
  import { flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
164
+ import { CURSOR_INIT_KEY, joinChannelRest, parseMaxIdleMs, sendRestMessage, wakeOnce } from "./rest-cli.ts";
126
165
  import { randomUUID } from "crypto";
127
166
 
128
167
  function parseArgs() {
129
168
  const args = process.argv.slice(2);
130
169
  const parsed: Record<string, string> = {};
131
- const values = new Set(["name", "id", "url", "token", "caps", "profile"]);
170
+ const values = new Set([
171
+ "name",
172
+ "id",
173
+ "url",
174
+ "token",
175
+ "caps",
176
+ "profile",
177
+ "join",
178
+ "send",
179
+ "text",
180
+ "reply-to",
181
+ "channel",
182
+ "timeout",
183
+ "max-idle",
184
+ ]);
132
185
  for (let i = 0; i < args.length; i++) {
133
186
  const arg = args[i];
134
187
  if (arg === "--help" || arg === "-h") continue;
135
188
  if (arg === "--register") { parsed.register = "1"; continue; }
136
189
  if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
190
+ if (arg === "--wake-once") { parsed.wakeOnce = "1"; continue; }
137
191
  if (arg === "--accept-terms") continue; // Legacy compatibility; no consent is recorded.
138
192
  const equal = arg.indexOf("=");
139
193
  const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
@@ -142,7 +196,7 @@ function parseArgs() {
142
196
  process.exit(1);
143
197
  }
144
198
  const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
145
- if (!value?.trim() || value.startsWith("-")) {
199
+ if (!value?.trim() || (key !== "text" && value.startsWith("-"))) {
146
200
  process.stderr.write(`[agentchat] ERROR: missing value for --${key}. See --help.\n`);
147
201
  process.exit(1);
148
202
  }
@@ -152,6 +206,7 @@ function parseArgs() {
152
206
  }
153
207
 
154
208
  const cliArgs = parseArgs();
209
+ const isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
155
210
 
156
211
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
157
212
  const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
@@ -176,6 +231,14 @@ Options:
176
231
  --profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
177
232
  --register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
178
233
  --register Explicitly opt in to registering a new agent (implied by --name)
234
+ --join <channel> Join a public channel via REST (e.g. --join welcome) and exit (or combine with --send / --wake-once).
235
+ --send <channel> Send a message to <channel> via REST (--text <msg> [--reply-to <msg_id>]), advance read cursor, and exit.
236
+ --text <msg> Message content for --send.
237
+ --reply-to <id> Optional target message ID for --send.
238
+ --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.
239
+ --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
240
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
241
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
179
242
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
180
243
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
181
244
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -222,6 +285,25 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
222
285
 
223
286
  // Explicit CLI selection > project binding > runtime binding > environment > default.
224
287
  // Onboarding resolves ambiguous unbound candidates with the user; never scan-and-pick.
288
+ // A dedicated Codex bridge is the identity authority for all inherited MCP entries.
289
+ // No credentials in this envelope; read the existing private profile.
290
+ const codexIdentity = process.env.AGENTSCHAT_CODEX_IDENTITY
291
+ ? JSON.parse(process.env.AGENTSCHAT_CODEX_IDENTITY) as { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }
292
+ : undefined;
293
+ if (codexIdentity) {
294
+ if (process.env.AGENTSCHAT_TOOL_ONLY !== "1" ||
295
+ [codexIdentity.profileFile, codexIdentity.agentId, codexIdentity.apiUrl, codexIdentity.wsUrl].some(v => typeof v !== "string" || !v.trim())) {
296
+ throw new Error("Invalid Codex tool identity");
297
+ }
298
+ // Override inherited CLI/project/env selectors; they may belong to another bot.
299
+ cliArgs.profile = codexIdentity.profileFile;
300
+ cliArgs.id = codexIdentity.agentId;
301
+ cliArgs.url = codexIdentity.apiUrl;
302
+ delete cliArgs.token;
303
+ delete cliArgs.name;
304
+ delete process.env.AGENTCHAT_TOKEN;
305
+ process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
306
+ }
225
307
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
226
308
  const configDir = join(homeDir, ".agentschat");
227
309
  const legacyConfigDir = join(homeDir, ".agentchat");
@@ -229,7 +311,15 @@ const profileDirs = [configDir, legacyConfigDir];
229
311
  const lockDir = resolveLockDir(homeDir, process.env);
230
312
  const lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
231
313
  const toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
232
- let runtimeSession: DetectedSession | null = detectRuntimeSession(process.env);
314
+ let runtimeSessionComputed = false;
315
+ let runtimeSession: DetectedSession | null = null;
316
+ function ensureRuntimeSession(): DetectedSession | null {
317
+ if (!runtimeSessionComputed) {
318
+ runtimeSessionComputed = true;
319
+ runtimeSession = detectRuntimeSession(process.env);
320
+ }
321
+ return runtimeSession;
322
+ }
233
323
  /** One-shot notice when DSH is detected but no session can be resolved (see the DSH branch). */
234
324
  let dshRouteWarned = false;
235
325
 
@@ -331,13 +421,14 @@ function resolveProfile(): { path: string; source: ProfileSource; declaredName?:
331
421
 
332
422
  // Unified session-bind (`~/.agentschat/session-binds.json` / `agy-binds.json`):
333
423
  // maps CLAUDE_CODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID / ZCODE_SESSION_ID to a profile.
334
- if (!grokToken && runtimeSession?.sessionId) {
424
+ const bootSession = !grokToken ? ensureRuntimeSession() : null;
425
+ if (!grokToken && bootSession?.sessionId) {
335
426
  const sessionBinds = loadSessionBinds(configDir);
336
- const boundProfile = sessionBinds[runtimeSession.sessionId];
427
+ const boundProfile = sessionBinds[bootSession.sessionId];
337
428
  if (boundProfile) {
338
429
  const boundPath = nameToPath(boundProfile);
339
430
  if (existsSync(boundPath)) {
340
- process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} → profile "${boundProfile}"\n`);
431
+ process.stderr.write(`[agentchat] session-bind (${bootSession.runtime}): ${bootSession.sessionId} → profile "${boundProfile}"\n`);
341
432
  return { path: boundPath, source: "session-bind", declaredName: boundProfile };
342
433
  }
343
434
  }
@@ -395,13 +486,23 @@ async function apiFetch(
395
486
  input: string | URL,
396
487
  init: RequestInit = {},
397
488
  timeoutMs = REST_TIMEOUT_MS,
489
+ bufferBody = false,
398
490
  ): Promise<Response> {
399
491
  const headers: Record<string, string> = { ...(init.headers as Record<string, string> | undefined) };
400
492
  if (TOKEN && !("Authorization" in headers)) headers["Authorization"] = `Bearer ${TOKEN}`;
493
+ if (TOKEN && !(WAKE_ID_HEADER in headers)) {
494
+ const wakeId = resolveEnvWakeId();
495
+ if (wakeId) headers[WAKE_ID_HEADER] = wakeId;
496
+ }
401
497
  const controller = new AbortController();
402
498
  const timer = setTimeout(() => controller.abort(), timeoutMs);
403
499
  try {
404
- return await nativeFetch(input as any, { ...init, headers, signal: init.signal ?? controller.signal });
500
+ const response = await nativeFetch(input as any, { ...init, headers, signal: init.signal ?? controller.signal });
501
+ if (!bufferBody) return response;
502
+ // Keep the abort deadline active until the body is consumed. Headers alone
503
+ // must not mark a stalled JSON response as complete.
504
+ const body = await response.text();
505
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
405
506
  } finally {
406
507
  clearTimeout(timer);
407
508
  }
@@ -454,6 +555,9 @@ if (identity.mode === "profile") {
454
555
  } else {
455
556
  try {
456
557
  profile = readIdentityProfile(profileFile);
558
+ if (codexIdentity && profile.agent_id !== codexIdentity.agentId) {
559
+ throw new Error("Codex tool profile identity mismatch");
560
+ }
457
561
  if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
458
562
  throw new Error("Project agent_id does not match selected profile");
459
563
  }
@@ -468,11 +572,14 @@ if (identity.mode === "profile") {
468
572
  process.exit(1);
469
573
  }
470
574
  const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
471
- const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
575
+ const activeRuntimeSession: DetectedSession | null = (!isOneShotCli && !toolOnlyMode)
576
+ ? ensureRuntimeSession()
577
+ : runtimeSession;
578
+ const lockCheck = (!isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
472
579
  ? checkAgentLock({
473
580
  lockDir,
474
581
  agentId: candidateAgentId,
475
- currentSessionId: runtimeSession?.sessionId ?? null,
582
+ currentSessionId: activeRuntimeSession?.sessionId ?? null,
476
583
  lockOwnerPid,
477
584
  })
478
585
  : { locked: false };
@@ -657,11 +764,12 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
657
764
  }
658
765
  }
659
766
 
660
- if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
767
+ if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
661
768
  let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
662
769
  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);
770
+ const currentRuntimeSession = ensureRuntimeSession();
663
771
  const isImplicitAgyBoot =
664
- (runtimeSession?.runtime === "antigravity" || (!runtimeSession && Boolean(discoverAntigravityHost()))) &&
772
+ (currentRuntimeSession?.runtime === "antigravity" || (!currentRuntimeSession && Boolean(discoverAntigravityHost()))) &&
665
773
  !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
666
774
  if (activeName && isImplicitAgyBoot) {
667
775
  const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
@@ -764,14 +872,83 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
764
872
  }
765
873
 
766
874
  // Authoritative, secret-free status; absent fields never mean unclaimed.
767
- if (cliArgs.registerOnly && !TOKEN) {
875
+ if (isOneShotCli && (!TOKEN || TOKEN === "dev-token")) {
768
876
  process.stderr.write("[agentchat] Select an existing profile or use --name <name> / --register to self-register.\n");
769
877
  process.exit(1);
770
878
  }
879
+ if (cliArgs.join || cliArgs.send || cliArgs.wakeOnce) {
880
+ if (cliArgs.send && !cliArgs.text) {
881
+ process.stderr.write("[agentchat] ERROR: --send <channel> requires --text <message>. See --help.\n");
882
+ process.exit(1);
883
+ }
884
+ if (cliArgs.join && !cliArgs.send && !cliArgs.wakeOnce) {
885
+ const res = await joinChannelRest({
886
+ restUrl: REST_URL,
887
+ agentId: AGENT_ID,
888
+ token: TOKEN,
889
+ channelId: cliArgs.join,
890
+ });
891
+ console.log(JSON.stringify(res));
892
+ process.exit(res.ok ? 0 : 1);
893
+ }
894
+ const explicitMaxIdleMs = parseMaxIdleMs(cliArgs["max-idle"]);
895
+ if (cliArgs.send) {
896
+ if (cliArgs.join) {
897
+ await joinChannelRest({
898
+ restUrl: REST_URL,
899
+ agentId: AGENT_ID,
900
+ token: TOKEN,
901
+ channelId: cliArgs.join,
902
+ });
903
+ }
904
+ const res = await sendRestMessage({
905
+ restUrl: REST_URL,
906
+ configDir,
907
+ agentId: AGENT_ID,
908
+ token: TOKEN,
909
+ channelId: cliArgs.send,
910
+ text: cliArgs.text!,
911
+ replyTo: cliArgs["reply-to"],
912
+ maxIdleMs: explicitMaxIdleMs,
913
+ });
914
+ console.log(JSON.stringify(res));
915
+ process.exit(res.ok ? 0 : 1);
916
+ }
917
+ if (cliArgs.wakeOnce) {
918
+ const rawChans = [
919
+ ...(cliArgs.join ? [cliArgs.join] : []),
920
+ ...(cliArgs.channel ? cliArgs.channel.split(",").map((c) => c.trim()).filter(Boolean) : []),
921
+ ];
922
+ const channels = rawChans.length > 0 ? [...new Set(rawChans)] : ["welcome"];
923
+ const timeoutSec = cliArgs.timeout !== undefined ? Number(cliArgs.timeout) : 240;
924
+ const timeoutMs = Number.isFinite(timeoutSec) && timeoutSec >= 0 ? timeoutSec * 1000 : 240_000;
925
+ const ev = await wakeOnce({
926
+ restUrl: REST_URL,
927
+ configDir,
928
+ agentId: AGENT_ID,
929
+ displayName: profile.display_name || AGENT_ID,
930
+ token: TOKEN,
931
+ channels,
932
+ timeoutMs,
933
+ maxIdleMs: explicitMaxIdleMs,
934
+ });
935
+ console.log(JSON.stringify(ev));
936
+ process.exit(0);
937
+ }
938
+ }
771
939
  if (TOKEN && TOKEN !== "dev-token") {
772
940
  const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
773
941
  process.stderr.write(`[agentchat] ${claimSummary(status)}\n`);
774
942
  if (cliArgs.registerOnly) {
943
+ try {
944
+ mkdirSync(configDir, { recursive: true });
945
+ const lastSeenFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
946
+ const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
947
+ if (!cursor.get(CURSOR_INIT_KEY)) {
948
+ cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
949
+ persistCursor(lastSeenFile, cursor, (m) => process.stderr.write(m));
950
+ }
951
+ } catch {}
775
952
  console.log(JSON.stringify({...status, terms_notice: TERMS_NOTICE, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false}));
776
953
  process.exit(0);
777
954
  }
@@ -925,7 +1102,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
925
1102
  "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.",
926
1103
  "2. Map non-trivial work into OKR tasks, DAG dependencies, or channel docs.",
927
1104
  "3. Store decisions in docs; store sequencing/blockers as depends_on; store progress in task status/comments.",
928
- "4. When closing work, leave evidence: commit hash, deploy build, test result, QA/pentest result, or linked doc.",
1105
+ "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.",
929
1106
  "5. Keep chat updates event-driven and concise: action -> result -> verification -> next owner.",
930
1107
  "",
931
1108
  "Do not create heavy process for one-line clarifications, games, or trivial fixes. Do not treat chat as the durable source of truth.",
@@ -945,7 +1122,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
945
1122
  "",
946
1123
  "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.",
947
1124
  "",
948
- "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).",
1125
+ "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).",
949
1126
  "",
950
1127
  "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.",
951
1128
  "",
@@ -995,11 +1172,18 @@ const CORE_TOOL_NAMES = new Set([
995
1172
  "save_skill",
996
1173
  "sync_skill",
997
1174
  "list_loops",
1175
+ "create_loop",
1176
+ "pause_loop",
1177
+ "resume_loop",
1178
+ "set_loop_interval",
1179
+ "stop_loop",
1180
+ "cloud_agent_wake_health",
998
1181
  "my_entitlements",
999
1182
  "channel_brief",
1000
1183
  "okr_list",
1001
1184
  "load_memory",
1002
1185
  "save_memory",
1186
+ "delete_memory",
1003
1187
  ]);
1004
1188
 
1005
1189
  const META_TOOL_NAMES = new Set([
@@ -1017,12 +1201,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1017
1201
  tools: [
1018
1202
  "okr_list",
1019
1203
  "okr_create_objective",
1204
+ "okr_update_objective",
1020
1205
  "okr_add_task",
1021
1206
  "okr_update_task",
1022
1207
  "okr_task_blockers",
1023
1208
  "okr_task_blocks",
1024
1209
  "okr_open_thread",
1025
1210
  "okr_add_kr",
1211
+ "okr_update_kr",
1026
1212
  "okr_set_kr_progress",
1027
1213
  "okr_add_task_comment",
1028
1214
  "okr_set_links",
@@ -1053,6 +1239,7 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1053
1239
  "react",
1054
1240
  "thread_reply",
1055
1241
  "pin",
1242
+ "list_pins",
1056
1243
  "edit_message",
1057
1244
  "delete_message",
1058
1245
  "archive_channel",
@@ -1063,10 +1250,10 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1063
1250
  },
1064
1251
  {
1065
1252
  name: "notifications",
1066
- summary: "Low-latency collaboration signals and channel metadata updates.",
1067
- tags: ["presence", "collaboration"],
1068
- estimated_tokens: 850,
1069
- tools: ["send_typing", "set_status", "set_topic", "propose", "vote"],
1253
+ summary: "Low-latency collaboration signals, channel metadata updates, and room proposal/consensus voting.",
1254
+ tags: ["presence", "collaboration", "proposals"],
1255
+ estimated_tokens: 950,
1256
+ tools: ["send_typing", "set_status", "set_topic", "list_proposals", "propose", "vote"],
1070
1257
  },
1071
1258
  {
1072
1259
  name: "forward_search",
@@ -1077,13 +1264,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1077
1264
  },
1078
1265
  {
1079
1266
  name: "channel_docs",
1080
- summary: "Channel documentation: rules, roles, context and deep-dive notes.",
1081
- tags: ["docs", "context"],
1082
- estimated_tokens: 900,
1267
+ summary: "Channel documentation & shared room skills: rules, roles, context, deep-dive notes, non-destructive CAS archiving, and revision history.",
1268
+ tags: ["docs", "context", "skills"],
1269
+ estimated_tokens: 1050,
1083
1270
  tools: [
1084
1271
  "list_channel_docs",
1085
1272
  "get_channel_doc",
1086
1273
  "upsert_channel_doc",
1274
+ "archive_channel_doc",
1087
1275
  "list_channel_doc_revisions",
1088
1276
  ],
1089
1277
  },
@@ -1287,6 +1475,17 @@ const ALL_TOOL_DEFS = [
1287
1475
  required: ["chat_id", "message_id"],
1288
1476
  },
1289
1477
  },
1478
+ {
1479
+ name: "list_pins",
1480
+ description: "List active pinned message IDs for a channel via GET /api/channels/:id/pins (deleted messages are automatically excluded).",
1481
+ inputSchema: {
1482
+ type: "object" as const,
1483
+ properties: {
1484
+ chat_id: { type: "string", description: "The channel_id" },
1485
+ },
1486
+ required: ["chat_id"],
1487
+ },
1488
+ },
1290
1489
  {
1291
1490
  name: "edit_message",
1292
1491
  description: "Edit a previously sent message.",
@@ -1410,12 +1609,25 @@ const ALL_TOOL_DEFS = [
1410
1609
  required: ["query"],
1411
1610
  },
1412
1611
  },
1612
+ {
1613
+ name: "list_proposals",
1614
+ description: "List room proposals and current consensus vote tallies in a channel.",
1615
+ inputSchema: {
1616
+ type: "object" as const,
1617
+ properties: {
1618
+ chat_id: { type: "string", description: "The channel_id to inspect proposals in" },
1619
+ status: { type: "string", enum: ["all", "pending", "passed", "rejected"], description: "Optional status filter (default: all)" },
1620
+ },
1621
+ required: ["chat_id"],
1622
+ },
1623
+ },
1413
1624
  {
1414
1625
  name: "vote",
1415
- description: "Cast a vote on a proposal (approve, reject, or abstain).",
1626
+ description: "Cast a vote on a proposal (approve, reject, or abstain). Pass chat_id for synchronous REST vote tally, with automatic WebSocket fallback.",
1416
1627
  inputSchema: {
1417
1628
  type: "object" as const,
1418
1629
  properties: {
1630
+ chat_id: { type: "string", description: "Optional channel_id for synchronous REST vote tally (falls back to WebSocket if omitted)" },
1419
1631
  proposal_id: { type: "string", description: "ID of the proposal to vote on" },
1420
1632
  decision: { type: "string", enum: ["approve", "reject", "abstain"], description: "Your vote decision" },
1421
1633
  reason: { type: "string", description: "Optional reason for your vote" },
@@ -1425,7 +1637,7 @@ const ALL_TOOL_DEFS = [
1425
1637
  },
1426
1638
  {
1427
1639
  name: "propose",
1428
- description: "Create a new proposal for agents to vote on.",
1640
+ description: "Create a new proposal for agents to vote on (REST-first with synchronous confirmation and automatic WebSocket fallback).",
1429
1641
  inputSchema: {
1430
1642
  type: "object" as const,
1431
1643
  properties: {
@@ -1434,6 +1646,7 @@ const ALL_TOOL_DEFS = [
1434
1646
  content: { type: "string", description: "Proposal description/body" },
1435
1647
  code_diff: { type: "string", description: "Optional code diff for code review proposals" },
1436
1648
  consensus_rule: { type: "string", enum: ["majority", "super_majority", "unanimous"], description: "Voting rule (default: majority)" },
1649
+ expires_at: { type: "string", description: "Optional ISO-8601 expiration timestamp" },
1437
1650
  },
1438
1651
  required: ["chat_id", "title", "content"],
1439
1652
  },
@@ -1535,65 +1748,87 @@ const ALL_TOOL_DEFS = [
1535
1748
  },
1536
1749
  {
1537
1750
  name: "list_skills",
1538
- 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.",
1751
+ 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.",
1539
1752
  inputSchema: {
1540
1753
  type: "object" as const,
1541
1754
  properties: {
1542
1755
  chat_id: { type: "string", description: "Optional channel_id — also lists that channel's skill docs" },
1756
+ active_only: { type: "boolean", description: "Exclude soft-archived tombstones (default: true). Pass false to include archived skills." },
1543
1757
  },
1544
1758
  },
1545
1759
  },
1546
1760
  {
1547
1761
  name: "load_skill",
1548
- 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).",
1762
+ 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.",
1549
1763
  inputSchema: {
1550
1764
  type: "object" as const,
1551
1765
  properties: {
1552
1766
  skill_id: { type: "string", description: "Global skill id (default: workspace-driven-eng)" },
1767
+ name: { type: "string", description: "Personal skill slug (per-owner, from list_skills.personal_skills)" },
1553
1768
  chat_id: { type: "string", description: "Channel id (for a channel skill, paired with doc_id)" },
1554
1769
  doc_id: { type: "string", description: "Channel doc id to load as a skill (paired with chat_id)" },
1770
+ include_revisions: { type: "boolean", description: "When true, also fetch revision history for a personal or channel skill" },
1555
1771
  },
1556
1772
  },
1557
1773
  },
1558
1774
  {
1559
1775
  name: "save_skill",
1560
- 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.",
1776
+ 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.",
1561
1777
  inputSchema: {
1562
1778
  type: "object" as const,
1563
1779
  properties: {
1564
1780
  chat_id: { type: "string", description: "Channel to save into (CHANNEL skill). OMIT for a PERSONAL skill (per-owner, follows you across agents)." },
1565
1781
  name: { type: "string", description: "Skill name (short)" },
1566
- description: { type: "string", description: "One line: what it does / when to use it" },
1782
+ description: { type: "string", description: "One line: what it does / when to use it (required unless archived=true)" },
1567
1783
  body: { type: "string", description: "The skill content in markdown — the instructions an agent follows" },
1568
- doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update." },
1784
+ trigger: { type: "string", description: "Optional slash trigger hint (e.g. '/deploy') stored in YAML frontmatter" },
1785
+ argument_hint: { type: "string", description: "Optional argument hint (e.g. '[target]') stored in YAML frontmatter" },
1786
+ doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update or archive." },
1569
1787
  level: { type: "number", description: "CHANNEL only: doc tier 1-4 (default 3 = any member may write; 1-2 require channel admin)" },
1788
+ 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)." },
1789
+ archived: { type: "boolean", description: "Pass true with a positive if_match_version to non-destructively soft-archive (keeps revisions intact and frees active quota)." },
1570
1790
  },
1571
- required: ["name", "description"],
1791
+ required: ["name"],
1572
1792
  },
1573
1793
  },
1574
1794
  {
1575
1795
  name: "load_memory",
1576
- 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.",
1796
+ 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.",
1577
1797
  inputSchema: {
1578
1798
  type: "object" as const,
1579
1799
  properties: {
1580
1800
  name: { type: "string", description: "A specific memory doc to load in full (omit to get the lean index of all your memory docs)" },
1801
+ 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)." },
1581
1802
  },
1582
1803
  },
1583
1804
  },
1584
1805
  {
1585
1806
  name: "save_memory",
1586
- 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).",
1807
+ 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.",
1587
1808
  inputSchema: {
1588
1809
  type: "object" as const,
1589
1810
  properties: {
1590
1811
  name: { type: "string", description: "Memory doc name/slug (e.g. 'index', 'context', 'lessons'). Reuse to update." },
1591
1812
  body: { type: "string", description: "The memory content in markdown (freeform)." },
1592
1813
  description: { type: "string", description: "Optional one-line index hook; auto-summarized from body if omitted." },
1814
+ 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." },
1593
1815
  },
1594
1816
  required: ["name", "body"],
1595
1817
  },
1596
1818
  },
1819
+ {
1820
+ name: "delete_memory",
1821
+ 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.",
1822
+ inputSchema: {
1823
+ type: "object" as const,
1824
+ properties: {
1825
+ name: { type: "string", description: "Memory doc name/slug to delete (1..64 safe chars)" },
1826
+ if_match_version: { type: "integer", minimum: 1, maximum: 1000000, description: "Optional CAS guard: delete only if stored note matches this exact version" },
1827
+ allow_missing: { type: "boolean", description: "When true, return { ok: true, deleted: false } instead of an error if the note is already absent" },
1828
+ },
1829
+ required: ["name"],
1830
+ },
1831
+ },
1597
1832
  {
1598
1833
  name: "sync_skill",
1599
1834
  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.",
@@ -1646,10 +1881,11 @@ const ALL_TOOL_DEFS = [
1646
1881
  },
1647
1882
  {
1648
1883
  name: "list_channels",
1649
- 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.",
1884
+ 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.",
1650
1885
  inputSchema: {
1651
1886
  type: "object" as const,
1652
1887
  properties: {
1888
+ query: { type: "string", description: "Optional search keyword matching channel name, topic, or online agent capabilities" },
1653
1889
  limit: { type: "number", description: "Max results (default 50)" },
1654
1890
  },
1655
1891
  },
@@ -1675,10 +1911,104 @@ const ALL_TOOL_DEFS = [
1675
1911
  required: ["target_agent_id"],
1676
1912
  },
1677
1913
  },
1914
+ {
1915
+ name: "create_loop",
1916
+ 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.",
1917
+ inputSchema: {
1918
+ type: "object" as const,
1919
+ properties: {
1920
+ channel_id: { type: "string", description: "Target channel_id (group/project room for okr_wake/okr_watch; group or owner-agent DM for prompt)" },
1921
+ mode: {
1922
+ type: "string",
1923
+ enum: [...CREATE_LOOP_MODES],
1924
+ description: "okr_wake (zero-cost DAG dependency-clear/assignee wake), okr_watch (stalled-progress watch), or prompt (periodic tick)",
1925
+ },
1926
+ interval: { type: "string", description: "Cadence shorthand like 5m, 15m, 30m, 1h (1m..24h; defaults to 5m when interval_ms omitted)" },
1927
+ interval_ms: {
1928
+ type: "integer",
1929
+ minimum: 60000,
1930
+ maximum: 86400000,
1931
+ description: "Optional cadence in milliseconds (integer 60000..86400000)",
1932
+ },
1933
+ objective_id: { type: "string", description: "Required when mode is okr_wake or okr_watch: active Objective ID anchored to channel_id" },
1934
+ prompt: { type: "string", description: "Required when mode is prompt: plain periodic tick prompt (max 500 chars; no secrets)" },
1935
+ target_agents: {
1936
+ type: "array",
1937
+ items: { type: "string" },
1938
+ description: "Optional @target agent handles (max 12) for group loops",
1939
+ },
1940
+ watch_idle: { type: "boolean", description: "okr_watch only: also alert when all tasks sit idle in todo with zero doing" },
1941
+ watch_supply: { type: "boolean", description: "okr_watch only: also alert when all tasks are done (task-supply exhausted)" },
1942
+ stall_minutes: { type: "integer", minimum: 5, maximum: 1440, description: "okr_watch only: base silent stall threshold in minutes (integer 5..1440, default 5)" },
1943
+ },
1944
+ required: ["channel_id", "mode"],
1945
+ },
1946
+ },
1678
1947
  {
1679
1948
  name: "list_loops",
1680
- 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.",
1681
- inputSchema: { type: "object" as const, properties: {} },
1949
+ 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.",
1950
+ inputSchema: {
1951
+ type: "object" as const,
1952
+ properties: {
1953
+ channel_id: { type: "string", description: "Optional channel_id filter" },
1954
+ status: { type: "string", enum: ["active", "paused"], description: "Optional status filter (active or paused)" },
1955
+ mode: { type: "string", enum: [...CREATE_LOOP_MODES], description: "Optional mode filter (okr_wake, okr_watch, or prompt)" },
1956
+ objective_id: { type: "string", description: "Optional target objective_id filter" },
1957
+ },
1958
+ },
1959
+ },
1960
+ {
1961
+ name: "pause_loop",
1962
+ 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.",
1963
+ inputSchema: {
1964
+ type: "object" as const,
1965
+ properties: { loop_id: { type: "string", description: "The loop_id to pause" } },
1966
+ required: ["loop_id"],
1967
+ },
1968
+ },
1969
+ {
1970
+ name: "resume_loop",
1971
+ 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.",
1972
+ inputSchema: {
1973
+ type: "object" as const,
1974
+ properties: { loop_id: { type: "string", description: "The loop_id to resume" } },
1975
+ required: ["loop_id"],
1976
+ },
1977
+ },
1978
+ {
1979
+ name: "set_loop_interval",
1980
+ 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.",
1981
+ inputSchema: {
1982
+ type: "object" as const,
1983
+ properties: {
1984
+ loop_id: { type: "string", description: "The loop_id to update" },
1985
+ interval_ms: {
1986
+ type: "integer",
1987
+ minimum: 60000,
1988
+ maximum: 86400000,
1989
+ description: "New interval in milliseconds (integer 60000..86400000)",
1990
+ },
1991
+ },
1992
+ required: ["loop_id", "interval_ms"],
1993
+ },
1994
+ },
1995
+ {
1996
+ name: "stop_loop",
1997
+ 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.",
1998
+ inputSchema: {
1999
+ type: "object" as const,
2000
+ properties: { loop_id: { type: "string", description: "The loop_id to permanently stop" } },
2001
+ required: ["loop_id"],
2002
+ },
2003
+ },
2004
+ {
2005
+ name: "cloud_agent_wake_health",
2006
+ 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.",
2007
+ inputSchema: {
2008
+ type: "object" as const,
2009
+ properties: { channel_id: { type: "string", description: "The authorized channel_id" } },
2010
+ required: ["channel_id"],
2011
+ },
1682
2012
  },
1683
2013
  {
1684
2014
  name: "my_entitlements",
@@ -1687,7 +2017,7 @@ const ALL_TOOL_DEFS = [
1687
2017
  },
1688
2018
  {
1689
2019
  name: "channel_brief",
1690
- 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.",
2020
+ 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.",
1691
2021
  inputSchema: {
1692
2022
  type: "object" as const,
1693
2023
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1741,7 +2071,7 @@ const ALL_TOOL_DEFS = [
1741
2071
  },
1742
2072
  {
1743
2073
  name: "okr_create_objective",
1744
- 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.",
2074
+ 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).",
1745
2075
  inputSchema: {
1746
2076
  type: "object" as const,
1747
2077
  properties: {
@@ -1751,21 +2081,79 @@ const ALL_TOOL_DEFS = [
1751
2081
  parent_id: { type: "string", description: "Optional parent Objective id for hierarchical OKRs (max 3 layers deep)" },
1752
2082
  due: { type: "string", description: "ISO-8601 due date (e.g. 2026-05-19)" },
1753
2083
  discussion_channel_id: { type: "string", description: "Optional existing channel id to anchor this objective into Workspace Graph / channel insights" },
2084
+ narrative: { type: "string", description: "Optional inline WHY summary (<=2000 chars; never include secrets)" },
2085
+ linked_channel_docs: {
2086
+ type: "array",
2087
+ maxItems: 10,
2088
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires discussion_channel_id matching channel_id).",
2089
+ items: {
2090
+ type: "object",
2091
+ properties: {
2092
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match discussion_channel_id)" },
2093
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2094
+ },
2095
+ required: ["channel_id", "doc_id"],
2096
+ },
2097
+ },
1754
2098
  },
1755
2099
  required: ["title", "horizon"],
1756
2100
  },
1757
2101
  },
2102
+ {
2103
+ name: "okr_update_objective",
2104
+ 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.",
2105
+ inputSchema: {
2106
+ type: "object" as const,
2107
+ properties: {
2108
+ objective_id: { type: "string", description: "Objective id to update" },
2109
+ title: { type: "string", description: "Updated Objective title (1..200 chars)" },
2110
+ status: { type: "string", enum: ["active", "done", "abandoned"], description: "Updated lifecycle status" },
2111
+ horizon: { type: "string", enum: ["week", "month", "Q"], description: "Updated planning horizon" },
2112
+ due: { type: "string", description: "Updated ISO-8601 due date/timestamp (<=32 chars); pass empty string to clear" },
2113
+ narrative: { type: "string", description: "Updated inline WHY summary (<=2000 chars); pass empty string to clear" },
2114
+ completion_summary: { type: "string", description: "Updated wrap-up summary (<=280 chars); pass empty string to clear" },
2115
+ linked_channel_docs: {
2116
+ type: "array",
2117
+ maxItems: 10,
2118
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear). Requires the Objective to be anchored to that discussion channel.",
2119
+ items: {
2120
+ type: "object",
2121
+ properties: {
2122
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
2123
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2124
+ },
2125
+ required: ["channel_id", "doc_id"],
2126
+ },
2127
+ },
2128
+ 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." },
2129
+ },
2130
+ required: ["objective_id"],
2131
+ },
2132
+ },
1758
2133
  {
1759
2134
  name: "okr_add_task",
1760
- 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.",
2135
+ 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.",
1761
2136
  inputSchema: {
1762
2137
  type: "object" as const,
1763
2138
  properties: {
1764
2139
  objective_id: { type: "string", description: "Parent Objective id" },
1765
2140
  title: { type: "string", description: "Task title (max 200 chars)" },
1766
- assignee: { type: "string", description: "Agent/account id to assign the task to" },
1767
- contributes_to: { type: "array", items: { type: "string" }, description: "Optional KR ids this task advances" },
1768
- 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." },
2141
+ assignee: { type: "string", description: "Agent handle to assign the task to (never an email address)" },
2142
+ contributes_to: { type: "array", maxItems: 5, items: { type: "string" }, description: "Optional KR ids (0..5) on the Objective that this task advances" },
2143
+ 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." },
2144
+ linked_channel_docs: {
2145
+ type: "array",
2146
+ maxItems: 10,
2147
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires the Objective to be anchored to that discussion channel).",
2148
+ items: {
2149
+ type: "object",
2150
+ properties: {
2151
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
2152
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2153
+ },
2154
+ required: ["channel_id", "doc_id"],
2155
+ },
2156
+ },
1769
2157
  due: { type: "string", description: "ISO-8601 due date" },
1770
2158
  },
1771
2159
  required: ["objective_id", "title", "assignee"],
@@ -1773,17 +2161,90 @@ const ALL_TOOL_DEFS = [
1773
2161
  },
1774
2162
  {
1775
2163
  name: "okr_update_task",
1776
- 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.",
2164
+ 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.",
1777
2165
  inputSchema: {
1778
2166
  type: "object" as const,
1779
2167
  properties: {
1780
2168
  task_id: { type: "string", description: "Task id to update" },
2169
+ title: { type: "string", maxLength: 200, description: "Updated task title (1..200 chars; never include secrets)" },
1781
2170
  status: { type: "string", enum: ["todo", "doing", "done", "blocked"], description: "New status" },
1782
- assignee: { type: "string", description: "Re-assign to another agent (owner/admin only)" },
2171
+ assignee: { type: "string", description: "Re-assign to another agent handle (Objective owner/admin only; never an email address)" },
2172
+ contributes_to: {
2173
+ type: "array",
2174
+ maxItems: 5,
2175
+ items: { type: "string" },
2176
+ description: "Replacement Key Result IDs (0..5) on the Objective tree that this task advances (Objective owner/admin only; pass [] to clear).",
2177
+ },
1783
2178
  blocked_reason: { type: "string", description: "Why is this task blocked (max 500 chars)" },
1784
2179
  blocker_agent: { type: "string", description: "Which agent is blocking this task" },
1785
- 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." },
1786
- due: { type: "string", description: "ISO-8601 due date" },
2180
+ 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." },
2181
+ linked_channel_docs: {
2182
+ type: "array",
2183
+ maxItems: 10,
2184
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear).",
2185
+ items: {
2186
+ type: "object",
2187
+ properties: {
2188
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match task/Objective discussion_channel_id)" },
2189
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" },
2190
+ },
2191
+ required: ["channel_id", "doc_id"],
2192
+ },
2193
+ },
2194
+ due: { type: "string", maxLength: 32, description: "ISO-8601 due date/timestamp (<=32 chars), or pass empty string \"\" to clear" },
2195
+ evidence: {
2196
+ type: "array",
2197
+ maxItems: 10,
2198
+ description: "Full-replacement structured completion receipts (max 10; pass [] to clear). Mutually exclusive with append_evidence.",
2199
+ items: {
2200
+ type: "object",
2201
+ properties: {
2202
+ kind: {
2203
+ type: "string",
2204
+ enum: [...TASK_EVIDENCE_KINDS],
2205
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout",
2206
+ },
2207
+ ref: {
2208
+ type: "string",
2209
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)",
2210
+ },
2211
+ note: {
2212
+ type: "string",
2213
+ description: "Optional concise context note (<=200 chars, never secrets)",
2214
+ },
2215
+ },
2216
+ required: ["kind", "ref"],
2217
+ },
2218
+ },
2219
+ append_evidence: {
2220
+ type: "array",
2221
+ minItems: 1,
2222
+ maxItems: 10,
2223
+ description: "Atomically append/deduplicate structured completion receipts (1..10 items) without overwriting existing history; mutually exclusive with evidence.",
2224
+ items: {
2225
+ type: "object",
2226
+ properties: {
2227
+ kind: {
2228
+ type: "string",
2229
+ enum: [...TASK_EVIDENCE_KINDS],
2230
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout",
2231
+ },
2232
+ ref: {
2233
+ type: "string",
2234
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)",
2235
+ },
2236
+ note: {
2237
+ type: "string",
2238
+ description: "Optional concise context note (<=200 chars, never secrets)",
2239
+ },
2240
+ },
2241
+ required: ["kind", "ref"],
2242
+ },
2243
+ },
2244
+ if_match_updated_at: {
2245
+ type: "string",
2246
+ description: "Optional optimistic concurrency guard (task.updated_at). Rejects with 409 stale_task_version if the task changed concurrently.",
2247
+ },
1787
2248
  },
1788
2249
  required: ["task_id"],
1789
2250
  },
@@ -1838,14 +2299,31 @@ const ALL_TOOL_DEFS = [
1838
2299
  required: ["objective_id", "title", "metric_type", "target"],
1839
2300
  },
1840
2301
  },
2302
+ {
2303
+ name: "okr_update_kr",
2304
+ 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).",
2305
+ inputSchema: {
2306
+ type: "object" as const,
2307
+ properties: {
2308
+ kr_id: { type: "string", description: "KR id to revise" },
2309
+ title: { type: "string", maxLength: 200, description: "Updated KR title (1..200 chars; never include secrets)" },
2310
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Updated metric shape (bool requires target/current in {0,1}; percent <= 100)" },
2311
+ target: { type: "number", description: "Updated target value (0..1000000; bool: 0 or 1; percent: <= 100)" },
2312
+ current: { type: "number", description: "Optional updated current value (0..1000000; bool: 0 or 1; percent: <= 100)" },
2313
+ risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Optional updated risk self-assessment" },
2314
+ if_match_updated_at: { type: "string", description: "Optional optimistic concurrency guard (kr.updated_at). Rejects with 409 stale_kr_version if modified concurrently." },
2315
+ },
2316
+ required: ["kr_id"],
2317
+ },
2318
+ },
1841
2319
  {
1842
2320
  name: "archive_objective",
1843
- description: "Archive one completed objective into the collapsed archived view. Objective-level only in v1.",
2321
+ 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.",
1844
2322
  inputSchema: {
1845
2323
  type: "object" as const,
1846
2324
  properties: {
1847
2325
  objective_id: { type: "string", description: "Objective id to archive" },
1848
- completion_summary: { type: "string", description: "Optional short completion summary (recommended ≤280 chars)" },
2326
+ completion_summary: { type: "string", maxLength: 280, description: "Optional short completion summary (max 280 chars; never include secrets)" },
1849
2327
  },
1850
2328
  required: ["objective_id"],
1851
2329
  },
@@ -1863,27 +2341,32 @@ const ALL_TOOL_DEFS = [
1863
2341
  },
1864
2342
  {
1865
2343
  name: "okr_reparent_objective",
1866
- 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.",
2344
+ 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).",
1867
2345
  inputSchema: {
1868
2346
  type: "object" as const,
1869
2347
  properties: {
1870
2348
  objective_id: { type: "string", description: "Your objective's id to move" },
1871
- 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)." },
2349
+ 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." },
2350
+ 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)" },
1872
2351
  },
1873
2352
  required: ["objective_id"],
1874
2353
  },
1875
2354
  },
1876
2355
  {
1877
2356
  name: "okr_set_kr_progress",
1878
- 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.",
2357
+ 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.",
1879
2358
  inputSchema: {
1880
2359
  type: "object" as const,
1881
2360
  properties: {
1882
2361
  kr_id: { type: "string", description: "KR id to update" },
1883
- current: { type: "number", description: "New current value. bool: 0/1 only. percent: ≤100." },
2362
+ current: { type: "number", description: "New current value (0..1000000; bool: 0/1 only; percent: <=100)" },
1884
2363
  risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Update risk self-assessment" },
2364
+ title: { type: "string", maxLength: 200, description: "Optional KR title revision (1..200 chars; Objective steward only)" },
2365
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Optional metric_type revision (Objective steward only)" },
2366
+ target: { type: "number", description: "Optional target value revision (0..1000000; Objective steward only)" },
2367
+ 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)" },
1885
2368
  },
1886
- required: ["kr_id", "current"],
2369
+ required: ["kr_id"],
1887
2370
  },
1888
2371
  },
1889
2372
  {
@@ -1926,6 +2409,7 @@ const ALL_TOOL_DEFS = [
1926
2409
  required: ["channel_id", "doc_id"],
1927
2410
  },
1928
2411
  },
2412
+ 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." },
1929
2413
  },
1930
2414
  required: ["target_type", "target_id"],
1931
2415
  },
@@ -1969,12 +2453,13 @@ const ALL_TOOL_DEFS = [
1969
2453
  },
1970
2454
  {
1971
2455
  name: "list_channel_docs",
1972
- description: "List documentation entries for a channel. Returns lightweight metadata and summaries, not full bodies.",
2456
+ 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.",
1973
2457
  inputSchema: {
1974
2458
  type: "object" as const,
1975
2459
  properties: {
1976
2460
  chat_id: { type: "string", description: "The channel_id" },
1977
2461
  level: { type: "number", description: "Optional level filter (1-4)" },
2462
+ active_only: { type: "boolean", description: "When true, omit soft-archived tombstones (bodyMarkdown === '')" },
1978
2463
  },
1979
2464
  required: ["chat_id"],
1980
2465
  },
@@ -1993,24 +2478,38 @@ const ALL_TOOL_DEFS = [
1993
2478
  },
1994
2479
  {
1995
2480
  name: "upsert_channel_doc",
1996
- description: "Create or update a channel doc. Use If-Match style version semantics via expected_version.",
2481
+ 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.",
1997
2482
  inputSchema: {
1998
2483
  type: "object" as const,
1999
2484
  properties: {
2000
2485
  chat_id: { type: "string", description: "The channel_id" },
2001
- doc_id: { type: "string", description: "The doc id" },
2002
- title: { type: "string", description: "Doc title" },
2003
- kind: { type: "string", enum: ["topic", "rules", "roles", "context", "deep_dive"], description: "Doc semantic kind" },
2004
- level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level" },
2005
- body_markdown: { type: "string", description: "Markdown body" },
2006
- expected_version: { type: "number", description: "Use 0 to create, or the current version to update" },
2486
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
2487
+ title: { type: "string", description: "Doc title (required unless archived=true)" },
2488
+ kind: { type: "string", enum: [...CHANNEL_DOC_KINDS], description: "Doc semantic kind (required unless archived=true)" },
2489
+ level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level (default 3; L1/L2 require moderator)" },
2490
+ body_markdown: { type: "string", description: "Markdown body (required unless archived=true)" },
2491
+ expected_version: { type: "number", description: "Use 0 to create, or the current positive version to update/archive (If-Match CAS)" },
2492
+ archived: { type: "boolean", description: "Optional: pass true with positive expected_version to non-destructively soft-archive while preserving revisions[]" },
2007
2493
  },
2008
- required: ["chat_id", "doc_id", "title", "kind", "level", "body_markdown", "expected_version"],
2494
+ required: ["chat_id", "doc_id", "expected_version"],
2495
+ },
2496
+ },
2497
+ {
2498
+ name: "archive_channel_doc",
2499
+ 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.",
2500
+ inputSchema: {
2501
+ type: "object" as const,
2502
+ properties: {
2503
+ chat_id: { type: "string", description: "The channel_id" },
2504
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
2505
+ expected_version: { type: "number", minimum: 1, description: "Current positive document version for If-Match optimistic concurrency" },
2506
+ },
2507
+ required: ["chat_id", "doc_id", "expected_version"],
2009
2508
  },
2010
2509
  },
2011
2510
  {
2012
2511
  name: "list_channel_doc_revisions",
2013
- description: "List revisions for a channel doc to inspect edit history.",
2512
+ description: "List retained historical revisions for a channel doc (including soft-archived tombstones) to inspect or restore prior versions.",
2014
2513
  inputSchema: {
2015
2514
  type: "object" as const,
2016
2515
  properties: {
@@ -2142,20 +2641,16 @@ HANDLERS.set("send_typing", async (args) => {
2142
2641
  });
2143
2642
 
2144
2643
  HANDLERS.set("okr_reparent_objective", async (args) => {
2145
- const { objective_id, parent_id } = (args || {}) as { objective_id?: string; parent_id?: string | null };
2146
- if (!objective_id) {
2147
- return { content: [{ type: "text", text: "okr_reparent_objective needs objective_id." }], isError: true };
2148
- }
2149
- // parent_id must be PRESENT (a string to attach under, or explicit null to
2150
- // detach to a root). Absent ≠ null — we don't silently detach on omission.
2151
- if (!(args && typeof args === "object" && "parent_id" in args)) {
2152
- 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 };
2644
+ const validated = validateOkrReparentObjectiveInput(args);
2645
+ if (!validated.ok) {
2646
+ return { content: [{ type: "text", text: `okr_reparent_objective invalid arguments: ${validated.error}` }], isError: true };
2153
2647
  }
2648
+ const { objective_id, body } = validated.value;
2154
2649
  try {
2155
2650
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/parent`, {
2156
2651
  method: "PATCH",
2157
2652
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2158
- body: JSON.stringify({ parent_id: parent_id ?? null }),
2653
+ body: JSON.stringify(body),
2159
2654
  });
2160
2655
  const text = await r.text();
2161
2656
  if (!r.ok) {
@@ -2167,6 +2662,629 @@ HANDLERS.set("okr_reparent_objective", async (args) => {
2167
2662
  }
2168
2663
  });
2169
2664
 
2665
+ async function setLoopPaused(args: any, action: "pause" | "resume") {
2666
+ const loopId = String(args?.loop_id || "");
2667
+ try {
2668
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/${action}`, {
2669
+ method: "POST",
2670
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2671
+ });
2672
+ const text = await r.text();
2673
+ if (!r.ok) {
2674
+ return { content: [{ type: "text", text: `${action}_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2675
+ }
2676
+ JSON.parse(text);
2677
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2678
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2679
+ });
2680
+ if (!verified.ok) {
2681
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2682
+ }
2683
+ const state = await verified.json() as any;
2684
+ const loop = Array.isArray(state?.loops)
2685
+ ? state.loops.find((candidate: any) => candidate?.loop_id === loopId)
2686
+ : undefined;
2687
+ if (!loop) {
2688
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but loop ${loopId} was absent from state verification; use list_loops before retrying.` }], isError: true };
2689
+ }
2690
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2691
+ const active = loop.paused === false || loop.paused_at === null;
2692
+ return {
2693
+ content: [{
2694
+ type: "text",
2695
+ text: JSON.stringify({
2696
+ ok: true,
2697
+ loop_id: loop.loop_id || loopId,
2698
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2699
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2700
+ }),
2701
+ }],
2702
+ };
2703
+ } catch (e: any) {
2704
+ return { content: [{ type: "text", text: `${action}_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2705
+ }
2706
+ }
2707
+
2708
+ HANDLERS.set("create_loop", async (args) => {
2709
+ const checked = validateCreateLoopInput(args);
2710
+ if (!checked.ok) {
2711
+ return { content: [{ type: "text", text: checked.error }], isError: true };
2712
+ }
2713
+ try {
2714
+ const r = await apiFetch(`${REST_URL}/api/loops`, {
2715
+ method: "POST",
2716
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2717
+ body: JSON.stringify(checked.value),
2718
+ });
2719
+ const text = await r.text();
2720
+ if (!r.ok) {
2721
+ return { content: [{ type: "text", text: `create_loop failed (${r.status}): ${text.slice(0, 220)}` }], isError: true };
2722
+ }
2723
+ const createdPayload = JSON.parse(text) as any;
2724
+ const createdLoopId = String(createdPayload?.loop?.loop_id || "").trim();
2725
+ if (!isSafeLoopIdentifier(createdLoopId)) {
2726
+ return {
2727
+ content: [{ type: "text", text: "create_loop returned an invalid loop_id; use list_loops before retrying." }],
2728
+ isError: true,
2729
+ };
2730
+ }
2731
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2732
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2733
+ });
2734
+ if (!verified.ok) {
2735
+ return {
2736
+ content: [{ type: "text", text: `create_loop was accepted (${createdLoopId}), but state verification failed (${verified.status}); use list_loops before retrying.` }],
2737
+ isError: true,
2738
+ };
2739
+ }
2740
+ const state = await verified.json() as any;
2741
+ if (!Array.isArray(state?.loops)) {
2742
+ return {
2743
+ content: [{ type: "text", text: "create_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }],
2744
+ isError: true,
2745
+ };
2746
+ }
2747
+ const loop = state.loops.find((candidate: any) => candidate?.loop_id === createdLoopId);
2748
+ if (!loop) {
2749
+ return {
2750
+ content: [{ type: "text", text: `create_loop was accepted, but loop ${createdLoopId} was absent from state verification; use list_loops before retrying.` }],
2751
+ isError: true,
2752
+ };
2753
+ }
2754
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2755
+ const active = loop.paused === false || loop.paused_at === null;
2756
+ return {
2757
+ content: [{
2758
+ type: "text",
2759
+ text: JSON.stringify({
2760
+ ok: true,
2761
+ deduplicated: Boolean(createdPayload?.deduplicated),
2762
+ loop: {
2763
+ loop_id: loop.loop_id || createdLoopId,
2764
+ channel_id: loop.channel_id || checked.value.channel_id,
2765
+ mode: loop.mode || (checked.value.mode === "prompt" ? "static" : checked.value.mode),
2766
+ ...(loop.objective_id ? { objective_id: loop.objective_id } : {}),
2767
+ interval_ms: loop.interval_ms,
2768
+ ...(Array.isArray(loop.target_agents) ? { target_agents: loop.target_agents } : {}),
2769
+ ...(typeof loop.watch_idle === "boolean" ? { watch_idle: loop.watch_idle } : {}),
2770
+ ...(typeof loop.watch_supply === "boolean" ? { watch_supply: loop.watch_supply } : {}),
2771
+ ...(typeof loop.stall_minutes === "number" ? { stall_minutes: loop.stall_minutes } : {}),
2772
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2773
+ paused,
2774
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2775
+ },
2776
+ }),
2777
+ }],
2778
+ };
2779
+ } catch (e: any) {
2780
+ return { content: [{ type: "text", text: `create_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2781
+ }
2782
+ });
2783
+
2784
+ HANDLERS.set("pause_loop", (args) => setLoopPaused(args, "pause"));
2785
+ HANDLERS.set("resume_loop", (args) => setLoopPaused(args, "resume"));
2786
+
2787
+ const LOOP_INTERVAL_MIN_MS = 60_000;
2788
+ const LOOP_INTERVAL_MAX_MS = 86_400_000;
2789
+
2790
+ function isSafeLoopIdentifier(loopId: string): boolean {
2791
+ return /^[A-Za-z0-9_.:-]{1,128}$/.test(loopId) && !loopId.includes("..");
2792
+ }
2793
+
2794
+ HANDLERS.set("set_loop_interval", async (args) => {
2795
+ const loopId = String(args?.loop_id || "").trim();
2796
+ const intervalMs = args?.interval_ms;
2797
+ if (!isSafeLoopIdentifier(loopId)) {
2798
+ return { content: [{ type: "text", text: "set_loop_interval needs a valid loop_id." }], isError: true };
2799
+ }
2800
+ if (!Number.isSafeInteger(intervalMs) || intervalMs < LOOP_INTERVAL_MIN_MS || intervalMs > LOOP_INTERVAL_MAX_MS) {
2801
+ return {
2802
+ content: [{ type: "text", text: `set_loop_interval needs integer interval_ms in ${LOOP_INTERVAL_MIN_MS}..${LOOP_INTERVAL_MAX_MS} (1m..24h).` }],
2803
+ isError: true,
2804
+ };
2805
+ }
2806
+ try {
2807
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/interval`, {
2808
+ method: "POST",
2809
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2810
+ body: JSON.stringify({ interval_ms: intervalMs }),
2811
+ });
2812
+ const text = await r.text();
2813
+ if (!r.ok) {
2814
+ return { content: [{ type: "text", text: `set_loop_interval failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2815
+ }
2816
+ JSON.parse(text);
2817
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2818
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2819
+ });
2820
+ if (!verified.ok) {
2821
+ return { content: [{ type: "text", text: `set_loop_interval was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2822
+ }
2823
+ const state = await verified.json() as any;
2824
+ const loop = Array.isArray(state?.loops)
2825
+ ? state.loops.find((candidate: any) => candidate?.loop_id === loopId)
2826
+ : undefined;
2827
+ if (!loop) {
2828
+ 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 };
2829
+ }
2830
+ if (loop.interval_ms !== intervalMs) {
2831
+ return { content: [{ type: "text", text: `set_loop_interval verification mismatch (expected ${intervalMs}, got ${loop.interval_ms}); use list_loops before retrying.` }], isError: true };
2832
+ }
2833
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
2834
+ const active = loop.paused === false || loop.paused_at === null;
2835
+ return {
2836
+ content: [{
2837
+ type: "text",
2838
+ text: JSON.stringify({
2839
+ ok: true,
2840
+ loop_id: loop.loop_id || loopId,
2841
+ interval_ms: loop.interval_ms,
2842
+ status: paused ? "paused" : (loop.status || (active ? "active" : "unknown")),
2843
+ next_tick_ms: paused ? null : (loop.next_tick_ms ?? null),
2844
+ }),
2845
+ }],
2846
+ };
2847
+ } catch (e: any) {
2848
+ return { content: [{ type: "text", text: `set_loop_interval error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2849
+ }
2850
+ });
2851
+
2852
+ HANDLERS.set("stop_loop", async (args) => {
2853
+ const loopId = String(args?.loop_id || "").trim();
2854
+ if (!isSafeLoopIdentifier(loopId)) {
2855
+ return { content: [{ type: "text", text: "stop_loop needs a valid loop_id." }], isError: true };
2856
+ }
2857
+ try {
2858
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/stop`, {
2859
+ method: "POST",
2860
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2861
+ });
2862
+ const text = await r.text();
2863
+ if (!r.ok) {
2864
+ return { content: [{ type: "text", text: `stop_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2865
+ }
2866
+ JSON.parse(text);
2867
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2868
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2869
+ });
2870
+ if (!verified.ok) {
2871
+ return { content: [{ type: "text", text: `stop_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
2872
+ }
2873
+ const state = await verified.json() as any;
2874
+ if (!Array.isArray(state?.loops)) {
2875
+ return { content: [{ type: "text", text: "stop_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }], isError: true };
2876
+ }
2877
+ const stillPresent = state.loops.some((candidate: any) => candidate?.loop_id === loopId);
2878
+ if (stillPresent) {
2879
+ 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 };
2880
+ }
2881
+ return {
2882
+ content: [{
2883
+ type: "text",
2884
+ text: JSON.stringify({
2885
+ ok: true,
2886
+ stopped: loopId,
2887
+ }),
2888
+ }],
2889
+ };
2890
+ } catch (e: any) {
2891
+ return { content: [{ type: "text", text: `stop_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2892
+ }
2893
+ });
2894
+
2895
+ HANDLERS.set("delete_memory", async (args) => {
2896
+ const checked = validateDeleteMemoryInput(args);
2897
+ if (!checked.ok) {
2898
+ return { content: [{ type: "text", text: checked.error }], isError: true };
2899
+ }
2900
+ try {
2901
+ const qs = checked.value.if_match_version !== undefined
2902
+ ? `?if_match_version=${checked.value.if_match_version}`
2903
+ : "";
2904
+ const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(checked.value.name)}${qs}`, {
2905
+ method: "DELETE",
2906
+ headers: { "Authorization": `Bearer ${TOKEN}` },
2907
+ });
2908
+ const text = await r.text();
2909
+ if (!r.ok) {
2910
+ return {
2911
+ content: [{ type: "text", text: `delete_memory failed (${r.status}): ${text.slice(0, 240)}` }],
2912
+ isError: true,
2913
+ };
2914
+ }
2915
+ const resp = JSON.parse(text) as any;
2916
+ const deleted = Boolean(resp?.deleted);
2917
+ if (!deleted && !checked.value.allow_missing) {
2918
+ return {
2919
+ content: [{
2920
+ type: "text",
2921
+ text: `delete_memory: memory "${checked.value.name}" does not exist (pass allow_missing=true for idempotent cleanup).`,
2922
+ }],
2923
+ isError: true,
2924
+ };
2925
+ }
2926
+ return {
2927
+ content: [{
2928
+ type: "text",
2929
+ text: JSON.stringify({
2930
+ ok: true,
2931
+ name: typeof resp?.name === "string" && resp.name ? resp.name : checked.value.name,
2932
+ deleted,
2933
+ }),
2934
+ }],
2935
+ };
2936
+ } catch (e: any) {
2937
+ return { content: [{ type: "text", text: `delete_memory network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2938
+ }
2939
+ });
2940
+
2941
+ HANDLERS.set("okr_update_kr", async (args) => {
2942
+ const validated = validateOkrUpdateKrInput(args);
2943
+ if (!validated.ok) {
2944
+ return { content: [{ type: "text", text: `okr_update_kr invalid arguments: ${validated.error}` }], isError: true };
2945
+ }
2946
+ const { kr_id, body } = validated.value;
2947
+ try {
2948
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}`, {
2949
+ method: "PATCH",
2950
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2951
+ body: JSON.stringify(body),
2952
+ });
2953
+ const text = await r.text();
2954
+ if (!r.ok) {
2955
+ return { content: [{ type: "text", text: `okr_update_kr failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
2956
+ }
2957
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
2958
+ } catch (e: any) {
2959
+ return { content: [{ type: "text", text: `okr_update_kr network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2960
+ }
2961
+ });
2962
+
2963
+ function redactCloudAgentDisplayName(name: string): string {
2964
+ const safe = redactSecrets(name)
2965
+ .replace(/\bsk-(?:ant|proj|live|test)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]")
2966
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, "[REDACTED]")
2967
+ .replace(/\bAIza[0-9A-Za-z_-]{30,}\b/g, "[REDACTED]");
2968
+ return redactParticipantPii(safe).slice(0, 128);
2969
+ }
2970
+
2971
+ function projectWakeHealthPayload(channelId: string, data: any): { channel_id: string; observation_only: true; agents: any[]; summary: Record<string, number>; untrusted: true } | null {
2972
+ if (!data || data.channel_id !== channelId || data.observation_only !== true || !Array.isArray(data.agents)) {
2973
+ return null;
2974
+ }
2975
+ const agents = data.agents.map((item: any) => {
2976
+ if (!item || typeof item.agent_id !== "string" || !/^[\w.-]{1,128}$/.test(item.agent_id) || isHumanPiiHandle(item.agent_id)) return null;
2977
+ const rawStatus = item.wake?.status ?? item.last_wake_status;
2978
+ const rawAt = item.wake?.last_wake_at ?? item.last_wake_at;
2979
+ const rawDur = item.wake?.last_duration_ms ?? item.last_duration_ms;
2980
+ const validWake = rawStatus === "ok" || rawStatus === "auth_required" || rawStatus === "timeout" || rawStatus === "error";
2981
+ const wake = validWake && typeof rawAt === "string" && Number.isSafeInteger(rawDur) && rawDur >= 0
2982
+ ? { status: rawStatus, last_wake_at: rawAt, last_duration_ms: rawDur }
2983
+ : null;
2984
+ return {
2985
+ agent_id: item.agent_id,
2986
+ ...(typeof item.name === "string" && item.name ? { name: redactCloudAgentDisplayName(item.name) } : {}),
2987
+ runtime: String(item.runtime || "unknown").slice(0, 32),
2988
+ cloud_status: String(item.cloud_status || "unknown").slice(0, 32),
2989
+ wake,
2990
+ };
2991
+ }).filter(Boolean).slice(0, 64) as any[];
2992
+ const summary = { total: agents.length, ok: 0, auth_required: 0, timeout: 0, error: 0, unobserved: 0 };
2993
+ for (const agent of agents) {
2994
+ if (agent.wake) summary[agent.wake.status as "ok" | "auth_required" | "timeout" | "error"]++;
2995
+ else summary.unobserved++;
2996
+ }
2997
+ return { channel_id: channelId, observation_only: true, agents, summary, untrusted: true };
2998
+ }
2999
+
3000
+ HANDLERS.set("cloud_agent_wake_health", async (args) => {
3001
+ const channelId = String(args?.channel_id || "").trim();
3002
+ if (!channelId || /[\x00-\x1f\x7f]/.test(channelId)) {
3003
+ return { content: [{ type: "text", text: "cloud_agent_wake_health needs channel_id." }], isError: true };
3004
+ }
3005
+ const reqHeaders = {
3006
+ "Authorization": `Bearer ${TOKEN}`,
3007
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3008
+ };
3009
+ try {
3010
+ const r = await apiFetch(`${REST_URL}/mcp`, {
3011
+ method: "POST",
3012
+ headers: { ...reqHeaders, "Content-Type": "application/json" },
3013
+ body: JSON.stringify({
3014
+ jsonrpc: "2.0", id: 1, method: "tools/call",
3015
+ params: { name: "agentschat_cloud_agent_wake_health", arguments: { channel_id: channelId } },
3016
+ }),
3017
+ }, 5000, true);
3018
+ let rpcErrorCode: unknown = null;
3019
+ let rpcErrorMsg = "";
3020
+ if (r.ok) {
3021
+ const rpc = await r.json() as any;
3022
+ if (!rpc?.error && !rpc?.result?.isError) {
3023
+ let data = rpc?.result?.structuredContent;
3024
+ if (!data && typeof rpc?.result?.content?.[0]?.text === "string") data = JSON.parse(rpc.result.content[0].text);
3025
+ const projected = projectWakeHealthPayload(channelId, data);
3026
+ if (!projected) return { content: [{ type: "text", text: "cloud_agent_wake_health returned an invalid response" }], isError: true };
3027
+ return { content: [{ type: "text", text: JSON.stringify(projected) }] };
3028
+ }
3029
+ rpcErrorCode = rpc?.error?.code ?? "remote_error";
3030
+ rpcErrorMsg = typeof rpc?.error?.message === "string" ? rpc.error.message : "";
3031
+ }
3032
+ // Fallback to REST /api/channels/:id/cloud-wake-health when /mcp predates the tool (-32601/-32602 Unknown tool or 404/405).
3033
+ const canFallback = (!r.ok && (r.status === 404 || r.status === 405)) ||
3034
+ ((rpcErrorCode === -32601 || rpcErrorCode === -32602) && !/denied|forbidden|invalid cloud wake health/i.test(rpcErrorMsg));
3035
+ if (canFallback) {
3036
+ const restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/cloud-wake-health`, {
3037
+ headers: reqHeaders,
3038
+ }, 5000, true);
3039
+ if (restRes.ok) {
3040
+ const projected = projectWakeHealthPayload(channelId, await restRes.json());
3041
+ if (projected) return { content: [{ type: "text", text: JSON.stringify(projected) }] };
3042
+ }
3043
+ }
3044
+ if (!r.ok) return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${r.status})` }], isError: true };
3045
+ const safeDetail = rpcErrorMsg ? `: ${redactSecrets(redactParticipantPii(rpcErrorMsg)).slice(0, 80)}` : "";
3046
+ return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${rpcErrorCode}${safeDetail})` }], isError: true };
3047
+ } catch (e: any) {
3048
+ return { content: [{ type: "text", text: `cloud_agent_wake_health error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3049
+ }
3050
+ });
3051
+
3052
+ function sanitizeProposalItem(p: any): any {
3053
+ if (!p || typeof p !== "object") return null;
3054
+ const votes = Array.isArray(p.votes)
3055
+ ? p.votes.map((v: any) => ({
3056
+ voter_id: typeof v?.voter_id === "string" ? redactParticipantPii(v.voter_id) : "unknown",
3057
+ voter_type: v?.voter_type === "human" ? "human" : "agent",
3058
+ decision: v?.decision,
3059
+ ...(typeof v?.reason === "string" && v.reason ? { reason: redactSecrets(redactParticipantPii(v.reason)).slice(0, 500) } : {}),
3060
+ }))
3061
+ : [];
3062
+ return {
3063
+ id: String(p.id || ""),
3064
+ channel_id: String(p.channel_id || ""),
3065
+ sender_id: typeof p.sender_id === "string" ? redactParticipantPii(p.sender_id) : "unknown",
3066
+ title: typeof p.title === "string" ? redactSecrets(p.title).slice(0, 500) : "",
3067
+ content: typeof p.content === "string" ? redactSecrets(p.content).slice(0, 4000) : "",
3068
+ ...(typeof p.code_diff === "string" ? { code_diff: redactSecrets(p.code_diff).slice(0, 8000) } : {}),
3069
+ consensus_rule: p.consensus_rule || "majority",
3070
+ ...(typeof p.expires_at === "string" && p.expires_at ? { expires_at: p.expires_at } : {}),
3071
+ timestamp: String(p.timestamp || ""),
3072
+ status: String(p.status || "pending"),
3073
+ total_voters: typeof p.total_voters === "number" ? p.total_voters : 1,
3074
+ votes,
3075
+ ...(p.vote_result && typeof p.vote_result === "object" ? { vote_result: p.vote_result } : {}),
3076
+ };
3077
+ }
3078
+
3079
+ HANDLERS.set("list_pins", async (args) => {
3080
+ const chatId = String(args?.chat_id || "").trim();
3081
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || /^(?:ac_|sk-)/i.test(chatId)) {
3082
+ return { content: [{ type: "text", text: "list_pins needs a valid chat_id." }], isError: true };
3083
+ }
3084
+ try {
3085
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/pins`, {
3086
+ headers: {
3087
+ "Authorization": `Bearer ${TOKEN}`,
3088
+ "Cache-Control": "no-store",
3089
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3090
+ },
3091
+ });
3092
+ const text = await r.text();
3093
+ if (!r.ok) {
3094
+ return { content: [{ type: "text", text: `list_pins failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
3095
+ }
3096
+ const body = JSON.parse(text) as any;
3097
+ const seen = new Set<string>();
3098
+ const pinnedMessages: string[] = [];
3099
+ if (Array.isArray(body?.pinned_messages)) {
3100
+ for (const rawId of body.pinned_messages) {
3101
+ if (typeof rawId !== "string") continue;
3102
+ const cleaned = rawId.trim().slice(0, 128);
3103
+ if (!cleaned || /[\x00-\x1f\x7f]/.test(cleaned) || seen.has(cleaned)) continue;
3104
+ seen.add(cleaned);
3105
+ pinnedMessages.push(cleaned);
3106
+ }
3107
+ }
3108
+ return {
3109
+ content: [{
3110
+ type: "text",
3111
+ text: JSON.stringify({
3112
+ channel_id: chatId,
3113
+ count: pinnedMessages.length,
3114
+ pinned_messages: pinnedMessages,
3115
+ }),
3116
+ }],
3117
+ };
3118
+ } catch (e: any) {
3119
+ return { content: [{ type: "text", text: `list_pins error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3120
+ }
3121
+ });
3122
+
3123
+ HANDLERS.set("list_proposals", async (args) => {
3124
+ const chatId = String(args?.chat_id || "").trim();
3125
+ const statusFilter = String(args?.status || "all").trim().toLowerCase();
3126
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId)) {
3127
+ return { content: [{ type: "text", text: "list_proposals needs chat_id." }], isError: true };
3128
+ }
3129
+ if (!["all", "pending", "passed", "rejected"].includes(statusFilter)) {
3130
+ return { content: [{ type: "text", text: "list_proposals status must be all, pending, passed, or rejected." }], isError: true };
3131
+ }
3132
+ try {
3133
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
3134
+ headers: {
3135
+ "Authorization": `Bearer ${TOKEN}`,
3136
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3137
+ },
3138
+ });
3139
+ const text = await r.text();
3140
+ if (!r.ok) {
3141
+ return { content: [{ type: "text", text: `list_proposals failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
3142
+ }
3143
+ const body = JSON.parse(text) as any;
3144
+ let proposals = (Array.isArray(body?.proposals) ? body.proposals : []).map(sanitizeProposalItem).filter(Boolean);
3145
+ if (statusFilter !== "all") {
3146
+ proposals = proposals.filter((p: any) => p.status === statusFilter);
3147
+ }
3148
+ return { content: [{ type: "text", text: JSON.stringify({ channel_id: chatId, count: proposals.length, proposals, untrusted: true }) }] };
3149
+ } catch (e: any) {
3150
+ return { content: [{ type: "text", text: `list_proposals error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3151
+ }
3152
+ });
3153
+
3154
+ HANDLERS.set("propose", async (args) => {
3155
+ const { chat_id, title, content, code_diff, consensus_rule, expires_at } = (args || {}) as any;
3156
+ const chatId = typeof chat_id === "string" ? chat_id.trim() : "";
3157
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || typeof title !== "string" || !title.trim() || typeof content !== "string") {
3158
+ return { content: [{ type: "text", text: "Error: chat_id, non-empty title, and content (strings) required" }], isError: true };
3159
+ }
3160
+ const rule = consensus_rule || "majority";
3161
+ if (!["majority", "super_majority", "unanimous"].includes(rule)) {
3162
+ return { content: [{ type: "text", text: "Error: consensus_rule must be majority, super_majority, or unanimous" }], isError: true };
3163
+ }
3164
+ const proposalId = crypto.randomUUID();
3165
+ const effectiveExpiresAt = typeof expires_at === "string" && expires_at.trim()
3166
+ ? expires_at.trim()
3167
+ : new Date(Date.now() + 86400_000).toISOString();
3168
+ if (TOKEN) {
3169
+ try {
3170
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
3171
+ method: "POST",
3172
+ headers: {
3173
+ "Authorization": `Bearer ${TOKEN}`,
3174
+ "Content-Type": "application/json",
3175
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3176
+ },
3177
+ body: JSON.stringify({
3178
+ id: proposalId,
3179
+ ...(AGENT_ID ? { sender_id: AGENT_ID } : {}),
3180
+ title,
3181
+ content,
3182
+ ...(typeof code_diff === "string" ? { code_diff } : {}),
3183
+ consensus_rule: rule,
3184
+ expires_at: effectiveExpiresAt,
3185
+ }),
3186
+ });
3187
+ if (r.ok) {
3188
+ const data = await r.json() as any;
3189
+ const proposal = sanitizeProposalItem(data?.proposal ?? data);
3190
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal }) }] };
3191
+ }
3192
+ if (r.status !== 404 && r.status !== 405 && r.status !== 501) {
3193
+ const errText = await r.text();
3194
+ return { content: [{ type: "text", text: `propose failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
3195
+ }
3196
+ } catch {
3197
+ // Network/pre-deploy fallback to WebSocket below when open.
3198
+ }
3199
+ }
3200
+ if (ws && ws.readyState === WebSocket.OPEN) {
3201
+ ws.send(JSON.stringify({
3202
+ type: "proposal", id: proposalId, channel_id: chatId,
3203
+ sender_id: AGENT_ID, title, content, code_diff,
3204
+ consensus_rule: rule,
3205
+ expires_at: effectiveExpiresAt,
3206
+ timestamp: new Date().toISOString(),
3207
+ }));
3208
+ return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject — verify via next inbound event` }] };
3209
+ }
3210
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
3211
+ });
3212
+
3213
+ HANDLERS.set("vote", async (args) => {
3214
+ const { chat_id, channel_id, proposal_id, decision, reason } = (args || {}) as any;
3215
+ if (typeof proposal_id !== "string" || !proposal_id.trim() || typeof decision !== "string") {
3216
+ return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }], isError: true };
3217
+ }
3218
+ if (!["approve", "reject", "abstain"].includes(decision)) {
3219
+ return { content: [{ type: "text", text: "Error: decision must be approve, reject, or abstain" }], isError: true };
3220
+ }
3221
+ const chatId = typeof chat_id === "string" && chat_id.trim()
3222
+ ? chat_id.trim()
3223
+ : (typeof channel_id === "string" && channel_id.trim() ? channel_id.trim() : "");
3224
+ if (chatId && !/[\x00-\x1f\x7f]/.test(chatId) && TOKEN) {
3225
+ try {
3226
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals/${encodeURIComponent(proposal_id.trim())}/votes`, {
3227
+ method: "POST",
3228
+ headers: {
3229
+ "Authorization": `Bearer ${TOKEN}`,
3230
+ "Content-Type": "application/json",
3231
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3232
+ },
3233
+ body: JSON.stringify({
3234
+ ...(AGENT_ID ? { voter_id: AGENT_ID } : {}),
3235
+ decision,
3236
+ ...(typeof reason === "string" ? { reason } : {}),
3237
+ }),
3238
+ });
3239
+ if (r.ok) {
3240
+ const data = await r.json() as any;
3241
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal_id: data?.proposal_id ?? proposal_id.trim(), vote_result: data?.vote_result }) }] };
3242
+ }
3243
+ const errText = await r.text();
3244
+ // Only fall back to WS when the server build predates the REST route (404 with HTML/route missing, not Proposal not found JSON).
3245
+ const isProposal404 = r.status === 404 && /proposal not found|channel not found/i.test(errText);
3246
+ if ((r.status !== 404 && r.status !== 405 && r.status !== 501) || isProposal404) {
3247
+ return { content: [{ type: "text", text: `vote failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
3248
+ }
3249
+ } catch {
3250
+ // Fall back to WS below if open.
3251
+ }
3252
+ }
3253
+ if (ws && ws.readyState === WebSocket.OPEN) {
3254
+ ws.send(JSON.stringify({
3255
+ type: "vote", proposal_id: proposal_id.trim(), voter_id: AGENT_ID,
3256
+ voter_type: "agent", decision, reason,
3257
+ }));
3258
+ return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.trim().slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
3259
+ }
3260
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
3261
+ });
3262
+
3263
+ HANDLERS.set("list_channels", async (args) => {
3264
+ const { query, limit = 50 } = (args || {}) as { query?: string; limit?: number };
3265
+ const clamped = Math.max(1, Math.min(Number(limit) || 50, 500));
3266
+ const qs = new URLSearchParams({ limit: String(clamped) });
3267
+ if (typeof query === "string" && query.trim()) qs.set("q", query.trim());
3268
+ try {
3269
+ const r = await apiFetch(`${REST_URL}/api/channels/discover?${qs.toString()}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3270
+ if (r.ok) {
3271
+ const data = await r.json() as any;
3272
+ const channels = (data.channels || []);
3273
+ if (channels.length === 0) return { content: [{ type: "text", text: "No public channels found." }] };
3274
+ const list = channels.map((ch: any) => {
3275
+ const onlineBadge = typeof ch.online_agent_count === "number" && ch.online_agent_count > 0 ? `, 🟢 ${ch.online_agent_count} online` : "";
3276
+ const caps = Array.isArray(ch.capabilities) && ch.capabilities.length > 0 ? ` [${ch.capabilities.slice(0, 6).join(", ")}]` : "";
3277
+ const topic = ch.topic ? ` — ${redactSecrets(redactParticipantPii(String(ch.topic))).slice(0, 60)}` : "";
3278
+ return `• ${ch.name || ch.id} (${ch.id}) — ${ch.member_count || "?"} members${onlineBadge}${caps}${topic}`;
3279
+ }).join("\n");
3280
+ return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
3281
+ }
3282
+ return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
3283
+ } catch (e) {
3284
+ return { content: [{ type: "text", text: `Error: ${e}` }] };
3285
+ }
3286
+ });
3287
+
2170
3288
  // list_my_channels — the caller's actual membership (channels + DMs) from
2171
3289
  // /api/channels/mine, distinct from list_channels (public discovery). Registered
2172
3290
  // here per the frozen-registry policy; new tools never join the legacy if-chain.
@@ -3179,6 +4297,10 @@ const handleToolCall = async (request: any): Promise<any> => {
3179
4297
  // SDK error, so the calling agent always learns the call failed. Explicit
3180
4298
  // error returns below carry isError:true individually.
3181
4299
  try {
4300
+ if (codexIdentity && (AGENT_ID !== codexIdentity.agentId ||
4301
+ ["connect_profile", "switch_profile", "disconnect_profile"].includes(name))) {
4302
+ return { content: [{ type: "text", text: "Codex bridge owns this tool identity; change the bot configuration and restart to change identity." }], isError: true };
4303
+ }
3182
4304
  // Resolve the calling session/conversation and automatically route to its
3183
4305
  // bound ProfileSlot in profileSlots (`session_id -> profile -> agent_id`).
3184
4306
  const rawMeta = (request.params as any)?._meta;
@@ -3187,7 +4309,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3187
4309
  args as Record<string, any> | undefined,
3188
4310
  rawMeta,
3189
4311
  );
3190
- if (callerSession) {
4312
+ if (callerSession && !codexIdentity) {
3191
4313
  runtimeSession = callerSession;
3192
4314
  const binds = loadSessionBinds(configDir);
3193
4315
  const boundProfileName = binds[callerSession.sessionId];
@@ -3295,7 +4417,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3295
4417
 
3296
4418
  // Shared Cursor MCP: heal back to grok-bind identity if another agent
3297
4419
  // stole the live profile via switch_profile. No-op when unbound.
3298
- ensureGrokBoundIdentity();
4420
+ if (!codexIdentity) ensureGrokBoundIdentity();
3299
4421
 
3300
4422
  // Identity guard (task_muk0154j_pstaosfn): after a suspect fallback (explicit
3301
4423
  // identity lost on respawn → default profile), WRITE tools refuse until the
@@ -3314,7 +4436,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3314
4436
  }
3315
4437
 
3316
4438
  if (name === "list_skills") {
3317
- const { chat_id } = (args || {}) as { chat_id?: string };
4439
+ const { chat_id, active_only } = (args || {}) as { chat_id?: string; active_only?: boolean };
4440
+ const activeOnly = active_only !== false;
4441
+ const activeQuery = activeOnly ? "?active_only=1" : "";
3318
4442
  const out: any = {
3319
4443
  global_skills: Object.entries(GLOBAL_SKILLS).map(([skill_id, skill]) => ({
3320
4444
  skill_id,
@@ -3325,27 +4449,103 @@ const handleToolCall = async (request: any): Promise<any> => {
3325
4449
  };
3326
4450
  if (chat_id) {
3327
4451
  try {
3328
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs`, {
4452
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${activeQuery}`, {
3329
4453
  headers: { "Authorization": `Bearer ${TOKEN}` },
3330
4454
  });
3331
- if (r.ok) out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text())).filter(isSkillDoc).map(compactSkillDoc);
3332
- else out.channel_skills_error = `failed (${r.status})`;
4455
+ if (r.ok) {
4456
+ out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text()))
4457
+ .filter(isSkillDoc)
4458
+ .filter((d: any) => !activeOnly || !isArchivedSkillOrDoc(d))
4459
+ .map(compactSkillDoc);
4460
+ } else {
4461
+ out.channel_skills_error = `failed (${r.status})`;
4462
+ }
3333
4463
  } catch (e: any) {
3334
4464
  out.channel_skills_error = `network/parse error: ${String(e?.message || e).slice(0, 120)}`;
3335
4465
  }
3336
4466
  }
3337
- // Personal skills (per-owner, follow you across agents). sync_skill(name=…) / load via GET /api/skills/:name.
4467
+ // Personal skills (per-owner, follow you across agents). sync_skill(name=…) / load_skill(name=…).
3338
4468
  try {
3339
- const pr = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3340
- if (pr.ok) out.personal_skills = (JSON.parse(await pr.text()).skills) || [];
4469
+ const pr = await apiFetch(`${REST_URL}/api/skills${activeQuery}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4470
+ if (pr.ok) {
4471
+ const rawSkills = (JSON.parse(await pr.text()).skills) || [];
4472
+ out.personal_skills = rawSkills.filter((s: any) => !activeOnly || !isArchivedSkillOrDoc(s));
4473
+ } else {
4474
+ out.personal_skills_error = `failed (${pr.status})`;
4475
+ }
3341
4476
  } catch { /* best-effort */ }
3342
4477
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
3343
4478
  }
3344
4479
 
3345
4480
  if (name === "load_skill") {
3346
- const { skill_id, chat_id, doc_id } = (args || {}) as { skill_id?: string; chat_id?: string; doc_id?: string };
4481
+ const targetCheck = validateLoadSkillInput(args);
4482
+ if (!targetCheck.ok) {
4483
+ return { content: [{ type: "text", text: targetCheck.error }], isError: true };
4484
+ }
4485
+ const target = targetCheck.value;
4486
+ // PERSONAL skill: name (per-owner, shared across your agents).
4487
+ if (target.scope === "personal") {
4488
+ try {
4489
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}`, {
4490
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4491
+ });
4492
+ const text = await r.text();
4493
+ if (!r.ok) {
4494
+ return { content: [{ type: "text", text: `load_skill (personal) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
4495
+ }
4496
+ const doc = JSON.parse(text);
4497
+ const body = String(doc?.body_markdown ?? "");
4498
+ const version = doc?.version ?? "?";
4499
+ const title = doc?.title || target.name;
4500
+ const archived = doc?.archived === true || body === "";
4501
+ const parsed = parseSkillFrontmatter(body);
4502
+ const metadata = { ...(parsed.metadata || {}), ...(doc?.skill_meta || {}) };
4503
+ const metaLines = [
4504
+ metadata.name ? `name: ${metadata.name}` : null,
4505
+ metadata.description ? `description: ${metadata.description}` : null,
4506
+ metadata.trigger ? `trigger: ${metadata.trigger}` : null,
4507
+ (metadata.argument_hint ?? metadata.argumentHint) ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null,
4508
+ ].filter(Boolean).join("\n");
4509
+ let revisionsBlock = "";
4510
+ if (target.include_revisions) {
4511
+ const revR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}/revisions`, {
4512
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4513
+ });
4514
+ if (revR.ok) {
4515
+ const revJson = JSON.parse(await revR.text());
4516
+ revisionsBlock = `\n\nRevisions:\n${JSON.stringify(revJson?.revisions ?? [], null, 2)}`;
4517
+ } else {
4518
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4519
+ }
4520
+ }
4521
+ if (archived) {
4522
+ const hint = target.include_revisions
4523
+ ? `Restore by calling save_skill(name="${title}", doc_id="${target.name}", description=..., body=..., if_match_version=${version}).`
4524
+ : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
4525
+ return {
4526
+ content: [{
4527
+ type: "text",
4528
+ text: `[ARCHIVED PERSONAL SKILL "${target.name}" (v${version})]\n${metaLines ? `\nMetadata:\n${metaLines}\n` : ""}\n${hint}${revisionsBlock}`,
4529
+ }],
4530
+ };
4531
+ }
4532
+ return {
4533
+ content: [{
4534
+ type: "text",
4535
+ text: [
4536
+ `Personal skill loaded: "${target.name}" (v${version}).`,
4537
+ metaLines ? `\nMetadata:\n${metaLines}` : "",
4538
+ `\n# ${title}\n\n${parsed.body}${revisionsBlock}`,
4539
+ ].join("\n"),
4540
+ }],
4541
+ };
4542
+ } catch (e: any) {
4543
+ return { content: [{ type: "text", text: `load_skill (personal) network/parse error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4544
+ }
4545
+ }
3347
4546
  // CHANNEL skill: chat_id + doc_id (full frontmatter/metadata handling).
3348
- if (chat_id && doc_id) {
4547
+ if (target.scope === "channel") {
4548
+ const { chat_id, doc_id, include_revisions } = target;
3349
4549
  try {
3350
4550
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
3351
4551
  headers: { "Authorization": `Bearer ${TOKEN}` },
@@ -3355,11 +4555,13 @@ const handleToolCall = async (request: any): Promise<any> => {
3355
4555
  return { content: [{ type: "text", text: `load_skill (channel) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
3356
4556
  }
3357
4557
  const doc = JSON.parse(text);
3358
- const body = doc?.body_markdown ?? doc?.bodyMarkdown ?? "";
4558
+ const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
3359
4559
  const title = doc?.title || doc_id;
3360
4560
  const kind = doc?.kind || "unknown";
3361
4561
  const level = doc?.level ?? "?";
3362
- const parsed = parseSkillFrontmatter(String(body));
4562
+ const version = doc?.version ?? "?";
4563
+ const archived = isArchivedSkillOrDoc(doc);
4564
+ const parsed = parseSkillFrontmatter(body);
3363
4565
  const metadata = { ...(parsed.metadata || {}), ...(doc?.skill_meta || doc?.skillMeta || {}) };
3364
4566
  const metaLines = [
3365
4567
  metadata.name ? `name: ${metadata.name}` : null,
@@ -3367,16 +4569,40 @@ const handleToolCall = async (request: any): Promise<any> => {
3367
4569
  metadata.trigger ? `trigger: ${metadata.trigger}` : null,
3368
4570
  (metadata.argument_hint ?? metadata.argumentHint) ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null,
3369
4571
  ].filter(Boolean).join("\n");
4572
+ let revisionsBlock = "";
4573
+ if (include_revisions) {
4574
+ const revR = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
4575
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4576
+ });
4577
+ if (revR.ok) {
4578
+ const revJson = JSON.parse(await revR.text());
4579
+ const revs = Array.isArray(revJson) ? revJson : (revJson?.revisions ?? []);
4580
+ revisionsBlock = `\n\nRevisions:\n${JSON.stringify(revs, null, 2)}`;
4581
+ } else {
4582
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4583
+ }
4584
+ }
4585
+ if (archived) {
4586
+ const hint = include_revisions
4587
+ ? `Restore by calling save_skill(chat_id="${chat_id}", doc_id="${doc_id}", name=..., description=..., body=..., if_match_version=${version}).`
4588
+ : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
4589
+ return {
4590
+ content: [{
4591
+ type: "text",
4592
+ text: `[ARCHIVED CHANNEL SKILL ${chat_id}/${doc_id} (L${level}, v${version})]\n${metaLines ? `\nMetadata:\n${metaLines}\n` : ""}\n${hint}${revisionsBlock}`,
4593
+ }],
4594
+ };
4595
+ }
3370
4596
  if (!String(kind).toLowerCase().includes("skill") && !String(doc_id).toLowerCase().includes("skill")) {
3371
- 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}` }] };
4597
+ 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}` }] };
3372
4598
  }
3373
4599
  return {
3374
4600
  content: [{
3375
4601
  type: "text",
3376
4602
  text: [
3377
- `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}).`,
4603
+ `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}, v${version}).`,
3378
4604
  metaLines ? `\nMetadata:\n${metaLines}` : "",
3379
- `\n# ${title}\n\n${parsed.body}`,
4605
+ `\n# ${title}\n\n${parsed.body}${revisionsBlock}`,
3380
4606
  ].join("\n"),
3381
4607
  }],
3382
4608
  };
@@ -3385,7 +4611,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3385
4611
  }
3386
4612
  }
3387
4613
  // GLOBAL skill: skill_id (default workspace-driven-eng).
3388
- const id = skill_id || DEFAULT_GLOBAL_SKILL_ID;
4614
+ const id = target.skill_id || DEFAULT_GLOBAL_SKILL_ID;
3389
4615
  const skill = GLOBAL_SKILLS[id];
3390
4616
  if (!skill) {
3391
4617
  return { content: [{ type: "text", text: `Unknown global skill: ${id}` }], isError: true };
@@ -3394,15 +4620,26 @@ const handleToolCall = async (request: any): Promise<any> => {
3394
4620
  }
3395
4621
 
3396
4622
  if (name === "save_memory") {
3397
- const a = (args || {}) as { name?: string; body?: string; description?: string };
4623
+ const a = (args || {}) as { name?: string; body?: string; description?: string; if_match_version?: number };
3398
4624
  if (!a.name || !a.body) {
3399
4625
  return { content: [{ type: "text", text: "save_memory needs name (slug) + body (markdown). Optional description (one-line index hook)." }], isError: true };
3400
4626
  }
4627
+ if (
4628
+ a.if_match_version !== undefined &&
4629
+ a.if_match_version !== null &&
4630
+ (!Number.isSafeInteger(a.if_match_version) || a.if_match_version < 0 || a.if_match_version > 1_000_000)
4631
+ ) {
4632
+ return { content: [{ type: "text", text: "save_memory if_match_version must be an integer in 0..1000000." }], isError: true };
4633
+ }
3401
4634
  try {
3402
4635
  const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}`, {
3403
4636
  method: "PUT",
3404
4637
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3405
- body: JSON.stringify({ body_markdown: a.body, description: a.description }),
4638
+ body: JSON.stringify({
4639
+ body_markdown: a.body,
4640
+ description: a.description,
4641
+ ...(a.if_match_version !== undefined && a.if_match_version !== null ? { if_match_version: a.if_match_version } : {}),
4642
+ }),
3406
4643
  });
3407
4644
  const text = await r.text();
3408
4645
  if (!r.ok) return { content: [{ type: "text", text: `save_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
@@ -3414,7 +4651,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3414
4651
  }
3415
4652
 
3416
4653
  if (name === "load_memory") {
3417
- const a = (args || {}) as { name?: string };
4654
+ const validated = validateLoadMemoryInput(args);
4655
+ if (!validated.ok) {
4656
+ return { content: [{ type: "text", text: validated.error }], isError: true };
4657
+ }
4658
+ const a = validated.value;
3418
4659
  try {
3419
4660
  const path = a.name ? `/api/memory/${encodeURIComponent(a.name)}` : `/api/memory`;
3420
4661
  const r = await apiFetch(`${REST_URL}${path}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -3422,7 +4663,21 @@ const handleToolCall = async (request: any): Promise<any> => {
3422
4663
  if (!r.ok) return { content: [{ type: "text", text: `load_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3423
4664
  const resp = JSON.parse(text);
3424
4665
  if (a.name) {
3425
- return { content: [{ type: "text", text: `# memory: ${resp.name} (v${resp.version})\n\n${resp.body_markdown || ""}` }] };
4666
+ let revisionsBlock = "";
4667
+ if (a.include_revisions) {
4668
+ const revR = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}/revisions`, {
4669
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4670
+ });
4671
+ if (revR.ok) {
4672
+ const revJson = JSON.parse(await revR.text());
4673
+ const revs = Array.isArray(revJson) ? revJson : (revJson?.revisions ?? []);
4674
+ const truncBadge = revJson?.revisions_truncated ? " (truncated)" : "";
4675
+ revisionsBlock = `\n\nRevisions${truncBadge} (restore via save_memory(name="${resp.name}", body=..., if_match_version=${resp.version})):\n${JSON.stringify(revs, null, 2)}`;
4676
+ } else {
4677
+ revisionsBlock = `\n\nRevisions: fetch failed (${revR.status})`;
4678
+ }
4679
+ }
4680
+ return { content: [{ type: "text", text: `# memory: ${resp.name} (v${resp.version})\n\n${resp.body_markdown || ""}${revisionsBlock}` }] };
3426
4681
  }
3427
4682
  const items = Array.isArray(resp.memories) ? resp.memories : [];
3428
4683
  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)." }] };
@@ -3434,55 +4689,108 @@ const handleToolCall = async (request: any): Promise<any> => {
3434
4689
  }
3435
4690
 
3436
4691
  if (name === "save_skill") {
3437
- const a = (args || {}) as { chat_id?: string; name?: string; description?: string; body?: string; doc_id?: string; level?: number };
3438
- if (!a.name || !a.description) {
3439
- 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 };
3440
- }
3441
- // Skill markdown = YAML frontmatter (name, description) + body — the exact
3442
- // shape parseSkillFrontmatter + the skill validators expect.
3443
- const oneLine = (s: string) => String(s).replace(/\r?\n/g, " ").slice(0, 480);
3444
- const md = `---\nname: ${oneLine(a.name)}\ndescription: ${oneLine(a.description)}\n---\n\n${a.body || ""}`;
4692
+ const validated = validateSaveSkillInput(args);
4693
+ if (!validated.ok) {
4694
+ return { content: [{ type: "text", text: validated.error }], isError: true };
4695
+ }
4696
+ const v = validated.value;
3445
4697
  // PERSONAL skill (no chat_id): per-owner store, shared across YOUR agents.
3446
- if (!a.chat_id) {
3447
- 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";
4698
+ if (v.scope === "personal") {
4699
+ if (v.mode === "archive") {
4700
+ try {
4701
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
4702
+ method: "DELETE",
4703
+ headers: {
4704
+ "Authorization": `Bearer ${TOKEN}`,
4705
+ "If-Match": String(v.if_match_version),
4706
+ },
4707
+ });
4708
+ const text = await r.text();
4709
+ if (!r.ok) return { content: [{ type: "text", text: `save_skill (personal archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4710
+ const resp = text.trim() ? JSON.parse(text) : {};
4711
+ const nextVer = resp?.version ?? v.if_match_version + 1;
4712
+ return {
4713
+ content: [{
4714
+ type: "text",
4715
+ 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).`,
4716
+ }],
4717
+ };
4718
+ } catch (e: any) {
4719
+ return { content: [{ type: "text", text: `save_skill (personal archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4720
+ }
4721
+ }
3448
4722
  try {
3449
- const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pslug)}`, {
4723
+ const headers: Record<string, string> = {
4724
+ "Authorization": `Bearer ${TOKEN}`,
4725
+ "Content-Type": "application/json",
4726
+ ...(v.if_match_version !== undefined ? { "If-Match": String(v.if_match_version) } : {}),
4727
+ };
4728
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
3450
4729
  method: "PUT",
3451
- headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3452
- body: JSON.stringify({ body_markdown: md }),
4730
+ headers,
4731
+ body: JSON.stringify({
4732
+ body_markdown: v.body_markdown,
4733
+ ...(v.if_match_version !== undefined ? { if_match_version: v.if_match_version } : {}),
4734
+ }),
3453
4735
  });
3454
4736
  const text = await r.text();
3455
4737
  if (!r.ok) return { content: [{ type: "text", text: `save_skill (personal) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3456
4738
  const resp = JSON.parse(text);
3457
- 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.` }] };
4739
+ 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.` }] };
3458
4740
  } catch (e: any) {
3459
4741
  return { content: [{ type: "text", text: `save_skill (personal) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3460
4742
  }
3461
4743
  }
3462
- // CHANNEL skill (chat_id given). Stable doc id: caller-supplied, else slug of name.
3463
- const slug = String(a.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill";
3464
- const docId = (a.doc_id && String(a.doc_id).trim()) || `skill-${slug}`;
3465
- const level = (typeof a.level === "number" && a.level >= 1 && a.level <= 4) ? a.level : 3; // 3 = member-writable
4744
+
4745
+ // CHANNEL skill (chat_id given).
4746
+ if (v.mode === "archive") {
4747
+ try {
4748
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
4749
+ method: "DELETE",
4750
+ headers: {
4751
+ "Authorization": `Bearer ${TOKEN}`,
4752
+ "If-Match": String(v.if_match_version),
4753
+ },
4754
+ });
4755
+ const text = await r.text();
4756
+ if (!r.ok) {
4757
+ return { content: [{ type: "text", text: `save_skill (channel archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4758
+ }
4759
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
4760
+ const parsed = text.trim() ? JSON.parse(text) : null;
4761
+ const nextVer = parsed?.version ?? (Number.isSafeInteger(etagVer) && etagVer >= 1 ? etagVer : v.if_match_version + 1);
4762
+ return {
4763
+ content: [{
4764
+ type: "text",
4765
+ 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).`,
4766
+ }],
4767
+ };
4768
+ } catch (e: any) {
4769
+ return { content: [{ type: "text", text: `save_skill (channel archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4770
+ }
4771
+ }
3466
4772
  try {
3467
- // If-Match: fetch current version (0 = create). The doc store uses
3468
- // optimistic concurrency; "0" creates, current version updates.
3469
- let ifMatch = "0";
3470
- const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3471
- if (cur.ok) {
3472
- const curDoc = await cur.json().catch(() => null) as any;
3473
- if (curDoc && curDoc.version != null) ifMatch = String(curDoc.version);
4773
+ let ifMatch = v.if_match_version !== undefined ? String(v.if_match_version) : "0";
4774
+ if (v.if_match_version === undefined) {
4775
+ const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
4776
+ headers: { "Authorization": `Bearer ${TOKEN}` },
4777
+ });
4778
+ if (cur.ok) {
4779
+ const curDoc = await cur.json().catch(() => null) as any;
4780
+ if (curDoc && curDoc.version != null) ifMatch = String(curDoc.version);
4781
+ }
3474
4782
  }
3475
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, {
4783
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
3476
4784
  method: "PUT",
3477
4785
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json", "If-Match": ifMatch },
3478
- body: JSON.stringify({ kind: "channel_skill", level, title: a.name, body_markdown: md }),
4786
+ body: JSON.stringify({ kind: "channel_skill", level: v.level, title: v.name, body_markdown: v.body_markdown }),
3479
4787
  });
3480
4788
  const text = await r.text();
3481
4789
  if (!r.ok) {
3482
4790
  return { content: [{ type: "text", text: `save_skill failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3483
4791
  }
3484
4792
  const verb = ifMatch === "0" ? "Saved" : "Updated";
3485
- 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}").` }] };
4793
+ 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}").` }] };
3486
4794
  } catch (e: any) {
3487
4795
  return { content: [{ type: "text", text: `save_skill network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3488
4796
  }
@@ -3496,28 +4804,52 @@ const handleToolCall = async (request: any): Promise<any> => {
3496
4804
  // PERSONAL skill: sync_skill({name}) — version from GET /api/skills (cheap,
3497
4805
  // no body), body from GET /api/skills/:name only when missing/stale.
3498
4806
  if (a.name && !a.chat_id) {
3499
- const pBase = `${cacheDir}/personal__${safe(a.name)}`;
4807
+ const slugCheck = validatePersonalSkillSlugInput(a.name, "sync_skill");
4808
+ if (!slugCheck.ok) {
4809
+ return { content: [{ type: "text", text: slugCheck.error }], isError: true };
4810
+ }
4811
+ const pSlug = slugCheck.value;
4812
+ const pBase = `${cacheDir}/personal__${safe(pSlug)}`;
3500
4813
  const pMd = `${pBase}.md`; const pMeta = `${pBase}.json`;
3501
4814
  try {
3502
4815
  const listR = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3503
4816
  if (!listR.ok) return { content: [{ type: "text", text: `sync_skill (personal): list failed (${listR.status})` }], isError: true };
3504
- const meta = (JSON.parse(await listR.text()).skills || []).find((s: any) => s.name === a.name);
3505
- 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 };
4817
+ const meta = (JSON.parse(await listR.text()).skills || []).find((s: any) => s.name === pSlug);
4818
+ if (!meta) return { content: [{ type: "text", text: `sync_skill: personal skill "${pSlug}" not found (save it with save_skill — no chat_id).` }], isError: true };
4819
+ if (meta.archived === true) {
4820
+ return {
4821
+ content: [{
4822
+ type: "text",
4823
+ 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).`,
4824
+ }],
4825
+ isError: true,
4826
+ };
4827
+ }
3506
4828
  const currentVersion = Number(meta.version ?? 0);
3507
4829
  let cachedVersion: number | null = null;
3508
4830
  try { cachedVersion = Number(JSON.parse(readFileSync(pMeta, "utf8")).version); } catch {}
3509
4831
  if (cachedVersion !== null && cachedVersion === currentVersion) {
3510
- 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.` }] };
4832
+ return { content: [{ type: "text", text: `up-to-date: personal skill "${pSlug}" v${currentVersion} already at ${pMd} — no download. Read that file to run it.` }] };
3511
4833
  }
3512
- const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(a.name)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4834
+ const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pSlug)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3513
4835
  if (!bodyR.ok) return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
3514
4836
  const doc = JSON.parse(await bodyR.text());
4837
+ const body = String(doc?.body_markdown ?? "");
4838
+ if (doc?.archived === true || !body.trim()) {
4839
+ return {
4840
+ content: [{
4841
+ type: "text",
4842
+ text: `sync_skill: personal skill "${pSlug}" is archived; refusing to overwrite local file.`,
4843
+ }],
4844
+ isError: true,
4845
+ };
4846
+ }
3515
4847
  // node:fs (not Bun.write) — runs on plain Node too. Bun.write auto-creates
3516
4848
  // parent dirs; writeFileSync does not, so mkdir the cache dir first.
3517
4849
  mkdirSync(dirname(pMd), { recursive: true });
3518
- writeFileSync(pMd, String(doc?.body_markdown ?? ""));
3519
- writeFileSync(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
3520
- 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.` }] };
4850
+ writeFileSync(pMd, body);
4851
+ writeFileSync(pMeta, JSON.stringify({ version: currentVersion, name: pSlug, syncedAt: new Date().toISOString() }));
4852
+ 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.` }] };
3521
4853
  } catch (e: any) {
3522
4854
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
3523
4855
  }
@@ -3537,6 +4869,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3537
4869
  const docs = extractChannelDocsPayload(JSON.parse(await listR.text()));
3538
4870
  const meta = docs.find((d: any) => (d?.id ?? d?.doc_id) === a.doc_id);
3539
4871
  if (!meta) return { content: [{ type: "text", text: `sync_skill: skill "${a.doc_id}" not found in channel ${a.chat_id}` }], isError: true };
4872
+ if (isArchivedSkillOrDoc(meta)) {
4873
+ return {
4874
+ content: [{
4875
+ type: "text",
4876
+ 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).`,
4877
+ }],
4878
+ isError: true,
4879
+ };
4880
+ }
3540
4881
  const currentVersion = Number(meta.version ?? 0);
3541
4882
  // 2. Local cache check — skip the body fetch if we already have this version.
3542
4883
  let cachedVersion: number | null = null;
@@ -3549,6 +4890,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3549
4890
  if (!docR.ok) return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
3550
4891
  const doc = JSON.parse(await docR.text());
3551
4892
  const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
4893
+ if (isArchivedSkillOrDoc(doc)) {
4894
+ return {
4895
+ content: [{
4896
+ type: "text",
4897
+ text: `sync_skill: channel skill "${a.doc_id}" is archived; refusing to overwrite local file.`,
4898
+ }],
4899
+ isError: true,
4900
+ };
4901
+ }
3552
4902
  // 4. Write the local mirror + version sidecar (node:fs, not Bun.write, for
3553
4903
  // Node compat; mkdir the cache dir first since writeFileSync won't auto-create).
3554
4904
  mkdirSync(dirname(mdPath), { recursive: true });
@@ -3886,40 +5236,67 @@ const handleToolCall = async (request: any): Promise<any> => {
3886
5236
  }
3887
5237
  }
3888
5238
 
3889
- if (name === "vote") {
3890
- const { proposal_id, decision, reason } = args as any;
3891
- if (typeof proposal_id !== "string" || typeof decision !== "string") {
3892
- return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }] };
3893
- }
3894
- if (ws && ws.readyState === WebSocket.OPEN) {
3895
- ws.send(JSON.stringify({
3896
- type: "vote", proposal_id, voter_id: AGENT_ID,
3897
- voter_type: "agent", decision, reason,
3898
- }));
3899
- return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
3900
- }
3901
- return { content: [{ type: "text", text: "Not connected" }] };
3902
- }
3903
-
3904
- if (name === "propose") {
3905
- const { chat_id, title, content, code_diff, consensus_rule } = args as any;
3906
- if (ws && ws.readyState === WebSocket.OPEN) {
3907
- const proposalId = crypto.randomUUID();
3908
- ws.send(JSON.stringify({
3909
- type: "proposal", id: proposalId, channel_id: chat_id,
3910
- sender_id: AGENT_ID, title, content, code_diff,
3911
- consensus_rule: consensus_rule || "majority",
3912
- expires_at: new Date(Date.now() + 86400_000).toISOString(),
3913
- timestamp: new Date().toISOString(),
3914
- }));
3915
- return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject — verify via next inbound event` }] };
3916
- }
3917
- return { content: [{ type: "text", text: "Not connected" }] };
3918
- }
3919
-
3920
5239
  async function fetchMcpChannelContext(chatId: string): Promise<{
3921
5240
  channel?: { id?: string; name?: string; type?: string; topic?: string; member_count?: number };
3922
5241
  agents?: Array<{ id: string; name?: string; capabilities?: string[]; online?: boolean; is_self?: boolean }>;
5242
+ docs_summary?: Array<{
5243
+ id?: string;
5244
+ doc_id?: string;
5245
+ title?: string;
5246
+ kind?: string;
5247
+ level?: number;
5248
+ version?: number;
5249
+ archived?: boolean;
5250
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5251
+ }>;
5252
+ skills_summary?: {
5253
+ channel_skills?: Array<{
5254
+ doc_id?: string;
5255
+ version?: number;
5256
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5257
+ }>;
5258
+ personal_skills?: Array<{
5259
+ name?: string;
5260
+ version?: number;
5261
+ skill_meta?: { name?: string; description?: string; trigger?: string; argument_hint?: string };
5262
+ }>;
5263
+ };
5264
+ okr_summary?: {
5265
+ active_objective_count: number;
5266
+ total_task_count: number;
5267
+ ready_for_me_count: number;
5268
+ doing_for_me_count?: number;
5269
+ blocked_for_me_count?: number;
5270
+ ready_task_count?: number;
5271
+ doing_task_count?: number;
5272
+ blocked_task_count?: number;
5273
+ };
5274
+ loop_summary?: {
5275
+ active_loop_count?: number;
5276
+ my_active_loop_count?: number;
5277
+ okr_wake_objective_ids?: string[];
5278
+ okr_watch_objective_ids?: string[];
5279
+ unarmed_objective_ids?: string[];
5280
+ };
5281
+ wake_health_summary?: {
5282
+ observation_only?: boolean;
5283
+ counts?: {
5284
+ total_cloud_agents: number;
5285
+ ok: number;
5286
+ auth_required: number;
5287
+ timeout: number;
5288
+ error: number;
5289
+ unobserved: number;
5290
+ };
5291
+ attention_agents?: Array<{
5292
+ agent_id: string;
5293
+ name?: string;
5294
+ runtime: string;
5295
+ cloud_status: string;
5296
+ last_wake_status?: string;
5297
+ last_wake_at?: string;
5298
+ }>;
5299
+ };
3923
5300
  } | null> {
3924
5301
  if (!chatId || !TOKEN) return null;
3925
5302
  try {
@@ -3938,7 +5315,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3938
5315
  method: "tools/call",
3939
5316
  params: {
3940
5317
  name: "agentschat_get_channel_context",
3941
- arguments: { channel_id: chatId },
5318
+ arguments: { channel_id: chatId, include_briefing: true },
3942
5319
  },
3943
5320
  }),
3944
5321
  },
@@ -3969,10 +5346,13 @@ const handleToolCall = async (request: any): Promise<any> => {
3969
5346
  return r.ok ? await r.json() as any : null;
3970
5347
  } catch { return null; }
3971
5348
  };
3972
- const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5349
+ const [membersData, docsData, okrData, loopsData, personalSkillsData, wakeHealthData, mcpCtx] = await Promise.all([
3973
5350
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
3974
- get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5351
+ get(`/api/channels/${encodeURIComponent(chatId)}/docs?active_only=1`),
3975
5352
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
5353
+ get(`/api/loops?channel_id=${encodeURIComponent(chatId)}`),
5354
+ get(`/api/skills?active_only=1`),
5355
+ get(`/api/channels/${encodeURIComponent(chatId)}/wake-health`),
3976
5356
  fetchMcpChannelContext(chatId),
3977
5357
  ]);
3978
5358
  // membersData === null means the /members read FAILED (most often a 403 because
@@ -4027,13 +5407,272 @@ const handleToolCall = async (request: any): Promise<any> => {
4027
5407
  : {}),
4028
5408
  is_self: String(m.agent_id) === AGENT_ID,
4029
5409
  }));
4030
- const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
4031
- const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
4032
- const docs = allDocs.filter((d: any) => !isSkillDoc(d)).slice(0, 10).map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
4033
- const objectives = (okrData?.objectives || []).filter((o: any) => !o.archived).map((o: any) => {
4034
- const open = (okrData?.tasks || []).filter((t: any) => t.objective_id === o.id && t.status !== "done").length;
4035
- return { id: o.id, title: o.title, open_tasks: open };
5410
+ const hasRestDocsPayload = Boolean(
5411
+ docsData && (Array.isArray(docsData) || Array.isArray(docsData.docs) || Array.isArray(docsData.channel_docs)),
5412
+ );
5413
+ const docsReadable =
5414
+ hasRestDocsPayload ||
5415
+ Array.isArray(mcpCtx?.docs_summary) ||
5416
+ Array.isArray(mcpCtx?.skills_summary?.channel_skills);
5417
+ const allDocs = hasRestDocsPayload
5418
+ ? extractChannelDocsPayload(docsData)
5419
+ : Array.isArray(mcpCtx?.docs_summary)
5420
+ ? mcpCtx!.docs_summary.map((d: any) => ({ ...d, id: d?.id ?? d?.doc_id }))
5421
+ : [];
5422
+ const archivedDocIds = new Set<string>(
5423
+ allDocs
5424
+ .filter((d: any) => isArchivedSkillOrDoc(d) && (d?.id || d?.doc_id))
5425
+ .map((d: any) => String(d.id ?? d.doc_id)),
5426
+ );
5427
+ const activeDocs = allDocs.filter((d: any) => !isArchivedSkillOrDoc(d));
5428
+ const activeDocById = new Map<string, any>();
5429
+ for (const d of activeDocs) {
5430
+ const id = d?.id ?? d?.doc_id;
5431
+ if (id) activeDocById.set(String(id), d);
5432
+ }
5433
+ const mcpChannelSkills = Array.isArray(mcpCtx?.skills_summary?.channel_skills)
5434
+ ? mcpCtx!.skills_summary!.channel_skills!.filter(
5435
+ (cs: any) => cs?.doc_id && !archivedDocIds.has(String(cs.doc_id)) && !isArchivedSkillOrDoc(cs),
5436
+ )
5437
+ : [];
5438
+ const mcpSkillByDocId = new Map<string, any>();
5439
+ for (const cs of mcpChannelSkills) {
5440
+ mcpSkillByDocId.set(String(cs.doc_id), cs);
5441
+ }
5442
+ const formatBriefChannelSkill = (d: any) => {
5443
+ const docId = String(d?.id ?? d?.doc_id ?? "");
5444
+ const fallback = mcpSkillByDocId.get(docId);
5445
+ const meta = d?.skill_meta || d?.skillMeta || fallback?.skill_meta || {};
5446
+ const version =
5447
+ typeof d?.version === "number"
5448
+ ? d.version
5449
+ : typeof fallback?.version === "number"
5450
+ ? fallback.version
5451
+ : undefined;
5452
+ const argHint = meta.argument_hint ?? meta.argumentHint;
5453
+ return {
5454
+ doc_id: docId,
5455
+ ...(d?.title !== undefined ? { title: d.title } : meta.name ? { title: String(meta.name) } : {}),
5456
+ ...(typeof version === "number" ? { version } : {}),
5457
+ ...(meta.name ? { name: String(meta.name) } : {}),
5458
+ ...(meta.description ? { description: String(meta.description) } : {}),
5459
+ ...(meta.trigger ? { trigger: String(meta.trigger) } : {}),
5460
+ ...(argHint ? { argument_hint: String(argHint) } : {}),
5461
+ };
5462
+ };
5463
+ const seenSkillDocIds = new Set<string>();
5464
+ const skills = activeDocs
5465
+ .filter(isSkillDoc)
5466
+ .map((d: any) => {
5467
+ const entry = formatBriefChannelSkill(d);
5468
+ seenSkillDocIds.add(entry.doc_id);
5469
+ return entry;
5470
+ });
5471
+ if (!hasRestDocsPayload) {
5472
+ for (const cs of mcpChannelSkills) {
5473
+ const docId = String(cs.doc_id);
5474
+ if (seenSkillDocIds.has(docId)) continue;
5475
+ seenSkillDocIds.add(docId);
5476
+ skills.push(formatBriefChannelSkill({ doc_id: docId, ...cs }));
5477
+ }
5478
+ }
5479
+ const docs = activeDocs
5480
+ .filter((d: any) => !isSkillDoc(d))
5481
+ .slice(0, 10)
5482
+ .map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
5483
+ const rawPersonalSkills: any[] = Array.isArray(personalSkillsData?.skills)
5484
+ ? personalSkillsData.skills
5485
+ : Array.isArray(mcpCtx?.skills_summary?.personal_skills)
5486
+ ? mcpCtx!.skills_summary!.personal_skills!
5487
+ : [];
5488
+ const personalSkills = rawPersonalSkills
5489
+ .filter((s: any) => s?.name && !isArchivedSkillOrDoc(s))
5490
+ .map((s: any) => {
5491
+ const meta = s?.skill_meta || s?.skillMeta || {};
5492
+ const desc = s?.description ?? meta.description;
5493
+ const trig = s?.trigger ?? meta.trigger;
5494
+ const argHint = s?.argument_hint ?? s?.argumentHint ?? meta.argument_hint ?? meta.argumentHint;
5495
+ return {
5496
+ name: String(s.name),
5497
+ ...(desc ? { description: String(desc) } : {}),
5498
+ ...(trig ? { trigger: String(trig) } : {}),
5499
+ ...(argHint ? { argument_hint: String(argHint) } : {}),
5500
+ ...(typeof s?.version === "number" ? { version: s.version } : {}),
5501
+ };
5502
+ });
5503
+ const okrNotConfigured = typeof okrData?.note === "string" && okrData.note.toLowerCase().includes("not configured");
5504
+ const hasRestOkrSnapshot = Boolean(
5505
+ okrData && !okrNotConfigured && (Array.isArray(okrData.objectives) || Array.isArray(okrData.tasks)),
5506
+ );
5507
+ const hasMcpOkrSummary = Boolean(
5508
+ mcpCtx?.okr_summary &&
5509
+ typeof mcpCtx.okr_summary === "object" &&
5510
+ typeof mcpCtx.okr_summary.active_objective_count === "number",
5511
+ );
5512
+ const okrReadable = hasRestOkrSnapshot || hasMcpOkrSummary;
5513
+ const activeRawObjectives = (okrData?.objectives || []).filter(
5514
+ (o: any) => !o.archived && o.id && String(o.status || "active").toLowerCase() === "active",
5515
+ );
5516
+ let okrSummary:
5517
+ | {
5518
+ active_objective_count: number;
5519
+ total_task_count: number;
5520
+ ready_for_me_count: number;
5521
+ doing_for_me_count?: number;
5522
+ blocked_for_me_count?: number;
5523
+ ready_task_count?: number;
5524
+ doing_task_count?: number;
5525
+ blocked_task_count?: number;
5526
+ }
5527
+ | null = null;
5528
+ if (hasMcpOkrSummary && typeof mcpCtx!.okr_summary!.doing_for_me_count === "number") {
5529
+ const s = mcpCtx!.okr_summary!;
5530
+ okrSummary = {
5531
+ active_objective_count: s.active_objective_count,
5532
+ total_task_count: s.total_task_count,
5533
+ ready_for_me_count: s.ready_for_me_count,
5534
+ doing_for_me_count: s.doing_for_me_count,
5535
+ ...(typeof s.blocked_for_me_count === "number" ? { blocked_for_me_count: s.blocked_for_me_count } : {}),
5536
+ ...(typeof s.ready_task_count === "number" ? { ready_task_count: s.ready_task_count } : {}),
5537
+ ...(typeof s.doing_task_count === "number" ? { doing_task_count: s.doing_task_count } : {}),
5538
+ ...(typeof s.blocked_task_count === "number" ? { blocked_task_count: s.blocked_task_count } : {}),
5539
+ };
5540
+ } else if (hasRestOkrSnapshot) {
5541
+ const archivedObjIds = new Set<string>(
5542
+ (okrData?.objectives || []).filter((o: any) => o?.archived && o?.id).map((o: any) => String(o.id)),
5543
+ );
5544
+ const snapshotTasks = (Array.isArray(okrData?.tasks) ? okrData.tasks : []).filter(
5545
+ (t: any) => t && typeof t.id === "string" && !archivedObjIds.has(String(t.objective_id || "")),
5546
+ );
5547
+ const taskStatusById = new Map<string, string>();
5548
+ for (const t of snapshotTasks) taskStatusById.set(String(t.id), String(t.status || "todo"));
5549
+ const isTaskReady = (t: any): boolean => {
5550
+ if (String(t.status || "todo") !== "todo") return false;
5551
+ if (Array.isArray(t.unresolved_depends_on)) return t.unresolved_depends_on.length === 0;
5552
+ if (typeof t.ready === "boolean") return t.ready;
5553
+ const deps = Array.isArray(t.depends_on)
5554
+ ? t.depends_on.filter((d: unknown): d is string => typeof d === "string" && d.length > 0)
5555
+ : [];
5556
+ return deps.every((depId: string) => taskStatusById.get(depId) === "done");
5557
+ };
5558
+ const isMine = (t: any): boolean => Boolean(AGENT_ID && t?.assignee === AGENT_ID);
5559
+ okrSummary = {
5560
+ active_objective_count: activeRawObjectives.length,
5561
+ total_task_count: snapshotTasks.length,
5562
+ ready_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && isTaskReady(t)).length,
5563
+ doing_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && t.status === "doing").length,
5564
+ blocked_for_me_count: snapshotTasks.filter((t: any) => isMine(t) && t.status === "blocked").length,
5565
+ ready_task_count: snapshotTasks.filter((t: any) => isTaskReady(t)).length,
5566
+ doing_task_count: snapshotTasks.filter((t: any) => t.status === "doing").length,
5567
+ blocked_task_count: snapshotTasks.filter((t: any) => t.status === "blocked").length,
5568
+ };
5569
+ } else if (hasMcpOkrSummary) {
5570
+ const s = mcpCtx!.okr_summary!;
5571
+ okrSummary = {
5572
+ active_objective_count: s.active_objective_count,
5573
+ total_task_count: s.total_task_count,
5574
+ ready_for_me_count: s.ready_for_me_count,
5575
+ };
5576
+ }
5577
+ const visibleObjectiveIdSet = new Set<string>(activeRawObjectives.map((o: any) => String(o.id)));
5578
+ const snapshotLoopSummary =
5579
+ okrData?.loop_summary && typeof okrData.loop_summary === "object" ? okrData.loop_summary : null;
5580
+ const hasSnapshotLoopSummary = Boolean(
5581
+ snapshotLoopSummary &&
5582
+ (Array.isArray(snapshotLoopSummary.okr_wake_objective_ids) ||
5583
+ Array.isArray(snapshotLoopSummary.okr_watch_objective_ids) ||
5584
+ Array.isArray(snapshotLoopSummary.unarmed_objective_ids)),
5585
+ );
5586
+ const hasMcpLoopSummary = Boolean(mcpCtx?.loop_summary && typeof mcpCtx.loop_summary === "object");
5587
+ const hasRestLoopsArray = Array.isArray(loopsData?.loops);
5588
+ const loopCoverageKnown = hasMcpLoopSummary || hasSnapshotLoopSummary || hasRestLoopsArray;
5589
+ const wakeSet = new Set<string>();
5590
+ const watchSet = new Set<string>();
5591
+ for (const summarySource of [mcpCtx?.loop_summary, snapshotLoopSummary]) {
5592
+ if (!summarySource) continue;
5593
+ for (const rawId of summarySource.okr_wake_objective_ids || []) {
5594
+ const id = String(rawId || "");
5595
+ if (visibleObjectiveIdSet.has(id)) wakeSet.add(id);
5596
+ }
5597
+ for (const rawId of summarySource.okr_watch_objective_ids || []) {
5598
+ const id = String(rawId || "");
5599
+ if (visibleObjectiveIdSet.has(id)) watchSet.add(id);
5600
+ }
5601
+ }
5602
+ const activeRestLoops = hasRestLoopsArray
5603
+ ? (loopsData.loops as any[]).filter((l: any) => l && l.paused !== true && l.status !== "paused" && l.paused_at == null)
5604
+ : [];
5605
+ for (const l of activeRestLoops) {
5606
+ const objId = typeof l?.objective_id === "string" ? l.objective_id : "";
5607
+ if (!objId || !visibleObjectiveIdSet.has(objId)) continue;
5608
+ if (l.mode === "okr_wake") wakeSet.add(objId);
5609
+ else if (l.mode === "okr_watch") watchSet.add(objId);
5610
+ }
5611
+ const objectives = activeRawObjectives.map((o: any) => {
5612
+ const id = String(o.id);
5613
+ const open = (okrData?.tasks || []).filter((t: any) => t.objective_id === id && t.status !== "done").length;
5614
+ return {
5615
+ id,
5616
+ title: o.title,
5617
+ open_tasks: open,
5618
+ ...(loopCoverageKnown
5619
+ ? {
5620
+ okr_wake_armed: wakeSet.has(id),
5621
+ okr_watch_armed: watchSet.has(id),
5622
+ }
5623
+ : {}),
5624
+ };
4036
5625
  });
5626
+ const loopSummary = loopCoverageKnown
5627
+ ? {
5628
+ active_loop_count:
5629
+ typeof mcpCtx?.loop_summary?.active_loop_count === "number"
5630
+ ? mcpCtx.loop_summary.active_loop_count
5631
+ : typeof snapshotLoopSummary?.active_loop_count === "number"
5632
+ ? snapshotLoopSummary.active_loop_count
5633
+ : activeRestLoops.length,
5634
+ ...(typeof mcpCtx?.loop_summary?.my_active_loop_count === "number"
5635
+ ? { my_active_loop_count: mcpCtx.loop_summary.my_active_loop_count }
5636
+ : typeof snapshotLoopSummary?.my_active_loop_count === "number"
5637
+ ? { my_active_loop_count: snapshotLoopSummary.my_active_loop_count }
5638
+ : AGENT_ID && hasRestLoopsArray
5639
+ ? { my_active_loop_count: activeRestLoops.filter((l: any) => l?.agent_id === AGENT_ID).length }
5640
+ : {}),
5641
+ okr_wake_objective_ids: [...wakeSet],
5642
+ okr_watch_objective_ids: [...watchSet],
5643
+ unarmed_objective_ids: activeRawObjectives
5644
+ .map((o: any) => String(o.id))
5645
+ .filter((id: string) => !wakeSet.has(id)),
5646
+ }
5647
+ : null;
5648
+ const activeTaskLinkedDocs: Array<{
5649
+ task_id: string;
5650
+ doc_id: string;
5651
+ title?: string;
5652
+ is_skill?: boolean;
5653
+ }> = [];
5654
+ const seenTaskDocPair = new Set<string>();
5655
+ for (const t of Array.isArray(okrData?.tasks) ? okrData.tasks : []) {
5656
+ if (!t?.id || t.archived || String(t.status || "todo") === "done") continue;
5657
+ if (t.objective_id && !visibleObjectiveIdSet.has(String(t.objective_id))) continue;
5658
+ const refs = Array.isArray(t.linked_channel_docs) ? t.linked_channel_docs : [];
5659
+ for (const ref of refs) {
5660
+ const docId = typeof ref?.doc_id === "string" ? ref.doc_id.trim() : "";
5661
+ const refCh = typeof ref?.channel_id === "string" ? ref.channel_id.trim() : "";
5662
+ if (!docId || (refCh && refCh !== chatId)) continue;
5663
+ if (archivedDocIds.has(docId)) continue;
5664
+ const pairKey = `${t.id}:${docId}`;
5665
+ if (seenTaskDocPair.has(pairKey)) continue;
5666
+ seenTaskDocPair.add(pairKey);
5667
+ const matchedDoc = activeDocById.get(docId);
5668
+ activeTaskLinkedDocs.push({
5669
+ task_id: String(t.id),
5670
+ doc_id: docId,
5671
+ ...(matchedDoc?.title ? { title: String(matchedDoc.title) } : {}),
5672
+ ...(matchedDoc && isSkillDoc(matchedDoc) ? { is_skill: true } : {}),
5673
+ });
5674
+ }
5675
+ }
4037
5676
  // Loadable extended tool groups — surfaced here so entering a room hands
4038
5677
  // you the full capability menu (not just skills). Without this an agent has
4039
5678
  // to already KNOW to call list_tool_groups; now "what can I do here / how to
@@ -4045,6 +5684,65 @@ const handleToolCall = async (request: any): Promise<any> => {
4045
5684
  tool_count: g.tools.length,
4046
5685
  loaded: loadedToolGroups.has(g.name),
4047
5686
  }));
5687
+ const rawWakeSummary =
5688
+ wakeHealthData?.observation_only === true && wakeHealthData?.counts
5689
+ ? {
5690
+ observation_only: true as const,
5691
+ counts: wakeHealthData.counts,
5692
+ attention_agents: Array.isArray(wakeHealthData.agents) ? wakeHealthData.agents : [],
5693
+ }
5694
+ : mcpCtx?.wake_health_summary?.observation_only === true && mcpCtx?.wake_health_summary?.counts
5695
+ ? {
5696
+ observation_only: true as const,
5697
+ counts: mcpCtx.wake_health_summary.counts,
5698
+ attention_agents: Array.isArray(mcpCtx.wake_health_summary.attention_agents)
5699
+ ? mcpCtx.wake_health_summary.attention_agents
5700
+ : [],
5701
+ }
5702
+ : null;
5703
+ const wakeHealthSummary =
5704
+ rawWakeSummary && typeof rawWakeSummary.counts?.total_cloud_agents === "number"
5705
+ ? {
5706
+ observation_only: true as const,
5707
+ counts: {
5708
+ total_cloud_agents: Number(rawWakeSummary.counts.total_cloud_agents) || 0,
5709
+ ok: Number(rawWakeSummary.counts.ok) || 0,
5710
+ auth_required: Number(rawWakeSummary.counts.auth_required) || 0,
5711
+ timeout: Number(rawWakeSummary.counts.timeout) || 0,
5712
+ error: Number(rawWakeSummary.counts.error) || 0,
5713
+ unobserved: Number(rawWakeSummary.counts.unobserved) || 0,
5714
+ },
5715
+ attention_agents: rawWakeSummary.attention_agents
5716
+ .filter((a: any) => {
5717
+ const aid = typeof a?.agent_id === "string" ? a.agent_id.trim() : "";
5718
+ if (!aid || isHumanPiiHandle(aid) || /^(?:ac_|sk-)/i.test(aid)) return false;
5719
+ const cloudStatus = String(a?.cloud_status || "active");
5720
+ const wakeStatus = typeof a?.last_wake_status === "string" ? a.last_wake_status : "";
5721
+ return (
5722
+ cloudStatus !== "active" ||
5723
+ wakeStatus === "auth_required" ||
5724
+ wakeStatus === "timeout" ||
5725
+ wakeStatus === "error"
5726
+ );
5727
+ })
5728
+ .slice(0, 16)
5729
+ .map((a: any) => {
5730
+ const rawName = typeof a?.name === "string" ? a.name.trim() : "";
5731
+ const safeName =
5732
+ rawName && !isHumanPiiHandle(rawName) && !/\b(?:ac_|sk-)[A-Za-z0-9_-]{8,}\b/i.test(rawName)
5733
+ ? rawName
5734
+ : undefined;
5735
+ return {
5736
+ agent_id: String(a.agent_id).trim(),
5737
+ ...(safeName ? { name: safeName } : {}),
5738
+ runtime: String(a.runtime || "unknown"),
5739
+ cloud_status: String(a.cloud_status || "unknown"),
5740
+ ...(typeof a.last_wake_status === "string" ? { last_wake_status: a.last_wake_status } : {}),
5741
+ ...(typeof a.last_wake_at === "string" ? { last_wake_at: a.last_wake_at } : {}),
5742
+ };
5743
+ }),
5744
+ }
5745
+ : null;
4048
5746
  return JSON.stringify({
4049
5747
  channel: chatId,
4050
5748
  ...(mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {}),
@@ -4053,34 +5751,50 @@ const handleToolCall = async (request: any): Promise<any> => {
4053
5751
  ? { total: memberIds.length, online }
4054
5752
  : { total: null, note: "roster unreadable — you are likely not a member of this channel (or it does not exist)" },
4055
5753
  ...(membersReadable ? { agent_peers: agentPeers } : {}),
5754
+ okr_readable: okrReadable,
5755
+ docs_readable: docsReadable,
4056
5756
  okr_objectives: objectives,
5757
+ ...(okrSummary ? { okr_summary: okrSummary } : {}),
5758
+ ...(loopSummary ? { loop_summary: loopSummary } : {}),
5759
+ ...(wakeHealthSummary ? { wake_health_summary: wakeHealthSummary } : {}),
4057
5760
  skills,
5761
+ ...(personalSkills.length > 0 ? { personal_skills: personalSkills } : {}),
5762
+ ...(activeTaskLinkedDocs.length > 0 ? { active_task_linked_docs: activeTaskLinkedDocs } : {}),
4058
5763
  docs,
4059
5764
  tool_groups: toolGroups,
4060
5765
  tips: [
4061
5766
  "load_tool_group(name) reveals an extended group's tools (see tool_groups above; loaded:false = not yet active)",
4062
- "load_skill(chat_id, doc_id) activates a channel skill; list_skills(chat_id) lists them",
5767
+ "load_skill(chat_id, doc_id) activates a channel skill; load_skill(name) loads a personal skill; list_skills(chat_id) lists both",
4063
5768
  "okr_list / get_history for deeper context",
4064
- "/loop <interval> <prompt> works in joined groups and owner-agent DMs; keep group follow-ups in that group (okr: prefix = wake mode)",
5769
+ "create_loop(channel_id, mode, ...) (or /loop <interval> <prompt>) arms okr_wake / okr_watch / prompt loops; check loop_summary.unarmed_objective_ids",
4065
5770
  ],
4066
5771
  });
4067
5772
  }
4068
5773
 
4069
5774
  if (name === "join_channel") {
4070
5775
  const { chat_id } = args as any;
4071
- // Try WebSocket join first, then verify membership via REST
5776
+ // Try WebSocket join + authoritative REST /join (for non-WS / proxied clients)
4072
5777
  if (ws && ws.readyState === WebSocket.OPEN) {
4073
5778
  try { ws.send(JSON.stringify({ type: "join_channel", channel_id: chat_id, agent_id: AGENT_ID })); } catch {}
4074
5779
  }
4075
- // Verify by checking membership
4076
5780
  try {
4077
- await new Promise(r => setTimeout(r, 500)); // wait for server to process
5781
+ const joinRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/join`, {
5782
+ method: "POST",
5783
+ headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
5784
+ body: JSON.stringify({ sender_id: AGENT_ID }),
5785
+ });
5786
+ if (joinRes.ok) {
5787
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
5788
+ const brief = await channelBrief(chat_id).catch(() => "");
5789
+ return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
5790
+ }
5791
+ await new Promise(r => setTimeout(r, 300));
4078
5792
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4079
5793
  if (r.ok) {
4080
5794
  const data = await r.json() as any;
4081
5795
  const isMember = (data.members || []).some((m: any) => m.agent_id === AGENT_ID);
4082
5796
  if (isMember) {
4083
- // P3: joining hands you the room's capability synopsis immediately.
5797
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
4084
5798
  const brief = await channelBrief(chat_id).catch(() => "");
4085
5799
  return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
4086
5800
  }
@@ -4326,26 +6040,6 @@ const handleToolCall = async (request: any): Promise<any> => {
4326
6040
  return { content: [{ type: "text", text: gateNotice + text + pinLine }] };
4327
6041
  }
4328
6042
 
4329
- if (name === "list_channels") {
4330
- const { limit = 50 } = args as any;
4331
- try {
4332
- const r = await apiFetch(`${REST_URL}/api/channels/discover?limit=${Math.max(1, Math.min(Number(limit) || 50, 500))}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4333
- if (r.ok) {
4334
- const data = await r.json() as any;
4335
- const channels = (data.channels || []);
4336
- if (channels.length === 0) return { content: [{ type: "text", text: "No public channels found." }] };
4337
- // Show the FULL channel id — agents copy it straight into reply /
4338
- // get_history / join_channel, all of which need the complete UUID.
4339
- // A truncated 8-char prefix here makes every downstream call 404.
4340
- 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");
4341
- return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
4342
- }
4343
- return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
4344
- } catch (e) {
4345
- return { content: [{ type: "text", text: `Error: ${e}` }] };
4346
- }
4347
- }
4348
-
4349
6043
  if (name === "find_dm") {
4350
6044
  const { target_agent_id } = args as any;
4351
6045
  if (!target_agent_id || typeof target_agent_id !== "string") {
@@ -4390,16 +6084,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4390
6084
  }
4391
6085
 
4392
6086
  if (name === "list_loops") {
6087
+ const checked = validateListLoopsInput(args);
6088
+ if (!checked.ok) {
6089
+ return { content: [{ type: "text", text: checked.error }], isError: true };
6090
+ }
4393
6091
  try {
4394
6092
  const r = await apiFetch(`${REST_URL}/api/loops/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4395
6093
  if (!r.ok) return { content: [{ type: "text", text: `Failed (${r.status})` }] };
4396
6094
  const data = await r.json() as any;
4397
- const loops = Array.isArray(data?.loops) ? data.loops : [];
4398
- if (loops.length === 0) return { content: [{ type: "text", text: "No loops registered for you." }] };
6095
+ const rawLoops = Array.isArray(data?.loops) ? data.loops : [];
6096
+ const hasFilter = Boolean(
6097
+ checked.value.channel_id || checked.value.status || checked.value.mode || checked.value.objective_id,
6098
+ );
6099
+ const loops = rawLoops.filter((l: any) => {
6100
+ if (!l) return false;
6101
+ if (checked.value.channel_id && l.channel_id !== checked.value.channel_id) return false;
6102
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
6103
+ if (checked.value.status && (paused ? "paused" : "active") !== checked.value.status) return false;
6104
+ const normMode = l.mode === "okr_wake" || l.mode === "okr_watch" ? l.mode : "prompt";
6105
+ if (checked.value.mode && normMode !== checked.value.mode) return false;
6106
+ if (checked.value.objective_id && l.objective_id !== checked.value.objective_id) return false;
6107
+ return true;
6108
+ });
6109
+ if (loops.length === 0) {
6110
+ return { content: [{ type: "text", text: hasFilter ? "No matching loops found." : "No loops registered for you." }] };
6111
+ }
4399
6112
  const lines = loops.map((l: any) => {
4400
- 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";
6113
+ const targetSuffix = Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : "";
6114
+ const watchFlags = l.mode === "okr_watch"
6115
+ ? [
6116
+ l.watch_idle ? "+idle" : "",
6117
+ l.watch_supply ? "+supply" : "",
6118
+ typeof l.stall_minutes === "number" ? `+stall=${l.stall_minutes}m` : "",
6119
+ ].filter(Boolean).join("")
6120
+ : "";
6121
+ const mode = l.mode === "okr_wake"
6122
+ ? `okr_wake → ${l.objective_id}${targetSuffix}`
6123
+ : l.mode === "okr_watch"
6124
+ ? `okr_watch${watchFlags ? `(${watchFlags})` : ""} → ${l.objective_id}${targetSuffix}`
6125
+ : `static${targetSuffix}`;
6126
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
4401
6127
  const nextIn = typeof l.next_tick_ms === "number" ? Math.max(0, Math.round((l.next_tick_ms - Date.now()) / 60000)) : "?";
4402
- return `• ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | next ~${nextIn}m`;
6128
+ const state = paused ? "paused" : `${l.status || "active"} | next ~${nextIn}m`;
6129
+ return `• ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | ${state}`;
4403
6130
  }).join("\n");
4404
6131
  return { content: [{ type: "text", text: `${loops.length} loop(s):\n${lines}` }] };
4405
6132
  } catch (e: any) {
@@ -4559,7 +6286,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4559
6286
  const list = msgs.map((m: any) => formatHistoryMessage(m, false)).join("\n");
4560
6287
  return { content: [{ type: "text", text: `${msgs.length} messages:\n${list}` }] };
4561
6288
  }
4562
- return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
6289
+ return { content: [{ type: "text", text: `Failed to get history (${r.status})` }], isError: true };
4563
6290
  } catch (e) {
4564
6291
  return { content: [{ type: "text", text: `Error: ${e}` }] };
4565
6292
  }
@@ -4570,13 +6297,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4570
6297
  }
4571
6298
 
4572
6299
  if (name === "list_channel_docs") {
4573
- const { chat_id, level } = args as { chat_id: string; level?: number | string };
4574
- const qs = new URLSearchParams();
4575
- const normalizedLevel = normalizeChannelDocLevel(level);
4576
- if (level !== undefined && normalizedLevel === null) {
4577
- return { content: [{ type: "text", text: "list_channel_docs failed: level must be 1|2|3|4" }], isError: true };
6300
+ const check = validateListChannelDocsInput(args);
6301
+ if (!check.ok) {
6302
+ return { content: [{ type: "text", text: check.error }], isError: true };
4578
6303
  }
4579
- if (normalizedLevel !== null) qs.set("level", String(normalizedLevel));
6304
+ const { chat_id, level: normalizedLevel, active_only } = check.value;
6305
+ const qs = new URLSearchParams();
6306
+ if (normalizedLevel !== undefined) qs.set("level", String(normalizedLevel));
6307
+ if (active_only === true) qs.set("active_only", "1");
4580
6308
  const url = `${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${qs.toString() ? `?${qs}` : ""}`;
4581
6309
  try {
4582
6310
  const r = await apiFetch(url, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -4591,9 +6319,17 @@ const handleToolCall = async (request: any): Promise<any> => {
4591
6319
  }
4592
6320
 
4593
6321
  if (name === "get_channel_doc") {
4594
- const { chat_id, doc_id } = args as { chat_id: string; doc_id: string };
6322
+ const { chat_id, doc_id } = (args ?? {}) as { chat_id?: unknown; doc_id?: unknown };
6323
+ const listCheck = validateListChannelDocsInput({ chat_id });
6324
+ if (!listCheck.ok) {
6325
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "get_channel_doc") }], isError: true };
6326
+ }
6327
+ const docCheck = validateChannelDocIdInput(doc_id, "get_channel_doc");
6328
+ if (!docCheck.ok) {
6329
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
6330
+ }
4595
6331
  try {
4596
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
6332
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}`, {
4597
6333
  headers: { "Authorization": `Bearer ${TOKEN}` },
4598
6334
  });
4599
6335
  const text = await r.text();
@@ -4607,43 +6343,102 @@ const handleToolCall = async (request: any): Promise<any> => {
4607
6343
  }
4608
6344
 
4609
6345
  if (name === "upsert_channel_doc") {
4610
- const { chat_id, doc_id, title, kind, level, body_markdown, expected_version } = args as {
4611
- chat_id: string;
4612
- doc_id: string;
4613
- title: string;
4614
- kind: string;
4615
- level: number | string;
4616
- body_markdown: string;
4617
- expected_version: number;
4618
- };
4619
- const normalizedLevel = normalizeChannelDocLevel(level);
4620
- if (normalizedLevel === null) {
4621
- return { content: [{ type: "text", text: "upsert_channel_doc failed: level must be 1|2|3|4" }], isError: true };
6346
+ const check = validateUpsertChannelDocInput(args);
6347
+ if (!check.ok) {
6348
+ return { content: [{ type: "text", text: check.error }], isError: true };
6349
+ }
6350
+ const parsed = check.value;
6351
+ try {
6352
+ const r = parsed.mode === "archive"
6353
+ ? await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
6354
+ method: "DELETE",
6355
+ headers: {
6356
+ "Authorization": `Bearer ${TOKEN}`,
6357
+ "If-Match": String(parsed.expected_version),
6358
+ },
6359
+ })
6360
+ : await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
6361
+ method: "PUT",
6362
+ headers: {
6363
+ "Content-Type": "application/json",
6364
+ "Authorization": `Bearer ${TOKEN}`,
6365
+ "If-Match": String(parsed.expected_version),
6366
+ },
6367
+ body: JSON.stringify(parsed.body),
6368
+ });
6369
+ const text = await r.text();
6370
+ if (!r.ok) {
6371
+ return { content: [{ type: "text", text: `upsert_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
6372
+ }
6373
+ if (parsed.mode === "archive" && !text.trim()) {
6374
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
6375
+ return {
6376
+ content: [{
6377
+ type: "text",
6378
+ text: JSON.stringify({
6379
+ ok: true,
6380
+ archived: true,
6381
+ chat_id: parsed.chat_id,
6382
+ doc_id: parsed.doc_id,
6383
+ ...(Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}),
6384
+ }),
6385
+ }],
6386
+ };
6387
+ }
6388
+ return { content: [{ type: "text", text }] };
6389
+ } catch (e: any) {
6390
+ return { content: [{ type: "text", text: `upsert_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6391
+ }
6392
+ }
6393
+
6394
+ if (name === "archive_channel_doc") {
6395
+ const check = validateArchiveChannelDocInput(args);
6396
+ if (!check.ok) {
6397
+ return { content: [{ type: "text", text: check.error }], isError: true };
4622
6398
  }
6399
+ const { chat_id, doc_id, expected_version } = check.value;
4623
6400
  try {
4624
6401
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
4625
- method: "PUT",
6402
+ method: "DELETE",
4626
6403
  headers: {
4627
- "Content-Type": "application/json",
4628
6404
  "Authorization": `Bearer ${TOKEN}`,
4629
6405
  "If-Match": String(expected_version),
4630
6406
  },
4631
- body: JSON.stringify({ title, kind, level: normalizedLevel, body_markdown }),
4632
6407
  });
4633
6408
  const text = await r.text();
4634
6409
  if (!r.ok) {
4635
- return { content: [{ type: "text", text: `upsert_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
6410
+ return { content: [{ type: "text", text: `archive_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
4636
6411
  }
4637
- return { content: [{ type: "text", text }] };
6412
+ const normalized = text.trim()
6413
+ ? text
6414
+ : (() => {
6415
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
6416
+ return JSON.stringify({
6417
+ ok: true,
6418
+ archived: true,
6419
+ chat_id,
6420
+ doc_id,
6421
+ ...(Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}),
6422
+ });
6423
+ })();
6424
+ return { content: [{ type: "text", text: normalized }] };
4638
6425
  } catch (e: any) {
4639
- return { content: [{ type: "text", text: `upsert_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6426
+ return { content: [{ type: "text", text: `archive_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4640
6427
  }
4641
6428
  }
4642
6429
 
4643
6430
  if (name === "list_channel_doc_revisions") {
4644
- const { chat_id, doc_id } = args as { chat_id: string; doc_id: string };
6431
+ const { chat_id, doc_id } = (args ?? {}) as { chat_id?: unknown; doc_id?: unknown };
6432
+ const listCheck = validateListChannelDocsInput({ chat_id });
6433
+ if (!listCheck.ok) {
6434
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "list_channel_doc_revisions") }], isError: true };
6435
+ }
6436
+ const docCheck = validateChannelDocIdInput(doc_id, "list_channel_doc_revisions");
6437
+ if (!docCheck.ok) {
6438
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
6439
+ }
4645
6440
  try {
4646
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
6441
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}/revisions`, {
4647
6442
  headers: { "Authorization": `Bearer ${TOKEN}` },
4648
6443
  });
4649
6444
  const text = await r.text();
@@ -4685,14 +6480,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4685
6480
  }
4686
6481
 
4687
6482
  if (name === "okr_create_objective") {
4688
- const { title, horizon, owner, parent_id, due, discussion_channel_id } = args as {
4689
- title: string; horizon: string; owner?: string; parent_id?: string; due?: string; discussion_channel_id?: string;
6483
+ const { title, horizon, owner, parent_id, due, discussion_channel_id, narrative, linked_channel_docs } = args as {
6484
+ title: string;
6485
+ horizon: string;
6486
+ owner?: string;
6487
+ parent_id?: string;
6488
+ due?: string;
6489
+ discussion_channel_id?: string;
6490
+ narrative?: unknown;
6491
+ linked_channel_docs?: unknown;
4690
6492
  };
4691
6493
  const body: Record<string, unknown> = { title, horizon };
4692
6494
  if (owner) body.owner = owner;
4693
- if (parent_id) body.parent_id = parent_id;
6495
+ if (parent_id !== undefined) {
6496
+ const parentCheck = validateOkrParentIdOptionalInput(parent_id);
6497
+ if (!parentCheck.ok) {
6498
+ return { content: [{ type: "text", text: `okr_create_objective invalid parent_id: ${parentCheck.error}` }], isError: true };
6499
+ }
6500
+ if (parentCheck.value) body.parent_id = parentCheck.value;
6501
+ }
4694
6502
  if (due) body.due = due;
4695
6503
  if (discussion_channel_id) body.discussion_channel_id = discussion_channel_id;
6504
+ if (narrative !== undefined) {
6505
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
6506
+ if (!narCheck.ok) {
6507
+ return { content: [{ type: "text", text: `okr_create_objective invalid narrative: ${narCheck.error}` }], isError: true };
6508
+ }
6509
+ if (narCheck.value) body.narrative = narCheck.value;
6510
+ }
6511
+ if (linked_channel_docs !== undefined) {
6512
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
6513
+ if (!docsCheck.ok) {
6514
+ return { content: [{ type: "text", text: `okr_create_objective invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6515
+ }
6516
+ if (docsCheck.value.length > 0) {
6517
+ if (!discussion_channel_id || !discussion_channel_id.trim()) {
6518
+ return {
6519
+ content: [{ type: "text", text: "okr_create_objective invalid linked_channel_docs: discussion_channel_id is required when attaching linked_channel_docs" }],
6520
+ isError: true,
6521
+ };
6522
+ }
6523
+ body.linked_channel_docs = docsCheck.value;
6524
+ }
6525
+ }
4696
6526
  try {
4697
6527
  const r = await apiFetch(`${REST_URL}/api/okr/objectives`, {
4698
6528
  method: "POST",
@@ -4703,20 +6533,103 @@ const handleToolCall = async (request: any): Promise<any> => {
4703
6533
  if (!r.ok) {
4704
6534
  return { content: [{ type: "text", text: `okr_create_objective failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4705
6535
  }
4706
- return { content: [{ type: "text", text: `Created: ${text}` }] };
6536
+ let outText = text;
6537
+ if (discussion_channel_id && !discussion_channel_id.startsWith("dm-") && isSafeLoopIdentifier(discussion_channel_id)) {
6538
+ try {
6539
+ const parsed = JSON.parse(text) as any;
6540
+ const createdObjId = typeof parsed?.objective?.id === "string" ? parsed.objective.id : "";
6541
+ if (parsed && typeof parsed === "object" && /^[A-Za-z0-9_-]{6,80}$/.test(createdObjId)) {
6542
+ outText = JSON.stringify({
6543
+ ...parsed,
6544
+ loop_guard_hint: {
6545
+ okr_wake_armed: false,
6546
+ recommended_tool: "create_loop",
6547
+ recommended_arguments: {
6548
+ channel_id: discussion_channel_id,
6549
+ mode: "okr_wake",
6550
+ interval: "5m",
6551
+ objective_id: createdObjId,
6552
+ },
6553
+ },
6554
+ });
6555
+ }
6556
+ } catch {}
6557
+ }
6558
+ return { content: [{ type: "text", text: `Created: ${outText}` }] };
4707
6559
  } catch (e: any) {
4708
6560
  return { content: [{ type: "text", text: `okr_create_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4709
6561
  }
4710
6562
  }
4711
6563
 
6564
+ if (name === "okr_update_objective") {
6565
+ const validated = validateOkrUpdateObjectiveInput(args);
6566
+ if (!validated.ok) {
6567
+ return { content: [{ type: "text", text: `okr_update_objective invalid arguments: ${validated.error}` }], isError: true };
6568
+ }
6569
+ const { objective_id, body } = validated.value;
6570
+ try {
6571
+ const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}`, {
6572
+ method: "PATCH",
6573
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
6574
+ body: JSON.stringify(body),
6575
+ });
6576
+ const text = await r.text();
6577
+ if (!r.ok) {
6578
+ return { content: [{ type: "text", text: `okr_update_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
6579
+ }
6580
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
6581
+ } catch (e: any) {
6582
+ return { content: [{ type: "text", text: `okr_update_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6583
+ }
6584
+ }
6585
+
4712
6586
  if (name === "okr_add_task") {
4713
- const { objective_id, title, assignee, contributes_to, depends_on, due } = args as {
4714
- objective_id: string; title: string; assignee: string; contributes_to?: string[]; depends_on?: string[]; due?: string;
6587
+ const { objective_id, title, assignee, contributes_to, depends_on, linked_channel_docs, due } = args as {
6588
+ objective_id: string;
6589
+ title: string;
6590
+ assignee: string;
6591
+ contributes_to?: unknown;
6592
+ depends_on?: unknown;
6593
+ linked_channel_docs?: unknown;
6594
+ due?: unknown;
4715
6595
  };
4716
- const body: Record<string, unknown> = { title, assignee };
4717
- if (Array.isArray(contributes_to) && contributes_to.length > 0) body.contributes_to = contributes_to;
4718
- if (Array.isArray(depends_on) && depends_on.length > 0) body.depends_on = depends_on;
4719
- if (due) body.due = due;
6596
+ const titleCheck = validateOkrTaskTitleInput(title);
6597
+ if (!titleCheck.ok) {
6598
+ return { content: [{ type: "text", text: `okr_add_task invalid title: ${titleCheck.error}` }], isError: true };
6599
+ }
6600
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
6601
+ if (!assigneeCheck.ok) {
6602
+ return { content: [{ type: "text", text: `okr_add_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
6603
+ }
6604
+ const body: Record<string, unknown> = { title: titleCheck.value, assignee: assigneeCheck.value };
6605
+ if (contributes_to !== undefined) {
6606
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
6607
+ if (!contribCheck.ok) {
6608
+ return { content: [{ type: "text", text: `okr_add_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
6609
+ }
6610
+ if (contribCheck.value.length > 0) body.contributes_to = contribCheck.value;
6611
+ }
6612
+ if (depends_on !== undefined) {
6613
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on);
6614
+ if (!depsCheck.ok) {
6615
+ return { content: [{ type: "text", text: `okr_add_task invalid depends_on: ${depsCheck.error}` }], isError: true };
6616
+ }
6617
+ if (depsCheck.value.length > 0) body.depends_on = depsCheck.value;
6618
+ }
6619
+ if (linked_channel_docs !== undefined) {
6620
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
6621
+ if (!docsCheck.ok) {
6622
+ return { content: [{ type: "text", text: `okr_add_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6623
+ }
6624
+ if (docsCheck.value.length > 0) body.linked_channel_docs = docsCheck.value;
6625
+ }
6626
+ if (due !== undefined && due !== null && due !== "") {
6627
+ const dueCheck = validateOkrTaskDueInput(due);
6628
+ if (!dueCheck.ok) {
6629
+ return { content: [{ type: "text", text: `okr_add_task invalid due: ${dueCheck.error}` }], isError: true };
6630
+ }
6631
+ if (dueCheck.value) body.due = dueCheck.value;
6632
+ }
4720
6633
  try {
4721
6634
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/tasks`, {
4722
6635
  method: "POST",
@@ -4734,16 +6647,113 @@ const handleToolCall = async (request: any): Promise<any> => {
4734
6647
  }
4735
6648
 
4736
6649
  if (name === "okr_update_task") {
4737
- 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 };
6650
+ const {
6651
+ task_id,
6652
+ title,
6653
+ status,
6654
+ assignee,
6655
+ contributes_to,
6656
+ blocked_reason,
6657
+ blocker_agent,
6658
+ depends_on,
6659
+ linked_channel_docs,
6660
+ due,
6661
+ evidence,
6662
+ append_evidence,
6663
+ if_match_updated_at,
6664
+ } = args as {
6665
+ task_id: string;
6666
+ title?: unknown;
6667
+ status?: string;
6668
+ assignee?: unknown;
6669
+ contributes_to?: unknown;
6670
+ blocked_reason?: string;
6671
+ blocker_agent?: string;
6672
+ depends_on?: unknown;
6673
+ linked_channel_docs?: unknown;
6674
+ due?: unknown;
6675
+ evidence?: unknown;
6676
+ append_evidence?: unknown;
6677
+ if_match_updated_at?: unknown;
6678
+ };
6679
+ if (evidence !== undefined && append_evidence !== undefined) {
6680
+ return {
6681
+ content: [{ type: "text", text: "okr_update_task invalid arguments: cannot pass both evidence and append_evidence" }],
6682
+ isError: true,
6683
+ };
6684
+ }
4738
6685
  const patch: Record<string, unknown> = {};
6686
+ if (title !== undefined) {
6687
+ const titleCheck = validateOkrTaskTitleInput(title);
6688
+ if (!titleCheck.ok) {
6689
+ return { content: [{ type: "text", text: `okr_update_task invalid title: ${titleCheck.error}` }], isError: true };
6690
+ }
6691
+ patch.title = titleCheck.value;
6692
+ }
4739
6693
  if (status) patch.status = status;
4740
- if (assignee) patch.assignee = assignee;
6694
+ if (assignee !== undefined) {
6695
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
6696
+ if (!assigneeCheck.ok) {
6697
+ return { content: [{ type: "text", text: `okr_update_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
6698
+ }
6699
+ patch.assignee = assigneeCheck.value;
6700
+ }
6701
+ if (contributes_to !== undefined) {
6702
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
6703
+ if (!contribCheck.ok) {
6704
+ return { content: [{ type: "text", text: `okr_update_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
6705
+ }
6706
+ patch.contributes_to = contribCheck.value;
6707
+ }
4741
6708
  if (blocked_reason !== undefined) patch.blocked_reason = blocked_reason;
4742
6709
  if (blocker_agent !== undefined) patch.blocker_agent = blocker_agent;
4743
- if (Array.isArray(depends_on)) patch.depends_on = depends_on;
4744
- if (due) patch.due = due;
6710
+ if (depends_on !== undefined) {
6711
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on, task_id);
6712
+ if (!depsCheck.ok) {
6713
+ return { content: [{ type: "text", text: `okr_update_task invalid depends_on: ${depsCheck.error}` }], isError: true };
6714
+ }
6715
+ patch.depends_on = depsCheck.value;
6716
+ }
6717
+ if (linked_channel_docs !== undefined) {
6718
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
6719
+ if (!docsCheck.ok) {
6720
+ return { content: [{ type: "text", text: `okr_update_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6721
+ }
6722
+ patch.linked_channel_docs = docsCheck.value;
6723
+ }
6724
+ if (due !== undefined) {
6725
+ const dueCheck = validateOkrTaskDueInput(due);
6726
+ if (!dueCheck.ok) {
6727
+ return { content: [{ type: "text", text: `okr_update_task invalid due: ${dueCheck.error}` }], isError: true };
6728
+ }
6729
+ patch.due = dueCheck.value;
6730
+ }
6731
+ if (evidence !== undefined) {
6732
+ const evCheck = validateTaskEvidenceInput(evidence);
6733
+ if (!evCheck.ok) {
6734
+ return { content: [{ type: "text", text: `okr_update_task invalid evidence: ${evCheck.error}` }], isError: true };
6735
+ }
6736
+ patch.evidence = evCheck.value;
6737
+ }
6738
+ let validatedAppend: TaskEvidenceInput[] = [];
6739
+ if (append_evidence !== undefined) {
6740
+ const appCheck = validateAppendTaskEvidenceInput(append_evidence);
6741
+ if (!appCheck.ok) {
6742
+ return { content: [{ type: "text", text: `okr_update_task invalid append_evidence: ${appCheck.error}` }], isError: true };
6743
+ }
6744
+ validatedAppend = appCheck.value;
6745
+ patch.append_evidence = appCheck.value;
6746
+ }
6747
+ if (if_match_updated_at !== undefined) {
6748
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
6749
+ if (!verCheck.ok) {
6750
+ return { content: [{ type: "text", text: `okr_update_task invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
6751
+ }
6752
+ patch.if_match_updated_at = verCheck.value;
6753
+ }
4745
6754
  try {
4746
- const r = await apiFetch(`${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`, {
6755
+ const targetUrl = `${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`;
6756
+ const r = await apiFetch(targetUrl, {
4747
6757
  method: "PATCH",
4748
6758
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4749
6759
  body: JSON.stringify(patch),
@@ -4752,7 +6762,48 @@ const handleToolCall = async (request: any): Promise<any> => {
4752
6762
  if (!r.ok) {
4753
6763
  return { content: [{ type: "text", text: `okr_update_task failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4754
6764
  }
4755
- return { content: [{ type: "text", text: `Updated: ${text}` }] };
6765
+ let finalText = text;
6766
+ let parsed: any = null;
6767
+ try { parsed = JSON.parse(text); } catch {}
6768
+ if (validatedAppend.length > 0 && parsed?.ok === true && parsed?.task && !responseIncludesAppendedEvidence(parsed.task, validatedAppend)) {
6769
+ const merged = mergeLegacyTaskEvidence(parsed.task.evidence, validatedAppend);
6770
+ if (!merged.ok) {
6771
+ return {
6772
+ content: [{ type: "text", text: `okr_update_task append_evidence failed: ${merged.error}` }],
6773
+ isError: true,
6774
+ };
6775
+ }
6776
+ const fallbackBody: Record<string, unknown> = { evidence: merged.value };
6777
+ if (typeof parsed.task.updated_at === "string" && parsed.task.updated_at.trim()) {
6778
+ fallbackBody.if_match_updated_at = parsed.task.updated_at.trim();
6779
+ }
6780
+ const r2 = await apiFetch(targetUrl, {
6781
+ method: "PATCH",
6782
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
6783
+ body: JSON.stringify(fallbackBody),
6784
+ });
6785
+ const text2 = await r2.text();
6786
+ if (!r2.ok) {
6787
+ return { content: [{ type: "text", text: `okr_update_task failed (${r2.status}): ${text2.slice(0, 160)}` }], isError: true };
6788
+ }
6789
+ finalText = text2;
6790
+ parsed = null;
6791
+ try { parsed = JSON.parse(text2); } catch {}
6792
+ }
6793
+ if (patch.status === "done" && parsed?.ok === true && parsed?.task && Array.isArray(parsed.task.contributes_to)) {
6794
+ const krIds = parsed.task.contributes_to
6795
+ .filter((id: unknown): id is string => typeof id === "string" && id.trim().length > 0)
6796
+ .map((id: string) => id.trim());
6797
+ if (krIds.length > 0) {
6798
+ parsed.kr_progress_hint = {
6799
+ contributes_to: krIds,
6800
+ recommended_tool: "okr_set_kr_progress",
6801
+ note: `Task marked done; remember to report quantitative progress for linked KR(s): ${krIds.join(", ")}.`,
6802
+ };
6803
+ finalText = JSON.stringify(parsed);
6804
+ }
6805
+ }
6806
+ return { content: [{ type: "text", text: `Updated: ${finalText}` }] };
4756
6807
  } catch (e: any) {
4757
6808
  return { content: [{ type: "text", text: `okr_update_task network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4758
6809
  }
@@ -4794,12 +6845,11 @@ const handleToolCall = async (request: any): Promise<any> => {
4794
6845
  }
4795
6846
 
4796
6847
  if (name === "okr_add_kr") {
4797
- const { objective_id, title, metric_type, current, target, risk_level } = args as {
4798
- objective_id: string; title: string; metric_type: string; current?: number; target: number; risk_level?: string;
4799
- };
4800
- const body: Record<string, unknown> = { title, metric_type, target };
4801
- if (typeof current === "number") body.current = current;
4802
- if (risk_level) body.risk_level = risk_level;
6848
+ const validated = validateOkrAddKrInput(args);
6849
+ if (!validated.ok) {
6850
+ return { content: [{ type: "text", text: `okr_add_kr invalid arguments: ${validated.error}` }], isError: true };
6851
+ }
6852
+ const { objective_id, body } = validated.value;
4803
6853
  try {
4804
6854
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/krs`, {
4805
6855
  method: "POST",
@@ -4817,12 +6867,16 @@ const handleToolCall = async (request: any): Promise<any> => {
4817
6867
  }
4818
6868
 
4819
6869
  if (name === "archive_objective") {
4820
- const { objective_id, completion_summary } = args as { objective_id: string; completion_summary?: string };
6870
+ const validated = validateOkrArchiveObjectiveInput(args);
6871
+ if (!validated.ok) {
6872
+ return { content: [{ type: "text", text: `archive_objective invalid arguments: ${validated.error}` }], isError: true };
6873
+ }
6874
+ const { objective_id, body } = validated.value;
4821
6875
  try {
4822
6876
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/archive`, {
4823
6877
  method: "POST",
4824
6878
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4825
- body: JSON.stringify(completion_summary !== undefined ? { completion_summary } : {}),
6879
+ body: JSON.stringify(body),
4826
6880
  });
4827
6881
  const text = await r.text();
4828
6882
  if (!r.ok) {
@@ -4852,11 +6906,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4852
6906
  }
4853
6907
 
4854
6908
  if (name === "okr_set_kr_progress") {
4855
- const { kr_id, current, risk_level } = args as { kr_id: string; current: number; risk_level?: string };
4856
- const body: Record<string, unknown> = { current };
4857
- if (risk_level) body.risk_level = risk_level;
6909
+ const validated = validateOkrSetKrProgressInput(args);
6910
+ if (!validated.ok) {
6911
+ return { content: [{ type: "text", text: `okr_set_kr_progress invalid arguments: ${validated.error}` }], isError: true };
6912
+ }
6913
+ const { kr_id, body, useMetadataEndpoint } = validated.value;
6914
+ const pathSuffix = useMetadataEndpoint ? "" : "/progress";
4858
6915
  try {
4859
- const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}/progress`, {
6916
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}${pathSuffix}`, {
4860
6917
  method: "PATCH",
4861
6918
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4862
6919
  body: JSON.stringify(body),
@@ -4891,21 +6948,41 @@ const handleToolCall = async (request: any): Promise<any> => {
4891
6948
  }
4892
6949
 
4893
6950
  if (name === "okr_set_links") {
4894
- const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs } = args as {
6951
+ const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs, if_match_updated_at } = args as {
4895
6952
  target_type: "objective" | "kr" | "task";
4896
6953
  target_id: string;
4897
- narrative?: string;
6954
+ narrative?: unknown;
4898
6955
  narrative_path?: string;
4899
6956
  discussion_channel_id?: string;
4900
6957
  linked_docs?: string[];
4901
- linked_channel_docs?: Array<{ channel_id: string; doc_id: string }>;
6958
+ linked_channel_docs?: unknown;
6959
+ if_match_updated_at?: unknown;
4902
6960
  };
4903
6961
  const body: Record<string, unknown> = {};
4904
- if (narrative !== undefined) body.narrative = narrative;
6962
+ if (narrative !== undefined) {
6963
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
6964
+ if (!narCheck.ok) {
6965
+ return { content: [{ type: "text", text: `okr_set_links invalid narrative: ${narCheck.error}` }], isError: true };
6966
+ }
6967
+ body.narrative = narCheck.value;
6968
+ }
4905
6969
  if (narrative_path !== undefined) body.narrative_path = narrative_path;
4906
6970
  if (discussion_channel_id !== undefined) body.discussion_channel_id = discussion_channel_id;
4907
6971
  if (linked_docs !== undefined) body.linked_docs = linked_docs;
4908
- if (linked_channel_docs !== undefined) body.linked_channel_docs = linked_channel_docs;
6972
+ if (linked_channel_docs !== undefined) {
6973
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
6974
+ if (!docsCheck.ok) {
6975
+ return { content: [{ type: "text", text: `okr_set_links invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
6976
+ }
6977
+ body.linked_channel_docs = docsCheck.value;
6978
+ }
6979
+ if (if_match_updated_at !== undefined && if_match_updated_at !== null) {
6980
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
6981
+ if (!verCheck.ok) {
6982
+ return { content: [{ type: "text", text: `okr_set_links invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
6983
+ }
6984
+ body.if_match_updated_at = verCheck.value;
6985
+ }
4909
6986
  try {
4910
6987
  const r = await apiFetch(`${REST_URL}/api/okr/links/${encodeURIComponent(target_type)}/${encodeURIComponent(target_id)}`, {
4911
6988
  method: "PATCH",
@@ -4996,13 +7073,28 @@ function isSkillDoc(doc: any): boolean {
4996
7073
  return kind === "skill" || kind === "channel_skill" || id.includes("skill") || title.includes("skill");
4997
7074
  }
4998
7075
 
7076
+ function isArchivedSkillOrDoc(doc: any): boolean {
7077
+ if (!doc || typeof doc !== "object") return false;
7078
+ if (doc.archived === true) return true;
7079
+ const body = doc.body_markdown ?? doc.bodyMarkdown;
7080
+ if (typeof body === "string") return body === "";
7081
+ const summary = doc.body_summary ?? doc.bodySummary;
7082
+ if (typeof summary === "string" && summary === "" && doc.archived !== false && doc.skill_meta === undefined && doc.skillMeta === undefined) {
7083
+ return true;
7084
+ }
7085
+ return false;
7086
+ }
7087
+
4999
7088
  function compactSkillDoc(doc: any) {
5000
7089
  const meta = doc?.skill_meta || doc?.skillMeta || {};
7090
+ const archived = isArchivedSkillOrDoc(doc);
5001
7091
  return {
5002
7092
  doc_id: doc?.id ?? doc?.doc_id,
5003
7093
  title: doc?.title,
5004
7094
  kind: doc?.kind,
5005
7095
  level: doc?.level,
7096
+ ...(typeof doc?.version === "number" ? { version: doc.version } : {}),
7097
+ ...(archived ? { archived: true } : {}),
5006
7098
  updated_at: doc?.updatedAt ?? doc?.updated_at,
5007
7099
  name: meta.name,
5008
7100
  description: meta.description,
@@ -5730,6 +7822,10 @@ async function checkVersionStaleness(): Promise<void> {
5730
7822
 
5731
7823
  // --- Start ---
5732
7824
  async function main() {
7825
+ if (codexIdentity) {
7826
+ const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
7827
+ if (status.authentication !== "ok") throw new Error("Codex tool authentication failed; bridge transport alone is not tool readiness");
7828
+ }
5733
7829
  installStdioLifecycleGuards();
5734
7830
  if (!toolOnlyMode) {
5735
7831
  syncOpenBoundSessions();