@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,675 @@
1
+ import * as fs from 'node:fs';
2
+ import * as net from 'node:net';
3
+ import * as os from 'node:os';
4
+ import * as path from 'node:path';
5
+ import * as readline from 'node:readline';
6
+ import { spawn } from 'node:child_process';
7
+ import { randomBytes, randomUUID } from 'node:crypto';
8
+ import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
9
+ import { listProjectDefsCached, projectNameForCwd, resolveDefinedProjectPath } from '../projects.js';
10
+ import { LeadTurnParser, shouldRotate, summarize, } from './events.js';
11
+ import { extractRefs, enrichTickets } from './refs.js';
12
+ import { mintConfirm, sweepExpiredConfirms } from './confirm.js';
13
+ import { FeedRoster, filterProject, formatRosterRow, rosterDelta } from './roster.js';
14
+ import { agentsMdDigest, briefSummary, buildBrief, composeTurnMessage, fetchOpenTickets, fetchRecentPrs, fleetLine, linearTeamKey, projectRepo, } from './brief.js';
15
+ import { appendHistory, clearSessionState, readMemory, readSessionState, writeMemory, writeSessionState, } from './store.js';
16
+ import { ensureLeadDir, leadRoot } from './paths.js';
17
+ import { runArgv } from './shapes.js';
18
+ import { LEAD_ALLOWED_TOOLS, agentsCliLaunch, curatedClientEnv, leadChildEnv, leadRunArgs, workerEnv, writeAgentsShim, writeLeadSettings, } from './harness.js';
19
+ export const LEAD_IDLE_EXIT_MS = 4 * 60 * 60 * 1000;
20
+ export const ROSTER_WAIT_MS = 4_000;
21
+ export const CONFIRM_SWEEP_MS = 5 * 60 * 1000;
22
+ const CHILD_STOP_GRACE_MS = 5_000;
23
+ const FEED_BACKOFF_MIN_MS = 2_000;
24
+ const FEED_BACKOFF_MAX_MS = 60_000;
25
+ const STDERR_TAIL_CHARS = 4_000;
26
+ const RESUME_MISSING_RE = /No session matching|No conversation found/i;
27
+ export const MEMORY_PROMPT = 'Your context is about to be rotated. Write the memory your successor Lead needs, as a short Markdown list (at most 25 lines): ' +
28
+ 'standing owner preferences, what was dispatched to whom (ticket ids, session titles), open threads and pending confirms. ' +
29
+ 'Facts only, no greeting. Reply with the list and nothing else.';
30
+ class ChildGone extends Error {
31
+ sawInit;
32
+ stderr;
33
+ constructor(sawInit, stderr, message) {
34
+ super(message);
35
+ this.sawInit = sawInit;
36
+ this.stderr = stderr;
37
+ }
38
+ }
39
+ function secs(ms) {
40
+ return Math.round(ms / 10) / 100;
41
+ }
42
+ function newTurnId() {
43
+ return `t_${randomBytes(6).toString('hex')}`;
44
+ }
45
+ function pidAlive(pid) {
46
+ try {
47
+ process.kill(pid, 0);
48
+ return true;
49
+ }
50
+ catch (err) {
51
+ return err.code === 'EPERM';
52
+ }
53
+ }
54
+ export function isLeadRow(row) {
55
+ if (row.title.startsWith('lead-'))
56
+ return true;
57
+ if (!row.cwd)
58
+ return false;
59
+ const rel = path.relative(leadRoot(), path.resolve(row.cwd));
60
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
61
+ }
62
+ export function readHostRecord(paths) {
63
+ try {
64
+ return JSON.parse(fs.readFileSync(paths.host, 'utf-8'));
65
+ }
66
+ catch (err) {
67
+ if (err.code === 'ENOENT')
68
+ return null;
69
+ throw err;
70
+ }
71
+ }
72
+ export function acquireHostLock(paths) {
73
+ for (let attempt = 0; attempt < 2; attempt++) {
74
+ try {
75
+ fs.writeFileSync(paths.lock, String(process.pid), { flag: 'wx', mode: 0o600 });
76
+ return;
77
+ }
78
+ catch (err) {
79
+ if (err.code !== 'EEXIST')
80
+ throw err;
81
+ const holder = Number.parseInt(fs.readFileSync(paths.lock, 'utf-8'), 10);
82
+ if (Number.isInteger(holder) && holder !== process.pid && pidAlive(holder)) {
83
+ throw new Error(`Another Lead host (pid ${holder}) holds ${paths.lock}.`);
84
+ }
85
+ fs.rmSync(paths.lock, { force: true });
86
+ }
87
+ }
88
+ throw new Error(`Could not take ${paths.lock}.`);
89
+ }
90
+ export function statusFromFiles(project, paths, model) {
91
+ const state = readSessionState(paths);
92
+ return {
93
+ project,
94
+ state: 'stopped',
95
+ session: state?.sessionId ?? null,
96
+ engine: state?.lastEngine ?? null,
97
+ model: state?.model ?? model,
98
+ host: os.hostname(),
99
+ brief: state?.brief ?? [],
100
+ memory: readMemory(paths).split('\n').filter((l) => l.trim().length > 0),
101
+ tools: [...LEAD_ALLOWED_TOOLS],
102
+ pid: null,
103
+ version: null,
104
+ busy: false,
105
+ queued: 0,
106
+ turns: state?.turns ?? 0,
107
+ contextPct: state?.contextTokens && state.contextWindow
108
+ ? Math.round((state.contextTokens / state.contextWindow) * 1000) / 10
109
+ : null,
110
+ lastTurnAt: state?.lastTurnAtMs ? new Date(state.lastTurnAtMs).toISOString() : null,
111
+ };
112
+ }
113
+ export class LeadHost {
114
+ opts;
115
+ server = null;
116
+ child = null;
117
+ childSessionId = null;
118
+ childStderr = '';
119
+ active = null;
120
+ queue = Promise.resolve();
121
+ queued = 0;
122
+ busy = false;
123
+ stopping = false;
124
+ roster = new FeedRoster();
125
+ feedChild = null;
126
+ feedBackoffMs = FEED_BACKOFF_MIN_MS;
127
+ timers = [];
128
+ idleTimer = null;
129
+ ticketCache = new Map();
130
+ knownPrs = new Set();
131
+ ticketPrefixes = new Set();
132
+ rotatedFrom;
133
+ clientEnv = {};
134
+ resolveClosed;
135
+ closed = new Promise((resolve) => { this.resolveClosed = resolve; });
136
+ constructor(opts) {
137
+ this.opts = opts;
138
+ const key = opts.teamKey ?? linearTeamKey(os.homedir());
139
+ if (key)
140
+ this.ticketPrefixes.add(key);
141
+ }
142
+ log(line) {
143
+ this.opts.log?.(`${new Date().toISOString()} ${line}`);
144
+ }
145
+ async start() {
146
+ const paths = ensureLeadDir(this.opts.project);
147
+ acquireHostLock(paths);
148
+ try {
149
+ await this.claimSocket();
150
+ this.server = net.createServer((socket) => this.onConnection(socket));
151
+ await new Promise((resolve, reject) => {
152
+ this.server.once('error', reject);
153
+ this.server.listen(paths.endpoint, () => resolve());
154
+ });
155
+ }
156
+ catch (err) {
157
+ fs.rmSync(paths.lock, { force: true });
158
+ throw err;
159
+ }
160
+ if (process.platform !== 'win32')
161
+ fs.chmodSync(paths.socket, 0o600);
162
+ writeLeadSettings(paths);
163
+ writeAgentsShim(paths);
164
+ const record = {
165
+ pid: process.pid, project: this.opts.project, version: this.opts.version, model: this.opts.model, startedAtMs: Date.now(),
166
+ };
167
+ fs.writeFileSync(paths.host, JSON.stringify(record));
168
+ this.startFeed();
169
+ this.armIdle();
170
+ const sweep = setInterval(() => {
171
+ const removed = sweepExpiredConfirms();
172
+ if (removed > 0)
173
+ this.log(`swept ${removed} expired confirm tokens`);
174
+ }, CONFIRM_SWEEP_MS);
175
+ sweep.unref();
176
+ this.timers.push(sweep);
177
+ void this.refreshRefData();
178
+ this.log(`host listening for ${this.opts.project} (pid ${process.pid}, version ${this.opts.version}, model ${this.opts.model})`);
179
+ }
180
+ async claimSocket() {
181
+ const live = await new Promise((resolve) => {
182
+ const probe = net.connect(this.opts.paths.endpoint);
183
+ probe.once('connect', () => { probe.destroy(); resolve(true); });
184
+ probe.once('error', () => resolve(false));
185
+ });
186
+ if (live)
187
+ throw new Error(`A Lead host for '${this.opts.project}' is already listening on ${this.opts.paths.socket}.`);
188
+ if (process.platform !== 'win32')
189
+ fs.rmSync(this.opts.paths.socket, { force: true });
190
+ }
191
+ armIdle() {
192
+ if (this.idleTimer)
193
+ clearTimeout(this.idleTimer);
194
+ this.idleTimer = setTimeout(() => {
195
+ if (this.busy || this.queued > 0) {
196
+ this.armIdle();
197
+ return;
198
+ }
199
+ this.log('idle limit reached; shutting down');
200
+ void this.shutdown();
201
+ }, this.opts.idleExitMs ?? LEAD_IDLE_EXIT_MS);
202
+ }
203
+ startFeed() {
204
+ if (!this.opts.feed || this.stopping)
205
+ return;
206
+ const feed = spawn(this.opts.feed.command, this.opts.feed.args, { stdio: ['ignore', 'pipe', 'pipe'] });
207
+ this.feedChild = feed;
208
+ readline.createInterface({ input: feed.stdout }).on('line', (line) => {
209
+ if (!line.trim())
210
+ return;
211
+ let envelope;
212
+ try {
213
+ envelope = JSON.parse(line);
214
+ }
215
+ catch {
216
+ this.log(`feed: unparseable line dropped (${line.slice(0, 80)})`);
217
+ return;
218
+ }
219
+ this.feedBackoffMs = FEED_BACKOFF_MIN_MS;
220
+ this.roster.apply(envelope);
221
+ });
222
+ feed.stderr.on('data', (d) => this.log(`feed stderr: ${d.toString().trim().slice(0, 300)}`));
223
+ feed.on('exit', (code, signal) => {
224
+ this.feedChild = null;
225
+ if (this.stopping)
226
+ return;
227
+ this.log(`feed watch exited (${code ?? signal}); restarting in ${this.feedBackoffMs}ms`);
228
+ const t = setTimeout(() => this.startFeed(), this.feedBackoffMs);
229
+ t.unref();
230
+ this.timers.push(t);
231
+ this.feedBackoffMs = Math.min(this.feedBackoffMs * 2, FEED_BACKOFF_MAX_MS);
232
+ });
233
+ }
234
+ isSelf(row) {
235
+ return row.id === this.childSessionId || isLeadRow(row);
236
+ }
237
+ liveRows() {
238
+ return Object.values(this.roster.snapshot()).filter((r) => !this.isSelf(r));
239
+ }
240
+ projectRoster(project = this.opts.project) {
241
+ const defs = listProjectDefsCached();
242
+ const others = Object.fromEntries(this.liveRows().map((r) => [r.id, r]));
243
+ return filterProject(others, project, (cwd) => projectNameForCwd(cwd, defs));
244
+ }
245
+ fleetSummary() {
246
+ const all = Object.values(this.roster.snapshot());
247
+ const others = all.filter((r) => !this.isSelf(r));
248
+ return fleetLine(others, all.length - others.length);
249
+ }
250
+ findRow(ref, rows) {
251
+ const exact = rows.find((r) => r.id === ref);
252
+ if (exact)
253
+ return exact;
254
+ const prefixed = rows.filter((r) => r.id.startsWith(ref));
255
+ return prefixed.length === 1 ? prefixed[0] : undefined;
256
+ }
257
+ onConnection(socket) {
258
+ socket.on('error', () => { });
259
+ const rl = readline.createInterface({ input: socket });
260
+ rl.once('line', (line) => {
261
+ rl.close();
262
+ let req;
263
+ try {
264
+ req = JSON.parse(line);
265
+ }
266
+ catch {
267
+ socket.end(`${JSON.stringify({ type: 'error', message: 'unparseable request' })}\n`);
268
+ return;
269
+ }
270
+ const emit = (event) => { if (!socket.destroyed)
271
+ socket.write(`${JSON.stringify(event)}\n`); };
272
+ const reply = (event) => { emit(event); socket.end(); };
273
+ if (req.op === 'ask') {
274
+ this.armIdle();
275
+ if (req.env)
276
+ this.clientEnv = curatedClientEnv(req.env);
277
+ void this.enqueue(req.text, req.voice, emit).finally(() => socket.end());
278
+ return;
279
+ }
280
+ try {
281
+ if (req.op === 'status')
282
+ reply(this.status());
283
+ else if (req.op === 'stop') {
284
+ void this.queue.then(async () => {
285
+ reply({ type: 'stopped', project: this.opts.project });
286
+ await this.shutdown();
287
+ });
288
+ }
289
+ else if (req.op === 'roster')
290
+ reply(this.rosterReply(req.project ?? this.opts.project));
291
+ else if (req.op === 'resolve')
292
+ reply(this.resolveReply(req.session));
293
+ else if (req.op === 'hold-stop')
294
+ reply(this.holdStop(req.session));
295
+ else if (req.op === 'spawn')
296
+ reply(this.spawnWorker(req.agent, req.prompt));
297
+ else
298
+ reply({ type: 'error', message: `unknown op ${req.op}` });
299
+ }
300
+ catch (err) {
301
+ reply({ type: 'error', message: err instanceof Error ? err.message : String(err) });
302
+ }
303
+ });
304
+ }
305
+ rosterReply(project) {
306
+ if (!this.roster.ready)
307
+ throw new Error('The live feed is not connected yet; try again in a few seconds.');
308
+ const rows = Object.values(this.projectRoster(project));
309
+ const lines = rows.length ? rows.map(formatRosterRow) : [`No live sessions for ${project}.`];
310
+ return { type: 'roster', text: [`Live sessions for ${project} (${rows.length}):`, ...lines, this.fleetSummary()].join('\n') };
311
+ }
312
+ resolveReply(session) {
313
+ const row = this.findRow(session, Object.values(this.projectRoster()));
314
+ if (!row)
315
+ throw new Error(`No live session '${session}' in ${this.opts.project}; check the roster tool.`);
316
+ return { type: 'session', id: row.id, title: row.title };
317
+ }
318
+ holdStop(session) {
319
+ const row = this.findRow(session, this.liveRows());
320
+ const record = mintConfirm({
321
+ project: this.opts.project,
322
+ action: 'stop',
323
+ sessionId: row?.id ?? session,
324
+ label: row ? `Stop “${row.title}”` : `Stop session ${session}`,
325
+ });
326
+ this.active?.emit({ type: 'confirm', token: record.token, action: 'stop', sessionId: record.sessionId, label: record.label });
327
+ this.log(`held stop of ${record.sessionId} as ${record.token}`);
328
+ return { type: 'held', token: record.token, label: record.label, sessionId: record.sessionId };
329
+ }
330
+ spawnWorker(agent, prompt) {
331
+ const { paths, project } = this.opts;
332
+ const argv = runArgv(agent, prompt, project);
333
+ fs.mkdirSync(paths.runs, { recursive: true, mode: 0o700 });
334
+ const log = path.join(paths.runs, `${new Date().toISOString().replace(/[:.]/g, '-')}-${agent}.log`);
335
+ const fd = fs.openSync(log, 'a');
336
+ const launch = (this.opts.workerLaunch ?? agentsCliLaunch)(argv);
337
+ const child = spawn(launch.command, launch.args, {
338
+ detached: true,
339
+ stdio: ['ignore', fd, fd],
340
+ env: workerEnv(process.env, this.clientEnv, leadRoot()),
341
+ cwd: os.homedir(),
342
+ });
343
+ fs.closeSync(fd);
344
+ child.unref();
345
+ this.log(`spawned ${agent} worker pid ${child.pid} (${log})`);
346
+ return { type: 'spawned', log, pid: child.pid };
347
+ }
348
+ status() {
349
+ const base = statusFromFiles(this.opts.project, this.opts.paths, this.opts.model);
350
+ return {
351
+ ...base,
352
+ state: this.child ? 'warm' : 'cold',
353
+ session: this.childSessionId ?? base.session,
354
+ model: this.opts.model,
355
+ pid: process.pid,
356
+ version: this.opts.version,
357
+ busy: this.busy,
358
+ queued: this.queued,
359
+ };
360
+ }
361
+ schedule(job) {
362
+ const next = this.queue.then(job);
363
+ this.queue = next.catch(() => { });
364
+ return next;
365
+ }
366
+ enqueue(text, voice, emit) {
367
+ this.queued++;
368
+ return this.schedule(async () => {
369
+ this.queued--;
370
+ this.busy = true;
371
+ let rotate = null;
372
+ try {
373
+ rotate = await this.runTurn(text, voice, emit);
374
+ }
375
+ catch (err) {
376
+ emit({ type: 'error', message: err instanceof Error ? err.message : String(err) });
377
+ }
378
+ finally {
379
+ this.busy = false;
380
+ this.armIdle();
381
+ }
382
+ if (rotate) {
383
+ const state = rotate;
384
+ void this.schedule(async () => {
385
+ this.busy = true;
386
+ try {
387
+ await this.rotate(state);
388
+ }
389
+ catch (err) {
390
+ this.log(`rotation failed: ${err instanceof Error ? err.message : String(err)}`);
391
+ }
392
+ finally {
393
+ this.busy = false;
394
+ }
395
+ });
396
+ }
397
+ });
398
+ }
399
+ spawnChild(start) {
400
+ const { paths, project } = this.opts;
401
+ const launch = this.opts.harness(leadRunArgs(project, this.opts.model, start, paths));
402
+ this.log(`spawn ${start.mode} ${start.sessionId}`);
403
+ const env = this.opts.childEnv ?? leadChildEnv(project, paths);
404
+ const child = spawn(launch.command, launch.args, { cwd: paths.dir, stdio: ['pipe', 'pipe', 'pipe'], env });
405
+ this.child = child;
406
+ this.childSessionId = start.sessionId;
407
+ this.childStderr = '';
408
+ child.stdin.on('error', (err) => this.log(`child stdin: ${err.message}`));
409
+ readline.createInterface({ input: child.stdout }).on('line', (line) => {
410
+ if (!line.trim())
411
+ return;
412
+ let msg;
413
+ try {
414
+ msg = JSON.parse(line);
415
+ }
416
+ catch {
417
+ this.log(`child stdout (non-JSON): ${line.slice(0, 200)}`);
418
+ return;
419
+ }
420
+ this.active?.onItem(msg);
421
+ });
422
+ child.stderr.on('data', (d) => {
423
+ const text = d.toString();
424
+ this.childStderr = (this.childStderr + text).slice(-STDERR_TAIL_CHARS);
425
+ this.log(`child stderr: ${text.trim().slice(0, 500)}`);
426
+ });
427
+ child.on('exit', (code, signal) => {
428
+ this.log(`child exited (${code ?? signal})`);
429
+ if (this.child === child) {
430
+ this.child = null;
431
+ this.childSessionId = null;
432
+ }
433
+ this.active?.onExit(code, signal);
434
+ });
435
+ }
436
+ async refreshRefData() {
437
+ const { def } = this.opts;
438
+ const root = resolveDefinedProjectPath(def, undefined, false);
439
+ const fetchTickets = this.opts.fetchTickets ?? ((d) => fetchOpenTickets(d, root));
440
+ const fetchPrs = this.opts.fetchPrs ?? ((d) => fetchRecentPrs(projectRepo(d), root));
441
+ const asError = (err) => ({ error: err instanceof Error ? err.message : String(err) });
442
+ const [tickets, prs] = await Promise.all([fetchTickets(def).catch(asError), fetchPrs(def).catch(asError)]);
443
+ if (Array.isArray(tickets)) {
444
+ for (const t of tickets) {
445
+ this.ticketCache.set(t.id, t);
446
+ this.ticketPrefixes.add(t.id.split('-')[0]);
447
+ }
448
+ }
449
+ else
450
+ this.log(`tickets unavailable: ${tickets.error}`);
451
+ if (Array.isArray(prs))
452
+ for (const p of prs)
453
+ this.knownPrs.add(p.number);
454
+ else
455
+ this.log(`PRs unavailable: ${prs.error}`);
456
+ return { tickets, prs };
457
+ }
458
+ async gatherBrief() {
459
+ const { def, project } = this.opts;
460
+ const [{ tickets, prs }] = await Promise.all([
461
+ this.refreshRefData(),
462
+ this.roster.whenReady(this.opts.feed ? ROSTER_WAIT_MS : 0),
463
+ ]);
464
+ return {
465
+ project, def,
466
+ agentsDigest: agentsMdDigest(resolveDefinedProjectPath(def, undefined, false)),
467
+ roster: this.projectRoster(),
468
+ fleet: this.fleetSummary(),
469
+ tickets, prs,
470
+ memory: readMemory(this.opts.paths),
471
+ };
472
+ }
473
+ async exchange(message, emit, turnId) {
474
+ const child = this.child;
475
+ if (!child)
476
+ throw new Error('Lead process is not running');
477
+ const parser = new LeadTurnParser();
478
+ const tools = new Map();
479
+ let initAtMs = null;
480
+ const result = await new Promise((resolve, reject) => {
481
+ this.active = {
482
+ emit,
483
+ onItem: (msg) => {
484
+ for (const item of parser.feed(msg, Date.now())) {
485
+ if (item.kind === 'init')
486
+ initAtMs = Date.now();
487
+ else if (item.kind === 'result')
488
+ resolve(item.result);
489
+ else {
490
+ const ev = item.event;
491
+ if (ev.type === 'tool') {
492
+ if (ev.state === 'run')
493
+ tools.set(ev.id, { label: ev.label, cmd: ev.cmd, state: 'run', secs: 0 });
494
+ else {
495
+ const t = tools.get(ev.id);
496
+ if (t) {
497
+ t.state = ev.state;
498
+ t.secs = ev.secs;
499
+ }
500
+ }
501
+ }
502
+ emit(ev);
503
+ }
504
+ }
505
+ },
506
+ onExit: (code, signal) => reject(new ChildGone(initAtMs !== null, this.childStderr, `Lead process exited (${code ?? signal}) during turn ${turnId}`)),
507
+ };
508
+ child.stdin.write(`${JSON.stringify({ type: 'user', message: { role: 'user', content: message } })}\n`);
509
+ }).finally(() => { this.active = null; });
510
+ return { result, parser, initAtMs, tools: [...tools.values()] };
511
+ }
512
+ async runTurn(text, voice, emit) {
513
+ const turnId = newTurnId();
514
+ const startedAt = Date.now();
515
+ let state = readSessionState(this.opts.paths);
516
+ let engine = 'warm';
517
+ let briefText;
518
+ let bootStart = null;
519
+ const coldStart = async (forceFresh) => {
520
+ engine = 'cold';
521
+ bootStart ??= Date.now();
522
+ if (state && state.briefed && !forceFresh) {
523
+ this.spawnChild({ mode: 'resume', sessionId: state.sessionId });
524
+ emit({ type: 'turn', turn: turnId, project: this.opts.project, session: state.sessionId, engine });
525
+ emit({ type: 'status', state: 'booting' });
526
+ briefText = undefined;
527
+ return;
528
+ }
529
+ const sessionId = randomUUID();
530
+ this.spawnChild({ mode: 'fresh', sessionId });
531
+ emit({ type: 'turn', turn: turnId, project: this.opts.project, session: sessionId, engine });
532
+ emit({ type: 'status', state: 'booting' });
533
+ const inputs = await this.gatherBrief();
534
+ briefText = buildBrief(inputs);
535
+ state = {
536
+ sessionId,
537
+ model: this.opts.model,
538
+ startedAtMs: Date.now(),
539
+ turns: 0,
540
+ briefed: false,
541
+ brief: briefSummary(inputs),
542
+ rotatedFrom: this.rotatedFrom,
543
+ roster: inputs.roster,
544
+ };
545
+ this.rotatedFrom = undefined;
546
+ };
547
+ if (this.child && state && this.childSessionId === state.sessionId) {
548
+ emit({ type: 'turn', turn: turnId, project: this.opts.project, session: state.sessionId, engine });
549
+ emit({ type: 'status', state: 'thinking' });
550
+ }
551
+ else {
552
+ if (this.child)
553
+ await this.stopChild();
554
+ await coldStart(false);
555
+ }
556
+ const feedLive = () => this.roster.ready || !this.opts.feed;
557
+ let roster = briefText || !feedLive() ? state?.roster ?? {} : this.projectRoster();
558
+ const delta = () => {
559
+ if (briefText)
560
+ return [];
561
+ if (!feedLive())
562
+ return ['Live feed not connected yet; the roster tool will say when it is.'];
563
+ const projectLines = rosterDelta(state?.roster ?? null, roster);
564
+ return [...(projectLines.length ? projectLines : ['No changes to this project\'s sessions.']), this.fleetSummary()];
565
+ };
566
+ const message = () => composeTurnMessage({ brief: briefText, delta: delta(), text, voiceSecs: voice });
567
+ const sent = Date.now();
568
+ let outcome;
569
+ try {
570
+ outcome = await this.exchange(message(), emit, turnId);
571
+ }
572
+ catch (err) {
573
+ const resumeMissing = err instanceof ChildGone && !err.sawInit && engine === 'cold' && !briefText && RESUME_MISSING_RE.test(err.stderr);
574
+ if (!resumeMissing) {
575
+ if (err instanceof ChildGone && err.stderr.trim()) {
576
+ throw new Error(`${err.message}: ${err.stderr.trim().split('\n').pop()}`);
577
+ }
578
+ throw err;
579
+ }
580
+ this.log(`session ${state?.sessionId} is gone; starting a fresh session from the brief`);
581
+ clearSessionState(this.opts.paths);
582
+ state = null;
583
+ await coldStart(true);
584
+ roster = state.roster ?? {};
585
+ outcome = await this.exchange(message(), emit, turnId);
586
+ }
587
+ const { result, parser, initAtMs, tools } = outcome;
588
+ const finished = Date.now();
589
+ const toolSecs = parser.toolSeconds();
590
+ const bootSecs = bootStart !== null ? secs((initAtMs ?? sent) - bootStart) : 0;
591
+ const timing = {
592
+ boot: bootSecs,
593
+ tools: toolSecs,
594
+ model: Math.max(0, Math.round((secs(finished - startedAt) - bootSecs - toolSecs) * 100) / 100),
595
+ };
596
+ const next = {
597
+ ...state,
598
+ briefed: true,
599
+ turns: state.turns + 1,
600
+ lastTurnAtMs: finished,
601
+ lastEngine: engine,
602
+ roster: briefText ? state.roster : roster,
603
+ contextTokens: result.usage?.tokens ?? state.contextTokens,
604
+ contextWindow: result.usage?.window ?? state.contextWindow,
605
+ };
606
+ writeSessionState(this.opts.paths, next);
607
+ if (result.isError) {
608
+ emit({ type: 'error', message: result.text || 'the Lead turn ended with an error' });
609
+ return null;
610
+ }
611
+ const refs = enrichTickets(extractRefs(result.text, {
612
+ ticketPrefixes: this.ticketPrefixes,
613
+ repo: projectRepo(this.opts.def),
614
+ knownPrs: this.knownPrs,
615
+ sessions: this.liveRows(),
616
+ }), { cached: (id) => this.ticketCache.get(id), urlFor: (id) => linearIssueUrl(id) });
617
+ const summary = summarize(result.text);
618
+ emit({ type: 'done', turn: turnId, text: result.text, summary, refs, timing });
619
+ appendHistory(this.opts.paths, {
620
+ turn: turnId,
621
+ at: new Date(startedAt).toISOString(),
622
+ ask: text,
623
+ ...(voice !== undefined ? { voice } : {}),
624
+ text: result.text,
625
+ summary,
626
+ refs,
627
+ tools,
628
+ session: next.sessionId,
629
+ timing,
630
+ });
631
+ return shouldRotate(result.usage) ? next : null;
632
+ }
633
+ async rotate(state) {
634
+ this.log(`rotating ${state.sessionId} at ${state.contextTokens}/${state.contextWindow} tokens`);
635
+ const { result } = await this.exchange(MEMORY_PROMPT, () => { }, 'rotation');
636
+ if (result.isError || !result.text.trim()) {
637
+ throw new Error(`context rotation could not write memory.md: ${result.text || 'empty reply'}`);
638
+ }
639
+ writeMemory(this.opts.paths, result.text.trim());
640
+ await this.stopChild();
641
+ clearSessionState(this.opts.paths);
642
+ this.rotatedFrom = state.sessionId;
643
+ this.log(`rotated ${state.sessionId}; memory.md written, next turn starts fresh`);
644
+ }
645
+ async stopChild() {
646
+ const child = this.child;
647
+ if (!child)
648
+ return;
649
+ const exited = new Promise((resolve) => child.once('exit', () => resolve()));
650
+ child.stdin.end();
651
+ const timer = setTimeout(() => child.kill('SIGTERM'), CHILD_STOP_GRACE_MS);
652
+ const hard = setTimeout(() => child.kill('SIGKILL'), CHILD_STOP_GRACE_MS * 2);
653
+ await exited;
654
+ clearTimeout(timer);
655
+ clearTimeout(hard);
656
+ }
657
+ async shutdown() {
658
+ if (this.stopping)
659
+ return;
660
+ this.stopping = true;
661
+ if (this.idleTimer)
662
+ clearTimeout(this.idleTimer);
663
+ for (const t of this.timers)
664
+ clearTimeout(t);
665
+ this.feedChild?.kill('SIGTERM');
666
+ await this.stopChild();
667
+ await new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve()));
668
+ fs.rmSync(this.opts.paths.host, { force: true });
669
+ fs.rmSync(this.opts.paths.lock, { force: true });
670
+ if (process.platform !== 'win32')
671
+ fs.rmSync(this.opts.paths.socket, { force: true });
672
+ this.log('host stopped');
673
+ this.resolveClosed();
674
+ }
675
+ }
@@ -0,0 +1,22 @@
1
+ export declare function leadRoot(): string;
2
+ export declare function ensureLeadRoot(): string;
3
+ export declare function assertLeadProject(project: string): void;
4
+ export interface LeadPaths {
5
+ dir: string;
6
+ session: string;
7
+ memory: string;
8
+ history: string;
9
+ host: string;
10
+ log: string;
11
+ out: string;
12
+ lock: string;
13
+ settings: string;
14
+ bin: string;
15
+ runs: string;
16
+ socket: string;
17
+ endpoint: string;
18
+ }
19
+ export declare function leadPaths(project: string): LeadPaths;
20
+ export declare function ensureLeadDir(project: string): LeadPaths;
21
+ export declare function confirmsDir(): string;
22
+ export declare function listLeadProjects(): string[];