@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.
@@ -1,3 +1,4 @@
1
+ import { isDeepStrictEqual } from 'node:util';
1
2
  import { isAgentId } from '../types.js';
2
3
  export const MAX_TASK_CHARS = 4_000;
3
4
  export const MAX_NOTE_CHARS = 500;
@@ -54,7 +55,10 @@ export function dispatchPrompt(id, title) {
54
55
  return `Work on ${id}: ${title}`;
55
56
  }
56
57
  export function runArgv(agent, prompt, project) {
57
- return ['run', assertAgent(agent), assertTask(prompt), '--headless', '-P', project, '--mode', 'edit'];
58
+ const task = assertTask(prompt);
59
+ if (task.startsWith('-'))
60
+ throw new LeadToolError('Refusing a task that starts with - (agents run would read it as a flag).');
61
+ return ['run', assertAgent(agent), task, '--headless', '-P', project, '--mode', 'edit'];
58
62
  }
59
63
  export function linearPickupArgv(id, agent) {
60
64
  return ['update', assertTicketId(id), '--pickup', '--delegate', assertAgent(agent)];
@@ -83,6 +87,203 @@ export function linearCreateArgv(def, title, description) {
83
87
  args.push('--description', assertTask(description));
84
88
  return args;
85
89
  }
90
+ const ATTENTION_KEY_RE = /^\w[^\s/]{0,127}\/[^\s/]{1,128}\/[^\s/]{1,128}$/;
91
+ const CHOICE_ID_RE = /^[\w.:-]{1,64}$/;
92
+ const REPO_RE = /^[\w.-]+\/[\w.-]+$/;
93
+ const SHA_RE = /^[0-9a-f]{7,40}$/i;
94
+ export const PR_VERBS = ['merge', 'comment', 'ready', 'rerun', 'close'];
95
+ export function assertAttentionKey(key) {
96
+ if (!ATTENTION_KEY_RE.test(key))
97
+ throw new LeadToolError(`'${key}' is not an attention key (expected <host>/<session>/<generation>, from the attention tool).`);
98
+ return key;
99
+ }
100
+ export function assertAnswerText(text) {
101
+ if (SEND_LINE_BREAK.test(text))
102
+ throw new LeadToolError('An answer must be one line.');
103
+ const body = assertTask(text.replace(SEND_CONTROL, ''));
104
+ if (SEND_SPECIAL_FIRST.test(body)) {
105
+ throw new LeadToolError('Refusing an answer that starts with /, ! or # (a slash command, shell escape or memory note in the session).');
106
+ }
107
+ return body;
108
+ }
109
+ export function answerArgv(key, value) {
110
+ assertAttentionKey(key);
111
+ if ('choice' in value) {
112
+ if (!CHOICE_ID_RE.test(value.choice))
113
+ throw new LeadToolError(`'${value.choice}' is not a choice id.`);
114
+ return ['feed', 'answer', key, '--choice', value.choice, '--json'];
115
+ }
116
+ return ['feed', 'answer', key, '--text', assertAnswerText(value.text), '--json'];
117
+ }
118
+ export function assertRepo(repo) {
119
+ if (!REPO_RE.test(repo))
120
+ throw new LeadToolError(`--repo expects owner/repo, got '${repo}'.`);
121
+ return repo;
122
+ }
123
+ export function assertPrNumber(raw) {
124
+ const n = typeof raw === 'number' ? raw : /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN;
125
+ if (!Number.isSafeInteger(n) || n <= 0)
126
+ throw new LeadToolError(`--number expects a positive integer, got '${raw}'.`);
127
+ return n;
128
+ }
129
+ export function assertSha(sha) {
130
+ if (!SHA_RE.test(sha))
131
+ throw new LeadToolError(`--sha expects a commit SHA, got '${sha}'.`);
132
+ return sha;
133
+ }
134
+ export function prsListArgv(project, repo) {
135
+ return ['projects', 'prs', 'list', project, '--json', ...(repo !== undefined ? ['--repo', assertRepo(repo)] : [])];
136
+ }
137
+ export function prReadArgv(project, repo, number) {
138
+ return ['projects', 'prs', 'list', project, '--json', '--repo', assertRepo(repo), '--number', String(assertPrNumber(number))];
139
+ }
140
+ export function prFailureArgv(project, repo, sha) {
141
+ return ['projects', 'prs', 'failure', project, '--repo', assertRepo(repo), '--sha', assertSha(sha), '--json'];
142
+ }
143
+ export function prArgv(project, verb, a) {
144
+ const base = ['projects', 'prs', verb, project, '--repo', assertRepo(a.repo)];
145
+ switch (verb) {
146
+ case 'merge':
147
+ if (a.sha === undefined)
148
+ throw new LeadToolError('A merge is pinned to the head commit; it needs its SHA.');
149
+ return [...base, '--number', String(assertPrNumber(a.number)), '--sha', assertSha(a.sha), '--json'];
150
+ case 'ready':
151
+ return [...base, '--number', String(assertPrNumber(a.number)), ...(a.sha !== undefined ? ['--sha', assertSha(a.sha)] : []), '--json'];
152
+ case 'comment':
153
+ if (a.body === undefined)
154
+ throw new LeadToolError('A comment needs --body <text>.');
155
+ return [...base, '--number', String(assertPrNumber(a.number)), '--body', assertTask(a.body), '--json'];
156
+ case 'close':
157
+ return [...base, '--number', String(assertPrNumber(a.number)), '--json'];
158
+ case 'rerun':
159
+ if (a.runId === undefined || !Number.isSafeInteger(a.runId) || a.runId <= 0)
160
+ throw new LeadToolError('A re-run needs a workflow run id.');
161
+ return [...base, '--run-id', String(a.runId), '--json'];
162
+ }
163
+ }
164
+ function prActionFromArgv(argv) {
165
+ const flag = (name) => { const i = argv.indexOf(name); return i === -1 ? undefined : argv[i + 1]; };
166
+ const runId = flag('--run-id');
167
+ const number = flag('--number');
168
+ return {
169
+ repo: flag('--repo') ?? '',
170
+ number: number === undefined ? 0 : Number(number),
171
+ sha: flag('--sha'),
172
+ body: flag('--body'),
173
+ runId: runId === undefined ? undefined : Number(runId),
174
+ };
175
+ }
176
+ export function assertHeldArgv(held) {
177
+ const { action, project, argv } = held;
178
+ let rebuilt;
179
+ switch (action) {
180
+ case 'stop':
181
+ rebuilt = ['ps', 'stop', assertSessionId(argv[2] ?? '')];
182
+ break;
183
+ case 'answer':
184
+ rebuilt = answerArgv(argv[2] ?? '', argv[3] === '--choice' ? { choice: argv[4] ?? '' } : { text: argv[4] ?? '' });
185
+ break;
186
+ case 'send':
187
+ if (!(argv[6] ?? '').startsWith(SEND_LABEL))
188
+ throw new LeadToolError('A held send has lost its [Lead] label.');
189
+ rebuilt = sendArgv(assertSessionId(argv[4] ?? ''), (argv[6] ?? '').slice(SEND_LABEL.length));
190
+ break;
191
+ case 'start':
192
+ case 'dispatch':
193
+ rebuilt = runArgv(argv[1] ?? '', argv[2] ?? '', project);
194
+ break;
195
+ case 'pr': {
196
+ const verb = argv[2];
197
+ if (!PR_VERBS.includes(verb))
198
+ throw new LeadToolError(`'${verb}' is not a PR action the Lead may hold.`);
199
+ rebuilt = prArgv(project, verb, prActionFromArgv(argv));
200
+ break;
201
+ }
202
+ }
203
+ if (!isDeepStrictEqual(argv, rebuilt))
204
+ throw new LeadToolError(`The held ${action} is not one of its fixed shapes; nothing was run.`);
205
+ const linear = held.linearArgv;
206
+ if (action === 'dispatch') {
207
+ if (!linear || !isDeepStrictEqual(linear, linearPickupArgv(linear[1] ?? '', linear[4] ?? ''))) {
208
+ throw new LeadToolError('The held dispatch has no valid ticket pickup; nothing was run.');
209
+ }
210
+ }
211
+ else if (linear !== undefined) {
212
+ throw new LeadToolError(`A held ${action} carries a ticket pickup it never has; nothing was run.`);
213
+ }
214
+ }
215
+ const MAX_CONTEXT_TABS = 60;
216
+ const MAX_CONTEXT_TITLE = 200;
217
+ const CONTEXT_SESSION_RE = /^[\w-]{1,64}$/;
218
+ function contextTab(raw, where) {
219
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
220
+ throw new LeadToolError(`--context: ${where} must be an object.`);
221
+ const out = {};
222
+ for (const [key, value] of Object.entries(raw)) {
223
+ if (key === 'sessionId') {
224
+ if (typeof value !== 'string' || !CONTEXT_SESSION_RE.test(value))
225
+ throw new LeadToolError(`--context: ${where}.sessionId must be a session id.`);
226
+ out.sessionId = value;
227
+ }
228
+ else if (key === 'title') {
229
+ if (typeof value !== 'string')
230
+ throw new LeadToolError(`--context: ${where}.title must be a string.`);
231
+ const title = value.replace(SEND_CONTROL, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_CONTEXT_TITLE);
232
+ if (title)
233
+ out.title = title;
234
+ }
235
+ else if (key === 'tab') {
236
+ if (!Number.isSafeInteger(value) || value < 1)
237
+ throw new LeadToolError(`--context: ${where}.tab must be a positive integer.`);
238
+ out.tab = value;
239
+ }
240
+ else {
241
+ throw new LeadToolError(`--context: ${where} has an unknown field '${key}' (expected sessionId, title, tab).`);
242
+ }
243
+ }
244
+ return out;
245
+ }
246
+ export function parseEditorContext(raw) {
247
+ let parsed;
248
+ try {
249
+ parsed = JSON.parse(raw);
250
+ }
251
+ catch {
252
+ throw new LeadToolError('--context expects a JSON object, e.g. {"front":{"sessionId":"…","title":"…","tab":3}}.');
253
+ }
254
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
255
+ throw new LeadToolError('--context expects a JSON object.');
256
+ const out = {};
257
+ for (const [key, value] of Object.entries(parsed)) {
258
+ if (key === 'front')
259
+ out.front = contextTab(value, 'front');
260
+ else if (key === 'tabs') {
261
+ if (!Array.isArray(value))
262
+ throw new LeadToolError('--context: tabs must be an array.');
263
+ if (value.length > MAX_CONTEXT_TABS)
264
+ throw new LeadToolError(`--context: at most ${MAX_CONTEXT_TABS} tabs.`);
265
+ out.tabs = value.map((t, i) => contextTab(t, `tabs[${i}]`));
266
+ }
267
+ else
268
+ throw new LeadToolError(`--context has an unknown field '${key}' (expected front, tabs).`);
269
+ }
270
+ return out;
271
+ }
272
+ function describeTab(t) {
273
+ return [
274
+ t.tab !== undefined ? `tab ${t.tab}` : null,
275
+ t.title ? `“${t.title}”` : null,
276
+ t.sessionId ? `(session ${t.sessionId.slice(0, 8)})` : null,
277
+ ].filter(Boolean).join(' ') || 'a tab with no session';
278
+ }
279
+ export function editorContextLines(ctx) {
280
+ const lines = [];
281
+ if (ctx.front)
282
+ lines.push(`Front tab (what "this one" means): ${describeTab(ctx.front)}`);
283
+ if (ctx.tabs?.length)
284
+ lines.push(`Open tabs: ${ctx.tabs.map(describeTab).join('; ')}`);
285
+ return lines;
286
+ }
86
287
  export function appendNote(memory, note) {
87
288
  const clean = note.replace(/\s+/g, ' ').trim();
88
289
  if (!clean)
@@ -0,0 +1,35 @@
1
+ import type { LeadEvent } from './events.js';
2
+ export declare const VOICE_MODEL = "eleven_turbo_v2_5";
3
+ export declare const VOICE_ID = "JBFqnCBsd6RMkjVDRZzb";
4
+ export declare const VOICE_KEY = "ELEVENLABS_API_KEY";
5
+ export declare class SentenceSplitter {
6
+ private buf;
7
+ push(delta: string): string[];
8
+ flush(): string[];
9
+ }
10
+ export declare function speakable(sentence: string): string | null;
11
+ export declare function playerArgv(file: string, platform?: NodeJS.Platform): string[];
12
+ export declare function voiceBundle(): string;
13
+ export interface SpeakerOptions {
14
+ apiKey: Promise<string>;
15
+ baseUrl?: string;
16
+ player?: (file: string) => string[];
17
+ onError?: (line: string) => void;
18
+ }
19
+ export declare class LeadSpeaker {
20
+ private readonly opts;
21
+ private readonly splitter;
22
+ private readonly dir;
23
+ private chain;
24
+ private clips;
25
+ private sawText;
26
+ private dead;
27
+ constructor(opts: SpeakerOptions);
28
+ static start(): LeadSpeaker | null;
29
+ onEvent(e: LeadEvent): void;
30
+ drain(): Promise<void>;
31
+ private fail;
32
+ private say;
33
+ private synthesize;
34
+ private play;
35
+ }
@@ -0,0 +1,165 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+ import { spawn } from 'node:child_process';
5
+ import { configKeySpec, getConfigValue } from '../device-config.js';
6
+ export const VOICE_MODEL = 'eleven_turbo_v2_5';
7
+ export const VOICE_ID = 'JBFqnCBsd6RMkjVDRZzb';
8
+ export const VOICE_KEY = 'ELEVENLABS_API_KEY';
9
+ const ELEVENLABS_URL = 'https://api.elevenlabs.io';
10
+ const SYNTH_TIMEOUT_MS = 20_000;
11
+ const PLAY_TIMEOUT_MS = 60_000;
12
+ const BOUNDARY = /[.!?…]+["”’')\]]*(?=\s)|\n+/g;
13
+ const ABBREVIATION = /(?:^|\s)(?:e\.g|i\.e|etc|vs|approx|Mr|Mrs|Ms|Dr|St|No)\.$/i;
14
+ const LIST_MARKER = /^\W*(?:\d+|[a-z])[.)]$/i;
15
+ export class SentenceSplitter {
16
+ buf = '';
17
+ push(delta) {
18
+ this.buf += delta;
19
+ const out = [];
20
+ let from = 0;
21
+ BOUNDARY.lastIndex = 0;
22
+ for (let m = BOUNDARY.exec(this.buf); m; m = BOUNDARY.exec(this.buf)) {
23
+ const end = m.index + m[0].length;
24
+ const candidate = this.buf.slice(from, end).trim();
25
+ if (!m[0].startsWith('\n') && (ABBREVIATION.test(candidate) || LIST_MARKER.test(candidate)))
26
+ continue;
27
+ if (candidate)
28
+ out.push(candidate);
29
+ from = end;
30
+ }
31
+ this.buf = this.buf.slice(from);
32
+ return out;
33
+ }
34
+ flush() {
35
+ const rest = this.buf.trim();
36
+ this.buf = '';
37
+ return rest ? [rest] : [];
38
+ }
39
+ }
40
+ export function speakable(sentence) {
41
+ const text = sentence
42
+ .replace(/https?:\/\/\S+/g, '')
43
+ .replace(/`([^`]*)`/g, '$1')
44
+ .replace(/[*_>|~]+|#+(?!\d)/g, ' ')
45
+ .replace(/^\s*[-•]\s+/, '')
46
+ .replace(/\s+/g, ' ')
47
+ .trim();
48
+ return /[\p{L}\p{N}]/u.test(text) ? text : null;
49
+ }
50
+ export function playerArgv(file, platform = process.platform) {
51
+ return platform === 'darwin' ? ['afplay', file] : ['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', file];
52
+ }
53
+ export function voiceBundle() {
54
+ const value = getConfigValue('lead.voice.bundle').value;
55
+ return typeof value === 'string' && value.length > 0 ? value : String(configKeySpec('lead.voice.bundle').defaultValue);
56
+ }
57
+ async function readVoiceKey(bundle) {
58
+ const [{ readAndResolveBundleEnv }, { resolveSecretsContextForRun }] = await Promise.all([
59
+ import('../secrets-client.js'),
60
+ import('../secrets-policy.js'),
61
+ ]);
62
+ const { env } = await readAndResolveBundleEnv(bundle, { caller: 'agents lead ask --speak', keys: [VOICE_KEY] }, await resolveSecretsContextForRun());
63
+ const key = env[VOICE_KEY];
64
+ if (!key)
65
+ throw new Error(`secrets bundle '${bundle}' has no ${VOICE_KEY}`);
66
+ return key;
67
+ }
68
+ export class LeadSpeaker {
69
+ opts;
70
+ splitter = new SentenceSplitter();
71
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agents-lead-speak-'));
72
+ chain = Promise.resolve();
73
+ clips = 0;
74
+ sawText = false;
75
+ dead = false;
76
+ constructor(opts) {
77
+ this.opts = opts;
78
+ opts.apiKey.catch((err) => this.fail(err));
79
+ }
80
+ static start() {
81
+ try {
82
+ return new LeadSpeaker({ apiKey: readVoiceKey(voiceBundle()) });
83
+ }
84
+ catch (err) {
85
+ process.stderr.write(`voice: ${err instanceof Error ? err.message : String(err)}; the reply is not spoken.\n`);
86
+ return null;
87
+ }
88
+ }
89
+ onEvent(e) {
90
+ if (e.type === 'text') {
91
+ this.sawText = true;
92
+ for (const s of this.splitter.push(e.delta))
93
+ this.say(s);
94
+ }
95
+ else if (e.type === 'done') {
96
+ const rest = this.sawText ? this.splitter.flush() : [...this.splitter.push(e.text), ...this.splitter.flush()];
97
+ for (const s of rest)
98
+ this.say(s);
99
+ }
100
+ else if (e.type === 'error') {
101
+ for (const s of this.splitter.flush())
102
+ this.say(s);
103
+ }
104
+ }
105
+ async drain() {
106
+ await this.chain;
107
+ fs.rmSync(this.dir, { recursive: true, force: true });
108
+ }
109
+ fail(err) {
110
+ if (this.dead)
111
+ return;
112
+ this.dead = true;
113
+ (this.opts.onError ?? ((line) => process.stderr.write(`${line}\n`)))(`voice: ${err instanceof Error ? err.message : String(err)}; the reply is not spoken.`);
114
+ }
115
+ say(sentence) {
116
+ const text = speakable(sentence);
117
+ if (!text || this.dead)
118
+ return;
119
+ const file = path.join(this.dir, `${String(++this.clips).padStart(3, '0')}.mp3`);
120
+ const audio = this.synthesize(text, file);
121
+ audio.catch(() => { });
122
+ this.chain = this.chain.then(async () => {
123
+ if (this.dead)
124
+ return;
125
+ try {
126
+ await audio;
127
+ await this.play(file);
128
+ }
129
+ catch (err) {
130
+ this.fail(err);
131
+ }
132
+ finally {
133
+ fs.rmSync(file, { force: true });
134
+ }
135
+ });
136
+ }
137
+ async synthesize(text, file) {
138
+ const key = await this.opts.apiKey;
139
+ const url = `${this.opts.baseUrl ?? ELEVENLABS_URL}/v1/text-to-speech/${VOICE_ID}?output_format=mp3_44100_128`;
140
+ const res = await fetch(url, {
141
+ method: 'POST',
142
+ headers: { 'xi-api-key': key, 'content-type': 'application/json', accept: 'audio/mpeg' },
143
+ body: JSON.stringify({ text, model_id: VOICE_MODEL }),
144
+ signal: AbortSignal.timeout(SYNTH_TIMEOUT_MS),
145
+ });
146
+ if (!res.ok)
147
+ throw new Error(`ElevenLabs answered HTTP ${res.status}`);
148
+ fs.writeFileSync(file, Buffer.from(await res.arrayBuffer()), { mode: 0o600 });
149
+ }
150
+ play(file) {
151
+ const [command, ...args] = (this.opts.player ?? playerArgv)(file);
152
+ return new Promise((resolve, reject) => {
153
+ const child = spawn(command, args, { stdio: 'ignore' });
154
+ const timer = setTimeout(() => child.kill('SIGKILL'), PLAY_TIMEOUT_MS);
155
+ child.on('error', (err) => { clearTimeout(timer); reject(err.code === 'ENOENT' ? new Error(`${command} is not installed`) : err); });
156
+ child.on('exit', (code, signal) => {
157
+ clearTimeout(timer);
158
+ if (code === 0)
159
+ resolve();
160
+ else
161
+ reject(new Error(signal === 'SIGKILL' ? `${command} did not finish within ${PLAY_TIMEOUT_MS / 1000}s` : `${command} exited ${code}`));
162
+ });
163
+ });
164
+ }
165
+ }
@@ -8,6 +8,7 @@ export interface LeadSessionState {
8
8
  turns: number;
9
9
  briefed: boolean;
10
10
  brief: string[];
11
+ rules?: string;
11
12
  contextTokens?: number;
12
13
  contextWindow?: number;
13
14
  lastTurnAtMs?: number;
@@ -1,4 +1,5 @@
1
1
  import { type ProjectDef } from '../projects.js';
2
+ import { type AnswerValue, type PrVerb } from './shapes.js';
2
3
  import { type LeadPaths } from './paths.js';
3
4
  export * from './shapes.js';
4
5
  export interface LeadToolContext {
@@ -8,10 +9,20 @@ export interface LeadToolContext {
8
9
  }
9
10
  export declare function leadToolContext(env?: NodeJS.ProcessEnv): LeadToolContext;
10
11
  export declare function toolRoster(ctx: LeadToolContext, project?: string): Promise<string>;
12
+ export declare function toolAttention(ctx: LeadToolContext): Promise<string>;
11
13
  export declare function toolDispatch(ctx: LeadToolContext, ticket: string, agent: string): Promise<string>;
12
14
  export declare function toolStart(ctx: LeadToolContext, agent: string, task: string): Promise<string>;
13
15
  export declare function toolSend(ctx: LeadToolContext, session: string, text: string): Promise<string>;
16
+ export declare function toolAnswer(ctx: LeadToolContext, key: string, value: AnswerValue): Promise<string>;
14
17
  export declare function toolStop(ctx: LeadToolContext, session: string): Promise<string>;
18
+ export declare function toolPrsList(ctx: LeadToolContext, repo?: string): Promise<string>;
19
+ export declare function toolPrAct(ctx: LeadToolContext, verb: PrVerb, opts: {
20
+ repo: string;
21
+ number: string;
22
+ sha?: string;
23
+ body?: string;
24
+ runId?: string;
25
+ }): Promise<string>;
15
26
  export declare function toolLinearTasks(ctx: LeadToolContext, status: string, limit: number): Promise<string>;
16
27
  export declare function toolLinearView(id: string): Promise<string>;
17
28
  export declare function toolLinearCreate(ctx: LeadToolContext, title: string, description?: string): Promise<string>;
@@ -1,13 +1,11 @@
1
- import { execFile } from 'node:child_process';
2
- import { getCliLaunch } from '../cli-entry.js';
3
1
  import { loadProjectDef } from '../projects.js';
4
2
  import { atomicWriteFileSync } from '../fs-atomic.js';
5
3
  import { connectHost, sendRequest } from './client.js';
6
- import { LeadToolError, appendNote, assertAgent, assertSendText, assertSessionId, assertTask, assertTicketId, dispatchPrompt, linearCreateArgv, linearPickupArgv, linearTasksArgv, linearViewArgv, runArgv, sendArgv, } from './shapes.js';
4
+ import { runAgents, runLinear } from './act.js';
5
+ import { LeadToolError, answerArgv, appendNote, assertAgent, assertPrNumber, assertRepo, assertSessionId, assertTask, assertTicketId, dispatchPrompt, linearCreateArgv, linearPickupArgv, linearTasksArgv, linearViewArgv, prArgv, prFailureArgv, prReadArgv, prsListArgv, runArgv, sendArgv, } from './shapes.js';
7
6
  import { ensureLeadDir } from './paths.js';
8
7
  import { readMemory } from './store.js';
9
8
  export * from './shapes.js';
10
- const LINEAR_TIMEOUT_MS = 20_000;
11
9
  export function leadToolContext(env = process.env) {
12
10
  const project = env.AGENTS_LEAD_PROJECT;
13
11
  if (!project)
@@ -17,16 +15,6 @@ export function leadToolContext(env = process.env) {
17
15
  throw new LeadToolError(`Unknown project '${project}'.`);
18
16
  return { project, def, paths: ensureLeadDir(project) };
19
17
  }
20
- function runLinear(args) {
21
- return new Promise((resolve, reject) => {
22
- execFile('linear', args, { timeout: LINEAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
23
- if (err)
24
- reject(new LeadToolError(`linear ${args[0]} failed: ${String(stderr || err.message).trim().split('\n').pop()}`));
25
- else
26
- resolve(stdout);
27
- });
28
- });
29
- }
30
18
  async function hostRequest(project, req) {
31
19
  const socket = await connectHost(project);
32
20
  if (!socket)
@@ -39,50 +27,123 @@ async function hostRequest(project, req) {
39
27
  throw new LeadToolError(String(reply.message));
40
28
  return reply;
41
29
  }
42
- async function spawnWorker(ctx, agent, prompt) {
43
- const reply = await hostRequest(ctx.project, { op: 'spawn', agent, prompt });
44
- return String(reply.log);
30
+ async function hold(ctx, held) {
31
+ const reply = await hostRequest(ctx.project, { op: 'hold', held });
32
+ return `Queued for the owner's Confirm: ${String(reply.label)}. Nothing has happened yet. Say what you queued and ask once; do not queue it again.`;
45
33
  }
46
34
  export async function toolRoster(ctx, project) {
47
35
  const reply = await hostRequest(ctx.project, { op: 'roster', project: project ?? ctx.project });
48
36
  return String(reply.text);
49
37
  }
38
+ export async function toolAttention(ctx) {
39
+ const reply = await hostRequest(ctx.project, { op: 'attention' });
40
+ return String(reply.text);
41
+ }
50
42
  export async function toolDispatch(ctx, ticket, agent) {
51
43
  assertTicketId(ticket);
52
44
  assertAgent(agent);
53
45
  const issue = JSON.parse(await runLinear(linearViewArgv(ticket)));
54
46
  const prompt = dispatchPrompt(issue.identifier, issue.title);
55
- runArgv(agent, prompt, ctx.project);
56
- await runLinear(linearPickupArgv(issue.identifier, agent));
57
- const log = await spawnWorker(ctx, agent, prompt);
58
- return `Dispatched ${agent} on ${issue.identifier}: ${issue.title}. ${issue.identifier} is In Progress, delegated to ${agent}. Log: ${log}`;
47
+ return hold(ctx, {
48
+ action: 'dispatch',
49
+ argv: runArgv(agent, prompt, ctx.project),
50
+ linearArgv: linearPickupArgv(issue.identifier, agent),
51
+ label: `Dispatch ${agent} on ${issue.identifier}: ${issue.title}`,
52
+ detail: prompt,
53
+ });
59
54
  }
60
55
  export async function toolStart(ctx, agent, task) {
61
- runArgv(agent, task, ctx.project);
62
- const log = await spawnWorker(ctx, agent, task);
63
- return `Started ${agent} on: ${assertTask(task).slice(0, 120)}. Log: ${log}`;
56
+ const argv = runArgv(agent, task, ctx.project);
57
+ return hold(ctx, { action: 'start', argv, label: `Start ${agent} on: ${argv[2].slice(0, 80)}`, detail: argv[2] });
64
58
  }
65
59
  export async function toolSend(ctx, session, text) {
66
60
  assertSessionId(session);
67
- assertSendText(text);
61
+ const argv = sendArgv(session, text);
68
62
  const reply = await hostRequest(ctx.project, { op: 'resolve', session });
69
63
  const id = String(reply.id);
70
- const argv = sendArgv(id, text);
71
- const launch = getCliLaunch(argv);
72
- await new Promise((resolve, reject) => {
73
- execFile(launch.command, launch.args, { timeout: 60_000 }, (err, _stdout, stderr) => {
74
- if (err)
75
- reject(new LeadToolError(`agents send failed: ${String(stderr || err.message).trim().split('\n').pop()}`));
76
- else
77
- resolve();
78
- });
79
- });
80
- return `Sent to “${String(reply.title)}” (${id.slice(0, 8)}).`;
64
+ return hold(ctx, { action: 'send', argv: sendArgv(id, text), sessionId: id, label: `Send to “${String(reply.title)}”`, detail: argv[6] });
65
+ }
66
+ export async function toolAnswer(ctx, key, value) {
67
+ const argv = answerArgv(key, value);
68
+ const reply = await hostRequest(ctx.project, { op: 'attention-item', key });
69
+ const ask = reply.ask;
70
+ let detail;
71
+ if ('choice' in value) {
72
+ const choice = ask.choices.find((c) => c.id === value.choice);
73
+ if (!choice) {
74
+ const known = ask.choices.map((c) => `${c.id}=${c.label}`).join(', ');
75
+ throw new LeadToolError(`'${value.choice}' is not a choice of this ask (${known || 'it takes a free-text answer'}).`);
76
+ }
77
+ detail = choice.label;
78
+ }
79
+ else
80
+ detail = argv[4];
81
+ return hold(ctx, { action: 'answer', argv, sessionId: ask.sessionId, label: `Answer “${String(reply.title)}”`, detail });
81
82
  }
82
83
  export async function toolStop(ctx, session) {
83
84
  assertSessionId(session);
84
85
  const reply = await hostRequest(ctx.project, { op: 'hold-stop', session });
85
- return `Held for the owner's Confirm: ${String(reply.label)}. Nothing was stopped. Do not retry.`;
86
+ return `Queued for the owner's Confirm: ${String(reply.label)}. Nothing was stopped. Do not retry.`;
87
+ }
88
+ export async function toolPrsList(ctx, repo) {
89
+ const envelope = JSON.parse(await runAgents(prsListArgv(ctx.project, repo)));
90
+ const lines = [];
91
+ for (const r of envelope.repositories) {
92
+ if (r.error) {
93
+ lines.push(`${r.slug}: could not be read (${r.error})`);
94
+ continue;
95
+ }
96
+ for (const pr of r.pullRequests)
97
+ lines.push(`${r.slug}#${pr.number}${pr.isDraft ? ' [draft]' : ''} ${pr.title}`);
98
+ }
99
+ return lines.length ? lines.join('\n') : `No open PRs for ${ctx.project}.`;
100
+ }
101
+ async function readPr(ctx, repo, number) {
102
+ const envelope = JSON.parse(await runAgents(prReadArgv(ctx.project, repo, number)));
103
+ const pr = envelope.repositories.flatMap((r) => r.pullRequests).find((p) => p.number === number);
104
+ if (!pr)
105
+ throw new LeadToolError(`${repo}#${number} is not an open PR of ${ctx.project}.`);
106
+ return pr;
107
+ }
108
+ async function failingRunIds(ctx, repo, sha) {
109
+ const report = JSON.parse(await runAgents(prFailureArgv(ctx.project, repo, sha)));
110
+ if (report.error)
111
+ throw new LeadToolError(`Could not read the failing checks: ${report.error}`);
112
+ return [...new Set(report.checks.flatMap((c) => (c.runId === null ? [] : [c.runId])))];
113
+ }
114
+ const PR_LABEL = { merge: 'Merge', comment: 'Comment on', ready: 'Mark ready', rerun: 'Re-run failed CI of', close: 'Close' };
115
+ export async function toolPrAct(ctx, verb, opts) {
116
+ const repo = assertRepo(opts.repo);
117
+ const number = assertPrNumber(opts.number);
118
+ if (opts.body !== undefined && verb !== 'comment')
119
+ throw new LeadToolError('--body applies only to prs comment.');
120
+ if (opts.runId !== undefined && verb !== 'rerun')
121
+ throw new LeadToolError('--run-id applies only to prs rerun.');
122
+ if (verb === 'comment')
123
+ assertTask(opts.body ?? '');
124
+ const pr = await readPr(ctx, repo, number);
125
+ const sha = opts.sha ?? (verb === 'merge' || verb === 'rerun' ? pr.headSha : undefined);
126
+ if ((verb === 'merge' || verb === 'rerun') && !sha)
127
+ throw new LeadToolError(`${repo}#${number} has no head commit to pin; pass --sha.`);
128
+ let runId;
129
+ if (verb === 'rerun') {
130
+ const runs = await failingRunIds(ctx, repo, sha);
131
+ runId = opts.runId !== undefined ? assertPrNumber(opts.runId) : runs.length === 1 ? runs[0] : undefined;
132
+ if (runId === undefined) {
133
+ throw new LeadToolError(runs.length === 0
134
+ ? `${repo}#${number} has no failing GitHub Actions run at ${sha.slice(0, 7)}.`
135
+ : `${repo}#${number} has ${runs.length} failing runs (${runs.join(', ')}); pass --run-id <id>.`);
136
+ }
137
+ if (!runs.includes(runId))
138
+ throw new LeadToolError(`Run ${runId} is not a failing run of ${repo}#${number}.`);
139
+ }
140
+ const argv = prArgv(ctx.project, verb, { repo, number, sha: verb === 'rerun' ? undefined : sha, body: opts.body, runId });
141
+ return hold(ctx, {
142
+ action: 'pr',
143
+ argv,
144
+ label: `${PR_LABEL[verb]} ${repo}#${number} “${pr.title}”`,
145
+ detail: verb === 'comment' ? argv[argv.indexOf('--body') + 1] : pr.title,
146
+ });
86
147
  }
87
148
  export async function toolLinearTasks(ctx, status, limit) {
88
149
  const raw = JSON.parse(await runLinear(linearTasksArgv(ctx.def, status, limit)));
@@ -13,4 +13,4 @@ export declare function hideLeadInSessionEnvelope<E extends {
13
13
  }>(event: E, hostSessionIds: ReadonlySet<string>): E;
14
14
  export declare function hideLeadInFeedEnvelope<E extends {
15
15
  type: string;
16
- }>(event: E, hostSessionIds: ReadonlySet<string>): E;
16
+ }>(event: E, hostSessionIds: ReadonlySet<string>, hidden?: Set<string>): E;