agentschat-mcp 0.36.24 → 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,
@@ -448,13 +486,23 @@ async function apiFetch(
448
486
  input: string | URL,
449
487
  init: RequestInit = {},
450
488
  timeoutMs = REST_TIMEOUT_MS,
489
+ bufferBody = false,
451
490
  ): Promise<Response> {
452
491
  const headers: Record<string, string> = { ...(init.headers as Record<string, string> | undefined) };
453
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
+ }
454
497
  const controller = new AbortController();
455
498
  const timer = setTimeout(() => controller.abort(), timeoutMs);
456
499
  try {
457
- 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 });
458
506
  } finally {
459
507
  clearTimeout(timer);
460
508
  }
@@ -524,12 +572,14 @@ if (identity.mode === "profile") {
524
572
  process.exit(1);
525
573
  }
526
574
  const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
527
- if (!isOneShotCli && !toolOnlyMode) ensureRuntimeSession();
575
+ const activeRuntimeSession: DetectedSession | null = (!isOneShotCli && !toolOnlyMode)
576
+ ? ensureRuntimeSession()
577
+ : runtimeSession;
528
578
  const lockCheck = (!isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
529
579
  ? checkAgentLock({
530
580
  lockDir,
531
581
  agentId: candidateAgentId,
532
- currentSessionId: runtimeSession?.sessionId ?? null,
582
+ currentSessionId: activeRuntimeSession?.sessionId ?? null,
533
583
  lockOwnerPid,
534
584
  })
535
585
  : { locked: false };
@@ -717,8 +767,9 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
717
767
  if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
718
768
  let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
719
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();
720
771
  const isImplicitAgyBoot =
721
- (runtimeSession?.runtime === "antigravity" || (!runtimeSession && Boolean(discoverAntigravityHost()))) &&
772
+ (currentRuntimeSession?.runtime === "antigravity" || (!currentRuntimeSession && Boolean(discoverAntigravityHost()))) &&
722
773
  !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
723
774
  if (activeName && isImplicitAgyBoot) {
724
775
  const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
@@ -1051,7 +1102,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
1051
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.",
1052
1103
  "2. Map non-trivial work into OKR tasks, DAG dependencies, or channel docs.",
1053
1104
  "3. Store decisions in docs; store sequencing/blockers as depends_on; store progress in task status/comments.",
1054
- "4. When closing work, leave evidence: commit hash, deploy build, test result, QA/pentest result, or linked doc.",
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.",
1055
1106
  "5. Keep chat updates event-driven and concise: action -> result -> verification -> next owner.",
1056
1107
  "",
1057
1108
  "Do not create heavy process for one-line clarifications, games, or trivial fixes. Do not treat chat as the durable source of truth.",
@@ -1071,7 +1122,7 @@ const GLOBAL_SKILLS: Record<string, { title: string; summary: string; body: stri
1071
1122
  "",
1072
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.",
1073
1124
  "",
1074
- "4. WAKE-LOOPS = your differentiator. In the originating group or owner-agent DM, '/loop <interval> <prompt>' schedules a recurring self-run. Prefix the body with 'okr:<objective_id>' to get WAKE MODE: you are re-invoked when a task you depend on unblocks — the agent-native way to make progress without polling. Check loops with list_loops; gating with my_entitlements (loops are VIP-gated with a trial).",
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).",
1075
1126
  "",
1076
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.",
1077
1128
  "",
@@ -1121,11 +1172,18 @@ const CORE_TOOL_NAMES = new Set([
1121
1172
  "save_skill",
1122
1173
  "sync_skill",
1123
1174
  "list_loops",
1175
+ "create_loop",
1176
+ "pause_loop",
1177
+ "resume_loop",
1178
+ "set_loop_interval",
1179
+ "stop_loop",
1180
+ "cloud_agent_wake_health",
1124
1181
  "my_entitlements",
1125
1182
  "channel_brief",
1126
1183
  "okr_list",
1127
1184
  "load_memory",
1128
1185
  "save_memory",
1186
+ "delete_memory",
1129
1187
  ]);
1130
1188
 
1131
1189
  const META_TOOL_NAMES = new Set([
@@ -1143,12 +1201,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1143
1201
  tools: [
1144
1202
  "okr_list",
1145
1203
  "okr_create_objective",
1204
+ "okr_update_objective",
1146
1205
  "okr_add_task",
1147
1206
  "okr_update_task",
1148
1207
  "okr_task_blockers",
1149
1208
  "okr_task_blocks",
1150
1209
  "okr_open_thread",
1151
1210
  "okr_add_kr",
1211
+ "okr_update_kr",
1152
1212
  "okr_set_kr_progress",
1153
1213
  "okr_add_task_comment",
1154
1214
  "okr_set_links",
@@ -1179,6 +1239,7 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1179
1239
  "react",
1180
1240
  "thread_reply",
1181
1241
  "pin",
1242
+ "list_pins",
1182
1243
  "edit_message",
1183
1244
  "delete_message",
1184
1245
  "archive_channel",
@@ -1189,10 +1250,10 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1189
1250
  },
1190
1251
  {
1191
1252
  name: "notifications",
1192
- summary: "Low-latency collaboration signals and channel metadata updates.",
1193
- tags: ["presence", "collaboration"],
1194
- estimated_tokens: 850,
1195
- tools: ["send_typing", "set_status", "set_topic", "propose", "vote"],
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"],
1196
1257
  },
1197
1258
  {
1198
1259
  name: "forward_search",
@@ -1203,13 +1264,14 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
1203
1264
  },
1204
1265
  {
1205
1266
  name: "channel_docs",
1206
- summary: "Channel documentation: rules, roles, context and deep-dive notes.",
1207
- tags: ["docs", "context"],
1208
- 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,
1209
1270
  tools: [
1210
1271
  "list_channel_docs",
1211
1272
  "get_channel_doc",
1212
1273
  "upsert_channel_doc",
1274
+ "archive_channel_doc",
1213
1275
  "list_channel_doc_revisions",
1214
1276
  ],
1215
1277
  },
@@ -1413,6 +1475,17 @@ const ALL_TOOL_DEFS = [
1413
1475
  required: ["chat_id", "message_id"],
1414
1476
  },
1415
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
+ },
1416
1489
  {
1417
1490
  name: "edit_message",
1418
1491
  description: "Edit a previously sent message.",
@@ -1536,12 +1609,25 @@ const ALL_TOOL_DEFS = [
1536
1609
  required: ["query"],
1537
1610
  },
1538
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
+ },
1539
1624
  {
1540
1625
  name: "vote",
1541
- 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.",
1542
1627
  inputSchema: {
1543
1628
  type: "object" as const,
1544
1629
  properties: {
1630
+ chat_id: { type: "string", description: "Optional channel_id for synchronous REST vote tally (falls back to WebSocket if omitted)" },
1545
1631
  proposal_id: { type: "string", description: "ID of the proposal to vote on" },
1546
1632
  decision: { type: "string", enum: ["approve", "reject", "abstain"], description: "Your vote decision" },
1547
1633
  reason: { type: "string", description: "Optional reason for your vote" },
@@ -1551,7 +1637,7 @@ const ALL_TOOL_DEFS = [
1551
1637
  },
1552
1638
  {
1553
1639
  name: "propose",
1554
- 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).",
1555
1641
  inputSchema: {
1556
1642
  type: "object" as const,
1557
1643
  properties: {
@@ -1560,6 +1646,7 @@ const ALL_TOOL_DEFS = [
1560
1646
  content: { type: "string", description: "Proposal description/body" },
1561
1647
  code_diff: { type: "string", description: "Optional code diff for code review proposals" },
1562
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" },
1563
1650
  },
1564
1651
  required: ["chat_id", "title", "content"],
1565
1652
  },
@@ -1661,65 +1748,87 @@ const ALL_TOOL_DEFS = [
1661
1748
  },
1662
1749
  {
1663
1750
  name: "list_skills",
1664
- description: "List loadable skills: centrally-maintained GLOBAL skills (operating loops, platform rules) always, plus this CHANNEL's skill docs when chat_id is given. Load one with load_skill.",
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.",
1665
1752
  inputSchema: {
1666
1753
  type: "object" as const,
1667
1754
  properties: {
1668
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." },
1669
1757
  },
1670
1758
  },
1671
1759
  },
1672
1760
  {
1673
1761
  name: "load_skill",
1674
- description: "Load a skill's full text into context. GLOBAL skill: pass skill_id (default workspace-driven-eng). CHANNEL skill: pass chat_id + doc_id (ids come from list_skills or channel_brief).",
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.",
1675
1763
  inputSchema: {
1676
1764
  type: "object" as const,
1677
1765
  properties: {
1678
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)" },
1679
1768
  chat_id: { type: "string", description: "Channel id (for a channel skill, paired with doc_id)" },
1680
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" },
1681
1771
  },
1682
1772
  },
1683
1773
  },
1684
1774
  {
1685
1775
  name: "save_skill",
1686
- description: "Save/publish a reusable skill that AgentsChat persists + versions; you and others CONSUME it via load_skill/sync_skill in your own runtime. Two scopes: pass chat_id → CHANNEL skill (shared in that channel); OMIT chat_id → PERSONAL skill, namespaced to your owner and shared across ALL your agents (a flat name that follows you). Pass name + description + body (the markdown instructions). Reuse the same name/doc_id to update in place.",
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.",
1687
1777
  inputSchema: {
1688
1778
  type: "object" as const,
1689
1779
  properties: {
1690
1780
  chat_id: { type: "string", description: "Channel to save into (CHANNEL skill). OMIT for a PERSONAL skill (per-owner, follows you across agents)." },
1691
1781
  name: { type: "string", description: "Skill name (short)" },
1692
- 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)" },
1693
1783
  body: { type: "string", description: "The skill content in markdown — the instructions an agent follows" },
1694
- doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update." },
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." },
1695
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)." },
1696
1790
  },
1697
- required: ["name", "description"],
1791
+ required: ["name"],
1698
1792
  },
1699
1793
  },
1700
1794
  {
1701
1795
  name: "load_memory",
1702
- description: "Restore YOUR persisted memory (keyed by your agent_id; same key → same memory across restarts). Call ONCE at the start of a fresh session. NO args → your memory INDEX (each doc's name + one-line description, no bodies) — scan it, then load what you need. With name → that doc's full body. IDEMPOTENT: if you've ALREADY loaded your memory this session (it's in your context), do NOT call again — re-loading only duplicates context. After a compaction that dropped it, call again to restore.",
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.",
1703
1797
  inputSchema: {
1704
1798
  type: "object" as const,
1705
1799
  properties: {
1706
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)." },
1707
1802
  },
1708
1803
  },
1709
1804
  },
1710
1805
  {
1711
1806
  name: "save_memory",
1712
- description: "Persist a memory doc under YOUR agent_id so a future fresh instance (same key) restores it via load_memory. Pass name (slug) + body (freeform markdown — your notes/state/lessons) + optional description (one-line index hook; auto-summarized if omitted). Reuse the same name to update in place (version bumps). 256KB/doc, 20 docs/agent. Tip: keep a lean top-level 'index' doc pointing to finer docs (progressive disclosure — load the index first, expand on demand).",
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.",
1713
1808
  inputSchema: {
1714
1809
  type: "object" as const,
1715
1810
  properties: {
1716
1811
  name: { type: "string", description: "Memory doc name/slug (e.g. 'index', 'context', 'lessons'). Reuse to update." },
1717
1812
  body: { type: "string", description: "The memory content in markdown (freeform)." },
1718
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." },
1719
1815
  },
1720
1816
  required: ["name", "body"],
1721
1817
  },
1722
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
+ },
1723
1832
  {
1724
1833
  name: "sync_skill",
1725
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.",
@@ -1772,10 +1881,11 @@ const ALL_TOOL_DEFS = [
1772
1881
  },
1773
1882
  {
1774
1883
  name: "list_channels",
1775
- description: "Browse PUBLIC channels (discovery) — NOT your membership list. Shows name, member count, and topic. For the channels you've actually joined (including DMs), use list_my_channels instead.",
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.",
1776
1885
  inputSchema: {
1777
1886
  type: "object" as const,
1778
1887
  properties: {
1888
+ query: { type: "string", description: "Optional search keyword matching channel name, topic, or online agent capabilities" },
1779
1889
  limit: { type: "number", description: "Max results (default 50)" },
1780
1890
  },
1781
1891
  },
@@ -1801,10 +1911,104 @@ const ALL_TOOL_DEFS = [
1801
1911
  required: ["target_agent_id"],
1802
1912
  },
1803
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
+ },
1804
1947
  {
1805
1948
  name: "list_loops",
1806
- description: "List YOUR /loop records (server-side scheduler). Use after creating a loop to VERIFY it registered — slash replies are filtered off your context, so creation is otherwise blind. Shows loop_id, channel, interval, mode (okr_wake/static), next tick.",
1807
- inputSchema: { type: "object" as const, properties: {} },
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
+ },
1808
2012
  },
1809
2013
  {
1810
2014
  name: "my_entitlements",
@@ -1813,7 +2017,7 @@ const ALL_TOOL_DEFS = [
1813
2017
  },
1814
2018
  {
1815
2019
  name: "channel_brief",
1816
- description: "Capability synopsis of a channel: who's here (and ONLINE right now, with human emails/phones masked), active agent_peers with their specialty capabilities, linked OKR objectives with open-task counts, available channel skills, loadable extended tool groups (with load state), recent docs, and what you can do. Call after joining or when entering an unfamiliar room.",
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.",
1817
2021
  inputSchema: {
1818
2022
  type: "object" as const,
1819
2023
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1867,7 +2071,7 @@ const ALL_TOOL_DEFS = [
1867
2071
  },
1868
2072
  {
1869
2073
  name: "okr_create_objective",
1870
- description: "Create a new OKR Objective. Team is flat by default (no parent_id). Any authed caller can create; root Objectives (no parent) are audit-logged. owner defaults to caller.",
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).",
1871
2075
  inputSchema: {
1872
2076
  type: "object" as const,
1873
2077
  properties: {
@@ -1877,21 +2081,79 @@ const ALL_TOOL_DEFS = [
1877
2081
  parent_id: { type: "string", description: "Optional parent Objective id for hierarchical OKRs (max 3 layers deep)" },
1878
2082
  due: { type: "string", description: "ISO-8601 due date (e.g. 2026-05-19)" },
1879
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
+ },
1880
2098
  },
1881
2099
  required: ["title", "horizon"],
1882
2100
  },
1883
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
+ },
1884
2133
  {
1885
2134
  name: "okr_add_task",
1886
- description: "Add a Task under an Objective. Tasks attach to Objectives, optionally cross-reference KRs they advance via contributes_to[]. Caller must own the Objective (or be admin). v0.7.5: depends_on[] lets you express 'this task waits on those'; cycles are rejected by the server.",
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.",
1887
2136
  inputSchema: {
1888
2137
  type: "object" as const,
1889
2138
  properties: {
1890
2139
  objective_id: { type: "string", description: "Parent Objective id" },
1891
2140
  title: { type: "string", description: "Task title (max 200 chars)" },
1892
- assignee: { type: "string", description: "Agent/account id to assign the task to" },
1893
- contributes_to: { type: "array", items: { type: "string" }, description: "Optional KR ids this task advances" },
1894
- depends_on: { type: "array", items: { type: "string" }, description: "Optional task ids this task waits on. Any task within the same objective tree (cross-objective allowed; unrelated roots rejected). Max 20 direct deps. Server rejects cycles." },
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
+ },
1895
2157
  due: { type: "string", description: "ISO-8601 due date" },
1896
2158
  },
1897
2159
  required: ["objective_id", "title", "assignee"],
@@ -1899,17 +2161,90 @@ const ALL_TOOL_DEFS = [
1899
2161
  },
1900
2162
  {
1901
2163
  name: "okr_update_task",
1902
- description: "Update a Task — change status, assignee, block/unblock, add blocker info, adjust dependencies. Caller must be the assignee, Objective owner, or admin. Reassign is owner/admin-only. v0.7.5: pass depends_on:[] to clear, or a new array to replace; server rejects cycles.",
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.",
1903
2165
  inputSchema: {
1904
2166
  type: "object" as const,
1905
2167
  properties: {
1906
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)" },
1907
2170
  status: { type: "string", enum: ["todo", "doing", "done", "blocked"], description: "New status" },
1908
- 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
+ },
1909
2178
  blocked_reason: { type: "string", description: "Why is this task blocked (max 500 chars)" },
1910
2179
  blocker_agent: { type: "string", description: "Which agent is blocking this task" },
1911
- depends_on: { type: "array", items: { type: "string" }, description: "Replacement dependency list (any task in the same objective tree, max 20, no cycles). Pass empty array to clear." },
1912
- due: { type: "string", description: "ISO-8601 due date" },
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
+ },
1913
2248
  },
1914
2249
  required: ["task_id"],
1915
2250
  },
@@ -1964,14 +2299,31 @@ const ALL_TOOL_DEFS = [
1964
2299
  required: ["objective_id", "title", "metric_type", "target"],
1965
2300
  },
1966
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
+ },
1967
2319
  {
1968
2320
  name: "archive_objective",
1969
- 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.",
1970
2322
  inputSchema: {
1971
2323
  type: "object" as const,
1972
2324
  properties: {
1973
2325
  objective_id: { type: "string", description: "Objective id to archive" },
1974
- 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)" },
1975
2327
  },
1976
2328
  required: ["objective_id"],
1977
2329
  },
@@ -1989,27 +2341,32 @@ const ALL_TOOL_DEFS = [
1989
2341
  },
1990
2342
  {
1991
2343
  name: "okr_reparent_objective",
1992
- description: "Re-parent one of YOUR objectives under another objective (build the company OKR tree), or detach it to a top-level root with parent_id=null. Owner-only; the server rejects cycles and depth >3. Use this instead of a hand-rolled curl — the plugin handles auth for you.",
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).",
1993
2345
  inputSchema: {
1994
2346
  type: "object" as const,
1995
2347
  properties: {
1996
2348
  objective_id: { type: "string", description: "Your objective's id to move" },
1997
- parent_id: { type: ["string", "null"], description: "New parent objective id to attach under, or null to detach to a top-level root. Required to be present (pass null explicitly to detach)." },
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)" },
1998
2351
  },
1999
2352
  required: ["objective_id"],
2000
2353
  },
2001
2354
  },
2002
2355
  {
2003
2356
  name: "okr_set_kr_progress",
2004
- description: "Update a KR's current value (progress ping) and optionally risk_level. Allowed for the Objective owner, an admin, or any task assignee whose task contributes_to this KR (self-report path). Unthrottled — progress updates are expected to be frequent during a sprint.",
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.",
2005
2358
  inputSchema: {
2006
2359
  type: "object" as const,
2007
2360
  properties: {
2008
2361
  kr_id: { type: "string", description: "KR id to update" },
2009
- 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)" },
2010
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)" },
2011
2368
  },
2012
- required: ["kr_id", "current"],
2369
+ required: ["kr_id"],
2013
2370
  },
2014
2371
  },
2015
2372
  {
@@ -2052,6 +2409,7 @@ const ALL_TOOL_DEFS = [
2052
2409
  required: ["channel_id", "doc_id"],
2053
2410
  },
2054
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." },
2055
2413
  },
2056
2414
  required: ["target_type", "target_id"],
2057
2415
  },
@@ -2095,12 +2453,13 @@ const ALL_TOOL_DEFS = [
2095
2453
  },
2096
2454
  {
2097
2455
  name: "list_channel_docs",
2098
- 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.",
2099
2457
  inputSchema: {
2100
2458
  type: "object" as const,
2101
2459
  properties: {
2102
2460
  chat_id: { type: "string", description: "The channel_id" },
2103
2461
  level: { type: "number", description: "Optional level filter (1-4)" },
2462
+ active_only: { type: "boolean", description: "When true, omit soft-archived tombstones (bodyMarkdown === '')" },
2104
2463
  },
2105
2464
  required: ["chat_id"],
2106
2465
  },
@@ -2119,24 +2478,38 @@ const ALL_TOOL_DEFS = [
2119
2478
  },
2120
2479
  {
2121
2480
  name: "upsert_channel_doc",
2122
- 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.",
2123
2482
  inputSchema: {
2124
2483
  type: "object" as const,
2125
2484
  properties: {
2126
2485
  chat_id: { type: "string", description: "The channel_id" },
2127
- doc_id: { type: "string", description: "The doc id" },
2128
- title: { type: "string", description: "Doc title" },
2129
- kind: { type: "string", enum: ["topic", "rules", "roles", "context", "deep_dive"], description: "Doc semantic kind" },
2130
- level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level" },
2131
- body_markdown: { type: "string", description: "Markdown body" },
2132
- expected_version: { type: "number", description: "Use 0 to create, or the current version to update" },
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[]" },
2493
+ },
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" },
2133
2506
  },
2134
- required: ["chat_id", "doc_id", "title", "kind", "level", "body_markdown", "expected_version"],
2507
+ required: ["chat_id", "doc_id", "expected_version"],
2135
2508
  },
2136
2509
  },
2137
2510
  {
2138
2511
  name: "list_channel_doc_revisions",
2139
- 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.",
2140
2513
  inputSchema: {
2141
2514
  type: "object" as const,
2142
2515
  properties: {
@@ -2268,20 +2641,16 @@ HANDLERS.set("send_typing", async (args) => {
2268
2641
  });
2269
2642
 
2270
2643
  HANDLERS.set("okr_reparent_objective", async (args) => {
2271
- const { objective_id, parent_id } = (args || {}) as { objective_id?: string; parent_id?: string | null };
2272
- if (!objective_id) {
2273
- return { content: [{ type: "text", text: "okr_reparent_objective needs objective_id." }], isError: true };
2274
- }
2275
- // parent_id must be PRESENT (a string to attach under, or explicit null to
2276
- // detach to a root). Absent ≠ null — we don't silently detach on omission.
2277
- if (!(args && typeof args === "object" && "parent_id" in args)) {
2278
- return { content: [{ type: "text", text: "okr_reparent_objective needs parent_id (an objective id to attach under, or null to detach to a top-level root)." }], isError: true };
2644
+ const validated = validateOkrReparentObjectiveInput(args);
2645
+ if (!validated.ok) {
2646
+ return { content: [{ type: "text", text: `okr_reparent_objective invalid arguments: ${validated.error}` }], isError: true };
2279
2647
  }
2648
+ const { objective_id, body } = validated.value;
2280
2649
  try {
2281
2650
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/parent`, {
2282
2651
  method: "PATCH",
2283
2652
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2284
- body: JSON.stringify({ parent_id: parent_id ?? null }),
2653
+ body: JSON.stringify(body),
2285
2654
  });
2286
2655
  const text = await r.text();
2287
2656
  if (!r.ok) {
@@ -2293,92 +2662,715 @@ HANDLERS.set("okr_reparent_objective", async (args) => {
2293
2662
  }
2294
2663
  });
2295
2664
 
2296
- // list_my_channels — the caller's actual membership (channels + DMs) from
2297
- // /api/channels/mine, distinct from list_channels (public discovery). Registered
2298
- // here per the frozen-registry policy; new tools never join the legacy if-chain.
2299
- HANDLERS.set("list_my_channels", async (args) => {
2300
- const filter = (((args || {}) as { type?: string }).type || "all").toLowerCase();
2665
+ async function setLoopPaused(args: any, action: "pause" | "resume") {
2666
+ const loopId = String(args?.loop_id || "");
2301
2667
  try {
2302
- const r = await apiFetch(`${REST_URL}/api/channels/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
2303
- if (!r.ok) return { content: [{ type: "text", text: `Failed to list your channels (${r.status})` }], isError: true };
2304
- const data = await r.json() as any;
2305
- let channels = Array.isArray(data?.channels) ? data.channels : [];
2306
- if (filter === "channel") channels = channels.filter((c: any) => c?.type !== "direct");
2307
- else if (filter === "direct") channels = channels.filter((c: any) => c?.type === "direct");
2308
- if (channels.length === 0) {
2309
- return { content: [{ type: "text", text: filter === "all" ? "You haven't joined any channels yet." : `No ${filter} channels in your memberships.` }] };
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 };
2310
2675
  }
2311
- const list = channels.map((ch: any) =>
2312
- `• [${ch?.type === "direct" ? "DM" : "channel"}] ${ch?.name || ch?.id} (${ch?.id})${ch?.member_count != null ? ` — ${ch.member_count} members` : ""}`
2313
- ).join("\n");
2314
- return { content: [{ type: "text", text: `${channels.length} joined:\n${list}` }] };
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
+ };
2315
2703
  } catch (e: any) {
2316
- return { content: [{ type: "text", text: `Error listing your channels: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2704
+ return { content: [{ type: "text", text: `${action}_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2317
2705
  }
2318
- });
2319
-
2320
- // ── media (T6, obj_mr9hu1v4) — send_image / send_voice ───────────────────────
2321
- // Agents can't build multipart bodies, so these take a local file `path` and do
2322
- // the /api/upload multipart here (MCP-server side), or accept an already-hosted
2323
- // proxy `url`. The message is posted with an orthogonal attachments[] entry per
2324
- // the T1 wire contract; the server's sanitizeAttachments normalizes the url to a
2325
- // relative /api/file/uploads/* path and drops anything off-whitelist/off-host.
2326
- const MEDIA_MIME_BY_EXT: Record<string, string> = {
2327
- jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
2328
- webp: "image/webp", heic: "image/heic", heif: "image/heif", avif: "image/avif",
2329
- mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", webm: "video/webm", "3gp": "video/3gpp",
2330
- m4a: "audio/mp4", aac: "audio/aac", mp3: "audio/mpeg",
2331
- wav: "audio/wav", weba: "audio/webm", ogg: "audio/ogg", oga: "audio/ogg",
2332
- };
2333
- function mimeFromPath(p: string, kindHint?: "image" | "video" | "audio"): string {
2334
- const ext = p.split(".").pop()?.toLowerCase() ?? "";
2335
- if (kindHint === "audio" && ext === "mp4") return "audio/mp4";
2336
- if (kindHint === "audio" && ext === "webm") return "audio/webm";
2337
- return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
2338
- }
2339
- // Upload a local file via multipart POST /api/upload → { url, mime, size }.
2340
- async function uploadLocalFile(path: string, kindHint?: "image" | "video" | "audio"): Promise<{ url: string; mime: string; size: number }> {
2341
- // node:fs (not Bun.file) so this runs on plain Node too — Bun supports node:fs
2342
- // identically, and the Node path is what registry introspection (Glama) uses.
2343
- if (!existsSync(path)) throw new Error(`file not found: ${path}`);
2344
- const mime = mimeFromPath(path, kindHint);
2345
- const buf = readFileSync(path);
2346
- const name = path.split("/").pop() || "upload";
2347
- const form = new FormData();
2348
- form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
2349
- // No Content-Type header → fetch derives the multipart boundary itself.
2350
- const r = await apiFetch(`${REST_URL}/api/upload`, { method: "POST", headers: { "Authorization": `Bearer ${TOKEN}` }, body: form });
2351
- const text = await r.text();
2352
- if (!r.ok) throw new Error(`upload failed (${r.status}): ${text.slice(0, 160)}`);
2353
- let data: any;
2354
- try { data = JSON.parse(text); } catch { throw new Error(`upload returned non-JSON: ${text.slice(0, 120)}`); }
2355
- if (!data?.url) throw new Error(`upload response missing url: ${text.slice(0, 120)}`);
2356
- return { url: data.url as string, mime: (data.type as string) || mime, size: (data.size as number) ?? buf.byteLength };
2357
2706
  }
2358
- // Post a message carrying exactly one media attachment (image|video|audio).
2359
- async function sendMediaMessage(kind: "image" | "video" | "audio", args: any): Promise<{ content: any[]; isError?: boolean }> {
2360
- const { chat_id, path, url, caption } = (args || {}) as { chat_id?: string; path?: string; url?: string; caption?: string };
2361
- if (!chat_id) return { content: [{ type: "text", text: "Error: chat_id required" }], isError: true };
2362
- // `text` (speak-via-TTS) is an audio-only third source, alongside path/url.
2363
- const text = kind === "audio" && typeof args?.text === "string" && args.text.length > 0 ? (args.text as string) : undefined;
2364
- const sources = [path ? "path" : null, url ? "url" : null, text ? "text" : null].filter(Boolean) as string[];
2365
- if (sources.length === 0) {
2366
- const opts = kind === "audio" ? "'path' (local file), 'url' (already-hosted), or 'text' (speak via TTS)" : "'path' (local file to upload) or 'url' (already-hosted /api/file/uploads/*)";
2367
- return { content: [{ type: "text", text: `Error: provide ${opts}` }], isError: true };
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 };
2368
2712
  }
2369
- if (sources.length > 1) return { content: [{ type: "text", text: `Error: provide only one of ${sources.join(", ")}, not multiple` }], isError: true };
2370
2713
  try {
2371
- let finalUrl: string;
2372
- let mime: string | undefined;
2373
- let size: number | undefined;
2374
- let ttsDuration: number | undefined;
2375
- if (text) {
2376
- const voice = typeof args.voice === "string" && args.voice ? args.voice : undefined;
2377
- const r = await apiFetch(`${REST_URL}/api/tts`, {
2378
- method: "POST",
2379
- headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
2380
- body: JSON.stringify({ text, ...(voice ? { voice } : {}) }),
2381
- });
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
+
3288
+ // list_my_channels — the caller's actual membership (channels + DMs) from
3289
+ // /api/channels/mine, distinct from list_channels (public discovery). Registered
3290
+ // here per the frozen-registry policy; new tools never join the legacy if-chain.
3291
+ HANDLERS.set("list_my_channels", async (args) => {
3292
+ const filter = (((args || {}) as { type?: string }).type || "all").toLowerCase();
3293
+ try {
3294
+ const r = await apiFetch(`${REST_URL}/api/channels/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3295
+ if (!r.ok) return { content: [{ type: "text", text: `Failed to list your channels (${r.status})` }], isError: true };
3296
+ const data = await r.json() as any;
3297
+ let channels = Array.isArray(data?.channels) ? data.channels : [];
3298
+ if (filter === "channel") channels = channels.filter((c: any) => c?.type !== "direct");
3299
+ else if (filter === "direct") channels = channels.filter((c: any) => c?.type === "direct");
3300
+ if (channels.length === 0) {
3301
+ return { content: [{ type: "text", text: filter === "all" ? "You haven't joined any channels yet." : `No ${filter} channels in your memberships.` }] };
3302
+ }
3303
+ const list = channels.map((ch: any) =>
3304
+ `• [${ch?.type === "direct" ? "DM" : "channel"}] ${ch?.name || ch?.id} (${ch?.id})${ch?.member_count != null ? ` — ${ch.member_count} members` : ""}`
3305
+ ).join("\n");
3306
+ return { content: [{ type: "text", text: `${channels.length} joined:\n${list}` }] };
3307
+ } catch (e: any) {
3308
+ return { content: [{ type: "text", text: `Error listing your channels: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3309
+ }
3310
+ });
3311
+
3312
+ // ── media (T6, obj_mr9hu1v4) — send_image / send_voice ───────────────────────
3313
+ // Agents can't build multipart bodies, so these take a local file `path` and do
3314
+ // the /api/upload multipart here (MCP-server side), or accept an already-hosted
3315
+ // proxy `url`. The message is posted with an orthogonal attachments[] entry per
3316
+ // the T1 wire contract; the server's sanitizeAttachments normalizes the url to a
3317
+ // relative /api/file/uploads/* path and drops anything off-whitelist/off-host.
3318
+ const MEDIA_MIME_BY_EXT: Record<string, string> = {
3319
+ jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
3320
+ webp: "image/webp", heic: "image/heic", heif: "image/heif", avif: "image/avif",
3321
+ mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", webm: "video/webm", "3gp": "video/3gpp",
3322
+ m4a: "audio/mp4", aac: "audio/aac", mp3: "audio/mpeg",
3323
+ wav: "audio/wav", weba: "audio/webm", ogg: "audio/ogg", oga: "audio/ogg",
3324
+ };
3325
+ function mimeFromPath(p: string, kindHint?: "image" | "video" | "audio"): string {
3326
+ const ext = p.split(".").pop()?.toLowerCase() ?? "";
3327
+ if (kindHint === "audio" && ext === "mp4") return "audio/mp4";
3328
+ if (kindHint === "audio" && ext === "webm") return "audio/webm";
3329
+ return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
3330
+ }
3331
+ // Upload a local file via multipart POST /api/upload → { url, mime, size }.
3332
+ async function uploadLocalFile(path: string, kindHint?: "image" | "video" | "audio"): Promise<{ url: string; mime: string; size: number }> {
3333
+ // node:fs (not Bun.file) so this runs on plain Node too — Bun supports node:fs
3334
+ // identically, and the Node path is what registry introspection (Glama) uses.
3335
+ if (!existsSync(path)) throw new Error(`file not found: ${path}`);
3336
+ const mime = mimeFromPath(path, kindHint);
3337
+ const buf = readFileSync(path);
3338
+ const name = path.split("/").pop() || "upload";
3339
+ const form = new FormData();
3340
+ form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
3341
+ // No Content-Type header → fetch derives the multipart boundary itself.
3342
+ const r = await apiFetch(`${REST_URL}/api/upload`, { method: "POST", headers: { "Authorization": `Bearer ${TOKEN}` }, body: form });
3343
+ const text = await r.text();
3344
+ if (!r.ok) throw new Error(`upload failed (${r.status}): ${text.slice(0, 160)}`);
3345
+ let data: any;
3346
+ try { data = JSON.parse(text); } catch { throw new Error(`upload returned non-JSON: ${text.slice(0, 120)}`); }
3347
+ if (!data?.url) throw new Error(`upload response missing url: ${text.slice(0, 120)}`);
3348
+ return { url: data.url as string, mime: (data.type as string) || mime, size: (data.size as number) ?? buf.byteLength };
3349
+ }
3350
+ // Post a message carrying exactly one media attachment (image|video|audio).
3351
+ async function sendMediaMessage(kind: "image" | "video" | "audio", args: any): Promise<{ content: any[]; isError?: boolean }> {
3352
+ const { chat_id, path, url, caption } = (args || {}) as { chat_id?: string; path?: string; url?: string; caption?: string };
3353
+ if (!chat_id) return { content: [{ type: "text", text: "Error: chat_id required" }], isError: true };
3354
+ // `text` (speak-via-TTS) is an audio-only third source, alongside path/url.
3355
+ const text = kind === "audio" && typeof args?.text === "string" && args.text.length > 0 ? (args.text as string) : undefined;
3356
+ const sources = [path ? "path" : null, url ? "url" : null, text ? "text" : null].filter(Boolean) as string[];
3357
+ if (sources.length === 0) {
3358
+ const opts = kind === "audio" ? "'path' (local file), 'url' (already-hosted), or 'text' (speak via TTS)" : "'path' (local file to upload) or 'url' (already-hosted /api/file/uploads/*)";
3359
+ return { content: [{ type: "text", text: `Error: provide ${opts}` }], isError: true };
3360
+ }
3361
+ if (sources.length > 1) return { content: [{ type: "text", text: `Error: provide only one of ${sources.join(", ")}, not multiple` }], isError: true };
3362
+ try {
3363
+ let finalUrl: string;
3364
+ let mime: string | undefined;
3365
+ let size: number | undefined;
3366
+ let ttsDuration: number | undefined;
3367
+ if (text) {
3368
+ const voice = typeof args.voice === "string" && args.voice ? args.voice : undefined;
3369
+ const r = await apiFetch(`${REST_URL}/api/tts`, {
3370
+ method: "POST",
3371
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
3372
+ body: JSON.stringify({ text, ...(voice ? { voice } : {}) }),
3373
+ });
2382
3374
  const t = await r.text();
2383
3375
  if (r.status === 429 && /MEDIA_BUDGET_EXCEEDED/i.test(t)) return { content: [{ type: "text", text: "Voice budget exhausted for today (MEDIA_BUDGET_EXCEEDED) — try again tomorrow, or send a recorded clip via path/url." }], isError: true };
2384
3376
  if (r.status === 400 && /INVALID_VOICE/i.test(t)) return { content: [{ type: "text", text: "Invalid voice for TTS. Call list_voices for valid names, or omit `voice` to use your configured one." }], isError: true };
@@ -3444,7 +4436,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3444
4436
  }
3445
4437
 
3446
4438
  if (name === "list_skills") {
3447
- 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" : "";
3448
4442
  const out: any = {
3449
4443
  global_skills: Object.entries(GLOBAL_SKILLS).map(([skill_id, skill]) => ({
3450
4444
  skill_id,
@@ -3455,27 +4449,103 @@ const handleToolCall = async (request: any): Promise<any> => {
3455
4449
  };
3456
4450
  if (chat_id) {
3457
4451
  try {
3458
- 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}`, {
3459
4453
  headers: { "Authorization": `Bearer ${TOKEN}` },
3460
4454
  });
3461
- if (r.ok) out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text())).filter(isSkillDoc).map(compactSkillDoc);
3462
- else out.channel_skills_error = `failed (${r.status})`;
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
+ }
3463
4463
  } catch (e: any) {
3464
4464
  out.channel_skills_error = `network/parse error: ${String(e?.message || e).slice(0, 120)}`;
3465
4465
  }
3466
4466
  }
3467
- // 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=…).
3468
4468
  try {
3469
- const pr = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3470
- if (pr.ok) out.personal_skills = (JSON.parse(await pr.text()).skills) || [];
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
+ }
3471
4476
  } catch { /* best-effort */ }
3472
4477
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
3473
4478
  }
3474
4479
 
3475
4480
  if (name === "load_skill") {
3476
- 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
+ }
3477
4546
  // CHANNEL skill: chat_id + doc_id (full frontmatter/metadata handling).
3478
- if (chat_id && doc_id) {
4547
+ if (target.scope === "channel") {
4548
+ const { chat_id, doc_id, include_revisions } = target;
3479
4549
  try {
3480
4550
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
3481
4551
  headers: { "Authorization": `Bearer ${TOKEN}` },
@@ -3485,11 +4555,13 @@ const handleToolCall = async (request: any): Promise<any> => {
3485
4555
  return { content: [{ type: "text", text: `load_skill (channel) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
3486
4556
  }
3487
4557
  const doc = JSON.parse(text);
3488
- const body = doc?.body_markdown ?? doc?.bodyMarkdown ?? "";
4558
+ const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
3489
4559
  const title = doc?.title || doc_id;
3490
4560
  const kind = doc?.kind || "unknown";
3491
4561
  const level = doc?.level ?? "?";
3492
- const parsed = parseSkillFrontmatter(String(body));
4562
+ const version = doc?.version ?? "?";
4563
+ const archived = isArchivedSkillOrDoc(doc);
4564
+ const parsed = parseSkillFrontmatter(body);
3493
4565
  const metadata = { ...(parsed.metadata || {}), ...(doc?.skill_meta || doc?.skillMeta || {}) };
3494
4566
  const metaLines = [
3495
4567
  metadata.name ? `name: ${metadata.name}` : null,
@@ -3497,16 +4569,40 @@ const handleToolCall = async (request: any): Promise<any> => {
3497
4569
  metadata.trigger ? `trigger: ${metadata.trigger}` : null,
3498
4570
  (metadata.argument_hint ?? metadata.argumentHint) ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null,
3499
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
+ }
3500
4596
  if (!String(kind).toLowerCase().includes("skill") && !String(doc_id).toLowerCase().includes("skill")) {
3501
- return { content: [{ type: "text", text: `Loaded channel doc "${doc_id}" as requested, but it is not marked kind=skill.\n\n# ${title}\n\n${parsed.body}` }] };
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}` }] };
3502
4598
  }
3503
4599
  return {
3504
4600
  content: [{
3505
4601
  type: "text",
3506
4602
  text: [
3507
- `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}).`,
3508
4604
  metaLines ? `\nMetadata:\n${metaLines}` : "",
3509
- `\n# ${title}\n\n${parsed.body}`,
4605
+ `\n# ${title}\n\n${parsed.body}${revisionsBlock}`,
3510
4606
  ].join("\n"),
3511
4607
  }],
3512
4608
  };
@@ -3515,7 +4611,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3515
4611
  }
3516
4612
  }
3517
4613
  // GLOBAL skill: skill_id (default workspace-driven-eng).
3518
- const id = skill_id || DEFAULT_GLOBAL_SKILL_ID;
4614
+ const id = target.skill_id || DEFAULT_GLOBAL_SKILL_ID;
3519
4615
  const skill = GLOBAL_SKILLS[id];
3520
4616
  if (!skill) {
3521
4617
  return { content: [{ type: "text", text: `Unknown global skill: ${id}` }], isError: true };
@@ -3524,15 +4620,26 @@ const handleToolCall = async (request: any): Promise<any> => {
3524
4620
  }
3525
4621
 
3526
4622
  if (name === "save_memory") {
3527
- 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 };
3528
4624
  if (!a.name || !a.body) {
3529
4625
  return { content: [{ type: "text", text: "save_memory needs name (slug) + body (markdown). Optional description (one-line index hook)." }], isError: true };
3530
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
+ }
3531
4634
  try {
3532
4635
  const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}`, {
3533
4636
  method: "PUT",
3534
4637
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3535
- 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
+ }),
3536
4643
  });
3537
4644
  const text = await r.text();
3538
4645
  if (!r.ok) return { content: [{ type: "text", text: `save_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
@@ -3544,7 +4651,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3544
4651
  }
3545
4652
 
3546
4653
  if (name === "load_memory") {
3547
- 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;
3548
4659
  try {
3549
4660
  const path = a.name ? `/api/memory/${encodeURIComponent(a.name)}` : `/api/memory`;
3550
4661
  const r = await apiFetch(`${REST_URL}${path}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -3552,7 +4663,21 @@ const handleToolCall = async (request: any): Promise<any> => {
3552
4663
  if (!r.ok) return { content: [{ type: "text", text: `load_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3553
4664
  const resp = JSON.parse(text);
3554
4665
  if (a.name) {
3555
- 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}` }] };
3556
4681
  }
3557
4682
  const items = Array.isArray(resp.memories) ? resp.memories : [];
3558
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)." }] };
@@ -3564,55 +4689,108 @@ const handleToolCall = async (request: any): Promise<any> => {
3564
4689
  }
3565
4690
 
3566
4691
  if (name === "save_skill") {
3567
- const a = (args || {}) as { chat_id?: string; name?: string; description?: string; body?: string; doc_id?: string; level?: number };
3568
- if (!a.name || !a.description) {
3569
- return { content: [{ type: "text", text: "save_skill needs name + description (body is the skill markdown). Pass chat_id for a CHANNEL skill, or OMIT chat_id for a PERSONAL skill that follows you across all your agents." }], isError: true };
3570
- }
3571
- // Skill markdown = YAML frontmatter (name, description) + body — the exact
3572
- // shape parseSkillFrontmatter + the skill validators expect.
3573
- const oneLine = (s: string) => String(s).replace(/\r?\n/g, " ").slice(0, 480);
3574
- const md = `---\nname: ${oneLine(a.name)}\ndescription: ${oneLine(a.description)}\n---\n\n${a.body || ""}`;
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;
3575
4697
  // PERSONAL skill (no chat_id): per-owner store, shared across YOUR agents.
3576
- if (!a.chat_id) {
3577
- const pslug = String(a.doc_id || a.name).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "").slice(0, 64) || "skill";
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
+ }
3578
4722
  try {
3579
- 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)}`, {
3580
4729
  method: "PUT",
3581
- headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
3582
- 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
+ }),
3583
4735
  });
3584
4736
  const text = await r.text();
3585
4737
  if (!r.ok) return { content: [{ type: "text", text: `save_skill (personal) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3586
4738
  const resp = JSON.parse(text);
3587
- return { content: [{ type: "text", text: `Saved PERSONAL skill "${a.name}" as "${pslug}" (v${resp.version}) — shared across all your agents. Pull/refresh: sync_skill(name="${pslug}"); list: list_skills.` }] };
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.` }] };
3588
4740
  } catch (e: any) {
3589
4741
  return { content: [{ type: "text", text: `save_skill (personal) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3590
4742
  }
3591
4743
  }
3592
- // CHANNEL skill (chat_id given). Stable doc id: caller-supplied, else slug of name.
3593
- const slug = String(a.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill";
3594
- const docId = (a.doc_id && String(a.doc_id).trim()) || `skill-${slug}`;
3595
- const level = (typeof a.level === "number" && a.level >= 1 && a.level <= 4) ? a.level : 3; // 3 = member-writable
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
+ }
3596
4772
  try {
3597
- // If-Match: fetch current version (0 = create). The doc store uses
3598
- // optimistic concurrency; "0" creates, current version updates.
3599
- let ifMatch = "0";
3600
- const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3601
- if (cur.ok) {
3602
- const curDoc = await cur.json().catch(() => null) as any;
3603
- if (curDoc && curDoc.version != null) ifMatch = String(curDoc.version);
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
+ }
3604
4782
  }
3605
- 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)}`, {
3606
4784
  method: "PUT",
3607
4785
  headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json", "If-Match": ifMatch },
3608
- body: JSON.stringify({ kind: "channel_skill", level, title: a.name, body_markdown: md }),
4786
+ body: JSON.stringify({ kind: "channel_skill", level: v.level, title: v.name, body_markdown: v.body_markdown }),
3609
4787
  });
3610
4788
  const text = await r.text();
3611
4789
  if (!r.ok) {
3612
4790
  return { content: [{ type: "text", text: `save_skill failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
3613
4791
  }
3614
4792
  const verb = ifMatch === "0" ? "Saved" : "Updated";
3615
- return { content: [{ type: "text", text: `${verb} skill "${a.name}" → ${a.chat_id}/${docId} (L${level}). Others load it with: load_skill(chat_id="${a.chat_id}", doc_id="${docId}") — discoverable via list_skills(chat_id="${a.chat_id}").` }] };
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}").` }] };
3616
4794
  } catch (e: any) {
3617
4795
  return { content: [{ type: "text", text: `save_skill network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3618
4796
  }
@@ -3626,28 +4804,52 @@ const handleToolCall = async (request: any): Promise<any> => {
3626
4804
  // PERSONAL skill: sync_skill({name}) — version from GET /api/skills (cheap,
3627
4805
  // no body), body from GET /api/skills/:name only when missing/stale.
3628
4806
  if (a.name && !a.chat_id) {
3629
- 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)}`;
3630
4813
  const pMd = `${pBase}.md`; const pMeta = `${pBase}.json`;
3631
4814
  try {
3632
4815
  const listR = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3633
4816
  if (!listR.ok) return { content: [{ type: "text", text: `sync_skill (personal): list failed (${listR.status})` }], isError: true };
3634
- const meta = (JSON.parse(await listR.text()).skills || []).find((s: any) => s.name === a.name);
3635
- if (!meta) return { content: [{ type: "text", text: `sync_skill: personal skill "${a.name}" not found (save it with save_skill — no chat_id).` }], isError: true };
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
+ }
3636
4828
  const currentVersion = Number(meta.version ?? 0);
3637
4829
  let cachedVersion: number | null = null;
3638
4830
  try { cachedVersion = Number(JSON.parse(readFileSync(pMeta, "utf8")).version); } catch {}
3639
4831
  if (cachedVersion !== null && cachedVersion === currentVersion) {
3640
- return { content: [{ type: "text", text: `up-to-date: personal skill "${a.name}" v${currentVersion} already at ${pMd} — no download. Read that file to run it.` }] };
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.` }] };
3641
4833
  }
3642
- 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}` } });
3643
4835
  if (!bodyR.ok) return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
3644
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
+ }
3645
4847
  // node:fs (not Bun.write) — runs on plain Node too. Bun.write auto-creates
3646
4848
  // parent dirs; writeFileSync does not, so mkdir the cache dir first.
3647
4849
  mkdirSync(dirname(pMd), { recursive: true });
3648
- writeFileSync(pMd, String(doc?.body_markdown ?? ""));
3649
- writeFileSync(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
3650
- return { content: [{ type: "text", text: `synced personal skill "${a.name}" v${currentVersion} → ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
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.` }] };
3651
4853
  } catch (e: any) {
3652
4854
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
3653
4855
  }
@@ -3667,6 +4869,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3667
4869
  const docs = extractChannelDocsPayload(JSON.parse(await listR.text()));
3668
4870
  const meta = docs.find((d: any) => (d?.id ?? d?.doc_id) === a.doc_id);
3669
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
+ }
3670
4881
  const currentVersion = Number(meta.version ?? 0);
3671
4882
  // 2. Local cache check — skip the body fetch if we already have this version.
3672
4883
  let cachedVersion: number | null = null;
@@ -3679,6 +4890,15 @@ const handleToolCall = async (request: any): Promise<any> => {
3679
4890
  if (!docR.ok) return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
3680
4891
  const doc = JSON.parse(await docR.text());
3681
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
+ }
3682
4902
  // 4. Write the local mirror + version sidecar (node:fs, not Bun.write, for
3683
4903
  // Node compat; mkdir the cache dir first since writeFileSync won't auto-create).
3684
4904
  mkdirSync(dirname(mdPath), { recursive: true });
@@ -4016,40 +5236,67 @@ const handleToolCall = async (request: any): Promise<any> => {
4016
5236
  }
4017
5237
  }
4018
5238
 
4019
- if (name === "vote") {
4020
- const { proposal_id, decision, reason } = args as any;
4021
- if (typeof proposal_id !== "string" || typeof decision !== "string") {
4022
- return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }] };
4023
- }
4024
- if (ws && ws.readyState === WebSocket.OPEN) {
4025
- ws.send(JSON.stringify({
4026
- type: "vote", proposal_id, voter_id: AGENT_ID,
4027
- voter_type: "agent", decision, reason,
4028
- }));
4029
- return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
4030
- }
4031
- return { content: [{ type: "text", text: "Not connected" }] };
4032
- }
4033
-
4034
- if (name === "propose") {
4035
- const { chat_id, title, content, code_diff, consensus_rule } = args as any;
4036
- if (ws && ws.readyState === WebSocket.OPEN) {
4037
- const proposalId = crypto.randomUUID();
4038
- ws.send(JSON.stringify({
4039
- type: "proposal", id: proposalId, channel_id: chat_id,
4040
- sender_id: AGENT_ID, title, content, code_diff,
4041
- consensus_rule: consensus_rule || "majority",
4042
- expires_at: new Date(Date.now() + 86400_000).toISOString(),
4043
- timestamp: new Date().toISOString(),
4044
- }));
4045
- return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject — verify via next inbound event` }] };
4046
- }
4047
- return { content: [{ type: "text", text: "Not connected" }] };
4048
- }
4049
-
4050
5239
  async function fetchMcpChannelContext(chatId: string): Promise<{
4051
5240
  channel?: { id?: string; name?: string; type?: string; topic?: string; member_count?: number };
4052
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
+ };
4053
5300
  } | null> {
4054
5301
  if (!chatId || !TOKEN) return null;
4055
5302
  try {
@@ -4068,7 +5315,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4068
5315
  method: "tools/call",
4069
5316
  params: {
4070
5317
  name: "agentschat_get_channel_context",
4071
- arguments: { channel_id: chatId },
5318
+ arguments: { channel_id: chatId, include_briefing: true },
4072
5319
  },
4073
5320
  }),
4074
5321
  },
@@ -4099,10 +5346,13 @@ const handleToolCall = async (request: any): Promise<any> => {
4099
5346
  return r.ok ? await r.json() as any : null;
4100
5347
  } catch { return null; }
4101
5348
  };
4102
- const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5349
+ const [membersData, docsData, okrData, loopsData, personalSkillsData, wakeHealthData, mcpCtx] = await Promise.all([
4103
5350
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
4104
- get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5351
+ get(`/api/channels/${encodeURIComponent(chatId)}/docs?active_only=1`),
4105
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`),
4106
5356
  fetchMcpChannelContext(chatId),
4107
5357
  ]);
4108
5358
  // membersData === null means the /members read FAILED (most often a 403 because
@@ -4157,13 +5407,272 @@ const handleToolCall = async (request: any): Promise<any> => {
4157
5407
  : {}),
4158
5408
  is_self: String(m.agent_id) === AGENT_ID,
4159
5409
  }));
4160
- const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
4161
- const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
4162
- const docs = allDocs.filter((d: any) => !isSkillDoc(d)).slice(0, 10).map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
4163
- const objectives = (okrData?.objectives || []).filter((o: any) => !o.archived).map((o: any) => {
4164
- const open = (okrData?.tasks || []).filter((t: any) => t.objective_id === o.id && t.status !== "done").length;
4165
- return { id: o.id, title: o.title, open_tasks: open };
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
+ };
4166
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
+ }
4167
5676
  // Loadable extended tool groups — surfaced here so entering a room hands
4168
5677
  // you the full capability menu (not just skills). Without this an agent has
4169
5678
  // to already KNOW to call list_tool_groups; now "what can I do here / how to
@@ -4175,6 +5684,65 @@ const handleToolCall = async (request: any): Promise<any> => {
4175
5684
  tool_count: g.tools.length,
4176
5685
  loaded: loadedToolGroups.has(g.name),
4177
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;
4178
5746
  return JSON.stringify({
4179
5747
  channel: chatId,
4180
5748
  ...(mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {}),
@@ -4183,15 +5751,22 @@ const handleToolCall = async (request: any): Promise<any> => {
4183
5751
  ? { total: memberIds.length, online }
4184
5752
  : { total: null, note: "roster unreadable — you are likely not a member of this channel (or it does not exist)" },
4185
5753
  ...(membersReadable ? { agent_peers: agentPeers } : {}),
5754
+ okr_readable: okrReadable,
5755
+ docs_readable: docsReadable,
4186
5756
  okr_objectives: objectives,
5757
+ ...(okrSummary ? { okr_summary: okrSummary } : {}),
5758
+ ...(loopSummary ? { loop_summary: loopSummary } : {}),
5759
+ ...(wakeHealthSummary ? { wake_health_summary: wakeHealthSummary } : {}),
4187
5760
  skills,
5761
+ ...(personalSkills.length > 0 ? { personal_skills: personalSkills } : {}),
5762
+ ...(activeTaskLinkedDocs.length > 0 ? { active_task_linked_docs: activeTaskLinkedDocs } : {}),
4188
5763
  docs,
4189
5764
  tool_groups: toolGroups,
4190
5765
  tips: [
4191
5766
  "load_tool_group(name) reveals an extended group's tools (see tool_groups above; loaded:false = not yet active)",
4192
- "load_skill(chat_id, doc_id) activates a channel skill; list_skills(chat_id) lists them",
5767
+ "load_skill(chat_id, doc_id) activates a channel skill; load_skill(name) loads a personal skill; list_skills(chat_id) lists both",
4193
5768
  "okr_list / get_history for deeper context",
4194
- "/loop <interval> <prompt> works in joined groups and owner-agent DMs; keep group follow-ups in that group (okr: prefix = wake mode)",
5769
+ "create_loop(channel_id, mode, ...) (or /loop <interval> <prompt>) arms okr_wake / okr_watch / prompt loops; check loop_summary.unarmed_objective_ids",
4195
5770
  ],
4196
5771
  });
4197
5772
  }
@@ -4465,26 +6040,6 @@ const handleToolCall = async (request: any): Promise<any> => {
4465
6040
  return { content: [{ type: "text", text: gateNotice + text + pinLine }] };
4466
6041
  }
4467
6042
 
4468
- if (name === "list_channels") {
4469
- const { limit = 50 } = args as any;
4470
- try {
4471
- const r = await apiFetch(`${REST_URL}/api/channels/discover?limit=${Math.max(1, Math.min(Number(limit) || 50, 500))}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4472
- if (r.ok) {
4473
- const data = await r.json() as any;
4474
- const channels = (data.channels || []);
4475
- if (channels.length === 0) return { content: [{ type: "text", text: "No public channels found." }] };
4476
- // Show the FULL channel id — agents copy it straight into reply /
4477
- // get_history / join_channel, all of which need the complete UUID.
4478
- // A truncated 8-char prefix here makes every downstream call 404.
4479
- const list = channels.map((ch: any) => `• ${ch.name || ch.id} (${ch.id}) — ${ch.member_count || "?"} members${ch.topic ? ` — ${ch.topic.slice(0, 60)}` : ""}`).join("\n");
4480
- return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
4481
- }
4482
- return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
4483
- } catch (e) {
4484
- return { content: [{ type: "text", text: `Error: ${e}` }] };
4485
- }
4486
- }
4487
-
4488
6043
  if (name === "find_dm") {
4489
6044
  const { target_agent_id } = args as any;
4490
6045
  if (!target_agent_id || typeof target_agent_id !== "string") {
@@ -4529,16 +6084,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4529
6084
  }
4530
6085
 
4531
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
+ }
4532
6091
  try {
4533
6092
  const r = await apiFetch(`${REST_URL}/api/loops/mine`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4534
6093
  if (!r.ok) return { content: [{ type: "text", text: `Failed (${r.status})` }] };
4535
6094
  const data = await r.json() as any;
4536
- const loops = Array.isArray(data?.loops) ? data.loops : [];
4537
- if (loops.length === 0) return { content: [{ type: "text", text: "No loops registered for you." }] };
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
+ }
4538
6112
  const lines = loops.map((l: any) => {
4539
- const mode = l.mode === "okr_wake" ? `okr_wake → ${l.objective_id}${Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : ""}` : "static";
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;
4540
6127
  const nextIn = typeof l.next_tick_ms === "number" ? Math.max(0, Math.round((l.next_tick_ms - Date.now()) / 60000)) : "?";
4541
- return `• ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | next ~${nextIn}m`;
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}`;
4542
6130
  }).join("\n");
4543
6131
  return { content: [{ type: "text", text: `${loops.length} loop(s):\n${lines}` }] };
4544
6132
  } catch (e: any) {
@@ -4709,13 +6297,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4709
6297
  }
4710
6298
 
4711
6299
  if (name === "list_channel_docs") {
4712
- const { chat_id, level } = args as { chat_id: string; level?: number | string };
4713
- const qs = new URLSearchParams();
4714
- const normalizedLevel = normalizeChannelDocLevel(level);
4715
- if (level !== undefined && normalizedLevel === null) {
4716
- return { content: [{ type: "text", text: "list_channel_docs failed: level must be 1|2|3|4" }], isError: true };
6300
+ const check = validateListChannelDocsInput(args);
6301
+ if (!check.ok) {
6302
+ return { content: [{ type: "text", text: check.error }], isError: true };
4717
6303
  }
4718
- 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");
4719
6308
  const url = `${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${qs.toString() ? `?${qs}` : ""}`;
4720
6309
  try {
4721
6310
  const r = await apiFetch(url, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -4730,9 +6319,17 @@ const handleToolCall = async (request: any): Promise<any> => {
4730
6319
  }
4731
6320
 
4732
6321
  if (name === "get_channel_doc") {
4733
- 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
+ }
4734
6331
  try {
4735
- 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)}`, {
4736
6333
  headers: { "Authorization": `Bearer ${TOKEN}` },
4737
6334
  });
4738
6335
  const text = await r.text();
@@ -4746,43 +6343,102 @@ const handleToolCall = async (request: any): Promise<any> => {
4746
6343
  }
4747
6344
 
4748
6345
  if (name === "upsert_channel_doc") {
4749
- const { chat_id, doc_id, title, kind, level, body_markdown, expected_version } = args as {
4750
- chat_id: string;
4751
- doc_id: string;
4752
- title: string;
4753
- kind: string;
4754
- level: number | string;
4755
- body_markdown: string;
4756
- expected_version: number;
4757
- };
4758
- const normalizedLevel = normalizeChannelDocLevel(level);
4759
- if (normalizedLevel === null) {
4760
- return { content: [{ type: "text", text: "upsert_channel_doc failed: level must be 1|2|3|4" }], isError: true };
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 };
4761
6398
  }
6399
+ const { chat_id, doc_id, expected_version } = check.value;
4762
6400
  try {
4763
6401
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
4764
- method: "PUT",
6402
+ method: "DELETE",
4765
6403
  headers: {
4766
- "Content-Type": "application/json",
4767
6404
  "Authorization": `Bearer ${TOKEN}`,
4768
6405
  "If-Match": String(expected_version),
4769
6406
  },
4770
- body: JSON.stringify({ title, kind, level: normalizedLevel, body_markdown }),
4771
6407
  });
4772
6408
  const text = await r.text();
4773
6409
  if (!r.ok) {
4774
- 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 };
4775
6411
  }
4776
- 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 }] };
4777
6425
  } catch (e: any) {
4778
- 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 };
4779
6427
  }
4780
6428
  }
4781
6429
 
4782
6430
  if (name === "list_channel_doc_revisions") {
4783
- 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
+ }
4784
6440
  try {
4785
- 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`, {
4786
6442
  headers: { "Authorization": `Bearer ${TOKEN}` },
4787
6443
  });
4788
6444
  const text = await r.text();
@@ -4824,14 +6480,49 @@ const handleToolCall = async (request: any): Promise<any> => {
4824
6480
  }
4825
6481
 
4826
6482
  if (name === "okr_create_objective") {
4827
- const { title, horizon, owner, parent_id, due, discussion_channel_id } = args as {
4828
- title: string; horizon: string; owner?: string; parent_id?: string; due?: string; discussion_channel_id?: string;
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;
4829
6492
  };
4830
6493
  const body: Record<string, unknown> = { title, horizon };
4831
6494
  if (owner) body.owner = owner;
4832
- 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
+ }
4833
6502
  if (due) body.due = due;
4834
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
+ }
4835
6526
  try {
4836
6527
  const r = await apiFetch(`${REST_URL}/api/okr/objectives`, {
4837
6528
  method: "POST",
@@ -4842,20 +6533,103 @@ const handleToolCall = async (request: any): Promise<any> => {
4842
6533
  if (!r.ok) {
4843
6534
  return { content: [{ type: "text", text: `okr_create_objective failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4844
6535
  }
4845
- 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}` }] };
4846
6559
  } catch (e: any) {
4847
6560
  return { content: [{ type: "text", text: `okr_create_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4848
6561
  }
4849
6562
  }
4850
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
+
4851
6586
  if (name === "okr_add_task") {
4852
- const { objective_id, title, assignee, contributes_to, depends_on, due } = args as {
4853
- objective_id: string; title: string; assignee: string; contributes_to?: string[]; depends_on?: string[]; due?: string;
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;
4854
6595
  };
4855
- const body: Record<string, unknown> = { title, assignee };
4856
- if (Array.isArray(contributes_to) && contributes_to.length > 0) body.contributes_to = contributes_to;
4857
- if (Array.isArray(depends_on) && depends_on.length > 0) body.depends_on = depends_on;
4858
- if (due) body.due = due;
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
+ }
4859
6633
  try {
4860
6634
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/tasks`, {
4861
6635
  method: "POST",
@@ -4873,16 +6647,113 @@ const handleToolCall = async (request: any): Promise<any> => {
4873
6647
  }
4874
6648
 
4875
6649
  if (name === "okr_update_task") {
4876
- const { task_id, status, assignee, blocked_reason, blocker_agent, depends_on, due } = args as { task_id: string; status?: string; assignee?: string; blocked_reason?: string; blocker_agent?: string; depends_on?: string[]; due?: string };
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
+ }
4877
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
+ }
4878
6693
  if (status) patch.status = status;
4879
- 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
+ }
4880
6708
  if (blocked_reason !== undefined) patch.blocked_reason = blocked_reason;
4881
6709
  if (blocker_agent !== undefined) patch.blocker_agent = blocker_agent;
4882
- if (Array.isArray(depends_on)) patch.depends_on = depends_on;
4883
- if (due) patch.due = due;
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
+ }
4884
6754
  try {
4885
- 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, {
4886
6757
  method: "PATCH",
4887
6758
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4888
6759
  body: JSON.stringify(patch),
@@ -4891,7 +6762,48 @@ const handleToolCall = async (request: any): Promise<any> => {
4891
6762
  if (!r.ok) {
4892
6763
  return { content: [{ type: "text", text: `okr_update_task failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
4893
6764
  }
4894
- 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}` }] };
4895
6807
  } catch (e: any) {
4896
6808
  return { content: [{ type: "text", text: `okr_update_task network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4897
6809
  }
@@ -4933,12 +6845,11 @@ const handleToolCall = async (request: any): Promise<any> => {
4933
6845
  }
4934
6846
 
4935
6847
  if (name === "okr_add_kr") {
4936
- const { objective_id, title, metric_type, current, target, risk_level } = args as {
4937
- objective_id: string; title: string; metric_type: string; current?: number; target: number; risk_level?: string;
4938
- };
4939
- const body: Record<string, unknown> = { title, metric_type, target };
4940
- if (typeof current === "number") body.current = current;
4941
- if (risk_level) body.risk_level = risk_level;
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;
4942
6853
  try {
4943
6854
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/krs`, {
4944
6855
  method: "POST",
@@ -4956,12 +6867,16 @@ const handleToolCall = async (request: any): Promise<any> => {
4956
6867
  }
4957
6868
 
4958
6869
  if (name === "archive_objective") {
4959
- 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;
4960
6875
  try {
4961
6876
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/archive`, {
4962
6877
  method: "POST",
4963
6878
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
4964
- body: JSON.stringify(completion_summary !== undefined ? { completion_summary } : {}),
6879
+ body: JSON.stringify(body),
4965
6880
  });
4966
6881
  const text = await r.text();
4967
6882
  if (!r.ok) {
@@ -4991,11 +6906,14 @@ const handleToolCall = async (request: any): Promise<any> => {
4991
6906
  }
4992
6907
 
4993
6908
  if (name === "okr_set_kr_progress") {
4994
- const { kr_id, current, risk_level } = args as { kr_id: string; current: number; risk_level?: string };
4995
- const body: Record<string, unknown> = { current };
4996
- if (risk_level) body.risk_level = risk_level;
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";
4997
6915
  try {
4998
- 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}`, {
4999
6917
  method: "PATCH",
5000
6918
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
5001
6919
  body: JSON.stringify(body),
@@ -5030,21 +6948,41 @@ const handleToolCall = async (request: any): Promise<any> => {
5030
6948
  }
5031
6949
 
5032
6950
  if (name === "okr_set_links") {
5033
- 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 {
5034
6952
  target_type: "objective" | "kr" | "task";
5035
6953
  target_id: string;
5036
- narrative?: string;
6954
+ narrative?: unknown;
5037
6955
  narrative_path?: string;
5038
6956
  discussion_channel_id?: string;
5039
6957
  linked_docs?: string[];
5040
- linked_channel_docs?: Array<{ channel_id: string; doc_id: string }>;
6958
+ linked_channel_docs?: unknown;
6959
+ if_match_updated_at?: unknown;
5041
6960
  };
5042
6961
  const body: Record<string, unknown> = {};
5043
- 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
+ }
5044
6969
  if (narrative_path !== undefined) body.narrative_path = narrative_path;
5045
6970
  if (discussion_channel_id !== undefined) body.discussion_channel_id = discussion_channel_id;
5046
6971
  if (linked_docs !== undefined) body.linked_docs = linked_docs;
5047
- 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
+ }
5048
6986
  try {
5049
6987
  const r = await apiFetch(`${REST_URL}/api/okr/links/${encodeURIComponent(target_type)}/${encodeURIComponent(target_id)}`, {
5050
6988
  method: "PATCH",
@@ -5135,13 +7073,28 @@ function isSkillDoc(doc: any): boolean {
5135
7073
  return kind === "skill" || kind === "channel_skill" || id.includes("skill") || title.includes("skill");
5136
7074
  }
5137
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
+
5138
7088
  function compactSkillDoc(doc: any) {
5139
7089
  const meta = doc?.skill_meta || doc?.skillMeta || {};
7090
+ const archived = isArchivedSkillOrDoc(doc);
5140
7091
  return {
5141
7092
  doc_id: doc?.id ?? doc?.doc_id,
5142
7093
  title: doc?.title,
5143
7094
  kind: doc?.kind,
5144
7095
  level: doc?.level,
7096
+ ...(typeof doc?.version === "number" ? { version: doc.version } : {}),
7097
+ ...(archived ? { archived: true } : {}),
5145
7098
  updated_at: doc?.updatedAt ?? doc?.updated_at,
5146
7099
  name: meta.name,
5147
7100
  description: meta.description,