@phnx-labs/agents-cli 1.23.35 → 1.23.36

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.
@@ -2,15 +2,12 @@ import * as fs from 'node:fs';
2
2
  import * as net from 'node:net';
3
3
  import * as readline from 'node:readline';
4
4
  import { spawn } from 'node:child_process';
5
- import { randomBytes } from 'node:crypto';
6
5
  import { getCliLaunch } from '../cli-entry.js';
7
6
  import { loadProjectDef } from '../projects.js';
8
7
  import { ensureLeadDir, leadPaths } from './paths.js';
9
8
  import { LeadHost, readHostRecord } from './host.js';
10
9
  import { agentsCliLaunch, cliVersion, leadModel } from './harness.js';
11
- import { claimConfirm } from './confirm.js';
12
- import { summarize } from './events.js';
13
- import { appendHistory, appendLog } from './store.js';
10
+ import { appendLog } from './store.js';
14
11
  export const HOST_START_TIMEOUT_MS = 15_000;
15
12
  const HOST_POLL_MS = 100;
16
13
  export function requireProjectDef(project) {
@@ -119,49 +116,3 @@ export async function runLeadHost(project) {
119
116
  await host.closed;
120
117
  return 0;
121
118
  }
122
- export async function runConfirm(token, emit, launch = agentsCliLaunch) {
123
- const record = claimConfirm(token);
124
- const paths = ensureLeadDir(record.project);
125
- const turn = `t_${randomBytes(6).toString('hex')}`;
126
- const startedAt = Date.now();
127
- const args = ['ps', 'stop', record.sessionId];
128
- const cmd = `agents ${args.join(' ')}`;
129
- const toolId = `confirm_${record.token}`;
130
- emit({ type: 'tool', id: toolId, label: 'agents ps stop', cmd, state: 'run' });
131
- const l = launch(args);
132
- const { code, output } = await new Promise((resolve) => {
133
- const child = spawn(l.command, l.args, { stdio: ['ignore', 'pipe', 'pipe'] });
134
- let output = '';
135
- child.stdout.on('data', (d) => { output += d.toString(); });
136
- child.stderr.on('data', (d) => { output += d.toString(); });
137
- child.on('error', (err) => resolve({ code: -1, output: err.message }));
138
- child.on('exit', (c) => resolve({ code: c ?? -1, output }));
139
- });
140
- const secs = Math.round((Date.now() - startedAt) / 10) / 100;
141
- const ok = code === 0;
142
- emit({ type: 'tool', id: toolId, label: 'agents ps stop', state: ok ? 'ok' : 'fail', secs });
143
- const title = record.label.replace(/^Stop\s+/, '');
144
- const text = ok
145
- ? `Stopped ${title}.`
146
- : `Could not stop ${title}: ${output.trim().split('\n').pop() ?? `exit ${code}`}`;
147
- if (!ok) {
148
- emit({ type: 'error', message: text });
149
- return false;
150
- }
151
- const refs = [{ kind: 'session', id: record.sessionId, title: title.replace(/^“|”$/g, '') }];
152
- const timing = { boot: 0, model: 0, tools: secs };
153
- const summary = summarize(text);
154
- emit({ type: 'done', turn, text, summary, refs, timing });
155
- appendHistory(paths, {
156
- turn,
157
- at: new Date(startedAt).toISOString(),
158
- ask: `confirm ${record.token}: ${record.label}`,
159
- text,
160
- summary,
161
- refs,
162
- tools: [{ label: 'agents ps stop', cmd, state: 'ok', secs }],
163
- session: record.sessionId,
164
- timing,
165
- });
166
- return true;
167
- }
@@ -1,10 +1,17 @@
1
1
  export declare const CONFIRM_TTL_MS: number;
2
- export interface ConfirmRecord {
3
- token: string;
2
+ export declare const CONFIRM_ACTIONS: readonly ["stop", "answer", "send", "start", "dispatch", "pr"];
3
+ export type ConfirmAction = typeof CONFIRM_ACTIONS[number];
4
+ export interface HeldAction {
4
5
  project: string;
5
- action: 'stop';
6
- sessionId: string;
6
+ action: ConfirmAction;
7
+ argv: string[];
7
8
  label: string;
9
+ detail?: string;
10
+ sessionId?: string;
11
+ linearArgv?: string[];
12
+ }
13
+ export interface ConfirmRecord extends HeldAction {
14
+ token: string;
8
15
  createdAtMs: number;
9
16
  expiresAtMs: number;
10
17
  }
@@ -12,11 +19,6 @@ export declare class ConfirmError extends Error {
12
19
  readonly reason: 'invalid' | 'unknown' | 'expired';
13
20
  constructor(message: string, reason: 'invalid' | 'unknown' | 'expired');
14
21
  }
15
- export declare function mintConfirm(input: {
16
- project: string;
17
- action: 'stop';
18
- sessionId: string;
19
- label: string;
20
- }, nowMs?: number): ConfirmRecord;
22
+ export declare function mintConfirm(input: HeldAction, nowMs?: number): ConfirmRecord;
21
23
  export declare function claimConfirm(token: string, nowMs?: number): ConfirmRecord;
22
24
  export declare function sweepExpiredConfirms(nowMs?: number): number;
@@ -5,6 +5,7 @@ import { atomicWriteJsonSync } from '../fs-atomic.js';
5
5
  import { confirmsDir, ensureLeadRoot } from './paths.js';
6
6
  export const CONFIRM_TTL_MS = 10 * 60 * 1000;
7
7
  const TOKEN_RE = /^c_[0-9a-f]{16}$/;
8
+ export const CONFIRM_ACTIONS = ['stop', 'answer', 'send', 'start', 'dispatch', 'pr'];
8
9
  export class ConfirmError extends Error {
9
10
  reason;
10
11
  constructor(message, reason) {
@@ -1,3 +1,4 @@
1
+ import type { ConfirmAction } from './confirm.js';
1
2
  export type LeadEngine = 'warm' | 'cold';
2
3
  export type LeadStatusState = 'booting' | 'thinking' | 'tool' | 'answering';
3
4
  export interface LeadTicketRef {
@@ -51,9 +52,10 @@ export type LeadEvent = {
51
52
  } | {
52
53
  type: 'confirm';
53
54
  token: string;
54
- action: 'stop';
55
- sessionId: string;
55
+ action: ConfirmAction;
56
56
  label: string;
57
+ detail?: string;
58
+ sessionId?: string;
57
59
  } | {
58
60
  type: 'done';
59
61
  turn: string;
@@ -1,6 +1,6 @@
1
1
  export const ROTATE_AT_FRACTION = 0.6;
2
- const LEAD_TOOL_RE = /^\s*agents\s+lead\s+tool\s+([a-z]+)/;
3
- const HELD_TOOLS = new Set(['stop']);
2
+ const LEAD_TOOL_RE = /^\s*agents\s+lead\s+tool\s+([a-z]+)(?:\s+([a-z]+))?/;
3
+ const HELD_TOOLS = new Set(['stop', 'answer', 'send', 'start', 'dispatch']);
4
4
  export function toolLabel(command) {
5
5
  const lead = LEAD_TOOL_RE.exec(command);
6
6
  if (lead)
@@ -10,7 +10,9 @@ export function toolLabel(command) {
10
10
  }
11
11
  export function isHeldCommand(command) {
12
12
  const lead = LEAD_TOOL_RE.exec(command);
13
- return lead !== null && HELD_TOOLS.has(lead[1]);
13
+ if (lead === null)
14
+ return false;
15
+ return HELD_TOOLS.has(lead[1]) || (lead[1] === 'prs' && lead[2] !== undefined && lead[2] !== 'list');
14
16
  }
15
17
  function round2(n) {
16
18
  return Math.round(n * 100) / 100;
@@ -1,5 +1,5 @@
1
1
  import type { LeadPaths } from './paths.js';
2
- export declare const LEAD_TOOL_NAMES: readonly ["roster", "dispatch", "start", "send", "stop", "linear", "remember"];
2
+ export declare const LEAD_TOOL_NAMES: readonly ["roster", "attention", "answer", "dispatch", "start", "send", "stop", "prs", "linear", "remember"];
3
3
  export type LeadToolName = typeof LEAD_TOOL_NAMES[number];
4
4
  export declare const LEAD_ALLOWED_TOOLS: readonly string[];
5
5
  export declare const LEAD_DENIED_TOOLS: readonly ["Edit", "Write", "MultiEdit", "NotebookEdit", "Read", "Glob", "Grep", "WebFetch", "WebSearch"];
@@ -23,7 +23,6 @@ export declare function writeLeadSettings(paths: LeadPaths): string;
23
23
  export declare function writeAgentsShim(paths: LeadPaths, launch?: Launch): string;
24
24
  export declare function leadChildEnv(project: string, paths: LeadPaths, source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
25
25
  export declare const WORKER_ENV_PASSTHROUGH: readonly ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "TMPDIR", "XDG_RUNTIME_DIR", "TERM", "SSH_AUTH_SOCK", "GH_TOKEN", "GITHUB_TOKEN", "LINEAR_API_KEY", "DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "COLORTERM", "EDITOR", "VISUAL"];
26
- export declare function curatedClientEnv(source?: NodeJS.ProcessEnv): Record<string, string>;
27
- export declare function workerEnv(hostEnv: NodeJS.ProcessEnv, clientEnv: Record<string, string>, leadRootDir: string): NodeJS.ProcessEnv;
26
+ export declare function workerEnv(source: NodeJS.ProcessEnv, leadRootDir: string): NodeJS.ProcessEnv;
28
27
  export declare function leadRunArgs(project: string, model: string, start: LeadSessionStart, paths: LeadPaths): string[];
29
28
  export declare function agentsCliLaunch(args: string[]): Launch;
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
4
4
  import { getCliLaunch } from '../cli-entry.js';
5
5
  import { atomicWriteFileSync, atomicWriteJsonSync } from '../fs-atomic.js';
6
6
  import { configKeySpec, getConfigValue } from '../device-config.js';
7
- export const LEAD_TOOL_NAMES = ['roster', 'dispatch', 'start', 'send', 'stop', 'linear', 'remember'];
7
+ export const LEAD_TOOL_NAMES = ['roster', 'attention', 'answer', 'dispatch', 'start', 'send', 'stop', 'prs', 'linear', 'remember'];
8
8
  export const LEAD_ALLOWED_TOOLS = LEAD_TOOL_NAMES.map((name) => `Bash(agents lead tool ${name}:*)`);
9
9
  export const LEAD_DENIED_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Read', 'Glob', 'Grep', 'WebFetch', 'WebSearch'];
10
10
  export const LEAD_EFFORT = 'low';
@@ -59,7 +59,7 @@ export const WORKER_ENV_PASSTHROUGH = [
59
59
  'SSH_AUTH_SOCK', 'GH_TOKEN', 'GITHUB_TOKEN', 'LINEAR_API_KEY', 'DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY',
60
60
  'DBUS_SESSION_BUS_ADDRESS', 'COLORTERM', 'EDITOR', 'VISUAL',
61
61
  ];
62
- export function curatedClientEnv(source = process.env) {
62
+ function curatedEnv(source) {
63
63
  const env = {};
64
64
  for (const key of WORKER_ENV_PASSTHROUGH) {
65
65
  const value = source[key];
@@ -71,8 +71,8 @@ export function curatedClientEnv(source = process.env) {
71
71
  env[key] = value;
72
72
  return env;
73
73
  }
74
- export function workerEnv(hostEnv, clientEnv, leadRootDir) {
75
- const env = { ...curatedClientEnv(hostEnv), ...curatedClientEnv(clientEnv) };
74
+ export function workerEnv(source, leadRootDir) {
75
+ const env = curatedEnv(source);
76
76
  if (env.PATH) {
77
77
  env.PATH = env.PATH.split(path.delimiter).filter((dir) => dir && !path.resolve(dir).startsWith(path.resolve(leadRootDir))).join(path.delimiter);
78
78
  }
@@ -1,7 +1,9 @@
1
1
  import { type ProjectDef } from '../projects.js';
2
2
  import { type LeadEngine, type LeadEvent } from './events.js';
3
+ import { type HeldAction } from './confirm.js';
3
4
  import { type BriefPr, type BriefTicket } from './brief.js';
4
5
  import { type LeadPaths } from './paths.js';
6
+ import { type EditorContext } from './shapes.js';
5
7
  import { type Launch } from './harness.js';
6
8
  export declare const LEAD_IDLE_EXIT_MS: number;
7
9
  export declare const ROSTER_WAIT_MS = 4000;
@@ -30,7 +32,7 @@ export type LeadRequest = {
30
32
  op: 'ask';
31
33
  text: string;
32
34
  voice?: number;
33
- env?: Record<string, string>;
35
+ context?: EditorContext;
34
36
  } | {
35
37
  op: 'status';
36
38
  } | {
@@ -45,9 +47,13 @@ export type LeadRequest = {
45
47
  op: 'hold-stop';
46
48
  session: string;
47
49
  } | {
48
- op: 'spawn';
49
- agent: string;
50
- prompt: string;
50
+ op: 'hold';
51
+ held: Omit<HeldAction, 'project'>;
52
+ } | {
53
+ op: 'attention';
54
+ } | {
55
+ op: 'attention-item';
56
+ key: string;
51
57
  };
52
58
  export interface LeadHostRecord {
53
59
  pid: number;
@@ -65,7 +71,6 @@ export interface LeadHostOptions {
65
71
  harness: (args: string[]) => Launch;
66
72
  feed: Launch | null;
67
73
  childEnv?: NodeJS.ProcessEnv;
68
- workerLaunch?: (args: string[]) => Launch;
69
74
  fetchTickets?: (def: ProjectDef) => Promise<BriefTicket[]>;
70
75
  fetchPrs?: (def: ProjectDef) => Promise<BriefPr[]>;
71
76
  teamKey?: string;
@@ -99,7 +104,6 @@ export declare class LeadHost {
99
104
  private readonly knownPrs;
100
105
  private readonly ticketPrefixes;
101
106
  private rotatedFrom;
102
- private clientEnv;
103
107
  private resolveClosed;
104
108
  readonly closed: Promise<void>;
105
109
  constructor(opts: LeadHostOptions);
@@ -117,10 +121,13 @@ export declare class LeadHost {
117
121
  private rosterReply;
118
122
  private resolveReply;
119
123
  private holdStop;
120
- private spawnWorker;
124
+ private hold;
125
+ private openAsk;
126
+ private attentionReply;
127
+ private attentionItem;
121
128
  status(): LeadStatus;
122
129
  private schedule;
123
- enqueue(text: string, voice: number | undefined, emit: (e: LeadEvent) => void): Promise<void>;
130
+ enqueue(text: string, voice: number | undefined, emit: (e: LeadEvent) => void, context?: EditorContext): Promise<void>;
124
131
  private spawnChild;
125
132
  private refreshRefData;
126
133
  private gatherBrief;
@@ -10,12 +10,12 @@ import { listProjectDefsCached, projectNameForCwd, resolveDefinedProjectPath } f
10
10
  import { LeadTurnParser, shouldRotate, summarize, } from './events.js';
11
11
  import { extractRefs, enrichTickets } from './refs.js';
12
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';
13
+ import { FeedRoster, filterProject, formatAttention, formatRosterRow, rosterDelta, } from './roster.js';
14
+ import { LEAD_RULES_ID, agentsMdDigest, briefSummary, buildBrief, composeTurnMessage, fetchOpenTickets, fetchRecentPrs, fleetLine, linearTeamKey, projectRepo, } from './brief.js';
15
15
  import { appendHistory, clearSessionState, readMemory, readSessionState, writeMemory, writeSessionState, } from './store.js';
16
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';
17
+ import { assertHeldArgv, editorContextLines } from './shapes.js';
18
+ import { LEAD_ALLOWED_TOOLS, leadChildEnv, leadRunArgs, writeAgentsShim, writeLeadSettings, } from './harness.js';
19
19
  export const LEAD_IDLE_EXIT_MS = 4 * 60 * 60 * 1000;
20
20
  export const ROSTER_WAIT_MS = 4_000;
21
21
  export const CONFIRM_SWEEP_MS = 5 * 60 * 1000;
@@ -130,7 +130,6 @@ export class LeadHost {
130
130
  knownPrs = new Set();
131
131
  ticketPrefixes = new Set();
132
132
  rotatedFrom;
133
- clientEnv = {};
134
133
  resolveClosed;
135
134
  closed = new Promise((resolve) => { this.resolveClosed = resolve; });
136
135
  constructor(opts) {
@@ -272,9 +271,7 @@ export class LeadHost {
272
271
  const reply = (event) => { emit(event); socket.end(); };
273
272
  if (req.op === 'ask') {
274
273
  this.armIdle();
275
- if (req.env)
276
- this.clientEnv = curatedClientEnv(req.env);
277
- void this.enqueue(req.text, req.voice, emit).finally(() => socket.end());
274
+ void this.enqueue(req.text, req.voice, emit, req.context).finally(() => socket.end());
278
275
  return;
279
276
  }
280
277
  try {
@@ -292,8 +289,12 @@ export class LeadHost {
292
289
  reply(this.resolveReply(req.session));
293
290
  else if (req.op === 'hold-stop')
294
291
  reply(this.holdStop(req.session));
295
- else if (req.op === 'spawn')
296
- reply(this.spawnWorker(req.agent, req.prompt));
292
+ else if (req.op === 'hold')
293
+ reply(this.hold({ ...req.held, project: this.opts.project }));
294
+ else if (req.op === 'attention')
295
+ reply(this.attentionReply());
296
+ else if (req.op === 'attention-item')
297
+ reply(this.attentionItem(req.key));
297
298
  else
298
299
  reply({ type: 'error', message: `unknown op ${req.op}` });
299
300
  }
@@ -317,33 +318,51 @@ export class LeadHost {
317
318
  }
318
319
  holdStop(session) {
319
320
  const row = this.findRow(session, this.liveRows());
320
- const record = mintConfirm({
321
+ const sessionId = row?.id ?? session;
322
+ return this.hold({
321
323
  project: this.opts.project,
322
324
  action: 'stop',
323
- sessionId: row?.id ?? session,
325
+ argv: ['ps', 'stop', sessionId],
326
+ sessionId,
324
327
  label: row ? `Stop “${row.title}”` : `Stop session ${session}`,
325
328
  });
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
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(),
330
+ hold(held) {
331
+ assertHeldArgv(held);
332
+ if (held.action === 'answer' && !this.openAsk(held.argv[2])) {
333
+ throw new Error(`The ask ${held.argv[2]} is no longer open; check the attention tool.`);
334
+ }
335
+ const record = mintConfirm(held);
336
+ this.active?.emit({
337
+ type: 'confirm',
338
+ token: record.token,
339
+ action: record.action,
340
+ label: record.label,
341
+ ...(record.detail !== undefined ? { detail: record.detail } : {}),
342
+ ...(record.sessionId !== undefined ? { sessionId: record.sessionId } : {}),
342
343
  });
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 };
344
+ this.log(`held ${record.action} (${record.label}) as ${record.token}`);
345
+ return { type: 'held', token: record.token, label: record.label };
346
+ }
347
+ openAsk(key) {
348
+ return this.roster.openAttention().find((a) => a.key === key);
349
+ }
350
+ attentionReply() {
351
+ if (!this.roster.ready)
352
+ throw new Error('The live feed is not connected yet; try again in a few seconds.');
353
+ const asks = this.roster.openAttention();
354
+ if (asks.length === 0)
355
+ return { type: 'attention', text: 'No open asks across the fleet.' };
356
+ const rows = this.roster.snapshot();
357
+ return { type: 'attention', text: [`Open asks across the fleet (${asks.length}):`, ...asks.map((a) => formatAttention(a, rows[a.sessionId]))].join('\n') };
358
+ }
359
+ attentionItem(key) {
360
+ if (!this.roster.ready)
361
+ throw new Error('The live feed is not connected yet; try again in a few seconds.');
362
+ const ask = this.openAsk(key);
363
+ if (!ask)
364
+ throw new Error(`No open ask '${key}' in the live feed; check the attention tool.`);
365
+ return { type: 'attention-item', ask, title: this.roster.snapshot()[ask.sessionId]?.title ?? ask.sessionId.slice(0, 8) };
347
366
  }
348
367
  status() {
349
368
  const base = statusFromFiles(this.opts.project, this.opts.paths, this.opts.model);
@@ -363,14 +382,14 @@ export class LeadHost {
363
382
  this.queue = next.catch(() => { });
364
383
  return next;
365
384
  }
366
- enqueue(text, voice, emit) {
385
+ enqueue(text, voice, emit, context) {
367
386
  this.queued++;
368
387
  return this.schedule(async () => {
369
388
  this.queued--;
370
389
  this.busy = true;
371
390
  let rotate = null;
372
391
  try {
373
- rotate = await this.runTurn(text, voice, emit);
392
+ rotate = await this.runTurn(text, voice, emit, context);
374
393
  }
375
394
  catch (err) {
376
395
  emit({ type: 'error', message: err instanceof Error ? err.message : String(err) });
@@ -509,7 +528,7 @@ export class LeadHost {
509
528
  }).finally(() => { this.active = null; });
510
529
  return { result, parser, initAtMs, tools: [...tools.values()] };
511
530
  }
512
- async runTurn(text, voice, emit) {
531
+ async runTurn(text, voice, emit, context) {
513
532
  const turnId = newTurnId();
514
533
  const startedAt = Date.now();
515
534
  let state = readSessionState(this.opts.paths);
@@ -539,11 +558,19 @@ export class LeadHost {
539
558
  turns: 0,
540
559
  briefed: false,
541
560
  brief: briefSummary(inputs),
561
+ rules: LEAD_RULES_ID,
542
562
  rotatedFrom: this.rotatedFrom,
543
563
  roster: inputs.roster,
544
564
  };
545
565
  this.rotatedFrom = undefined;
546
566
  };
567
+ if (state && state.rules !== LEAD_RULES_ID) {
568
+ this.log(`session ${state.sessionId} was briefed with older rules; starting a fresh session from the brief`);
569
+ if (this.child)
570
+ await this.stopChild();
571
+ clearSessionState(this.opts.paths);
572
+ state = null;
573
+ }
547
574
  if (this.child && state && this.childSessionId === state.sessionId) {
548
575
  emit({ type: 'turn', turn: turnId, project: this.opts.project, session: state.sessionId, engine });
549
576
  emit({ type: 'status', state: 'thinking' });
@@ -563,7 +590,8 @@ export class LeadHost {
563
590
  const projectLines = rosterDelta(state?.roster ?? null, roster);
564
591
  return [...(projectLines.length ? projectLines : ['No changes to this project\'s sessions.']), this.fleetSummary()];
565
592
  };
566
- const message = () => composeTurnMessage({ brief: briefText, delta: delta(), text, voiceSecs: voice });
593
+ const editor = context ? editorContextLines(context) : [];
594
+ const message = () => composeTurnMessage({ brief: briefText, delta: delta(), editor, text, voiceSecs: voice });
567
595
  const sent = Date.now();
568
596
  let outcome;
569
597
  try {
@@ -8,19 +8,37 @@ export interface RosterRow {
8
8
  ticket?: string;
9
9
  }
10
10
  export type RosterSnapshot = Record<string, RosterRow>;
11
+ export interface LeadAttention {
12
+ key: string;
13
+ sessionId: string;
14
+ host: string;
15
+ project?: string;
16
+ kind: string;
17
+ openedAt: string;
18
+ question?: string;
19
+ choices: Array<{
20
+ id: string;
21
+ label: string;
22
+ }>;
23
+ }
11
24
  type Row = Record<string, unknown>;
12
25
  export declare function rosterRowFromFeed(scope: string, agent: Row): RosterRow | null;
26
+ export declare function attentionFromFeed(item: Row): LeadAttention | null;
13
27
  export declare class FeedRoster {
14
28
  private readonly byScope;
29
+ private readonly attentionByScope;
15
30
  private readonly scopesSeen;
16
31
  private readonly waiters;
17
32
  apply(envelope: Row): void;
18
33
  get ready(): boolean;
19
34
  whenReady(timeoutMs: number): Promise<boolean>;
20
35
  snapshot(): RosterSnapshot;
36
+ openAttention(): LeadAttention[];
37
+ private scopeAttention;
21
38
  private scopeRows;
22
39
  }
23
40
  export declare function filterProject(snapshot: RosterSnapshot, project: string, projectForCwd: (cwd: string | undefined) => string | undefined, exclude?: ReadonlySet<string>): RosterSnapshot;
24
41
  export declare function formatRosterRow(row: RosterRow): string;
25
42
  export declare function rosterDelta(prev: RosterSnapshot | null, cur: RosterSnapshot): string[];
43
+ export declare function formatAttention(ask: LeadAttention, row: RosterRow | undefined, nowMs?: number): string;
26
44
  export {};
@@ -18,8 +18,27 @@ export function rosterRowFromFeed(scope, agent) {
18
18
  ticket: str(agent.ticketId),
19
19
  };
20
20
  }
21
+ export function attentionFromFeed(item) {
22
+ const key = str(item.key);
23
+ const sessionId = str(item.sessionId);
24
+ if (!key || !sessionId || item.state !== 'open')
25
+ return null;
26
+ const question = (item.question ?? {});
27
+ const choices = Array.isArray(item.choices) ? item.choices : [];
28
+ return {
29
+ key,
30
+ sessionId,
31
+ host: str(item.host) ?? key.split('/')[0],
32
+ project: str(item.project),
33
+ kind: str(item.kind) ?? 'question',
34
+ openedAt: str(item.openedAt) ?? '',
35
+ question: str(question.text) ?? str(question.header),
36
+ choices: choices.flatMap((c) => (str(c.id) ? [{ id: String(c.id), label: str(c.label) ?? String(c.id) }] : [])),
37
+ };
38
+ }
21
39
  export class FeedRoster {
22
40
  byScope = new Map();
41
+ attentionByScope = new Map();
23
42
  scopesSeen = new Set();
24
43
  waiters = [];
25
44
  apply(envelope) {
@@ -33,6 +52,13 @@ export class FeedRoster {
33
52
  rows.set(String(agent.rowKey ?? row.id), row);
34
53
  }
35
54
  this.byScope.set(scope, rows);
55
+ const asks = new Map();
56
+ for (const item of envelope.attention ?? []) {
57
+ const ask = attentionFromFeed(item);
58
+ if (ask)
59
+ asks.set(ask.key, ask);
60
+ }
61
+ this.attentionByScope.set(scope, asks);
36
62
  this.scopesSeen.add(scope);
37
63
  for (const wake of this.waiters.splice(0))
38
64
  wake();
@@ -51,6 +77,19 @@ export class FeedRoster {
51
77
  case 'agent.remove':
52
78
  this.scopeRows(scope).delete(String(envelope.rowKey));
53
79
  return;
80
+ case 'attention.upsert': {
81
+ const asks = this.scopeAttention(scope);
82
+ const key = String(envelope.rowKey);
83
+ const ask = attentionFromFeed(envelope.attention ?? {});
84
+ if (ask)
85
+ asks.set(key, ask);
86
+ else
87
+ asks.delete(key);
88
+ return;
89
+ }
90
+ case 'attention.remove':
91
+ this.scopeAttention(scope).delete(String(envelope.rowKey));
92
+ return;
54
93
  default:
55
94
  return;
56
95
  }
@@ -75,6 +114,21 @@ export class FeedRoster {
75
114
  }
76
115
  return out;
77
116
  }
117
+ openAttention() {
118
+ const out = new Map();
119
+ for (const asks of this.attentionByScope.values())
120
+ for (const ask of asks.values())
121
+ out.set(ask.key, ask);
122
+ return [...out.values()].sort((a, b) => a.openedAt.localeCompare(b.openedAt));
123
+ }
124
+ scopeAttention(scope) {
125
+ let asks = this.attentionByScope.get(scope);
126
+ if (!asks) {
127
+ asks = new Map();
128
+ this.attentionByScope.set(scope, asks);
129
+ }
130
+ return asks;
131
+ }
78
132
  scopeRows(scope) {
79
133
  let rows = this.byScope.get(scope);
80
134
  if (!rows) {
@@ -119,3 +173,24 @@ export function rosterDelta(prev, cur) {
119
173
  }
120
174
  return lines;
121
175
  }
176
+ const MAX_QUESTION_CHARS = 240;
177
+ function age(openedAt, nowMs) {
178
+ const ms = nowMs - Date.parse(openedAt);
179
+ if (!Number.isFinite(ms) || ms < 0)
180
+ return 'just now';
181
+ const mins = Math.floor(ms / 60_000);
182
+ if (mins < 1)
183
+ return 'just now';
184
+ if (mins < 60)
185
+ return `${mins}m ago`;
186
+ const hours = Math.floor(mins / 60);
187
+ return hours < 48 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
188
+ }
189
+ export function formatAttention(ask, row, nowMs = Date.now()) {
190
+ const question = (ask.question ?? `(${ask.kind}, no question text)`).replace(/\s+/g, ' ').trim();
191
+ const trimmed = question.length > MAX_QUESTION_CHARS ? `${question.slice(0, MAX_QUESTION_CHARS - 1)}…` : question;
192
+ const title = row?.title ?? ask.sessionId.slice(0, 8);
193
+ const project = ask.project ?? row?.project;
194
+ const choices = ask.choices.length ? ` Choices: ${ask.choices.map((c) => `${c.id}=${c.label}`).join(', ')}` : ' Free-text answer.';
195
+ return `- ${ask.key} “${title}” on ${ask.host}${project ? ` · ${project}` : ''} · ${age(ask.openedAt, nowMs)}: ${trimmed}${choices}`;
196
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ProjectDef } from '../projects.js';
2
+ import type { ConfirmAction } from './confirm.js';
2
3
  export declare const MAX_TASK_CHARS = 4000;
3
4
  export declare const MAX_NOTE_CHARS = 500;
4
5
  export declare const MAX_MEMORY_LINES = 60;
@@ -20,4 +21,45 @@ export declare function sendArgv(sessionId: string, text: string): string[];
20
21
  export declare function linearTasksArgv(def: ProjectDef, status: string, limit: number): string[];
21
22
  export declare function linearViewArgv(id: string): string[];
22
23
  export declare function linearCreateArgv(def: ProjectDef, title: string, description?: string): string[];
24
+ export declare const PR_VERBS: readonly ["merge", "comment", "ready", "rerun", "close"];
25
+ export type PrVerb = typeof PR_VERBS[number];
26
+ export declare function assertAttentionKey(key: string): string;
27
+ export declare function assertAnswerText(text: string): string;
28
+ export type AnswerValue = {
29
+ choice: string;
30
+ } | {
31
+ text: string;
32
+ };
33
+ export declare function answerArgv(key: string, value: AnswerValue): string[];
34
+ export declare function assertRepo(repo: string): string;
35
+ export declare function assertPrNumber(raw: string | number): number;
36
+ export declare function assertSha(sha: string): string;
37
+ export declare function prsListArgv(project: string, repo?: string): string[];
38
+ export declare function prReadArgv(project: string, repo: string, number: number): string[];
39
+ export declare function prFailureArgv(project: string, repo: string, sha: string): string[];
40
+ export interface PrAction {
41
+ repo: string;
42
+ number: number;
43
+ sha?: string;
44
+ body?: string;
45
+ runId?: number;
46
+ }
47
+ export declare function prArgv(project: string, verb: PrVerb, a: PrAction): string[];
48
+ export declare function assertHeldArgv(held: {
49
+ action: ConfirmAction;
50
+ project: string;
51
+ argv: string[];
52
+ linearArgv?: string[];
53
+ }): void;
54
+ export interface EditorTab {
55
+ sessionId?: string;
56
+ title?: string;
57
+ tab?: number;
58
+ }
59
+ export interface EditorContext {
60
+ front?: EditorTab;
61
+ tabs?: EditorTab[];
62
+ }
63
+ export declare function parseEditorContext(raw: string): EditorContext;
64
+ export declare function editorContextLines(ctx: EditorContext): string[];
23
65
  export declare function appendNote(memory: string, note: string): string;