@phnx-labs/agents-cli 1.23.0 → 1.23.1

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 (59) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +2 -0
  3. package/dist/commands/cloud-transcripts.js +1 -2
  4. package/dist/commands/daemon.js +70 -11
  5. package/dist/commands/exec.js +1 -1
  6. package/dist/commands/feed.js +1 -2
  7. package/dist/commands/focus.js +4 -1
  8. package/dist/commands/go.js +3 -2
  9. package/dist/commands/logs.js +1 -1
  10. package/dist/commands/menubar.js +28 -3
  11. package/dist/commands/ps-roster.d.ts +0 -11
  12. package/dist/commands/ps-roster.js +3 -116
  13. package/dist/commands/ps.d.ts +10 -0
  14. package/dist/commands/ps.js +182 -1
  15. package/dist/commands/resume.js +1 -1
  16. package/dist/commands/sessions-browser.d.ts +0 -1
  17. package/dist/commands/sessions-browser.js +6 -23
  18. package/dist/commands/sessions-export.js +1 -1
  19. package/dist/commands/sessions-migrate.js +1 -1
  20. package/dist/commands/sessions-picker.d.ts +6 -32
  21. package/dist/commands/sessions-picker.js +81 -8
  22. package/dist/commands/sessions-render.js +1 -1
  23. package/dist/commands/sessions-resume.js +2 -2
  24. package/dist/commands/sessions-share.js +1 -1
  25. package/dist/commands/sessions-trace.js +1 -1
  26. package/dist/commands/sessions.d.ts +2 -165
  27. package/dist/commands/sessions.js +16 -1216
  28. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  29. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  30. package/dist/lib/daemon/attention-notify-service.js +8 -4
  31. package/dist/lib/daemon/daemon.d.ts +5 -1
  32. package/dist/lib/daemon/daemon.js +53 -6
  33. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  34. package/dist/lib/daemon/diagnostics.js +185 -0
  35. package/dist/lib/daemon/service.d.ts +1 -1
  36. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  37. package/dist/lib/daemon/session-state-service.js +2 -2
  38. package/dist/lib/daemon/supervisor.d.ts +8 -0
  39. package/dist/lib/daemon/supervisor.js +47 -6
  40. package/dist/lib/daemon-services.d.ts +3 -0
  41. package/dist/lib/daemon-services.js +36 -0
  42. package/dist/lib/daemon-ticks.d.ts +3 -1
  43. package/dist/lib/daemon-ticks.js +18 -12
  44. package/dist/lib/feed/tool-activity.js +10 -3
  45. package/dist/lib/feed/watch.js +8 -5
  46. package/dist/lib/helper-versions.js +1 -1
  47. package/dist/lib/menubar/install-menubar.d.ts +18 -0
  48. package/dist/lib/menubar/install-menubar.js +59 -1
  49. package/dist/lib/session/active.js +18 -14
  50. package/dist/lib/session/pid-registry.js +9 -6
  51. package/dist/lib/session/presentation.d.ts +107 -1
  52. package/dist/lib/session/presentation.js +543 -4
  53. package/dist/lib/session/remote/remote-list.d.ts +3 -0
  54. package/dist/lib/session/remote/remote-list.js +13 -0
  55. package/dist/lib/session/resume-command.d.ts +9 -0
  56. package/dist/lib/session/resume-command.js +107 -0
  57. package/dist/lib/session/selection.d.ts +102 -0
  58. package/dist/lib/session/selection.js +443 -0
  59. package/package.json +1 -1
@@ -1,3 +1,110 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { spawn } from 'child_process';
4
+ import chalk from 'chalk';
5
+ import { AGENTS } from '../agents.js';
6
+ import { getAgentsInvocation } from '../daemon/daemon.js';
7
+ import { composeWin32CommandLine, needsWindowsShell } from '../platform/index.js';
8
+ import { getShimsDir } from '../state.js';
9
+ import { sessionAgentSupportsResume, sessionRecoveryRunArgs } from './recovery.js';
10
+ import { sessionOwnerDevice } from './resume-owner.js';
1
11
  export function buildCanonicalResumeCommand(sessionId) {
2
12
  return ['agents', 'sessions', 'resume', sessionId];
3
13
  }
14
+ export async function resumeSessionInPlace(session) {
15
+ const owner = sessionOwnerDevice(session);
16
+ if (owner) {
17
+ console.error(chalk.red(`Session ${session.shortId} belongs to ${owner} — it cannot resume on this machine.`));
18
+ console.error(chalk.gray(` Resume it there: agents sessions resume ${session.id}`));
19
+ process.exitCode = 1;
20
+ return;
21
+ }
22
+ const cwd = session.cwd && fs.existsSync(session.cwd)
23
+ ? session.cwd
24
+ : process.cwd();
25
+ const resume = buildSessionRecoveryCommand(session);
26
+ console.log(chalk.gray(`Resuming: ${resume.join(' ')} (cwd: ${cwd})`));
27
+ await spawnResumeCommand(resume, cwd);
28
+ }
29
+ export function buildSessionRecoveryCommand(session, portable = false) {
30
+ const args = sessionRecoveryRunArgs(session);
31
+ if (portable)
32
+ return ['agents', ...args];
33
+ const invocation = getAgentsInvocation(args);
34
+ return [invocation.command, ...invocation.args];
35
+ }
36
+ export function resumeSpawnInvocation(cmd, platform = process.platform) {
37
+ const shell = needsWindowsShell(cmd[0], platform);
38
+ if (shell) {
39
+ return {
40
+ command: composeWin32CommandLine(cmd[0], cmd.slice(1)),
41
+ args: [],
42
+ shell: true,
43
+ };
44
+ }
45
+ return { command: cmd[0], args: cmd.slice(1), shell: false };
46
+ }
47
+ function spawnResumeCommand(cmd, cwd) {
48
+ return new Promise((resolve) => {
49
+ let child;
50
+ try {
51
+ const { command, args, shell } = resumeSpawnInvocation(cmd);
52
+ child = spawn(command, args, {
53
+ cwd,
54
+ stdio: 'inherit',
55
+ shell,
56
+ });
57
+ }
58
+ catch (err) {
59
+ console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
60
+ resolve();
61
+ return;
62
+ }
63
+ child.on('error', (err) => {
64
+ console.error(chalk.red(`Failed to launch ${cmd[0]}: ${err.message}`));
65
+ if (err.code === 'ENOENT') {
66
+ console.error(chalk.gray(`Make sure '${cmd[0]}' is on your PATH.`));
67
+ }
68
+ resolve();
69
+ });
70
+ child.on('close', () => resolve());
71
+ });
72
+ }
73
+ function resumeArgv(agent, id, launcher) {
74
+ switch (agent) {
75
+ case 'claude': return [launcher, '--resume', id];
76
+ case 'codex': return [launcher, 'resume', id];
77
+ case 'opencode': return [launcher, '--session', id];
78
+ case 'muse': return [launcher, 'resume', id];
79
+ default: return null;
80
+ }
81
+ }
82
+ function versionedAliasIfPresent(agent, version) {
83
+ const cli = AGENTS[agent]?.cliCommand ?? agent;
84
+ const base = path.join(getShimsDir(), `${cli}@${version}`);
85
+ if (process.platform === 'win32' && fs.existsSync(`${base}.cmd`))
86
+ return `${base}.cmd`;
87
+ if (fs.existsSync(base))
88
+ return base;
89
+ return null;
90
+ }
91
+ export function buildResumeCommand(session) {
92
+ if (!sessionAgentSupportsResume(session.agent))
93
+ return null;
94
+ switch (session.agent) {
95
+ case 'opencode':
96
+ return resumeArgv('opencode', session.id, 'opencode');
97
+ case 'claude':
98
+ case 'codex':
99
+ case 'muse': {
100
+ const cli = AGENTS[session.agent]?.cliCommand ?? session.agent;
101
+ if (session.version) {
102
+ const alias = versionedAliasIfPresent(session.agent, session.version);
103
+ return resumeArgv(session.agent, session.id, alias ?? `${cli}@${session.version}`);
104
+ }
105
+ return resumeArgv(session.agent, session.id, cli);
106
+ }
107
+ default:
108
+ return null;
109
+ }
110
+ }
@@ -0,0 +1,102 @@
1
+ import type { SessionAgentId, SessionMeta } from '@phnx-labs/sessions-cli/reader';
2
+ import { type ActiveSession } from './active.js';
3
+ import { loadLocalActiveSessions } from './session-cache.js';
4
+ import { gatherRemoteList, runOnPeer } from './remote/remote-list.js';
5
+ export interface SessionFilterOptions {
6
+ agent?: string;
7
+ version?: string;
8
+ sessionVersion?: string;
9
+ project?: string;
10
+ all?: boolean;
11
+ teams?: boolean;
12
+ inTeam?: string;
13
+ routine?: boolean | string;
14
+ since?: string;
15
+ until?: string;
16
+ }
17
+ type InstalledVersionsForAgent = (agent: SessionAgentId) => string[];
18
+ export declare function parseInstalledAgentVersionQuery(query: string | undefined, installedVersions?: InstalledVersionsForAgent): string | undefined;
19
+ export declare function ticketLabel(s: Pick<SessionMeta, 'ticketId' | 'prNumber'>): string;
20
+ export declare function sessionMatchesQuery(s: SessionMeta, query: string): boolean;
21
+ export declare function mergeLocalFirst(sessions: SessionMeta[], localMachine: string): SessionMeta[];
22
+ export declare function serializeResolvedSessionsJson(sessions: SessionMeta[]): string;
23
+ interface AgentFilter {
24
+ agent?: SessionAgentId;
25
+ version?: string;
26
+ }
27
+ export declare function resolveSessionAgentName(name: string): SessionAgentId | null;
28
+ export declare function parseAgentFilter(agentName?: string): AgentFilter;
29
+ export type SessionSearchScope = {
30
+ agent?: string;
31
+ project?: string;
32
+ routine?: boolean | string;
33
+ };
34
+ interface SessionQueryResolution {
35
+ matches: SessionMeta[];
36
+ byId: boolean;
37
+ completeId: boolean;
38
+ }
39
+ export declare function resolveSessionQuery(pool: SessionMeta[], query: string, options?: {
40
+ indexFallback?: boolean;
41
+ scope?: SessionSearchScope;
42
+ }): SessionQueryResolution;
43
+ export declare function filterSessionsByQuery(sessions: SessionMeta[], query: string | undefined, scope?: SessionSearchScope): SessionMeta[];
44
+ export declare function applyScopeFilters(sessions: SessionMeta[], scope: SessionSearchScope): SessionMeta[];
45
+ export declare function scopedContentIndex(sessions: SessionMeta[], query: string, scope?: SessionSearchScope): Map<string, SessionMeta>;
46
+ export interface FleetResolveDeps {
47
+ gatherRemoteList: typeof gatherRemoteList;
48
+ runOnPeer: typeof runOnPeer;
49
+ }
50
+ interface FleetHit {
51
+ machine: string;
52
+ session: SessionMeta;
53
+ }
54
+ export interface FleetSessionCandidate {
55
+ id: string;
56
+ hits: FleetHit[];
57
+ }
58
+ export type MetadataResolveOutcome = {
59
+ kind: 'resolved';
60
+ session: SessionMeta;
61
+ } | {
62
+ kind: 'not-found';
63
+ } | {
64
+ kind: 'ambiguous';
65
+ candidates: FleetSessionCandidate[];
66
+ } | {
67
+ kind: 'partial';
68
+ failedPeers: string[];
69
+ };
70
+ export declare function isDefinitiveMatch(session: SessionMeta, selector: string): boolean;
71
+ export declare function selectorAllowsEarlyExit(selector: string): boolean;
72
+ export declare function fleetCandidatesByQuery(rows: SessionMeta[], query: string, trustResolvedRows?: boolean): FleetSessionCandidate[];
73
+ export declare function metadataResolveForwardedArgs(selector: string, scope: Pick<SessionFilterOptions, 'agent' | 'project'>): string[];
74
+ export declare function isUniqueEnoughSelector(selector: string): boolean;
75
+ export declare function metadataResolveOutcome(localMatches: SessionMeta[], remote: {
76
+ sessions: SessionMeta[];
77
+ unreachable: string[];
78
+ }, selector: string): MetadataResolveOutcome;
79
+ export declare function isLocallyDefinitiveMatch(session: SessionMeta, self: string): boolean;
80
+ export declare function preferOwnerAttribution(localMatches: SessionMeta[], remoteSessions: SessionMeta[], self: string): SessionMeta[];
81
+ export type LiveMetadataDeps = {
82
+ loadActive?: typeof loadLocalActiveSessions;
83
+ loadFleetActive?: () => ActiveSession[];
84
+ };
85
+ export declare function computeLocalMetadataMatches(selector: string, scope: {
86
+ agent?: string;
87
+ project?: string;
88
+ local?: boolean;
89
+ hosts?: string[];
90
+ }, deps?: LiveMetadataDeps): Promise<SessionMeta[]>;
91
+ export declare function liveMetadataMatches(selector: string, scope: {
92
+ agent?: string;
93
+ project?: string;
94
+ }, self: string, deps?: LiveMetadataDeps): Promise<SessionMeta[]>;
95
+ export declare function resolveSessionMetadataValue(selector: string, scope?: {
96
+ agent?: string;
97
+ project?: string;
98
+ local?: boolean;
99
+ hosts?: string[];
100
+ }, deps?: Pick<FleetResolveDeps, 'gatherRemoteList'> & LiveMetadataDeps): Promise<MetadataResolveOutcome>;
101
+ export declare function matchesTeam(session: SessionMeta, team: string): boolean;
102
+ export {};
@@ -0,0 +1,443 @@
1
+ import chalk from 'chalk';
2
+ import { SESSION_AGENTS, isAgentTmuxAlias, resolveRoutineName, safeTeamText } from '@phnx-labs/sessions-cli/reader';
3
+ import { shortIdFromName } from './active.js';
4
+ import { machineId } from './sync/config.js';
5
+ import { loadLocalActiveSessions, readActiveSessionsCache } from './session-cache.js';
6
+ import { gatherRemoteList, shouldIncludeLocal } from './remote/remote-list.js';
7
+ import { findLocalSessionTranscripts, hydrateSessionTranscript, isCompleteSessionId, looksLikeSessionId, resolveSessionById, scanSessionsIncremental, searchContentIndex, waitForScanToSettle, } from './discover.js';
8
+ import { findSessionsById, querySessions } from './db.js';
9
+ import { liveSessionMetas, fleetExecutionMachineById, reconcileLiveMetaMachine } from './live-metadata.js';
10
+ import { resolveSessionAlias } from './actor-sidecar.js';
11
+ import { AGENTS, resolveAgentName } from '../agents.js';
12
+ import { fuzzyMatch, FUZZY_PRESETS } from '../fuzzy.js';
13
+ import { listInstalledVersions, resolveVersionAliasLoose } from '../installations/versions.js';
14
+ export function parseInstalledAgentVersionQuery(query, installedVersions = (agent) => (agent in AGENTS ? listInstalledVersions(agent) : [])) {
15
+ const trimmed = query?.trim();
16
+ if (!trimmed)
17
+ return undefined;
18
+ const at = trimmed.indexOf('@');
19
+ if (at <= 0 || at !== trimmed.lastIndexOf('@') || at === trimmed.length - 1)
20
+ return undefined;
21
+ const agentName = trimmed.slice(0, at).toLowerCase();
22
+ if (!SESSION_AGENTS.includes(agentName))
23
+ return undefined;
24
+ const agent = agentName;
25
+ const version = trimmed.slice(at + 1);
26
+ return installedVersions(agent).includes(version) ? `${agent}@${version}` : undefined;
27
+ }
28
+ export function ticketLabel(s) {
29
+ return s.ticketId ?? (s.prNumber ? `PR#${s.prNumber}` : '');
30
+ }
31
+ export function sessionMatchesQuery(s, query) {
32
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
33
+ if (terms.length === 0)
34
+ return true;
35
+ const hay = [
36
+ s.shortId,
37
+ s.agent,
38
+ s.project,
39
+ s.cwd,
40
+ s.topic,
41
+ s.label,
42
+ ticketLabel(s),
43
+ s.machine,
44
+ ]
45
+ .filter(Boolean)
46
+ .join(' ')
47
+ .toLowerCase();
48
+ return terms.every((t) => hay.includes(t));
49
+ }
50
+ export function mergeLocalFirst(sessions, localMachine) {
51
+ const byMachine = new Map();
52
+ const seen = new Set();
53
+ for (const s of sessions) {
54
+ const machine = s.machine || localMachine;
55
+ if (s.id) {
56
+ const dedupeKey = `${machine}:${s.id}`;
57
+ if (seen.has(dedupeKey))
58
+ continue;
59
+ seen.add(dedupeKey);
60
+ }
61
+ (byMachine.get(machine) ?? byMachine.set(machine, []).get(machine)).push(s);
62
+ }
63
+ const keys = Array.from(byMachine.keys()).sort((a, b) => {
64
+ if (a === localMachine)
65
+ return -1;
66
+ if (b === localMachine)
67
+ return 1;
68
+ const ac = byMachine.get(a).length, bc = byMachine.get(b).length;
69
+ if (ac !== bc)
70
+ return bc - ac;
71
+ return a.localeCompare(b);
72
+ });
73
+ return keys.flatMap((k) => byMachine.get(k));
74
+ }
75
+ // Peer resolution exposes launch identity only; paths, plans, costs, and content stay local.
76
+ export function serializeResolvedSessionsJson(sessions) {
77
+ const safe = sessions.map((session) => ({
78
+ id: session.id,
79
+ shortId: session.shortId,
80
+ agent: session.agent,
81
+ harness: session.harness,
82
+ origin: session.origin,
83
+ timestamp: session.timestamp,
84
+ lastActivity: session.lastActivity,
85
+ project: session.project,
86
+ version: session.version,
87
+ mode: session.mode,
88
+ label: session.label,
89
+ topic: session.topic,
90
+ machine: session.machine,
91
+ }));
92
+ return JSON.stringify(safe, null, 2) + '\n';
93
+ }
94
+ export function resolveSessionAgentName(name) {
95
+ const normalized = name.toLowerCase();
96
+ if (SESSION_AGENTS.includes(normalized)) {
97
+ return normalized;
98
+ }
99
+ const resolved = resolveAgentName(normalized);
100
+ if (resolved && SESSION_AGENTS.includes(resolved)) {
101
+ return resolved;
102
+ }
103
+ return fuzzyMatch(normalized, SESSION_AGENTS, FUZZY_PRESETS.agents);
104
+ }
105
+ export function parseAgentFilter(agentName) {
106
+ if (!agentName)
107
+ return {};
108
+ const [name, version] = agentName.split('@', 2);
109
+ const agent = resolveSessionAgentName(name);
110
+ if (!agent) {
111
+ console.error(chalk.red(`Unknown agent: ${name}. Use: ${SESSION_AGENTS.join(', ')}`));
112
+ process.exit(1);
113
+ }
114
+ return { agent, version };
115
+ }
116
+ export function resolveSessionQuery(pool, query, options = {}) {
117
+ const normalized = query.trim();
118
+ const completeId = isCompleteSessionId(normalized);
119
+ const byIdMatches = resolveSessionById(pool, normalized);
120
+ if (byIdMatches.length > 0)
121
+ return { matches: byIdMatches, byId: true, completeId };
122
+ if (looksLikeSessionId(normalized)) {
123
+ const matches = options.indexFallback === false ? [] : findSessionsById(normalized);
124
+ return { matches, byId: true, completeId };
125
+ }
126
+ return { matches: filterSessionsByQuery(pool, normalized, options.scope), byId: false, completeId };
127
+ }
128
+ export function filterSessionsByQuery(sessions, query, scope) {
129
+ const trimmed = query?.trim().toLowerCase() || '';
130
+ if (!trimmed)
131
+ return sessions;
132
+ const installedAgentVersion = parseInstalledAgentVersionQuery(trimmed);
133
+ if (installedAgentVersion) {
134
+ const { agent, version } = parseAgentFilter(installedAgentVersion);
135
+ return sessions.filter((session) => session.agent === agent && session.version === version);
136
+ }
137
+ const terms = trimmed.split(/\s+/).filter(Boolean);
138
+ const contentIndex = scopedContentIndex(sessions, trimmed, scope);
139
+ const EXACT_LABEL_SCORE = 1_000_000;
140
+ const exactLabelHits = [...contentIndex.values()].filter(s => (s._bm25Score ?? 0) >= EXACT_LABEL_SCORE);
141
+ if (exactLabelHits.length > 0) {
142
+ return exactLabelHits.sort((a, b) => (b._bm25Score ?? 0) - (a._bm25Score ?? 0));
143
+ }
144
+ const poolById = new Map(sessions.map(s => [s.id, s]));
145
+ for (const [id, hit] of contentIndex) {
146
+ if (!poolById.has(id))
147
+ poolById.set(id, hit);
148
+ }
149
+ return [...poolById.values()]
150
+ .map(session => ({ session, score: scoreSessionQuery(session, terms) }))
151
+ .filter(entry => {
152
+ if (entry.score > 0)
153
+ return true;
154
+ const contentMatch = contentIndex.get(entry.session.id);
155
+ if (contentMatch && contentMatch._matchedTerms && contentMatch._matchedTerms.length > 0) {
156
+ return true;
157
+ }
158
+ return false;
159
+ })
160
+ .sort((a, b) => {
161
+ if (b.score !== a.score)
162
+ return b.score - a.score;
163
+ const cmA = contentIndex.get(a.session.id);
164
+ const cmB = contentIndex.get(b.session.id);
165
+ const bmA = cmA?._bm25Score ?? 0;
166
+ const bmB = cmB?._bm25Score ?? 0;
167
+ if (bmB !== bmA)
168
+ return bmB - bmA;
169
+ return new Date(b.session.timestamp).getTime() - new Date(a.session.timestamp).getTime();
170
+ })
171
+ .map(entry => {
172
+ const cm = contentIndex.get(entry.session.id);
173
+ if (cm && cm._matchedTerms) {
174
+ return { ...cm };
175
+ }
176
+ return entry.session;
177
+ });
178
+ }
179
+ function scoreSessionQuery(session, terms) {
180
+ let score = 0;
181
+ for (const term of terms) {
182
+ const exactId = session.id.toLowerCase() === term || session.shortId.toLowerCase() === term;
183
+ const prefixId = session.id.toLowerCase().startsWith(term) || session.shortId.toLowerCase().startsWith(term);
184
+ const topic = session.topic?.toLowerCase() || '';
185
+ const project = session.project?.toLowerCase() || '';
186
+ const account = session.account?.toLowerCase() || '';
187
+ const cwd = session.cwd?.toLowerCase() || '';
188
+ const agent = session.agent.toLowerCase();
189
+ const version = session.version?.toLowerCase() || '';
190
+ let termScore = 0;
191
+ if (exactId)
192
+ termScore = 1000;
193
+ else if (prefixId)
194
+ termScore = 900;
195
+ else if (topic.startsWith(term))
196
+ termScore = 700;
197
+ else if (project.startsWith(term))
198
+ termScore = 600;
199
+ else if (account.startsWith(term))
200
+ termScore = 550;
201
+ else if (agent.startsWith(term) || version.startsWith(term))
202
+ termScore = 500;
203
+ else if (topic.includes(term))
204
+ termScore = 400;
205
+ else if (project.includes(term))
206
+ termScore = 300;
207
+ else if (account.includes(term))
208
+ termScore = 250;
209
+ else if (cwd.includes(term))
210
+ termScore = 200;
211
+ else if (version.includes(term) || agent.includes(term))
212
+ termScore = 150;
213
+ else
214
+ return 0;
215
+ score += termScore;
216
+ }
217
+ return score;
218
+ }
219
+ export function applyScopeFilters(sessions, scope) {
220
+ let filtered = sessions;
221
+ if (scope.project) {
222
+ const projectQuery = scope.project.toLowerCase();
223
+ filtered = filtered.filter((s) => {
224
+ const project = (s.project || '').toLowerCase();
225
+ const cwd = (s.cwd || '').toLowerCase();
226
+ return project.includes(projectQuery) || cwd.includes(projectQuery);
227
+ });
228
+ }
229
+ if (scope.agent) {
230
+ const [wantAgent, rawVersion] = scope.agent.split('@');
231
+ const resolvedAgent = resolveAgentName(wantAgent);
232
+ const wantVersion = resolvedAgent ? resolveVersionAliasLoose(resolvedAgent, rawVersion) : rawVersion;
233
+ filtered = filtered.filter((s) => {
234
+ if (s.agent !== wantAgent)
235
+ return false;
236
+ if (wantVersion && s.version !== wantVersion)
237
+ return false;
238
+ return true;
239
+ });
240
+ }
241
+ if (scope.routine) {
242
+ filtered = filtered.filter((session) => session.origin === 'routine');
243
+ if (typeof scope.routine === 'string') {
244
+ const names = [...new Set(filtered.map((session) => session.routineName).filter((name) => !!name))];
245
+ const selected = resolveRoutineName(scope.routine, names);
246
+ filtered = selected
247
+ ? filtered.filter((session) => session.routineName === selected)
248
+ : [];
249
+ }
250
+ }
251
+ return filtered;
252
+ }
253
+ export function scopedContentIndex(sessions, query, scope) {
254
+ const hits = searchContentIndex(sessions, query);
255
+ if (!scope || (!scope.agent && !scope.project && !scope.routine))
256
+ return hits;
257
+ const kept = new Map();
258
+ for (const [id, session] of hits) {
259
+ if (applyScopeFilters([session], scope).length > 0)
260
+ kept.set(id, session);
261
+ }
262
+ return kept;
263
+ }
264
+ const FULL_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
265
+ const SHORT_SESSION_ID_RE = /^[0-9a-f]{8}$/i;
266
+ export function isDefinitiveMatch(session, selector) {
267
+ const trimmed = selector.trim();
268
+ if (FULL_SESSION_ID_RE.test(trimmed)) {
269
+ return session.id.toLowerCase() === trimmed.toLowerCase();
270
+ }
271
+ const shortId = shortIdFromName(trimmed) ?? (SHORT_SESSION_ID_RE.test(trimmed) ? trimmed : undefined);
272
+ return !!shortId && session.shortId.toLowerCase() === shortId.toLowerCase();
273
+ }
274
+ export function selectorAllowsEarlyExit(selector) {
275
+ const trimmed = selector.trim();
276
+ return FULL_SESSION_ID_RE.test(trimmed) || isAgentTmuxAlias(trimmed) || SHORT_SESSION_ID_RE.test(trimmed);
277
+ }
278
+ export function fleetCandidatesByQuery(rows, query, trustResolvedRows = false) {
279
+ const matched = !trustResolvedRows && looksLikeSessionId(query)
280
+ ? resolveSessionQuery(rows, query, { indexFallback: false }).matches
281
+ : rows;
282
+ const byId = new Map();
283
+ for (const session of matched) {
284
+ const machine = session.machine;
285
+ if (!machine)
286
+ continue;
287
+ const logicalId = session.id.toLowerCase();
288
+ let byMachine = byId.get(logicalId);
289
+ if (!byMachine) {
290
+ byMachine = new Map();
291
+ byId.set(logicalId, byMachine);
292
+ }
293
+ if (!byMachine.has(machine))
294
+ byMachine.set(machine, session);
295
+ }
296
+ return Array.from(byId.values()).map(byMachine => {
297
+ const hits = Array.from(byMachine.entries()).map(([machine, session]) => ({ machine, session }));
298
+ return { id: hits[0].session.id, hits };
299
+ });
300
+ }
301
+ function resolveIndexedMetadataRows(indexed, selector, scope) {
302
+ const alias = resolveSessionAlias(selector);
303
+ if (alias.kind === 'resolved') {
304
+ return resolveSessionQuery(indexed, alias.sessionId, { indexFallback: false, scope }).matches;
305
+ }
306
+ if (alias.kind === 'ambiguous') {
307
+ const ids = new Set(alias.sessionIds.map(id => id.toLowerCase()));
308
+ return indexed.filter(session => ids.has(session.id.toLowerCase()));
309
+ }
310
+ return resolveSessionQuery(indexed, selector, { indexFallback: false, scope }).matches;
311
+ }
312
+ function indexedRowsForSelector(selector, scope) {
313
+ const indexed = looksLikeSessionId(selector)
314
+ ? findSessionsById(selector)
315
+ : querySessions();
316
+ return applyScopeFilters(indexed, scope);
317
+ }
318
+ export function metadataResolveForwardedArgs(selector, scope) {
319
+ const args = ['sessions', '--resolve-safe-v1', selector, '--json', '--all', '--local'];
320
+ if (scope.agent)
321
+ args.push('--agent', scope.agent);
322
+ if (scope.project)
323
+ args.push('--project', scope.project);
324
+ return args;
325
+ }
326
+ const SHORT_SESSION_ID_WIDTH = 8;
327
+ export function isUniqueEnoughSelector(selector) {
328
+ const trimmed = selector.trim();
329
+ if (isCompleteSessionId(trimmed))
330
+ return true;
331
+ return /^[0-9a-f-]+$/i.test(trimmed)
332
+ && trimmed.replace(/-/g, '').length >= SHORT_SESSION_ID_WIDTH;
333
+ }
334
+ export function metadataResolveOutcome(localMatches, remote, selector) {
335
+ const candidates = fleetCandidatesByQuery([...localMatches, ...remote.sessions], selector, true);
336
+ if (isUniqueEnoughSelector(selector) && candidates.length === 1) {
337
+ return { kind: 'resolved', session: candidates[0].hits[0].session };
338
+ }
339
+ if (remote.unreachable.length > 0)
340
+ return { kind: 'partial', failedPeers: remote.unreachable };
341
+ if (candidates.length === 0)
342
+ return { kind: 'not-found' };
343
+ if (candidates.length > 1)
344
+ return { kind: 'ambiguous', candidates };
345
+ return { kind: 'resolved', session: candidates[0].hits[0].session };
346
+ }
347
+ export function isLocallyDefinitiveMatch(session, self) {
348
+ if (session.filePath)
349
+ return true;
350
+ return !!session.machine && session.machine !== self;
351
+ }
352
+ export function preferOwnerAttribution(localMatches, remoteSessions, self) {
353
+ if (remoteSessions.length === 0)
354
+ return localMatches;
355
+ const answeredByPeer = new Set(remoteSessions.map(session => session.id.toLowerCase()));
356
+ return localMatches.filter(session => isLocallyDefinitiveMatch(session, self) || !answeredByPeer.has(session.id.toLowerCase()));
357
+ }
358
+ export async function computeLocalMetadataMatches(selector, scope, deps = {}) {
359
+ const localMachine = machineId();
360
+ const includeLocal = !scope.hosts?.length || shouldIncludeLocal(scope.hosts, localMachine);
361
+ if (!includeLocal)
362
+ return [];
363
+ let indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
364
+ if (!looksLikeSessionId(selector)) {
365
+ return indexed.map(session => ({ ...session, machine: session.machine || localMachine }));
366
+ }
367
+ if (indexed.length === 0) {
368
+ const disk = await findLocalSessionTranscripts(selector, scope.agent);
369
+ const live = disk.length ? [] : await liveMetadataMatches(selector, scope, localMachine, deps);
370
+ if (disk.length > 0)
371
+ indexed = resolveIndexedMetadataRows(disk, selector, scope);
372
+ else if (live.length > 0)
373
+ indexed = live;
374
+ else if (scope.agent !== 'claude' && scope.agent !== 'codex') {
375
+ const { claimed } = await scanSessionsIncremental({ agent: scope.agent });
376
+ if (!claimed) {
377
+ if (!await waitForScanToSettle())
378
+ throw new Error('Session lookup is incomplete: another index scan is still running. Retry when it finishes.');
379
+ const retry = await scanSessionsIncremental({ agent: scope.agent });
380
+ if (!retry.claimed)
381
+ throw new Error('Session lookup is incomplete: the session index is busy. Retry when the scan finishes.');
382
+ }
383
+ indexed = resolveIndexedMetadataRows(indexedRowsForSelector(selector, scope), selector, scope);
384
+ }
385
+ }
386
+ const hydrated = [];
387
+ for (const session of indexed) {
388
+ hydrated.push(await hydrateSessionTranscript({ ...session, machine: session.machine || localMachine }));
389
+ }
390
+ return hydrated;
391
+ }
392
+ export async function liveMetadataMatches(selector, scope, self, deps = {}) {
393
+ const load = deps.loadActive ?? loadLocalActiveSessions;
394
+ const loadFleet = deps.loadFleetActive ?? (() => readActiveSessionsCache('fleet')?.sessions ?? []);
395
+ let fleetExecMachine;
396
+ try {
397
+ fleetExecMachine = fleetExecutionMachineById(loadFleet());
398
+ }
399
+ catch {
400
+ fleetExecMachine = new Map();
401
+ }
402
+ const match = (metas) => resolveIndexedMetadataRows(applyScopeFilters(reconcileLiveMetaMachine(metas, fleetExecMachine, self), scope), selector, scope);
403
+ try {
404
+ const cached = liveSessionMetas((await load()).sessions, self, Date.now());
405
+ const hit = match(cached);
406
+ if (hit.length > 0)
407
+ return hit;
408
+ const fresh = liveSessionMetas((await load({ forceRefresh: true })).sessions, self, Date.now());
409
+ return match(fresh);
410
+ }
411
+ catch {
412
+ return [];
413
+ }
414
+ }
415
+ export async function resolveSessionMetadataValue(selector, scope = {}, deps = { gatherRemoteList }) {
416
+ const localMatches = await computeLocalMetadataMatches(selector, scope, deps);
417
+ const localMachine = machineId();
418
+ if (FULL_SESSION_ID_RE.test(selector)) {
419
+ const localOutcome = metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
420
+ if (localOutcome.kind === 'resolved' && isLocallyDefinitiveMatch(localOutcome.session, localMachine)) {
421
+ return localOutcome;
422
+ }
423
+ }
424
+ if (scope.local === true)
425
+ return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [] }, selector);
426
+ try {
427
+ const forwarded = metadataResolveForwardedArgs(selector, scope);
428
+ const remote = await deps.gatherRemoteList(forwarded, scope.hosts, selectorAllowsEarlyExit(selector)
429
+ ? { isDefinitive: (session) => isDefinitiveMatch(session, selector) }
430
+ : undefined);
431
+ return metadataResolveOutcome(preferOwnerAttribution(localMatches, remote.sessions, localMachine), remote, selector);
432
+ }
433
+ catch (error) {
434
+ return metadataResolveOutcome(localMatches, { sessions: [], unreachable: [error?.message ?? 'fleet fan-out'] }, selector);
435
+ }
436
+ }
437
+ export function matchesTeam(session, team) {
438
+ const want = safeTeamText(team)?.trim().toLowerCase();
439
+ if (!want)
440
+ return true;
441
+ return (safeTeamText(session.spawnedTeam)?.toLowerCase() === want ||
442
+ safeTeamText(session.teamOrigin?.team)?.toLowerCase() === want);
443
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.0",
3
+ "version": "1.23.1",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",