@phnx-labs/agents-cli 1.20.29 → 1.20.30

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 (45) hide show
  1. package/dist/commands/computer-actions.js +6 -2
  2. package/dist/commands/computer.d.ts +12 -0
  3. package/dist/commands/computer.js +88 -13
  4. package/dist/commands/inspect.js +1 -1
  5. package/dist/commands/models.js +8 -2
  6. package/dist/commands/sessions.js +156 -44
  7. package/dist/commands/sync.js +70 -14
  8. package/dist/lib/agents.d.ts +0 -4
  9. package/dist/lib/agents.js +54 -5
  10. package/dist/lib/browser/drivers/ssh.js +4 -35
  11. package/dist/lib/computer-rpc.d.ts +6 -1
  12. package/dist/lib/computer-rpc.js +86 -3
  13. package/dist/lib/exec.js +14 -0
  14. package/dist/lib/models.js +138 -5
  15. package/dist/lib/runner.js +7 -7
  16. package/dist/lib/session/active.d.ts +13 -0
  17. package/dist/lib/session/active.js +79 -18
  18. package/dist/lib/session/cloud.js +2 -0
  19. package/dist/lib/session/db.d.ts +11 -0
  20. package/dist/lib/session/db.js +62 -5
  21. package/dist/lib/session/discover.d.ts +5 -0
  22. package/dist/lib/session/discover.js +81 -0
  23. package/dist/lib/session/parse.d.ts +15 -0
  24. package/dist/lib/session/parse.js +22 -2
  25. package/dist/lib/session/remote.d.ts +1 -1
  26. package/dist/lib/session/remote.js +8 -3
  27. package/dist/lib/session/state.d.ts +82 -0
  28. package/dist/lib/session/state.js +221 -0
  29. package/dist/lib/session/tail.d.ts +18 -0
  30. package/dist/lib/session/tail.js +57 -0
  31. package/dist/lib/session/types.d.ts +9 -0
  32. package/dist/lib/session/width.d.ts +29 -0
  33. package/dist/lib/session/width.js +91 -0
  34. package/dist/lib/shims.d.ts +17 -1
  35. package/dist/lib/shims.js +130 -6
  36. package/dist/lib/ssh-tunnel.d.ts +127 -0
  37. package/dist/lib/ssh-tunnel.js +346 -0
  38. package/dist/lib/state.d.ts +2 -0
  39. package/dist/lib/state.js +17 -1
  40. package/dist/lib/teams/agents.d.ts +11 -1
  41. package/dist/lib/teams/agents.js +16 -2
  42. package/dist/lib/types.d.ts +1 -0
  43. package/dist/lib/versions.d.ts +19 -0
  44. package/dist/lib/versions.js +84 -24
  45. package/package.json +1 -1
@@ -165,6 +165,26 @@ export function locateModelSource(agent, version) {
165
165
  return { path: pathBin, kind: 'cli' };
166
166
  return null;
167
167
  }
168
+ if (agent === 'antigravity') {
169
+ // The `agy` shim under node_modules/.bin exposes `agy models`. We don't parse
170
+ // any bundle; the CLI produces its own (display-name-only) catalog.
171
+ const cli = path.join(versionDir, 'node_modules', '.bin', 'agy');
172
+ if (fs.existsSync(cli))
173
+ return { path: cli, kind: 'cli' };
174
+ const pathBin = findOnPath('agy');
175
+ if (pathBin)
176
+ return { path: pathBin, kind: 'cli' };
177
+ return null;
178
+ }
179
+ if (agent === 'kimi') {
180
+ const cli = path.join(versionDir, 'node_modules', '.bin', 'kimi');
181
+ if (fs.existsSync(cli))
182
+ return { path: cli, kind: 'cli' };
183
+ const pathBin = findOnPath('kimi');
184
+ if (pathBin)
185
+ return { path: pathBin, kind: 'cli' };
186
+ return null;
187
+ }
168
188
  if (agent === 'cursor') {
169
189
  // cursor-agent is installed via curl script, not agents-cli. Version argument
170
190
  // is accepted for API symmetry but ignored -- cursor lives on PATH.
@@ -606,6 +626,114 @@ function extractOpenClawCatalog(binaryPath) {
606
626
  }));
607
627
  return { models, aliases: {} };
608
628
  }
629
+ /**
630
+ * Extract Antigravity's catalog via `agy models`. Antigravity is unusual: it
631
+ * prints DISPLAY NAMES ONLY, one per line, with no machine ids and no --json:
632
+ * Gemini 3.5 Flash (Medium)
633
+ * Claude Sonnet 4.6 (Thinking)
634
+ * Verified (agy 1.0.11) that those display strings ARE the accepted `--model`
635
+ * values -- `agy --model "Claude Opus 4.6 (Thinking)"` routes to that model,
636
+ * and an unknown value silently falls back to the first row. So we use each
637
+ * display string as both id and displayName, and mark the first row default.
638
+ */
639
+ function extractAntigravityCatalog(binaryPath) {
640
+ let stdout;
641
+ try {
642
+ stdout = execFileSync(binaryPath, ['models'], {
643
+ encoding: 'utf-8',
644
+ stdio: ['ignore', 'pipe', 'ignore'],
645
+ timeout: 15_000,
646
+ maxBuffer: 8 * 1024 * 1024,
647
+ });
648
+ }
649
+ catch {
650
+ return { models: [], aliases: {} };
651
+ }
652
+ // Strip ANSI in case a spinner or color codes slip through.
653
+ // eslint-disable-next-line no-control-regex
654
+ const plain = stdout.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
655
+ const models = [];
656
+ const seen = new Set();
657
+ for (const raw of plain.split('\n')) {
658
+ const name = raw.trim();
659
+ if (!name)
660
+ continue;
661
+ // Guard against any stray banner/usage lines: real rows look like
662
+ // "<Vendor> <Model> (<Level>)". Require an alphanumeric start and a
663
+ // parenthesized suffix, which every observed model row has.
664
+ if (!/^[A-Za-z0-9].*\([^)]+\)\s*$/.test(name))
665
+ continue;
666
+ if (seen.has(name))
667
+ continue;
668
+ seen.add(name);
669
+ models.push({
670
+ id: name,
671
+ displayName: name,
672
+ // Antigravity's first listed model is its default (unknown --model values
673
+ // fall back to it), so flag the first row we accept.
674
+ isDefault: models.length === 0,
675
+ });
676
+ }
677
+ return { models, aliases: {} };
678
+ }
679
+ /**
680
+ * Extract Kimi's catalog via `kimi provider list --json`, which emits the raw
681
+ * providers/models config. Model ids are the `models` object keys (e.g.
682
+ * `kimi-code/kimi-for-coding`). The default is reported on a separate plain
683
+ * `Default model: <id>` line by `kimi provider list` (no flags), so we run that
684
+ * too to flag the default row.
685
+ */
686
+ function extractKimiCatalog(binaryPath) {
687
+ let jsonOut;
688
+ try {
689
+ jsonOut = execFileSync(binaryPath, ['provider', 'list', '--json'], {
690
+ encoding: 'utf-8',
691
+ stdio: ['ignore', 'pipe', 'ignore'],
692
+ timeout: 15_000,
693
+ maxBuffer: 16 * 1024 * 1024,
694
+ });
695
+ }
696
+ catch {
697
+ return { models: [], aliases: {} };
698
+ }
699
+ const firstBrace = jsonOut.indexOf('{');
700
+ if (firstBrace === -1)
701
+ return { models: [], aliases: {} };
702
+ let parsed;
703
+ try {
704
+ parsed = JSON.parse(jsonOut.slice(firstBrace));
705
+ }
706
+ catch {
707
+ return { models: [], aliases: {} };
708
+ }
709
+ // Resolve the default model id from the plain listing's "Default model:" line.
710
+ let defaultId = null;
711
+ try {
712
+ const plain = execFileSync(binaryPath, ['provider', 'list'], {
713
+ encoding: 'utf-8',
714
+ stdio: ['ignore', 'pipe', 'ignore'],
715
+ timeout: 10_000,
716
+ maxBuffer: 4 * 1024 * 1024,
717
+ });
718
+ const m = plain.match(/Default model:\s*(\S+)/);
719
+ if (m)
720
+ defaultId = m[1];
721
+ }
722
+ catch {
723
+ /* default flag is best-effort */
724
+ }
725
+ const modelsObj = parsed?.models && typeof parsed.models === 'object' ? parsed.models : {};
726
+ const models = [];
727
+ for (const id of Object.keys(modelsObj)) {
728
+ const info = modelsObj[id] ?? {};
729
+ models.push({
730
+ id,
731
+ displayName: typeof info.displayName === 'string' ? info.displayName : undefined,
732
+ isDefault: defaultId != null && id === defaultId,
733
+ });
734
+ }
735
+ return { models, aliases: {} };
736
+ }
609
737
  /**
610
738
  * Build (or load from cache) the model catalog for a specific (agent, version).
611
739
  * Cache is keyed on source-file mtime (binary or js module), so re-extracts
@@ -654,6 +782,10 @@ export function getModelCatalog(agent, version) {
654
782
  ({ models, aliases } = extractCursorCatalog(src.path));
655
783
  else if (agent === 'openclaw')
656
784
  ({ models, aliases } = extractOpenClawCatalog(src.path));
785
+ else if (agent === 'antigravity')
786
+ ({ models, aliases } = extractAntigravityCatalog(src.path));
787
+ else if (agent === 'kimi')
788
+ ({ models, aliases } = extractKimiCatalog(src.path));
657
789
  }
658
790
  const catalog = {
659
791
  agent,
@@ -663,11 +795,12 @@ export function getModelCatalog(agent, version) {
663
795
  models,
664
796
  aliases,
665
797
  };
666
- // Don't cache empty CLI extractions: the CLI may have been mid-install,
667
- // network-dependent, or transiently failing. Caching 0 models would mask
668
- // the real catalog forever (mtime won't change). Bundle/binary/js sources
669
- // are deterministic, so cache those even when empty.
670
- if (src.kind !== 'cli' || models.length > 0) {
798
+ // Never cache an empty extraction, regardless of source kind. A 0-model
799
+ // result is always suspect: the CLI may have been mid-install, network-
800
+ // dependent, or transiently failing, and a js/bundle/binary extractor that
801
+ // regex-misses would otherwise pin an empty catalog forever (mtime won't
802
+ // change until the source file does). Only persist a non-empty catalog.
803
+ if (models.length > 0) {
671
804
  cache.entries[key] = { sourcePath: src.path, mtime, catalog };
672
805
  saveCache();
673
806
  }
@@ -95,14 +95,14 @@ export function buildJobCommand(config, resolvedPrompt) {
95
95
  appendModelAndReasoning(cmd, config);
96
96
  }
97
97
  if (config.agent === 'kimi') {
98
+ // kimi daemon jobs always run headless via `--prompt`, which cannot be
99
+ // combined with any startup-mode flag (--plan/--auto/--yolo all abort with
100
+ // "Cannot combine --prompt with --X"). edit/auto/skip reduce to kimi's default
101
+ // headless auto-run, so emit no flag; plan has no headless read-only
102
+ // equivalent, so fail closed rather than silently allowing writes.
98
103
  if (mode === 'plan') {
99
- cmd.push('--plan');
100
- }
101
- else if (mode === 'auto') {
102
- cmd.push('--auto');
103
- }
104
- else if (mode === 'skip') {
105
- cmd.push('--yolo');
104
+ throw new Error('kimi has no headless read-only mode: routine jobs cannot run kimi with --mode plan ' +
105
+ '(kimi rejects --prompt + --plan). Use --mode edit, auto, or skip.');
106
106
  }
107
107
  appendModelAndReasoning(cmd, config);
108
108
  }
@@ -1,3 +1,4 @@
1
+ import { type SessionActivity, type AwaitingReason, type DetectedPr, type DetectedWorktree, type DetectedTicket } from './state.js';
1
2
  export type ActiveContext = 'terminal' | 'teams' | 'cloud' | 'headless';
2
3
  export type ActiveStatus = 'running' | 'idle' | 'queued' | 'input_required';
3
4
  export interface ActiveSession {
@@ -12,6 +13,18 @@ export interface ActiveSession {
12
13
  label?: string;
13
14
  /** First meaningful line of the initial prompt (extracted topic). */
14
15
  topic?: string;
16
+ /** Live preview: the latest turn (agent message or tool action), from the state engine. */
17
+ preview?: string;
18
+ /** Inferred activity: working / waiting_input / idle (from the transcript tail). */
19
+ activity?: SessionActivity;
20
+ /** Why the agent is waiting, when activity is waiting_input. */
21
+ awaitingReason?: AwaitingReason;
22
+ /** PR opened during the session. */
23
+ pr?: DetectedPr;
24
+ /** Worktree the session runs in. */
25
+ worktree?: DetectedWorktree;
26
+ /** Tracker ticket the session is tied to. */
27
+ ticket?: DetectedTicket;
15
28
  sessionFile?: string;
16
29
  startedAtMs?: number;
17
30
  status: ActiveStatus;
@@ -25,7 +25,10 @@ import { listActiveTasks } from '../cloud/store.js';
25
25
  import { AgentManager } from '../teams/agents.js';
26
26
  import { getTerminalsDir } from '../state.js';
27
27
  import { buildClaudeLabelMap } from './discover.js';
28
+ import { latestSessionFileForCwd } from './db.js';
28
29
  import { extractSessionTopic } from './prompt.js';
30
+ import { readSessionTail } from './tail.js';
31
+ import { inferSessionState } from './state.js';
29
32
  const execFileAsync = promisify(execFile);
30
33
  const HOME = os.homedir();
31
34
  const LIVE_TERMINALS_FILE = path.join(getTerminalsDir(), 'live-terminals.json');
@@ -42,6 +45,7 @@ const AGENT_CLI_NAMES = {
42
45
  gemini: 'gemini',
43
46
  'cursor-agent': 'cursor',
44
47
  opencode: 'opencode',
48
+ droid: 'droid',
45
49
  };
46
50
  function isPidAlive(pid) {
47
51
  if (!pid || pid < 1)
@@ -128,6 +132,66 @@ function classifyActivity(sessionFile) {
128
132
  return 'running';
129
133
  }
130
134
  }
135
+ /**
136
+ * Locate the live transcript for an agent process. Claude files are keyed by
137
+ * cwd (+ optional session uuid); Codex files are date-partitioned, so we resolve
138
+ * the newest indexed Codex session for the cwd instead.
139
+ */
140
+ function findSessionFileForKind(kind, cwd, sessionId) {
141
+ if (!cwd)
142
+ return undefined;
143
+ if (kind === 'claude')
144
+ return findClaudeSessionFile(cwd, sessionId);
145
+ if (kind === 'codex')
146
+ return latestSessionFileForCwd('codex', cwd);
147
+ return undefined;
148
+ }
149
+ /** Recover the session UUID from a transcript filename (Claude `<uuid>.jsonl`, Codex `rollout-…-<uuid>.jsonl`). */
150
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
151
+ function sessionIdFromFile(file) {
152
+ if (!file)
153
+ return undefined;
154
+ return path.basename(file).match(UUID_RE)?.[0];
155
+ }
156
+ /** Infer live state from a session file's tail (Claude/Codex). Undefined when unreadable. */
157
+ function computeLiveState(kind, sessionFile, cwd, pidAlive) {
158
+ if (!sessionFile)
159
+ return undefined;
160
+ const agent = kind === 'codex' ? 'codex' : 'claude';
161
+ const events = readSessionTail(sessionFile, agent);
162
+ if (events.length === 0)
163
+ return undefined;
164
+ let mtimeMs;
165
+ try {
166
+ mtimeMs = fs.statSync(sessionFile).mtimeMs;
167
+ }
168
+ catch { /* vanished between calls */ }
169
+ return inferSessionState(events, { cwd, pidAlive, mtimeMs, activeWindowMs: ACTIVE_MTIME_WINDOW_MS });
170
+ }
171
+ /** Map inferred activity onto the coarse ActiveStatus used by the renderer and counts. */
172
+ function statusFromActivity(activity) {
173
+ return activity === 'working' ? 'running' : activity === 'waiting_input' ? 'input_required' : 'idle';
174
+ }
175
+ /**
176
+ * Fold a computed SessionState onto an active-session row: rich status +
177
+ * preview + PR/worktree/ticket badges. With no state (unreadable/non-Claude/
178
+ * Codex file) it degrades to the mtime-only classification.
179
+ */
180
+ function applyState(base, state, fallbackFile) {
181
+ if (!state)
182
+ return { ...base, status: classifyActivity(fallbackFile) };
183
+ return {
184
+ ...base,
185
+ status: statusFromActivity(state.activity),
186
+ activity: state.activity,
187
+ awaitingReason: state.awaitingReason,
188
+ // Prefer the live preview (latest turn); keep the first-prompt topic as a fallback.
189
+ preview: state.preview ?? base.preview,
190
+ pr: state.pr,
191
+ worktree: state.worktree,
192
+ ticket: state.ticket,
193
+ };
194
+ }
131
195
  /**
132
196
  * Extract the first user message's content from a Claude JSONL file.
133
197
  * Reads only the first ~50 lines for speed, since the user message is
@@ -207,24 +271,22 @@ export async function listTeamsActive() {
207
271
  const running = await mgr.listRunning();
208
272
  return running.map((a) => {
209
273
  const sessionId = a.parentSessionId ?? a.remoteSessionId ?? undefined;
210
- const sessionFile = a.agentType === 'claude' && a.cwd
211
- ? findClaudeSessionFile(a.cwd, sessionId ?? undefined)
212
- : undefined;
274
+ const sessionFile = findSessionFileForKind(a.agentType, a.cwd ?? undefined, sessionId ?? undefined);
213
275
  const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
214
- return {
276
+ const state = computeLiveState(a.agentType, sessionFile, a.cwd ?? undefined, a.pid ? isPidAlive(a.pid) : true);
277
+ return applyState({
215
278
  context: 'teams',
216
279
  kind: a.agentType,
217
280
  pid: a.pid ?? undefined,
218
- sessionId,
281
+ sessionId: sessionId ?? sessionIdFromFile(sessionFile),
219
282
  cwd: a.cwd ?? undefined,
220
283
  label: a.name ?? undefined,
221
284
  topic,
222
285
  sessionFile,
223
286
  startedAtMs: a.startedAt.getTime(),
224
- status: classifyActivity(sessionFile),
225
287
  teamName: a.taskName,
226
288
  agentId: a.agentId,
227
- };
289
+ }, state, sessionFile);
228
290
  });
229
291
  }
230
292
  /** Live editor-terminal agents across every IDE window. */
@@ -240,27 +302,25 @@ export async function listTerminalsActive() {
240
302
  // Build label map from Claude's sessions/*.json for /rename support
241
303
  const labelMap = buildClaudeLabelMap();
242
304
  return entries.map((t) => {
243
- const sessionFile = t.kind === 'claude' && t.cwd
244
- ? findClaudeSessionFile(t.cwd, t.sessionId)
245
- : undefined;
305
+ const sessionFile = findSessionFileForKind(t.kind, t.cwd ?? undefined, t.sessionId);
246
306
  // Prefer label from live terminal, fall back to Claude's session label
247
307
  const label = t.label ?? (t.sessionId ? labelMap.get(t.sessionId) : undefined) ?? undefined;
248
308
  // Extract topic from session file (first meaningful user message)
249
309
  const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
250
- return {
310
+ const state = computeLiveState(t.kind, sessionFile, t.cwd ?? undefined, isPidAlive(t.pid));
311
+ return applyState({
251
312
  context: 'terminal',
252
313
  kind: t.kind,
253
314
  host: detectHost(t.pid, procByPid),
254
315
  pid: t.pid,
255
- sessionId: t.sessionId,
316
+ sessionId: t.sessionId ?? sessionIdFromFile(sessionFile),
256
317
  cwd: t.cwd ?? undefined,
257
318
  label,
258
319
  topic,
259
320
  sessionFile,
260
321
  startedAtMs: t.startedAtMs,
261
- status: classifyActivity(sessionFile),
262
322
  windowId: t.windowId,
263
- };
323
+ }, state, sessionFile);
264
324
  });
265
325
  }
266
326
  /** Cloud tasks still in a non-terminal state. `tasks.db` may not exist; that's fine. */
@@ -439,20 +499,21 @@ export async function listUnattributedActive(attributed) {
439
499
  for (let i = 0; i < candidates.length; i++) {
440
500
  const { pid, kind } = candidates[i];
441
501
  const cwd = cwds[i];
442
- const sessionFile = kind === 'claude' && cwd ? findClaudeSessionFile(cwd) : undefined;
502
+ const sessionFile = findSessionFileForKind(kind, cwd);
443
503
  const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
444
504
  const host = detectHost(pid, procByPid);
445
505
  const context = host && UI_HOSTS.has(host) ? 'terminal' : 'headless';
446
- out.push({
506
+ const state = computeLiveState(kind, sessionFile, cwd, true);
507
+ out.push(applyState({
447
508
  context,
448
509
  kind,
449
510
  host,
450
511
  pid,
451
512
  cwd,
513
+ sessionId: sessionIdFromFile(sessionFile),
452
514
  topic,
453
515
  sessionFile,
454
- status: classifyActivity(sessionFile),
455
- });
516
+ }, state, sessionFile));
456
517
  }
457
518
  return out;
458
519
  }
@@ -44,6 +44,8 @@ function agentToFormat(agent) {
44
44
  return 'codex';
45
45
  if (agent === 'rush')
46
46
  return 'rush';
47
+ if (agent === 'droid')
48
+ return 'droid';
47
49
  return null;
48
50
  }
49
51
  export function assertContained(candidate, rootDir) {
@@ -30,6 +30,10 @@ export interface SessionRow {
30
30
  file_size: number | null;
31
31
  scanned_at: number | null;
32
32
  is_team_origin: number;
33
+ pr_url: string | null;
34
+ pr_number: number | null;
35
+ worktree_slug: string | null;
36
+ ticket_id: string | null;
33
37
  }
34
38
  /** File stat snapshot used to detect changes between scan runs. */
35
39
  export interface ScanStamp {
@@ -133,6 +137,13 @@ export declare function syncLabels(labelMap: Map<string, string | null>): number
133
137
  * Returns the number of rows updated.
134
138
  */
135
139
  export declare function syncTopics(topicMap: Map<string, string>): number;
140
+ /**
141
+ * Newest indexed session file for an agent working in `cwd`. Lets the live
142
+ * `--active` scanner locate a Codex transcript (whose files are date-partitioned,
143
+ * not cwd-keyed like Claude's) by reusing the index. Returns undefined if the
144
+ * session hasn't been scanned yet — the caller degrades to no live state.
145
+ */
146
+ export declare function latestSessionFileForCwd(agent: SessionAgentId, cwd: string): string | undefined;
136
147
  /** Query sessions from the database, applying filters and ordering by timestamp descending. */
137
148
  export declare function querySessions(options?: QueryOptions): SessionMeta[];
138
149
  /** Count sessions matching the given filter options. */
@@ -13,7 +13,7 @@ import { getSessionsDir, getSessionsDbPath } from '../state.js';
13
13
  const SESSIONS_DIR = getSessionsDir();
14
14
  const DB_PATH = getSessionsDbPath();
15
15
  /** Current schema version; bumped when migrations are added. */
16
- const SCHEMA_VERSION = 6;
16
+ const SCHEMA_VERSION = 7;
17
17
  /**
18
18
  * Canonicalize a file path for use as a scan_ledger key. The same physical
19
19
  * session file is reachable via multiple aliases — `~/.claude/projects/x.jsonl`
@@ -59,7 +59,11 @@ CREATE TABLE IF NOT EXISTS sessions (
59
59
  file_mtime_ms INTEGER,
60
60
  file_size INTEGER,
61
61
  scanned_at INTEGER,
62
- is_team_origin INTEGER DEFAULT 0
62
+ is_team_origin INTEGER DEFAULT 0,
63
+ pr_url TEXT,
64
+ pr_number INTEGER,
65
+ worktree_slug TEXT,
66
+ ticket_id TEXT
63
67
  );
64
68
  CREATE INDEX IF NOT EXISTS idx_sessions_timestamp ON sessions(timestamp DESC);
65
69
  CREATE INDEX IF NOT EXISTS idx_sessions_cwd ON sessions(cwd);
@@ -157,6 +161,21 @@ function migrateSchema(db, fromVersion) {
157
161
  }
158
162
  db.exec(`DELETE FROM scan_ledger;`);
159
163
  }
164
+ if (fromVersion < 7) {
165
+ // v6 → v7: the session-state engine now persists durable signals (PR opened,
166
+ // worktree, tracker ticket) at scan time. Add the columns and force a full
167
+ // rescan so every existing session gets them populated.
168
+ const cols = db.prepare(`PRAGMA table_info(sessions)`).all();
169
+ if (!cols.some(c => c.name === 'pr_url'))
170
+ db.exec(`ALTER TABLE sessions ADD COLUMN pr_url TEXT`);
171
+ if (!cols.some(c => c.name === 'pr_number'))
172
+ db.exec(`ALTER TABLE sessions ADD COLUMN pr_number INTEGER`);
173
+ if (!cols.some(c => c.name === 'worktree_slug'))
174
+ db.exec(`ALTER TABLE sessions ADD COLUMN worktree_slug TEXT`);
175
+ if (!cols.some(c => c.name === 'ticket_id'))
176
+ db.exec(`ALTER TABLE sessions ADD COLUMN ticket_id TEXT`);
177
+ db.exec(`DELETE FROM scan_ledger;`);
178
+ }
160
179
  }
161
180
  /** Open (or return the cached) sessions database, applying migrations as needed. */
162
181
  export function getDB() {
@@ -367,12 +386,14 @@ const upsertSessionStmt = (db) => db.prepare(`
367
386
  id, short_id, agent, version, account, timestamp,
368
387
  project, cwd, git_branch, topic, label, message_count, token_count,
369
388
  cost_usd, duration_ms,
370
- file_path, file_mtime_ms, file_size, scanned_at, is_team_origin
389
+ file_path, file_mtime_ms, file_size, scanned_at, is_team_origin,
390
+ pr_url, pr_number, worktree_slug, ticket_id
371
391
  ) VALUES (
372
392
  @id, @short_id, @agent, @version, @account, @timestamp,
373
393
  @project, @cwd, @git_branch, @topic, @label, @message_count, @token_count,
374
394
  @cost_usd, @duration_ms,
375
- @file_path, @file_mtime_ms, @file_size, @scanned_at, @is_team_origin
395
+ @file_path, @file_mtime_ms, @file_size, @scanned_at, @is_team_origin,
396
+ @pr_url, @pr_number, @worktree_slug, @ticket_id
376
397
  )
377
398
  ON CONFLICT(id) DO UPDATE SET
378
399
  short_id = excluded.short_id,
@@ -393,7 +414,11 @@ const upsertSessionStmt = (db) => db.prepare(`
393
414
  file_mtime_ms = excluded.file_mtime_ms,
394
415
  file_size = excluded.file_size,
395
416
  scanned_at = excluded.scanned_at,
396
- is_team_origin = excluded.is_team_origin
417
+ is_team_origin = excluded.is_team_origin,
418
+ pr_url = excluded.pr_url,
419
+ pr_number = excluded.pr_number,
420
+ worktree_slug = excluded.worktree_slug,
421
+ ticket_id = excluded.ticket_id
397
422
  `);
398
423
  const deleteTextStmt = (db) => db.prepare(`DELETE FROM session_text WHERE session_id = ?`);
399
424
  const insertTextStmt = (db) => db.prepare(`INSERT INTO session_text (session_id, label, topic, project, content) VALUES (?, ?, ?, ?, ?)`);
@@ -436,6 +461,10 @@ export function upsertSession(meta, content, scan) {
436
461
  file_size: scan?.fileSize ?? null,
437
462
  scanned_at: Date.now(),
438
463
  is_team_origin: meta.isTeamOrigin ? 1 : 0,
464
+ pr_url: meta.prUrl ?? null,
465
+ pr_number: meta.prNumber ?? null,
466
+ worktree_slug: meta.worktreeSlug ?? null,
467
+ ticket_id: meta.ticketId ?? null,
439
468
  };
440
469
  const txn = db.transaction(() => {
441
470
  upsert.run(row);
@@ -511,6 +540,10 @@ export function upsertSessionsBatch(entries) {
511
540
  file_size: scan?.fileSize ?? null,
512
541
  scanned_at: now,
513
542
  is_team_origin: meta.isTeamOrigin ? 1 : 0,
543
+ pr_url: meta.prUrl ?? null,
544
+ pr_number: meta.prNumber ?? null,
545
+ worktree_slug: meta.worktreeSlug ?? null,
546
+ ticket_id: meta.ticketId ?? null,
514
547
  });
515
548
  delText.run(meta.id);
516
549
  insText.run(meta.id, meta.label ?? '', meta.topic ?? '', meta.project ?? '', content ?? '');
@@ -621,8 +654,32 @@ function rowToMeta(row) {
621
654
  topic: row.topic ?? undefined,
622
655
  label: row.label ?? undefined,
623
656
  isTeamOrigin: row.is_team_origin === 1,
657
+ prUrl: row.pr_url ?? undefined,
658
+ prNumber: row.pr_number ?? undefined,
659
+ worktreeSlug: row.worktree_slug ?? undefined,
660
+ ticketId: row.ticket_id ?? undefined,
624
661
  };
625
662
  }
663
+ /**
664
+ * Newest indexed session file for an agent working in `cwd`. Lets the live
665
+ * `--active` scanner locate a Codex transcript (whose files are date-partitioned,
666
+ * not cwd-keyed like Claude's) by reusing the index. Returns undefined if the
667
+ * session hasn't been scanned yet — the caller degrades to no live state.
668
+ */
669
+ export function latestSessionFileForCwd(agent, cwd) {
670
+ if (!cwd)
671
+ return undefined;
672
+ let normalized = cwd;
673
+ try {
674
+ normalized = fs.realpathSync(cwd);
675
+ }
676
+ catch { /* use as-is */ }
677
+ const db = getDB();
678
+ const row = db
679
+ .prepare(`SELECT file_path FROM sessions WHERE agent = ? AND cwd = ? ORDER BY timestamp DESC LIMIT 1`)
680
+ .get(agent, normalized);
681
+ return row?.file_path;
682
+ }
626
683
  /** Build a parameterized WHERE clause from query options. */
627
684
  function buildSessionWhere(options) {
628
685
  const where = [];
@@ -57,6 +57,11 @@ interface ClaudeSessionScan {
57
57
  entrypoint?: string;
58
58
  /** Concatenated user message text, ready to hand to FTS5. */
59
59
  contentText?: string;
60
+ /** Durable state signals persisted to the index by the session-state engine. */
61
+ prUrl?: string;
62
+ prNumber?: number;
63
+ worktreeSlug?: string;
64
+ ticketId?: string;
60
65
  }
61
66
  /**
62
67
  * Discover sessions. Scans only files whose (mtime, size) have changed since