agentschat-mcp 0.36.18 → 0.36.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +25 -14
  2. package/codex/README.md +2 -2
  3. package/cordis.patch.yml +23 -0
  4. package/dist/codex-bridge.js +10 -9
  5. package/dist/connector.js +3 -2
  6. package/dist/dsh.js +932 -0
  7. package/dist/muse.js +612 -0
  8. package/dist/server.js +1173 -435
  9. package/dsh/README.md +83 -0
  10. package/dsh/identity-ui/README.md +76 -0
  11. package/dsh/identity-ui/client.js +260 -0
  12. package/dsh/identity-ui/cordis.patch.yml +11 -0
  13. package/dsh/identity-ui/index.js +21 -0
  14. package/dsh/identity-ui/package.json +29 -0
  15. package/dsh/inbound-bridge/README.md +84 -0
  16. package/dsh/inbound-bridge/index.js +716 -0
  17. package/dsh/inbound-bridge/package.json +14 -0
  18. package/dsh/src/cli.ts +374 -0
  19. package/dsh/src/patch.ts +117 -0
  20. package/dsh/tests/dsh.test.ts +113 -0
  21. package/muse/README.md +179 -0
  22. package/muse/scripts/ensure-muse-wakes.mjs +108 -0
  23. package/muse/scripts/keepalive-hook.sh +45 -0
  24. package/muse/scripts/muse-wake-receiver.mjs +51 -0
  25. package/muse/scripts/setup-muse-keepalive.sh +68 -0
  26. package/muse/scripts/smoke.mjs +17 -0
  27. package/muse/skills/muse-keepalive.md +95 -0
  28. package/muse/skills/onboarding.md +137 -0
  29. package/muse/src/bridge.ts +83 -0
  30. package/muse/src/cli.ts +155 -0
  31. package/muse/src/client.ts +241 -0
  32. package/muse/src/config.ts +79 -0
  33. package/muse/src/index.ts +10 -0
  34. package/muse/src/policy.ts +68 -0
  35. package/muse/src/types.ts +38 -0
  36. package/muse/src/typing.ts +51 -0
  37. package/muse/src/wake.ts +176 -0
  38. package/muse/tests/bridge.test.mjs +51 -0
  39. package/muse/tests/client.test.mjs +178 -0
  40. package/muse/tests/config.test.mjs +24 -0
  41. package/muse/tests/policy.test.mjs +47 -0
  42. package/muse/tests/typing.test.mjs +26 -0
  43. package/muse/tests/wake.test.mjs +81 -0
  44. package/package.json +17 -3
  45. package/skills/grok-wake-keepalive.md +1 -1
  46. package/skills/onboarding.md +40 -34
  47. package/src/cli.mjs +17 -7
  48. package/src/redact.ts +10 -4
  49. package/src/server.ts +817 -431
  50. package/src/session-bind.ts +325 -12
  51. package/src/session-route.ts +87 -0
  52. package/src/tool-annotations.ts +1 -0
  53. package/src/wake.ts +75 -8
@@ -14,8 +14,8 @@
14
14
  * crashed/closed processes automatically release their lock (never deadlocks).
15
15
  */
16
16
  import { createHash } from "node:crypto";
17
- import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
18
- import { tmpdir } from "node:os";
17
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, unlinkSync } from "node:fs";
18
+ import { homedir, tmpdir } from "node:os";
19
19
  import { join } from "node:path";
20
20
  import { spawnSync } from "node:child_process";
21
21
  import { safeWriteProfile } from "./profile-store.ts";
@@ -23,7 +23,7 @@ import { safeWriteProfile } from "./profile-store.ts";
23
23
  export const DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
24
24
  export const LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
25
25
 
26
- export type HarnessRuntime = "claude-code" | "antigravity" | "zcode" | "codex-bridge" | "custom" | "mcp";
26
+ export type HarnessRuntime = "claude-code" | "antigravity" | "zcode" | "dsh" | "codex-bridge" | "custom" | "mcp";
27
27
 
28
28
  export interface DetectedSession {
29
29
  sessionId: string;
@@ -109,7 +109,12 @@ export function checkAgentLock(opts: {
109
109
  try { unlinkSync(lockFilePath(lockDir, agentId)); } catch {}
110
110
  return { locked: false, stale: true };
111
111
  }
112
- if (record.pid === currentPid) return { locked: false, holder: record };
112
+ if (record.pid === currentPid) {
113
+ if (opts.currentSessionId && record.sessionId && opts.currentSessionId !== record.sessionId) {
114
+ return { locked: true, holder: record };
115
+ }
116
+ return { locked: false, holder: record };
117
+ }
113
118
  if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid) return { locked: false, holder: record };
114
119
  if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
115
120
  return { locked: false, holder: record };
@@ -294,17 +299,11 @@ export function detectRuntimeSession(
294
299
  return { sessionId: zcodeEnvSid, runtime: "zcode", ...(workspacePath ? { workspacePath } : {}) };
295
300
  }
296
301
 
297
- // 3. Antigravity environment variable or parent language_server discovery
302
+ // 3. Antigravity explicit environment variable
298
303
  const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim();
299
304
  if (agySid) {
300
305
  return { sessionId: agySid, runtime: "antigravity" };
301
306
  }
302
- if (env.__CFBundleIdentifier === "com.google.antigravity" || env.AGY_BROWSER_WS_URL) {
303
- const agyHost = discoverAntigravityHost();
304
- if (agyHost && agyHost.openConversations.length === 1) {
305
- return { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
306
- }
307
- }
308
307
 
309
308
  // 4. Claude Code environment variable
310
309
  const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
@@ -319,6 +318,18 @@ export function detectRuntimeSession(
319
318
  return { sessionId: explicitSid, runtime: "custom" };
320
319
  }
321
320
 
321
+ // 6. Antigravity parent language_server discovery (macOS & Linux)
322
+ if (
323
+ env === process.env ||
324
+ env.__CFBundleIdentifier === "com.google.antigravity" ||
325
+ Boolean(env.AGY_BROWSER_WS_URL)
326
+ ) {
327
+ const agyHost = discoverAntigravityHost();
328
+ if (agyHost && agyHost.openConversations.length === 1) {
329
+ return { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
330
+ }
331
+ }
332
+
322
333
  return null;
323
334
  }
324
335
 
@@ -390,7 +401,9 @@ export function discoverAntigravityHost(opts?: {
390
401
  const p = Number(portMatch[1]);
391
402
  if (p > 0 && !ports.includes(p)) ports.push(p);
392
403
  }
393
- const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
404
+ const presMatch =
405
+ line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/) ||
406
+ line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
394
407
  if (presMatch) {
395
408
  const cid = presMatch[1]!;
396
409
  if (!openConversations.includes(cid)) openConversations.push(cid);
@@ -409,3 +422,303 @@ export function discoverAntigravityHost(opts?: {
409
422
  return null;
410
423
  }
411
424
  }
425
+
426
+ /**
427
+ * Identify which Antigravity conversation (`<conversationId>`) just invoked an MCP tool.
428
+ * Immediately before invoking any MCP tool, Antigravity's `language_server` appends a
429
+ * `PLANNER_RESPONSE` JSONL entry containing the tool call (`call_mcp_tool` or
430
+ * `mcp_agentschat_<tool>`) to `<brainDir>/<cid>/.system_generated/logs/transcript.jsonl`.
431
+ */
432
+ export function detectAntigravityCallerSession(opts?: {
433
+ toolName?: string;
434
+ args?: Record<string, unknown> | null;
435
+ brainDir?: string;
436
+ openConversations?: string[];
437
+ nowMs?: number;
438
+ maxAgeMs?: number;
439
+ }): string | null {
440
+ const brainDir =
441
+ opts?.brainDir?.trim() ||
442
+ process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() ||
443
+ join(homedir(), ".gemini", "antigravity", "brain");
444
+ if (!existsSync(brainDir)) return null;
445
+
446
+ const nowMs = opts?.nowMs ?? Date.now();
447
+ const maxAgeMs = opts?.maxAgeMs ?? 30_000;
448
+ const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
449
+
450
+ const candidateSet = new Set<string>();
451
+ for (const cid of opts?.openConversations ?? []) {
452
+ if (uuidRe.test(cid)) candidateSet.add(cid);
453
+ }
454
+ try {
455
+ for (const entry of readdirSync(brainDir)) {
456
+ if (uuidRe.test(entry)) candidateSet.add(entry);
457
+ }
458
+ } catch {}
459
+ if (candidateSet.size === 0) return null;
460
+
461
+ const toolName = opts?.toolName?.trim() || "";
462
+ const argStrings: string[] = [];
463
+ if (opts?.args && typeof opts.args === "object") {
464
+ for (const val of Object.values(opts.args)) {
465
+ if (typeof val === "string") {
466
+ const trimmed = val.trim();
467
+ if (trimmed.length >= 2 && trimmed.length <= 200) {
468
+ argStrings.push(trimmed);
469
+ }
470
+ }
471
+ }
472
+ }
473
+
474
+ let bestCid: string | null = null;
475
+ let bestScore = -1;
476
+ let bestMtime = -1;
477
+ const recentCids: { cid: string; mtimeMs: number }[] = [];
478
+
479
+ for (const cid of candidateSet) {
480
+ const transcriptPath = join(brainDir, cid, ".system_generated", "logs", "transcript.jsonl");
481
+ let st: ReturnType<typeof statSync>;
482
+ try {
483
+ st = statSync(transcriptPath);
484
+ } catch {
485
+ continue;
486
+ }
487
+ if (st.size <= 0 || nowMs - st.mtimeMs > maxAgeMs) continue;
488
+ recentCids.push({ cid, mtimeMs: st.mtimeMs });
489
+
490
+ let tail = "";
491
+ let fd: number | null = null;
492
+ try {
493
+ fd = openSync(transcriptPath, "r");
494
+ const readLen = Math.min(st.size, 16_384);
495
+ const buf = Buffer.allocUnsafe(readLen);
496
+ const bytesRead = readSync(fd, buf, 0, readLen, st.size - readLen);
497
+ tail = buf.toString("utf8", 0, bytesRead);
498
+ } catch {
499
+ continue;
500
+ } finally {
501
+ if (fd !== null) {
502
+ try { closeSync(fd); } catch {}
503
+ }
504
+ }
505
+
506
+ const lines = tail.split(/\r?\n/).filter((l) => l.trim().length > 0);
507
+ for (let i = lines.length - 1; i >= Math.max(0, lines.length - 12); i--) {
508
+ const line = lines[i]!;
509
+ if (!line.includes('"PLANNER_RESPONSE"')) continue;
510
+ let score = 0;
511
+ if (toolName) {
512
+ const hasToolMatch =
513
+ line.includes(`"mcp_agentschat_${toolName}"`) ||
514
+ line.includes(`\\"ToolName\\":\\"${toolName}\\"`) ||
515
+ line.includes(`"ToolName":"\\"${toolName}\\""`) ||
516
+ line.includes(`"ToolName":"${toolName}"`) ||
517
+ line.includes(`"name":"${toolName}"`) ||
518
+ line.includes(`\\"tool_name\\":\\"${toolName}\\"`) ||
519
+ line.includes(`"tool_name":"${toolName}"`);
520
+ if (!hasToolMatch) continue;
521
+ score += 1000;
522
+ } else {
523
+ score += 100;
524
+ }
525
+ if (i === lines.length - 1) score += 50;
526
+ for (const s of argStrings) {
527
+ if (line.includes(s)) score += 200;
528
+ }
529
+ if (score > bestScore || (score === bestScore && st.mtimeMs > bestMtime)) {
530
+ bestScore = score;
531
+ bestMtime = st.mtimeMs;
532
+ bestCid = cid;
533
+ }
534
+ break;
535
+ }
536
+ }
537
+
538
+ if (bestCid) return bestCid;
539
+ if (recentCids.length === 1 && nowMs - recentCids[0]!.mtimeMs <= 5_000) {
540
+ return recentCids[0]!.cid;
541
+ }
542
+ return null;
543
+ }
544
+
545
+ let cachedIsDshHost: { at: number; value: boolean } | null = null;
546
+
547
+ /** Check if this MCP server was spawned by DeepSeek Harness (`dsh`). */
548
+ export function isDshHostProcess(opts?: {
549
+ currentPid?: number;
550
+ env?: Record<string, string | undefined>;
551
+ cacheMs?: number;
552
+ }): boolean {
553
+ const env = opts?.env ?? process.env;
554
+ if (
555
+ env.AGENTSCHAT_DSH_HOME?.trim() ||
556
+ env.DSH_HOME?.trim() ||
557
+ env.AGENTSCHAT_DSH_HEALTH_URL?.trim()
558
+ ) {
559
+ return true;
560
+ }
561
+ const now = Date.now();
562
+ const cacheMs = opts?.cacheMs ?? 15_000;
563
+ if (cachedIsDshHost && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
564
+ try {
565
+ let pid = opts?.currentPid ?? process.pid;
566
+ for (let hop = 0; hop < 4 && pid > 1; hop++) {
567
+ const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "ppid=,command="], {
568
+ encoding: "utf8",
569
+ timeout: 1000,
570
+ });
571
+ if (ps.status !== 0 || !ps.stdout) break;
572
+ const line = ps.stdout.trim().split(/\r?\n/)[0]?.trim() || "";
573
+ const m = line.match(/^(\d+)\s+(.*)$/);
574
+ if (!m) break;
575
+ const ppid = Number(m[1]);
576
+ const cmd = m[2]!;
577
+ if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test"))) break;
578
+ if (cmd.includes("@deepseek-ai") || cmd.includes("/.dsh/") || /\bdsh\b/.test(cmd)) {
579
+ cachedIsDshHost = { at: now, value: true };
580
+ return true;
581
+ }
582
+ pid = ppid;
583
+ }
584
+ } catch {}
585
+ cachedIsDshHost = { at: now, value: false };
586
+ return false;
587
+ }
588
+
589
+ /** mtime of a session directory's log, or 0 when it has none. */
590
+ function sessionDirMtime(dir: string): number {
591
+ let newest = 0;
592
+ for (const file of ["session.v4.jsonl.zstd", "session.v4.jsonl"]) {
593
+ try {
594
+ const mtime = statSync(join(dir, file)).mtimeMs;
595
+ if (mtime > newest) newest = mtime;
596
+ } catch {}
597
+ }
598
+ return newest;
599
+ }
600
+
601
+ /**
602
+ * mtime of `sid`'s session log (`<dshHome>/sessions/<project>/<sid>/…`), or 0.
603
+ *
604
+ * DSH rewrites the log on every durable row, so during a tool call the caller's
605
+ * log is the most recently modified one — the only signal that distinguishes
606
+ * two sessions that are both `running` at the same time.
607
+ */
608
+ function sessionLogMtime(dshHome: string, sid: string): number {
609
+ let projects: string[];
610
+ try {
611
+ projects = readdirSync(join(dshHome, "sessions"));
612
+ } catch {
613
+ return 0;
614
+ }
615
+ let newest = 0;
616
+ for (const project of projects) {
617
+ const mtime = sessionDirMtime(join(dshHome, "sessions", project, sid));
618
+ if (mtime > newest) newest = mtime;
619
+ }
620
+ return newest;
621
+ }
622
+
623
+ /** Newest session log within `maxAgeMs`; the fallback when `/health` is unavailable. */
624
+ function newestSessionLog(dshHome: string, nowMs: number, maxAgeMs: number): string | null {
625
+ const root = join(dshHome, "sessions");
626
+ let projects: string[];
627
+ try {
628
+ projects = readdirSync(root);
629
+ } catch {
630
+ return null;
631
+ }
632
+ let best: { sid: string; mtime: number } | null = null;
633
+ for (const project of projects) {
634
+ let entries: string[];
635
+ try {
636
+ entries = readdirSync(join(root, project));
637
+ } catch {
638
+ continue;
639
+ }
640
+ for (const entry of entries) {
641
+ if (!entry.startsWith("session-")) continue;
642
+ const mtime = sessionDirMtime(join(root, project, entry));
643
+ if (mtime === 0 || nowMs - mtime > maxAgeMs) continue;
644
+ if (best === null || mtime > best.mtime) best = { sid: entry, mtime };
645
+ }
646
+ }
647
+ return best?.sid ?? null;
648
+ }
649
+
650
+ /**
651
+ * Identify the active DeepSeek Harness (`dsh`) session (`session-...`) during a tool call.
652
+ *
653
+ * Primary signal: the local DSH inbound plugin's `/health`, whose `roots[].status`
654
+ * names the session(s) currently mid-turn. Secondary (and the only signal when
655
+ * that plugin is absent): the most recently written session log under
656
+ * `<dshHome>/sessions/`. When several sessions are running, the log mtime decides;
657
+ * otherwise the newest root wins — never the oldest.
658
+ */
659
+ export async function detectDshCallerSession(opts?: {
660
+ dshHome?: string;
661
+ healthUrl?: string;
662
+ env?: Record<string, string | undefined>;
663
+ nowMs?: number;
664
+ fetchImpl?: typeof fetch;
665
+ }): Promise<string | null> {
666
+ const env = opts?.env ?? process.env;
667
+ if (!opts?.dshHome && !opts?.healthUrl && !isDshHostProcess({ env })) {
668
+ return null;
669
+ }
670
+ const dshHome =
671
+ opts?.dshHome?.trim() ||
672
+ env.AGENTSCHAT_DSH_HOME?.trim() ||
673
+ env.DSH_HOME?.trim() ||
674
+ join(homedir(), ".dsh");
675
+ const healthUrl =
676
+ opts?.healthUrl?.trim() ||
677
+ env.AGENTSCHAT_DSH_HEALTH_URL?.trim() ||
678
+ "http://127.0.0.1:8799/health";
679
+ const nowMs = opts?.nowMs ?? Date.now();
680
+
681
+ try {
682
+ const f = opts?.fetchImpl ?? fetch;
683
+ const ctrl = new AbortController();
684
+ const timer = setTimeout(() => ctrl.abort(), 150);
685
+ try {
686
+ const res = await f(healthUrl, { signal: ctrl.signal });
687
+ if (res.ok) {
688
+ const data = (await res.json()) as {
689
+ roots?: Array<{ id?: string; status?: string }>;
690
+ };
691
+ const roots = Array.isArray(data?.roots) ? data.roots : [];
692
+ const running = roots
693
+ .filter((r) => typeof r?.id === "string" && r.id.startsWith("session-") && r.status === "running")
694
+ .map((r) => r.id!);
695
+ if (running.length === 1) return running[0]!;
696
+ if (running.length > 1) {
697
+ // More than one session is mid-turn; the caller is the one that just
698
+ // wrote a row (its session log mtime is the newest). `roots` is
699
+ // oldest-first, so the newest root is the fallback when logs are
700
+ // unavailable — never `running[0]`, which is the *oldest*.
701
+ const ranked = running
702
+ .map((sid) => ({ sid, mtime: sessionLogMtime(dshHome, sid) }))
703
+ .sort((a, b) => b.mtime - a.mtime);
704
+ if (ranked[0]!.mtime > 0 && ranked[0]!.mtime >= ranked[1]!.mtime) return ranked[0]!.sid;
705
+ return running[running.length - 1]!;
706
+ }
707
+ const allValid = roots
708
+ .filter((r) => typeof r?.id === "string" && r.id.startsWith("session-"))
709
+ .map((r) => r.id!);
710
+ if (allValid.length === 1) return allValid[0]!;
711
+ }
712
+ } finally {
713
+ clearTimeout(timer);
714
+ }
715
+ } catch {}
716
+
717
+ // No health endpoint (older/newer DSH, or the inbound plugin is not
718
+ // installed): the same log-mtime signal still identifies the session that
719
+ // just ran a tool call. DSH writes one directory per session under
720
+ // `<dshHome>/sessions/<project>/session-<uuid>/`.
721
+ const newestByLog = newestSessionLog(dshHome, nowMs, 30_000);
722
+ if (newestByLog) return newestByLog;
723
+ return null;
724
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Wake routing for a single-process / single-identity bridge.
3
+ *
4
+ * A wake can only land in a harness Session, but the bridge knows AgentsChat
5
+ * identities, not Session ids. `session-binds.json` is the join: it maps
6
+ * `sessionId -> profileName`, and each profile file carries that identity's
7
+ * `agent_id`. Inverting the pair answers "which Session owns the agent that just
8
+ * received this DM?", so the wake payload can carry an explicit target instead of
9
+ * the receiver guessing "the newest idle Session" — a guess that is wrong whenever
10
+ * an older Session happens to be idle.
11
+ *
12
+ * Deliberately conservative: every missing or malformed piece resolves to
13
+ * `undefined`, which leaves the receiver on its existing fallback. Routing must
14
+ * never turn a delivery problem into a lost message.
15
+ */
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import { homedir } from "node:os";
18
+ import { join } from "node:path";
19
+ import { loadSessionBinds } from "./session-bind.ts";
20
+
21
+ export interface AgentSessionRoute {
22
+ /** Harness session the wake should be delivered to. */
23
+ sessionId: string;
24
+ /** AgentsChat profile bound to that session. */
25
+ profileName: string;
26
+ /** Identity the profile file declares. */
27
+ agentId: string;
28
+ }
29
+
30
+ /** Same config root the MCP server uses for profiles and `session-binds.json`. */
31
+ export function agentschatConfigDir(env: Record<string, string | undefined> = process.env): string {
32
+ return env.AGENTSCHAT_CONFIG_DIR ?? join(homedir(), ".agentschat");
33
+ }
34
+
35
+ /**
36
+ * Resolve a bind entry's profile name to its file.
37
+ *
38
+ * Mirrors the server's nested-first convention (`<configDir>/profiles/<name>.json`)
39
+ * and the flat legacy layout. Only plain profile names resolve — a name that
40
+ * contains a path separator is skipped rather than guessed, because a wrong path
41
+ * would silently route a wake into the wrong identity.
42
+ */
43
+ function profilePathForName(configDir: string, name: string): string | undefined {
44
+ if (!name || name.includes("/") || name.includes("\\")) return undefined;
45
+ const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
46
+ const nested = join(configDir, "profiles", `${base}.json`);
47
+ if (existsSync(nested)) return nested;
48
+ const flat = join(configDir, `${base}.json`);
49
+ return existsSync(flat) ? flat : undefined;
50
+ }
51
+
52
+ function readAgentId(path: string): string | undefined {
53
+ try {
54
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as { agent_id?: unknown };
55
+ return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
56
+ } catch {
57
+ return undefined;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Session currently bound to `agentId`, or `undefined` when unknown.
63
+ *
64
+ * The last matching bind wins: binds are appended as sessions are bound, and
65
+ * re-binding an existing session keeps its position, so the final match is the
66
+ * most recently established route for this identity.
67
+ */
68
+ export function resolveSessionForAgent(
69
+ agentId: string | null | undefined,
70
+ opts: { configDir?: string; env?: Record<string, string | undefined> } = {},
71
+ ): AgentSessionRoute | undefined {
72
+ if (typeof agentId !== "string" || agentId.length === 0) return undefined;
73
+ const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
74
+ let binds: Record<string, string>;
75
+ try {
76
+ binds = loadSessionBinds(configDir);
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
81
+ const path = profilePathForName(configDir, profileName);
82
+ if (path === undefined) continue;
83
+ if (readAgentId(path) !== agentId) continue;
84
+ return { sessionId, profileName, agentId };
85
+ }
86
+ return undefined;
87
+ }
@@ -28,6 +28,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotation> = {
28
28
  // ── core messaging ──
29
29
  reply: W,
30
30
  send_image: W,
31
+ send_video: W,
31
32
  send_voice: W,
32
33
  transcribe: R,
33
34
  list_voices: R,
package/src/wake.ts CHANGED
@@ -33,14 +33,28 @@ export const WAKE_CONTENT_MAX = 500;
33
33
  /** Cap for native IDE/CLI wake prompts (Antigravity / ZCode), matching get_history per-message cap. */
34
34
  export const NATIVE_WAKE_CONTENT_MAX = 4000;
35
35
 
36
+ export interface WakeAttachment {
37
+ type?: string;
38
+ url?: string;
39
+ mime?: string;
40
+ size?: number;
41
+ width?: number;
42
+ height?: number;
43
+ duration_ms?: number;
44
+ transcript?: string;
45
+ }
46
+
36
47
  export interface WakeMessage {
37
48
  type?: string;
38
49
  id?: string;
39
50
  channel_id?: string;
40
51
  sender_id?: string;
41
52
  content?: string;
53
+ attachments?: WakeAttachment[];
42
54
  mentioned_ids?: string[];
43
55
  timestamp?: string;
56
+ /** True when server verified this DM is between an owner and their own agent, or sibling agents of the same owner. */
57
+ same_owner_direct?: boolean;
44
58
  /** Anything credential-shaped is stripped; these are accepted only to be dropped. */
45
59
  token?: string;
46
60
  agent_key?: string;
@@ -53,28 +67,73 @@ export interface WakePayload {
53
67
  message_id?: string;
54
68
  sender_id?: string;
55
69
  content?: string;
70
+ attachments?: WakeAttachment[];
56
71
  mentioned_ids?: string[];
57
72
  timestamp?: string;
73
+ /**
74
+ * Harness session this wake belongs to, resolved from `session-binds.json`.
75
+ * Absent means "not bound" — receivers must then use their own fallback.
76
+ */
77
+ target_session_id?: string;
78
+ }
79
+
80
+ export function formatWakeAttachments(attachments: unknown): string {
81
+ if (!Array.isArray(attachments) || attachments.length === 0) return "";
82
+ const lines: string[] = [];
83
+ for (const raw of attachments) {
84
+ if (!raw || typeof raw !== "object") continue;
85
+ const a = raw as WakeAttachment;
86
+ if (typeof a.url !== "string" || !a.url) continue;
87
+ const t = typeof a.type === "string" ? a.type : "file";
88
+ const dim = typeof a.width === "number" && typeof a.height === "number" ? ` ${a.width}×${a.height}` : "";
89
+ const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
90
+ const icon = t === "image" ? "🖼" : t === "video" ? "🎬" : t === "audio" ? "🔊" : "📎";
91
+ let desc = `${icon} ${t}${dim}${dur}: ${a.url}`;
92
+ if (typeof a.transcript === "string" && a.transcript.trim()) {
93
+ desc += ` (transcript: "${redactSecrets(a.transcript.trim().slice(0, 300))}")`;
94
+ }
95
+ lines.push(desc);
96
+ }
97
+ return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
58
98
  }
59
99
 
60
100
  /**
61
101
  * Build the wake body: the fields the receiver needs to wake + decide + optionally
62
102
  * skip a history fetch. Credential-shaped fields are never carried across.
63
103
  */
64
- export function buildWakePayload(msg: WakeMessage): WakePayload {
104
+ export function buildWakePayload(msg: WakeMessage, opts: { targetSessionId?: string } = {}): WakePayload {
65
105
  // The content excerpt crosses the wire to the wake receiver, so it goes through
66
106
  // the same redactSecrets every other outbound content path uses (reply/edit/
67
107
  // caption/status) — a message with an ac_ key or JWT pasted into it must not leak
68
- // it into the wake body either.
69
- const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
108
+ // it into the wake body either (except ac_ keys in same-owner direct channels).
109
+ const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
110
+ const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX), redactOpts) : undefined;
111
+ const attachments = Array.isArray(msg.attachments) && msg.attachments.length > 0
112
+ ? msg.attachments
113
+ .filter((a) => a && typeof a === "object" && typeof a.url === "string")
114
+ .map((a) => ({
115
+ type: typeof a.type === "string" ? a.type : undefined,
116
+ url: a.url,
117
+ mime: typeof a.mime === "string" ? a.mime : undefined,
118
+ size: typeof a.size === "number" ? a.size : undefined,
119
+ width: typeof a.width === "number" ? a.width : undefined,
120
+ height: typeof a.height === "number" ? a.height : undefined,
121
+ duration_ms: typeof a.duration_ms === "number" ? a.duration_ms : undefined,
122
+ transcript: typeof a.transcript === "string" ? redactSecrets(a.transcript.slice(0, 300), redactOpts) : undefined,
123
+ }))
124
+ : undefined;
125
+ const targetSessionId =
126
+ typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
70
127
  return {
71
128
  type: typeof msg.type === "string" ? msg.type : "message",
72
129
  channel_id: msg.channel_id,
73
130
  message_id: msg.id,
74
131
  sender_id: msg.sender_id,
75
132
  content,
133
+ ...(attachments && attachments.length > 0 ? { attachments } : {}),
76
134
  mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
77
135
  timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
136
+ ...(targetSessionId ? { target_session_id: targetSessionId } : {}),
78
137
  };
79
138
  }
80
139
 
@@ -111,6 +170,8 @@ export interface WakeConfig {
111
170
  /** Extra fetch impl for tests. */
112
171
  fetchImpl?: typeof fetch;
113
172
  logger?: (msg: string) => void;
173
+ /** Harness session the wake belongs to (see buildWakePayload). */
174
+ targetSessionId?: string;
114
175
  }
115
176
 
116
177
  /**
@@ -122,7 +183,7 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
122
183
  const url = (cfg.url ?? "").trim();
123
184
  if (!url) return; // not configured — the wake path is opt-in
124
185
 
125
- const payload = buildWakePayload(msg);
186
+ const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
126
187
  const body = JSON.stringify(payload);
127
188
  const headers: Record<string, string> = { "Content-Type": "application/json" };
128
189
  if (cfg.secret) headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
@@ -173,8 +234,9 @@ export interface GrokPrompt {
173
234
  export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix = ""): GrokPrompt {
174
235
  const rawContent = typeof msg.content === "string" ? msg.content : "";
175
236
  const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX;
176
- const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX)) : "";
177
- const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim()) : "";
237
+ const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
238
+ const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
239
+ const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
178
240
  const channel = msg.channel_id ?? "?";
179
241
  const sender = msg.sender_id ?? "someone";
180
242
  const msgId = (msg.id ?? (msg as any).message_id ?? "") as string;
@@ -183,10 +245,12 @@ export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix
183
245
  const actionHint = isTruncated
184
246
  ? `——消息已截断,可调 get_history 查看全文,再用 reply 回复`
185
247
  : `——请直接用 reply 回复;仅需更早历史时调 get_history`;
248
+ const attSummary = formatWakeAttachments(msg.attachments);
186
249
  const prompt =
187
250
  (cleanPrefix ? `${cleanPrefix}\n\n` : "") +
188
251
  `[AgentsChat] ${sender} 在${where}提到了你` +
189
252
  (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") +
253
+ attSummary +
190
254
  (msgId ? ` (channel_id=${channel}, message_id=${msgId}${actionHint})` : "");
191
255
  return { agentId, prompt };
192
256
  }
@@ -349,8 +413,9 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
349
413
  export function buildWakePrompt(msg: WakeMessage, contextPrefix = ""): string {
350
414
  const rawContent = typeof msg.content === "string" ? msg.content : "";
351
415
  const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX;
352
- const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX)) : "";
353
- const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim()) : "";
416
+ const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
417
+ const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
418
+ const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
354
419
  const channel = msg.channel_id ?? "?";
355
420
  const sender = msg.sender_id ?? "someone";
356
421
  const msgId = (msg.id ?? (msg as any).message_id ?? "") as string;
@@ -359,10 +424,12 @@ export function buildWakePrompt(msg: WakeMessage, contextPrefix = ""): string {
359
424
  const actionHint = isTruncated
360
425
  ? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读`
361
426
  : ` —— 请直接用 reply 回复并用 mark_read 标记已读;仅在需要更早上下文时调用 get_history`;
427
+ const attSummary = formatWakeAttachments(msg.attachments);
362
428
  return (
363
429
  (cleanPrefix ? `${cleanPrefix}\n\n` : "") +
364
430
  `[AgentsChat] ${sender} 在${where}给你发了消息` +
365
431
  (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") +
432
+ attSummary +
366
433
  ` (channel_id=${channel}` +
367
434
  (msgId ? `, message_id=${msgId}` : "") +
368
435
  `${actionHint})`