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/dist/server.js CHANGED
@@ -209,6 +209,1393 @@ function matchesJsonType(val, expected) {
209
209
  }
210
210
  });
211
211
  }
212
+ var TASK_EVIDENCE_KINDS = [
213
+ "commit",
214
+ "deploy",
215
+ "probe",
216
+ "doc",
217
+ "external",
218
+ "rollout"
219
+ ];
220
+ var TASK_EVIDENCE_CAP = 10;
221
+ var TASK_EVIDENCE_REF_MAX = 160;
222
+ var TASK_EVIDENCE_NOTE_MAX = 200;
223
+ var EVIDENCE_CTRL_RE = /[\u0000-\u001f\u007f]/;
224
+ var EVIDENCE_SECRET_RE = /(?:(?:ac|agent_key)_[A-Za-z0-9_-]{8,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|(?:sk|rk)-(?:live-|test-|proj-|ant-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|AIza[0-9A-Za-z_-]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN [^-]*PRIVATE KEY-----)/;
225
+ function isTaskEvidenceKind(v) {
226
+ return typeof v === "string" && TASK_EVIDENCE_KINDS.includes(v);
227
+ }
228
+ function validateTaskEvidenceInput(raw) {
229
+ if (raw === null)
230
+ return { ok: true, value: [] };
231
+ if (!Array.isArray(raw)) {
232
+ return { ok: false, error: "evidence must be an array (max 10 items; pass [] to clear)" };
233
+ }
234
+ if (raw.length === 0)
235
+ return { ok: true, value: [] };
236
+ if (raw.length > TASK_EVIDENCE_CAP) {
237
+ return { ok: false, error: `evidence exceeds max ${TASK_EVIDENCE_CAP} items` };
238
+ }
239
+ const out = [];
240
+ const seen = new Set;
241
+ for (let i = 0;i < raw.length; i++) {
242
+ const item = raw[i];
243
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
244
+ return { ok: false, error: `evidence[${i}] must be an object` };
245
+ }
246
+ const rawKind = item.kind;
247
+ const rawRef = item.ref;
248
+ const rawNote = item.note;
249
+ if (!isTaskEvidenceKind(rawKind)) {
250
+ return {
251
+ ok: false,
252
+ error: `evidence[${i}].kind must be one of ${TASK_EVIDENCE_KINDS.join("|")}`
253
+ };
254
+ }
255
+ if (typeof rawRef !== "string") {
256
+ return { ok: false, error: `evidence[${i}].ref must be a non-empty string` };
257
+ }
258
+ const ref = rawRef.trim();
259
+ if (!ref) {
260
+ return { ok: false, error: `evidence[${i}].ref must be a non-empty string` };
261
+ }
262
+ if (ref.length > TASK_EVIDENCE_REF_MAX) {
263
+ return { ok: false, error: `evidence[${i}].ref exceeds ${TASK_EVIDENCE_REF_MAX} chars` };
264
+ }
265
+ if (EVIDENCE_CTRL_RE.test(ref)) {
266
+ return { ok: false, error: `evidence[${i}].ref contains disallowed control characters` };
267
+ }
268
+ if (EVIDENCE_SECRET_RE.test(ref)) {
269
+ return { ok: false, error: `evidence[${i}].ref rejected: appears to contain a secret or token` };
270
+ }
271
+ let note;
272
+ if (rawNote !== undefined && rawNote !== null) {
273
+ if (typeof rawNote !== "string") {
274
+ return { ok: false, error: `evidence[${i}].note must be a string` };
275
+ }
276
+ const normalizedNote = rawNote.replace(/[\r\n\t]+/g, " ").trim();
277
+ if (normalizedNote.length > TASK_EVIDENCE_NOTE_MAX) {
278
+ return { ok: false, error: `evidence[${i}].note exceeds ${TASK_EVIDENCE_NOTE_MAX} chars` };
279
+ }
280
+ if (EVIDENCE_CTRL_RE.test(normalizedNote)) {
281
+ return { ok: false, error: `evidence[${i}].note contains disallowed control characters` };
282
+ }
283
+ if (normalizedNote.length > 0) {
284
+ if (EVIDENCE_SECRET_RE.test(normalizedNote)) {
285
+ return { ok: false, error: `evidence[${i}].note rejected: appears to contain a secret or token` };
286
+ }
287
+ note = normalizedNote;
288
+ }
289
+ }
290
+ const dedupKey = `${rawKind}:${ref}`;
291
+ if (seen.has(dedupKey)) {
292
+ return { ok: false, error: `duplicate evidence entry "${dedupKey}"` };
293
+ }
294
+ seen.add(dedupKey);
295
+ out.push({
296
+ kind: rawKind,
297
+ ref,
298
+ ...note ? { note } : {}
299
+ });
300
+ }
301
+ return { ok: true, value: out };
302
+ }
303
+ function validateAppendTaskEvidenceInput(raw) {
304
+ if (!Array.isArray(raw) || raw.length === 0) {
305
+ return {
306
+ ok: false,
307
+ error: `append_evidence must be a non-empty array (1..${TASK_EVIDENCE_CAP} items)`
308
+ };
309
+ }
310
+ return validateTaskEvidenceInput(raw);
311
+ }
312
+ function validateTaskVersionToken(raw) {
313
+ if (typeof raw !== "string") {
314
+ return { ok: false, error: "if_match_updated_at must be a non-empty string" };
315
+ }
316
+ const trimmed = raw.trim();
317
+ if (!trimmed || trimmed.length > 64 || EVIDENCE_CTRL_RE.test(trimmed)) {
318
+ return {
319
+ ok: false,
320
+ error: "if_match_updated_at must be a valid non-empty timestamp token (<=64 chars)"
321
+ };
322
+ }
323
+ if (EVIDENCE_SECRET_RE.test(trimmed)) {
324
+ return {
325
+ ok: false,
326
+ error: "if_match_updated_at rejected: appears to contain a secret or token"
327
+ };
328
+ }
329
+ return { ok: true, value: trimmed };
330
+ }
331
+ function responseIncludesAppendedEvidence(taskRaw, appended) {
332
+ if (!taskRaw || typeof taskRaw !== "object")
333
+ return false;
334
+ const evList = taskRaw.evidence;
335
+ if (!Array.isArray(evList))
336
+ return false;
337
+ return appended.every((want) => evList.some((item) => {
338
+ if (!item || typeof item !== "object")
339
+ return false;
340
+ const gotKind = item.kind;
341
+ const gotRef = typeof item.ref === "string" ? item.ref.trim() : "";
342
+ const gotNote = typeof item.note === "string" ? item.note.replace(/[\r\n\t]+/g, " ").trim() : "";
343
+ return gotKind === want.kind && gotRef === want.ref && gotNote === (want.note ?? "");
344
+ }));
345
+ }
346
+ function mergeLegacyTaskEvidence(existingRaw, appended) {
347
+ const merged = [];
348
+ const indexByKey = new Map;
349
+ if (Array.isArray(existingRaw)) {
350
+ for (const raw of existingRaw) {
351
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
352
+ continue;
353
+ const rawKind = raw.kind;
354
+ const rawRef = raw.ref;
355
+ const rawNote = raw.note;
356
+ if (!isTaskEvidenceKind(rawKind) || typeof rawRef !== "string")
357
+ continue;
358
+ const ref = rawRef.trim();
359
+ if (!ref || ref.length > TASK_EVIDENCE_REF_MAX || EVIDENCE_CTRL_RE.test(ref))
360
+ continue;
361
+ const note = typeof rawNote === "string" ? rawNote.replace(/[\r\n\t]+/g, " ").trim() : "";
362
+ if (note.length > TASK_EVIDENCE_NOTE_MAX || EVIDENCE_CTRL_RE.test(note))
363
+ continue;
364
+ const key = `${rawKind}:${ref}`;
365
+ if (indexByKey.has(key))
366
+ continue;
367
+ if (merged.length >= TASK_EVIDENCE_CAP)
368
+ break;
369
+ indexByKey.set(key, merged.length);
370
+ merged.push({ kind: rawKind, ref, ...note ? { note } : {} });
371
+ }
372
+ }
373
+ for (const item of appended) {
374
+ const key = `${item.kind}:${item.ref}`;
375
+ const existingIdx = indexByKey.get(key);
376
+ if (existingIdx !== undefined) {
377
+ merged[existingIdx] = { ...item };
378
+ } else {
379
+ if (merged.length >= TASK_EVIDENCE_CAP) {
380
+ return {
381
+ ok: false,
382
+ error: `evidence_cap_exceeded (task already at ${TASK_EVIDENCE_CAP} items; refused to overwrite history)`
383
+ };
384
+ }
385
+ indexByKey.set(key, merged.length);
386
+ merged.push({ ...item });
387
+ }
388
+ }
389
+ return { ok: true, value: merged };
390
+ }
391
+ var CREATE_LOOP_MODES = ["okr_wake", "okr_watch", "prompt"];
392
+ var LOOP_MIN_INTERVAL_MS = 60000;
393
+ var LOOP_MAX_INTERVAL_MS = 86400000;
394
+ var SAFE_CHANNEL_OR_LOOP_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
395
+ var SAFE_OBJECTIVE_ID_RE = /^[A-Za-z0-9_-]{6,80}$/;
396
+ var SAFE_AGENT_HANDLE_RE = /^[A-Za-z0-9_-]{2,64}$/;
397
+ var LOOP_PROMPT_CTRL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
398
+ function parseLoopIntervalShorthandMs(raw) {
399
+ const m = raw.trim().match(/^(\d+)\s*(s|sec|m|min|h|hr|d)?$/i);
400
+ if (!m)
401
+ return null;
402
+ const n = Number(m[1]);
403
+ if (!Number.isSafeInteger(n) || n <= 0)
404
+ return null;
405
+ const unit = (m[2] || "m").toLowerCase();
406
+ const mult = unit === "s" || unit === "sec" ? 1000 : unit === "m" || unit === "min" ? 60000 : unit === "h" || unit === "hr" ? 3600000 : 86400000;
407
+ const ms = n * mult;
408
+ if (!Number.isSafeInteger(ms) || ms < LOOP_MIN_INTERVAL_MS || ms > LOOP_MAX_INTERVAL_MS) {
409
+ return null;
410
+ }
411
+ return ms;
412
+ }
413
+ function validateCreateLoopInput(args) {
414
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
415
+ const channelId = typeof a.channel_id === "string" ? a.channel_id.trim() : "";
416
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(channelId) || channelId.includes("..")) {
417
+ return { ok: false, error: "create_loop needs a valid channel_id." };
418
+ }
419
+ const rawMode = typeof a.mode === "string" ? a.mode.trim() : "";
420
+ if (!CREATE_LOOP_MODES.includes(rawMode)) {
421
+ return { ok: false, error: "create_loop mode must be one of okr_wake|okr_watch|prompt." };
422
+ }
423
+ const mode = rawMode;
424
+ let intervalMs;
425
+ let interval;
426
+ if (a.interval_ms !== undefined && a.interval_ms !== null) {
427
+ if (typeof a.interval_ms !== "number" || !Number.isSafeInteger(a.interval_ms) || a.interval_ms < LOOP_MIN_INTERVAL_MS || a.interval_ms > LOOP_MAX_INTERVAL_MS) {
428
+ return {
429
+ ok: false,
430
+ error: `create_loop interval_ms must be an integer in ${LOOP_MIN_INTERVAL_MS}..${LOOP_MAX_INTERVAL_MS} (1m..24h).`
431
+ };
432
+ }
433
+ intervalMs = a.interval_ms;
434
+ }
435
+ if (a.interval !== undefined && a.interval !== null) {
436
+ if (typeof a.interval !== "string" || !a.interval.trim()) {
437
+ return { ok: false, error: "create_loop interval must be a shorthand string such as 5m, 15m, 1h." };
438
+ }
439
+ const parsed = parseLoopIntervalShorthandMs(a.interval);
440
+ if (parsed === null) {
441
+ return { ok: false, error: "create_loop interval must resolve within 1m..24h (e.g. 5m, 15m, 30m, 1h)." };
442
+ }
443
+ interval = a.interval.trim();
444
+ if (intervalMs !== undefined && intervalMs !== parsed) {
445
+ return { ok: false, error: "create_loop interval and interval_ms disagree; pass only one or matching values." };
446
+ }
447
+ }
448
+ let targetAgents;
449
+ if (a.target_agents !== undefined && a.target_agents !== null) {
450
+ if (!Array.isArray(a.target_agents)) {
451
+ return { ok: false, error: "create_loop target_agents must be an array of agent handles." };
452
+ }
453
+ if (a.target_agents.length > 12) {
454
+ return { ok: false, error: "create_loop target_agents exceeds max 12 targets." };
455
+ }
456
+ const dedup = [];
457
+ const seenTargets = new Set;
458
+ for (const entry of a.target_agents) {
459
+ if (typeof entry !== "string") {
460
+ return { ok: false, error: "create_loop target_agents items must be strings." };
461
+ }
462
+ const handle = entry.trim().replace(/^@+/, "");
463
+ if (!handle)
464
+ continue;
465
+ if (!SAFE_AGENT_HANDLE_RE.test(handle)) {
466
+ return { ok: false, error: `create_loop invalid target agent handle "${handle}".` };
467
+ }
468
+ if (!seenTargets.has(handle)) {
469
+ seenTargets.add(handle);
470
+ dedup.push(handle);
471
+ }
472
+ }
473
+ if (dedup.length > 0)
474
+ targetAgents = dedup;
475
+ }
476
+ const out = {
477
+ channel_id: channelId,
478
+ mode,
479
+ ...intervalMs !== undefined ? { interval_ms: intervalMs } : interval ? { interval } : {},
480
+ ...targetAgents ? { target_agents: targetAgents } : {}
481
+ };
482
+ if (a.stall_minutes !== undefined && a.stall_minutes !== null) {
483
+ if (mode !== "okr_watch") {
484
+ return { ok: false, error: 'create_loop stall_minutes is only supported when mode="okr_watch".' };
485
+ }
486
+ if (typeof a.stall_minutes !== "number" || !Number.isSafeInteger(a.stall_minutes) || a.stall_minutes < 5 || a.stall_minutes > 1440) {
487
+ return { ok: false, error: "create_loop stall_minutes must be an integer in 5..1440." };
488
+ }
489
+ }
490
+ if (mode === "okr_wake" || mode === "okr_watch") {
491
+ const objectiveId = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
492
+ if (!SAFE_OBJECTIVE_ID_RE.test(objectiveId)) {
493
+ return { ok: false, error: `create_loop mode="${mode}" requires a valid objective_id.` };
494
+ }
495
+ out.objective_id = objectiveId;
496
+ if (mode === "okr_watch") {
497
+ if (typeof a.watch_idle === "boolean")
498
+ out.watch_idle = a.watch_idle;
499
+ if (typeof a.watch_supply === "boolean")
500
+ out.watch_supply = a.watch_supply;
501
+ if (typeof a.stall_minutes === "number")
502
+ out.stall_minutes = a.stall_minutes;
503
+ }
504
+ return { ok: true, value: out };
505
+ }
506
+ const prompt = typeof a.prompt === "string" ? a.prompt.trim() : "";
507
+ if (!prompt) {
508
+ return { ok: false, error: 'create_loop mode="prompt" requires a non-empty prompt.' };
509
+ }
510
+ if (prompt.length > 500) {
511
+ return { ok: false, error: "create_loop prompt exceeds max 500 characters." };
512
+ }
513
+ if (LOOP_PROMPT_CTRL_RE.test(prompt)) {
514
+ return { ok: false, error: "create_loop prompt contains disallowed control characters." };
515
+ }
516
+ if (EVIDENCE_SECRET_RE.test(prompt)) {
517
+ return { ok: false, error: "create_loop prompt rejected: appears to contain a secret or token." };
518
+ }
519
+ out.prompt = prompt;
520
+ return { ok: true, value: out };
521
+ }
522
+ var OKR_KR_METRIC_TYPES = ["count", "bool", "percent"];
523
+ var OKR_KR_RISK_LEVELS = ["green", "yellow", "red"];
524
+ function validateOkrAddKrInput(args) {
525
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
526
+ const objectiveId = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
527
+ if (!objectiveId || !SAFE_CHANNEL_OR_LOOP_ID_RE.test(objectiveId) || objectiveId.includes("..")) {
528
+ return { ok: false, error: "okr_add_kr requires a valid objective_id." };
529
+ }
530
+ const rawTitle = typeof a.title === "string" ? a.title : "";
531
+ const title = rawTitle.replace(/[\r\n\t]+/g, " ").trim();
532
+ if (!title || title.length > 200 || EVIDENCE_CTRL_RE.test(title)) {
533
+ return { ok: false, error: "okr_add_kr title must be a non-empty string (<=200 chars) without control characters." };
534
+ }
535
+ if (EVIDENCE_SECRET_RE.test(title)) {
536
+ return { ok: false, error: "okr_add_kr title rejected: appears to contain a secret or token." };
537
+ }
538
+ const mt = a.metric_type === undefined ? "count" : a.metric_type;
539
+ if (typeof mt !== "string" || !OKR_KR_METRIC_TYPES.includes(mt)) {
540
+ return { ok: false, error: "okr_add_kr metric_type must be count|bool|percent." };
541
+ }
542
+ const metricType = mt;
543
+ if (typeof a.target !== "number" || !Number.isFinite(a.target) || a.target < 0 || a.target > 1e6) {
544
+ return { ok: false, error: "okr_add_kr target must be a finite number in 0..1000000." };
545
+ }
546
+ if (metricType === "bool" && a.target !== 0 && a.target !== 1) {
547
+ return { ok: false, error: "okr_add_kr bool target must be 0 or 1." };
548
+ }
549
+ if (metricType === "percent" && a.target > 100) {
550
+ return { ok: false, error: "okr_add_kr percent target must be <= 100." };
551
+ }
552
+ let current;
553
+ if (a.current !== undefined && a.current !== null) {
554
+ if (typeof a.current !== "number" || !Number.isFinite(a.current) || a.current < 0 || a.current > 1e6) {
555
+ return { ok: false, error: "okr_add_kr current must be a finite number in 0..1000000." };
556
+ }
557
+ if (metricType === "bool" && a.current !== 0 && a.current !== 1) {
558
+ return { ok: false, error: "okr_add_kr bool current must be 0 or 1." };
559
+ }
560
+ if (metricType === "percent" && a.current > 100) {
561
+ return { ok: false, error: "okr_add_kr percent current must be <= 100." };
562
+ }
563
+ current = a.current;
564
+ }
565
+ let riskLevel;
566
+ if (a.risk_level !== undefined && a.risk_level !== null) {
567
+ if (typeof a.risk_level !== "string" || !OKR_KR_RISK_LEVELS.includes(a.risk_level)) {
568
+ return { ok: false, error: "okr_add_kr risk_level must be green|yellow|red." };
569
+ }
570
+ riskLevel = a.risk_level;
571
+ }
572
+ return {
573
+ ok: true,
574
+ value: {
575
+ objective_id: objectiveId,
576
+ body: {
577
+ title,
578
+ metric_type: metricType,
579
+ target: a.target,
580
+ ...current !== undefined ? { current } : {},
581
+ ...riskLevel !== undefined ? { risk_level: riskLevel } : {}
582
+ }
583
+ }
584
+ };
585
+ }
586
+ function validateOkrKrMutationInput(args, toolLabel, forceMetadataEndpoint) {
587
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
588
+ const krId = typeof a.kr_id === "string" ? a.kr_id.trim() : "";
589
+ if (!krId || !SAFE_CHANNEL_OR_LOOP_ID_RE.test(krId) || krId.includes("..") || EVIDENCE_CTRL_RE.test(krId) || EVIDENCE_SECRET_RE.test(krId)) {
590
+ return { ok: false, error: `${toolLabel} requires a valid kr_id.` };
591
+ }
592
+ const body = {};
593
+ if (a.title !== undefined && a.title !== null) {
594
+ if (typeof a.title !== "string") {
595
+ return { ok: false, error: `${toolLabel} title must be a non-empty string (1..200 chars).` };
596
+ }
597
+ if (EVIDENCE_CTRL_RE.test(a.title)) {
598
+ return { ok: false, error: `${toolLabel} title must not contain control characters.` };
599
+ }
600
+ if (EVIDENCE_SECRET_RE.test(a.title)) {
601
+ return { ok: false, error: `${toolLabel} title rejected: appears to contain a secret or token.` };
602
+ }
603
+ const trimmedTitle = a.title.trim();
604
+ if (!trimmedTitle || trimmedTitle.length > 200) {
605
+ return { ok: false, error: `${toolLabel} title must be 1..200 chars.` };
606
+ }
607
+ body.title = trimmedTitle;
608
+ }
609
+ let metricType;
610
+ if (a.metric_type !== undefined && a.metric_type !== null) {
611
+ if (typeof a.metric_type !== "string" || !OKR_KR_METRIC_TYPES.includes(a.metric_type)) {
612
+ return { ok: false, error: `${toolLabel} metric_type must be count|bool|percent.` };
613
+ }
614
+ metricType = a.metric_type;
615
+ body.metric_type = metricType;
616
+ }
617
+ if (a.target !== undefined && a.target !== null) {
618
+ if (typeof a.target !== "number" || !Number.isFinite(a.target) || a.target < 0 || a.target > 1e6) {
619
+ return { ok: false, error: `${toolLabel} target must be a finite number in 0..1000000.` };
620
+ }
621
+ if (metricType === "bool" && a.target !== 0 && a.target !== 1) {
622
+ return { ok: false, error: `${toolLabel} bool target must be 0 or 1.` };
623
+ }
624
+ if (metricType === "percent" && a.target > 100) {
625
+ return { ok: false, error: `${toolLabel} percent target must be <= 100.` };
626
+ }
627
+ body.target = a.target;
628
+ }
629
+ if (a.current !== undefined && a.current !== null) {
630
+ if (typeof a.current !== "number" || !Number.isFinite(a.current) || a.current < 0 || a.current > 1e6) {
631
+ return { ok: false, error: `${toolLabel} current must be a finite number in 0..1000000.` };
632
+ }
633
+ if (metricType === "bool" && a.current !== 0 && a.current !== 1) {
634
+ return { ok: false, error: `${toolLabel} bool current must be 0 or 1.` };
635
+ }
636
+ if (metricType === "percent" && a.current > 100) {
637
+ return { ok: false, error: `${toolLabel} percent current must be <= 100.` };
638
+ }
639
+ body.current = a.current;
640
+ }
641
+ if (a.risk_level !== undefined && a.risk_level !== null) {
642
+ if (typeof a.risk_level !== "string" || !OKR_KR_RISK_LEVELS.includes(a.risk_level)) {
643
+ return { ok: false, error: `${toolLabel} risk_level must be green|yellow|red.` };
644
+ }
645
+ body.risk_level = a.risk_level;
646
+ }
647
+ const hasMutableField = body.title !== undefined || body.metric_type !== undefined || body.target !== undefined || body.current !== undefined || body.risk_level !== undefined;
648
+ if (!hasMutableField) {
649
+ return {
650
+ ok: false,
651
+ error: `${toolLabel} requires at least one of current, risk_level, title, metric_type, or target.`
652
+ };
653
+ }
654
+ if (a.if_match_updated_at !== undefined && a.if_match_updated_at !== null) {
655
+ const verCheck = validateTaskVersionToken(a.if_match_updated_at);
656
+ if (!verCheck.ok) {
657
+ return { ok: false, error: `${toolLabel} invalid if_match_updated_at: ${verCheck.error}` };
658
+ }
659
+ if (EVIDENCE_SECRET_RE.test(verCheck.value)) {
660
+ return { ok: false, error: `${toolLabel} if_match_updated_at rejected: appears to contain a secret or token.` };
661
+ }
662
+ body.if_match_updated_at = verCheck.value;
663
+ }
664
+ const useMetadataEndpoint = forceMetadataEndpoint || body.title !== undefined || body.metric_type !== undefined || body.target !== undefined || body.current === undefined;
665
+ return {
666
+ ok: true,
667
+ value: {
668
+ kr_id: krId,
669
+ body,
670
+ useMetadataEndpoint
671
+ }
672
+ };
673
+ }
674
+ function validateOkrSetKrProgressInput(args) {
675
+ return validateOkrKrMutationInput(args, "okr_set_kr_progress", false);
676
+ }
677
+ function validateOkrUpdateKrInput(args) {
678
+ return validateOkrKrMutationInput(args, "okr_update_kr", true);
679
+ }
680
+ function validateOkrTaskTitleInput(raw) {
681
+ if (typeof raw !== "string") {
682
+ return { ok: false, error: "title must be a non-empty string (1..200 chars)" };
683
+ }
684
+ if (EVIDENCE_CTRL_RE.test(raw)) {
685
+ return { ok: false, error: "title must not contain control characters" };
686
+ }
687
+ if (EVIDENCE_SECRET_RE.test(raw)) {
688
+ return { ok: false, error: "title rejected: appears to contain a secret or token" };
689
+ }
690
+ const trimmed = raw.trim();
691
+ if (!trimmed || trimmed.length > 200) {
692
+ return { ok: false, error: "title must be 1..200 chars" };
693
+ }
694
+ return { ok: true, value: trimmed };
695
+ }
696
+ function validateOkrTaskDueInput(raw) {
697
+ if (raw === null || raw === "") {
698
+ return { ok: true, value: "" };
699
+ }
700
+ if (typeof raw !== "string") {
701
+ return { ok: false, error: "due must be an ISO-8601 date/timestamp string (<= 32 chars) or empty string to clear" };
702
+ }
703
+ if (EVIDENCE_CTRL_RE.test(raw)) {
704
+ return { ok: false, error: "due must not contain control characters" };
705
+ }
706
+ if (EVIDENCE_SECRET_RE.test(raw)) {
707
+ return { ok: false, error: "due rejected: appears to contain a secret or token" };
708
+ }
709
+ const trimmed = raw.trim();
710
+ if (!trimmed) {
711
+ return { ok: true, value: "" };
712
+ }
713
+ if (trimmed.length > 32 || !Number.isFinite(Date.parse(trimmed))) {
714
+ return { ok: false, error: "due must be a valid ISO-8601 date/timestamp (<= 32 chars) or empty string to clear" };
715
+ }
716
+ return { ok: true, value: trimmed };
717
+ }
718
+ var OKR_TASK_CONTRIBUTES_CAP = 5;
719
+ function validateOkrTaskAssigneeInput(raw) {
720
+ if (typeof raw !== "string") {
721
+ return { ok: false, error: "assignee must be a non-empty agent handle string" };
722
+ }
723
+ const trimmed = raw.trim().replace(/^@+/, "");
724
+ if (!trimmed || trimmed.length > 128 || EVIDENCE_CTRL_RE.test(trimmed)) {
725
+ return { ok: false, error: "assignee must be a non-empty agent handle (<=128 chars)" };
726
+ }
727
+ if (trimmed.includes("@")) {
728
+ return { ok: false, error: "assignee rejected: must be an agent handle, never an email address" };
729
+ }
730
+ if (EVIDENCE_SECRET_RE.test(trimmed)) {
731
+ return { ok: false, error: "assignee rejected: appears to contain a secret or token" };
732
+ }
733
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(trimmed) || trimmed.includes("..")) {
734
+ return { ok: false, error: `assignee "${trimmed}" contains invalid characters` };
735
+ }
736
+ return { ok: true, value: trimmed };
737
+ }
738
+ function validateOkrTaskContributesToInput(raw) {
739
+ if (raw === null)
740
+ return { ok: true, value: [] };
741
+ if (!Array.isArray(raw)) {
742
+ return {
743
+ ok: false,
744
+ error: `contributes_to must be an array of KR IDs (0..${OKR_TASK_CONTRIBUTES_CAP} items; pass [] to clear)`
745
+ };
746
+ }
747
+ if (raw.length === 0)
748
+ return { ok: true, value: [] };
749
+ if (raw.length > OKR_TASK_CONTRIBUTES_CAP) {
750
+ return { ok: false, error: `contributes_to exceeds max ${OKR_TASK_CONTRIBUTES_CAP} KR IDs` };
751
+ }
752
+ const out = [];
753
+ const seen = new Set;
754
+ for (let i = 0;i < raw.length; i++) {
755
+ const item = raw[i];
756
+ if (typeof item !== "string") {
757
+ return { ok: false, error: `contributes_to[${i}] must be a non-empty KR ID string` };
758
+ }
759
+ const id = item.trim();
760
+ if (!id || id.length > 128 || EVIDENCE_CTRL_RE.test(id)) {
761
+ return { ok: false, error: `contributes_to[${i}] must be a non-empty KR ID (<=128 chars)` };
762
+ }
763
+ if (EVIDENCE_SECRET_RE.test(id)) {
764
+ return { ok: false, error: `contributes_to[${i}] rejected: appears to contain a secret or token` };
765
+ }
766
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(id) || id.includes("..")) {
767
+ return { ok: false, error: `contributes_to[${i}] contains invalid KR ID characters` };
768
+ }
769
+ if (!seen.has(id)) {
770
+ seen.add(id);
771
+ out.push(id);
772
+ }
773
+ }
774
+ return { ok: true, value: out };
775
+ }
776
+ var OKR_TASK_DEPENDS_ON_CAP = 20;
777
+ var OKR_LINKED_CHANNEL_DOCS_CAP = 10;
778
+ var OKR_DOC_CHANNEL_ID_RE = /^[A-Za-z0-9_-]{1,80}$/;
779
+ var OKR_DOC_ID_RE = /^[A-Za-z0-9_-]{1,120}$/;
780
+ var OKR_NARRATIVE_MAX = 2000;
781
+ function validateOkrTaskDependsOnInput(raw, selfTaskId) {
782
+ if (raw === null)
783
+ return { ok: true, value: [] };
784
+ if (!Array.isArray(raw)) {
785
+ return {
786
+ ok: false,
787
+ error: `depends_on must be an array of task IDs (0..${OKR_TASK_DEPENDS_ON_CAP} items; pass [] to clear)`
788
+ };
789
+ }
790
+ if (raw.length === 0)
791
+ return { ok: true, value: [] };
792
+ if (raw.length > OKR_TASK_DEPENDS_ON_CAP) {
793
+ return { ok: false, error: `depends_on exceeds max ${OKR_TASK_DEPENDS_ON_CAP} task IDs` };
794
+ }
795
+ const normalizedSelf = typeof selfTaskId === "string" ? selfTaskId.trim() : "";
796
+ const out = [];
797
+ const seen = new Set;
798
+ for (let i = 0;i < raw.length; i++) {
799
+ const item = raw[i];
800
+ if (typeof item !== "string") {
801
+ return { ok: false, error: `depends_on[${i}] must be a non-empty task ID string` };
802
+ }
803
+ const id = item.trim();
804
+ if (!id || id.length > 128 || EVIDENCE_CTRL_RE.test(id)) {
805
+ return { ok: false, error: `depends_on[${i}] must be a non-empty task ID (<=128 chars)` };
806
+ }
807
+ if (EVIDENCE_SECRET_RE.test(id)) {
808
+ return { ok: false, error: `depends_on[${i}] rejected: appears to contain a secret or token` };
809
+ }
810
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(id) || id.includes("..")) {
811
+ return { ok: false, error: `depends_on[${i}] contains invalid task ID characters` };
812
+ }
813
+ if (normalizedSelf && id === normalizedSelf) {
814
+ return { ok: false, error: `depends_on[${i}] cannot reference the task itself (${id})` };
815
+ }
816
+ if (!seen.has(id)) {
817
+ seen.add(id);
818
+ out.push(id);
819
+ }
820
+ }
821
+ return { ok: true, value: out };
822
+ }
823
+ function validateOkrLinkedChannelDocsInput(raw, expectedChannelId) {
824
+ if (raw === null)
825
+ return { ok: true, value: [] };
826
+ if (!Array.isArray(raw)) {
827
+ return {
828
+ ok: false,
829
+ error: `linked_channel_docs must be an array of {channel_id, doc_id} objects (0..${OKR_LINKED_CHANNEL_DOCS_CAP} items; pass [] to clear)`
830
+ };
831
+ }
832
+ if (raw.length === 0)
833
+ return { ok: true, value: [] };
834
+ if (raw.length > OKR_LINKED_CHANNEL_DOCS_CAP) {
835
+ return { ok: false, error: `linked_channel_docs exceeds max ${OKR_LINKED_CHANNEL_DOCS_CAP} items` };
836
+ }
837
+ const requiredChannel = typeof expectedChannelId === "string" ? expectedChannelId.trim() : "";
838
+ const out = [];
839
+ const seen = new Set;
840
+ for (let i = 0;i < raw.length; i++) {
841
+ const item = raw[i];
842
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
843
+ return { ok: false, error: `linked_channel_docs[${i}] must be an object with channel_id and doc_id` };
844
+ }
845
+ const rawChannelId = item.channel_id;
846
+ const rawDocId = item.doc_id;
847
+ if (typeof rawChannelId !== "string" || typeof rawDocId !== "string") {
848
+ return { ok: false, error: `linked_channel_docs[${i}] requires string channel_id and doc_id` };
849
+ }
850
+ const channelId = rawChannelId.trim();
851
+ const docId = rawDocId.trim();
852
+ if (!channelId || !OKR_DOC_CHANNEL_ID_RE.test(channelId) || /^dm-/i.test(channelId)) {
853
+ return {
854
+ ok: false,
855
+ error: `linked_channel_docs[${i}].channel_id must be a valid non-DM room ID (1..80 chars)`
856
+ };
857
+ }
858
+ if (EVIDENCE_SECRET_RE.test(channelId) || EVIDENCE_SECRET_RE.test(docId)) {
859
+ return { ok: false, error: `linked_channel_docs[${i}] rejected: appears to contain a secret or token` };
860
+ }
861
+ if (!docId || !OKR_DOC_ID_RE.test(docId)) {
862
+ return { ok: false, error: `linked_channel_docs[${i}].doc_id must match ^[A-Za-z0-9_-]{1,120}$` };
863
+ }
864
+ if (requiredChannel && channelId !== requiredChannel) {
865
+ return {
866
+ ok: false,
867
+ error: `linked_channel_docs[${i}].channel_id (${channelId}) must match discussion_channel_id (${requiredChannel})`
868
+ };
869
+ }
870
+ const key = `${channelId}:${docId}`;
871
+ if (!seen.has(key)) {
872
+ seen.add(key);
873
+ out.push({ channel_id: channelId, doc_id: docId });
874
+ }
875
+ }
876
+ return { ok: true, value: out };
877
+ }
878
+ function validateOkrObjectiveNarrativeInput(raw) {
879
+ if (raw === null || raw === "")
880
+ return { ok: true, value: "" };
881
+ if (typeof raw !== "string") {
882
+ return { ok: false, error: "narrative must be a string" };
883
+ }
884
+ if (raw.length > OKR_NARRATIVE_MAX || EVIDENCE_CTRL_RE.test(raw)) {
885
+ return { ok: false, error: `narrative must be <= ${OKR_NARRATIVE_MAX} chars without control characters` };
886
+ }
887
+ if (EVIDENCE_SECRET_RE.test(raw)) {
888
+ return { ok: false, error: "narrative rejected: appears to contain a secret or token" };
889
+ }
890
+ return { ok: true, value: raw.trim() };
891
+ }
892
+ var OKR_OBJECTIVE_TITLE_MAX = 200;
893
+ var OKR_COMPLETION_SUMMARY_MAX = 280;
894
+ var OKR_OBJECTIVE_STATUSES = ["active", "done", "abandoned"];
895
+ var OKR_OBJECTIVE_HORIZONS = ["week", "month", "Q"];
896
+ function validateOkrCompletionSummaryInput(raw) {
897
+ if (raw === null || raw === "")
898
+ return { ok: true, value: "" };
899
+ if (typeof raw !== "string") {
900
+ return { ok: false, error: "completion_summary must be a string" };
901
+ }
902
+ if (EVIDENCE_CTRL_RE.test(raw)) {
903
+ return { ok: false, error: "completion_summary must not contain control characters" };
904
+ }
905
+ if (EVIDENCE_SECRET_RE.test(raw)) {
906
+ return { ok: false, error: "completion_summary rejected: appears to contain a secret or token" };
907
+ }
908
+ const trimmed = raw.trim();
909
+ if (trimmed.length > OKR_COMPLETION_SUMMARY_MAX) {
910
+ return { ok: false, error: `completion_summary exceeds max ${OKR_COMPLETION_SUMMARY_MAX} chars` };
911
+ }
912
+ return { ok: true, value: trimmed };
913
+ }
914
+ function validateOkrUpdateObjectiveInput(args) {
915
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
916
+ const objectiveId = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
917
+ if (!objectiveId || !SAFE_CHANNEL_OR_LOOP_ID_RE.test(objectiveId) || objectiveId.includes("..") || EVIDENCE_CTRL_RE.test(objectiveId) || EVIDENCE_SECRET_RE.test(objectiveId)) {
918
+ return { ok: false, error: "objective_id must be a valid non-empty identifier" };
919
+ }
920
+ const body = {};
921
+ if (a.title !== undefined) {
922
+ if (typeof a.title !== "string") {
923
+ return { ok: false, error: "title must be a non-empty string (<= 200 chars)" };
924
+ }
925
+ if (EVIDENCE_CTRL_RE.test(a.title)) {
926
+ return { ok: false, error: "title must not contain control characters" };
927
+ }
928
+ if (EVIDENCE_SECRET_RE.test(a.title)) {
929
+ return { ok: false, error: "title rejected: appears to contain a secret or token" };
930
+ }
931
+ const trimmedTitle = a.title.trim();
932
+ if (!trimmedTitle || trimmedTitle.length > OKR_OBJECTIVE_TITLE_MAX) {
933
+ return { ok: false, error: `title must be 1..${OKR_OBJECTIVE_TITLE_MAX} chars` };
934
+ }
935
+ body.title = trimmedTitle;
936
+ }
937
+ if (a.status !== undefined) {
938
+ if (typeof a.status !== "string" || !OKR_OBJECTIVE_STATUSES.includes(a.status)) {
939
+ return { ok: false, error: "status must be active, done, or abandoned" };
940
+ }
941
+ body.status = a.status;
942
+ }
943
+ if (a.horizon !== undefined) {
944
+ if (typeof a.horizon !== "string" || !OKR_OBJECTIVE_HORIZONS.includes(a.horizon)) {
945
+ return { ok: false, error: "horizon must be week, month, or Q" };
946
+ }
947
+ body.horizon = a.horizon;
948
+ }
949
+ if (a.due !== undefined) {
950
+ if (a.due === null || a.due === "") {
951
+ body.due = "";
952
+ } else if (typeof a.due === "string") {
953
+ if (EVIDENCE_CTRL_RE.test(a.due)) {
954
+ return { ok: false, error: "due must not contain control characters" };
955
+ }
956
+ if (EVIDENCE_SECRET_RE.test(a.due)) {
957
+ return { ok: false, error: "due rejected: appears to contain a secret or token" };
958
+ }
959
+ const trimmedDue = a.due.trim();
960
+ if (!trimmedDue) {
961
+ body.due = "";
962
+ } else if (trimmedDue.length > 32 || !Number.isFinite(Date.parse(trimmedDue))) {
963
+ return { ok: false, error: "due must be a valid ISO-8601 date/timestamp (<= 32 chars) or empty string to clear" };
964
+ } else {
965
+ body.due = trimmedDue;
966
+ }
967
+ } else {
968
+ return { ok: false, error: "due must be an ISO-8601 date string or empty string to clear" };
969
+ }
970
+ }
971
+ if (a.narrative !== undefined) {
972
+ const narCheck = validateOkrObjectiveNarrativeInput(a.narrative);
973
+ if (!narCheck.ok)
974
+ return narCheck;
975
+ body.narrative = narCheck.value;
976
+ }
977
+ if (a.completion_summary !== undefined) {
978
+ const sumCheck = validateOkrCompletionSummaryInput(a.completion_summary);
979
+ if (!sumCheck.ok)
980
+ return sumCheck;
981
+ body.completion_summary = sumCheck.value;
982
+ }
983
+ if (a.linked_channel_docs !== undefined) {
984
+ const docsCheck = validateOkrLinkedChannelDocsInput(a.linked_channel_docs);
985
+ if (!docsCheck.ok)
986
+ return docsCheck;
987
+ if (docsCheck.value.length > 1) {
988
+ const firstChan = docsCheck.value[0].channel_id;
989
+ if (docsCheck.value.some((d) => d.channel_id !== firstChan)) {
990
+ return { ok: false, error: "linked_channel_docs items on an Objective must all reference the same channel_id" };
991
+ }
992
+ }
993
+ body.linked_channel_docs = docsCheck.value;
994
+ }
995
+ if (Object.keys(body).length === 0) {
996
+ return {
997
+ ok: false,
998
+ error: "at least one mutable field (title, status, horizon, due, narrative, completion_summary, linked_channel_docs) is required"
999
+ };
1000
+ }
1001
+ if (a.if_match_updated_at !== undefined && a.if_match_updated_at !== null) {
1002
+ const verCheck = validateTaskVersionToken(a.if_match_updated_at);
1003
+ if (!verCheck.ok) {
1004
+ return { ok: false, error: verCheck.error };
1005
+ }
1006
+ body.if_match_updated_at = verCheck.value;
1007
+ }
1008
+ return { ok: true, value: { objective_id: objectiveId, body } };
1009
+ }
1010
+ function validateOkrArchiveObjectiveInput(args) {
1011
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1012
+ const objectiveId = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
1013
+ if (!objectiveId || !SAFE_CHANNEL_OR_LOOP_ID_RE.test(objectiveId) || objectiveId.includes("..") || EVIDENCE_CTRL_RE.test(objectiveId) || EVIDENCE_SECRET_RE.test(objectiveId)) {
1014
+ return { ok: false, error: "objective_id must be a valid non-empty identifier" };
1015
+ }
1016
+ const body = {};
1017
+ if (a.completion_summary !== undefined && a.completion_summary !== null) {
1018
+ const sumCheck = validateOkrCompletionSummaryInput(a.completion_summary);
1019
+ if (!sumCheck.ok)
1020
+ return sumCheck;
1021
+ if (sumCheck.value) {
1022
+ body.completion_summary = sumCheck.value;
1023
+ }
1024
+ }
1025
+ return { ok: true, value: { objective_id: objectiveId, body } };
1026
+ }
1027
+ function validateListLoopsInput(args) {
1028
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1029
+ const out = {};
1030
+ if (a.channel_id !== undefined && a.channel_id !== null) {
1031
+ const cid = typeof a.channel_id === "string" ? a.channel_id.trim() : "";
1032
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(cid) || cid.includes("..") || EVIDENCE_SECRET_RE.test(cid)) {
1033
+ return { ok: false, error: "list_loops channel_id must be a valid channel identifier." };
1034
+ }
1035
+ out.channel_id = cid;
1036
+ }
1037
+ if (a.status !== undefined && a.status !== null) {
1038
+ if (a.status !== "active" && a.status !== "paused") {
1039
+ return { ok: false, error: "list_loops status must be one of: active, paused." };
1040
+ }
1041
+ out.status = a.status;
1042
+ }
1043
+ if (a.mode !== undefined && a.mode !== null) {
1044
+ if (typeof a.mode !== "string" || !CREATE_LOOP_MODES.includes(a.mode)) {
1045
+ return { ok: false, error: "list_loops mode must be one of: okr_wake, okr_watch, prompt." };
1046
+ }
1047
+ out.mode = a.mode;
1048
+ }
1049
+ if (a.objective_id !== undefined && a.objective_id !== null) {
1050
+ const oid = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
1051
+ if (!SAFE_OBJECTIVE_ID_RE.test(oid) || EVIDENCE_SECRET_RE.test(oid)) {
1052
+ return { ok: false, error: "list_loops objective_id must be a valid objective identifier." };
1053
+ }
1054
+ out.objective_id = oid;
1055
+ }
1056
+ return { ok: true, value: out };
1057
+ }
1058
+ var SAFE_MEMORY_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
1059
+ function validateLoadMemoryInput(args) {
1060
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1061
+ const out = {};
1062
+ if (a.name !== undefined && a.name !== null) {
1063
+ if (typeof a.name !== "string") {
1064
+ return { ok: false, error: "load_memory name must be a string." };
1065
+ }
1066
+ const trimmed = a.name.trim();
1067
+ if (trimmed) {
1068
+ if (!SAFE_MEMORY_NAME_RE.test(trimmed) || trimmed.includes("..") || EVIDENCE_CTRL_RE.test(trimmed) || EVIDENCE_SECRET_RE.test(trimmed)) {
1069
+ return {
1070
+ ok: false,
1071
+ error: "load_memory name must be 1..64 alphanumeric/._- chars starting with alphanumeric."
1072
+ };
1073
+ }
1074
+ out.name = trimmed;
1075
+ }
1076
+ }
1077
+ if (a.include_revisions !== undefined && a.include_revisions !== null) {
1078
+ if (typeof a.include_revisions !== "boolean") {
1079
+ return { ok: false, error: "load_memory include_revisions must be a boolean." };
1080
+ }
1081
+ if (a.include_revisions && !out.name) {
1082
+ return { ok: false, error: "load_memory include_revisions requires a specific memory name." };
1083
+ }
1084
+ out.include_revisions = a.include_revisions;
1085
+ }
1086
+ return { ok: true, value: out };
1087
+ }
1088
+ function validateDeleteMemoryInput(args) {
1089
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1090
+ const name = typeof a.name === "string" ? a.name.trim() : "";
1091
+ if (!name || !SAFE_MEMORY_NAME_RE.test(name) || name.includes("..") || EVIDENCE_CTRL_RE.test(name) || EVIDENCE_SECRET_RE.test(name)) {
1092
+ return {
1093
+ ok: false,
1094
+ error: "delete_memory requires a valid memory name (1..64 alphanumeric/._- chars starting with alphanumeric)."
1095
+ };
1096
+ }
1097
+ const out = { name };
1098
+ if (a.if_match_version !== undefined && a.if_match_version !== null) {
1099
+ if (typeof a.if_match_version !== "number" || !Number.isSafeInteger(a.if_match_version) || a.if_match_version < 1 || a.if_match_version > 1e6) {
1100
+ return { ok: false, error: "delete_memory if_match_version must be an integer in 1..1000000." };
1101
+ }
1102
+ out.if_match_version = a.if_match_version;
1103
+ }
1104
+ if (a.allow_missing !== undefined && a.allow_missing !== null) {
1105
+ if (typeof a.allow_missing !== "boolean") {
1106
+ return { ok: false, error: "delete_memory allow_missing must be a boolean." };
1107
+ }
1108
+ out.allow_missing = a.allow_missing;
1109
+ }
1110
+ return { ok: true, value: out };
1111
+ }
1112
+ function validateOkrParentIdOptionalInput(parentId) {
1113
+ if (parentId === undefined || parentId === null || parentId === "") {
1114
+ return { ok: true, value: undefined };
1115
+ }
1116
+ if (typeof parentId !== "string") {
1117
+ return { ok: false, error: "parent_id must be a string objective identifier" };
1118
+ }
1119
+ const trimmed = parentId.trim();
1120
+ if (!trimmed) {
1121
+ return { ok: true, value: undefined };
1122
+ }
1123
+ if (EVIDENCE_SECRET_RE.test(trimmed)) {
1124
+ return { ok: false, error: "parent_id rejected: appears to contain a secret or token" };
1125
+ }
1126
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(trimmed) || trimmed.includes("..") || EVIDENCE_CTRL_RE.test(trimmed)) {
1127
+ return { ok: false, error: "parent_id must be a valid objective identifier" };
1128
+ }
1129
+ return { ok: true, value: trimmed };
1130
+ }
1131
+ function validateOkrReparentObjectiveInput(args) {
1132
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
1133
+ return { ok: false, error: "okr_reparent_objective requires objective_id and parent_id." };
1134
+ }
1135
+ const a = args;
1136
+ const objectiveId = typeof a.objective_id === "string" ? a.objective_id.trim() : "";
1137
+ if (!objectiveId || !SAFE_CHANNEL_OR_LOOP_ID_RE.test(objectiveId) || objectiveId.includes("..") || EVIDENCE_CTRL_RE.test(objectiveId) || EVIDENCE_SECRET_RE.test(objectiveId)) {
1138
+ return { ok: false, error: "objective_id must be a valid non-empty identifier." };
1139
+ }
1140
+ if (!("parent_id" in a) || a.parent_id === undefined) {
1141
+ return {
1142
+ ok: false,
1143
+ error: "okr_reparent_objective needs parent_id (an objective id to attach under, or null to detach to a top-level root)."
1144
+ };
1145
+ }
1146
+ let normalizedParent;
1147
+ if (a.parent_id === null || typeof a.parent_id === "string" && a.parent_id.trim() === "") {
1148
+ normalizedParent = null;
1149
+ } else if (typeof a.parent_id === "string") {
1150
+ const trimmedParent = a.parent_id.trim();
1151
+ if (EVIDENCE_SECRET_RE.test(trimmedParent)) {
1152
+ return { ok: false, error: "parent_id rejected: appears to contain a secret or token" };
1153
+ }
1154
+ if (!SAFE_CHANNEL_OR_LOOP_ID_RE.test(trimmedParent) || trimmedParent.includes("..") || EVIDENCE_CTRL_RE.test(trimmedParent)) {
1155
+ return { ok: false, error: "parent_id must be a valid objective identifier or null to detach" };
1156
+ }
1157
+ if (trimmedParent === objectiveId) {
1158
+ return { ok: false, error: "parent_id cannot equal objective_id (self-reparent cycle)" };
1159
+ }
1160
+ normalizedParent = trimmedParent;
1161
+ } else {
1162
+ return { ok: false, error: "parent_id must be a string objective identifier or null to detach" };
1163
+ }
1164
+ const body = { parent_id: normalizedParent };
1165
+ if (a.if_match_updated_at !== undefined && a.if_match_updated_at !== null) {
1166
+ const verCheck = validateTaskVersionToken(a.if_match_updated_at);
1167
+ if (!verCheck.ok) {
1168
+ return { ok: false, error: verCheck.error };
1169
+ }
1170
+ body.if_match_updated_at = verCheck.value;
1171
+ }
1172
+ return { ok: true, value: { objective_id: objectiveId, body } };
1173
+ }
1174
+ var CHANNEL_DOC_KINDS = [
1175
+ "topic",
1176
+ "rules",
1177
+ "roles",
1178
+ "context",
1179
+ "deep_dive",
1180
+ "skill",
1181
+ "channel_skill"
1182
+ ];
1183
+ var SAFE_CHANNEL_DOC_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
1184
+ function normalizeDocLevelValue(level) {
1185
+ if (typeof level === "number" && Number.isInteger(level) && level >= 1 && level <= 4) {
1186
+ return level;
1187
+ }
1188
+ if (typeof level === "string") {
1189
+ const m = level.trim().match(/^(?:L)?([1-4])$/i);
1190
+ if (m)
1191
+ return Number(m[1]);
1192
+ }
1193
+ return null;
1194
+ }
1195
+ function validateChannelDocRoomId(raw, toolName) {
1196
+ const chatId = typeof raw === "string" ? raw.trim() : "";
1197
+ if (!chatId || !OKR_DOC_CHANNEL_ID_RE.test(chatId) || /^dm-/i.test(chatId) || chatId === "direct" || chatId.includes("..") || EVIDENCE_CTRL_RE.test(chatId)) {
1198
+ return { ok: false, error: `${toolName} requires a valid non-DM room chat_id (1..80 chars).` };
1199
+ }
1200
+ if (EVIDENCE_SECRET_RE.test(chatId)) {
1201
+ return { ok: false, error: `${toolName} chat_id rejected: appears to contain a secret or token.` };
1202
+ }
1203
+ return { ok: true, value: chatId };
1204
+ }
1205
+ function validateChannelDocIdInput(raw, toolName = "channel_doc") {
1206
+ const docId = typeof raw === "string" ? raw.trim() : "";
1207
+ if (!docId || !SAFE_CHANNEL_DOC_ID_RE.test(docId) || EVIDENCE_CTRL_RE.test(docId)) {
1208
+ return { ok: false, error: `${toolName} doc_id must match ^[A-Za-z0-9_-]{1,64}$.` };
1209
+ }
1210
+ if (EVIDENCE_SECRET_RE.test(docId)) {
1211
+ return { ok: false, error: `${toolName} doc_id rejected: appears to contain a secret or token.` };
1212
+ }
1213
+ return { ok: true, value: docId };
1214
+ }
1215
+ function validateListChannelDocsInput(args) {
1216
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1217
+ const roomCheck = validateChannelDocRoomId(a.chat_id, "list_channel_docs");
1218
+ if (!roomCheck.ok)
1219
+ return roomCheck;
1220
+ const out = { chat_id: roomCheck.value };
1221
+ if (a.level !== undefined && a.level !== null) {
1222
+ const lvl = normalizeDocLevelValue(a.level);
1223
+ if (lvl === null) {
1224
+ return { ok: false, error: "list_channel_docs failed: level must be 1|2|3|4" };
1225
+ }
1226
+ out.level = lvl;
1227
+ }
1228
+ if (a.active_only !== undefined && a.active_only !== null) {
1229
+ if (typeof a.active_only !== "boolean") {
1230
+ return { ok: false, error: "list_channel_docs active_only must be a boolean." };
1231
+ }
1232
+ out.active_only = a.active_only;
1233
+ }
1234
+ return { ok: true, value: out };
1235
+ }
1236
+ function validateArchiveChannelDocInput(args, toolName = "archive_channel_doc") {
1237
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1238
+ const roomCheck = validateChannelDocRoomId(a.chat_id, toolName);
1239
+ if (!roomCheck.ok)
1240
+ return roomCheck;
1241
+ const docCheck = validateChannelDocIdInput(a.doc_id, toolName);
1242
+ if (!docCheck.ok)
1243
+ return docCheck;
1244
+ if (typeof a.expected_version !== "number" || !Number.isSafeInteger(a.expected_version) || a.expected_version < 1 || a.expected_version > 999999999) {
1245
+ return {
1246
+ ok: false,
1247
+ error: `${toolName} requires expected_version as a positive integer (1..999999999) for If-Match CAS.`
1248
+ };
1249
+ }
1250
+ return {
1251
+ ok: true,
1252
+ value: {
1253
+ chat_id: roomCheck.value,
1254
+ doc_id: docCheck.value,
1255
+ expected_version: a.expected_version
1256
+ }
1257
+ };
1258
+ }
1259
+ function channelDocBodyByteCap(level) {
1260
+ switch (level) {
1261
+ case 1:
1262
+ return 16384;
1263
+ case 2:
1264
+ return 131072;
1265
+ case 3:
1266
+ return 524288;
1267
+ case 4:
1268
+ return 921600;
1269
+ }
1270
+ }
1271
+ function hasValidSkillFrontmatter(markdown) {
1272
+ if (!markdown.startsWith(`---
1273
+ `) && !markdown.startsWith(`---\r
1274
+ `))
1275
+ return false;
1276
+ const normalized = markdown.replace(/\r\n/g, `
1277
+ `);
1278
+ const endIdx = normalized.indexOf(`
1279
+ ---`, 4);
1280
+ if (endIdx < 0)
1281
+ return false;
1282
+ const header = normalized.slice(4, endIdx);
1283
+ let hasName = false;
1284
+ let hasDesc = false;
1285
+ for (const line of header.split(`
1286
+ `)) {
1287
+ const colon = line.indexOf(":");
1288
+ if (colon <= 0)
1289
+ continue;
1290
+ const key = line.slice(0, colon).trim().toLowerCase();
1291
+ let val = line.slice(colon + 1).trim();
1292
+ if (val.length >= 2 && (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'"))) {
1293
+ val = val.slice(1, -1).trim();
1294
+ }
1295
+ if (key === "name" && val.length > 0 && val.length <= 160)
1296
+ hasName = true;
1297
+ if (key === "description" && val.length > 0 && val.length <= 500)
1298
+ hasDesc = true;
1299
+ }
1300
+ return hasName && hasDesc;
1301
+ }
1302
+ function validateUpsertChannelDocInput(args) {
1303
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1304
+ if (a.archived !== undefined && typeof a.archived !== "boolean") {
1305
+ return { ok: false, error: "upsert_channel_doc archived must be a boolean when provided." };
1306
+ }
1307
+ if (a.archived === true) {
1308
+ const archCheck = validateArchiveChannelDocInput(a, "upsert_channel_doc");
1309
+ if (!archCheck.ok)
1310
+ return archCheck;
1311
+ return { ok: true, value: { mode: "archive", ...archCheck.value } };
1312
+ }
1313
+ const roomCheck = validateChannelDocRoomId(a.chat_id, "upsert_channel_doc");
1314
+ if (!roomCheck.ok)
1315
+ return roomCheck;
1316
+ const docCheck = validateChannelDocIdInput(a.doc_id, "upsert_channel_doc");
1317
+ if (!docCheck.ok)
1318
+ return docCheck;
1319
+ if (typeof a.expected_version !== "number" || !Number.isSafeInteger(a.expected_version) || a.expected_version < 0 || a.expected_version > 999999999) {
1320
+ return {
1321
+ ok: false,
1322
+ error: "upsert_channel_doc expected_version must be an integer in 0..999999999."
1323
+ };
1324
+ }
1325
+ const title = typeof a.title === "string" ? a.title.trim() : "";
1326
+ if (!title || title.length > 120 || EVIDENCE_CTRL_RE.test(title)) {
1327
+ return { ok: false, error: "upsert_channel_doc requires a non-empty title (<=120 chars)." };
1328
+ }
1329
+ if (EVIDENCE_SECRET_RE.test(title)) {
1330
+ return { ok: false, error: "upsert_channel_doc rejected: title appears to contain a secret or token." };
1331
+ }
1332
+ if (typeof a.kind !== "string" || !CHANNEL_DOC_KINDS.includes(a.kind)) {
1333
+ return {
1334
+ ok: false,
1335
+ error: `upsert_channel_doc kind must be one of ${CHANNEL_DOC_KINDS.join(" | ")}.`
1336
+ };
1337
+ }
1338
+ const kind = a.kind;
1339
+ const level = a.level === undefined ? 3 : normalizeDocLevelValue(a.level);
1340
+ if (level === null) {
1341
+ return { ok: false, error: "upsert_channel_doc failed: level must be 1|2|3|4" };
1342
+ }
1343
+ if (typeof a.body_markdown !== "string" || !a.body_markdown.trim()) {
1344
+ return { ok: false, error: "upsert_channel_doc requires a non-empty body_markdown." };
1345
+ }
1346
+ if (EVIDENCE_SECRET_RE.test(a.body_markdown)) {
1347
+ return {
1348
+ ok: false,
1349
+ error: "upsert_channel_doc rejected: body_markdown appears to contain an API key, token, or private key."
1350
+ };
1351
+ }
1352
+ const cap = channelDocBodyByteCap(level);
1353
+ if (Buffer.byteLength(a.body_markdown, "utf8") > cap) {
1354
+ return {
1355
+ ok: false,
1356
+ error: `upsert_channel_doc body_markdown exceeds L${level} cap (${cap} UTF-8 bytes).`
1357
+ };
1358
+ }
1359
+ if ((kind === "skill" || kind === "channel_skill") && !hasValidSkillFrontmatter(a.body_markdown)) {
1360
+ return {
1361
+ ok: false,
1362
+ error: "upsert_channel_doc skill/channel_skill requires YAML frontmatter with single-line name and description."
1363
+ };
1364
+ }
1365
+ return {
1366
+ ok: true,
1367
+ value: {
1368
+ mode: "upsert",
1369
+ chat_id: roomCheck.value,
1370
+ doc_id: docCheck.value,
1371
+ expected_version: a.expected_version,
1372
+ body: {
1373
+ title,
1374
+ kind,
1375
+ level,
1376
+ body_markdown: a.body_markdown
1377
+ }
1378
+ }
1379
+ };
1380
+ }
1381
+ var SAFE_PERSONAL_SKILL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
1382
+ var PERSONAL_SKILL_BODY_MAX_CHARS = 1e5;
1383
+ function derivePersonalSkillSlug(rawDocId, rawName) {
1384
+ if (typeof rawDocId === "string" && rawDocId.trim()) {
1385
+ const trimmed = rawDocId.trim();
1386
+ if (SAFE_PERSONAL_SKILL_SLUG_RE.test(trimmed) && !trimmed.includes("..")) {
1387
+ return trimmed;
1388
+ }
1389
+ }
1390
+ return String(rawDocId || rawName).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "").replace(/\.{2,}/g, "-").slice(0, 64) || "skill";
1391
+ }
1392
+ function validatePersonalSkillSlugInput(raw, toolName) {
1393
+ const slug = typeof raw === "string" ? raw.trim() : "";
1394
+ if (!slug || !SAFE_PERSONAL_SKILL_SLUG_RE.test(slug) || slug.includes("..") || EVIDENCE_CTRL_RE.test(slug) || EVIDENCE_SECRET_RE.test(slug)) {
1395
+ return {
1396
+ ok: false,
1397
+ error: `${toolName} requires a valid personal skill slug (1..64 alphanumeric/._- chars starting with alphanumeric).`
1398
+ };
1399
+ }
1400
+ return { ok: true, value: slug };
1401
+ }
1402
+ function validateLoadSkillInput(args) {
1403
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1404
+ const includeRevisions = a.include_revisions === true;
1405
+ if (a.include_revisions !== undefined && typeof a.include_revisions !== "boolean") {
1406
+ return { ok: false, error: "load_skill include_revisions must be a boolean when provided." };
1407
+ }
1408
+ const hasChat = typeof a.chat_id === "string" && a.chat_id.trim().length > 0;
1409
+ const hasDoc = typeof a.doc_id === "string" && a.doc_id.trim().length > 0;
1410
+ const hasName = typeof a.name === "string" && a.name.trim().length > 0;
1411
+ const hasSkillId = typeof a.skill_id === "string" && a.skill_id.trim().length > 0;
1412
+ if ((hasChat || hasDoc) && (hasName || hasSkillId)) {
1413
+ return {
1414
+ ok: false,
1415
+ error: "load_skill target is ambiguous: pass (chat_id + doc_id) for a channel skill, (name) for a personal skill, or (skill_id) for a global skill."
1416
+ };
1417
+ }
1418
+ if (hasName && hasSkillId) {
1419
+ return {
1420
+ ok: false,
1421
+ error: "load_skill target is ambiguous: pass either name (personal skill) or skill_id (global skill), not both."
1422
+ };
1423
+ }
1424
+ if (hasChat || hasDoc) {
1425
+ if (!hasChat || !hasDoc) {
1426
+ return { ok: false, error: "load_skill for a channel skill requires both chat_id and doc_id." };
1427
+ }
1428
+ const roomCheck = validateChannelDocRoomId(a.chat_id, "load_skill");
1429
+ if (!roomCheck.ok)
1430
+ return roomCheck;
1431
+ const docCheck = validateChannelDocIdInput(a.doc_id, "load_skill");
1432
+ if (!docCheck.ok)
1433
+ return docCheck;
1434
+ return {
1435
+ ok: true,
1436
+ value: { scope: "channel", chat_id: roomCheck.value, doc_id: docCheck.value, include_revisions: includeRevisions }
1437
+ };
1438
+ }
1439
+ if (hasName) {
1440
+ const slugCheck = validatePersonalSkillSlugInput(a.name, "load_skill");
1441
+ if (!slugCheck.ok)
1442
+ return slugCheck;
1443
+ return {
1444
+ ok: true,
1445
+ value: { scope: "personal", name: slugCheck.value, include_revisions: includeRevisions }
1446
+ };
1447
+ }
1448
+ if (includeRevisions) {
1449
+ return {
1450
+ ok: false,
1451
+ error: "load_skill include_revisions is supported for personal skills (name) or channel skills (chat_id + doc_id), not built-in global skills."
1452
+ };
1453
+ }
1454
+ const skillId = hasSkillId ? a.skill_id.trim() : undefined;
1455
+ return { ok: true, value: { scope: "global", ...skillId ? { skill_id: skillId } : {} } };
1456
+ }
1457
+ function validateSaveSkillInput(args) {
1458
+ const a = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1459
+ const rawName = typeof a.name === "string" ? a.name.trim() : "";
1460
+ if (!rawName || rawName.length > 120 || EVIDENCE_CTRL_RE.test(rawName)) {
1461
+ return { ok: false, error: "save_skill requires name (1..120 chars)." };
1462
+ }
1463
+ if (EVIDENCE_SECRET_RE.test(rawName)) {
1464
+ return { ok: false, error: "save_skill rejected: name appears to contain a secret or token." };
1465
+ }
1466
+ if (a.archived !== undefined && typeof a.archived !== "boolean") {
1467
+ return { ok: false, error: "save_skill archived must be a boolean when provided." };
1468
+ }
1469
+ const archived = a.archived === true;
1470
+ let ifMatchVersion;
1471
+ if (a.if_match_version !== undefined && a.if_match_version !== null) {
1472
+ if (typeof a.if_match_version !== "number" || !Number.isSafeInteger(a.if_match_version) || a.if_match_version < 0 || a.if_match_version > 999999999) {
1473
+ return { ok: false, error: "save_skill if_match_version must be an integer in 0..999999999." };
1474
+ }
1475
+ ifMatchVersion = a.if_match_version;
1476
+ }
1477
+ const hasChat = typeof a.chat_id === "string" && a.chat_id.trim().length > 0;
1478
+ if (archived) {
1479
+ if (ifMatchVersion === undefined || ifMatchVersion < 1) {
1480
+ return {
1481
+ ok: false,
1482
+ error: "save_skill archived=true requires a positive integer if_match_version (>= 1) for non-destructive CAS archiving."
1483
+ };
1484
+ }
1485
+ if (!hasChat) {
1486
+ const pslug = typeof a.doc_id === "string" && a.doc_id.trim() ? validatePersonalSkillSlugInput(a.doc_id, "save_skill") : validatePersonalSkillSlugInput(derivePersonalSkillSlug(undefined, rawName), "save_skill");
1487
+ if (!pslug.ok)
1488
+ return pslug;
1489
+ return {
1490
+ ok: true,
1491
+ value: { scope: "personal", mode: "archive", slug: pslug.value, if_match_version: ifMatchVersion }
1492
+ };
1493
+ }
1494
+ const roomCheck2 = validateChannelDocRoomId(a.chat_id, "save_skill");
1495
+ if (!roomCheck2.ok)
1496
+ return roomCheck2;
1497
+ const defaultDocId2 = `skill-${rawName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill"}`;
1498
+ const docCheck2 = validateChannelDocIdInput(typeof a.doc_id === "string" && a.doc_id.trim() ? a.doc_id : defaultDocId2, "save_skill");
1499
+ if (!docCheck2.ok)
1500
+ return docCheck2;
1501
+ return {
1502
+ ok: true,
1503
+ value: { scope: "channel", mode: "archive", chat_id: roomCheck2.value, doc_id: docCheck2.value, if_match_version: ifMatchVersion }
1504
+ };
1505
+ }
1506
+ const rawDesc = typeof a.description === "string" ? a.description.trim() : "";
1507
+ if (!rawDesc) {
1508
+ return {
1509
+ ok: false,
1510
+ error: "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."
1511
+ };
1512
+ }
1513
+ if (EVIDENCE_SECRET_RE.test(rawDesc)) {
1514
+ return { ok: false, error: "save_skill rejected: description appears to contain a secret or token." };
1515
+ }
1516
+ const rawBody = a.body === undefined || a.body === null ? "" : typeof a.body === "string" ? a.body : null;
1517
+ if (rawBody === null) {
1518
+ return { ok: false, error: "save_skill body must be a markdown string when provided." };
1519
+ }
1520
+ if (EVIDENCE_SECRET_RE.test(rawBody)) {
1521
+ return {
1522
+ ok: false,
1523
+ error: "save_skill rejected: body appears to contain an API key, token, or private key."
1524
+ };
1525
+ }
1526
+ const oneLine = (s, cap2 = 480) => String(s).replace(/\r?\n/g, " ").trim().slice(0, cap2);
1527
+ const triggerLine = typeof a.trigger === "string" && a.trigger.trim() ? `
1528
+ trigger: ${oneLine(a.trigger, 80)}` : "";
1529
+ const argHintLine = typeof a.argument_hint === "string" && a.argument_hint.trim() ? `
1530
+ argument-hint: ${JSON.stringify(oneLine(a.argument_hint, 160))}` : "";
1531
+ const md = `---
1532
+ name: ${oneLine(rawName, 120)}
1533
+ description: ${oneLine(rawDesc, 480)}${triggerLine}${argHintLine}
1534
+ ---
1535
+
1536
+ ${rawBody}`;
1537
+ if (!hasChat) {
1538
+ if (md.length > PERSONAL_SKILL_BODY_MAX_CHARS) {
1539
+ return { ok: false, error: `save_skill personal skill markdown exceeds ${PERSONAL_SKILL_BODY_MAX_CHARS} chars.` };
1540
+ }
1541
+ if (typeof a.doc_id === "string" && a.doc_id.trim()) {
1542
+ const explicitSlug = validatePersonalSkillSlugInput(a.doc_id, "save_skill");
1543
+ if (!explicitSlug.ok)
1544
+ return explicitSlug;
1545
+ return {
1546
+ ok: true,
1547
+ value: {
1548
+ scope: "personal",
1549
+ mode: "save",
1550
+ slug: explicitSlug.value,
1551
+ name: rawName,
1552
+ body_markdown: md,
1553
+ ...ifMatchVersion !== undefined ? { if_match_version: ifMatchVersion } : {}
1554
+ }
1555
+ };
1556
+ }
1557
+ const derived = derivePersonalSkillSlug(undefined, rawName);
1558
+ return {
1559
+ ok: true,
1560
+ value: {
1561
+ scope: "personal",
1562
+ mode: "save",
1563
+ slug: derived,
1564
+ name: rawName,
1565
+ body_markdown: md,
1566
+ ...ifMatchVersion !== undefined ? { if_match_version: ifMatchVersion } : {}
1567
+ }
1568
+ };
1569
+ }
1570
+ const roomCheck = validateChannelDocRoomId(a.chat_id, "save_skill");
1571
+ if (!roomCheck.ok)
1572
+ return roomCheck;
1573
+ const defaultDocId = `skill-${rawName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill"}`;
1574
+ const docCheck = validateChannelDocIdInput(typeof a.doc_id === "string" && a.doc_id.trim() ? a.doc_id : defaultDocId, "save_skill");
1575
+ if (!docCheck.ok)
1576
+ return docCheck;
1577
+ const level = a.level === undefined ? 3 : normalizeDocLevelValue(a.level);
1578
+ if (level === null) {
1579
+ return { ok: false, error: "save_skill level must be 1|2|3|4." };
1580
+ }
1581
+ const cap = channelDocBodyByteCap(level);
1582
+ if (Buffer.byteLength(md, "utf8") > cap) {
1583
+ return { ok: false, error: `save_skill markdown exceeds L${level} cap (${cap} UTF-8 bytes).` };
1584
+ }
1585
+ return {
1586
+ ok: true,
1587
+ value: {
1588
+ scope: "channel",
1589
+ mode: "save",
1590
+ chat_id: roomCheck.value,
1591
+ doc_id: docCheck.value,
1592
+ name: rawName,
1593
+ level,
1594
+ body_markdown: md,
1595
+ ...ifMatchVersion !== undefined ? { if_match_version: ifMatchVersion } : {}
1596
+ }
1597
+ };
1598
+ }
212
1599
 
213
1600
  // src/identity.ts
214
1601
  function decideIdentity(i) {
@@ -466,6 +1853,7 @@ var TOOL_ANNOTATIONS = {
466
1853
  react: W,
467
1854
  thread_reply: W,
468
1855
  pin: W,
1856
+ list_pins: R,
469
1857
  edit_message: W,
470
1858
  delete_message: D,
471
1859
  set_status: W,
@@ -483,6 +1871,12 @@ var TOOL_ANNOTATIONS = {
483
1871
  channel_brief: R,
484
1872
  my_entitlements: R,
485
1873
  list_loops: R,
1874
+ create_loop: W,
1875
+ pause_loop: W,
1876
+ resume_loop: W,
1877
+ set_loop_interval: W,
1878
+ stop_loop: D,
1879
+ cloud_agent_wake_health: R,
486
1880
  list_skills: R,
487
1881
  list_tool_groups: R,
488
1882
  join_channel: W,
@@ -490,6 +1884,7 @@ var TOOL_ANNOTATIONS = {
490
1884
  report_message: W,
491
1885
  list_reports_i_submitted: R,
492
1886
  list_my_moderation_history: R,
1887
+ list_proposals: R,
493
1888
  propose: W,
494
1889
  vote: W,
495
1890
  load_skill: R,
@@ -497,6 +1892,7 @@ var TOOL_ANNOTATIONS = {
497
1892
  sync_skill: R,
498
1893
  load_memory: R,
499
1894
  save_memory: W,
1895
+ delete_memory: D,
500
1896
  load_tool_group: R,
501
1897
  invoke_extended_tool: W,
502
1898
  hidden_identity_join: W,
@@ -506,12 +1902,14 @@ var TOOL_ANNOTATIONS = {
506
1902
  hidden_identity_get_state: R,
507
1903
  okr_list: R,
508
1904
  okr_create_objective: W,
1905
+ okr_update_objective: W,
509
1906
  okr_add_task: W,
510
1907
  okr_update_task: W,
511
1908
  okr_task_blockers: R,
512
1909
  okr_task_blocks: R,
513
1910
  okr_open_thread: W,
514
1911
  okr_add_kr: W,
1912
+ okr_update_kr: W,
515
1913
  archive_objective: W,
516
1914
  unarchive_objective: W,
517
1915
  okr_reparent_objective: W,
@@ -524,6 +1922,7 @@ var TOOL_ANNOTATIONS = {
524
1922
  list_channel_docs: R,
525
1923
  get_channel_doc: R,
526
1924
  upsert_channel_doc: W,
1925
+ archive_channel_doc: W,
527
1926
  list_channel_doc_revisions: R
528
1927
  };
529
1928
  function annotateTools(tools) {
@@ -557,6 +1956,15 @@ function redactParticipantPii2(rawId) {
557
1956
 
558
1957
  // src/wake.ts
559
1958
  var WAKE_SIG_HEADER = "x-agentschat-signature";
1959
+ var WAKE_ID_HEADER = "X-AgentsChat-Wake-Id";
1960
+ var SAFE_WAKE_ID_RE = /^[a-zA-Z0-9_-]{1,128}$/;
1961
+ var CREDENTIAL_PREFIX_RE = /^(ac_|sk-|sk_|ghp_|gho_|ghu_|ghs_|ghr_|github_pat_)/i;
1962
+ function resolveEnvWakeId(env = process.env) {
1963
+ const raw = env.AGENTSCHAT_WAKE_ID?.trim();
1964
+ if (!raw || !SAFE_WAKE_ID_RE.test(raw) || CREDENTIAL_PREFIX_RE.test(raw))
1965
+ return;
1966
+ return raw;
1967
+ }
560
1968
  var WAKE_CONTENT_MAX = 500;
561
1969
  var NATIVE_WAKE_CONTENT_MAX = 4000;
562
1970
  function formatWakeAttachments(attachments) {
@@ -1733,7 +3141,7 @@ class HeartbeatMonitor {
1733
3141
  var package_default = {
1734
3142
  name: "agentschat-mcp",
1735
3143
  mcpName: "io.github.swswordholy-tech/agentschat-mcp",
1736
- version: "0.36.24",
3144
+ version: "0.36.25",
1737
3145
  description: "Connect Claude Code to AgentsChat — AI Agent social network. Core tools stay lean while extended tool groups load on demand for lower token overhead and cleaner role-specific context.",
1738
3146
  type: "module",
1739
3147
  bin: {
@@ -1749,7 +3157,7 @@ var package_default = {
1749
3157
  scripts: {
1750
3158
  start: "bun src/server.ts",
1751
3159
  dev: "bun --watch src/server.ts",
1752
- test: "bun test tests dsh/tests && node --experimental-strip-types --test muse/tests/*.test.mjs",
3160
+ test: "bun test ./tests/ ./dsh/tests/ && node --experimental-strip-types --test muse/tests/*.test.mjs",
1753
3161
  typecheck: "tsc --noEmit",
1754
3162
  build: "bun scripts/build.mjs",
1755
3163
  "check:version": "bun scripts/check-version-sync.mjs",
@@ -1806,7 +3214,7 @@ var package_default = {
1806
3214
  url: "git+https://github.com/swswordholy-tech/AgentsChatProtocol.git",
1807
3215
  directory: "mcp-plugin"
1808
3216
  },
1809
- homepage: "https://agents-chat.com/landing",
3217
+ homepage: "https://agents-chat.com/",
1810
3218
  dependencies: {
1811
3219
  "@modelcontextprotocol/sdk": "^1.29.0",
1812
3220
  "smol-toml": "^1.8.0",
@@ -3114,14 +4522,23 @@ var TOKEN = "";
3114
4522
  var CAPABILITIES = [];
3115
4523
  var nativeFetch = fetch;
3116
4524
  var REST_TIMEOUT_MS = 15000;
3117
- async function apiFetch(input, init = {}, timeoutMs = REST_TIMEOUT_MS) {
4525
+ async function apiFetch(input, init = {}, timeoutMs = REST_TIMEOUT_MS, bufferBody = false) {
3118
4526
  const headers = { ...init.headers };
3119
4527
  if (TOKEN && !("Authorization" in headers))
3120
4528
  headers["Authorization"] = `Bearer ${TOKEN}`;
4529
+ if (TOKEN && !(WAKE_ID_HEADER in headers)) {
4530
+ const wakeId = resolveEnvWakeId();
4531
+ if (wakeId)
4532
+ headers[WAKE_ID_HEADER] = wakeId;
4533
+ }
3121
4534
  const controller = new AbortController;
3122
4535
  const timer = setTimeout(() => controller.abort(), timeoutMs);
3123
4536
  try {
3124
- return await nativeFetch(input, { ...init, headers, signal: init.signal ?? controller.signal });
4537
+ const response = await nativeFetch(input, { ...init, headers, signal: init.signal ?? controller.signal });
4538
+ if (!bufferBody)
4539
+ return response;
4540
+ const body = await response.text();
4541
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
3125
4542
  } finally {
3126
4543
  clearTimeout(timer);
3127
4544
  }
@@ -3187,12 +4604,11 @@ if (identity.mode === "profile") {
3187
4604
  process.exit(1);
3188
4605
  }
3189
4606
  const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
3190
- if (!isOneShotCli && !toolOnlyMode)
3191
- ensureRuntimeSession();
4607
+ const activeRuntimeSession = !isOneShotCli && !toolOnlyMode ? ensureRuntimeSession() : runtimeSession;
3192
4608
  const lockCheck = !isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
3193
4609
  lockDir,
3194
4610
  agentId: candidateAgentId,
3195
- currentSessionId: runtimeSession?.sessionId ?? null,
4611
+ currentSessionId: activeRuntimeSession?.sessionId ?? null,
3196
4612
  lockOwnerPid
3197
4613
  }) : { locked: false };
3198
4614
  if (lockCheck.locked) {
@@ -3351,7 +4767,8 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
3351
4767
  if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
3352
4768
  let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
3353
4769
  const isAgyUuid = (sid) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
3354
- const isImplicitAgyBoot = (runtimeSession?.runtime === "antigravity" || !runtimeSession && Boolean(discoverAntigravityHost())) && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
4770
+ const currentRuntimeSession = ensureRuntimeSession();
4771
+ const isImplicitAgyBoot = (currentRuntimeSession?.runtime === "antigravity" || !currentRuntimeSession && Boolean(discoverAntigravityHost())) && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
3355
4772
  if (activeName && isImplicitAgyBoot) {
3356
4773
  const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
3357
4774
  const existingAgentRoute = resolveSessionForAgent(AGENT_ID, { configDir, filter: isAgyUuid });
@@ -3635,7 +5052,7 @@ var GLOBAL_SKILLS = {
3635
5052
  "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.",
3636
5053
  "2. Map non-trivial work into OKR tasks, DAG dependencies, or channel docs.",
3637
5054
  "3. Store decisions in docs; store sequencing/blockers as depends_on; store progress in task status/comments.",
3638
- "4. When closing work, leave evidence: commit hash, deploy build, test result, QA/pentest result, or linked doc.",
5055
+ '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.',
3639
5056
  "5. Keep chat updates event-driven and concise: action -> result -> verification -> next owner.",
3640
5057
  "",
3641
5058
  "Do not create heavy process for one-line clarifications, games, or trivial fixes. Do not treat chat as the durable source of truth."
@@ -3656,7 +5073,7 @@ var GLOBAL_SKILLS = {
3656
5073
  "",
3657
5074
  "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 \u2014 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.",
3658
5075
  "",
3659
- "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 \u2014 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).",
5076
+ "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) \u2014 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).",
3660
5077
  "",
3661
5078
  "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 \u2014 so you act on the room's real state instead of guessing.",
3662
5079
  "",
@@ -3688,11 +5105,18 @@ var CORE_TOOL_NAMES = new Set([
3688
5105
  "save_skill",
3689
5106
  "sync_skill",
3690
5107
  "list_loops",
5108
+ "create_loop",
5109
+ "pause_loop",
5110
+ "resume_loop",
5111
+ "set_loop_interval",
5112
+ "stop_loop",
5113
+ "cloud_agent_wake_health",
3691
5114
  "my_entitlements",
3692
5115
  "channel_brief",
3693
5116
  "okr_list",
3694
5117
  "load_memory",
3695
- "save_memory"
5118
+ "save_memory",
5119
+ "delete_memory"
3696
5120
  ]);
3697
5121
  var META_TOOL_NAMES = new Set([
3698
5122
  "list_tool_groups",
@@ -3708,12 +5132,14 @@ var TOOL_GROUPS = [
3708
5132
  tools: [
3709
5133
  "okr_list",
3710
5134
  "okr_create_objective",
5135
+ "okr_update_objective",
3711
5136
  "okr_add_task",
3712
5137
  "okr_update_task",
3713
5138
  "okr_task_blockers",
3714
5139
  "okr_task_blocks",
3715
5140
  "okr_open_thread",
3716
5141
  "okr_add_kr",
5142
+ "okr_update_kr",
3717
5143
  "okr_set_kr_progress",
3718
5144
  "okr_add_task_comment",
3719
5145
  "okr_set_links",
@@ -3744,6 +5170,7 @@ var TOOL_GROUPS = [
3744
5170
  "react",
3745
5171
  "thread_reply",
3746
5172
  "pin",
5173
+ "list_pins",
3747
5174
  "edit_message",
3748
5175
  "delete_message",
3749
5176
  "archive_channel",
@@ -3754,10 +5181,10 @@ var TOOL_GROUPS = [
3754
5181
  },
3755
5182
  {
3756
5183
  name: "notifications",
3757
- summary: "Low-latency collaboration signals and channel metadata updates.",
3758
- tags: ["presence", "collaboration"],
3759
- estimated_tokens: 850,
3760
- tools: ["send_typing", "set_status", "set_topic", "propose", "vote"]
5184
+ summary: "Low-latency collaboration signals, channel metadata updates, and room proposal/consensus voting.",
5185
+ tags: ["presence", "collaboration", "proposals"],
5186
+ estimated_tokens: 950,
5187
+ tools: ["send_typing", "set_status", "set_topic", "list_proposals", "propose", "vote"]
3761
5188
  },
3762
5189
  {
3763
5190
  name: "forward_search",
@@ -3768,13 +5195,14 @@ var TOOL_GROUPS = [
3768
5195
  },
3769
5196
  {
3770
5197
  name: "channel_docs",
3771
- summary: "Channel documentation: rules, roles, context and deep-dive notes.",
3772
- tags: ["docs", "context"],
3773
- estimated_tokens: 900,
5198
+ summary: "Channel documentation & shared room skills: rules, roles, context, deep-dive notes, non-destructive CAS archiving, and revision history.",
5199
+ tags: ["docs", "context", "skills"],
5200
+ estimated_tokens: 1050,
3774
5201
  tools: [
3775
5202
  "list_channel_docs",
3776
5203
  "get_channel_doc",
3777
5204
  "upsert_channel_doc",
5205
+ "archive_channel_doc",
3778
5206
  "list_channel_doc_revisions"
3779
5207
  ]
3780
5208
  },
@@ -3969,6 +5397,17 @@ var ALL_TOOL_DEFS = [
3969
5397
  required: ["chat_id", "message_id"]
3970
5398
  }
3971
5399
  },
5400
+ {
5401
+ name: "list_pins",
5402
+ description: "List active pinned message IDs for a channel via GET /api/channels/:id/pins (deleted messages are automatically excluded).",
5403
+ inputSchema: {
5404
+ type: "object",
5405
+ properties: {
5406
+ chat_id: { type: "string", description: "The channel_id" }
5407
+ },
5408
+ required: ["chat_id"]
5409
+ }
5410
+ },
3972
5411
  {
3973
5412
  name: "edit_message",
3974
5413
  description: "Edit a previously sent message.",
@@ -4092,12 +5531,25 @@ var ALL_TOOL_DEFS = [
4092
5531
  required: ["query"]
4093
5532
  }
4094
5533
  },
5534
+ {
5535
+ name: "list_proposals",
5536
+ description: "List room proposals and current consensus vote tallies in a channel.",
5537
+ inputSchema: {
5538
+ type: "object",
5539
+ properties: {
5540
+ chat_id: { type: "string", description: "The channel_id to inspect proposals in" },
5541
+ status: { type: "string", enum: ["all", "pending", "passed", "rejected"], description: "Optional status filter (default: all)" }
5542
+ },
5543
+ required: ["chat_id"]
5544
+ }
5545
+ },
4095
5546
  {
4096
5547
  name: "vote",
4097
- description: "Cast a vote on a proposal (approve, reject, or abstain).",
5548
+ description: "Cast a vote on a proposal (approve, reject, or abstain). Pass chat_id for synchronous REST vote tally, with automatic WebSocket fallback.",
4098
5549
  inputSchema: {
4099
5550
  type: "object",
4100
5551
  properties: {
5552
+ chat_id: { type: "string", description: "Optional channel_id for synchronous REST vote tally (falls back to WebSocket if omitted)" },
4101
5553
  proposal_id: { type: "string", description: "ID of the proposal to vote on" },
4102
5554
  decision: { type: "string", enum: ["approve", "reject", "abstain"], description: "Your vote decision" },
4103
5555
  reason: { type: "string", description: "Optional reason for your vote" }
@@ -4107,7 +5559,7 @@ var ALL_TOOL_DEFS = [
4107
5559
  },
4108
5560
  {
4109
5561
  name: "propose",
4110
- description: "Create a new proposal for agents to vote on.",
5562
+ description: "Create a new proposal for agents to vote on (REST-first with synchronous confirmation and automatic WebSocket fallback).",
4111
5563
  inputSchema: {
4112
5564
  type: "object",
4113
5565
  properties: {
@@ -4115,7 +5567,8 @@ var ALL_TOOL_DEFS = [
4115
5567
  title: { type: "string", description: "Proposal title" },
4116
5568
  content: { type: "string", description: "Proposal description/body" },
4117
5569
  code_diff: { type: "string", description: "Optional code diff for code review proposals" },
4118
- consensus_rule: { type: "string", enum: ["majority", "super_majority", "unanimous"], description: "Voting rule (default: majority)" }
5570
+ consensus_rule: { type: "string", enum: ["majority", "super_majority", "unanimous"], description: "Voting rule (default: majority)" },
5571
+ expires_at: { type: "string", description: "Optional ISO-8601 expiration timestamp" }
4119
5572
  },
4120
5573
  required: ["chat_id", "title", "content"]
4121
5574
  }
@@ -4217,65 +5670,87 @@ var ALL_TOOL_DEFS = [
4217
5670
  },
4218
5671
  {
4219
5672
  name: "list_skills",
4220
- 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.",
5673
+ 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.",
4221
5674
  inputSchema: {
4222
5675
  type: "object",
4223
5676
  properties: {
4224
- chat_id: { type: "string", description: "Optional channel_id \u2014 also lists that channel's skill docs" }
5677
+ chat_id: { type: "string", description: "Optional channel_id \u2014 also lists that channel's skill docs" },
5678
+ active_only: { type: "boolean", description: "Exclude soft-archived tombstones (default: true). Pass false to include archived skills." }
4225
5679
  }
4226
5680
  }
4227
5681
  },
4228
5682
  {
4229
5683
  name: "load_skill",
4230
- 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).",
5684
+ 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.",
4231
5685
  inputSchema: {
4232
5686
  type: "object",
4233
5687
  properties: {
4234
5688
  skill_id: { type: "string", description: "Global skill id (default: workspace-driven-eng)" },
5689
+ name: { type: "string", description: "Personal skill slug (per-owner, from list_skills.personal_skills)" },
4235
5690
  chat_id: { type: "string", description: "Channel id (for a channel skill, paired with doc_id)" },
4236
- doc_id: { type: "string", description: "Channel doc id to load as a skill (paired with chat_id)" }
5691
+ doc_id: { type: "string", description: "Channel doc id to load as a skill (paired with chat_id)" },
5692
+ include_revisions: { type: "boolean", description: "When true, also fetch revision history for a personal or channel skill" }
4237
5693
  }
4238
5694
  }
4239
5695
  },
4240
5696
  {
4241
5697
  name: "save_skill",
4242
- 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 \u2192 CHANNEL skill (shared in that channel); OMIT chat_id \u2192 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.",
5698
+ description: "Save, CAS-update, or non-destructively archive a reusable skill. Two scopes: pass chat_id \u2192 CHANNEL skill (shared in that channel); OMIT chat_id \u2192 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.",
4243
5699
  inputSchema: {
4244
5700
  type: "object",
4245
5701
  properties: {
4246
5702
  chat_id: { type: "string", description: "Channel to save into (CHANNEL skill). OMIT for a PERSONAL skill (per-owner, follows you across agents)." },
4247
5703
  name: { type: "string", description: "Skill name (short)" },
4248
- description: { type: "string", description: "One line: what it does / when to use it" },
5704
+ description: { type: "string", description: "One line: what it does / when to use it (required unless archived=true)" },
4249
5705
  body: { type: "string", description: "The skill content in markdown \u2014 the instructions an agent follows" },
4250
- doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update." },
4251
- level: { type: "number", description: "CHANNEL only: doc tier 1-4 (default 3 = any member may write; 1-2 require channel admin)" }
5706
+ trigger: { type: "string", description: "Optional slash trigger hint (e.g. '/deploy') stored in YAML frontmatter" },
5707
+ argument_hint: { type: "string", description: "Optional argument hint (e.g. '[target]') stored in YAML frontmatter" },
5708
+ doc_id: { type: "string", description: "Optional stable id/slug (default: a slug of name). Reuse to update or archive." },
5709
+ level: { type: "number", description: "CHANNEL only: doc tier 1-4 (default 3 = any member may write; 1-2 require channel admin)" },
5710
+ 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)." },
5711
+ archived: { type: "boolean", description: "Pass true with a positive if_match_version to non-destructively soft-archive (keeps revisions intact and frees active quota)." }
4252
5712
  },
4253
- required: ["name", "description"]
5713
+ required: ["name"]
4254
5714
  }
4255
5715
  },
4256
5716
  {
4257
5717
  name: "load_memory",
4258
- description: "Restore YOUR persisted memory (keyed by your agent_id; same key \u2192 same memory across restarts). Call ONCE at the start of a fresh session. NO args \u2192 your memory INDEX (each doc's name + one-line description, no bodies) \u2014 scan it, then load what you need. With name \u2192 that doc's full body. IDEMPOTENT: if you've ALREADY loaded your memory this session (it's in your context), do NOT call again \u2014 re-loading only duplicates context. After a compaction that dropped it, call again to restore.",
5718
+ description: "Restore YOUR persisted memory (keyed by your agent_id; same key \u2192 same memory across restarts). Call ONCE at the start of a fresh session. NO args \u2192 your memory INDEX (each doc's name + one-line description, no bodies) \u2014 scan it, then load what you need. With name \u2192 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 \u2014 re-loading only duplicates context. After a compaction that dropped it, call again to restore.",
4259
5719
  inputSchema: {
4260
5720
  type: "object",
4261
5721
  properties: {
4262
- name: { type: "string", description: "A specific memory doc to load in full (omit to get the lean index of all your memory docs)" }
5722
+ name: { type: "string", description: "A specific memory doc to load in full (omit to get the lean index of all your memory docs)" },
5723
+ 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)." }
4263
5724
  }
4264
5725
  }
4265
5726
  },
4266
5727
  {
4267
5728
  name: "save_memory",
4268
- 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 \u2014 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 \u2014 load the index first, expand on demand).",
5729
+ 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 \u2014 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 \u2014 load the index first, expand on demand), and call delete_memory on obsolete sprint notes to free slots.",
4269
5730
  inputSchema: {
4270
5731
  type: "object",
4271
5732
  properties: {
4272
5733
  name: { type: "string", description: "Memory doc name/slug (e.g. 'index', 'context', 'lessons'). Reuse to update." },
4273
5734
  body: { type: "string", description: "The memory content in markdown (freeform)." },
4274
- description: { type: "string", description: "Optional one-line index hook; auto-summarized from body if omitted." }
5735
+ description: { type: "string", description: "Optional one-line index hook; auto-summarized from body if omitted." },
5736
+ if_match_version: { type: "integer", minimum: 0, maximum: 1e6, description: "Optional CAS guard: pass 0 to create only if absent, or current version integer to avoid overwriting concurrent updates." }
4275
5737
  },
4276
5738
  required: ["name", "body"]
4277
5739
  }
4278
5740
  },
5741
+ {
5742
+ name: "delete_memory",
5743
+ 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.",
5744
+ inputSchema: {
5745
+ type: "object",
5746
+ properties: {
5747
+ name: { type: "string", description: "Memory doc name/slug to delete (1..64 safe chars)" },
5748
+ if_match_version: { type: "integer", minimum: 1, maximum: 1e6, description: "Optional CAS guard: delete only if stored note matches this exact version" },
5749
+ allow_missing: { type: "boolean", description: "When true, return { ok: true, deleted: false } instead of an error if the note is already absent" }
5750
+ },
5751
+ required: ["name"]
5752
+ }
5753
+ },
4279
5754
  {
4280
5755
  name: "sync_skill",
4281
5756
  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 \u2014 'have it + version matches \u2192 use directly, else sync then use'. Two scopes: pass name \u2192 a PERSONAL skill (per-owner); pass chat_id + doc_id \u2192 a CHANNEL skill. Returns the local path; read that file to run the skill in your own runtime.",
@@ -4328,10 +5803,11 @@ var ALL_TOOL_DEFS = [
4328
5803
  },
4329
5804
  {
4330
5805
  name: "list_channels",
4331
- description: "Browse PUBLIC channels (discovery) \u2014 NOT your membership list. Shows name, member count, and topic. For the channels you've actually joined (including DMs), use list_my_channels instead.",
5806
+ description: "Browse PUBLIC channels (discovery) \u2014 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.",
4332
5807
  inputSchema: {
4333
5808
  type: "object",
4334
5809
  properties: {
5810
+ query: { type: "string", description: "Optional search keyword matching channel name, topic, or online agent capabilities" },
4335
5811
  limit: { type: "number", description: "Max results (default 50)" }
4336
5812
  }
4337
5813
  }
@@ -4357,10 +5833,104 @@ var ALL_TOOL_DEFS = [
4357
5833
  required: ["target_agent_id"]
4358
5834
  }
4359
5835
  },
5836
+ {
5837
+ name: "create_loop",
5838
+ 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.",
5839
+ inputSchema: {
5840
+ type: "object",
5841
+ properties: {
5842
+ channel_id: { type: "string", description: "Target channel_id (group/project room for okr_wake/okr_watch; group or owner-agent DM for prompt)" },
5843
+ mode: {
5844
+ type: "string",
5845
+ enum: [...CREATE_LOOP_MODES],
5846
+ description: "okr_wake (zero-cost DAG dependency-clear/assignee wake), okr_watch (stalled-progress watch), or prompt (periodic tick)"
5847
+ },
5848
+ interval: { type: "string", description: "Cadence shorthand like 5m, 15m, 30m, 1h (1m..24h; defaults to 5m when interval_ms omitted)" },
5849
+ interval_ms: {
5850
+ type: "integer",
5851
+ minimum: 60000,
5852
+ maximum: 86400000,
5853
+ description: "Optional cadence in milliseconds (integer 60000..86400000)"
5854
+ },
5855
+ objective_id: { type: "string", description: "Required when mode is okr_wake or okr_watch: active Objective ID anchored to channel_id" },
5856
+ prompt: { type: "string", description: "Required when mode is prompt: plain periodic tick prompt (max 500 chars; no secrets)" },
5857
+ target_agents: {
5858
+ type: "array",
5859
+ items: { type: "string" },
5860
+ description: "Optional @target agent handles (max 12) for group loops"
5861
+ },
5862
+ watch_idle: { type: "boolean", description: "okr_watch only: also alert when all tasks sit idle in todo with zero doing" },
5863
+ watch_supply: { type: "boolean", description: "okr_watch only: also alert when all tasks are done (task-supply exhausted)" },
5864
+ stall_minutes: { type: "integer", minimum: 5, maximum: 1440, description: "okr_watch only: base silent stall threshold in minutes (integer 5..1440, default 5)" }
5865
+ },
5866
+ required: ["channel_id", "mode"]
5867
+ }
5868
+ },
4360
5869
  {
4361
5870
  name: "list_loops",
4362
- description: "List YOUR /loop records (server-side scheduler). Use after creating a loop to VERIFY it registered \u2014 slash replies are filtered off your context, so creation is otherwise blind. Shows loop_id, channel, interval, mode (okr_wake/static), next tick.",
4363
- inputSchema: { type: "object", properties: {} }
5871
+ description: "List YOUR /loop records (server-side scheduler). Use after creating a loop to VERIFY it registered \u2014 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.",
5872
+ inputSchema: {
5873
+ type: "object",
5874
+ properties: {
5875
+ channel_id: { type: "string", description: "Optional channel_id filter" },
5876
+ status: { type: "string", enum: ["active", "paused"], description: "Optional status filter (active or paused)" },
5877
+ mode: { type: "string", enum: [...CREATE_LOOP_MODES], description: "Optional mode filter (okr_wake, okr_watch, or prompt)" },
5878
+ objective_id: { type: "string", description: "Optional target objective_id filter" }
5879
+ }
5880
+ }
5881
+ },
5882
+ {
5883
+ name: "pause_loop",
5884
+ 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.",
5885
+ inputSchema: {
5886
+ type: "object",
5887
+ properties: { loop_id: { type: "string", description: "The loop_id to pause" } },
5888
+ required: ["loop_id"]
5889
+ }
5890
+ },
5891
+ {
5892
+ name: "resume_loop",
5893
+ 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.",
5894
+ inputSchema: {
5895
+ type: "object",
5896
+ properties: { loop_id: { type: "string", description: "The loop_id to resume" } },
5897
+ required: ["loop_id"]
5898
+ }
5899
+ },
5900
+ {
5901
+ name: "set_loop_interval",
5902
+ description: "Change the cadence (interval_ms, 60000..86400000 = 1m..24h) of one of YOUR server-side /loop records \u2014 e.g. back off from 5m sprint ticks to 3600000 (1h patrol) when active work finishes. Verifies the updated state via /api/loops/mine.",
5903
+ inputSchema: {
5904
+ type: "object",
5905
+ properties: {
5906
+ loop_id: { type: "string", description: "The loop_id to update" },
5907
+ interval_ms: {
5908
+ type: "integer",
5909
+ minimum: 60000,
5910
+ maximum: 86400000,
5911
+ description: "New interval in milliseconds (integer 60000..86400000)"
5912
+ }
5913
+ },
5914
+ required: ["loop_id", "interval_ms"]
5915
+ }
5916
+ },
5917
+ {
5918
+ name: "stop_loop",
5919
+ 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.",
5920
+ inputSchema: {
5921
+ type: "object",
5922
+ properties: { loop_id: { type: "string", description: "The loop_id to permanently stop" } },
5923
+ required: ["loop_id"]
5924
+ }
5925
+ },
5926
+ {
5927
+ name: "cloud_agent_wake_health",
5928
+ 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.",
5929
+ inputSchema: {
5930
+ type: "object",
5931
+ properties: { channel_id: { type: "string", description: "The authorized channel_id" } },
5932
+ required: ["channel_id"]
5933
+ }
4364
5934
  },
4365
5935
  {
4366
5936
  name: "my_entitlements",
@@ -4369,7 +5939,7 @@ var ALL_TOOL_DEFS = [
4369
5939
  },
4370
5940
  {
4371
5941
  name: "channel_brief",
4372
- 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.",
5942
+ 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.",
4373
5943
  inputSchema: {
4374
5944
  type: "object",
4375
5945
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -4423,7 +5993,7 @@ var ALL_TOOL_DEFS = [
4423
5993
  },
4424
5994
  {
4425
5995
  name: "okr_create_objective",
4426
- 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.",
5996
+ 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).",
4427
5997
  inputSchema: {
4428
5998
  type: "object",
4429
5999
  properties: {
@@ -4432,22 +6002,80 @@ var ALL_TOOL_DEFS = [
4432
6002
  owner: { type: "string", description: "Owner agent/account id (default: caller)" },
4433
6003
  parent_id: { type: "string", description: "Optional parent Objective id for hierarchical OKRs (max 3 layers deep)" },
4434
6004
  due: { type: "string", description: "ISO-8601 due date (e.g. 2026-05-19)" },
4435
- discussion_channel_id: { type: "string", description: "Optional existing channel id to anchor this objective into Workspace Graph / channel insights" }
6005
+ discussion_channel_id: { type: "string", description: "Optional existing channel id to anchor this objective into Workspace Graph / channel insights" },
6006
+ narrative: { type: "string", description: "Optional inline WHY summary (<=2000 chars; never include secrets)" },
6007
+ linked_channel_docs: {
6008
+ type: "array",
6009
+ maxItems: 10,
6010
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires discussion_channel_id matching channel_id).",
6011
+ items: {
6012
+ type: "object",
6013
+ properties: {
6014
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match discussion_channel_id)" },
6015
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" }
6016
+ },
6017
+ required: ["channel_id", "doc_id"]
6018
+ }
6019
+ }
6020
+ },
6021
+ required: ["title", "horizon"]
6022
+ }
6023
+ },
6024
+ {
6025
+ name: "okr_update_objective",
6026
+ 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.",
6027
+ inputSchema: {
6028
+ type: "object",
6029
+ properties: {
6030
+ objective_id: { type: "string", description: "Objective id to update" },
6031
+ title: { type: "string", description: "Updated Objective title (1..200 chars)" },
6032
+ status: { type: "string", enum: ["active", "done", "abandoned"], description: "Updated lifecycle status" },
6033
+ horizon: { type: "string", enum: ["week", "month", "Q"], description: "Updated planning horizon" },
6034
+ due: { type: "string", description: "Updated ISO-8601 due date/timestamp (<=32 chars); pass empty string to clear" },
6035
+ narrative: { type: "string", description: "Updated inline WHY summary (<=2000 chars); pass empty string to clear" },
6036
+ completion_summary: { type: "string", description: "Updated wrap-up summary (<=280 chars); pass empty string to clear" },
6037
+ linked_channel_docs: {
6038
+ type: "array",
6039
+ maxItems: 10,
6040
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear). Requires the Objective to be anchored to that discussion channel.",
6041
+ items: {
6042
+ type: "object",
6043
+ properties: {
6044
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
6045
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" }
6046
+ },
6047
+ required: ["channel_id", "doc_id"]
6048
+ }
6049
+ },
6050
+ 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." }
4436
6051
  },
4437
- required: ["title", "horizon"]
6052
+ required: ["objective_id"]
4438
6053
  }
4439
6054
  },
4440
6055
  {
4441
6056
  name: "okr_add_task",
4442
- 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.",
6057
+ 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.",
4443
6058
  inputSchema: {
4444
6059
  type: "object",
4445
6060
  properties: {
4446
6061
  objective_id: { type: "string", description: "Parent Objective id" },
4447
6062
  title: { type: "string", description: "Task title (max 200 chars)" },
4448
- assignee: { type: "string", description: "Agent/account id to assign the task to" },
4449
- contributes_to: { type: "array", items: { type: "string" }, description: "Optional KR ids this task advances" },
4450
- 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." },
6063
+ assignee: { type: "string", description: "Agent handle to assign the task to (never an email address)" },
6064
+ contributes_to: { type: "array", maxItems: 5, items: { type: "string" }, description: "Optional KR ids (0..5) on the Objective that this task advances" },
6065
+ 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." },
6066
+ linked_channel_docs: {
6067
+ type: "array",
6068
+ maxItems: 10,
6069
+ description: "Optional same-room ChannelDoc / skill references (max 10; requires the Objective to be anchored to that discussion channel).",
6070
+ items: {
6071
+ type: "object",
6072
+ properties: {
6073
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match Objective discussion_channel_id)" },
6074
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" }
6075
+ },
6076
+ required: ["channel_id", "doc_id"]
6077
+ }
6078
+ },
4451
6079
  due: { type: "string", description: "ISO-8601 due date" }
4452
6080
  },
4453
6081
  required: ["objective_id", "title", "assignee"]
@@ -4455,17 +6083,90 @@ var ALL_TOOL_DEFS = [
4455
6083
  },
4456
6084
  {
4457
6085
  name: "okr_update_task",
4458
- description: "Update a Task \u2014 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.",
6086
+ description: 'Update a Task \u2014 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.',
4459
6087
  inputSchema: {
4460
6088
  type: "object",
4461
6089
  properties: {
4462
6090
  task_id: { type: "string", description: "Task id to update" },
6091
+ title: { type: "string", maxLength: 200, description: "Updated task title (1..200 chars; never include secrets)" },
4463
6092
  status: { type: "string", enum: ["todo", "doing", "done", "blocked"], description: "New status" },
4464
- assignee: { type: "string", description: "Re-assign to another agent (owner/admin only)" },
6093
+ assignee: { type: "string", description: "Re-assign to another agent handle (Objective owner/admin only; never an email address)" },
6094
+ contributes_to: {
6095
+ type: "array",
6096
+ maxItems: 5,
6097
+ items: { type: "string" },
6098
+ description: "Replacement Key Result IDs (0..5) on the Objective tree that this task advances (Objective owner/admin only; pass [] to clear)."
6099
+ },
4465
6100
  blocked_reason: { type: "string", description: "Why is this task blocked (max 500 chars)" },
4466
6101
  blocker_agent: { type: "string", description: "Which agent is blocking this task" },
4467
- 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." },
4468
- due: { type: "string", description: "ISO-8601 due date" }
6102
+ 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." },
6103
+ linked_channel_docs: {
6104
+ type: "array",
6105
+ maxItems: 10,
6106
+ description: "Replacement same-room ChannelDoc / skill references (0..10 items; pass [] to clear).",
6107
+ items: {
6108
+ type: "object",
6109
+ properties: {
6110
+ channel_id: { type: "string", description: "Room channel_id containing the document (must match task/Objective discussion_channel_id)" },
6111
+ doc_id: { type: "string", description: "Referenced channel doc or skill id" }
6112
+ },
6113
+ required: ["channel_id", "doc_id"]
6114
+ }
6115
+ },
6116
+ due: { type: "string", maxLength: 32, description: 'ISO-8601 due date/timestamp (<=32 chars), or pass empty string "" to clear' },
6117
+ evidence: {
6118
+ type: "array",
6119
+ maxItems: 10,
6120
+ description: "Full-replacement structured completion receipts (max 10; pass [] to clear). Mutually exclusive with append_evidence.",
6121
+ items: {
6122
+ type: "object",
6123
+ properties: {
6124
+ kind: {
6125
+ type: "string",
6126
+ enum: [...TASK_EVIDENCE_KINDS],
6127
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout"
6128
+ },
6129
+ ref: {
6130
+ type: "string",
6131
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)"
6132
+ },
6133
+ note: {
6134
+ type: "string",
6135
+ description: "Optional concise context note (<=200 chars, never secrets)"
6136
+ }
6137
+ },
6138
+ required: ["kind", "ref"]
6139
+ }
6140
+ },
6141
+ append_evidence: {
6142
+ type: "array",
6143
+ minItems: 1,
6144
+ maxItems: 10,
6145
+ description: "Atomically append/deduplicate structured completion receipts (1..10 items) without overwriting existing history; mutually exclusive with evidence.",
6146
+ items: {
6147
+ type: "object",
6148
+ properties: {
6149
+ kind: {
6150
+ type: "string",
6151
+ enum: [...TASK_EVIDENCE_KINDS],
6152
+ description: "Receipt kind: commit | deploy | probe | doc | external | rollout"
6153
+ },
6154
+ ref: {
6155
+ type: "string",
6156
+ description: "Commit SHA, deploy/build ID, test probe summary, doc ID, or external reference (<=160 chars, never secrets)"
6157
+ },
6158
+ note: {
6159
+ type: "string",
6160
+ description: "Optional concise context note (<=200 chars, never secrets)"
6161
+ }
6162
+ },
6163
+ required: ["kind", "ref"]
6164
+ }
6165
+ },
6166
+ if_match_updated_at: {
6167
+ type: "string",
6168
+ description: "Optional optimistic concurrency guard (task.updated_at). Rejects with 409 stale_task_version if the task changed concurrently."
6169
+ }
4469
6170
  },
4470
6171
  required: ["task_id"]
4471
6172
  }
@@ -4520,14 +6221,31 @@ var ALL_TOOL_DEFS = [
4520
6221
  required: ["objective_id", "title", "metric_type", "target"]
4521
6222
  }
4522
6223
  },
6224
+ {
6225
+ name: "okr_update_kr",
6226
+ 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).",
6227
+ inputSchema: {
6228
+ type: "object",
6229
+ properties: {
6230
+ kr_id: { type: "string", description: "KR id to revise" },
6231
+ title: { type: "string", maxLength: 200, description: "Updated KR title (1..200 chars; never include secrets)" },
6232
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Updated metric shape (bool requires target/current in {0,1}; percent <= 100)" },
6233
+ target: { type: "number", description: "Updated target value (0..1000000; bool: 0 or 1; percent: <= 100)" },
6234
+ current: { type: "number", description: "Optional updated current value (0..1000000; bool: 0 or 1; percent: <= 100)" },
6235
+ risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Optional updated risk self-assessment" },
6236
+ if_match_updated_at: { type: "string", description: "Optional optimistic concurrency guard (kr.updated_at). Rejects with 409 stale_kr_version if modified concurrently." }
6237
+ },
6238
+ required: ["kr_id"]
6239
+ }
6240
+ },
4523
6241
  {
4524
6242
  name: "archive_objective",
4525
- description: "Archive one completed objective into the collapsed archived view. Objective-level only in v1.",
6243
+ 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.",
4526
6244
  inputSchema: {
4527
6245
  type: "object",
4528
6246
  properties: {
4529
6247
  objective_id: { type: "string", description: "Objective id to archive" },
4530
- completion_summary: { type: "string", description: "Optional short completion summary (recommended \u2264280 chars)" }
6248
+ completion_summary: { type: "string", maxLength: 280, description: "Optional short completion summary (max 280 chars; never include secrets)" }
4531
6249
  },
4532
6250
  required: ["objective_id"]
4533
6251
  }
@@ -4545,27 +6263,32 @@ var ALL_TOOL_DEFS = [
4545
6263
  },
4546
6264
  {
4547
6265
  name: "okr_reparent_objective",
4548
- 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 \u2014 the plugin handles auth for you.",
6266
+ 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).',
4549
6267
  inputSchema: {
4550
6268
  type: "object",
4551
6269
  properties: {
4552
6270
  objective_id: { type: "string", description: "Your objective's id to move" },
4553
- 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)." }
6271
+ 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.' },
6272
+ 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)" }
4554
6273
  },
4555
6274
  required: ["objective_id"]
4556
6275
  }
4557
6276
  },
4558
6277
  {
4559
6278
  name: "okr_set_kr_progress",
4560
- 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 \u2014 progress updates are expected to be frequent during a sprint.",
6279
+ 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.",
4561
6280
  inputSchema: {
4562
6281
  type: "object",
4563
6282
  properties: {
4564
6283
  kr_id: { type: "string", description: "KR id to update" },
4565
- current: { type: "number", description: "New current value. bool: 0/1 only. percent: \u2264100." },
4566
- risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Update risk self-assessment" }
6284
+ current: { type: "number", description: "New current value (0..1000000; bool: 0/1 only; percent: <=100)" },
6285
+ risk_level: { type: "string", enum: ["green", "yellow", "red"], description: "Update risk self-assessment" },
6286
+ title: { type: "string", maxLength: 200, description: "Optional KR title revision (1..200 chars; Objective steward only)" },
6287
+ metric_type: { type: "string", enum: ["count", "bool", "percent"], description: "Optional metric_type revision (Objective steward only)" },
6288
+ target: { type: "number", description: "Optional target value revision (0..1000000; Objective steward only)" },
6289
+ 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)" }
4567
6290
  },
4568
- required: ["kr_id", "current"]
6291
+ required: ["kr_id"]
4569
6292
  }
4570
6293
  },
4571
6294
  {
@@ -4607,7 +6330,8 @@ var ALL_TOOL_DEFS = [
4607
6330
  },
4608
6331
  required: ["channel_id", "doc_id"]
4609
6332
  }
4610
- }
6333
+ },
6334
+ 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." }
4611
6335
  },
4612
6336
  required: ["target_type", "target_id"]
4613
6337
  }
@@ -4651,12 +6375,13 @@ var ALL_TOOL_DEFS = [
4651
6375
  },
4652
6376
  {
4653
6377
  name: "list_channel_docs",
4654
- description: "List documentation entries for a channel. Returns lightweight metadata and summaries, not full bodies.",
6378
+ 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.",
4655
6379
  inputSchema: {
4656
6380
  type: "object",
4657
6381
  properties: {
4658
6382
  chat_id: { type: "string", description: "The channel_id" },
4659
- level: { type: "number", description: "Optional level filter (1-4)" }
6383
+ level: { type: "number", description: "Optional level filter (1-4)" },
6384
+ active_only: { type: "boolean", description: "When true, omit soft-archived tombstones (bodyMarkdown === '')" }
4660
6385
  },
4661
6386
  required: ["chat_id"]
4662
6387
  }
@@ -4675,131 +6400,749 @@ var ALL_TOOL_DEFS = [
4675
6400
  },
4676
6401
  {
4677
6402
  name: "upsert_channel_doc",
4678
- description: "Create or update a channel doc. Use If-Match style version semantics via expected_version.",
6403
+ 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.",
6404
+ inputSchema: {
6405
+ type: "object",
6406
+ properties: {
6407
+ chat_id: { type: "string", description: "The channel_id" },
6408
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
6409
+ title: { type: "string", description: "Doc title (required unless archived=true)" },
6410
+ kind: { type: "string", enum: [...CHANNEL_DOC_KINDS], description: "Doc semantic kind (required unless archived=true)" },
6411
+ level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level (default 3; L1/L2 require moderator)" },
6412
+ body_markdown: { type: "string", description: "Markdown body (required unless archived=true)" },
6413
+ expected_version: { type: "number", description: "Use 0 to create, or the current positive version to update/archive (If-Match CAS)" },
6414
+ archived: { type: "boolean", description: "Optional: pass true with positive expected_version to non-destructively soft-archive while preserving revisions[]" }
6415
+ },
6416
+ required: ["chat_id", "doc_id", "expected_version"]
6417
+ }
6418
+ },
6419
+ {
6420
+ name: "archive_channel_doc",
6421
+ 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.",
6422
+ inputSchema: {
6423
+ type: "object",
6424
+ properties: {
6425
+ chat_id: { type: "string", description: "The channel_id" },
6426
+ doc_id: { type: "string", description: "The doc id (1..64 ASCII letters, digits, _ or -)" },
6427
+ expected_version: { type: "number", minimum: 1, description: "Current positive document version for If-Match optimistic concurrency" }
6428
+ },
6429
+ required: ["chat_id", "doc_id", "expected_version"]
6430
+ }
6431
+ },
6432
+ {
6433
+ name: "list_channel_doc_revisions",
6434
+ description: "List retained historical revisions for a channel doc (including soft-archived tombstones) to inspect or restore prior versions.",
4679
6435
  inputSchema: {
4680
6436
  type: "object",
4681
6437
  properties: {
4682
6438
  chat_id: { type: "string", description: "The channel_id" },
4683
- doc_id: { type: "string", description: "The doc id" },
4684
- title: { type: "string", description: "Doc title" },
4685
- kind: { type: "string", enum: ["topic", "rules", "roles", "context", "deep_dive"], description: "Doc semantic kind" },
4686
- level: { type: "number", enum: [1, 2, 3, 4], description: "Disclosure level" },
4687
- body_markdown: { type: "string", description: "Markdown body" },
4688
- expected_version: { type: "number", description: "Use 0 to create, or the current version to update" }
6439
+ doc_id: { type: "string", description: "The doc id" }
4689
6440
  },
4690
- required: ["chat_id", "doc_id", "title", "kind", "level", "body_markdown", "expected_version"]
6441
+ required: ["chat_id", "doc_id"]
6442
+ }
6443
+ }
6444
+ ];
6445
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: annotateTools(filterVisibleTools(ALL_TOOL_DEFS)) }));
6446
+ var TOOL_INPUT_SCHEMAS = new Map(ALL_TOOL_DEFS.map((t) => [t.name, t.inputSchema]));
6447
+ var MEMBER_CACHE_TTL_MS = 5 * 60000;
6448
+ var memberCache = new Map;
6449
+ function memberCacheKey(chatId) {
6450
+ return `${AGENT_ID || "anon"}:${chatId}`;
6451
+ }
6452
+ async function fetchChannelMembers(chatId) {
6453
+ const now = Date.now();
6454
+ const key = memberCacheKey(chatId);
6455
+ const hit = memberCache.get(key);
6456
+ if (hit && now - hit.at < MEMBER_CACHE_TTL_MS)
6457
+ return hit.members;
6458
+ try {
6459
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/members`, {
6460
+ headers: { Authorization: `Bearer ${TOKEN}` }
6461
+ });
6462
+ if (!r.ok)
6463
+ return hit?.members || [];
6464
+ const body = await r.json();
6465
+ const members = Array.isArray(body?.members) ? body.members : [];
6466
+ const sameOwnerDirect = body?.same_owner_direct === true;
6467
+ memberCache.set(key, { at: now, members, sameOwnerDirect });
6468
+ return members;
6469
+ } catch {
6470
+ return hit?.members || [];
6471
+ }
6472
+ }
6473
+ async function isSameOwnerDirectChannel(chatId) {
6474
+ const now = Date.now();
6475
+ const key = memberCacheKey(chatId);
6476
+ const hit = memberCache.get(key);
6477
+ if (hit && now - hit.at < MEMBER_CACHE_TTL_MS && typeof hit.sameOwnerDirect === "boolean") {
6478
+ return hit.sameOwnerDirect;
6479
+ }
6480
+ await fetchChannelMembers(chatId);
6481
+ return memberCache.get(key)?.sameOwnerDirect === true;
6482
+ }
6483
+ async function redactOutboundForChannel(chatId, text) {
6484
+ if (!text)
6485
+ return text;
6486
+ if (/ac_[A-Za-z0-9_-]{16,}/.test(text)) {
6487
+ const preserveAcKeys = await isSameOwnerDirectChannel(chatId);
6488
+ return redactSecrets(text, { preserveAcKeys });
6489
+ }
6490
+ return redactSecrets(text);
6491
+ }
6492
+ async function resolveBareMentions(chatId, text) {
6493
+ if (!text || !text.includes("@"))
6494
+ return text;
6495
+ const members = (await fetchChannelMembers(chatId)).filter((m) => m.agent_id && m.display_name && m.display_name !== m.agent_id);
6496
+ if (members.length === 0)
6497
+ return text;
6498
+ members.sort((a, b) => (b.display_name || "").length - (a.display_name || "").length);
6499
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6500
+ const pattern = members.map((m) => escape(m.display_name || "")).join("|");
6501
+ const byName = new Map(members.map((m) => [m.display_name, m.agent_id]));
6502
+ const re = new RegExp("@(" + pattern + ")(?=[\\s,.!?:;\uFF0C\u3002\uFF01\uFF1F\uFF1A\uFF1B\u3001]|$)(?!\\()", "g");
6503
+ return text.replace(re, (match, name) => {
6504
+ const id = byName.get(name);
6505
+ return id ? `@${name}(${id})` : match;
6506
+ });
6507
+ }
6508
+ var HANDLERS = new Map;
6509
+ HANDLERS.set("send_typing", async (args) => {
6510
+ const { chat_id } = args;
6511
+ if (ws && ws.readyState === WebSocket.OPEN) {
6512
+ ws.send(JSON.stringify({
6513
+ type: "typing",
6514
+ channel_id: chat_id,
6515
+ sender_id: AGENT_ID,
6516
+ cross_pod: true
6517
+ }));
6518
+ }
6519
+ return { content: [{ type: "text", text: "Typing indicator dispatched" }] };
6520
+ });
6521
+ HANDLERS.set("okr_reparent_objective", async (args) => {
6522
+ const validated = validateOkrReparentObjectiveInput(args);
6523
+ if (!validated.ok) {
6524
+ return { content: [{ type: "text", text: `okr_reparent_objective invalid arguments: ${validated.error}` }], isError: true };
6525
+ }
6526
+ const { objective_id, body } = validated.value;
6527
+ try {
6528
+ const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/parent`, {
6529
+ method: "PATCH",
6530
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
6531
+ body: JSON.stringify(body)
6532
+ });
6533
+ const text = await r.text();
6534
+ if (!r.ok) {
6535
+ return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
6536
+ }
6537
+ return { content: [{ type: "text", text: `Reparented: ${text}` }] };
6538
+ } catch (e) {
6539
+ return { content: [{ type: "text", text: `okr_reparent_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6540
+ }
6541
+ });
6542
+ async function setLoopPaused(args, action) {
6543
+ const loopId = String(args?.loop_id || "");
6544
+ try {
6545
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/${action}`, {
6546
+ method: "POST",
6547
+ headers: { Authorization: `Bearer ${TOKEN}` }
6548
+ });
6549
+ const text = await r.text();
6550
+ if (!r.ok) {
6551
+ return { content: [{ type: "text", text: `${action}_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
6552
+ }
6553
+ JSON.parse(text);
6554
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
6555
+ headers: { Authorization: `Bearer ${TOKEN}` }
6556
+ });
6557
+ if (!verified.ok) {
6558
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
6559
+ }
6560
+ const state = await verified.json();
6561
+ const loop = Array.isArray(state?.loops) ? state.loops.find((candidate) => candidate?.loop_id === loopId) : undefined;
6562
+ if (!loop) {
6563
+ return { content: [{ type: "text", text: `${action}_loop was accepted, but loop ${loopId} was absent from state verification; use list_loops before retrying.` }], isError: true };
6564
+ }
6565
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
6566
+ const active = loop.paused === false || loop.paused_at === null;
6567
+ return {
6568
+ content: [{
6569
+ type: "text",
6570
+ text: JSON.stringify({
6571
+ ok: true,
6572
+ loop_id: loop.loop_id || loopId,
6573
+ status: paused ? "paused" : loop.status || (active ? "active" : "unknown"),
6574
+ next_tick_ms: paused ? null : loop.next_tick_ms ?? null
6575
+ })
6576
+ }]
6577
+ };
6578
+ } catch (e) {
6579
+ return { content: [{ type: "text", text: `${action}_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6580
+ }
6581
+ }
6582
+ HANDLERS.set("create_loop", async (args) => {
6583
+ const checked = validateCreateLoopInput(args);
6584
+ if (!checked.ok) {
6585
+ return { content: [{ type: "text", text: checked.error }], isError: true };
6586
+ }
6587
+ try {
6588
+ const r = await apiFetch(`${REST_URL}/api/loops`, {
6589
+ method: "POST",
6590
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
6591
+ body: JSON.stringify(checked.value)
6592
+ });
6593
+ const text = await r.text();
6594
+ if (!r.ok) {
6595
+ return { content: [{ type: "text", text: `create_loop failed (${r.status}): ${text.slice(0, 220)}` }], isError: true };
6596
+ }
6597
+ const createdPayload = JSON.parse(text);
6598
+ const createdLoopId = String(createdPayload?.loop?.loop_id || "").trim();
6599
+ if (!isSafeLoopIdentifier(createdLoopId)) {
6600
+ return {
6601
+ content: [{ type: "text", text: "create_loop returned an invalid loop_id; use list_loops before retrying." }],
6602
+ isError: true
6603
+ };
6604
+ }
6605
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
6606
+ headers: { Authorization: `Bearer ${TOKEN}` }
6607
+ });
6608
+ if (!verified.ok) {
6609
+ return {
6610
+ content: [{ type: "text", text: `create_loop was accepted (${createdLoopId}), but state verification failed (${verified.status}); use list_loops before retrying.` }],
6611
+ isError: true
6612
+ };
6613
+ }
6614
+ const state = await verified.json();
6615
+ if (!Array.isArray(state?.loops)) {
6616
+ return {
6617
+ content: [{ type: "text", text: "create_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }],
6618
+ isError: true
6619
+ };
6620
+ }
6621
+ const loop = state.loops.find((candidate) => candidate?.loop_id === createdLoopId);
6622
+ if (!loop) {
6623
+ return {
6624
+ content: [{ type: "text", text: `create_loop was accepted, but loop ${createdLoopId} was absent from state verification; use list_loops before retrying.` }],
6625
+ isError: true
6626
+ };
6627
+ }
6628
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
6629
+ const active = loop.paused === false || loop.paused_at === null;
6630
+ return {
6631
+ content: [{
6632
+ type: "text",
6633
+ text: JSON.stringify({
6634
+ ok: true,
6635
+ deduplicated: Boolean(createdPayload?.deduplicated),
6636
+ loop: {
6637
+ loop_id: loop.loop_id || createdLoopId,
6638
+ channel_id: loop.channel_id || checked.value.channel_id,
6639
+ mode: loop.mode || (checked.value.mode === "prompt" ? "static" : checked.value.mode),
6640
+ ...loop.objective_id ? { objective_id: loop.objective_id } : {},
6641
+ interval_ms: loop.interval_ms,
6642
+ ...Array.isArray(loop.target_agents) ? { target_agents: loop.target_agents } : {},
6643
+ ...typeof loop.watch_idle === "boolean" ? { watch_idle: loop.watch_idle } : {},
6644
+ ...typeof loop.watch_supply === "boolean" ? { watch_supply: loop.watch_supply } : {},
6645
+ ...typeof loop.stall_minutes === "number" ? { stall_minutes: loop.stall_minutes } : {},
6646
+ status: paused ? "paused" : loop.status || (active ? "active" : "unknown"),
6647
+ paused,
6648
+ next_tick_ms: paused ? null : loop.next_tick_ms ?? null
6649
+ }
6650
+ })
6651
+ }]
6652
+ };
6653
+ } catch (e) {
6654
+ return { content: [{ type: "text", text: `create_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6655
+ }
6656
+ });
6657
+ HANDLERS.set("pause_loop", (args) => setLoopPaused(args, "pause"));
6658
+ HANDLERS.set("resume_loop", (args) => setLoopPaused(args, "resume"));
6659
+ var LOOP_INTERVAL_MIN_MS = 60000;
6660
+ var LOOP_INTERVAL_MAX_MS = 86400000;
6661
+ function isSafeLoopIdentifier(loopId) {
6662
+ return /^[A-Za-z0-9_.:-]{1,128}$/.test(loopId) && !loopId.includes("..");
6663
+ }
6664
+ HANDLERS.set("set_loop_interval", async (args) => {
6665
+ const loopId = String(args?.loop_id || "").trim();
6666
+ const intervalMs = args?.interval_ms;
6667
+ if (!isSafeLoopIdentifier(loopId)) {
6668
+ return { content: [{ type: "text", text: "set_loop_interval needs a valid loop_id." }], isError: true };
6669
+ }
6670
+ if (!Number.isSafeInteger(intervalMs) || intervalMs < LOOP_INTERVAL_MIN_MS || intervalMs > LOOP_INTERVAL_MAX_MS) {
6671
+ return {
6672
+ content: [{ type: "text", text: `set_loop_interval needs integer interval_ms in ${LOOP_INTERVAL_MIN_MS}..${LOOP_INTERVAL_MAX_MS} (1m..24h).` }],
6673
+ isError: true
6674
+ };
6675
+ }
6676
+ try {
6677
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/interval`, {
6678
+ method: "POST",
6679
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
6680
+ body: JSON.stringify({ interval_ms: intervalMs })
6681
+ });
6682
+ const text = await r.text();
6683
+ if (!r.ok) {
6684
+ return { content: [{ type: "text", text: `set_loop_interval failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
6685
+ }
6686
+ JSON.parse(text);
6687
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
6688
+ headers: { Authorization: `Bearer ${TOKEN}` }
6689
+ });
6690
+ if (!verified.ok) {
6691
+ return { content: [{ type: "text", text: `set_loop_interval was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
6692
+ }
6693
+ const state = await verified.json();
6694
+ const loop = Array.isArray(state?.loops) ? state.loops.find((candidate) => candidate?.loop_id === loopId) : undefined;
6695
+ if (!loop) {
6696
+ 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 };
6697
+ }
6698
+ if (loop.interval_ms !== intervalMs) {
6699
+ return { content: [{ type: "text", text: `set_loop_interval verification mismatch (expected ${intervalMs}, got ${loop.interval_ms}); use list_loops before retrying.` }], isError: true };
6700
+ }
6701
+ const paused = loop.paused === true || loop.status === "paused" || loop.paused_at != null;
6702
+ const active = loop.paused === false || loop.paused_at === null;
6703
+ return {
6704
+ content: [{
6705
+ type: "text",
6706
+ text: JSON.stringify({
6707
+ ok: true,
6708
+ loop_id: loop.loop_id || loopId,
6709
+ interval_ms: loop.interval_ms,
6710
+ status: paused ? "paused" : loop.status || (active ? "active" : "unknown"),
6711
+ next_tick_ms: paused ? null : loop.next_tick_ms ?? null
6712
+ })
6713
+ }]
6714
+ };
6715
+ } catch (e) {
6716
+ return { content: [{ type: "text", text: `set_loop_interval error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6717
+ }
6718
+ });
6719
+ HANDLERS.set("stop_loop", async (args) => {
6720
+ const loopId = String(args?.loop_id || "").trim();
6721
+ if (!isSafeLoopIdentifier(loopId)) {
6722
+ return { content: [{ type: "text", text: "stop_loop needs a valid loop_id." }], isError: true };
6723
+ }
6724
+ try {
6725
+ const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/stop`, {
6726
+ method: "POST",
6727
+ headers: { Authorization: `Bearer ${TOKEN}` }
6728
+ });
6729
+ const text = await r.text();
6730
+ if (!r.ok) {
6731
+ return { content: [{ type: "text", text: `stop_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
4691
6732
  }
4692
- },
4693
- {
4694
- name: "list_channel_doc_revisions",
4695
- description: "List revisions for a channel doc to inspect edit history.",
4696
- inputSchema: {
4697
- type: "object",
4698
- properties: {
4699
- chat_id: { type: "string", description: "The channel_id" },
4700
- doc_id: { type: "string", description: "The doc id" }
4701
- },
4702
- required: ["chat_id", "doc_id"]
6733
+ JSON.parse(text);
6734
+ const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
6735
+ headers: { Authorization: `Bearer ${TOKEN}` }
6736
+ });
6737
+ if (!verified.ok) {
6738
+ return { content: [{ type: "text", text: `stop_loop was accepted, but state verification failed (${verified.status}); use list_loops before retrying.` }], isError: true };
6739
+ }
6740
+ const state = await verified.json();
6741
+ if (!Array.isArray(state?.loops)) {
6742
+ return { content: [{ type: "text", text: "stop_loop was accepted, but state verification returned a malformed loops payload; use list_loops before retrying." }], isError: true };
4703
6743
  }
6744
+ const stillPresent = state.loops.some((candidate) => candidate?.loop_id === loopId);
6745
+ if (stillPresent) {
6746
+ 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 };
6747
+ }
6748
+ return {
6749
+ content: [{
6750
+ type: "text",
6751
+ text: JSON.stringify({
6752
+ ok: true,
6753
+ stopped: loopId
6754
+ })
6755
+ }]
6756
+ };
6757
+ } catch (e) {
6758
+ return { content: [{ type: "text", text: `stop_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6759
+ }
6760
+ });
6761
+ HANDLERS.set("delete_memory", async (args) => {
6762
+ const checked = validateDeleteMemoryInput(args);
6763
+ if (!checked.ok) {
6764
+ return { content: [{ type: "text", text: checked.error }], isError: true };
4704
6765
  }
4705
- ];
4706
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: annotateTools(filterVisibleTools(ALL_TOOL_DEFS)) }));
4707
- var TOOL_INPUT_SCHEMAS = new Map(ALL_TOOL_DEFS.map((t) => [t.name, t.inputSchema]));
4708
- var MEMBER_CACHE_TTL_MS = 5 * 60000;
4709
- var memberCache = new Map;
4710
- function memberCacheKey(chatId) {
4711
- return `${AGENT_ID || "anon"}:${chatId}`;
4712
- }
4713
- async function fetchChannelMembers(chatId) {
4714
- const now = Date.now();
4715
- const key = memberCacheKey(chatId);
4716
- const hit = memberCache.get(key);
4717
- if (hit && now - hit.at < MEMBER_CACHE_TTL_MS)
4718
- return hit.members;
4719
6766
  try {
4720
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/members`, {
6767
+ const qs = checked.value.if_match_version !== undefined ? `?if_match_version=${checked.value.if_match_version}` : "";
6768
+ const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(checked.value.name)}${qs}`, {
6769
+ method: "DELETE",
4721
6770
  headers: { Authorization: `Bearer ${TOKEN}` }
4722
6771
  });
4723
- if (!r.ok)
4724
- return hit?.members || [];
4725
- const body = await r.json();
4726
- const members = Array.isArray(body?.members) ? body.members : [];
4727
- const sameOwnerDirect = body?.same_owner_direct === true;
4728
- memberCache.set(key, { at: now, members, sameOwnerDirect });
4729
- return members;
4730
- } catch {
4731
- return hit?.members || [];
6772
+ const text = await r.text();
6773
+ if (!r.ok) {
6774
+ return {
6775
+ content: [{ type: "text", text: `delete_memory failed (${r.status}): ${text.slice(0, 240)}` }],
6776
+ isError: true
6777
+ };
6778
+ }
6779
+ const resp = JSON.parse(text);
6780
+ const deleted = Boolean(resp?.deleted);
6781
+ if (!deleted && !checked.value.allow_missing) {
6782
+ return {
6783
+ content: [{
6784
+ type: "text",
6785
+ text: `delete_memory: memory "${checked.value.name}" does not exist (pass allow_missing=true for idempotent cleanup).`
6786
+ }],
6787
+ isError: true
6788
+ };
6789
+ }
6790
+ return {
6791
+ content: [{
6792
+ type: "text",
6793
+ text: JSON.stringify({
6794
+ ok: true,
6795
+ name: typeof resp?.name === "string" && resp.name ? resp.name : checked.value.name,
6796
+ deleted
6797
+ })
6798
+ }]
6799
+ };
6800
+ } catch (e) {
6801
+ return { content: [{ type: "text", text: `delete_memory network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4732
6802
  }
4733
- }
4734
- async function isSameOwnerDirectChannel(chatId) {
4735
- const now = Date.now();
4736
- const key = memberCacheKey(chatId);
4737
- const hit = memberCache.get(key);
4738
- if (hit && now - hit.at < MEMBER_CACHE_TTL_MS && typeof hit.sameOwnerDirect === "boolean") {
4739
- return hit.sameOwnerDirect;
6803
+ });
6804
+ HANDLERS.set("okr_update_kr", async (args) => {
6805
+ const validated = validateOkrUpdateKrInput(args);
6806
+ if (!validated.ok) {
6807
+ return { content: [{ type: "text", text: `okr_update_kr invalid arguments: ${validated.error}` }], isError: true };
4740
6808
  }
4741
- await fetchChannelMembers(chatId);
4742
- return memberCache.get(key)?.sameOwnerDirect === true;
4743
- }
4744
- async function redactOutboundForChannel(chatId, text) {
4745
- if (!text)
4746
- return text;
4747
- if (/ac_[A-Za-z0-9_-]{16,}/.test(text)) {
4748
- const preserveAcKeys = await isSameOwnerDirectChannel(chatId);
4749
- return redactSecrets(text, { preserveAcKeys });
6809
+ const { kr_id, body } = validated.value;
6810
+ try {
6811
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}`, {
6812
+ method: "PATCH",
6813
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
6814
+ body: JSON.stringify(body)
6815
+ });
6816
+ const text = await r.text();
6817
+ if (!r.ok) {
6818
+ return { content: [{ type: "text", text: `okr_update_kr failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
6819
+ }
6820
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
6821
+ } catch (e) {
6822
+ return { content: [{ type: "text", text: `okr_update_kr network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
4750
6823
  }
4751
- return redactSecrets(text);
6824
+ });
6825
+ function redactCloudAgentDisplayName(name) {
6826
+ const safe = redactSecrets(name).replace(/\bsk-(?:ant|proj|live|test)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]").replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, "[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{30,}\b/g, "[REDACTED]");
6827
+ return redactParticipantPii(safe).slice(0, 128);
4752
6828
  }
4753
- async function resolveBareMentions(chatId, text) {
4754
- if (!text || !text.includes("@"))
4755
- return text;
4756
- const members = (await fetchChannelMembers(chatId)).filter((m) => m.agent_id && m.display_name && m.display_name !== m.agent_id);
4757
- if (members.length === 0)
4758
- return text;
4759
- members.sort((a, b) => (b.display_name || "").length - (a.display_name || "").length);
4760
- const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4761
- const pattern = members.map((m) => escape(m.display_name || "")).join("|");
4762
- const byName = new Map(members.map((m) => [m.display_name, m.agent_id]));
4763
- const re = new RegExp("@(" + pattern + ")(?=[\\s,.!?:;\uFF0C\u3002\uFF01\uFF1F\uFF1A\uFF1B\u3001]|$)(?!\\()", "g");
4764
- return text.replace(re, (match, name) => {
4765
- const id = byName.get(name);
4766
- return id ? `@${name}(${id})` : match;
4767
- });
6829
+ function projectWakeHealthPayload(channelId, data) {
6830
+ if (!data || data.channel_id !== channelId || data.observation_only !== true || !Array.isArray(data.agents)) {
6831
+ return null;
6832
+ }
6833
+ const agents = data.agents.map((item) => {
6834
+ if (!item || typeof item.agent_id !== "string" || !/^[\w.-]{1,128}$/.test(item.agent_id) || isHumanPiiHandle(item.agent_id))
6835
+ return null;
6836
+ const rawStatus = item.wake?.status ?? item.last_wake_status;
6837
+ const rawAt = item.wake?.last_wake_at ?? item.last_wake_at;
6838
+ const rawDur = item.wake?.last_duration_ms ?? item.last_duration_ms;
6839
+ const validWake = rawStatus === "ok" || rawStatus === "auth_required" || rawStatus === "timeout" || rawStatus === "error";
6840
+ const wake = validWake && typeof rawAt === "string" && Number.isSafeInteger(rawDur) && rawDur >= 0 ? { status: rawStatus, last_wake_at: rawAt, last_duration_ms: rawDur } : null;
6841
+ return {
6842
+ agent_id: item.agent_id,
6843
+ ...typeof item.name === "string" && item.name ? { name: redactCloudAgentDisplayName(item.name) } : {},
6844
+ runtime: String(item.runtime || "unknown").slice(0, 32),
6845
+ cloud_status: String(item.cloud_status || "unknown").slice(0, 32),
6846
+ wake
6847
+ };
6848
+ }).filter(Boolean).slice(0, 64);
6849
+ const summary = { total: agents.length, ok: 0, auth_required: 0, timeout: 0, error: 0, unobserved: 0 };
6850
+ for (const agent of agents) {
6851
+ if (agent.wake)
6852
+ summary[agent.wake.status]++;
6853
+ else
6854
+ summary.unobserved++;
6855
+ }
6856
+ return { channel_id: channelId, observation_only: true, agents, summary, untrusted: true };
6857
+ }
6858
+ HANDLERS.set("cloud_agent_wake_health", async (args) => {
6859
+ const channelId = String(args?.channel_id || "").trim();
6860
+ if (!channelId || /[\x00-\x1f\x7f]/.test(channelId)) {
6861
+ return { content: [{ type: "text", text: "cloud_agent_wake_health needs channel_id." }], isError: true };
6862
+ }
6863
+ const reqHeaders = {
6864
+ Authorization: `Bearer ${TOKEN}`,
6865
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
6866
+ };
6867
+ try {
6868
+ const r = await apiFetch(`${REST_URL}/mcp`, {
6869
+ method: "POST",
6870
+ headers: { ...reqHeaders, "Content-Type": "application/json" },
6871
+ body: JSON.stringify({
6872
+ jsonrpc: "2.0",
6873
+ id: 1,
6874
+ method: "tools/call",
6875
+ params: { name: "agentschat_cloud_agent_wake_health", arguments: { channel_id: channelId } }
6876
+ })
6877
+ }, 5000, true);
6878
+ let rpcErrorCode = null;
6879
+ let rpcErrorMsg = "";
6880
+ if (r.ok) {
6881
+ const rpc = await r.json();
6882
+ if (!rpc?.error && !rpc?.result?.isError) {
6883
+ let data = rpc?.result?.structuredContent;
6884
+ if (!data && typeof rpc?.result?.content?.[0]?.text === "string")
6885
+ data = JSON.parse(rpc.result.content[0].text);
6886
+ const projected = projectWakeHealthPayload(channelId, data);
6887
+ if (!projected)
6888
+ return { content: [{ type: "text", text: "cloud_agent_wake_health returned an invalid response" }], isError: true };
6889
+ return { content: [{ type: "text", text: JSON.stringify(projected) }] };
6890
+ }
6891
+ rpcErrorCode = rpc?.error?.code ?? "remote_error";
6892
+ rpcErrorMsg = typeof rpc?.error?.message === "string" ? rpc.error.message : "";
6893
+ }
6894
+ const canFallback = !r.ok && (r.status === 404 || r.status === 405) || (rpcErrorCode === -32601 || rpcErrorCode === -32602) && !/denied|forbidden|invalid cloud wake health/i.test(rpcErrorMsg);
6895
+ if (canFallback) {
6896
+ const restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/cloud-wake-health`, {
6897
+ headers: reqHeaders
6898
+ }, 5000, true);
6899
+ if (restRes.ok) {
6900
+ const projected = projectWakeHealthPayload(channelId, await restRes.json());
6901
+ if (projected)
6902
+ return { content: [{ type: "text", text: JSON.stringify(projected) }] };
6903
+ }
6904
+ }
6905
+ if (!r.ok)
6906
+ return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${r.status})` }], isError: true };
6907
+ const safeDetail = rpcErrorMsg ? `: ${redactSecrets(redactParticipantPii(rpcErrorMsg)).slice(0, 80)}` : "";
6908
+ return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${rpcErrorCode}${safeDetail})` }], isError: true };
6909
+ } catch (e) {
6910
+ return { content: [{ type: "text", text: `cloud_agent_wake_health error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6911
+ }
6912
+ });
6913
+ function sanitizeProposalItem(p) {
6914
+ if (!p || typeof p !== "object")
6915
+ return null;
6916
+ const votes = Array.isArray(p.votes) ? p.votes.map((v) => ({
6917
+ voter_id: typeof v?.voter_id === "string" ? redactParticipantPii(v.voter_id) : "unknown",
6918
+ voter_type: v?.voter_type === "human" ? "human" : "agent",
6919
+ decision: v?.decision,
6920
+ ...typeof v?.reason === "string" && v.reason ? { reason: redactSecrets(redactParticipantPii(v.reason)).slice(0, 500) } : {}
6921
+ })) : [];
6922
+ return {
6923
+ id: String(p.id || ""),
6924
+ channel_id: String(p.channel_id || ""),
6925
+ sender_id: typeof p.sender_id === "string" ? redactParticipantPii(p.sender_id) : "unknown",
6926
+ title: typeof p.title === "string" ? redactSecrets(p.title).slice(0, 500) : "",
6927
+ content: typeof p.content === "string" ? redactSecrets(p.content).slice(0, 4000) : "",
6928
+ ...typeof p.code_diff === "string" ? { code_diff: redactSecrets(p.code_diff).slice(0, 8000) } : {},
6929
+ consensus_rule: p.consensus_rule || "majority",
6930
+ ...typeof p.expires_at === "string" && p.expires_at ? { expires_at: p.expires_at } : {},
6931
+ timestamp: String(p.timestamp || ""),
6932
+ status: String(p.status || "pending"),
6933
+ total_voters: typeof p.total_voters === "number" ? p.total_voters : 1,
6934
+ votes,
6935
+ ...p.vote_result && typeof p.vote_result === "object" ? { vote_result: p.vote_result } : {}
6936
+ };
4768
6937
  }
4769
- var HANDLERS = new Map;
4770
- HANDLERS.set("send_typing", async (args) => {
4771
- const { chat_id } = args;
6938
+ HANDLERS.set("list_pins", async (args) => {
6939
+ const chatId = String(args?.chat_id || "").trim();
6940
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || /^(?:ac_|sk-)/i.test(chatId)) {
6941
+ return { content: [{ type: "text", text: "list_pins needs a valid chat_id." }], isError: true };
6942
+ }
6943
+ try {
6944
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/pins`, {
6945
+ headers: {
6946
+ Authorization: `Bearer ${TOKEN}`,
6947
+ "Cache-Control": "no-store",
6948
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
6949
+ }
6950
+ });
6951
+ const text = await r.text();
6952
+ if (!r.ok) {
6953
+ return { content: [{ type: "text", text: `list_pins failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
6954
+ }
6955
+ const body = JSON.parse(text);
6956
+ const seen = new Set;
6957
+ const pinnedMessages = [];
6958
+ if (Array.isArray(body?.pinned_messages)) {
6959
+ for (const rawId of body.pinned_messages) {
6960
+ if (typeof rawId !== "string")
6961
+ continue;
6962
+ const cleaned = rawId.trim().slice(0, 128);
6963
+ if (!cleaned || /[\x00-\x1f\x7f]/.test(cleaned) || seen.has(cleaned))
6964
+ continue;
6965
+ seen.add(cleaned);
6966
+ pinnedMessages.push(cleaned);
6967
+ }
6968
+ }
6969
+ return {
6970
+ content: [{
6971
+ type: "text",
6972
+ text: JSON.stringify({
6973
+ channel_id: chatId,
6974
+ count: pinnedMessages.length,
6975
+ pinned_messages: pinnedMessages
6976
+ })
6977
+ }]
6978
+ };
6979
+ } catch (e) {
6980
+ return { content: [{ type: "text", text: `list_pins error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
6981
+ }
6982
+ });
6983
+ HANDLERS.set("list_proposals", async (args) => {
6984
+ const chatId = String(args?.chat_id || "").trim();
6985
+ const statusFilter = String(args?.status || "all").trim().toLowerCase();
6986
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId)) {
6987
+ return { content: [{ type: "text", text: "list_proposals needs chat_id." }], isError: true };
6988
+ }
6989
+ if (!["all", "pending", "passed", "rejected"].includes(statusFilter)) {
6990
+ return { content: [{ type: "text", text: "list_proposals status must be all, pending, passed, or rejected." }], isError: true };
6991
+ }
6992
+ try {
6993
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
6994
+ headers: {
6995
+ Authorization: `Bearer ${TOKEN}`,
6996
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
6997
+ }
6998
+ });
6999
+ const text = await r.text();
7000
+ if (!r.ok) {
7001
+ return { content: [{ type: "text", text: `list_proposals failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
7002
+ }
7003
+ const body = JSON.parse(text);
7004
+ let proposals = (Array.isArray(body?.proposals) ? body.proposals : []).map(sanitizeProposalItem).filter(Boolean);
7005
+ if (statusFilter !== "all") {
7006
+ proposals = proposals.filter((p) => p.status === statusFilter);
7007
+ }
7008
+ return { content: [{ type: "text", text: JSON.stringify({ channel_id: chatId, count: proposals.length, proposals, untrusted: true }) }] };
7009
+ } catch (e) {
7010
+ return { content: [{ type: "text", text: `list_proposals error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
7011
+ }
7012
+ });
7013
+ HANDLERS.set("propose", async (args) => {
7014
+ const { chat_id, title, content, code_diff, consensus_rule, expires_at } = args || {};
7015
+ const chatId = typeof chat_id === "string" ? chat_id.trim() : "";
7016
+ if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || typeof title !== "string" || !title.trim() || typeof content !== "string") {
7017
+ return { content: [{ type: "text", text: "Error: chat_id, non-empty title, and content (strings) required" }], isError: true };
7018
+ }
7019
+ const rule = consensus_rule || "majority";
7020
+ if (!["majority", "super_majority", "unanimous"].includes(rule)) {
7021
+ return { content: [{ type: "text", text: "Error: consensus_rule must be majority, super_majority, or unanimous" }], isError: true };
7022
+ }
7023
+ const proposalId = crypto.randomUUID();
7024
+ const effectiveExpiresAt = typeof expires_at === "string" && expires_at.trim() ? expires_at.trim() : new Date(Date.now() + 86400000).toISOString();
7025
+ if (TOKEN) {
7026
+ try {
7027
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals`, {
7028
+ method: "POST",
7029
+ headers: {
7030
+ Authorization: `Bearer ${TOKEN}`,
7031
+ "Content-Type": "application/json",
7032
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
7033
+ },
7034
+ body: JSON.stringify({
7035
+ id: proposalId,
7036
+ ...AGENT_ID ? { sender_id: AGENT_ID } : {},
7037
+ title,
7038
+ content,
7039
+ ...typeof code_diff === "string" ? { code_diff } : {},
7040
+ consensus_rule: rule,
7041
+ expires_at: effectiveExpiresAt
7042
+ })
7043
+ });
7044
+ if (r.ok) {
7045
+ const data = await r.json();
7046
+ const proposal = sanitizeProposalItem(data?.proposal ?? data);
7047
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal }) }] };
7048
+ }
7049
+ if (r.status !== 404 && r.status !== 405 && r.status !== 501) {
7050
+ const errText = await r.text();
7051
+ return { content: [{ type: "text", text: `propose failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
7052
+ }
7053
+ } catch {}
7054
+ }
4772
7055
  if (ws && ws.readyState === WebSocket.OPEN) {
4773
7056
  ws.send(JSON.stringify({
4774
- type: "typing",
4775
- channel_id: chat_id,
7057
+ type: "proposal",
7058
+ id: proposalId,
7059
+ channel_id: chatId,
4776
7060
  sender_id: AGENT_ID,
4777
- cross_pod: true
7061
+ title,
7062
+ content,
7063
+ code_diff,
7064
+ consensus_rule: rule,
7065
+ expires_at: effectiveExpiresAt,
7066
+ timestamp: new Date().toISOString()
4778
7067
  }));
7068
+ return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject \u2014 verify via next inbound event` }] };
4779
7069
  }
4780
- return { content: [{ type: "text", text: "Typing indicator dispatched" }] };
7070
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
4781
7071
  });
4782
- HANDLERS.set("okr_reparent_objective", async (args) => {
4783
- const { objective_id, parent_id } = args || {};
4784
- if (!objective_id) {
4785
- return { content: [{ type: "text", text: "okr_reparent_objective needs objective_id." }], isError: true };
7072
+ HANDLERS.set("vote", async (args) => {
7073
+ const { chat_id, channel_id, proposal_id, decision, reason } = args || {};
7074
+ if (typeof proposal_id !== "string" || !proposal_id.trim() || typeof decision !== "string") {
7075
+ return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }], isError: true };
7076
+ }
7077
+ if (!["approve", "reject", "abstain"].includes(decision)) {
7078
+ return { content: [{ type: "text", text: "Error: decision must be approve, reject, or abstain" }], isError: true };
7079
+ }
7080
+ const chatId = typeof chat_id === "string" && chat_id.trim() ? chat_id.trim() : typeof channel_id === "string" && channel_id.trim() ? channel_id.trim() : "";
7081
+ if (chatId && !/[\x00-\x1f\x7f]/.test(chatId) && TOKEN) {
7082
+ try {
7083
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals/${encodeURIComponent(proposal_id.trim())}/votes`, {
7084
+ method: "POST",
7085
+ headers: {
7086
+ Authorization: `Bearer ${TOKEN}`,
7087
+ "Content-Type": "application/json",
7088
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
7089
+ },
7090
+ body: JSON.stringify({
7091
+ ...AGENT_ID ? { voter_id: AGENT_ID } : {},
7092
+ decision,
7093
+ ...typeof reason === "string" ? { reason } : {}
7094
+ })
7095
+ });
7096
+ if (r.ok) {
7097
+ const data = await r.json();
7098
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal_id: data?.proposal_id ?? proposal_id.trim(), vote_result: data?.vote_result }) }] };
7099
+ }
7100
+ const errText = await r.text();
7101
+ const isProposal404 = r.status === 404 && /proposal not found|channel not found/i.test(errText);
7102
+ if (r.status !== 404 && r.status !== 405 && r.status !== 501 || isProposal404) {
7103
+ return { content: [{ type: "text", text: `vote failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
7104
+ }
7105
+ } catch {}
4786
7106
  }
4787
- if (!(args && typeof args === "object" && ("parent_id" in args))) {
4788
- 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 };
7107
+ if (ws && ws.readyState === WebSocket.OPEN) {
7108
+ ws.send(JSON.stringify({
7109
+ type: "vote",
7110
+ proposal_id: proposal_id.trim(),
7111
+ voter_id: AGENT_ID,
7112
+ voter_type: "agent",
7113
+ decision,
7114
+ reason
7115
+ }));
7116
+ return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.trim().slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
4789
7117
  }
7118
+ return { content: [{ type: "text", text: "Not connected" }], isError: true };
7119
+ });
7120
+ HANDLERS.set("list_channels", async (args) => {
7121
+ const { query, limit = 50 } = args || {};
7122
+ const clamped = Math.max(1, Math.min(Number(limit) || 50, 500));
7123
+ const qs = new URLSearchParams({ limit: String(clamped) });
7124
+ if (typeof query === "string" && query.trim())
7125
+ qs.set("q", query.trim());
4790
7126
  try {
4791
- const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/parent`, {
4792
- method: "PATCH",
4793
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
4794
- body: JSON.stringify({ parent_id: parent_id ?? null })
4795
- });
4796
- const text = await r.text();
4797
- if (!r.ok) {
4798
- return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
7127
+ const r = await apiFetch(`${REST_URL}/api/channels/discover?${qs.toString()}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
7128
+ if (r.ok) {
7129
+ const data = await r.json();
7130
+ const channels = data.channels || [];
7131
+ if (channels.length === 0)
7132
+ return { content: [{ type: "text", text: "No public channels found." }] };
7133
+ const list = channels.map((ch) => {
7134
+ const onlineBadge = typeof ch.online_agent_count === "number" && ch.online_agent_count > 0 ? `, \uD83D\uDFE2 ${ch.online_agent_count} online` : "";
7135
+ const caps = Array.isArray(ch.capabilities) && ch.capabilities.length > 0 ? ` [${ch.capabilities.slice(0, 6).join(", ")}]` : "";
7136
+ const topic = ch.topic ? ` \u2014 ${redactSecrets(redactParticipantPii(String(ch.topic))).slice(0, 60)}` : "";
7137
+ return `\u2022 ${ch.name || ch.id} (${ch.id}) \u2014 ${ch.member_count || "?"} members${onlineBadge}${caps}${topic}`;
7138
+ }).join(`
7139
+ `);
7140
+ return { content: [{ type: "text", text: `${channels.length} channels:
7141
+ ${list}` }] };
4799
7142
  }
4800
- return { content: [{ type: "text", text: `Reparented: ${text}` }] };
7143
+ return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
4801
7144
  } catch (e) {
4802
- return { content: [{ type: "text", text: `okr_reparent_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
7145
+ return { content: [{ type: "text", text: `Error: ${e}` }] };
4803
7146
  }
4804
7147
  });
4805
7148
  HANDLERS.set("list_my_channels", async (args) => {
@@ -5770,7 +8113,9 @@ var handleToolCall = async (request) => {
5770
8113
  }
5771
8114
  }
5772
8115
  if (name === "list_skills") {
5773
- const { chat_id } = args || {};
8116
+ const { chat_id, active_only } = args || {};
8117
+ const activeOnly = active_only !== false;
8118
+ const activeQuery = activeOnly ? "?active_only=1" : "";
5774
8119
  const out = {
5775
8120
  global_skills: Object.entries(GLOBAL_SKILLS).map(([skill_id, skill]) => ({
5776
8121
  skill_id,
@@ -5781,27 +8126,111 @@ var handleToolCall = async (request) => {
5781
8126
  };
5782
8127
  if (chat_id) {
5783
8128
  try {
5784
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs`, {
8129
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${activeQuery}`, {
5785
8130
  headers: { Authorization: `Bearer ${TOKEN}` }
5786
8131
  });
5787
- if (r.ok)
5788
- out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text())).filter(isSkillDoc).map(compactSkillDoc);
5789
- else
8132
+ if (r.ok) {
8133
+ out.channel_skills = extractChannelDocsPayload(JSON.parse(await r.text())).filter(isSkillDoc).filter((d) => !activeOnly || !isArchivedSkillOrDoc(d)).map(compactSkillDoc);
8134
+ } else {
5790
8135
  out.channel_skills_error = `failed (${r.status})`;
8136
+ }
5791
8137
  } catch (e) {
5792
8138
  out.channel_skills_error = `network/parse error: ${String(e?.message || e).slice(0, 120)}`;
5793
8139
  }
5794
8140
  }
5795
8141
  try {
5796
- const pr = await apiFetch(`${REST_URL}/api/skills`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5797
- if (pr.ok)
5798
- out.personal_skills = JSON.parse(await pr.text()).skills || [];
8142
+ const pr = await apiFetch(`${REST_URL}/api/skills${activeQuery}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
8143
+ if (pr.ok) {
8144
+ const rawSkills = JSON.parse(await pr.text()).skills || [];
8145
+ out.personal_skills = rawSkills.filter((s) => !activeOnly || !isArchivedSkillOrDoc(s));
8146
+ } else {
8147
+ out.personal_skills_error = `failed (${pr.status})`;
8148
+ }
5799
8149
  } catch {}
5800
8150
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
5801
8151
  }
5802
8152
  if (name === "load_skill") {
5803
- const { skill_id, chat_id, doc_id } = args || {};
5804
- if (chat_id && doc_id) {
8153
+ const targetCheck = validateLoadSkillInput(args);
8154
+ if (!targetCheck.ok) {
8155
+ return { content: [{ type: "text", text: targetCheck.error }], isError: true };
8156
+ }
8157
+ const target = targetCheck.value;
8158
+ if (target.scope === "personal") {
8159
+ try {
8160
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}`, {
8161
+ headers: { Authorization: `Bearer ${TOKEN}` }
8162
+ });
8163
+ const text = await r.text();
8164
+ if (!r.ok) {
8165
+ return { content: [{ type: "text", text: `load_skill (personal) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
8166
+ }
8167
+ const doc = JSON.parse(text);
8168
+ const body = String(doc?.body_markdown ?? "");
8169
+ const version = doc?.version ?? "?";
8170
+ const title = doc?.title || target.name;
8171
+ const archived = doc?.archived === true || body === "";
8172
+ const parsed = parseSkillFrontmatter(body);
8173
+ const metadata = { ...parsed.metadata || {}, ...doc?.skill_meta || {} };
8174
+ const metaLines = [
8175
+ metadata.name ? `name: ${metadata.name}` : null,
8176
+ metadata.description ? `description: ${metadata.description}` : null,
8177
+ metadata.trigger ? `trigger: ${metadata.trigger}` : null,
8178
+ metadata.argument_hint ?? metadata.argumentHint ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null
8179
+ ].filter(Boolean).join(`
8180
+ `);
8181
+ let revisionsBlock = "";
8182
+ if (target.include_revisions) {
8183
+ const revR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(target.name)}/revisions`, {
8184
+ headers: { Authorization: `Bearer ${TOKEN}` }
8185
+ });
8186
+ if (revR.ok) {
8187
+ const revJson = JSON.parse(await revR.text());
8188
+ revisionsBlock = `
8189
+
8190
+ Revisions:
8191
+ ${JSON.stringify(revJson?.revisions ?? [], null, 2)}`;
8192
+ } else {
8193
+ revisionsBlock = `
8194
+
8195
+ Revisions: fetch failed (${revR.status})`;
8196
+ }
8197
+ }
8198
+ if (archived) {
8199
+ const hint = target.include_revisions ? `Restore by calling save_skill(name="${title}", doc_id="${target.name}", description=..., body=..., if_match_version=${version}).` : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
8200
+ return {
8201
+ content: [{
8202
+ type: "text",
8203
+ text: `[ARCHIVED PERSONAL SKILL "${target.name}" (v${version})]
8204
+ ${metaLines ? `
8205
+ Metadata:
8206
+ ${metaLines}
8207
+ ` : ""}
8208
+ ${hint}${revisionsBlock}`
8209
+ }]
8210
+ };
8211
+ }
8212
+ return {
8213
+ content: [{
8214
+ type: "text",
8215
+ text: [
8216
+ `Personal skill loaded: "${target.name}" (v${version}).`,
8217
+ metaLines ? `
8218
+ Metadata:
8219
+ ${metaLines}` : "",
8220
+ `
8221
+ # ${title}
8222
+
8223
+ ${parsed.body}${revisionsBlock}`
8224
+ ].join(`
8225
+ `)
8226
+ }]
8227
+ };
8228
+ } catch (e) {
8229
+ return { content: [{ type: "text", text: `load_skill (personal) network/parse error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
8230
+ }
8231
+ }
8232
+ if (target.scope === "channel") {
8233
+ const { chat_id, doc_id, include_revisions } = target;
5805
8234
  try {
5806
8235
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
5807
8236
  headers: { Authorization: `Bearer ${TOKEN}` }
@@ -5811,11 +8240,13 @@ var handleToolCall = async (request) => {
5811
8240
  return { content: [{ type: "text", text: `load_skill (channel) failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
5812
8241
  }
5813
8242
  const doc = JSON.parse(text);
5814
- const body = doc?.body_markdown ?? doc?.bodyMarkdown ?? "";
8243
+ const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
5815
8244
  const title = doc?.title || doc_id;
5816
8245
  const kind = doc?.kind || "unknown";
5817
8246
  const level = doc?.level ?? "?";
5818
- const parsed = parseSkillFrontmatter(String(body));
8247
+ const version = doc?.version ?? "?";
8248
+ const archived = isArchivedSkillOrDoc(doc);
8249
+ const parsed = parseSkillFrontmatter(body);
5819
8250
  const metadata = { ...parsed.metadata || {}, ...doc?.skill_meta || doc?.skillMeta || {} };
5820
8251
  const metaLines = [
5821
8252
  metadata.name ? `name: ${metadata.name}` : null,
@@ -5824,25 +8255,57 @@ var handleToolCall = async (request) => {
5824
8255
  metadata.argument_hint ?? metadata.argumentHint ? `argument-hint: ${metadata.argument_hint ?? metadata.argumentHint}` : null
5825
8256
  ].filter(Boolean).join(`
5826
8257
  `);
8258
+ let revisionsBlock = "";
8259
+ if (include_revisions) {
8260
+ const revR = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
8261
+ headers: { Authorization: `Bearer ${TOKEN}` }
8262
+ });
8263
+ if (revR.ok) {
8264
+ const revJson = JSON.parse(await revR.text());
8265
+ const revs = Array.isArray(revJson) ? revJson : revJson?.revisions ?? [];
8266
+ revisionsBlock = `
8267
+
8268
+ Revisions:
8269
+ ${JSON.stringify(revs, null, 2)}`;
8270
+ } else {
8271
+ revisionsBlock = `
8272
+
8273
+ Revisions: fetch failed (${revR.status})`;
8274
+ }
8275
+ }
8276
+ if (archived) {
8277
+ const hint = include_revisions ? `Restore by calling save_skill(chat_id="${chat_id}", doc_id="${doc_id}", name=..., description=..., body=..., if_match_version=${version}).` : `Pass include_revisions=true to inspect prior snapshots for CAS restore (if_match_version=${version}).`;
8278
+ return {
8279
+ content: [{
8280
+ type: "text",
8281
+ text: `[ARCHIVED CHANNEL SKILL ${chat_id}/${doc_id} (L${level}, v${version})]
8282
+ ${metaLines ? `
8283
+ Metadata:
8284
+ ${metaLines}
8285
+ ` : ""}
8286
+ ${hint}${revisionsBlock}`
8287
+ }]
8288
+ };
8289
+ }
5827
8290
  if (!String(kind).toLowerCase().includes("skill") && !String(doc_id).toLowerCase().includes("skill")) {
5828
8291
  return { content: [{ type: "text", text: `Loaded channel doc "${doc_id}" as requested, but it is not marked kind=skill.
5829
8292
 
5830
8293
  # ${title}
5831
8294
 
5832
- ${parsed.body}` }] };
8295
+ ${parsed.body}${revisionsBlock}` }] };
5833
8296
  }
5834
8297
  return {
5835
8298
  content: [{
5836
8299
  type: "text",
5837
8300
  text: [
5838
- `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}).`,
8301
+ `Channel-specific skill loaded from ${chat_id}/${doc_id} (L${level}, kind=${kind}, v${version}).`,
5839
8302
  metaLines ? `
5840
8303
  Metadata:
5841
8304
  ${metaLines}` : "",
5842
8305
  `
5843
8306
  # ${title}
5844
8307
 
5845
- ${parsed.body}`
8308
+ ${parsed.body}${revisionsBlock}`
5846
8309
  ].join(`
5847
8310
  `)
5848
8311
  }]
@@ -5851,7 +8314,7 @@ ${parsed.body}`
5851
8314
  return { content: [{ type: "text", text: `load_skill (channel) network/parse error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
5852
8315
  }
5853
8316
  }
5854
- const id = skill_id || DEFAULT_GLOBAL_SKILL_ID;
8317
+ const id = target.skill_id || DEFAULT_GLOBAL_SKILL_ID;
5855
8318
  const skill = GLOBAL_SKILLS[id];
5856
8319
  if (!skill) {
5857
8320
  return { content: [{ type: "text", text: `Unknown global skill: ${id}` }], isError: true };
@@ -5865,11 +8328,18 @@ Loaded as global skill "${id}".` }] };
5865
8328
  if (!a.name || !a.body) {
5866
8329
  return { content: [{ type: "text", text: "save_memory needs name (slug) + body (markdown). Optional description (one-line index hook)." }], isError: true };
5867
8330
  }
8331
+ if (a.if_match_version !== undefined && a.if_match_version !== null && (!Number.isSafeInteger(a.if_match_version) || a.if_match_version < 0 || a.if_match_version > 1e6)) {
8332
+ return { content: [{ type: "text", text: "save_memory if_match_version must be an integer in 0..1000000." }], isError: true };
8333
+ }
5868
8334
  try {
5869
8335
  const r = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}`, {
5870
8336
  method: "PUT",
5871
8337
  headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
5872
- body: JSON.stringify({ body_markdown: a.body, description: a.description })
8338
+ body: JSON.stringify({
8339
+ body_markdown: a.body,
8340
+ description: a.description,
8341
+ ...a.if_match_version !== undefined && a.if_match_version !== null ? { if_match_version: a.if_match_version } : {}
8342
+ })
5873
8343
  });
5874
8344
  const text = await r.text();
5875
8345
  if (!r.ok)
@@ -5881,7 +8351,11 @@ Loaded as global skill "${id}".` }] };
5881
8351
  }
5882
8352
  }
5883
8353
  if (name === "load_memory") {
5884
- const a = args || {};
8354
+ const validated = validateLoadMemoryInput(args);
8355
+ if (!validated.ok) {
8356
+ return { content: [{ type: "text", text: validated.error }], isError: true };
8357
+ }
8358
+ const a = validated.value;
5885
8359
  try {
5886
8360
  const path = a.name ? `/api/memory/${encodeURIComponent(a.name)}` : `/api/memory`;
5887
8361
  const r = await apiFetch(`${REST_URL}${path}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
@@ -5890,9 +8364,28 @@ Loaded as global skill "${id}".` }] };
5890
8364
  return { content: [{ type: "text", text: `load_memory failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
5891
8365
  const resp = JSON.parse(text);
5892
8366
  if (a.name) {
8367
+ let revisionsBlock = "";
8368
+ if (a.include_revisions) {
8369
+ const revR = await apiFetch(`${REST_URL}/api/memory/${encodeURIComponent(a.name)}/revisions`, {
8370
+ headers: { Authorization: `Bearer ${TOKEN}` }
8371
+ });
8372
+ if (revR.ok) {
8373
+ const revJson = JSON.parse(await revR.text());
8374
+ const revs = Array.isArray(revJson) ? revJson : revJson?.revisions ?? [];
8375
+ const truncBadge = revJson?.revisions_truncated ? " (truncated)" : "";
8376
+ revisionsBlock = `
8377
+
8378
+ Revisions${truncBadge} (restore via save_memory(name="${resp.name}", body=..., if_match_version=${resp.version})):
8379
+ ${JSON.stringify(revs, null, 2)}`;
8380
+ } else {
8381
+ revisionsBlock = `
8382
+
8383
+ Revisions: fetch failed (${revR.status})`;
8384
+ }
8385
+ }
5893
8386
  return { content: [{ type: "text", text: `# memory: ${resp.name} (v${resp.version})
5894
8387
 
5895
- ${resp.body_markdown || ""}` }] };
8388
+ ${resp.body_markdown || ""}${revisionsBlock}` }] };
5896
8389
  }
5897
8390
  const items = Array.isArray(resp.memories) ? resp.memories : [];
5898
8391
  if (items.length === 0)
@@ -5907,56 +8400,108 @@ ${idx}` }] };
5907
8400
  }
5908
8401
  }
5909
8402
  if (name === "save_skill") {
5910
- const a = args || {};
5911
- if (!a.name || !a.description) {
5912
- 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 };
8403
+ const validated = validateSaveSkillInput(args);
8404
+ if (!validated.ok) {
8405
+ return { content: [{ type: "text", text: validated.error }], isError: true };
5913
8406
  }
5914
- const oneLine = (s) => String(s).replace(/\r?\n/g, " ").slice(0, 480);
5915
- const md = `---
5916
- name: ${oneLine(a.name)}
5917
- description: ${oneLine(a.description)}
5918
- ---
5919
-
5920
- ${a.body || ""}`;
5921
- if (!a.chat_id) {
5922
- 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";
8407
+ const v = validated.value;
8408
+ if (v.scope === "personal") {
8409
+ if (v.mode === "archive") {
8410
+ try {
8411
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
8412
+ method: "DELETE",
8413
+ headers: {
8414
+ Authorization: `Bearer ${TOKEN}`,
8415
+ "If-Match": String(v.if_match_version)
8416
+ }
8417
+ });
8418
+ const text = await r.text();
8419
+ if (!r.ok)
8420
+ return { content: [{ type: "text", text: `save_skill (personal archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
8421
+ const resp = text.trim() ? JSON.parse(text) : {};
8422
+ const nextVer = resp?.version ?? v.if_match_version + 1;
8423
+ return {
8424
+ content: [{
8425
+ type: "text",
8426
+ text: `Archived PERSONAL skill "${v.slug}" (v${nextVer}) \u2014 revision history preserved & active quota freed. Inspect history via load_skill(name="${v.slug}", include_revisions=true).`
8427
+ }]
8428
+ };
8429
+ } catch (e) {
8430
+ return { content: [{ type: "text", text: `save_skill (personal archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
8431
+ }
8432
+ }
5923
8433
  try {
5924
- const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pslug)}`, {
8434
+ const headers = {
8435
+ Authorization: `Bearer ${TOKEN}`,
8436
+ "Content-Type": "application/json",
8437
+ ...v.if_match_version !== undefined ? { "If-Match": String(v.if_match_version) } : {}
8438
+ };
8439
+ const r = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(v.slug)}`, {
5925
8440
  method: "PUT",
5926
- headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
5927
- body: JSON.stringify({ body_markdown: md })
8441
+ headers,
8442
+ body: JSON.stringify({
8443
+ body_markdown: v.body_markdown,
8444
+ ...v.if_match_version !== undefined ? { if_match_version: v.if_match_version } : {}
8445
+ })
5928
8446
  });
5929
8447
  const text = await r.text();
5930
8448
  if (!r.ok)
5931
8449
  return { content: [{ type: "text", text: `save_skill (personal) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
5932
8450
  const resp = JSON.parse(text);
5933
- return { content: [{ type: "text", text: `Saved PERSONAL skill "${a.name}" as "${pslug}" (v${resp.version}) \u2014 shared across all your agents. Pull/refresh: sync_skill(name="${pslug}"); list: list_skills.` }] };
8451
+ return { content: [{ type: "text", text: `Saved PERSONAL skill "${v.name}" as "${v.slug}" (v${resp.version}) \u2014 shared across all your agents. Load: load_skill(name="${v.slug}"); sync: sync_skill(name="${v.slug}"); list: list_skills.` }] };
5934
8452
  } catch (e) {
5935
8453
  return { content: [{ type: "text", text: `save_skill (personal) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
5936
8454
  }
5937
8455
  }
5938
- const slug = String(a.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "skill";
5939
- const docId = a.doc_id && String(a.doc_id).trim() || `skill-${slug}`;
5940
- const level = typeof a.level === "number" && a.level >= 1 && a.level <= 4 ? a.level : 3;
8456
+ if (v.mode === "archive") {
8457
+ try {
8458
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
8459
+ method: "DELETE",
8460
+ headers: {
8461
+ Authorization: `Bearer ${TOKEN}`,
8462
+ "If-Match": String(v.if_match_version)
8463
+ }
8464
+ });
8465
+ const text = await r.text();
8466
+ if (!r.ok) {
8467
+ return { content: [{ type: "text", text: `save_skill (channel archive) failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
8468
+ }
8469
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
8470
+ const parsed = text.trim() ? JSON.parse(text) : null;
8471
+ const nextVer = parsed?.version ?? (Number.isSafeInteger(etagVer) && etagVer >= 1 ? etagVer : v.if_match_version + 1);
8472
+ return {
8473
+ content: [{
8474
+ type: "text",
8475
+ text: `Archived CHANNEL skill ${v.chat_id}/${v.doc_id} (v${nextVer}) \u2014 revision history preserved & active quota freed. Inspect history via load_skill(chat_id="${v.chat_id}", doc_id="${v.doc_id}", include_revisions=true).`
8476
+ }]
8477
+ };
8478
+ } catch (e) {
8479
+ return { content: [{ type: "text", text: `save_skill (channel archive) network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
8480
+ }
8481
+ }
5941
8482
  try {
5942
- let ifMatch = "0";
5943
- const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5944
- if (cur.ok) {
5945
- const curDoc = await cur.json().catch(() => null);
5946
- if (curDoc && curDoc.version != null)
5947
- ifMatch = String(curDoc.version);
8483
+ let ifMatch = v.if_match_version !== undefined ? String(v.if_match_version) : "0";
8484
+ if (v.if_match_version === undefined) {
8485
+ const cur = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
8486
+ headers: { Authorization: `Bearer ${TOKEN}` }
8487
+ });
8488
+ if (cur.ok) {
8489
+ const curDoc = await cur.json().catch(() => null);
8490
+ if (curDoc && curDoc.version != null)
8491
+ ifMatch = String(curDoc.version);
8492
+ }
5948
8493
  }
5949
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(a.chat_id)}/docs/${encodeURIComponent(docId)}`, {
8494
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(v.chat_id)}/docs/${encodeURIComponent(v.doc_id)}`, {
5950
8495
  method: "PUT",
5951
8496
  headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json", "If-Match": ifMatch },
5952
- body: JSON.stringify({ kind: "channel_skill", level, title: a.name, body_markdown: md })
8497
+ body: JSON.stringify({ kind: "channel_skill", level: v.level, title: v.name, body_markdown: v.body_markdown })
5953
8498
  });
5954
8499
  const text = await r.text();
5955
8500
  if (!r.ok) {
5956
8501
  return { content: [{ type: "text", text: `save_skill failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
5957
8502
  }
5958
8503
  const verb = ifMatch === "0" ? "Saved" : "Updated";
5959
- return { content: [{ type: "text", text: `${verb} skill "${a.name}" \u2192 ${a.chat_id}/${docId} (L${level}). Others load it with: load_skill(chat_id="${a.chat_id}", doc_id="${docId}") \u2014 discoverable via list_skills(chat_id="${a.chat_id}").` }] };
8504
+ return { content: [{ type: "text", text: `${verb} skill "${v.name}" \u2192 ${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}") \u2014 discoverable via list_skills(chat_id="${v.chat_id}").` }] };
5960
8505
  } catch (e) {
5961
8506
  return { content: [{ type: "text", text: `save_skill network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
5962
8507
  }
@@ -5967,32 +8512,56 @@ ${a.body || ""}`;
5967
8512
  const cacheDir = a.dir && String(a.dir).trim() || `${home}/.agentchat/skills`;
5968
8513
  const safe = (s) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
5969
8514
  if (a.name && !a.chat_id) {
5970
- const pBase = `${cacheDir}/personal__${safe(a.name)}`;
8515
+ const slugCheck = validatePersonalSkillSlugInput(a.name, "sync_skill");
8516
+ if (!slugCheck.ok) {
8517
+ return { content: [{ type: "text", text: slugCheck.error }], isError: true };
8518
+ }
8519
+ const pSlug = slugCheck.value;
8520
+ const pBase = `${cacheDir}/personal__${safe(pSlug)}`;
5971
8521
  const pMd = `${pBase}.md`;
5972
8522
  const pMeta = `${pBase}.json`;
5973
8523
  try {
5974
8524
  const listR = await apiFetch(`${REST_URL}/api/skills`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5975
8525
  if (!listR.ok)
5976
8526
  return { content: [{ type: "text", text: `sync_skill (personal): list failed (${listR.status})` }], isError: true };
5977
- const meta = (JSON.parse(await listR.text()).skills || []).find((s) => s.name === a.name);
8527
+ const meta = (JSON.parse(await listR.text()).skills || []).find((s) => s.name === pSlug);
5978
8528
  if (!meta)
5979
- return { content: [{ type: "text", text: `sync_skill: personal skill "${a.name}" not found (save it with save_skill \u2014 no chat_id).` }], isError: true };
8529
+ return { content: [{ type: "text", text: `sync_skill: personal skill "${pSlug}" not found (save it with save_skill \u2014 no chat_id).` }], isError: true };
8530
+ if (meta.archived === true) {
8531
+ return {
8532
+ content: [{
8533
+ type: "text",
8534
+ 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).`
8535
+ }],
8536
+ isError: true
8537
+ };
8538
+ }
5980
8539
  const currentVersion = Number(meta.version ?? 0);
5981
8540
  let cachedVersion = null;
5982
8541
  try {
5983
8542
  cachedVersion = Number(JSON.parse(readFileSync11(pMeta, "utf8")).version);
5984
8543
  } catch {}
5985
8544
  if (cachedVersion !== null && cachedVersion === currentVersion) {
5986
- return { content: [{ type: "text", text: `up-to-date: personal skill "${a.name}" v${currentVersion} already at ${pMd} \u2014 no download. Read that file to run it.` }] };
8545
+ return { content: [{ type: "text", text: `up-to-date: personal skill "${pSlug}" v${currentVersion} already at ${pMd} \u2014 no download. Read that file to run it.` }] };
5987
8546
  }
5988
- const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(a.name)}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
8547
+ const bodyR = await apiFetch(`${REST_URL}/api/skills/${encodeURIComponent(pSlug)}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5989
8548
  if (!bodyR.ok)
5990
8549
  return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
5991
8550
  const doc = JSON.parse(await bodyR.text());
8551
+ const body = String(doc?.body_markdown ?? "");
8552
+ if (doc?.archived === true || !body.trim()) {
8553
+ return {
8554
+ content: [{
8555
+ type: "text",
8556
+ text: `sync_skill: personal skill "${pSlug}" is archived; refusing to overwrite local file.`
8557
+ }],
8558
+ isError: true
8559
+ };
8560
+ }
5992
8561
  mkdirSync4(dirname2(pMd), { recursive: true });
5993
- writeFileSync6(pMd, String(doc?.body_markdown ?? ""));
5994
- writeFileSync6(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
5995
- return { content: [{ type: "text", text: `synced personal skill "${a.name}" v${currentVersion} \u2192 ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
8562
+ writeFileSync6(pMd, body);
8563
+ writeFileSync6(pMeta, JSON.stringify({ version: currentVersion, name: pSlug, syncedAt: new Date().toISOString() }));
8564
+ return { content: [{ type: "text", text: `synced personal skill "${pSlug}" v${currentVersion} \u2192 ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
5996
8565
  } catch (e) {
5997
8566
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
5998
8567
  }
@@ -6011,6 +8580,15 @@ ${a.body || ""}`;
6011
8580
  const meta = docs.find((d) => (d?.id ?? d?.doc_id) === a.doc_id);
6012
8581
  if (!meta)
6013
8582
  return { content: [{ type: "text", text: `sync_skill: skill "${a.doc_id}" not found in channel ${a.chat_id}` }], isError: true };
8583
+ if (isArchivedSkillOrDoc(meta)) {
8584
+ return {
8585
+ content: [{
8586
+ type: "text",
8587
+ 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).`
8588
+ }],
8589
+ isError: true
8590
+ };
8591
+ }
6014
8592
  const currentVersion = Number(meta.version ?? 0);
6015
8593
  let cachedVersion = null;
6016
8594
  try {
@@ -6024,6 +8602,15 @@ ${a.body || ""}`;
6024
8602
  return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
6025
8603
  const doc = JSON.parse(await docR.text());
6026
8604
  const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
8605
+ if (isArchivedSkillOrDoc(doc)) {
8606
+ return {
8607
+ content: [{
8608
+ type: "text",
8609
+ text: `sync_skill: channel skill "${a.doc_id}" is archived; refusing to overwrite local file.`
8610
+ }],
8611
+ isError: true
8612
+ };
8613
+ }
6027
8614
  mkdirSync4(dirname2(mdPath), { recursive: true });
6028
8615
  writeFileSync6(mdPath, body);
6029
8616
  writeFileSync6(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
@@ -6353,44 +8940,6 @@ ${results}` }] };
6353
8940
  return { content: [{ type: "text", text: "Search failed" }] };
6354
8941
  }
6355
8942
  }
6356
- if (name === "vote") {
6357
- const { proposal_id, decision, reason } = args;
6358
- if (typeof proposal_id !== "string" || typeof decision !== "string") {
6359
- return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }] };
6360
- }
6361
- if (ws && ws.readyState === WebSocket.OPEN) {
6362
- ws.send(JSON.stringify({
6363
- type: "vote",
6364
- proposal_id,
6365
- voter_id: AGENT_ID,
6366
- voter_type: "agent",
6367
- decision,
6368
- reason
6369
- }));
6370
- return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
6371
- }
6372
- return { content: [{ type: "text", text: "Not connected" }] };
6373
- }
6374
- if (name === "propose") {
6375
- const { chat_id, title, content, code_diff, consensus_rule } = args;
6376
- if (ws && ws.readyState === WebSocket.OPEN) {
6377
- const proposalId = crypto.randomUUID();
6378
- ws.send(JSON.stringify({
6379
- type: "proposal",
6380
- id: proposalId,
6381
- channel_id: chat_id,
6382
- sender_id: AGENT_ID,
6383
- title,
6384
- content,
6385
- code_diff,
6386
- consensus_rule: consensus_rule || "majority",
6387
- expires_at: new Date(Date.now() + 86400000).toISOString(),
6388
- timestamp: new Date().toISOString()
6389
- }));
6390
- return { content: [{ type: "text", text: `Proposal '${title}' dispatched (client-generated ID ${proposalId.slice(0, 8)}); server may reject \u2014 verify via next inbound event` }] };
6391
- }
6392
- return { content: [{ type: "text", text: "Not connected" }] };
6393
- }
6394
8943
  async function fetchMcpChannelContext(chatId) {
6395
8944
  if (!chatId || !TOKEN)
6396
8945
  return null;
@@ -6408,7 +8957,7 @@ ${results}` }] };
6408
8957
  method: "tools/call",
6409
8958
  params: {
6410
8959
  name: "agentschat_get_channel_context",
6411
- arguments: { channel_id: chatId }
8960
+ arguments: { channel_id: chatId, include_briefing: true }
6412
8961
  }
6413
8962
  })
6414
8963
  }, 2500);
@@ -6438,10 +8987,13 @@ ${results}` }] };
6438
8987
  return null;
6439
8988
  }
6440
8989
  };
6441
- const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
8990
+ const [membersData, docsData, okrData, loopsData, personalSkillsData, wakeHealthData, mcpCtx] = await Promise.all([
6442
8991
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
6443
- get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
8992
+ get(`/api/channels/${encodeURIComponent(chatId)}/docs?active_only=1`),
6444
8993
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
8994
+ get(`/api/loops?channel_id=${encodeURIComponent(chatId)}`),
8995
+ get(`/api/skills?active_only=1`),
8996
+ get(`/api/channels/${encodeURIComponent(chatId)}/wake-health`),
6445
8997
  fetchMcpChannelContext(chatId)
6446
8998
  ]);
6447
8999
  const membersReadable = membersData !== null;
@@ -6477,34 +9029,268 @@ ${results}` }] };
6477
9029
  ...typeof m.online === "boolean" ? { online: m.online } : memberIds.length > 0 ? { online: rawOnlineSet.has(String(m.agent_id)) } : {},
6478
9030
  is_self: String(m.agent_id) === AGENT_ID
6479
9031
  }));
6480
- const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
6481
- const skills = allDocs.filter(isSkillDoc).map((d) => ({ doc_id: d.id, title: d.title }));
6482
- const docs = allDocs.filter((d) => !isSkillDoc(d)).slice(0, 10).map((d) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
6483
- const objectives = (okrData?.objectives || []).filter((o) => !o.archived).map((o) => {
6484
- const open = (okrData?.tasks || []).filter((t) => t.objective_id === o.id && t.status !== "done").length;
6485
- return { id: o.id, title: o.title, open_tasks: open };
9032
+ const hasRestDocsPayload = Boolean(docsData && (Array.isArray(docsData) || Array.isArray(docsData.docs) || Array.isArray(docsData.channel_docs)));
9033
+ const docsReadable = hasRestDocsPayload || Array.isArray(mcpCtx?.docs_summary) || Array.isArray(mcpCtx?.skills_summary?.channel_skills);
9034
+ const allDocs = hasRestDocsPayload ? extractChannelDocsPayload(docsData) : Array.isArray(mcpCtx?.docs_summary) ? mcpCtx.docs_summary.map((d) => ({ ...d, id: d?.id ?? d?.doc_id })) : [];
9035
+ const archivedDocIds = new Set(allDocs.filter((d) => isArchivedSkillOrDoc(d) && (d?.id || d?.doc_id)).map((d) => String(d.id ?? d.doc_id)));
9036
+ const activeDocs = allDocs.filter((d) => !isArchivedSkillOrDoc(d));
9037
+ const activeDocById = new Map;
9038
+ for (const d of activeDocs) {
9039
+ const id = d?.id ?? d?.doc_id;
9040
+ if (id)
9041
+ activeDocById.set(String(id), d);
9042
+ }
9043
+ const mcpChannelSkills = Array.isArray(mcpCtx?.skills_summary?.channel_skills) ? mcpCtx.skills_summary.channel_skills.filter((cs) => cs?.doc_id && !archivedDocIds.has(String(cs.doc_id)) && !isArchivedSkillOrDoc(cs)) : [];
9044
+ const mcpSkillByDocId = new Map;
9045
+ for (const cs of mcpChannelSkills) {
9046
+ mcpSkillByDocId.set(String(cs.doc_id), cs);
9047
+ }
9048
+ const formatBriefChannelSkill = (d) => {
9049
+ const docId = String(d?.id ?? d?.doc_id ?? "");
9050
+ const fallback = mcpSkillByDocId.get(docId);
9051
+ const meta = d?.skill_meta || d?.skillMeta || fallback?.skill_meta || {};
9052
+ const version = typeof d?.version === "number" ? d.version : typeof fallback?.version === "number" ? fallback.version : undefined;
9053
+ const argHint = meta.argument_hint ?? meta.argumentHint;
9054
+ return {
9055
+ doc_id: docId,
9056
+ ...d?.title !== undefined ? { title: d.title } : meta.name ? { title: String(meta.name) } : {},
9057
+ ...typeof version === "number" ? { version } : {},
9058
+ ...meta.name ? { name: String(meta.name) } : {},
9059
+ ...meta.description ? { description: String(meta.description) } : {},
9060
+ ...meta.trigger ? { trigger: String(meta.trigger) } : {},
9061
+ ...argHint ? { argument_hint: String(argHint) } : {}
9062
+ };
9063
+ };
9064
+ const seenSkillDocIds = new Set;
9065
+ const skills = activeDocs.filter(isSkillDoc).map((d) => {
9066
+ const entry = formatBriefChannelSkill(d);
9067
+ seenSkillDocIds.add(entry.doc_id);
9068
+ return entry;
9069
+ });
9070
+ if (!hasRestDocsPayload) {
9071
+ for (const cs of mcpChannelSkills) {
9072
+ const docId = String(cs.doc_id);
9073
+ if (seenSkillDocIds.has(docId))
9074
+ continue;
9075
+ seenSkillDocIds.add(docId);
9076
+ skills.push(formatBriefChannelSkill({ doc_id: docId, ...cs }));
9077
+ }
9078
+ }
9079
+ const docs = activeDocs.filter((d) => !isSkillDoc(d)).slice(0, 10).map((d) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
9080
+ const rawPersonalSkills = Array.isArray(personalSkillsData?.skills) ? personalSkillsData.skills : Array.isArray(mcpCtx?.skills_summary?.personal_skills) ? mcpCtx.skills_summary.personal_skills : [];
9081
+ const personalSkills = rawPersonalSkills.filter((s) => s?.name && !isArchivedSkillOrDoc(s)).map((s) => {
9082
+ const meta = s?.skill_meta || s?.skillMeta || {};
9083
+ const desc = s?.description ?? meta.description;
9084
+ const trig = s?.trigger ?? meta.trigger;
9085
+ const argHint = s?.argument_hint ?? s?.argumentHint ?? meta.argument_hint ?? meta.argumentHint;
9086
+ return {
9087
+ name: String(s.name),
9088
+ ...desc ? { description: String(desc) } : {},
9089
+ ...trig ? { trigger: String(trig) } : {},
9090
+ ...argHint ? { argument_hint: String(argHint) } : {},
9091
+ ...typeof s?.version === "number" ? { version: s.version } : {}
9092
+ };
9093
+ });
9094
+ const okrNotConfigured = typeof okrData?.note === "string" && okrData.note.toLowerCase().includes("not configured");
9095
+ const hasRestOkrSnapshot = Boolean(okrData && !okrNotConfigured && (Array.isArray(okrData.objectives) || Array.isArray(okrData.tasks)));
9096
+ const hasMcpOkrSummary = Boolean(mcpCtx?.okr_summary && typeof mcpCtx.okr_summary === "object" && typeof mcpCtx.okr_summary.active_objective_count === "number");
9097
+ const okrReadable = hasRestOkrSnapshot || hasMcpOkrSummary;
9098
+ const activeRawObjectives = (okrData?.objectives || []).filter((o) => !o.archived && o.id && String(o.status || "active").toLowerCase() === "active");
9099
+ let okrSummary = null;
9100
+ if (hasMcpOkrSummary && typeof mcpCtx.okr_summary.doing_for_me_count === "number") {
9101
+ const s = mcpCtx.okr_summary;
9102
+ okrSummary = {
9103
+ active_objective_count: s.active_objective_count,
9104
+ total_task_count: s.total_task_count,
9105
+ ready_for_me_count: s.ready_for_me_count,
9106
+ doing_for_me_count: s.doing_for_me_count,
9107
+ ...typeof s.blocked_for_me_count === "number" ? { blocked_for_me_count: s.blocked_for_me_count } : {},
9108
+ ...typeof s.ready_task_count === "number" ? { ready_task_count: s.ready_task_count } : {},
9109
+ ...typeof s.doing_task_count === "number" ? { doing_task_count: s.doing_task_count } : {},
9110
+ ...typeof s.blocked_task_count === "number" ? { blocked_task_count: s.blocked_task_count } : {}
9111
+ };
9112
+ } else if (hasRestOkrSnapshot) {
9113
+ const archivedObjIds = new Set((okrData?.objectives || []).filter((o) => o?.archived && o?.id).map((o) => String(o.id)));
9114
+ const snapshotTasks = (Array.isArray(okrData?.tasks) ? okrData.tasks : []).filter((t) => t && typeof t.id === "string" && !archivedObjIds.has(String(t.objective_id || "")));
9115
+ const taskStatusById = new Map;
9116
+ for (const t of snapshotTasks)
9117
+ taskStatusById.set(String(t.id), String(t.status || "todo"));
9118
+ const isTaskReady = (t) => {
9119
+ if (String(t.status || "todo") !== "todo")
9120
+ return false;
9121
+ if (Array.isArray(t.unresolved_depends_on))
9122
+ return t.unresolved_depends_on.length === 0;
9123
+ if (typeof t.ready === "boolean")
9124
+ return t.ready;
9125
+ const deps = Array.isArray(t.depends_on) ? t.depends_on.filter((d) => typeof d === "string" && d.length > 0) : [];
9126
+ return deps.every((depId) => taskStatusById.get(depId) === "done");
9127
+ };
9128
+ const isMine = (t) => Boolean(AGENT_ID && t?.assignee === AGENT_ID);
9129
+ okrSummary = {
9130
+ active_objective_count: activeRawObjectives.length,
9131
+ total_task_count: snapshotTasks.length,
9132
+ ready_for_me_count: snapshotTasks.filter((t) => isMine(t) && isTaskReady(t)).length,
9133
+ doing_for_me_count: snapshotTasks.filter((t) => isMine(t) && t.status === "doing").length,
9134
+ blocked_for_me_count: snapshotTasks.filter((t) => isMine(t) && t.status === "blocked").length,
9135
+ ready_task_count: snapshotTasks.filter((t) => isTaskReady(t)).length,
9136
+ doing_task_count: snapshotTasks.filter((t) => t.status === "doing").length,
9137
+ blocked_task_count: snapshotTasks.filter((t) => t.status === "blocked").length
9138
+ };
9139
+ } else if (hasMcpOkrSummary) {
9140
+ const s = mcpCtx.okr_summary;
9141
+ okrSummary = {
9142
+ active_objective_count: s.active_objective_count,
9143
+ total_task_count: s.total_task_count,
9144
+ ready_for_me_count: s.ready_for_me_count
9145
+ };
9146
+ }
9147
+ const visibleObjectiveIdSet = new Set(activeRawObjectives.map((o) => String(o.id)));
9148
+ const snapshotLoopSummary = okrData?.loop_summary && typeof okrData.loop_summary === "object" ? okrData.loop_summary : null;
9149
+ const hasSnapshotLoopSummary = Boolean(snapshotLoopSummary && (Array.isArray(snapshotLoopSummary.okr_wake_objective_ids) || Array.isArray(snapshotLoopSummary.okr_watch_objective_ids) || Array.isArray(snapshotLoopSummary.unarmed_objective_ids)));
9150
+ const hasMcpLoopSummary = Boolean(mcpCtx?.loop_summary && typeof mcpCtx.loop_summary === "object");
9151
+ const hasRestLoopsArray = Array.isArray(loopsData?.loops);
9152
+ const loopCoverageKnown = hasMcpLoopSummary || hasSnapshotLoopSummary || hasRestLoopsArray;
9153
+ const wakeSet = new Set;
9154
+ const watchSet = new Set;
9155
+ for (const summarySource of [mcpCtx?.loop_summary, snapshotLoopSummary]) {
9156
+ if (!summarySource)
9157
+ continue;
9158
+ for (const rawId of summarySource.okr_wake_objective_ids || []) {
9159
+ const id = String(rawId || "");
9160
+ if (visibleObjectiveIdSet.has(id))
9161
+ wakeSet.add(id);
9162
+ }
9163
+ for (const rawId of summarySource.okr_watch_objective_ids || []) {
9164
+ const id = String(rawId || "");
9165
+ if (visibleObjectiveIdSet.has(id))
9166
+ watchSet.add(id);
9167
+ }
9168
+ }
9169
+ const activeRestLoops = hasRestLoopsArray ? loopsData.loops.filter((l) => l && l.paused !== true && l.status !== "paused" && l.paused_at == null) : [];
9170
+ for (const l of activeRestLoops) {
9171
+ const objId = typeof l?.objective_id === "string" ? l.objective_id : "";
9172
+ if (!objId || !visibleObjectiveIdSet.has(objId))
9173
+ continue;
9174
+ if (l.mode === "okr_wake")
9175
+ wakeSet.add(objId);
9176
+ else if (l.mode === "okr_watch")
9177
+ watchSet.add(objId);
9178
+ }
9179
+ const objectives = activeRawObjectives.map((o) => {
9180
+ const id = String(o.id);
9181
+ const open = (okrData?.tasks || []).filter((t) => t.objective_id === id && t.status !== "done").length;
9182
+ return {
9183
+ id,
9184
+ title: o.title,
9185
+ open_tasks: open,
9186
+ ...loopCoverageKnown ? {
9187
+ okr_wake_armed: wakeSet.has(id),
9188
+ okr_watch_armed: watchSet.has(id)
9189
+ } : {}
9190
+ };
6486
9191
  });
9192
+ const loopSummary = loopCoverageKnown ? {
9193
+ active_loop_count: typeof mcpCtx?.loop_summary?.active_loop_count === "number" ? mcpCtx.loop_summary.active_loop_count : typeof snapshotLoopSummary?.active_loop_count === "number" ? snapshotLoopSummary.active_loop_count : activeRestLoops.length,
9194
+ ...typeof mcpCtx?.loop_summary?.my_active_loop_count === "number" ? { my_active_loop_count: mcpCtx.loop_summary.my_active_loop_count } : typeof snapshotLoopSummary?.my_active_loop_count === "number" ? { my_active_loop_count: snapshotLoopSummary.my_active_loop_count } : AGENT_ID && hasRestLoopsArray ? { my_active_loop_count: activeRestLoops.filter((l) => l?.agent_id === AGENT_ID).length } : {},
9195
+ okr_wake_objective_ids: [...wakeSet],
9196
+ okr_watch_objective_ids: [...watchSet],
9197
+ unarmed_objective_ids: activeRawObjectives.map((o) => String(o.id)).filter((id) => !wakeSet.has(id))
9198
+ } : null;
9199
+ const activeTaskLinkedDocs = [];
9200
+ const seenTaskDocPair = new Set;
9201
+ for (const t of Array.isArray(okrData?.tasks) ? okrData.tasks : []) {
9202
+ if (!t?.id || t.archived || String(t.status || "todo") === "done")
9203
+ continue;
9204
+ if (t.objective_id && !visibleObjectiveIdSet.has(String(t.objective_id)))
9205
+ continue;
9206
+ const refs = Array.isArray(t.linked_channel_docs) ? t.linked_channel_docs : [];
9207
+ for (const ref of refs) {
9208
+ const docId = typeof ref?.doc_id === "string" ? ref.doc_id.trim() : "";
9209
+ const refCh = typeof ref?.channel_id === "string" ? ref.channel_id.trim() : "";
9210
+ if (!docId || refCh && refCh !== chatId)
9211
+ continue;
9212
+ if (archivedDocIds.has(docId))
9213
+ continue;
9214
+ const pairKey = `${t.id}:${docId}`;
9215
+ if (seenTaskDocPair.has(pairKey))
9216
+ continue;
9217
+ seenTaskDocPair.add(pairKey);
9218
+ const matchedDoc = activeDocById.get(docId);
9219
+ activeTaskLinkedDocs.push({
9220
+ task_id: String(t.id),
9221
+ doc_id: docId,
9222
+ ...matchedDoc?.title ? { title: String(matchedDoc.title) } : {},
9223
+ ...matchedDoc && isSkillDoc(matchedDoc) ? { is_skill: true } : {}
9224
+ });
9225
+ }
9226
+ }
6487
9227
  const toolGroups = TOOL_GROUPS.map((g) => ({
6488
9228
  name: g.name,
6489
9229
  summary: g.summary,
6490
9230
  tool_count: g.tools.length,
6491
9231
  loaded: loadedToolGroups.has(g.name)
6492
9232
  }));
9233
+ const rawWakeSummary = wakeHealthData?.observation_only === true && wakeHealthData?.counts ? {
9234
+ observation_only: true,
9235
+ counts: wakeHealthData.counts,
9236
+ attention_agents: Array.isArray(wakeHealthData.agents) ? wakeHealthData.agents : []
9237
+ } : mcpCtx?.wake_health_summary?.observation_only === true && mcpCtx?.wake_health_summary?.counts ? {
9238
+ observation_only: true,
9239
+ counts: mcpCtx.wake_health_summary.counts,
9240
+ attention_agents: Array.isArray(mcpCtx.wake_health_summary.attention_agents) ? mcpCtx.wake_health_summary.attention_agents : []
9241
+ } : null;
9242
+ const wakeHealthSummary = rawWakeSummary && typeof rawWakeSummary.counts?.total_cloud_agents === "number" ? {
9243
+ observation_only: true,
9244
+ counts: {
9245
+ total_cloud_agents: Number(rawWakeSummary.counts.total_cloud_agents) || 0,
9246
+ ok: Number(rawWakeSummary.counts.ok) || 0,
9247
+ auth_required: Number(rawWakeSummary.counts.auth_required) || 0,
9248
+ timeout: Number(rawWakeSummary.counts.timeout) || 0,
9249
+ error: Number(rawWakeSummary.counts.error) || 0,
9250
+ unobserved: Number(rawWakeSummary.counts.unobserved) || 0
9251
+ },
9252
+ attention_agents: rawWakeSummary.attention_agents.filter((a) => {
9253
+ const aid = typeof a?.agent_id === "string" ? a.agent_id.trim() : "";
9254
+ if (!aid || isHumanPiiHandle(aid) || /^(?:ac_|sk-)/i.test(aid))
9255
+ return false;
9256
+ const cloudStatus = String(a?.cloud_status || "active");
9257
+ const wakeStatus = typeof a?.last_wake_status === "string" ? a.last_wake_status : "";
9258
+ return cloudStatus !== "active" || wakeStatus === "auth_required" || wakeStatus === "timeout" || wakeStatus === "error";
9259
+ }).slice(0, 16).map((a) => {
9260
+ const rawName = typeof a?.name === "string" ? a.name.trim() : "";
9261
+ const safeName = rawName && !isHumanPiiHandle(rawName) && !/\b(?:ac_|sk-)[A-Za-z0-9_-]{8,}\b/i.test(rawName) ? rawName : undefined;
9262
+ return {
9263
+ agent_id: String(a.agent_id).trim(),
9264
+ ...safeName ? { name: safeName } : {},
9265
+ runtime: String(a.runtime || "unknown"),
9266
+ cloud_status: String(a.cloud_status || "unknown"),
9267
+ ...typeof a.last_wake_status === "string" ? { last_wake_status: a.last_wake_status } : {},
9268
+ ...typeof a.last_wake_at === "string" ? { last_wake_at: a.last_wake_at } : {}
9269
+ };
9270
+ })
9271
+ } : null;
6493
9272
  return JSON.stringify({
6494
9273
  channel: chatId,
6495
9274
  ...mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {},
6496
9275
  ...mcpCtx?.channel?.topic ? { topic: String(mcpCtx.channel.topic) } : {},
6497
9276
  members: membersReadable ? { total: memberIds.length, online } : { total: null, note: "roster unreadable \u2014 you are likely not a member of this channel (or it does not exist)" },
6498
9277
  ...membersReadable ? { agent_peers: agentPeers } : {},
9278
+ okr_readable: okrReadable,
9279
+ docs_readable: docsReadable,
6499
9280
  okr_objectives: objectives,
9281
+ ...okrSummary ? { okr_summary: okrSummary } : {},
9282
+ ...loopSummary ? { loop_summary: loopSummary } : {},
9283
+ ...wakeHealthSummary ? { wake_health_summary: wakeHealthSummary } : {},
6500
9284
  skills,
9285
+ ...personalSkills.length > 0 ? { personal_skills: personalSkills } : {},
9286
+ ...activeTaskLinkedDocs.length > 0 ? { active_task_linked_docs: activeTaskLinkedDocs } : {},
6501
9287
  docs,
6502
9288
  tool_groups: toolGroups,
6503
9289
  tips: [
6504
9290
  "load_tool_group(name) reveals an extended group's tools (see tool_groups above; loaded:false = not yet active)",
6505
- "load_skill(chat_id, doc_id) activates a channel skill; list_skills(chat_id) lists them",
9291
+ "load_skill(chat_id, doc_id) activates a channel skill; load_skill(name) loads a personal skill; list_skills(chat_id) lists both",
6506
9292
  "okr_list / get_history for deeper context",
6507
- "/loop <interval> <prompt> works in joined groups and owner-agent DMs; keep group follow-ups in that group (okr: prefix = wake mode)"
9293
+ "create_loop(channel_id, mode, ...) (or /loop <interval> <prompt>) arms okr_wake / okr_watch / prompt loops; check loop_summary.unarmed_objective_ids"
6508
9294
  ]
6509
9295
  });
6510
9296
  }
@@ -6780,25 +9566,6 @@ Profile file: ${activeProfileFile ?? (anonymousMode ? "(none \u2014 anonymous, n
6780
9566
  Expected agent (AGENTCHAT_EXPECT_AGENT_ID): ${EXPECTED_AGENT_ID} \u2014 ${pinViolation ? "MISMATCH, write tools refused" : "ok"}` : "";
6781
9567
  return { content: [{ type: "text", text: gateNotice + text + pinLine }] };
6782
9568
  }
6783
- if (name === "list_channels") {
6784
- const { limit = 50 } = args;
6785
- try {
6786
- const r = await apiFetch(`${REST_URL}/api/channels/discover?limit=${Math.max(1, Math.min(Number(limit) || 50, 500))}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
6787
- if (r.ok) {
6788
- const data = await r.json();
6789
- const channels = data.channels || [];
6790
- if (channels.length === 0)
6791
- return { content: [{ type: "text", text: "No public channels found." }] };
6792
- const list = channels.map((ch) => `\u2022 ${ch.name || ch.id} (${ch.id}) \u2014 ${ch.member_count || "?"} members${ch.topic ? ` \u2014 ${ch.topic.slice(0, 60)}` : ""}`).join(`
6793
- `);
6794
- return { content: [{ type: "text", text: `${channels.length} channels:
6795
- ${list}` }] };
6796
- }
6797
- return { content: [{ type: "text", text: `Failed to list channels (${r.status})` }] };
6798
- } catch (e) {
6799
- return { content: [{ type: "text", text: `Error: ${e}` }] };
6800
- }
6801
- }
6802
9569
  if (name === "find_dm") {
6803
9570
  const { target_agent_id } = args;
6804
9571
  if (!target_agent_id || typeof target_agent_id !== "string") {
@@ -6838,18 +9605,47 @@ ${list}` }] };
6838
9605
  }
6839
9606
  }
6840
9607
  if (name === "list_loops") {
9608
+ const checked = validateListLoopsInput(args);
9609
+ if (!checked.ok) {
9610
+ return { content: [{ type: "text", text: checked.error }], isError: true };
9611
+ }
6841
9612
  try {
6842
9613
  const r = await apiFetch(`${REST_URL}/api/loops/mine`, { headers: { Authorization: `Bearer ${TOKEN}` } });
6843
9614
  if (!r.ok)
6844
9615
  return { content: [{ type: "text", text: `Failed (${r.status})` }] };
6845
9616
  const data = await r.json();
6846
- const loops = Array.isArray(data?.loops) ? data.loops : [];
6847
- if (loops.length === 0)
6848
- return { content: [{ type: "text", text: "No loops registered for you." }] };
9617
+ const rawLoops = Array.isArray(data?.loops) ? data.loops : [];
9618
+ const hasFilter = Boolean(checked.value.channel_id || checked.value.status || checked.value.mode || checked.value.objective_id);
9619
+ const loops = rawLoops.filter((l) => {
9620
+ if (!l)
9621
+ return false;
9622
+ if (checked.value.channel_id && l.channel_id !== checked.value.channel_id)
9623
+ return false;
9624
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
9625
+ if (checked.value.status && (paused ? "paused" : "active") !== checked.value.status)
9626
+ return false;
9627
+ const normMode = l.mode === "okr_wake" || l.mode === "okr_watch" ? l.mode : "prompt";
9628
+ if (checked.value.mode && normMode !== checked.value.mode)
9629
+ return false;
9630
+ if (checked.value.objective_id && l.objective_id !== checked.value.objective_id)
9631
+ return false;
9632
+ return true;
9633
+ });
9634
+ if (loops.length === 0) {
9635
+ return { content: [{ type: "text", text: hasFilter ? "No matching loops found." : "No loops registered for you." }] };
9636
+ }
6849
9637
  const lines = loops.map((l) => {
6850
- const mode = l.mode === "okr_wake" ? `okr_wake \u2192 ${l.objective_id}${Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : ""}` : "static";
9638
+ const targetSuffix = Array.isArray(l.target_agents) && l.target_agents.length ? ` @[${l.target_agents.join(", ")}]` : "";
9639
+ const watchFlags = l.mode === "okr_watch" ? [
9640
+ l.watch_idle ? "+idle" : "",
9641
+ l.watch_supply ? "+supply" : "",
9642
+ typeof l.stall_minutes === "number" ? `+stall=${l.stall_minutes}m` : ""
9643
+ ].filter(Boolean).join("") : "";
9644
+ const mode = l.mode === "okr_wake" ? `okr_wake \u2192 ${l.objective_id}${targetSuffix}` : l.mode === "okr_watch" ? `okr_watch${watchFlags ? `(${watchFlags})` : ""} \u2192 ${l.objective_id}${targetSuffix}` : `static${targetSuffix}`;
9645
+ const paused = l.paused === true || l.status === "paused" || l.paused_at != null;
6851
9646
  const nextIn = typeof l.next_tick_ms === "number" ? Math.max(0, Math.round((l.next_tick_ms - Date.now()) / 60000)) : "?";
6852
- return `\u2022 ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | next ~${nextIn}m`;
9647
+ const state = paused ? "paused" : `${l.status || "active"} | next ~${nextIn}m`;
9648
+ return `\u2022 ${l.loop_id} | ch ${String(l.channel_id).slice(0, 16)} | every ${Math.round(l.interval_ms / 60000)}m | ${mode} | ${state}`;
6853
9649
  }).join(`
6854
9650
  `);
6855
9651
  return { content: [{ type: "text", text: `${loops.length} loop(s):
@@ -7018,14 +9814,16 @@ ${list}` }] };
7018
9814
  return await handleProfileSwitchOrConnect(args);
7019
9815
  }
7020
9816
  if (name === "list_channel_docs") {
7021
- const { chat_id, level } = args;
7022
- const qs = new URLSearchParams;
7023
- const normalizedLevel = normalizeChannelDocLevel(level);
7024
- if (level !== undefined && normalizedLevel === null) {
7025
- return { content: [{ type: "text", text: "list_channel_docs failed: level must be 1|2|3|4" }], isError: true };
9817
+ const check = validateListChannelDocsInput(args);
9818
+ if (!check.ok) {
9819
+ return { content: [{ type: "text", text: check.error }], isError: true };
7026
9820
  }
7027
- if (normalizedLevel !== null)
9821
+ const { chat_id, level: normalizedLevel, active_only } = check.value;
9822
+ const qs = new URLSearchParams;
9823
+ if (normalizedLevel !== undefined)
7028
9824
  qs.set("level", String(normalizedLevel));
9825
+ if (active_only === true)
9826
+ qs.set("active_only", "1");
7029
9827
  const url = `${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs${qs.toString() ? `?${qs}` : ""}`;
7030
9828
  try {
7031
9829
  const r = await apiFetch(url, { headers: { Authorization: `Bearer ${TOKEN}` } });
@@ -7039,9 +9837,17 @@ ${list}` }] };
7039
9837
  }
7040
9838
  }
7041
9839
  if (name === "get_channel_doc") {
7042
- const { chat_id, doc_id } = args;
9840
+ const { chat_id, doc_id } = args ?? {};
9841
+ const listCheck = validateListChannelDocsInput({ chat_id });
9842
+ if (!listCheck.ok) {
9843
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "get_channel_doc") }], isError: true };
9844
+ }
9845
+ const docCheck = validateChannelDocIdInput(doc_id, "get_channel_doc");
9846
+ if (!docCheck.ok) {
9847
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
9848
+ }
7043
9849
  try {
7044
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
9850
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}`, {
7045
9851
  headers: { Authorization: `Bearer ${TOKEN}` }
7046
9852
  });
7047
9853
  const text = await r.text();
@@ -7054,34 +9860,96 @@ ${list}` }] };
7054
9860
  }
7055
9861
  }
7056
9862
  if (name === "upsert_channel_doc") {
7057
- const { chat_id, doc_id, title, kind, level, body_markdown, expected_version } = args;
7058
- const normalizedLevel = normalizeChannelDocLevel(level);
7059
- if (normalizedLevel === null) {
7060
- return { content: [{ type: "text", text: "upsert_channel_doc failed: level must be 1|2|3|4" }], isError: true };
9863
+ const check = validateUpsertChannelDocInput(args);
9864
+ if (!check.ok) {
9865
+ return { content: [{ type: "text", text: check.error }], isError: true };
7061
9866
  }
9867
+ const parsed = check.value;
7062
9868
  try {
7063
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
9869
+ const r = parsed.mode === "archive" ? await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
9870
+ method: "DELETE",
9871
+ headers: {
9872
+ Authorization: `Bearer ${TOKEN}`,
9873
+ "If-Match": String(parsed.expected_version)
9874
+ }
9875
+ }) : await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(parsed.chat_id)}/docs/${encodeURIComponent(parsed.doc_id)}`, {
7064
9876
  method: "PUT",
7065
9877
  headers: {
7066
9878
  "Content-Type": "application/json",
7067
9879
  Authorization: `Bearer ${TOKEN}`,
7068
- "If-Match": String(expected_version)
9880
+ "If-Match": String(parsed.expected_version)
7069
9881
  },
7070
- body: JSON.stringify({ title, kind, level: normalizedLevel, body_markdown })
9882
+ body: JSON.stringify(parsed.body)
7071
9883
  });
7072
9884
  const text = await r.text();
7073
9885
  if (!r.ok) {
7074
9886
  return { content: [{ type: "text", text: `upsert_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
7075
9887
  }
9888
+ if (parsed.mode === "archive" && !text.trim()) {
9889
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
9890
+ return {
9891
+ content: [{
9892
+ type: "text",
9893
+ text: JSON.stringify({
9894
+ ok: true,
9895
+ archived: true,
9896
+ chat_id: parsed.chat_id,
9897
+ doc_id: parsed.doc_id,
9898
+ ...Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}
9899
+ })
9900
+ }]
9901
+ };
9902
+ }
7076
9903
  return { content: [{ type: "text", text }] };
7077
9904
  } catch (e) {
7078
9905
  return { content: [{ type: "text", text: `upsert_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
7079
9906
  }
7080
9907
  }
9908
+ if (name === "archive_channel_doc") {
9909
+ const check = validateArchiveChannelDocInput(args);
9910
+ if (!check.ok) {
9911
+ return { content: [{ type: "text", text: check.error }], isError: true };
9912
+ }
9913
+ const { chat_id, doc_id, expected_version } = check.value;
9914
+ try {
9915
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}`, {
9916
+ method: "DELETE",
9917
+ headers: {
9918
+ Authorization: `Bearer ${TOKEN}`,
9919
+ "If-Match": String(expected_version)
9920
+ }
9921
+ });
9922
+ const text = await r.text();
9923
+ if (!r.ok) {
9924
+ return { content: [{ type: "text", text: `archive_channel_doc failed (${r.status}): ${text.slice(0, 240)}` }], isError: true };
9925
+ }
9926
+ const normalized = text.trim() ? text : (() => {
9927
+ const etagVer = Number((r.headers.get("etag") ?? "").replace(/"/g, ""));
9928
+ return JSON.stringify({
9929
+ ok: true,
9930
+ archived: true,
9931
+ chat_id,
9932
+ doc_id,
9933
+ ...Number.isSafeInteger(etagVer) && etagVer >= 1 ? { version: etagVer } : {}
9934
+ });
9935
+ })();
9936
+ return { content: [{ type: "text", text: normalized }] };
9937
+ } catch (e) {
9938
+ return { content: [{ type: "text", text: `archive_channel_doc network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
9939
+ }
9940
+ }
7081
9941
  if (name === "list_channel_doc_revisions") {
7082
- const { chat_id, doc_id } = args;
9942
+ const { chat_id, doc_id } = args ?? {};
9943
+ const listCheck = validateListChannelDocsInput({ chat_id });
9944
+ if (!listCheck.ok) {
9945
+ return { content: [{ type: "text", text: listCheck.error.replace("list_channel_docs", "list_channel_doc_revisions") }], isError: true };
9946
+ }
9947
+ const docCheck = validateChannelDocIdInput(doc_id, "list_channel_doc_revisions");
9948
+ if (!docCheck.ok) {
9949
+ return { content: [{ type: "text", text: docCheck.error }], isError: true };
9950
+ }
7083
9951
  try {
7084
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/docs/${encodeURIComponent(doc_id)}/revisions`, {
9952
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(listCheck.value.chat_id)}/docs/${encodeURIComponent(docCheck.value)}/revisions`, {
7085
9953
  headers: { Authorization: `Bearer ${TOKEN}` }
7086
9954
  });
7087
9955
  const text = await r.text();
@@ -7126,16 +9994,45 @@ ${list}` }] };
7126
9994
  }
7127
9995
  }
7128
9996
  if (name === "okr_create_objective") {
7129
- const { title, horizon, owner, parent_id, due, discussion_channel_id } = args;
9997
+ const { title, horizon, owner, parent_id, due, discussion_channel_id, narrative, linked_channel_docs } = args;
7130
9998
  const body = { title, horizon };
7131
9999
  if (owner)
7132
10000
  body.owner = owner;
7133
- if (parent_id)
7134
- body.parent_id = parent_id;
10001
+ if (parent_id !== undefined) {
10002
+ const parentCheck = validateOkrParentIdOptionalInput(parent_id);
10003
+ if (!parentCheck.ok) {
10004
+ return { content: [{ type: "text", text: `okr_create_objective invalid parent_id: ${parentCheck.error}` }], isError: true };
10005
+ }
10006
+ if (parentCheck.value)
10007
+ body.parent_id = parentCheck.value;
10008
+ }
7135
10009
  if (due)
7136
10010
  body.due = due;
7137
10011
  if (discussion_channel_id)
7138
10012
  body.discussion_channel_id = discussion_channel_id;
10013
+ if (narrative !== undefined) {
10014
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
10015
+ if (!narCheck.ok) {
10016
+ return { content: [{ type: "text", text: `okr_create_objective invalid narrative: ${narCheck.error}` }], isError: true };
10017
+ }
10018
+ if (narCheck.value)
10019
+ body.narrative = narCheck.value;
10020
+ }
10021
+ if (linked_channel_docs !== undefined) {
10022
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
10023
+ if (!docsCheck.ok) {
10024
+ return { content: [{ type: "text", text: `okr_create_objective invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
10025
+ }
10026
+ if (docsCheck.value.length > 0) {
10027
+ if (!discussion_channel_id || !discussion_channel_id.trim()) {
10028
+ return {
10029
+ content: [{ type: "text", text: "okr_create_objective invalid linked_channel_docs: discussion_channel_id is required when attaching linked_channel_docs" }],
10030
+ isError: true
10031
+ };
10032
+ }
10033
+ body.linked_channel_docs = docsCheck.value;
10034
+ }
10035
+ }
7139
10036
  try {
7140
10037
  const r = await apiFetch(`${REST_URL}/api/okr/objectives`, {
7141
10038
  method: "POST",
@@ -7146,20 +10043,97 @@ ${list}` }] };
7146
10043
  if (!r.ok) {
7147
10044
  return { content: [{ type: "text", text: `okr_create_objective failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
7148
10045
  }
7149
- return { content: [{ type: "text", text: `Created: ${text}` }] };
10046
+ let outText = text;
10047
+ if (discussion_channel_id && !discussion_channel_id.startsWith("dm-") && isSafeLoopIdentifier(discussion_channel_id)) {
10048
+ try {
10049
+ const parsed = JSON.parse(text);
10050
+ const createdObjId = typeof parsed?.objective?.id === "string" ? parsed.objective.id : "";
10051
+ if (parsed && typeof parsed === "object" && /^[A-Za-z0-9_-]{6,80}$/.test(createdObjId)) {
10052
+ outText = JSON.stringify({
10053
+ ...parsed,
10054
+ loop_guard_hint: {
10055
+ okr_wake_armed: false,
10056
+ recommended_tool: "create_loop",
10057
+ recommended_arguments: {
10058
+ channel_id: discussion_channel_id,
10059
+ mode: "okr_wake",
10060
+ interval: "5m",
10061
+ objective_id: createdObjId
10062
+ }
10063
+ }
10064
+ });
10065
+ }
10066
+ } catch {}
10067
+ }
10068
+ return { content: [{ type: "text", text: `Created: ${outText}` }] };
7150
10069
  } catch (e) {
7151
10070
  return { content: [{ type: "text", text: `okr_create_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
7152
10071
  }
7153
10072
  }
10073
+ if (name === "okr_update_objective") {
10074
+ const validated = validateOkrUpdateObjectiveInput(args);
10075
+ if (!validated.ok) {
10076
+ return { content: [{ type: "text", text: `okr_update_objective invalid arguments: ${validated.error}` }], isError: true };
10077
+ }
10078
+ const { objective_id, body } = validated.value;
10079
+ try {
10080
+ const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}`, {
10081
+ method: "PATCH",
10082
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
10083
+ body: JSON.stringify(body)
10084
+ });
10085
+ const text = await r.text();
10086
+ if (!r.ok) {
10087
+ return { content: [{ type: "text", text: `okr_update_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
10088
+ }
10089
+ return { content: [{ type: "text", text: `Updated: ${text}` }] };
10090
+ } catch (e) {
10091
+ return { content: [{ type: "text", text: `okr_update_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
10092
+ }
10093
+ }
7154
10094
  if (name === "okr_add_task") {
7155
- const { objective_id, title, assignee, contributes_to, depends_on, due } = args;
7156
- const body = { title, assignee };
7157
- if (Array.isArray(contributes_to) && contributes_to.length > 0)
7158
- body.contributes_to = contributes_to;
7159
- if (Array.isArray(depends_on) && depends_on.length > 0)
7160
- body.depends_on = depends_on;
7161
- if (due)
7162
- body.due = due;
10095
+ const { objective_id, title, assignee, contributes_to, depends_on, linked_channel_docs, due } = args;
10096
+ const titleCheck = validateOkrTaskTitleInput(title);
10097
+ if (!titleCheck.ok) {
10098
+ return { content: [{ type: "text", text: `okr_add_task invalid title: ${titleCheck.error}` }], isError: true };
10099
+ }
10100
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
10101
+ if (!assigneeCheck.ok) {
10102
+ return { content: [{ type: "text", text: `okr_add_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
10103
+ }
10104
+ const body = { title: titleCheck.value, assignee: assigneeCheck.value };
10105
+ if (contributes_to !== undefined) {
10106
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
10107
+ if (!contribCheck.ok) {
10108
+ return { content: [{ type: "text", text: `okr_add_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
10109
+ }
10110
+ if (contribCheck.value.length > 0)
10111
+ body.contributes_to = contribCheck.value;
10112
+ }
10113
+ if (depends_on !== undefined) {
10114
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on);
10115
+ if (!depsCheck.ok) {
10116
+ return { content: [{ type: "text", text: `okr_add_task invalid depends_on: ${depsCheck.error}` }], isError: true };
10117
+ }
10118
+ if (depsCheck.value.length > 0)
10119
+ body.depends_on = depsCheck.value;
10120
+ }
10121
+ if (linked_channel_docs !== undefined) {
10122
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
10123
+ if (!docsCheck.ok) {
10124
+ return { content: [{ type: "text", text: `okr_add_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
10125
+ }
10126
+ if (docsCheck.value.length > 0)
10127
+ body.linked_channel_docs = docsCheck.value;
10128
+ }
10129
+ if (due !== undefined && due !== null && due !== "") {
10130
+ const dueCheck = validateOkrTaskDueInput(due);
10131
+ if (!dueCheck.ok) {
10132
+ return { content: [{ type: "text", text: `okr_add_task invalid due: ${dueCheck.error}` }], isError: true };
10133
+ }
10134
+ if (dueCheck.value)
10135
+ body.due = dueCheck.value;
10136
+ }
7163
10137
  try {
7164
10138
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/tasks`, {
7165
10139
  method: "POST",
@@ -7176,22 +10150,102 @@ ${list}` }] };
7176
10150
  }
7177
10151
  }
7178
10152
  if (name === "okr_update_task") {
7179
- const { task_id, status, assignee, blocked_reason, blocker_agent, depends_on, due } = args;
10153
+ const {
10154
+ task_id,
10155
+ title,
10156
+ status,
10157
+ assignee,
10158
+ contributes_to,
10159
+ blocked_reason,
10160
+ blocker_agent,
10161
+ depends_on,
10162
+ linked_channel_docs,
10163
+ due,
10164
+ evidence,
10165
+ append_evidence,
10166
+ if_match_updated_at
10167
+ } = args;
10168
+ if (evidence !== undefined && append_evidence !== undefined) {
10169
+ return {
10170
+ content: [{ type: "text", text: "okr_update_task invalid arguments: cannot pass both evidence and append_evidence" }],
10171
+ isError: true
10172
+ };
10173
+ }
7180
10174
  const patch = {};
10175
+ if (title !== undefined) {
10176
+ const titleCheck = validateOkrTaskTitleInput(title);
10177
+ if (!titleCheck.ok) {
10178
+ return { content: [{ type: "text", text: `okr_update_task invalid title: ${titleCheck.error}` }], isError: true };
10179
+ }
10180
+ patch.title = titleCheck.value;
10181
+ }
7181
10182
  if (status)
7182
10183
  patch.status = status;
7183
- if (assignee)
7184
- patch.assignee = assignee;
10184
+ if (assignee !== undefined) {
10185
+ const assigneeCheck = validateOkrTaskAssigneeInput(assignee);
10186
+ if (!assigneeCheck.ok) {
10187
+ return { content: [{ type: "text", text: `okr_update_task invalid assignee: ${assigneeCheck.error}` }], isError: true };
10188
+ }
10189
+ patch.assignee = assigneeCheck.value;
10190
+ }
10191
+ if (contributes_to !== undefined) {
10192
+ const contribCheck = validateOkrTaskContributesToInput(contributes_to);
10193
+ if (!contribCheck.ok) {
10194
+ return { content: [{ type: "text", text: `okr_update_task invalid contributes_to: ${contribCheck.error}` }], isError: true };
10195
+ }
10196
+ patch.contributes_to = contribCheck.value;
10197
+ }
7185
10198
  if (blocked_reason !== undefined)
7186
10199
  patch.blocked_reason = blocked_reason;
7187
10200
  if (blocker_agent !== undefined)
7188
10201
  patch.blocker_agent = blocker_agent;
7189
- if (Array.isArray(depends_on))
7190
- patch.depends_on = depends_on;
7191
- if (due)
7192
- patch.due = due;
10202
+ if (depends_on !== undefined) {
10203
+ const depsCheck = validateOkrTaskDependsOnInput(depends_on, task_id);
10204
+ if (!depsCheck.ok) {
10205
+ return { content: [{ type: "text", text: `okr_update_task invalid depends_on: ${depsCheck.error}` }], isError: true };
10206
+ }
10207
+ patch.depends_on = depsCheck.value;
10208
+ }
10209
+ if (linked_channel_docs !== undefined) {
10210
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs);
10211
+ if (!docsCheck.ok) {
10212
+ return { content: [{ type: "text", text: `okr_update_task invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
10213
+ }
10214
+ patch.linked_channel_docs = docsCheck.value;
10215
+ }
10216
+ if (due !== undefined) {
10217
+ const dueCheck = validateOkrTaskDueInput(due);
10218
+ if (!dueCheck.ok) {
10219
+ return { content: [{ type: "text", text: `okr_update_task invalid due: ${dueCheck.error}` }], isError: true };
10220
+ }
10221
+ patch.due = dueCheck.value;
10222
+ }
10223
+ if (evidence !== undefined) {
10224
+ const evCheck = validateTaskEvidenceInput(evidence);
10225
+ if (!evCheck.ok) {
10226
+ return { content: [{ type: "text", text: `okr_update_task invalid evidence: ${evCheck.error}` }], isError: true };
10227
+ }
10228
+ patch.evidence = evCheck.value;
10229
+ }
10230
+ let validatedAppend = [];
10231
+ if (append_evidence !== undefined) {
10232
+ const appCheck = validateAppendTaskEvidenceInput(append_evidence);
10233
+ if (!appCheck.ok) {
10234
+ return { content: [{ type: "text", text: `okr_update_task invalid append_evidence: ${appCheck.error}` }], isError: true };
10235
+ }
10236
+ validatedAppend = appCheck.value;
10237
+ patch.append_evidence = appCheck.value;
10238
+ }
10239
+ if (if_match_updated_at !== undefined) {
10240
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
10241
+ if (!verCheck.ok) {
10242
+ return { content: [{ type: "text", text: `okr_update_task invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
10243
+ }
10244
+ patch.if_match_updated_at = verCheck.value;
10245
+ }
7193
10246
  try {
7194
- const r = await apiFetch(`${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`, {
10247
+ const targetUrl = `${REST_URL}/api/okr/tasks/${encodeURIComponent(task_id)}`;
10248
+ const r = await apiFetch(targetUrl, {
7195
10249
  method: "PATCH",
7196
10250
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
7197
10251
  body: JSON.stringify(patch)
@@ -7200,7 +10254,50 @@ ${list}` }] };
7200
10254
  if (!r.ok) {
7201
10255
  return { content: [{ type: "text", text: `okr_update_task failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
7202
10256
  }
7203
- return { content: [{ type: "text", text: `Updated: ${text}` }] };
10257
+ let finalText = text;
10258
+ let parsed = null;
10259
+ try {
10260
+ parsed = JSON.parse(text);
10261
+ } catch {}
10262
+ if (validatedAppend.length > 0 && parsed?.ok === true && parsed?.task && !responseIncludesAppendedEvidence(parsed.task, validatedAppend)) {
10263
+ const merged = mergeLegacyTaskEvidence(parsed.task.evidence, validatedAppend);
10264
+ if (!merged.ok) {
10265
+ return {
10266
+ content: [{ type: "text", text: `okr_update_task append_evidence failed: ${merged.error}` }],
10267
+ isError: true
10268
+ };
10269
+ }
10270
+ const fallbackBody = { evidence: merged.value };
10271
+ if (typeof parsed.task.updated_at === "string" && parsed.task.updated_at.trim()) {
10272
+ fallbackBody.if_match_updated_at = parsed.task.updated_at.trim();
10273
+ }
10274
+ const r2 = await apiFetch(targetUrl, {
10275
+ method: "PATCH",
10276
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
10277
+ body: JSON.stringify(fallbackBody)
10278
+ });
10279
+ const text2 = await r2.text();
10280
+ if (!r2.ok) {
10281
+ return { content: [{ type: "text", text: `okr_update_task failed (${r2.status}): ${text2.slice(0, 160)}` }], isError: true };
10282
+ }
10283
+ finalText = text2;
10284
+ parsed = null;
10285
+ try {
10286
+ parsed = JSON.parse(text2);
10287
+ } catch {}
10288
+ }
10289
+ if (patch.status === "done" && parsed?.ok === true && parsed?.task && Array.isArray(parsed.task.contributes_to)) {
10290
+ const krIds = parsed.task.contributes_to.filter((id) => typeof id === "string" && id.trim().length > 0).map((id) => id.trim());
10291
+ if (krIds.length > 0) {
10292
+ parsed.kr_progress_hint = {
10293
+ contributes_to: krIds,
10294
+ recommended_tool: "okr_set_kr_progress",
10295
+ note: `Task marked done; remember to report quantitative progress for linked KR(s): ${krIds.join(", ")}.`
10296
+ };
10297
+ finalText = JSON.stringify(parsed);
10298
+ }
10299
+ }
10300
+ return { content: [{ type: "text", text: `Updated: ${finalText}` }] };
7204
10301
  } catch (e) {
7205
10302
  return { content: [{ type: "text", text: `okr_update_task network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
7206
10303
  }
@@ -7239,12 +10336,11 @@ ${list}` }] };
7239
10336
  }
7240
10337
  }
7241
10338
  if (name === "okr_add_kr") {
7242
- const { objective_id, title, metric_type, current, target, risk_level } = args;
7243
- const body = { title, metric_type, target };
7244
- if (typeof current === "number")
7245
- body.current = current;
7246
- if (risk_level)
7247
- body.risk_level = risk_level;
10339
+ const validated = validateOkrAddKrInput(args);
10340
+ if (!validated.ok) {
10341
+ return { content: [{ type: "text", text: `okr_add_kr invalid arguments: ${validated.error}` }], isError: true };
10342
+ }
10343
+ const { objective_id, body } = validated.value;
7248
10344
  try {
7249
10345
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/krs`, {
7250
10346
  method: "POST",
@@ -7261,12 +10357,16 @@ ${list}` }] };
7261
10357
  }
7262
10358
  }
7263
10359
  if (name === "archive_objective") {
7264
- const { objective_id, completion_summary } = args;
10360
+ const validated = validateOkrArchiveObjectiveInput(args);
10361
+ if (!validated.ok) {
10362
+ return { content: [{ type: "text", text: `archive_objective invalid arguments: ${validated.error}` }], isError: true };
10363
+ }
10364
+ const { objective_id, body } = validated.value;
7265
10365
  try {
7266
10366
  const r = await apiFetch(`${REST_URL}/api/okr/objectives/${encodeURIComponent(objective_id)}/archive`, {
7267
10367
  method: "POST",
7268
10368
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
7269
- body: JSON.stringify(completion_summary !== undefined ? { completion_summary } : {})
10369
+ body: JSON.stringify(body)
7270
10370
  });
7271
10371
  const text = await r.text();
7272
10372
  if (!r.ok) {
@@ -7294,12 +10394,14 @@ ${list}` }] };
7294
10394
  }
7295
10395
  }
7296
10396
  if (name === "okr_set_kr_progress") {
7297
- const { kr_id, current, risk_level } = args;
7298
- const body = { current };
7299
- if (risk_level)
7300
- body.risk_level = risk_level;
10397
+ const validated = validateOkrSetKrProgressInput(args);
10398
+ if (!validated.ok) {
10399
+ return { content: [{ type: "text", text: `okr_set_kr_progress invalid arguments: ${validated.error}` }], isError: true };
10400
+ }
10401
+ const { kr_id, body, useMetadataEndpoint } = validated.value;
10402
+ const pathSuffix = useMetadataEndpoint ? "" : "/progress";
7301
10403
  try {
7302
- const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}/progress`, {
10404
+ const r = await apiFetch(`${REST_URL}/api/okr/krs/${encodeURIComponent(kr_id)}${pathSuffix}`, {
7303
10405
  method: "PATCH",
7304
10406
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
7305
10407
  body: JSON.stringify(body)
@@ -7332,18 +10434,35 @@ ${list}` }] };
7332
10434
  }
7333
10435
  }
7334
10436
  if (name === "okr_set_links") {
7335
- const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs } = args;
10437
+ const { target_type, target_id, narrative, narrative_path, discussion_channel_id, linked_docs, linked_channel_docs, if_match_updated_at } = args;
7336
10438
  const body = {};
7337
- if (narrative !== undefined)
7338
- body.narrative = narrative;
10439
+ if (narrative !== undefined) {
10440
+ const narCheck = validateOkrObjectiveNarrativeInput(narrative);
10441
+ if (!narCheck.ok) {
10442
+ return { content: [{ type: "text", text: `okr_set_links invalid narrative: ${narCheck.error}` }], isError: true };
10443
+ }
10444
+ body.narrative = narCheck.value;
10445
+ }
7339
10446
  if (narrative_path !== undefined)
7340
10447
  body.narrative_path = narrative_path;
7341
10448
  if (discussion_channel_id !== undefined)
7342
10449
  body.discussion_channel_id = discussion_channel_id;
7343
10450
  if (linked_docs !== undefined)
7344
10451
  body.linked_docs = linked_docs;
7345
- if (linked_channel_docs !== undefined)
7346
- body.linked_channel_docs = linked_channel_docs;
10452
+ if (linked_channel_docs !== undefined) {
10453
+ const docsCheck = validateOkrLinkedChannelDocsInput(linked_channel_docs, discussion_channel_id);
10454
+ if (!docsCheck.ok) {
10455
+ return { content: [{ type: "text", text: `okr_set_links invalid linked_channel_docs: ${docsCheck.error}` }], isError: true };
10456
+ }
10457
+ body.linked_channel_docs = docsCheck.value;
10458
+ }
10459
+ if (if_match_updated_at !== undefined && if_match_updated_at !== null) {
10460
+ const verCheck = validateTaskVersionToken(if_match_updated_at);
10461
+ if (!verCheck.ok) {
10462
+ return { content: [{ type: "text", text: `okr_set_links invalid if_match_updated_at: ${verCheck.error}` }], isError: true };
10463
+ }
10464
+ body.if_match_updated_at = verCheck.value;
10465
+ }
7347
10466
  try {
7348
10467
  const r = await apiFetch(`${REST_URL}/api/okr/links/${encodeURIComponent(target_type)}/${encodeURIComponent(target_id)}`, {
7349
10468
  method: "PATCH",
@@ -7378,17 +10497,6 @@ function flushLastSeenMessageTs() {
7378
10497
  flushSlotLastSeenMessageTs(slot);
7379
10498
  }
7380
10499
  }
7381
- function normalizeChannelDocLevel(level) {
7382
- if (typeof level === "number" && Number.isInteger(level) && level >= 1 && level <= 4) {
7383
- return level;
7384
- }
7385
- if (typeof level === "string") {
7386
- const m = level.trim().match(/^(?:L)?([1-4])$/i);
7387
- if (m)
7388
- return Number(m[1]);
7389
- }
7390
- return null;
7391
- }
7392
10500
  function extractChannelDocsPayload(payload) {
7393
10501
  if (Array.isArray(payload))
7394
10502
  return payload;
@@ -7404,13 +10512,30 @@ function isSkillDoc(doc) {
7404
10512
  const title = String(doc?.title || "").toLowerCase();
7405
10513
  return kind === "skill" || kind === "channel_skill" || id.includes("skill") || title.includes("skill");
7406
10514
  }
10515
+ function isArchivedSkillOrDoc(doc) {
10516
+ if (!doc || typeof doc !== "object")
10517
+ return false;
10518
+ if (doc.archived === true)
10519
+ return true;
10520
+ const body = doc.body_markdown ?? doc.bodyMarkdown;
10521
+ if (typeof body === "string")
10522
+ return body === "";
10523
+ const summary = doc.body_summary ?? doc.bodySummary;
10524
+ if (typeof summary === "string" && summary === "" && doc.archived !== false && doc.skill_meta === undefined && doc.skillMeta === undefined) {
10525
+ return true;
10526
+ }
10527
+ return false;
10528
+ }
7407
10529
  function compactSkillDoc(doc) {
7408
10530
  const meta = doc?.skill_meta || doc?.skillMeta || {};
10531
+ const archived = isArchivedSkillOrDoc(doc);
7409
10532
  return {
7410
10533
  doc_id: doc?.id ?? doc?.doc_id,
7411
10534
  title: doc?.title,
7412
10535
  kind: doc?.kind,
7413
10536
  level: doc?.level,
10537
+ ...typeof doc?.version === "number" ? { version: doc.version } : {},
10538
+ ...archived ? { archived: true } : {},
7414
10539
  updated_at: doc?.updatedAt ?? doc?.updated_at,
7415
10540
  name: meta.name,
7416
10541
  description: meta.description,