@phnx-labs/agents-cli 1.23.20 → 1.23.22

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 (180) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +17 -0
  3. package/dist/bootstrap.js +5 -4
  4. package/dist/cli/command-registry.js +2 -0
  5. package/dist/commands/config.js +16 -0
  6. package/dist/commands/daemon.js +3 -3
  7. package/dist/commands/doctor.js +10 -19
  8. package/dist/commands/events.js +1 -14
  9. package/dist/commands/feed-watch.js +5 -2
  10. package/dist/commands/go.js +2 -2
  11. package/dist/commands/lead.d.ts +3 -0
  12. package/dist/commands/lead.js +280 -0
  13. package/dist/commands/projects.js +3 -2
  14. package/dist/commands/ps-roster.d.ts +2 -12
  15. package/dist/commands/ps-roster.js +5 -87
  16. package/dist/commands/ps.js +3 -1
  17. package/dist/commands/repo.js +12 -12
  18. package/dist/commands/resource-view.js +5 -5
  19. package/dist/commands/sessions-browser.js +2 -2
  20. package/dist/commands/sessions-watch.js +5 -2
  21. package/dist/commands/setup-secrets.d.ts +3 -4
  22. package/dist/commands/setup-secrets.js +15 -46
  23. package/dist/commands/setup-session-backup.js +1 -1
  24. package/dist/commands/ssh.d.ts +0 -4
  25. package/dist/commands/ssh.js +14 -81
  26. package/dist/commands/teams-picker.js +1 -12
  27. package/dist/commands/teams.js +1 -13
  28. package/dist/commands/view.d.ts +1 -40
  29. package/dist/commands/view.js +9 -330
  30. package/dist/commands/watchdog.js +4 -4
  31. package/dist/index.js +4 -0
  32. package/dist/lib/accounting/usage.d.ts +0 -1
  33. package/dist/lib/accounting/usage.js +1 -112
  34. package/dist/lib/accounts/add.js +1 -1
  35. package/dist/lib/accounts/migrate.js +1 -1
  36. package/dist/lib/auto-pull-worker.js +2 -16
  37. package/dist/lib/auto-pull.d.ts +1 -0
  38. package/dist/lib/auto-pull.js +27 -0
  39. package/dist/lib/browser-client.js +2 -11
  40. package/dist/lib/cloud/codex.js +3 -0
  41. package/dist/lib/commands.d.ts +0 -6
  42. package/dist/lib/commands.js +3 -116
  43. package/dist/lib/comms-render.d.ts +1 -7
  44. package/dist/lib/comms-render.js +0 -19
  45. package/dist/lib/computer-client.js +2 -11
  46. package/dist/lib/config-keys.d.ts +7 -3
  47. package/dist/lib/config-keys.js +15 -2
  48. package/dist/lib/crabbox/runtimes.d.ts +0 -14
  49. package/dist/lib/crabbox/runtimes.js +0 -80
  50. package/dist/lib/daemon/attention-notify-service.d.ts +51 -28
  51. package/dist/lib/daemon/attention-notify-service.js +219 -53
  52. package/dist/lib/daemon/daemon.js +1 -2
  53. package/dist/lib/daemon/feed-stream-service.js +2 -4
  54. package/dist/lib/device-config.d.ts +0 -5
  55. package/dist/lib/device-config.js +20 -27
  56. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  57. package/dist/lib/devices/doctor-findings.js +12 -1
  58. package/dist/lib/devices/fleet.d.ts +6 -0
  59. package/dist/lib/devices/fleet.js +15 -0
  60. package/dist/lib/devices/harness-inventory.d.ts +9 -0
  61. package/dist/lib/devices/harness-inventory.js +66 -0
  62. package/dist/lib/exec.js +1 -3
  63. package/dist/lib/feed/attention.d.ts +16 -1
  64. package/dist/lib/feed/attention.js +63 -1
  65. package/dist/lib/feed/feed.d.ts +1 -1
  66. package/dist/lib/feed/feed.js +12 -2
  67. package/dist/lib/feed/hub.d.ts +9 -0
  68. package/dist/lib/feed/hub.js +27 -1
  69. package/dist/lib/feed/notify-schedule.d.ts +16 -0
  70. package/dist/lib/feed/notify-schedule.js +62 -0
  71. package/dist/lib/feed/ticket-priority.d.ts +4 -0
  72. package/dist/lib/feed/ticket-priority.js +30 -0
  73. package/dist/lib/feed/watch.d.ts +1 -0
  74. package/dist/lib/feed/watch.js +27 -3
  75. package/dist/lib/feed-ranking.d.ts +1 -0
  76. package/dist/lib/feed-ranking.js +3 -1
  77. package/dist/lib/format.d.ts +0 -2
  78. package/dist/lib/format.js +0 -8
  79. package/dist/lib/github/open-prs.d.ts +0 -2
  80. package/dist/lib/github/open-prs.js +17 -35
  81. package/dist/lib/github/project-prs.d.ts +5 -0
  82. package/dist/lib/github/project-prs.js +73 -32
  83. package/dist/lib/helper-versions.js +1 -1
  84. package/dist/lib/hooks/cache.d.ts +1 -0
  85. package/dist/lib/hooks/cache.js +12 -1
  86. package/dist/lib/installations/duplicate-prune.d.ts +37 -0
  87. package/dist/lib/installations/duplicate-prune.js +85 -0
  88. package/dist/lib/installations/inventory-json.d.ts +20 -0
  89. package/dist/lib/installations/inventory-json.js +252 -0
  90. package/dist/lib/installations/shims.d.ts +0 -18
  91. package/dist/lib/installations/shims.js +1 -257
  92. package/dist/lib/lead/brief.d.ts +49 -0
  93. package/dist/lib/lead/brief.js +173 -0
  94. package/dist/lib/lead/client.d.ts +21 -0
  95. package/dist/lib/lead/client.js +167 -0
  96. package/dist/lib/lead/confirm.d.ts +22 -0
  97. package/dist/lib/lead/confirm.js +73 -0
  98. package/dist/lib/lead/events.d.ts +106 -0
  99. package/dist/lib/lead/events.js +188 -0
  100. package/dist/lib/lead/harness.d.ts +29 -0
  101. package/dist/lib/lead/harness.js +107 -0
  102. package/dist/lib/lead/host.d.ts +132 -0
  103. package/dist/lib/lead/host.js +675 -0
  104. package/dist/lib/lead/paths.d.ts +22 -0
  105. package/dist/lib/lead/paths.js +69 -0
  106. package/dist/lib/lead/refs.d.ts +17 -0
  107. package/dist/lib/lead/refs.js +75 -0
  108. package/dist/lib/lead/roster.d.ts +26 -0
  109. package/dist/lib/lead/roster.js +121 -0
  110. package/dist/lib/lead/shapes.d.ts +23 -0
  111. package/dist/lib/lead/shapes.js +95 -0
  112. package/dist/lib/lead/store.d.ts +46 -0
  113. package/dist/lib/lead/store.js +77 -0
  114. package/dist/lib/lead/tools.d.ts +18 -0
  115. package/dist/lib/lead/tools.js +106 -0
  116. package/dist/lib/lead/visibility.d.ts +16 -0
  117. package/dist/lib/lead/visibility.js +77 -0
  118. package/dist/lib/mailbox.d.ts +0 -18
  119. package/dist/lib/mailbox.js +0 -170
  120. package/dist/lib/menubar/notify-desktop.d.ts +5 -0
  121. package/dist/lib/menubar/notify-desktop.js +24 -0
  122. package/dist/lib/models.js +1 -19
  123. package/dist/lib/permissions.d.ts +0 -6
  124. package/dist/lib/permissions.js +0 -140
  125. package/dist/lib/platform/process.d.ts +1 -0
  126. package/dist/lib/platform/process.js +5 -0
  127. package/dist/lib/probe.js +13 -1
  128. package/dist/lib/project-status.js +4 -3
  129. package/dist/lib/projects.d.ts +9 -0
  130. package/dist/lib/projects.js +61 -3
  131. package/dist/lib/scheduling/routines.d.ts +1 -13
  132. package/dist/lib/scheduling/routines.js +1 -37
  133. package/dist/lib/secrets-cli.d.ts +3 -3
  134. package/dist/lib/secrets-cli.js +1 -1
  135. package/dist/lib/secrets-client.d.ts +4 -37
  136. package/dist/lib/secrets-client.js +19 -265
  137. package/dist/lib/session/active.d.ts +18 -8
  138. package/dist/lib/session/active.js +94 -18
  139. package/dist/lib/session/db.d.ts +0 -16
  140. package/dist/lib/session/db.js +1 -134
  141. package/dist/lib/session/detached.d.ts +0 -1
  142. package/dist/lib/session/detached.js +0 -18
  143. package/dist/lib/session/pending-work.d.ts +21 -0
  144. package/dist/lib/session/pending-work.js +284 -0
  145. package/dist/lib/session/remote/remote-list.d.ts +0 -3
  146. package/dist/lib/session/remote/remote-list.js +1 -23
  147. package/dist/lib/session/remote/watch.d.ts +5 -0
  148. package/dist/lib/session/remote/watch.js +19 -2
  149. package/dist/lib/session/session-cache.d.ts +1 -1
  150. package/dist/lib/session/session-cache.js +12 -5
  151. package/dist/lib/session/sync/provision.js +1 -2
  152. package/dist/lib/smart-launch.js +7 -2
  153. package/dist/lib/snapshot.js +3 -4
  154. package/dist/lib/ssh-exec.d.ts +0 -40
  155. package/dist/lib/ssh-exec.js +0 -108
  156. package/dist/lib/ssh-tunnel.d.ts +0 -6
  157. package/dist/lib/ssh-tunnel.js +0 -42
  158. package/dist/lib/standalone-tools.js +12 -1
  159. package/dist/lib/startup/command-registry.js +1 -1
  160. package/dist/lib/startup/spellcheck.d.ts +0 -1
  161. package/dist/lib/startup/spellcheck.js +1 -20
  162. package/dist/lib/state.d.ts +0 -6
  163. package/dist/lib/state.js +1 -14
  164. package/dist/lib/teams/delivery.d.ts +1 -0
  165. package/dist/lib/teams/delivery.js +13 -0
  166. package/dist/lib/types.d.ts +0 -37
  167. package/dist/lib/types.js +0 -9
  168. package/dist/lib/watchdog/log.d.ts +1 -1
  169. package/dist/lib/watchdog/log.js +6 -4
  170. package/package.json +2 -1
  171. package/dist/lib/artifact-actions.d.ts +0 -7
  172. package/dist/lib/artifact-actions.js +0 -39
  173. package/dist/lib/session/sync/managed-config.d.ts +0 -3
  174. package/dist/lib/session/sync/managed-config.js +0 -3
  175. package/dist/lib/session/sync/worker-template.d.ts +0 -1
  176. package/dist/lib/session/sync/worker-template.js +0 -807
  177. package/dist/lib/storage/selection.d.ts +0 -8
  178. package/dist/lib/storage/selection.js +0 -10
  179. package/dist/lib/watchdog/index.d.ts +0 -3
  180. package/dist/lib/watchdog/index.js +0 -3
@@ -0,0 +1,280 @@
1
+ import chalk from 'chalk';
2
+ import { setHelpSections } from '../lib/help.js';
3
+ import { writeStdoutFlushed } from '../lib/stdout.js';
4
+ import { connectHost, ensureHost, requireProjectDef, runConfirm, sendRequest } from '../lib/lead/client.js';
5
+ import { ConfirmError } from '../lib/lead/confirm.js';
6
+ import { curatedClientEnv, leadModel } from '../lib/lead/harness.js';
7
+ import { statusFromFiles } from '../lib/lead/host.js';
8
+ import { leadPaths, listLeadProjects } from '../lib/lead/paths.js';
9
+ import { readHistory } from '../lib/lead/store.js';
10
+ import { LINEAR_STATUSES, MAX_TASKS_LIMIT, leadToolContext, toolDispatch, toolLinearCreate, toolLinearTasks, toolLinearView, toolRemember, toolRoster, toolSend, toolStart, toolStop, } from '../lib/lead/tools.js';
11
+ function toolAction(fn) {
12
+ return async (...args) => {
13
+ try {
14
+ const out = await fn(...args);
15
+ await writeStdoutFlushed(`${out}\n`);
16
+ }
17
+ catch (err) {
18
+ process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
19
+ process.exitCode = 1;
20
+ }
21
+ };
22
+ }
23
+ export function registerLeadToolCommands(lead) {
24
+ const tool = lead
25
+ .command('tool')
26
+ .description('The fixed-shape commands a Lead may run (only inside a Lead; the harness allows nothing else)');
27
+ setHelpSections(tool, {
28
+ notes: `
29
+ - These run inside the Lead's Claude process, which sets AGENTS_LEAD_PROJECT. Each has one fixed shape:
30
+ no --mode, --secrets, --device, --lease, --cloud or pass-through arguments exist on any of them.
31
+ - stop never stops anything: it mints a confirm token the owner runs with agents lead confirm.
32
+ `,
33
+ });
34
+ const strict = (c) => c.allowExcessArguments(false).allowUnknownOption(false);
35
+ strict(tool.command('roster'))
36
+ .description('List live sessions for this project (or --project) from the Lead host\'s live feed')
37
+ .option('--project <name>', 'Another project')
38
+ .action(toolAction(async (opts) => toolRoster(leadToolContext(), opts.project)));
39
+ strict(tool.command('dispatch'))
40
+ .description('Move a ticket to In Progress, delegate it, and start the agent on it in edit mode')
41
+ .requiredOption('--ticket <id>', 'Ticket id, e.g. PHNX-4365')
42
+ .option('--agent <agent>', 'Agent to run', 'claude')
43
+ .action(toolAction(async (opts) => toolDispatch(leadToolContext(), opts.ticket, opts.agent)));
44
+ strict(tool.command('start'))
45
+ .description('Start an agent in edit mode on a task with no ticket')
46
+ .requiredOption('--agent <agent>', 'Agent to run')
47
+ .argument('<task...>', 'The task (after --)')
48
+ .action(toolAction(async (task, opts) => toolStart(leadToolContext(), opts.agent, task.join(' '))));
49
+ strict(tool.command('send'))
50
+ .description('Type a message into a running session of this project (slash commands are refused)')
51
+ .requiredOption('--session <id>', 'Session id or 8+ character prefix')
52
+ .argument('<text...>', 'The message (after --)')
53
+ .action(toolAction(async (text, opts) => toolSend(leadToolContext(), opts.session, text.join(' '))));
54
+ strict(tool.command('stop'))
55
+ .description('Ask the owner to confirm stopping a session; mints a confirm token, never stops anything')
56
+ .requiredOption('--session <id>', 'Session id or 8+ character prefix')
57
+ .action(toolAction(async (opts) => toolStop(leadToolContext(), opts.session)));
58
+ const linear = tool.command('linear').description('Read this project\'s Linear tickets, or create one');
59
+ strict(linear.command('tasks'))
60
+ .description('List tickets of this project')
61
+ .option('--status <status>', LINEAR_STATUSES.join('|'), 'open')
62
+ .option('--limit <n>', `1-${MAX_TASKS_LIMIT}`, '20')
63
+ .action(toolAction(async (opts) => toolLinearTasks(leadToolContext(), opts.status, Number.parseInt(opts.limit, 10))));
64
+ strict(linear.command('view'))
65
+ .description('Show one ticket')
66
+ .argument('<id>', 'Ticket id')
67
+ .action(toolAction(async (id) => { leadToolContext(); return toolLinearView(id); }));
68
+ strict(linear.command('create'))
69
+ .description('Create a ticket in this project')
70
+ .requiredOption('--title <title>', 'Title')
71
+ .option('--description <text>', 'Description')
72
+ .action(toolAction(async (opts) => toolLinearCreate(leadToolContext(), opts.title, opts.description)));
73
+ strict(tool.command('remember'))
74
+ .description('Save one short note to the Lead\'s memory.md')
75
+ .argument('<note...>', 'The note (after --)')
76
+ .action(toolAction(async (note) => toolRemember(leadToolContext(), note.join(' '))));
77
+ }
78
+ function printJsonLine(obj) {
79
+ process.stdout.write(`${JSON.stringify(obj)}\n`);
80
+ }
81
+ function humanRenderer() {
82
+ let sawText = false;
83
+ return (e) => {
84
+ switch (e.type) {
85
+ case 'turn':
86
+ if (e.engine === 'cold')
87
+ process.stderr.write(chalk.gray(`starting the Lead for ${e.project}…\n`));
88
+ return;
89
+ case 'tool':
90
+ if (e.state === 'run')
91
+ process.stderr.write(chalk.gray(` $ ${e.cmd}\n`));
92
+ else
93
+ process.stderr.write(chalk.gray(` ${e.state === 'ok' ? '✓' : '✗'} ${e.label} ${e.secs}s\n`));
94
+ return;
95
+ case 'text':
96
+ sawText = true;
97
+ process.stdout.write(e.delta);
98
+ return;
99
+ case 'confirm':
100
+ process.stdout.write(`\n${chalk.yellow(`Confirm: ${e.label}`)} → agents lead confirm ${e.token}\n`);
101
+ return;
102
+ case 'done':
103
+ if (!sawText)
104
+ process.stdout.write(e.text);
105
+ process.stdout.write('\n');
106
+ return;
107
+ case 'error':
108
+ process.stderr.write(chalk.red(`error: ${e.message}\n`));
109
+ return;
110
+ default:
111
+ return;
112
+ }
113
+ };
114
+ }
115
+ function parseVoice(raw) {
116
+ if (raw === undefined)
117
+ return undefined;
118
+ const n = Number(raw);
119
+ if (!Number.isFinite(n) || n < 0)
120
+ throw new Error(`--voice expects seconds as a number, got '${raw}'.`);
121
+ return n;
122
+ }
123
+ async function liveStatus(project) {
124
+ const socket = await connectHost(project);
125
+ if (!socket)
126
+ return statusFromFiles(project, leadPaths(project), leadModel());
127
+ let status = null;
128
+ await sendRequest(socket, { op: 'status' }, (obj) => { status = obj; });
129
+ if (!status)
130
+ throw new Error(`The Lead host for '${project}' closed without a status.`);
131
+ return status;
132
+ }
133
+ function renderStatus(s) {
134
+ const ctx = s.contextPct === null ? '' : ` · context ${s.contextPct}%`;
135
+ const session = s.session ? s.session.slice(0, 8) : 'none';
136
+ return `${chalk.bold(s.project)} ${s.state} session ${session} ${s.turns} turns model ${s.model}${ctx}${s.busy ? ' (busy)' : ''}`;
137
+ }
138
+ export function registerLeadCommand(program) {
139
+ const lead = program
140
+ .command('lead')
141
+ .description('Talk to the per-project Lead: one warm headless Claude that dispatches and manages your agents');
142
+ setHelpSections(lead, {
143
+ examples: `
144
+ # Ask the Lead (starts its warm host on first use; later turns reuse it)
145
+ agents lead ask --project rush -- what is running?
146
+ agents lead ask --project rush --json -- put Claude on PHNX-4365
147
+
148
+ # A stop is held for you; run the token it printed
149
+ agents lead confirm c_0123456789abcdef
150
+
151
+ # What it said before, its state, and shutting it down
152
+ agents lead history --project rush --limit 20 --json
153
+ agents lead status --json
154
+ agents lead stop --project rush
155
+ `,
156
+ notes: `
157
+ - One host process per project owns the Claude child and survives the caller exiting.
158
+ Its files live in ~/.agents/lead/<project>/ (session.json, memory.md, history.ndjson, host.log).
159
+ - The Lead runs with isolated settings and may only run the fixed-shape agents lead tool commands.
160
+ - Stops go through confirm tokens, which expire after 10 minutes.
161
+ - The model is the lead.model setting (default sonnet): agents config set lead.model <model>.
162
+ `,
163
+ });
164
+ lead
165
+ .command('ask')
166
+ .description('Send one message to the project Lead and stream its reply')
167
+ .requiredOption('--project <name>', 'Project name from agents projects list')
168
+ .option('--voice <secs>', 'The text is a voice transcript of this many seconds')
169
+ .option('--json', 'Stream NDJSON events (turn, status, tool, text, confirm, done, error)')
170
+ .argument('<text...>', 'What to ask (put it after --)')
171
+ .action(async (words, opts) => {
172
+ const emit = opts.json ? (e) => printJsonLine(e) : humanRenderer();
173
+ let failed = false;
174
+ try {
175
+ const voice = parseVoice(opts.voice);
176
+ requireProjectDef(opts.project);
177
+ const text = words.join(' ').trim();
178
+ if (!text)
179
+ throw new Error('Nothing to ask: pass the text after --.');
180
+ const socket = await ensureHost(opts.project);
181
+ let finished = false;
182
+ await sendRequest(socket, { op: 'ask', text, env: curatedClientEnv(), ...(voice !== undefined ? { voice } : {}) }, (obj) => {
183
+ const e = obj;
184
+ if (e.type === 'done')
185
+ finished = true;
186
+ if (e.type === 'error')
187
+ failed = true;
188
+ emit(e);
189
+ });
190
+ if (!finished && !failed) {
191
+ failed = true;
192
+ emit({ type: 'error', message: `The Lead host for '${opts.project}' closed the stream before the turn finished; see ${leadPaths(opts.project).log}` });
193
+ }
194
+ }
195
+ catch (err) {
196
+ failed = true;
197
+ emit({ type: 'error', message: err instanceof Error ? err.message : String(err) });
198
+ }
199
+ await writeStdoutFlushed('');
200
+ if (failed)
201
+ process.exitCode = 1;
202
+ });
203
+ lead
204
+ .command('confirm')
205
+ .description('Run an action the Lead held for confirmation (a stop), by its token')
206
+ .argument('<token>', 'The c_… token from the confirm event')
207
+ .option('--json', 'Stream NDJSON events (tool, done, error)')
208
+ .action(async (token, opts) => {
209
+ const emit = opts.json ? (e) => printJsonLine(e) : humanRenderer();
210
+ let ok = false;
211
+ try {
212
+ ok = await runConfirm(token, emit);
213
+ }
214
+ catch (err) {
215
+ emit({ type: 'error', message: err instanceof ConfirmError || err instanceof Error ? err.message : String(err) });
216
+ }
217
+ await writeStdoutFlushed('');
218
+ if (!ok)
219
+ process.exitCode = 1;
220
+ });
221
+ lead
222
+ .command('history')
223
+ .description('Print finished Lead turns for a project, oldest first')
224
+ .requiredOption('--project <name>', 'Project name')
225
+ .option('--limit <n>', 'Only the last N turns')
226
+ .option('--json', 'Print a JSON array of turns')
227
+ .action(async (opts) => {
228
+ const limit = opts.limit === undefined ? undefined : Number.parseInt(opts.limit, 10);
229
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1))
230
+ throw new Error(`--limit expects a positive integer, got '${opts.limit}'.`);
231
+ const turns = readHistory(leadPaths(opts.project), limit);
232
+ if (opts.json) {
233
+ await writeStdoutFlushed(`${JSON.stringify(turns, null, 2)}\n`);
234
+ return;
235
+ }
236
+ if (turns.length === 0) {
237
+ console.log(chalk.gray(`No Lead turns for ${opts.project} yet.`));
238
+ return;
239
+ }
240
+ for (const t of turns) {
241
+ console.log(`${chalk.gray(t.at)} ${chalk.cyan('>')} ${t.ask}`);
242
+ console.log(` ${t.text.split('\n').join('\n ')}\n`);
243
+ }
244
+ });
245
+ lead
246
+ .command('status')
247
+ .description('Show whether each project Lead is warm, cold or stopped, with its session and context use')
248
+ .option('--project <name>', 'Only this project')
249
+ .option('--json', 'Print JSON (an object with --project, else an array)')
250
+ .action(async (opts) => {
251
+ const projects = opts.project ? [opts.project] : listLeadProjects();
252
+ const statuses = await Promise.all(projects.map((p) => liveStatus(p)));
253
+ if (opts.json) {
254
+ await writeStdoutFlushed(`${JSON.stringify(opts.project ? statuses[0] : statuses, null, 2)}\n`);
255
+ return;
256
+ }
257
+ if (statuses.length === 0) {
258
+ console.log(chalk.gray('No Lead has run on this machine yet. Start one with: agents lead ask --project <name> -- <text>'));
259
+ return;
260
+ }
261
+ for (const s of statuses)
262
+ console.log(renderStatus(s));
263
+ });
264
+ registerLeadToolCommands(lead);
265
+ lead
266
+ .command('stop')
267
+ .description('Stop a project Lead host and its Claude process (its session stays resumable)')
268
+ .requiredOption('--project <name>', 'Project name')
269
+ .option('--json', 'Print {project, stopped}')
270
+ .action(async (opts) => {
271
+ const socket = await connectHost(opts.project);
272
+ let stopped = false;
273
+ if (socket)
274
+ await sendRequest(socket, { op: 'stop' }, () => { stopped = true; });
275
+ if (opts.json)
276
+ printJsonLine({ project: opts.project, stopped });
277
+ else
278
+ console.log(stopped ? `Stopped the Lead for ${opts.project}.` : `The Lead for ${opts.project} was not running.`);
279
+ });
280
+ }
@@ -11,7 +11,7 @@ import { getActiveSessions } from '../lib/session/active.js';
11
11
  import { gatherRemoteActive } from '../lib/session/remote-active.js';
12
12
  import { gatherRemoteAgentsJson } from '../lib/remote-agents-json.js';
13
13
  import { formatFleetSummary, formatFleetWorkspaces, parseRemoteProbe, probeProjectWorkspaces, workspaceTargetsForDef, workspaceWarnings, } from '../lib/project-probe.js';
14
- import { listProjectDefs, loadProjectDef, writeProjectDef, removeProjectDef, projectDefPath, isSafeProjectName, validateProjectDef, projectNameForCwd, projectRepoTargetsForDef, } from '../lib/projects.js';
14
+ import { listProjectDefs, loadProjectDef, writeProjectDef, removeProjectDef, projectDefPath, isSafeProjectName, validateProjectDef, projectNameForCwd, canonicalProjectName, projectRepoTargetsForDef, } from '../lib/projects.js';
15
15
  import { buildPullEnvelope, decodePullTargets, fingerprintTargets, pullLocalArgs, parseProjectPullEnvelope, printProjectPullSummary, projectPullComplete, pullProjectTargets, } from '../lib/project-pull.js';
16
16
  import { rollupSessionsByProject, withDefaultMachine, isDeadStatus, formatDeadSummary, liveDeadSplit, enrichProjectSignals, formatProjectMembersByHost, formatProjectWarnings, } from '../lib/project-status.js';
17
17
  import { fetchLinearProjectCounts } from '../lib/linear-project-counts.js';
@@ -40,7 +40,8 @@ export function looksLikePath(token) {
40
40
  return token === '.' || token === '..' || token.startsWith('~') || token.includes('/');
41
41
  }
42
42
  export function detectProjectForPath(cwd, defs) {
43
- const name = projectNameForCwd(cwd, defs);
43
+ const found = projectNameForCwd(cwd, defs);
44
+ const name = found === undefined ? undefined : canonicalProjectName(found, defs);
44
45
  const def = name ? defs.find((d) => d.name === name) : undefined;
45
46
  return {
46
47
  name: name ?? null,
@@ -37,24 +37,13 @@ interface MachineGroupedLayout {
37
37
  machines: MachineGroup[];
38
38
  }
39
39
  export declare function groupSessionsByMachine(sessions: ActiveSession[], localMachine: string): MachineGroupedLayout;
40
- export declare function dedupeByMachineSession(sessions: ActiveSession[], answered: readonly string[]): ActiveSession[];
41
- export declare function filterActiveSessionsByHostScope(sessions: ActiveSession[], hosts: string[] | undefined, self: string): ActiveSession[];
42
- export declare function gatherActiveSessions(opts?: {
43
- local?: boolean;
44
- hosts?: string[];
45
- forceRefresh?: boolean;
46
- }): Promise<{
47
- sessions: ActiveSession[];
48
- remoteDeviceCount: number;
49
- remoteSkipped?: string[];
50
- remoteDiscoveryFailed?: boolean;
51
- }>;
52
40
  export declare function renderActiveSessions(asJson: boolean, waitingOnly?: boolean, opts?: {
53
41
  local?: boolean;
54
42
  hosts?: string[];
55
43
  bookmarksOnly?: boolean;
56
44
  statuses?: LiveStatusFilter[];
57
45
  routine?: boolean | string;
46
+ includeLead?: boolean;
58
47
  }): Promise<void>;
59
48
  export declare function filterActiveSessionsByRoutine(sessions: ActiveSession[], routine: boolean | string | undefined): ActiveSession[];
60
49
  export type LiveStatusFilter = 'working' | 'idle' | 'waiting' | 'orphaned' | 'crashed' | 'closed' | 'abandoned' | 'queued' | 'unknown';
@@ -74,6 +63,7 @@ export interface LiveRosterOptions extends LiveStatusFlags {
74
63
  bookmarks?: boolean;
75
64
  routine?: boolean | string;
76
65
  project?: string;
66
+ includeLead?: boolean;
77
67
  sort?: string;
78
68
  }
79
69
  export declare function runLiveRoster(options: LiveRosterOptions): Promise<void>;
@@ -1,14 +1,12 @@
1
1
  import * as path from 'path';
2
+ import { withoutLeadSessions } from '../lib/lead/visibility.js';
2
3
  import chalk from 'chalk';
3
4
  import { sessionDisplayAgent, linkUrl } from '@phnx-labs/sessions-cli/reader';
4
- import { getActiveSessions, describeActiveDiscoveryHealth, sessionProcessIsLocal, backfillActiveRowsFromIndex, isRunningLiveSession, serializeActiveSessionsForJson, } from '../lib/session/active.js';
5
+ import { gatherActiveSessions, describeActiveDiscoveryHealth, sessionProcessIsLocal, backfillActiveRowsFromIndex, isRunningLiveSession, serializeActiveSessionsForJson, } from '../lib/session/active.js';
5
6
  import { enumerateGhosttyTabs, assignGhosttyTabs } from '../lib/session/ghostty-tabs.js';
6
7
  import { mapPanesToTargets, listClients } from '../lib/tmux/session.js';
7
8
  import { resolveViewingIn, viewingInLabel } from '../lib/session/viewing-in.js';
8
9
  import { machineId, normalizeHost } from '../lib/session/sync/config.js';
9
- import { gatherRemoteActive, NO_FANOUT_ENV } from '../lib/session/remote-active.js';
10
- import { hostToken, remoteHostsToDial, shouldIncludeLocal } from '../lib/session/remote-list.js';
11
- import { loadFleetActiveSessions, loadLocalActiveSessions } from '../lib/session/session-cache.js';
12
10
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
13
11
  import { formatCompactAge } from '../lib/session/relative-time.js';
14
12
  import { colorAgent } from '../lib/agents.js';
@@ -262,33 +260,6 @@ export function groupSessionsByMachine(sessions, localMachine) {
262
260
  }));
263
261
  return { machines };
264
262
  }
265
- export function dedupeByMachineSession(sessions, answered) {
266
- const heard = new Set(answered.map(normalizeHost));
267
- const seen = new Map();
268
- const out = [];
269
- for (const s of sessions) {
270
- if (!s.sessionId) {
271
- out.push(s);
272
- continue;
273
- }
274
- const key = `${s.machine ?? ''}:${s.sessionId}`;
275
- const at = seen.get(key);
276
- if (at === undefined) {
277
- seen.set(key, out.length);
278
- out.push(s);
279
- continue;
280
- }
281
- if (out[at].offloadedFrom && !s.offloadedFrom)
282
- out[at] = s;
283
- }
284
- return out.filter(s => !(s.sessionId && s.offloadedFrom && s.context !== 'teams' && s.machine && heard.has(normalizeHost(s.machine))));
285
- }
286
- export function filterActiveSessionsByHostScope(sessions, hosts, self) {
287
- if (!hosts || hosts.length === 0)
288
- return sessions;
289
- const wanted = new Set(hosts.map(hostToken));
290
- return sessions.filter((s) => wanted.has(s.machine ?? self));
291
- }
292
263
  function groupTally(sessions) {
293
264
  const running = sessions.filter(s => s.status === 'running').length;
294
265
  const idle = sessions.filter(s => s.status === 'idle').length;
@@ -399,62 +370,6 @@ async function enrichTmuxLocators(local, surfaces = []) {
399
370
  }
400
371
  catch { }
401
372
  }
402
- export async function gatherActiveSessions(opts = {}) {
403
- const forceRefresh = opts.forceRefresh === true
404
- || process.env.AGENTS_SESSIONS_FORCE_REFRESH === '1'
405
- || process.env[NO_FANOUT_ENV] === '1';
406
- const scoped = (opts.hosts?.length ?? 0) > 0;
407
- if (opts.local && !scoped) {
408
- const loaded = await loadLocalActiveSessions({ forceRefresh });
409
- const self = machineId();
410
- for (const s of loaded.sessions)
411
- if (!s.machine)
412
- s.machine = self;
413
- return { sessions: loaded.sessions, remoteDeviceCount: 0 };
414
- }
415
- if (!opts.local && !scoped) {
416
- const loaded = await loadFleetActiveSessions({
417
- forceRefresh,
418
- gather: () => gatherActiveSessionsLive({ local: false }),
419
- });
420
- return {
421
- sessions: loaded.sessions,
422
- remoteDeviceCount: loaded.remoteDeviceCount,
423
- remoteSkipped: loaded.remoteSkipped,
424
- remoteDiscoveryFailed: loaded.remoteDiscoveryFailed,
425
- };
426
- }
427
- return gatherActiveSessionsLive(opts);
428
- }
429
- async function gatherActiveSessionsLive(opts = {}) {
430
- const self = machineId();
431
- const local = shouldIncludeLocal(opts.hosts, self)
432
- ? await getActiveSessions({ localOnly: opts.local })
433
- : [];
434
- for (const s of local)
435
- if (!s.machine)
436
- s.machine = self;
437
- let remoteDeviceCount = 0;
438
- let remoteSkipped = [];
439
- let remoteDiscoveryFailed = false;
440
- let merged = local;
441
- if (!opts.local) {
442
- const remoteHosts = remoteHostsToDial(opts.hosts, self);
443
- if (!opts.hosts?.length || (remoteHosts && remoteHosts.length > 0)) {
444
- const remote = await gatherRemoteActive(remoteHosts);
445
- remoteDeviceCount = remote.deviceCount;
446
- remoteSkipped = remote.skipped;
447
- remoteDiscoveryFailed = remote.discoveryFailed;
448
- merged = dedupeByMachineSession([...local, ...remote.sessions], remote.answered);
449
- }
450
- }
451
- return {
452
- sessions: filterActiveSessionsByHostScope(merged, opts.hosts, self),
453
- remoteDeviceCount,
454
- remoteSkipped,
455
- remoteDiscoveryFailed,
456
- };
457
- }
458
373
  async function describeEmptyActiveDiscovery(opts, remoteSkipped, remoteDiscoveryFailed) {
459
374
  const parts = [];
460
375
  if (!opts.hosts?.length || opts.local) {
@@ -476,6 +391,8 @@ async function describeEmptyActiveDiscovery(opts, remoteSkipped, remoteDiscovery
476
391
  export async function renderActiveSessions(asJson, waitingOnly = false, opts = {}) {
477
392
  const self = machineId();
478
393
  const gathered = await gatherActiveSessions(opts);
394
+ if (!opts.includeLead)
395
+ gathered.sessions = withoutLeadSessions(gathered.sessions);
479
396
  const { remoteDeviceCount, remoteSkipped, remoteDiscoveryFailed } = gathered;
480
397
  backfillActiveRowsFromIndex(gathered.sessions);
481
398
  const merged = opts.bookmarksOnly
@@ -610,5 +527,6 @@ export async function runLiveRoster(options) {
610
527
  bookmarksOnly: options.bookmarks === true,
611
528
  statuses: liveStatuses,
612
529
  routine: options.routine,
530
+ includeLead: options.includeLead === true,
613
531
  });
614
532
  }
@@ -56,7 +56,8 @@ export function registerPsCommand(program) {
56
56
  .option('--status <state...>', `Only these live states: ${PS_STATUSES.join(', ')} (repeatable or comma-separated)`)
57
57
  .option('--bookmarks', 'Only bookmarked sessions (bookmark one with `sessions bookmark <id>`)')
58
58
  .option('--routines, --routine [name]', 'Only routine-run sessions; pass a name to narrow to one routine (fuzzy name matching)')
59
- .option('--no-interactive', 'Print the roster instead of opening the picker on a TTY');
59
+ .option('--no-interactive', 'Print the roster instead of opening the picker on a TTY')
60
+ .option('--include-lead', 'Also list project Lead sessions (agents lead), which are hidden by default');
60
61
  setHelpSections(ps, {
61
62
  examples: `
62
63
  # What is running right now, here and on every reachable device
@@ -115,6 +116,7 @@ export function registerPsCommand(program) {
115
116
  interactive: opts.interactive,
116
117
  bookmarks: opts.bookmarks,
117
118
  routine: opts.routine,
119
+ includeLead: opts.includeLead,
118
120
  });
119
121
  });
120
122
  registerSessionsStopCommand(ps);
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import { visibleWidth, padVisible } from '../lib/format.js';
2
+ import { stringWidth, padToWidth } from '../lib/text/width.js';
3
3
  import { stripAnsi } from '../lib/session/width.js';
4
4
  import { interruptibleSpinner } from '../lib/spinner.js';
5
5
  import * as fs from 'fs';
@@ -293,16 +293,16 @@ function renderTable(rows, compact) {
293
293
  }
294
294
  const headers = ['REPO', 'BRANCH', 'SYNC', 'CHANGES'];
295
295
  const tableCells = [...cells.values()];
296
- const aliasW = Math.max(headers[0].length, ...rows.map((r) => r.alias.length));
297
- const branchW = Math.max(headers[1].length, 0, ...tableCells.map((c) => visibleWidth(c[0])));
298
- const syncW = Math.max(headers[2].length, 0, ...tableCells.map((c) => visibleWidth(c[1])));
299
- const changesW = Math.max(headers[3].length, 0, ...tableCells.map((c) => visibleWidth(c[2])));
296
+ const aliasW = Math.max(headers[0].length, ...rows.map((r) => stringWidth(r.alias)));
297
+ const branchW = Math.max(headers[1].length, 0, ...tableCells.map((c) => stringWidth(c[0])));
298
+ const syncW = Math.max(headers[2].length, 0, ...tableCells.map((c) => stringWidth(c[1])));
299
+ const changesW = Math.max(headers[3].length, 0, ...tableCells.map((c) => stringWidth(c[2])));
300
300
  console.log(` ${chalk.gray(headers[0].padEnd(aliasW))} ${chalk.gray(headers[1].padEnd(branchW))} ${chalk.gray(headers[2].padEnd(syncW))} ${chalk.gray(headers[3].padEnd(changesW))} ${chalk.gray('REMOTE')}`);
301
301
  for (const r of rows) {
302
- const aliasCol = chalk.cyan(r.alias.padEnd(aliasW));
302
+ const aliasCol = chalk.cyan(padToWidth(r.alias, aliasW));
303
303
  const c = cells.get(r.alias);
304
304
  if (c) {
305
- console.log(` ${aliasCol} ${padVisible(c[0], branchW)} ${padVisible(c[1], syncW)} ${padVisible(c[2], changesW)} ${c[3]}`);
305
+ console.log(` ${aliasCol} ${padToWidth(c[0], branchW)} ${padToWidth(c[1], syncW)} ${padToWidth(c[2], changesW)} ${c[3]}`);
306
306
  }
307
307
  else {
308
308
  console.log(` ${aliasCol} ${r.raw}`);
@@ -314,7 +314,7 @@ export function wrapPhrases(parts, width) {
314
314
  let cur = '';
315
315
  for (const p of parts) {
316
316
  const cand = cur ? `${cur}, ${p}` : p;
317
- if (cur && visibleWidth(cand) > width) {
317
+ if (cur && stringWidth(cand) > width) {
318
318
  lines.push(cur);
319
319
  cur = p;
320
320
  }
@@ -416,13 +416,13 @@ export function renderDeviceStatusRows(results) {
416
416
  if (cells.length === 0)
417
417
  return [];
418
418
  const headers = ['DEVICE', 'REPO', 'SYNC', 'CHANGES'];
419
- const devW = Math.max(headers[0].length, ...cells.map((c) => visibleWidth(c.device)));
420
- const repoW = Math.max(headers[1].length, ...cells.map((c) => visibleWidth(c.repo)));
421
- const syncW = Math.max(headers[2].length, ...cells.map((c) => visibleWidth(c.sync)));
419
+ const devW = Math.max(headers[0].length, ...cells.map((c) => stringWidth(c.device)));
420
+ const repoW = Math.max(headers[1].length, ...cells.map((c) => stringWidth(c.repo)));
421
+ const syncW = Math.max(headers[2].length, ...cells.map((c) => stringWidth(c.sync)));
422
422
  const lines = [];
423
423
  lines.push(` ${chalk.gray(headers[0].padEnd(devW))} ${chalk.gray(headers[1].padEnd(repoW))} ${chalk.gray(headers[2].padEnd(syncW))} ${chalk.gray(headers[3])}`);
424
424
  for (const c of cells) {
425
- lines.push(` ${chalk.cyan(padVisible(c.device, devW))} ${padVisible(c.repo, repoW)} ${padVisible(c.sync, syncW)} ${c.changes}`);
425
+ lines.push(` ${chalk.cyan(padToWidth(c.device, devW))} ${padToWidth(c.repo, repoW)} ${padToWidth(c.sync, syncW)} ${c.changes}`);
426
426
  }
427
427
  return lines;
428
428
  }
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import { truncate, padVisible, termLink } from '../lib/format.js';
2
+ import { truncate, termLink } from '../lib/format.js';
3
3
  import { agentLabel } from '../lib/agents.js';
4
4
  import { itemPicker } from '../lib/picker.js';
5
5
  import { isInteractiveTerminal, isPromptCancelled, printWithPager } from './utils.js';
@@ -63,19 +63,19 @@ function filterRows(rows, query) {
63
63
  }
64
64
  function formatPickerRow(row, opts) {
65
65
  const linkTarget = opts.linkFor?.(row);
66
- const padded = chalk.cyan(padVisible(row.name, opts.nameCap ?? 22));
66
+ const padded = chalk.cyan(padToWidth(row.name, opts.nameCap ?? 22));
67
67
  const name = linkTarget ? termLink(padded, linkTarget) : padded;
68
68
  const extra = opts.extraLabel
69
- ? chalk.gray(padVisible(row.extra ?? '-', 10))
69
+ ? chalk.gray(padToWidth(row.extra ?? '-', 10))
70
70
  : '';
71
71
  const extra2 = opts.extra2Label
72
- ? chalk.gray(padVisible(row.extra2 ?? '-', 16))
72
+ ? chalk.gray(padToWidth(row.extra2 ?? '-', 16))
73
73
  : '';
74
74
  const descRaw = row.description ? truncate(row.description, 40) : '';
75
75
  if (!syncEnabled(opts)) {
76
76
  return `${name} ${extra}${extra2}${chalk.gray(row.description ? truncate(row.description, 84) : '')}`;
77
77
  }
78
- const desc = padVisible(chalk.gray(descRaw), 42);
78
+ const desc = padToWidth(chalk.gray(descRaw), 42);
79
79
  const sync = formatSyncSummary(row.targets, opts);
80
80
  return `${name} ${extra}${extra2}${desc} ${sync}`;
81
81
  }
@@ -11,10 +11,10 @@ import { enrichTeamOrigins, safeTeamText, shouldShowTeamSessions } from '@phnx-l
11
11
  import { listBookmarks, toggleBookmark } from '../lib/session/bookmarks.js';
12
12
  import { machineId, normalizeHost } from '../lib/session/sync/config.js';
13
13
  import { buildPreview, setRemotePreviewRepaint, LIVE_ROW_PREFIX, handlePickedSession } from './sessions-picker.js';
14
- import { isRunningLiveSession } from '../lib/session/active.js';
14
+ import { gatherActiveSessions, isRunningLiveSession } from '../lib/session/active.js';
15
15
  import { cleanPreview, formatPickerLabel, pickerColumnsFor, liveHostLabel, formatLiveStatusHeadline } from '../lib/session/presentation.js';
16
16
  import { matchesTeam, mergeLocalFirst, parseAgentFilter, sessionMatchesQuery } from '../lib/session/selection.js';
17
- import { gatherActiveSessions, matchesLiveStatus, resolveRoutineName } from './ps-roster.js';
17
+ import { matchesLiveStatus, resolveRoutineName } from './ps-roster.js';
18
18
  export function buildInitialFilter(initial) {
19
19
  return {
20
20
  running: initial.running ?? false,
@@ -1,11 +1,13 @@
1
1
  import { machineId } from '../lib/machine-id.js';
2
2
  import { setHelpSections } from '../lib/help.js';
3
3
  import { watchFleetSessions, watchLocalSessions } from '../lib/session/watch.js';
4
+ import { hideLeadInSessionEnvelope, leadSessionIds } from '../lib/lead/visibility.js';
4
5
  export function registerSessionsWatchCommand(parent) {
5
6
  const command = parent.command('watch')
6
7
  .description('Stream canonical live and recoverable session row changes as NDJSON')
7
8
  .option('--json', 'Emit versioned NDJSON envelopes')
8
- .option('--local', 'Watch only this machine');
9
+ .option('--local', 'Watch only this machine')
10
+ .option('--include-lead', 'Also stream project Lead sessions (agents lead), which are hidden by default');
9
11
  setHelpSections(command, {
10
12
  examples: `
11
13
  # Subscribe to session changes for a long-lived UI consumer
@@ -38,7 +40,8 @@ export function registerSessionsWatchCommand(parent) {
38
40
  process.once('SIGTERM', stop);
39
41
  process.stdout.on('error', stopOnClosedConsumer);
40
42
  try {
41
- const emit = (event) => process.stdout.write(`${JSON.stringify(event)}\n`);
43
+ const leadIds = leadSessionIds();
44
+ const emit = (event) => process.stdout.write(`${JSON.stringify(options.includeLead ? event : hideLeadInSessionEnvelope(event, leadIds))}\n`);
42
45
  if (options.local)
43
46
  await watchLocalSessions({ scope: machineId(), signal: controller.signal, emit });
44
47
  else
@@ -1,8 +1,7 @@
1
1
  import type { Command } from 'commander';
2
- export declare const SECRETS_CLI_PACKAGE = "@phnx-labs/secrets-cli@0.1.8";
3
- export declare const INSTALL_HINT = "agents clis install secrets # or: npm i -g @phnx-labs/secrets-cli@0.1.8";
2
+ export declare const SECRETS_CLI_PACKAGE = "@phnx-labs/secrets-cli@0.4.0";
3
+ export declare const INSTALL_HINT = "agents setup tools --tool secrets # or: npm i -g @phnx-labs/secrets-cli@0.4.0";
4
4
  export declare function setupSecretsPrefsPath(): string;
5
- export declare function isSecretsCliInstalled(): boolean;
6
- export declare function installSecretsCli(): boolean;
5
+ export declare function installSecretsCli(): Promise<boolean>;
7
6
  export declare function runSecretsSetupWizard(): Promise<boolean>;
8
7
  export declare function registerSetupSecretsCommand(setupCmd: Command): void;