@phnx-labs/agents-cli 1.22.22 → 1.22.23

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 (91) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/README.md +8 -2
  3. package/dist/commands/doctor.js +15 -7
  4. package/dist/commands/exec.js +20 -6
  5. package/dist/commands/focus.d.ts +76 -4
  6. package/dist/commands/focus.js +219 -40
  7. package/dist/commands/fork.d.ts +20 -2
  8. package/dist/commands/fork.js +91 -64
  9. package/dist/commands/go.d.ts +25 -0
  10. package/dist/commands/go.js +63 -2
  11. package/dist/commands/harness-wizard.d.ts +206 -0
  12. package/dist/commands/harness-wizard.js +403 -0
  13. package/dist/commands/harness.d.ts +12 -0
  14. package/dist/commands/harness.js +97 -101
  15. package/dist/commands/resume.js +10 -3
  16. package/dist/commands/secrets.js +25 -30
  17. package/dist/commands/sessions-resume.d.ts +21 -3
  18. package/dist/commands/sessions-resume.js +50 -11
  19. package/dist/commands/sessions.d.ts +81 -5
  20. package/dist/commands/sessions.js +325 -66
  21. package/dist/commands/watchdog.js +13 -2
  22. package/dist/lib/agents.d.ts +1 -1
  23. package/dist/lib/agents.js +132 -0
  24. package/dist/lib/codex-policy.d.ts +17 -0
  25. package/dist/lib/codex-policy.js +48 -0
  26. package/dist/lib/crabbox/lease.d.ts +25 -0
  27. package/dist/lib/crabbox/lease.js +62 -0
  28. package/dist/lib/daemon.js +70 -0
  29. package/dist/lib/exec.d.ts +4 -0
  30. package/dist/lib/exec.js +88 -54
  31. package/dist/lib/feed-broadcast.d.ts +1 -20
  32. package/dist/lib/feed-broadcast.js +31 -1
  33. package/dist/lib/hooks.js +12 -2
  34. package/dist/lib/mcp.js +44 -0
  35. package/dist/lib/menubar/MenubarHelper.app/Contents/Info.plist +1 -5
  36. package/dist/lib/menubar/MenubarHelper.app/Contents/MacOS/MenubarHelper +0 -0
  37. package/dist/lib/menubar/MenubarHelper.app/Contents/_CodeSignature/CodeResources +2 -15
  38. package/dist/lib/models.d.ts +0 -5
  39. package/dist/lib/models.js +48 -0
  40. package/dist/lib/plugin-marketplace.js +9 -0
  41. package/dist/lib/pricing/prices.json +119 -92
  42. package/dist/lib/pricing/table.js +13 -0
  43. package/dist/lib/remote-agents-json.d.ts +29 -1
  44. package/dist/lib/remote-agents-json.js +47 -10
  45. package/dist/lib/resources/mcp.js +2 -0
  46. package/dist/lib/resources/permissions.js +3 -0
  47. package/dist/lib/resources/types.d.ts +2 -1
  48. package/dist/lib/runner.js +28 -19
  49. package/dist/lib/secrets/Agents CLI.app/Contents/CodeResources +0 -0
  50. package/dist/lib/secrets/Agents CLI.app/Contents/Info.plist +0 -2
  51. package/dist/lib/secrets/Agents CLI.app/Contents/MacOS/Agents CLI +0 -0
  52. package/dist/lib/secrets/Agents CLI.app/Contents/_CodeSignature/CodeResources +1 -13
  53. package/dist/lib/secrets/index.d.ts +15 -1
  54. package/dist/lib/secrets/index.js +118 -49
  55. package/dist/lib/secrets/reaper.d.ts +87 -0
  56. package/dist/lib/secrets/reaper.js +184 -0
  57. package/dist/lib/secrets/remote.d.ts +29 -0
  58. package/dist/lib/secrets/remote.js +37 -1
  59. package/dist/lib/session/active.d.ts +36 -1
  60. package/dist/lib/session/active.js +60 -19
  61. package/dist/lib/session/actor-sidecar.d.ts +14 -0
  62. package/dist/lib/session/actor-sidecar.js +67 -4
  63. package/dist/lib/session/db.d.ts +1 -1
  64. package/dist/lib/session/db.js +32 -1
  65. package/dist/lib/session/discover.js +168 -0
  66. package/dist/lib/session/parse.d.ts +10 -0
  67. package/dist/lib/session/parse.js +98 -0
  68. package/dist/lib/session/remote-list.d.ts +10 -1
  69. package/dist/lib/session/remote-list.js +2 -8
  70. package/dist/lib/session/remote.d.ts +57 -3
  71. package/dist/lib/session/remote.js +90 -26
  72. package/dist/lib/session/resume-command.d.ts +6 -0
  73. package/dist/lib/session/resume-command.js +8 -0
  74. package/dist/lib/session/session-cache.d.ts +173 -0
  75. package/dist/lib/session/session-cache.js +399 -0
  76. package/dist/lib/session/types.d.ts +1 -1
  77. package/dist/lib/session/types.js +1 -1
  78. package/dist/lib/session/width.d.ts +1 -1
  79. package/dist/lib/session/width.js +12 -2
  80. package/dist/lib/shims.d.ts +2 -2
  81. package/dist/lib/shims.js +40 -5
  82. package/dist/lib/staleness/writers/hooks.js +1 -1
  83. package/dist/lib/types.d.ts +1 -1
  84. package/dist/lib/usage.d.ts +13 -0
  85. package/dist/lib/usage.js +215 -0
  86. package/dist/lib/versions.js +13 -2
  87. package/package.json +1 -1
  88. package/dist/bin/agents +0 -0
  89. package/dist/lib/menubar/MenubarHelper.app/Contents/CodeResources +0 -0
  90. package/dist/lib/menubar/MenubarHelper.app/Contents/Resources/AppIcon.icns +0 -0
  91. package/dist/lib/secrets/Agents CLI.app/Contents/Resources/AppIcon.icns +0 -0
@@ -2,7 +2,7 @@ import type { CloudTaskStatus } from '../cloud/types.js';
2
2
  import { type PidSessionEntry } from './pid-registry.js';
3
3
  import { type HookSessionIndex } from './hook-sessions.js';
4
4
  import { type SessionState, type SessionActivity, type AwaitingReason, type StructuredQuestion, type TodoProgress, type DetectedPr, type DetectedWorktree, type DetectedTicket } from './state.js';
5
- import { type SessionAttachment } from './types.js';
5
+ import { type SessionAgentId, type SessionAttachment } from './types.js';
6
6
  import { type SessionProvenance } from './provenance.js';
7
7
  import { type DeviceRegistry } from '../devices/registry.js';
8
8
  import { type Presence } from './detached.js';
@@ -111,6 +111,13 @@ export interface ActiveSession {
111
111
  attachments?: SessionAttachment[];
112
112
  sessionFile?: string;
113
113
  startedAtMs?: number;
114
+ /**
115
+ * Agent version (e.g. `2.1.207`) for the row's `agent version` cell. Not a
116
+ * live-scan signal — a running process does not report its own semver — so it
117
+ * is backfilled at render time from the indexed {@link SessionMeta} by session
118
+ * id (RUSH-2205), never asserted by a source.
119
+ */
120
+ version?: string;
114
121
  /**
115
122
  * Last-activity epoch — the transcript's last write (mtime). Distinct from
116
123
  * {@link startedAtMs} (session START): a session begun 3h ago but last touched
@@ -294,6 +301,16 @@ export declare const ACTIVE_SESSION_STALE_MS: number;
294
301
  * concern) — this is the lifecycle threshold, not the freshness window.
295
302
  */
296
303
  export declare const ABANDONED_STALE_MS: number;
304
+ /**
305
+ * Every process executable ("comm") name that identifies a given session-agent
306
+ * kind in the headless `ps`-scan. Driven off the AGENTS registry's `cliCommand`
307
+ * (the real executable name — e.g. `agy` for antigravity, `cursor-agent` for
308
+ * cursor) plus {@link EXTRA_SESSION_AGENT_COMMS} for members with no registry
309
+ * row. Exported so the completeness test can assert every {@link SESSION_AGENTS}
310
+ * member resolves — the fix for the harness-parity gap where bare-headless
311
+ * grok/kimi/antigravity/openclaw/hermes/rush were silently dropped.
312
+ */
313
+ export declare function sessionAgentComms(id: SessionAgentId): string[];
297
314
  /**
298
315
  * Resolve an agent kind from a process's reported executable. `comm` may be an
299
316
  * absolute path (shim-launched agents), and Windows image names carry an
@@ -600,6 +617,24 @@ export declare function foldHostLink(rows: ActiveSession[]): void;
600
617
  * renderer shows the short id. Pure over the array; exported for tests.
601
618
  */
602
619
  export declare function annotateOrchestratorLabels(sessions: ActiveSession[]): void;
620
+ /**
621
+ * Attach provenance (host / local-vs-SSH / tmux pane / reply rail) to every
622
+ * session that has a live pid. Mutates in place. Runs after dedupe so we probe
623
+ * each session once, not once per fork pid. Probes run in parallel — each is a
624
+ * single /proc read (Linux) or `ps` call (macOS); failures leave `provenance`
625
+ * undefined rather than blocking the listing. The probes use the same bounded
626
+ * concurrency as the adjacent per-PID lsof sweep so large session lists cannot
627
+ * spawn one `ps eww` subprocess per row at once on macOS.
628
+ *
629
+ * A row that already carries provenance (the tmux path, which knows its exact
630
+ * mux/reply from the pane) is not skipped — it is probe-and-MERGED. The tmux
631
+ * path can only stamp a `transport:'local'` placeholder because the pane alone
632
+ * doesn't reveal how the shell above it was reached; the process env does. So we
633
+ * still read the env and fill in the real SSH origin/term, while preserving the
634
+ * authoritative mux/reply the pane already gave us. Skipping this (the old
635
+ * behavior) is exactly why ssh-launched tmux sessions rendered as local.
636
+ */
637
+ export declare function enrichProvenance(sessions: ActiveSession[], probe?: (pid: number) => Promise<SessionProvenance | undefined>): Promise<void>;
603
638
  /**
604
639
  * Match an SSH client IP to a registered device (pure — testable with a plain
605
640
  * registry object). Returns the device name + ssh login user when the IP is a
@@ -25,7 +25,7 @@ import { listActiveTasks } from '../cloud/store.js';
25
25
  import { AgentManager } from '../teams/agents.js';
26
26
  import { getTerminalsDir } from '../state.js';
27
27
  import { readPidSessionEntry, listPidSessionEntries, prunePidSessionRegistry } from './pid-registry.js';
28
- import { readSessionActorRecord } from './actor-sidecar.js';
28
+ import { readSessionActorRecord, writeSessionAliasRecord } from './actor-sidecar.js';
29
29
  import { loadHookSessionIndex, resolveHookSessionRecord, readStateSessionRecord } from './hook-sessions.js';
30
30
  import { buildClaudeLabelMap, getAgentSessionDirs } from './discover.js';
31
31
  import { buildRunNameMap } from './run-names.js';
@@ -35,7 +35,8 @@ import { readSessionTailWithRaw } from './tail.js';
35
35
  import { parseSession } from './parse.js';
36
36
  import { computeTokPerSec } from './throughput.js';
37
37
  import { inferSessionState } from './state.js';
38
- import { isSessionTrackedAgent } from './types.js';
38
+ import { isSessionTrackedAgent, SESSION_AGENTS } from './types.js';
39
+ import { AGENTS } from '../agents.js';
39
40
  import { detectProvenance } from './provenance.js';
40
41
  import { loadDevices } from '../devices/registry.js';
41
42
  import { presenceFromStore } from './detached.js';
@@ -132,15 +133,47 @@ export const ABANDONED_STALE_MS = 2 * 24 * 60 * 60_000;
132
133
  * just reintroduce the same class of bug with a lower probability.
133
134
  */
134
135
  const TMUX_FIELD_SEP = ':';
135
- /** Executables we recognize as agent CLIs when scanning the process table. */
136
- const AGENT_CLI_NAMES = {
137
- claude: 'claude',
138
- codex: 'codex',
139
- gemini: 'gemini',
140
- 'cursor-agent': 'cursor',
141
- opencode: 'opencode',
142
- droid: 'droid',
136
+ /**
137
+ * Process comm names that are NOT derivable from the AGENTS registry's
138
+ * `cliCommand`. `rush` is a {@link SESSION_AGENTS} member with no AGENTS registry
139
+ * row (it is the Rush app, not a managed harness), so its executable name is
140
+ * mapped explicitly here. Everything else flows from the registry below.
141
+ */
142
+ const EXTRA_SESSION_AGENT_COMMS = {
143
+ rush: ['rush'],
143
144
  };
145
+ /**
146
+ * Every process executable ("comm") name that identifies a given session-agent
147
+ * kind in the headless `ps`-scan. Driven off the AGENTS registry's `cliCommand`
148
+ * (the real executable name — e.g. `agy` for antigravity, `cursor-agent` for
149
+ * cursor) plus {@link EXTRA_SESSION_AGENT_COMMS} for members with no registry
150
+ * row. Exported so the completeness test can assert every {@link SESSION_AGENTS}
151
+ * member resolves — the fix for the harness-parity gap where bare-headless
152
+ * grok/kimi/antigravity/openclaw/hermes/rush were silently dropped.
153
+ */
154
+ export function sessionAgentComms(id) {
155
+ const comms = new Set();
156
+ const cli = AGENTS[id]?.cliCommand;
157
+ if (cli)
158
+ comms.add(cli);
159
+ for (const extra of EXTRA_SESSION_AGENT_COMMS[id] ?? [])
160
+ comms.add(extra);
161
+ return [...comms];
162
+ }
163
+ /**
164
+ * Executables we recognize as agent CLIs when scanning the process table. Built
165
+ * once from {@link sessionAgentComms} across {@link SESSION_AGENTS} — a single
166
+ * derived source, not a second hand-maintained allowlist that drifts from the
167
+ * discovery surface (the harness-parity code-review rule).
168
+ */
169
+ const AGENT_CLI_NAMES = (() => {
170
+ const map = {};
171
+ for (const id of SESSION_AGENTS) {
172
+ for (const comm of sessionAgentComms(id))
173
+ map[comm] = id;
174
+ }
175
+ return map;
176
+ })();
144
177
  /**
145
178
  * Resolve an agent kind from a process's reported executable. `comm` may be an
146
179
  * absolute path (shim-launched agents), and Windows image names carry an
@@ -1310,7 +1343,7 @@ export async function listTmuxAgentSessions() {
1310
1343
  try {
1311
1344
  res = await runTmux({
1312
1345
  socket,
1313
- args: ['list-panes', '-a', '-F', ['#{pane_id}', '#{session_name}', '#{pane_pid}', '#{pane_current_path}'].join(TMUX_FIELD_SEP)],
1346
+ args: ['list-panes', '-a', '-F', ['#{pane_id}', '#{session_name}', '#{pane_pid}', '#{pane_dead}', '#{pane_current_path}'].join(TMUX_FIELD_SEP)],
1314
1347
  throwOnError: false,
1315
1348
  // A wedged tmux server must not hang the whole active-session scan. The
1316
1349
  // catch below turns a timeout into an empty tmux source (the other sources
@@ -1351,8 +1384,8 @@ export async function listTmuxAgentSessions() {
1351
1384
  // The path is the LAST field, so rejoin its tail: a directory containing the
1352
1385
  // separator must not truncate it (the earlier fields cannot contain one).
1353
1386
  const parts = line.split(TMUX_FIELD_SEP);
1354
- const [pane, sessName, pidRaw] = parts;
1355
- const curPath = parts.slice(3).join(TMUX_FIELD_SEP);
1387
+ const [pane, sessName, pidRaw, paneDeadRaw] = parts;
1388
+ const curPath = parts.slice(4).join(TMUX_FIELD_SEP);
1356
1389
  if (!pane || !sessName)
1357
1390
  continue;
1358
1391
  const meta = readSessionMeta(sessName);
@@ -1378,6 +1411,9 @@ export async function listTmuxAgentSessions() {
1378
1411
  if (backfilled)
1379
1412
  id = { ...id, sessionId: backfilled };
1380
1413
  }
1414
+ if (id.sessionId && shortIdFromName(sessName)) {
1415
+ writeSessionAliasRecord(id.sessionId, sessName);
1416
+ }
1381
1417
  // Dedupe by resolved session id; an as-yet-unresolved id (a hookless/lagging
1382
1418
  // split) keys on the unique pane so it still surfaces as its own row.
1383
1419
  const dedupKey = id.sessionId ?? pane;
@@ -1395,7 +1431,10 @@ export async function listTmuxAgentSessions() {
1395
1431
  // bug). Refuse to guess: an id-less pane surfaces as its own row instead.
1396
1432
  const sessionFile = id.sessionId ? findSessionFileForKind(id.agent, cwd, id.sessionId) : undefined;
1397
1433
  const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
1398
- const pidAlive = pid ? isPidAlive(pid, liveEntry?.startedAtMs) : true;
1434
+ // `remain-on-exit` retains the pane after its child exits. pane_dead is the
1435
+ // authoritative signal; a retained pane is diagnostic, not attachable.
1436
+ const paneDead = paneDeadRaw === '1';
1437
+ const pidAlive = !paneDead && (pid ? isPidAlive(pid, liveEntry?.startedAtMs) : true);
1399
1438
  const { state, tokPerSec } = computeLiveSignals(id.agent, sessionFile, cwd, pidAlive);
1400
1439
  const { birthtimeMs, mtimeMs } = sessionFileTimes(sessionFile);
1401
1440
  // The mux/reply rails are known exactly here (the pane IS a tmux pane), so we
@@ -1620,7 +1659,9 @@ function foldPresence(rows) {
1620
1659
  * session that has a live pid. Mutates in place. Runs after dedupe so we probe
1621
1660
  * each session once, not once per fork pid. Probes run in parallel — each is a
1622
1661
  * single /proc read (Linux) or `ps` call (macOS); failures leave `provenance`
1623
- * undefined rather than blocking the listing.
1662
+ * undefined rather than blocking the listing. The probes use the same bounded
1663
+ * concurrency as the adjacent per-PID lsof sweep so large session lists cannot
1664
+ * spawn one `ps eww` subprocess per row at once on macOS.
1624
1665
  *
1625
1666
  * A row that already carries provenance (the tmux path, which knows its exact
1626
1667
  * mux/reply from the pane) is not skipped — it is probe-and-MERGED. The tmux
@@ -1630,11 +1671,11 @@ function foldPresence(rows) {
1630
1671
  * authoritative mux/reply the pane already gave us. Skipping this (the old
1631
1672
  * behavior) is exactly why ssh-launched tmux sessions rendered as local.
1632
1673
  */
1633
- async function enrichProvenance(sessions) {
1634
- await Promise.all(sessions.map(async (s) => {
1674
+ export async function enrichProvenance(sessions, probe = detectProvenance) {
1675
+ await mapBounded(sessions, async (s) => {
1635
1676
  if (!s.pid)
1636
1677
  return;
1637
- const probed = await detectProvenance(s.pid);
1678
+ const probed = await probe(s.pid);
1638
1679
  if (!probed)
1639
1680
  return;
1640
1681
  if (!s.provenance) {
@@ -1649,7 +1690,7 @@ async function enrichProvenance(sessions) {
1649
1690
  }
1650
1691
  if (probed.term && !s.provenance.term)
1651
1692
  s.provenance.term = probed.term;
1652
- }));
1693
+ }, { concurrency: LSOF_CONCURRENCY });
1653
1694
  }
1654
1695
  /**
1655
1696
  * Match an SSH client IP to a registered device (pure — testable with a plain
@@ -7,6 +7,8 @@ export interface SessionActorRecord {
7
7
  initiatedBy?: 'human' | 'agent';
8
8
  /** Effective permissions mode used by the launcher. */
9
9
  mode?: SessionRunMode;
10
+ /** Stable wrapper names that resolve to this native session id. */
11
+ aliases?: string[];
10
12
  startedAtMs: number;
11
13
  }
12
14
  /**
@@ -15,6 +17,18 @@ export interface SessionActorRecord {
15
17
  * No-ops without a concrete session id (nothing to key on).
16
18
  */
17
19
  export declare function writeSessionActorRecord(record: SessionActorRecord): void;
20
+ export declare function writeSessionAliasRecord(sessionId: string, alias: string): void;
21
+ export type SessionAliasResolution = {
22
+ kind: 'resolved';
23
+ sessionId: string;
24
+ } | {
25
+ kind: 'ambiguous';
26
+ sessionIds: string[];
27
+ } | {
28
+ kind: 'not-found';
29
+ };
30
+ /** Resolve an exact alias, or a unique prefix/suffix of at least six chars. */
31
+ export declare function resolveSessionAlias(selector: string): SessionAliasResolution;
18
32
  /** Read one session's actor record. Returns undefined if absent/corrupt. */
19
33
  export declare function readSessionActorRecord(sessionId: string): SessionActorRecord | undefined;
20
34
  /**
@@ -33,6 +33,25 @@ function isSafeSessionId(sessionId) {
33
33
  function recordPath(sessionId) {
34
34
  return path.join(sidecarDir(), `${sessionId}.json`);
35
35
  }
36
+ function isSafeAlias(alias) {
37
+ return /^ag-[a-z][a-z0-9-]*-[0-9a-f]{8}$/i.test(alias);
38
+ }
39
+ function hasRecordData(record) {
40
+ return typeof record.actor === 'string'
41
+ || typeof record.mode === 'string'
42
+ || (Array.isArray(record.aliases) && record.aliases.some(alias => typeof alias === 'string'));
43
+ }
44
+ function normalizedAliases(aliases) {
45
+ if (!Array.isArray(aliases))
46
+ return [];
47
+ return [...new Set(aliases
48
+ .filter((alias) => typeof alias === 'string' && isSafeAlias(alias))
49
+ .map(alias => alias.toLowerCase()))];
50
+ }
51
+ function writeRecord(record) {
52
+ fs.mkdirSync(sidecarDir(), { recursive: true });
53
+ fs.writeFileSync(recordPath(record.sessionId), JSON.stringify(record), 'utf8');
54
+ }
36
55
  /**
37
56
  * Record the actor a session was launched under. Never throws — the sidecar is
38
57
  * an attribution optimization; a session with no record simply scans unattributed.
@@ -42,13 +61,57 @@ export function writeSessionActorRecord(record) {
42
61
  if (!isSafeSessionId(record.sessionId))
43
62
  return;
44
63
  try {
45
- fs.mkdirSync(sidecarDir(), { recursive: true });
46
- fs.writeFileSync(recordPath(record.sessionId), JSON.stringify(record), 'utf8');
64
+ const previous = readSessionActorRecord(record.sessionId);
65
+ writeRecord({
66
+ ...previous,
67
+ ...record,
68
+ aliases: normalizedAliases([...(previous?.aliases ?? []), ...(record.aliases ?? [])]),
69
+ });
47
70
  }
48
71
  catch {
49
72
  /* degrade to an unattributed row */
50
73
  }
51
74
  }
75
+ export function writeSessionAliasRecord(sessionId, alias) {
76
+ if (!isSafeSessionId(sessionId) || !isSafeAlias(alias))
77
+ return;
78
+ try {
79
+ const previous = readSessionActorRecord(sessionId);
80
+ writeRecord({
81
+ sessionId,
82
+ actor: previous?.actor,
83
+ initiatedBy: previous?.initiatedBy,
84
+ mode: previous?.mode,
85
+ aliases: normalizedAliases([...(previous?.aliases ?? []), alias]),
86
+ startedAtMs: previous?.startedAtMs ?? Date.now(),
87
+ });
88
+ }
89
+ catch {
90
+ /* the native id remains usable */
91
+ }
92
+ }
93
+ /** Resolve an exact alias, or a unique prefix/suffix of at least six chars. */
94
+ export function resolveSessionAlias(selector) {
95
+ const normalized = selector.trim().toLowerCase();
96
+ if (!normalized)
97
+ return { kind: 'not-found' };
98
+ const exact = new Set();
99
+ const fuzzy = new Set();
100
+ for (const record of loadSessionActorIndex().values()) {
101
+ for (const alias of normalizedAliases(record.aliases)) {
102
+ if (alias === normalized)
103
+ exact.add(record.sessionId);
104
+ else if (normalized.length >= 6 && (alias.startsWith(normalized) || alias.endsWith(normalized)))
105
+ fuzzy.add(record.sessionId);
106
+ }
107
+ }
108
+ const matches = exact.size > 0 ? [...exact] : [...fuzzy];
109
+ if (matches.length === 0)
110
+ return { kind: 'not-found' };
111
+ if (matches.length > 1)
112
+ return { kind: 'ambiguous', sessionIds: matches.sort() };
113
+ return { kind: 'resolved', sessionId: matches[0] };
114
+ }
52
115
  /** Read one session's actor record. Returns undefined if absent/corrupt. */
53
116
  export function readSessionActorRecord(sessionId) {
54
117
  if (!isSafeSessionId(sessionId))
@@ -63,7 +126,7 @@ export function readSessionActorRecord(sessionId) {
63
126
  try {
64
127
  const parsed = JSON.parse(raw);
65
128
  if (parsed && typeof parsed === 'object' && typeof parsed.sessionId === 'string' &&
66
- (typeof parsed.actor === 'string' || typeof parsed.mode === 'string')) {
129
+ hasRecordData(parsed)) {
67
130
  return parsed;
68
131
  }
69
132
  }
@@ -91,7 +154,7 @@ export function loadSessionActorIndex() {
91
154
  try {
92
155
  const parsed = JSON.parse(fs.readFileSync(path.join(sidecarDir(), f), 'utf8'));
93
156
  if (parsed && typeof parsed === 'object' && typeof parsed.sessionId === 'string' &&
94
- (typeof parsed.actor === 'string' || typeof parsed.mode === 'string')) {
157
+ hasRecordData(parsed)) {
95
158
  out.set(parsed.sessionId, parsed);
96
159
  }
97
160
  }
@@ -12,7 +12,7 @@ import { type IndexedToolCall } from './tool-calls.js';
12
12
  /** Current schema version; bumped when migrations are added. Exported so tests
13
13
  * assert against the constant instead of hardcoding a number that every bump
14
14
  * then has to chase (docs/05-sessions.md calls the constant the source of truth). */
15
- export declare const SCHEMA_VERSION = 33;
15
+ export declare const SCHEMA_VERSION = 34;
16
16
  /**
17
17
  * Bump to force `agents sessions backfill resources` to re-derive every
18
18
  * session's skill/slash-command tallies on its next run (resource_scan_ledger
@@ -26,7 +26,7 @@ const DB_PATH = getSessionsDbPath();
26
26
  /** Current schema version; bumped when migrations are added. Exported so tests
27
27
  * assert against the constant instead of hardcoding a number that every bump
28
28
  * then has to chase (docs/05-sessions.md calls the constant the source of truth). */
29
- export const SCHEMA_VERSION = 33;
29
+ export const SCHEMA_VERSION = 34;
30
30
  /**
31
31
  * Bump to force `agents sessions backfill resources` to re-derive every
32
32
  * session's skill/slash-command tallies on its next run (resource_scan_ledger
@@ -779,6 +779,37 @@ function migrateSchema(db, fromVersion) {
779
779
  db.exec(`CREATE INDEX IF NOT EXISTS idx_sessions_account_key ON sessions(account_key)`);
780
780
  backfillClaudeAccounts(db);
781
781
  }
782
+ if (fromVersion < 34) {
783
+ // v33 -> v34: claude-opus-5 and claude-sonnet-5 were missing from the pricing
784
+ // table. `getModelPricing` matches on a dash-bounded prefix, so neither could fall
785
+ // back to its Claude 4 entry: both resolved to null and every session using them
786
+ // priced to $0 -- silently, because an unpriced model contributes nothing rather
787
+ // than raising. On one real index that was 526 sessions, 478 of them the current
788
+ // default model.
789
+ //
790
+ // Adding the prices alone fixes nothing already indexed: cost_usd is computed at
791
+ // scan time, and the scanner skips any transcript whose (file_mtime_ms, file_size)
792
+ // is unchanged. Nor can those rows be repaired in place -- the row stores
793
+ // token_count and output_tokens, not the uncached-input / cache-read / cache-write
794
+ // split the price table needs -- so the figure has to come from re-reading the
795
+ // transcript.
796
+ //
797
+ // Flush ONLY the affected transcripts, not the whole ledger. A blanket
798
+ // `DELETE FROM scan_ledger` (what v5 -> v6 did when cost was introduced) would
799
+ // re-parse every session on the next scan and break the contract the other
800
+ // migrations here are tested against: adding a column must not invalidate warm
801
+ // session ledgers. Scoping it to the rows that actually mispriced keeps every
802
+ // other ledger entry warm and still guarantees the numbers correct themselves.
803
+ db.exec(`
804
+ DELETE FROM scan_ledger
805
+ WHERE file_path IN (
806
+ SELECT file_path FROM sessions
807
+ WHERE cost_usd IS NULL
808
+ AND file_path IS NOT NULL AND file_path <> ''
809
+ AND (model LIKE 'claude-opus-5%' OR model LIKE 'claude-sonnet-5%')
810
+ );
811
+ `);
812
+ }
782
813
  }
783
814
  /**
784
815
  * Stamp `account_key` / `account_org` / `account` on every Claude row from its
@@ -47,6 +47,8 @@ const HOME = os.homedir();
47
47
  const VERSIONS_ROOTS = [getHistoryDir(), getAgentsDir()];
48
48
  const RUSH_SESSIONS_DIR = path.join(HOME, '.rush', 'sessions');
49
49
  const HERMES_SESSIONS_DIR = path.join(HOME, '.hermes', 'sessions');
50
+ /** Muse Code sessions: ~/.local/share/muse/sessions/YYYY/MM/DD/<uuid>/session.jsonl */
51
+ const MUSE_SESSIONS_DIR = path.join(HOME, '.local', 'share', 'muse', 'sessions');
50
52
  /** How long OpenClaw channel/cron snapshots stay valid before we re-shell-out. */
51
53
  const OPENCLAW_TTL_MS = 60_000;
52
54
  const ACTIVE_APPEND_RESCAN_DEBOUNCE_MS = 5_000;
@@ -303,6 +305,7 @@ function dispatchAgentScan(agent, onProgress) {
303
305
  case 'droid': return scanDroidIncremental(onProgress);
304
306
  case 'grok': return scanGrokIncremental(onProgress);
305
307
  case 'cursor': return scanCursorIncremental(onProgress);
308
+ case 'muse': return scanMuseIncremental(onProgress);
306
309
  default: return Promise.resolve();
307
310
  }
308
311
  }
@@ -2274,6 +2277,171 @@ function readHermesMeta(filePath) {
2274
2277
  };
2275
2278
  return { meta, content: userTexts.join('\n') };
2276
2279
  }
2280
+ /**
2281
+ * Muse Code stores one session per directory under
2282
+ * ~/.local/share/muse/sessions/YYYY/MM/DD/<uuid>/session.jsonl (event-sourced
2283
+ * JSONL). Walk the tree for session.jsonl files and index each one.
2284
+ *
2285
+ * Also scan version homes (`versions/muse/<v>/home/.local/share/muse/sessions`)
2286
+ * so managed/isolated runs that rewrite HOME still show up in `agents sessions`.
2287
+ */
2288
+ function scanMuseIncremental(onProgress) {
2289
+ const roots = [];
2290
+ if (fs.existsSync(MUSE_SESSIONS_DIR))
2291
+ roots.push(MUSE_SESSIONS_DIR);
2292
+ for (const root of VERSIONS_ROOTS) {
2293
+ const versionsBase = path.join(root, 'versions', 'muse');
2294
+ if (!fs.existsSync(versionsBase))
2295
+ continue;
2296
+ try {
2297
+ for (const version of fs.readdirSync(versionsBase)) {
2298
+ const dir = path.join(versionsBase, version, 'home', '.local', 'share', 'muse', 'sessions');
2299
+ if (fs.existsSync(dir))
2300
+ roots.push(dir);
2301
+ }
2302
+ }
2303
+ catch {
2304
+ /* unreadable */
2305
+ }
2306
+ }
2307
+ if (roots.length === 0)
2308
+ return Promise.resolve();
2309
+ const filePaths = [];
2310
+ const walk = (dir) => {
2311
+ let entries;
2312
+ try {
2313
+ entries = fs.readdirSync(dir, { withFileTypes: true });
2314
+ }
2315
+ catch {
2316
+ return;
2317
+ }
2318
+ for (const ent of entries) {
2319
+ const full = path.join(dir, ent.name);
2320
+ if (ent.isDirectory()) {
2321
+ // Skip subagent child sessions — nested under subagent/<id>/
2322
+ if (ent.name === 'subagent')
2323
+ continue;
2324
+ walk(full);
2325
+ }
2326
+ else if (ent.name === 'session.jsonl') {
2327
+ filePaths.push(full);
2328
+ }
2329
+ }
2330
+ };
2331
+ for (const root of roots)
2332
+ walk(root);
2333
+ const changed = filterChangedFiles(filePaths);
2334
+ if (changed.length === 0)
2335
+ return Promise.resolve();
2336
+ onProgress?.({ agent: 'muse', parsed: 0, total: changed.length });
2337
+ const scanEntries = [];
2338
+ const touched = [];
2339
+ const seen = new Set();
2340
+ let parsed = 0;
2341
+ for (const { filePath, scan } of changed) {
2342
+ try {
2343
+ const result = readMuseMeta(filePath);
2344
+ if (result && !seen.has(result.meta.id)) {
2345
+ seen.add(result.meta.id);
2346
+ scanEntries.push({ meta: result.meta, content: result.content, scan });
2347
+ }
2348
+ else {
2349
+ touched.push({ filePath, scan });
2350
+ }
2351
+ }
2352
+ catch {
2353
+ touched.push({ filePath, scan });
2354
+ }
2355
+ parsed++;
2356
+ onProgress?.({ agent: 'muse', parsed, total: changed.length });
2357
+ }
2358
+ upsertSessionsBatch(scanEntries);
2359
+ recordScans(touched);
2360
+ return Promise.resolve();
2361
+ }
2362
+ /** Parse a Muse session.jsonl for session metadata + first user prompt text. */
2363
+ function readMuseMeta(filePath) {
2364
+ // Path shape: .../sessions/YYYY/MM/DD/<uuid>/session.jsonl
2365
+ const sessionId = path.basename(path.dirname(filePath));
2366
+ if (!/^[0-9a-f-]{36}$/i.test(sessionId))
2367
+ return null;
2368
+ let content;
2369
+ try {
2370
+ content = fs.readFileSync(filePath, 'utf-8');
2371
+ }
2372
+ catch {
2373
+ return null;
2374
+ }
2375
+ const userTexts = [];
2376
+ let topic;
2377
+ let messageCount = 0;
2378
+ let model;
2379
+ let project;
2380
+ let firstTs;
2381
+ let lastTs;
2382
+ for (const line of content.split('\n')) {
2383
+ if (!line.trim())
2384
+ continue;
2385
+ let raw;
2386
+ try {
2387
+ raw = JSON.parse(line);
2388
+ }
2389
+ catch {
2390
+ continue;
2391
+ }
2392
+ if (typeof raw.recorded_at === 'number') {
2393
+ const v = raw.recorded_at;
2394
+ // Muse logs use microseconds; values < 1e14 are treated as milliseconds.
2395
+ const ms = v > 1e14 ? Math.floor(v / 1000) : v;
2396
+ const ts = new Date(ms).toISOString();
2397
+ if (!firstTs)
2398
+ firstTs = ts;
2399
+ lastTs = ts;
2400
+ }
2401
+ const payloadType = raw.payload_type;
2402
+ const payload = raw.payload;
2403
+ if (payloadType === 'runtime.session.metadata') {
2404
+ const record = payload?.record;
2405
+ if (typeof record?.workspace_root === 'string')
2406
+ project = record.workspace_root;
2407
+ }
2408
+ if (payloadType === 'runtime.command_intake.received') {
2409
+ const cmd = payload?.record?.command;
2410
+ if (cmd?.kind === 'turn_submit' && typeof cmd.prompt === 'string' && cmd.prompt.trim()) {
2411
+ messageCount++;
2412
+ userTexts.push(cmd.prompt.trim());
2413
+ if (!topic)
2414
+ topic = extractSessionTopic(cmd.prompt.trim());
2415
+ }
2416
+ }
2417
+ const event = payload?.event ?? payload;
2418
+ if (event?.kind === 'assistant_message_committed' && typeof event.text === 'string') {
2419
+ messageCount++;
2420
+ }
2421
+ if (event?.kind === 'model_request_configured' && typeof event.model === 'string') {
2422
+ model = event.model;
2423
+ }
2424
+ if (typeof event?.model === 'string' && !model)
2425
+ model = event.model;
2426
+ }
2427
+ const stat = safeStatSync(filePath);
2428
+ const timestamp = lastTs
2429
+ || firstTs
2430
+ || (stat ? stat.mtime.toISOString() : new Date().toISOString());
2431
+ const shortId = deriveShortId(sessionId);
2432
+ const meta = {
2433
+ id: sessionId,
2434
+ shortId,
2435
+ agent: 'muse',
2436
+ timestamp,
2437
+ project,
2438
+ filePath,
2439
+ model,
2440
+ topic,
2441
+ messageCount: messageCount || undefined,
2442
+ };
2443
+ return { meta, content: userTexts.join('\n') };
2444
+ }
2277
2445
  /** Extract plain text from a Hermes message content field (string or list of parts). */
2278
2446
  function extractHermesMessageText(content) {
2279
2447
  if (typeof content === 'string')
@@ -133,6 +133,16 @@ export declare function parseGrok(filePath: string): SessionEvent[];
133
133
  export declare function parseOpenCode(filePath: string): SessionEvent[];
134
134
  /** Parse a Rush JSONL session file into normalized events. */
135
135
  export declare function parseRush(filePath: string): SessionEvent[];
136
+ /**
137
+ * Muse Code session.jsonl → normalized events.
138
+ *
139
+ * Muse records an append-only event log. We map:
140
+ * - runtime.command_intake.received / turn_submit → user message
141
+ * - assistant_message_committed → assistant message
142
+ * - model_completed.usage → usage
143
+ * - tool-related events when present
144
+ */
145
+ export declare function parseMuse(filePath: string): SessionEvent[];
136
146
  /** Parse a Hermes session JSON file into normalized events. */
137
147
  export declare function parseHermes(filePath: string): SessionEvent[];
138
148
  /** Parse a Kimi session state.json file by reading its agents/main/wire.jsonl. */