pi-harness-delegate 0.6.1 → 0.7.0

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.
@@ -14,1087 +14,36 @@
14
14
  * Legacy: { claudeDelegate: {...} } is auto-migrated.
15
15
  */
16
16
 
17
- import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
18
- import { basename, join } from 'node:path';
19
17
  import { type ExtensionAPI, type ExtensionContext, getMarkdownTheme } from '@earendil-works/pi-coding-agent';
20
- import {
21
- Container,
22
- Key,
23
- Markdown,
24
- matchesKey,
25
- type OverlayHandle,
26
- type SelectItem,
27
- SelectList,
28
- Text,
29
- truncateToWidth,
30
- } from '@earendil-works/pi-tui';
18
+ import { Container, Markdown, type OverlayHandle, Text } from '@earendil-works/pi-tui';
31
19
  import { Type } from 'typebox';
32
- import { acpView, runAcpHarness } from './acp-runner.ts';
33
- import {
34
- aggregateSpend,
35
- buildFanoutReport,
36
- buildReportContent,
37
- buildTranscript,
38
- buildVerifyResult,
39
- collectActivityLog,
40
- type FanoutRunSummary,
41
- formatMetrics,
42
- formatSpend,
43
- formatToolUse,
44
- orderFanoutResults,
45
- parseTranscriptMeta,
46
- pruneOutputs,
47
- resolveVerifyPlan,
48
- safeSegmentName,
49
- skipVerifyResult,
50
- ToolCallIndex,
51
- type VerifyResult,
52
- } from './activity.ts';
53
- import {
54
- isFanoutSpec,
55
- parseDelegateCommand,
56
- resolveDefaults,
57
- resolveHarnessFilter,
58
- resolveHarnessList,
59
- } from './command.ts';
60
- import { acquireSlot, activeCount } from './concurrency.ts';
20
+ import { formatMetrics, formatToolUse, ToolCallIndex } from './activity.ts';
21
+ import { isFanoutSpec, parseDelegateCommand, resolveDefaults, resolveHarnessFilter } from './command.ts';
22
+ import { loadConfig } from './config.ts';
61
23
  import {
62
- buildConfigReport,
63
- type DelegateConfig,
64
- describeConfigSource,
65
- getMaxConcurrent,
66
- outputsDir as getOutputsDir,
67
- legacyOutputsDir,
68
- loadConfig,
69
- loadConfigWithSource,
70
- resolveModelForHarness,
71
- resolveTransport,
72
- writeDelegateConfig,
73
- } from './config.ts';
74
- import {
75
- ALIASES,
76
- detectAll,
77
- getHarness,
78
- HARNESS_NAMES,
79
- isKnownHarness,
80
- isNativeDangerPermission,
81
- resolveHarnessName,
82
- } from './harnesses/registry.ts';
83
- import type { ActivityEvent, NormalizedPermission } from './harnesses/types.ts';
24
+ type DelegateToolParams,
25
+ delegate,
26
+ formatCost,
27
+ injectReport,
28
+ isProjectTrusted,
29
+ runDelegateForTool,
30
+ summarize,
31
+ type ToolProgressUpdate,
32
+ takePendingReport,
33
+ } from './engine.ts';
34
+ import { closeWhenMounted, type RunUiState, runFanoutCommand, runFanoutTool } from './fanout.ts';
35
+ import { ALIASES, HARNESS_NAMES, isKnownHarness, resolveHarnessName } from './harnesses/registry.ts';
36
+ import type { ActivityEvent } from './harnesses/types.ts';
84
37
  import { delegationHint, stripMarker } from './hint.ts';
85
- import { NotifyBatcher } from './notify.ts';
38
+ import { showHistory } from './history.ts';
86
39
  import { type FeedEntry, progressWindow } from './progress.ts';
87
- import { formatFanoutChip, multiProgressWindow, type RunRow } from './progress-multi.ts';
88
- import { runHarness } from './runner.ts';
89
- import {
90
- type DelegateTemplate,
91
- describeSkippedProjectTemplates,
92
- loadTemplates,
93
- projectTemplatePresence,
94
- resolveNativePermission,
95
- } from './templates.ts';
40
+ import { initConfig, showConfig, showModes, showStatus } from './subcommands.ts';
41
+ import { type DelegateTemplate, loadTemplates } from './templates.ts';
96
42
  import { mapClaudeUsage } from './usage.ts';
97
-
98
- /** Render a possibly-unknown cost — `null` means the harness didn't report one, not a measured $0. */
99
- function formatCost(cost: number | null): string {
100
- return cost !== null ? `$${cost.toFixed(3)}` : '$—';
101
- }
102
-
103
- interface DelegateOptions {
104
- harness?: string;
105
- task: string;
106
- mode?: string;
107
- scope?: string;
108
- model?: string;
109
- maxBudgetUsd?: number;
110
- allowDangerous?: boolean;
111
- sessionId?: string;
112
- pr?: string;
113
- /**
114
- * Host-run verification command override — takes precedence over the template's `verify`
115
- * frontmatter. Internal engine option only, not exposed on the `delegate` tool's schema — see
116
- * the trust-model note on `runVerify` below for why.
117
- */
118
- verify?: string;
119
- onStream?: (text: string) => void;
120
- onActivity?: (ev: ActivityEvent) => void;
121
- signal?: AbortSignal;
122
- /** Queue for a concurrency slot instead of failing fast when at capacity — fan-out only, see
123
- * `acquireSlot` in concurrency.ts. Single-harness runs leave this false (the default). */
124
- waitForSlot?: boolean;
125
- /** Called once this run has acquired its concurrency slot and is about to actually start —
126
- * fan-out uses it to flip a row from "queued" to "running". */
127
- onAcquired?: () => void;
128
- }
129
-
130
- /** Verify commands run on the host after the harness exits — bounded independent of harness timeoutMs. */
131
- const VERIFY_TIMEOUT_MS = 5 * 60_000;
132
- /** How long the fan-out overlay lingers on the finished board after the last run resolves, so a
133
- * user who looked away still catches the final state instead of it clearing instantly. */
134
- const FANOUT_LINGER_MS = 3000;
135
-
136
- /**
137
- * Run a verify command in-process on the host (never delegated to the harness). Report-only —
138
- * callers must not let this flip a run's `isError`.
139
- *
140
- * Trust model: a verify command can only come from two places — on-disk template frontmatter
141
- * (project-local templates are already gated by `isProjectTrusted(ctx)` — pi's own trust store,
142
- * never anything inside the project itself) or a human typing `/delegate --verify=<cmd>` at the
143
- * CLI. It is deliberately **not** a `delegate` tool parameter: a tool
144
- * param is set by the model, whose context includes repo content and delegated-harness output —
145
- * both attacker-influenceable, so a model-settable `verify` would be a prompt-injection ->
146
- * arbitrary-host-command path (e.g. injected text in a reviewed file steering the parent agent
147
- * into `delegate({verify: "curl ... | sh"})`). A model that wants verification selects a
148
- * template that declares one instead.
149
- *
150
- * `resolveVerifyPlan` additionally never lets a verify command run on a `readonly` permission —
151
- * `readonly` guarantees no execution/modification, and a verify command riding along on one
152
- * would silently break that guarantee (a permission-tier bypass), independent of how trusted its
153
- * source is. See the matching Conventions entry in AGENTS.md.
154
- *
155
- * Runs via `sh -c` (not a fixed binary+argv) so compound commands like `bun test && bun run
156
- * lint` work — safe only because of the source/permission restrictions above, not because the
157
- * command itself is sanitized.
158
- */
159
- async function runVerify(pi: ExtensionAPI, cwd: string, command: string): Promise<VerifyResult> {
160
- try {
161
- const res = await pi.exec('sh', ['-c', command], { cwd, timeout: VERIFY_TIMEOUT_MS });
162
- return buildVerifyResult(command, res.code, `${res.stdout}${res.stderr}`);
163
- } catch (err) {
164
- return buildVerifyResult(command, 1, err instanceof Error ? err.message : String(err));
165
- }
166
- }
167
-
168
- async function closeWhenMounted(getClose: () => (() => void) | null, capMs: number): Promise<void> {
169
- const close = getClose();
170
- if (close) {
171
- close();
172
- return;
173
- }
174
- await new Promise<void>(resolve => {
175
- const start = Date.now();
176
- const timer = setInterval(() => {
177
- const fn = getClose();
178
- if (fn || Date.now() - start > capMs) {
179
- clearInterval(timer);
180
- fn?.();
181
- resolve();
182
- }
183
- }, 20);
184
- });
185
- }
186
-
187
- function outputsDirFor(harness: string): string {
188
- return getOutputsDir(harness);
189
- }
190
-
191
- /**
192
- * Whether pi's own trust store (`ctx.isProjectTrusted()`, backed by `~/.pi/agent/trust.json`,
193
- * outside any project) considers `ctx.cwd` trusted. This is the sole source of truth for whether
194
- * project-local delegate templates load — see the trust-tier comment on `loadTemplates`. Fails
195
- * closed (untrusted) if the host is old enough not to expose the method, or if it throws.
196
- */
197
- /**
198
- * Warn once per project when trusted-only content was silently skipped.
199
- *
200
- * Before 0.6.0 a committed `.pi/trusted` file (or `PI_TRUSTED=1`) granted trust; both were removed as
201
- * a security fix. A user who relied on either loses their project-local templates on upgrade with no
202
- * visible signal — an override shares its name with the builtin it replaces, so the run just uses the
203
- * builtin and looks fine. `/delegate status` reports trust state, but nobody runs it unless something
204
- * already looks wrong, so this fires on an actual delegation instead — and only when the project
205
- * demonstrably has the content being skipped, so it never nags anyone unaffected.
206
- */
207
- const warnedUntrustedProjects = new Set<string>();
208
-
209
- function warnIfProjectTemplatesSkipped(ctx: ExtensionContext, trusted: boolean): void {
210
- if (trusted || warnedUntrustedProjects.has(ctx.cwd)) return;
211
- const lines = describeSkippedProjectTemplates(projectTemplatePresence(ctx.cwd));
212
- if (lines.length === 0) return;
213
- warnedUntrustedProjects.add(ctx.cwd);
214
- const msg = lines.join('\n');
215
- if (ctx.hasUI) ctx.ui.notify?.(msg, 'warning');
216
- else process.stderr.write(`${msg}\n`);
217
- }
218
-
219
- function isProjectTrusted(ctx: ExtensionContext): boolean {
220
- try {
221
- return typeof ctx.isProjectTrusted === 'function' && ctx.isProjectTrusted() === true;
222
- } catch {
223
- return false;
224
- }
225
- }
226
-
227
- function formatTemplateRow(t: DelegateTemplate): string {
228
- const parts = [
229
- t.name,
230
- `[${t.permission}]`,
231
- t.model ? `model=${t.model}` : '',
232
- t.defaultTask ? '↳ default task' : '',
233
- t.harness ? `(${t.harness})` : '',
234
- ];
235
- return `${parts.filter(Boolean).join(' ')} — ${t.description}`;
236
- }
237
-
238
- async function showModes(ctx: ExtensionContext, harnessFilter?: string): Promise<void> {
239
- const all = new Map<string, DelegateTemplate>();
240
- const trusted = isProjectTrusted(ctx);
241
- // collect from all harnesses if no filter
242
- if (harnessFilter) {
243
- for (const [k, v] of loadTemplates(ctx.cwd, harnessFilter, trusted)) all.set(k, v);
244
- } else {
245
- for (const h of [...HARNESS_NAMES, 'shared']) {
246
- for (const [k, v] of loadTemplates(ctx.cwd, h, trusted)) if (!all.has(k)) all.set(k, v);
247
- }
248
- // also load without harness param
249
- for (const [k, v] of loadTemplates(ctx.cwd, undefined, trusted)) if (!all.has(k)) all.set(k, v);
250
- }
251
- const rows = [...all.values()].map(formatTemplateRow);
252
- if (!ctx.hasUI) {
253
- process.stdout.write(`${rows.join('\n')}\n`);
254
- return;
255
- }
256
- await ctx.ui.custom((tui, theme, _kb, done) => {
257
- let offset = 0;
258
- const height = 12;
259
- return {
260
- render(width: number): string[] {
261
- const header = theme.fg(
262
- 'accent',
263
- `delegate — modes${harnessFilter ? ` (${harnessFilter})` : ''} (↑↓ scroll · any key to close)`,
264
- );
265
- const visible = rows.slice(offset, offset + height);
266
- return [header, ...visible.map(l => theme.fg('muted', truncateToWidth(l, width)))];
267
- },
268
- handleInput(data: string): void {
269
- if (matchesKey(data, Key.up) && offset > 0) {
270
- offset--;
271
- tui.requestRender();
272
- } else if (matchesKey(data, Key.down) && offset < rows.length - 1) {
273
- offset++;
274
- tui.requestRender();
275
- } else {
276
- done(undefined);
277
- }
278
- },
279
- invalidate() {},
280
- };
281
- });
282
- }
283
-
284
- interface HistoryEntry {
285
- file: string;
286
- mode: string;
287
- harness: string;
288
- cost: number | null;
289
- sessionId: string | null;
290
- mtime: number;
291
- }
292
-
293
- function readHistory(dir: string, harness: string): HistoryEntry[] {
294
- try {
295
- return readdirSync(dir)
296
- .filter(f => f.endsWith('.md') && !f.includes('-partial'))
297
- .map(f => {
298
- const file = join(dir, f);
299
- let mode = 'delegate';
300
- let cost: number | null = null;
301
- let sessionId: string | null = null;
302
- try {
303
- const meta = parseTranscriptMeta(readFileSync(file, 'utf8').slice(0, 2000));
304
- mode = meta.mode;
305
- cost = meta.cost;
306
- sessionId = meta.sessionId;
307
- } catch (_e) {
308
- void _e;
309
- }
310
- return {
311
- file,
312
- mode,
313
- harness,
314
- cost,
315
- sessionId,
316
- mtime: statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0,
317
- };
318
- })
319
- .sort((a, b) => b.mtime - a.mtime);
320
- } catch {
321
- return [];
322
- }
323
- }
324
-
325
- function readAllHistory(): HistoryEntry[] {
326
- const entries: HistoryEntry[] = [];
327
- // new partitioned dir
328
- for (const h of HARNESS_NAMES) {
329
- entries.push(...readHistory(getOutputsDir(h), h));
330
- }
331
- // also legacy dir for migration display
332
- try {
333
- const legacy = readdirSync(legacyOutputsDir()).filter(f => f.endsWith('.md') && !f.includes('-partial'));
334
- for (const f of legacy) {
335
- const file = join(legacyOutputsDir(), f);
336
- let mode = 'delegate';
337
- let cost: number | null = null;
338
- let sessionId: string | null = null;
339
- try {
340
- const meta = parseTranscriptMeta(readFileSync(file, 'utf8').slice(0, 2000));
341
- mode = meta.mode;
342
- cost = meta.cost;
343
- sessionId = meta.sessionId;
344
- } catch (_e) {
345
- void _e;
346
- }
347
- entries.push({
348
- file,
349
- mode,
350
- harness: 'claude',
351
- cost,
352
- sessionId,
353
- mtime: statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? 0,
354
- });
355
- }
356
- } catch (_e) {
357
- void _e;
358
- }
359
- return entries.sort((a, b) => b.mtime - a.mtime);
360
- }
361
-
362
- async function viewTranscript(ctx: ExtensionContext, entry: HistoryEntry): Promise<void> {
363
- if (!ctx.hasUI) {
364
- process.stdout.write(readFileSync(entry.file, 'utf8'));
365
- return;
366
- }
367
- await ctx.ui.custom((tui, theme, _kb, done) => {
368
- const lines = readFileSync(entry.file, 'utf8').split('\n');
369
- let offset = 0;
370
- const height = 12;
371
- return {
372
- render(width: number): string[] {
373
- const resume = entry.sessionId ? ` · r resume` : '';
374
- const header = theme.fg('accent', `${basename(entry.file)} (↑↓ scroll${resume} · esc close)`);
375
- const visible = lines.slice(offset, offset + height);
376
- return [header, ...visible.map(l => theme.fg('muted', truncateToWidth(l, width)))];
377
- },
378
- handleInput(data: string): void {
379
- if (matchesKey(data, Key.down) && offset < lines.length - 1) {
380
- offset++;
381
- tui.requestRender();
382
- } else if (matchesKey(data, Key.up) && offset > 0) {
383
- offset--;
384
- tui.requestRender();
385
- } else if (matchesKey(data, Key.escape)) {
386
- done(undefined);
387
- } else if (entry.sessionId && data === 'r') {
388
- ctx.ui.notify?.(`resume with: /delegate --resume=${entry.sessionId} <prompt>`, 'info');
389
- }
390
- },
391
- invalidate() {},
392
- };
393
- });
394
- }
395
-
396
- function saveOutput(harness: string, mode: string, text: string): string {
397
- const dir = outputsDirFor(harness);
398
- mkdirSync(dir, { recursive: true });
399
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
400
- const file = join(dir, `${stamp}-${safeSegmentName(mode)}.md`);
401
- writeFileSync(file, text, 'utf8');
402
- return file;
403
- }
404
-
405
- async function showHistory(ctx: ExtensionContext, harnessFilter?: string): Promise<void> {
406
- const entries = harnessFilter ? readAllHistory().filter(e => e.harness === harnessFilter) : readAllHistory();
407
- if (entries.length === 0) {
408
- const msg = harnessFilter
409
- ? `No transcripts yet for ${harnessFilter} — run /delegate ${harnessFilter} <mode> <prompt> first`
410
- : 'No transcripts yet — run /delegate <harness> <mode> <prompt> first';
411
- if (!ctx.hasUI) process.stdout.write(`${msg}\n`);
412
- else ctx.ui.notify?.(msg, 'info');
413
- return;
414
- }
415
- if (!ctx.hasUI) {
416
- if (harnessFilter) process.stdout.write(`delegate — history (${harnessFilter})\n`);
417
- for (const e of entries)
418
- process.stdout.write(`${e.harness} ${e.mode} · ${formatCost(e.cost)} · ${e.sessionId ?? '-'}\n`);
419
- return;
420
- }
421
- const entry = await ctx.ui.custom((tui, theme, _kb, done) => {
422
- const items: SelectItem[] = entries.map(e => ({
423
- value: e.file,
424
- label: `${e.harness} ${e.mode} · ${formatCost(e.cost)} · ${new Date(e.mtime).toISOString().slice(0, 16)}`,
425
- description: e.sessionId ? `session ${e.sessionId.slice(0, 8)}…` : undefined,
426
- }));
427
- const list = new SelectList(items, Math.min(items.length, 10), {
428
- selectedPrefix: (s: string) => theme.fg('accent', s),
429
- selectedText: (s: string) => theme.fg('accent', s),
430
- description: (s: string) => theme.fg('dim', s),
431
- scrollInfo: (s: string) => theme.fg('dim', s),
432
- noMatch: (s: string) => theme.fg('warning', s),
433
- });
434
- list.onSelect = item => done(item.value);
435
- list.onCancel = () => done(undefined);
436
- return {
437
- render: (w: number) => {
438
- const rows = list.render(w);
439
- return harnessFilter ? [theme.fg('accent', `delegate — history (${harnessFilter})`), ...rows] : rows;
440
- },
441
- invalidate: () => list.invalidate(),
442
- handleInput: (data: string) => {
443
- list.handleInput(data);
444
- tui.requestRender();
445
- },
446
- };
447
- });
448
- if (entry) {
449
- const chosen = entries.find(e => e.file === entry);
450
- if (chosen) await viewTranscript(ctx, chosen);
451
- }
452
- }
453
-
454
- async function showStatus(ctx: ExtensionContext, harnessFilter?: string): Promise<void> {
455
- const { config: cfg, source } = loadConfigWithSource();
456
- const detection = await detectAll();
457
- const trusted = isProjectTrusted(ctx);
458
- const allHarnesses = harnessFilter ? [harnessFilter].filter(h => isKnownHarness(h)) : HARNESS_NAMES;
459
- const lines: string[] = [];
460
- lines.push(`delegate — status${harnessFilter ? ` (${harnessFilter})` : ''}`);
461
- lines.push(...describeConfigSource(source));
462
- lines.push(`defaultHarness: ${cfg.defaultHarness} · defaultMode: ${cfg.defaultMode} · model: ${cfg.model ?? '—'}`);
463
- lines.push(
464
- `maxConcurrent: ${typeof cfg.maxConcurrent === 'number' ? cfg.maxConcurrent : JSON.stringify(cfg.maxConcurrent)} · maxTranscripts: ${cfg.maxTranscripts}`,
465
- );
466
- lines.push(
467
- trusted
468
- ? 'project trust: trusted — project-local templates (.pi/delegate/templates/) are loaded'
469
- : "project trust: untrusted — project-local templates skipped (trust this project via pi's trust prompt, or set defaultProjectTrust, to load them)",
470
- );
471
- lines.push('');
472
- lines.push('harness binary ok version outputs templates active');
473
- lines.push('─'.repeat(78));
474
- for (const h of harnessFilter ? allHarnesses : HARNESS_NAMES) {
475
- const det = detection[h] ?? { ok: false };
476
- const harness = getHarness(h);
477
- const bin = harness?.binary ?? h;
478
- const ver = det.version ? det.version.slice(0, 18) : det.hint ? '—' : '—';
479
- const ok = det.ok ? '✓' : '✗';
480
- let outputs = 0;
481
- try {
482
- outputs = readdirSync(getOutputsDir(h)).filter(f => f.endsWith('.md')).length;
483
- } catch {}
484
- let templates = 0;
485
- try {
486
- templates = loadTemplates(ctx.cwd, h, trusted).size;
487
- } catch {}
488
- // cross-process count via the file registry, combined with the in-process counter as a fallback
489
- const active = activeCount(h);
490
- const cap = getMaxConcurrent(cfg, h);
491
- const activeCol = `${active}/${cap > 0 ? cap : '∞'}`;
492
- const hint = !det.ok && det.hint ? ` ← ${det.hint}` : '';
493
- lines.push(
494
- `${h.padEnd(20)} ${bin.padEnd(8)} ${ok.padEnd(3)} ${ver.padEnd(20)} ${String(outputs).padEnd(8)} ${String(templates).padEnd(10)} ${activeCol}${hint}`,
495
- );
496
- }
497
- const historyEntries = harnessFilter ? readAllHistory().filter(e => e.harness === harnessFilter) : readAllHistory();
498
- const spend = aggregateSpend(historyEntries.map(e => ({ harness: e.harness, cost: e.cost })));
499
- lines.push('');
500
- lines.push('spend:');
501
- for (const h of harnessFilter ? allHarnesses : HARNESS_NAMES) {
502
- const s = spend.byHarness[h];
503
- lines.push(` ${h}: ${s ? formatSpend(s) : '$0.000 over 0 run(s)'}`);
504
- }
505
- if (!harnessFilter) lines.push(` total: ${formatSpend(spend.total)}`);
506
- if (!harnessFilter) {
507
- const globalCap = getMaxConcurrent(cfg);
508
- lines.push('');
509
- lines.push(
510
- `global active: ${activeCount()}/${globalCap > 0 ? globalCap : '∞'} · aliases: ${
511
- Object.entries(ALIASES)
512
- .map(([k, v]) => `${k}→${v}`)
513
- .join(', ') || '—'
514
- }`,
515
- );
516
- lines.push(`outputs dir: ${getOutputsDir()} (plus ${legacyOutputsDir()} legacy)`);
517
- }
518
- if (!ctx.hasUI) {
519
- process.stdout.write(`${lines.join('\n')}\n`);
520
- return;
521
- }
522
- await ctx.ui.custom((tui, theme, _kb, done) => {
523
- let offset = 0;
524
- const height = 14;
525
- return {
526
- render(width: number): string[] {
527
- const header = theme.fg(
528
- 'accent',
529
- `delegate status${harnessFilter ? ` — ${harnessFilter}` : ''} (↑↓ scroll · any key to close)`,
530
- );
531
- const visible = lines.slice(offset, offset + height);
532
- return [header, ...visible.map(l => theme.fg('muted', truncateToWidth(l, width)))];
533
- },
534
- handleInput(data: string): void {
535
- if (matchesKey(data, Key.up) && offset > 0) {
536
- offset--;
537
- tui.requestRender();
538
- } else if (matchesKey(data, Key.down) && offset < lines.length - 1) {
539
- offset++;
540
- tui.requestRender();
541
- } else done(undefined);
542
- },
543
- invalidate() {},
544
- };
545
- });
546
- }
547
-
548
- /**
549
- * `/delegate config` — the discoverability gap `/delegate status`'s provenance line only hints at:
550
- * shows exactly what was read from `settings.json` (or why it wasn't) plus the effective config
551
- * with defaults filled in, formatted as a paste-ready JSON block under the `delegate` key. Print-
552
- * only — writing is a separate, explicit action (`/delegate config init`, below), never triggered
553
- * from this default view.
554
- */
555
- async function showConfig(ctx: ExtensionContext): Promise<void> {
556
- const result = loadConfigWithSource();
557
- const lines = ['delegate — config', '', ...buildConfigReport(result)];
558
- if (!ctx.hasUI) {
559
- process.stdout.write(`${lines.join('\n')}\n`);
560
- return;
561
- }
562
- await ctx.ui.custom((tui, theme, _kb, done) => {
563
- let offset = 0;
564
- const height = 20;
565
- return {
566
- render(width: number): string[] {
567
- const header = theme.fg('accent', `delegate config — ${result.source.file} (↑↓ scroll · any key to close)`);
568
- const visible = lines.slice(offset, offset + height);
569
- return [header, ...visible.map(l => theme.fg('muted', truncateToWidth(l, width)))];
570
- },
571
- handleInput(data: string): void {
572
- if (matchesKey(data, Key.up) && offset > 0) {
573
- offset--;
574
- tui.requestRender();
575
- } else if (matchesKey(data, Key.down) && offset < lines.length - 1) {
576
- offset++;
577
- tui.requestRender();
578
- } else done(undefined);
579
- },
580
- invalidate() {},
581
- };
582
- });
583
- }
584
-
585
- /**
586
- * `/delegate config init` — the one place this extension ever writes to `settings.json`, and only
587
- * because a human explicitly typed this subcommand. Writes the current effective config (defaults
588
- * merged with whatever was already on disk) into the `delegate` key via `writeDelegateConfig()`
589
- * (read-modify-write, atomic, refuses on an unparseable file rather than clobbering it). This is
590
- * also the practical fix for the legacy-`claudeDelegate`-only gap `describeConfigSource` warns
591
- * about: writing an explicit `delegate` key (with the correctly-resolved values already folded
592
- * in — the legacy migration already ran before this point) makes it win from then on, without
593
- * this command ever touching or deleting the old `claudeDelegate` key itself.
594
- */
595
- async function initConfig(ctx: ExtensionContext): Promise<void> {
596
- const result = loadConfigWithSource();
597
- const write = writeDelegateConfig(result.config);
598
- const msg = write.ok ? `✓ ${write.message}` : `✗ ${write.message}`;
599
- if (!ctx.hasUI) process.stdout.write(`${msg}\n`);
600
- else ctx.ui.notify?.(msg, write.ok ? 'info' : 'warning');
601
- }
602
-
603
- function buildPrompt(
604
- template: DelegateTemplate,
605
- task: string,
606
- scopeText: string | null,
607
- cwd: string,
608
- harness: string,
609
- ): string {
610
- let prompt = [
611
- `You are being delegated a subtask by the pi coding agent.`,
612
- `Working directory: ${cwd}`,
613
- `Harness: ${harness}`,
614
- `Mode: ${template.name}`,
615
- ``,
616
- template.prompt,
617
- ].join('\n');
618
- prompt += `\n\n# Task\n${task}`;
619
- if (scopeText) prompt += `\n\n# Scope\n${scopeText}`;
620
- if (template.skill) prompt += `\n\nUse the "${template.skill}" skill.`;
621
- return prompt;
622
- }
623
-
624
- async function delegate(
625
- pi: ExtensionAPI,
626
- ctx: ExtensionContext,
627
- opts: DelegateOptions,
628
- ): Promise<{
629
- content: string;
630
- details: Record<string, unknown>;
631
- result: import('./harnesses/types.ts').StreamedResult & { streamedText: string; harness: string };
632
- activityLog: string[];
633
- verify?: VerifyResult;
634
- }> {
635
- const config = loadConfig();
636
- const harnessName = opts.harness ?? config.defaultHarness ?? 'claude';
637
- const harness = getHarness(harnessName);
638
- if (!harness)
639
- throw new Error(
640
- `unknown harness "${harnessName}". Available: ${HARNESS_NAMES.join(', ')} (aliases: ${Object.keys(ALIASES).join(', ')})`,
641
- );
642
- const projectTrusted = isProjectTrusted(ctx);
643
- warnIfProjectTemplatesSkipped(ctx, projectTrusted);
644
- const templates = loadTemplates(ctx.cwd, harnessName, projectTrusted);
645
- const mode = opts.mode || config.defaultMode;
646
- const template = templates.get(mode);
647
- if (!template)
648
- throw new Error(
649
- `unknown delegate mode "${mode}" for harness "${harnessName}". Available: ${[...templates.keys()].sort().join(', ')}`,
650
- );
651
- const task = opts.task || template.defaultTask;
652
- if (!task) throw new Error(`delegate mode "${mode}" requires a task`);
653
-
654
- // Fail-fast, before acquireSlot()/spawn — configuring e.g. transport:'acp' for a harness with no
655
- // ACP surface (or 'stdout' for an ACP-only one) should error immediately with a clear message,
656
- // not spawn the process and surface a cryptic native failure. See config.ts's resolveTransport.
657
- const transport = resolveTransport(config, harnessName, harness);
658
-
659
- // concurrency guard — see concurrency.ts. Single runs (waitForSlot unset) fail fast at capacity,
660
- // exactly as before; fan-out passes waitForSlot:true to queue instead.
661
- const release = await acquireSlot({
662
- harness: harnessName,
663
- mode,
664
- config,
665
- wait: opts.waitForSlot ?? false,
666
- signal: opts.signal,
667
- });
668
- opts.onAcquired?.();
669
-
670
- let scopeText: string | null = opts.scope ?? null;
671
- if (opts.scope === 'diff') {
672
- const diff = await pi.exec('git', ['diff', 'HEAD'], { cwd: ctx.cwd });
673
- scopeText = diff.stdout
674
- ? `Current git diff (working tree vs HEAD):\n${diff.stdout}`
675
- : 'No git diff vs HEAD (working tree clean).';
676
- } else if (opts.scope === 'pr' || opts.pr) {
677
- const target = opts.pr ?? '';
678
- const pr = await pi.exec('gh', target ? ['pr', 'diff', target] : ['pr', 'diff'], { cwd: ctx.cwd });
679
- scopeText = pr.stdout
680
- ? `Pull request diff (${target || 'current branch'}):\n${pr.stdout}`
681
- : `Could not resolve the PR diff${pr.stderr ? ` — ${pr.stderr.trim().slice(0, 300)}` : ''}.`;
682
- }
683
-
684
- // permission: normalized, danger requires explicit per-call allowDangerous:true
685
- let permission: NormalizedPermission = template.permission;
686
- const nativePerm = template.nativePermission;
687
- const isNativeDanger = isNativeDangerPermission(harness, nativePerm);
688
- if (template.permission === 'danger' || isNativeDanger) {
689
- if (opts.allowDangerous !== true) {
690
- throw new Error(
691
- `template "${mode}" requires danger permission — pass allowDangerous:true to run it (never a default)`,
692
- );
693
- }
694
- permission = 'danger';
695
- } else if (opts.allowDangerous === true) {
696
- // explicit per-call escalation for any template
697
- permission = 'danger';
698
- }
699
- const permissionForDisplay = nativePerm ?? permission;
700
- // Dropped when an explicit escalation moved us off the template's own tier — see
701
- // resolveNativePermission(). Applies to both transports.
702
- const nativePermissionForRun = resolveNativePermission(template.permission, permission, nativePerm);
703
-
704
- const model = resolveModelForHarness(config, harnessName, opts.model, template.model);
705
- const prompt = buildPrompt(template, task, scopeText, ctx.cwd, harnessName);
706
-
707
- const activityEvents: ActivityEvent[] = [];
708
- let streamedFull = '';
709
- let result: import('./runner.ts').HarnessResult;
710
- try {
711
- const baseRunOpts = {
712
- harness,
713
- prompt,
714
- cwd: ctx.cwd,
715
- permission,
716
- model,
717
- maxBudgetUsd:
718
- opts.maxBudgetUsd ??
719
- template.maxBudgetUsd ??
720
- config.maxBudgetUsd ??
721
- config.harnesses[harnessName]?.maxBudgetUsd,
722
- signal: opts.signal,
723
- timeoutMs: config.harnesses[harnessName]?.timeoutMs ?? config.timeoutMs,
724
- resumeSessionId: opts.sessionId,
725
- onStream: (t: string) => {
726
- streamedFull += t;
727
- opts.onStream?.(t);
728
- },
729
- onActivity: (ev: ActivityEvent) => {
730
- activityEvents.push(ev);
731
- opts.onActivity?.(ev);
732
- },
733
- nativePermission: nativePermissionForRun,
734
- };
735
- result =
736
- transport === 'acp'
737
- ? await runAcpHarness({ ...baseRunOpts, harness: acpView(harness) })
738
- : await runHarness(baseRunOpts);
739
- } catch (err) {
740
- release();
741
- if (streamedFull.length > 0) {
742
- try {
743
- saveOutput(
744
- harnessName,
745
- `${mode}-partial`,
746
- buildTranscript({
747
- harness: harnessName,
748
- mode: `${mode} (partial)`,
749
- permission: permission,
750
- nativePermission: nativePerm ?? undefined,
751
- model: model ?? null,
752
- cwd: ctx.cwd,
753
- sessionId: null,
754
- resumed: Boolean(opts.sessionId),
755
- numTurns: null,
756
- totalCostUsd: null,
757
- isError: true,
758
- stopReason: null,
759
- durationMs: null,
760
- usage: null,
761
- contextPercent: null,
762
- contextWindow: null,
763
- activityLog: collectActivityLog(activityEvents),
764
- output: streamedFull,
765
- }),
766
- );
767
- } catch (_e) {
768
- void _e;
769
- }
770
- }
771
- throw err;
772
- }
773
- release();
774
-
775
- if (result.isError && !result.result && !result.streamedText)
776
- throw new Error(`${harnessName} reported an error and produced no output`);
777
-
778
- const actualModel = result.model ?? model ?? null;
779
- const promptTokens =
780
- result.usage === null
781
- ? null
782
- : result.usage.inputTokens + result.usage.cacheCreationInputTokens + result.usage.cacheReadInputTokens;
783
- const contextPercent =
784
- promptTokens !== null && result.contextWindow ? (promptTokens / result.contextWindow) * 100 : null;
785
-
786
- // Host-run post-hoc verification — report-only evidence, never flips `result.isError`. Never
787
- // actually executes on a readonly permission (permission-tier bypass) — recorded as skipped
788
- // instead of silently dropped. See the trust-model note on runVerify().
789
- const verifyPlan = resolveVerifyPlan(opts.verify, template.verify, permission);
790
- const verify = verifyPlan
791
- ? verifyPlan.skip
792
- ? skipVerifyResult(verifyPlan.command, 'readonly run')
793
- : await runVerify(pi, ctx.cwd, verifyPlan.command)
794
- : undefined;
795
-
796
- const file = saveOutput(
797
- harnessName,
798
- mode,
799
- buildTranscript({
800
- harness: harnessName,
801
- mode: mode,
802
- permission: permission,
803
- nativePermission: nativePerm ?? undefined,
804
- model: actualModel,
805
- cwd: ctx.cwd,
806
- sessionId: result.sessionId,
807
- resumed: Boolean(opts.sessionId),
808
- numTurns: result.numTurns,
809
- totalCostUsd: result.totalCostUsd,
810
- isError: result.isError,
811
- stopReason: result.stopReason,
812
- durationMs: result.durationMs,
813
- usage: result.usage,
814
- contextPercent,
815
- contextWindow: result.contextWindow,
816
- activityLog: collectActivityLog(activityEvents),
817
- output: result.result || result.streamedText,
818
- verify,
819
- }),
820
- );
821
- pruneOutputs(outputsDirFor(harnessName), config.maxTranscripts);
822
- // also prune legacy if claude
823
- if (harnessName === 'claude') pruneOutputs(legacyOutputsDir(), config.maxTranscripts);
824
-
825
- return {
826
- content: result.result || result.streamedText || '(empty result)',
827
- details: {
828
- harness: harnessName,
829
- mode,
830
- permission,
831
- nativePermission: nativePerm ?? null,
832
- permissionMode: String(permissionForDisplay),
833
- model: actualModel,
834
- numTurns: result.numTurns,
835
- totalCostUsd: result.totalCostUsd,
836
- sessionId: result.sessionId,
837
- stopReason: result.stopReason,
838
- permissionDenials: result.permissionDenials,
839
- isError: result.isError,
840
- resumed: Boolean(opts.sessionId),
841
- file,
842
- durationMs: result.durationMs,
843
- ttftMs: result.ttftMs,
844
- contextWindow: result.contextWindow,
845
- contextPercent,
846
- promptTokens,
847
- usage: result.usage,
848
- verify,
849
- },
850
- result,
851
- activityLog: collectActivityLog(activityEvents),
852
- verify,
853
- };
854
- }
855
-
856
- function summarize(content: string, max = 30_000): { text: string; truncated: boolean } {
857
- if (content.length <= max) return { text: content, truncated: false };
858
- return { text: `${content.slice(0, max)}\n…[truncated — full output saved to file]`, truncated: true };
859
- }
860
-
861
- interface PendingReport {
862
- content: string;
863
- details: Record<string, unknown>;
864
- }
865
- let pendingReport: PendingReport | null = null;
866
- function injectReport(
867
- _ctx: ExtensionContext,
868
- opts: {
869
- harness: string;
870
- mode: string;
871
- metrics: string;
872
- body: string;
873
- file?: string;
874
- sessionId?: string;
875
- verify?: VerifyResult;
876
- },
877
- ): void {
878
- pendingReport = {
879
- content: buildReportContent({
880
- harness: opts.harness,
881
- mode: opts.mode,
882
- metrics: opts.metrics,
883
- body: opts.body,
884
- file: opts.file,
885
- sessionId: opts.sessionId,
886
- verify: opts.verify,
887
- }),
888
- details: {
889
- harness: opts.harness,
890
- mode: opts.mode,
891
- file: opts.file,
892
- sessionId: opts.sessionId,
893
- metrics: opts.metrics,
894
- },
895
- };
896
- }
897
-
898
- interface ToolProgressUpdate {
899
- content: { type: string; text: string }[];
900
- details: { progress: number };
901
- }
902
-
903
- /**
904
- * `delegate` tool params. Deliberately has no `verify` field — a tool param is model-controlled,
905
- * and the model's context (repo content, delegated-harness output) is attacker-influenceable, so
906
- * a model-settable verify command would be a prompt-injection -> arbitrary-host-command path.
907
- * Verify only comes from on-disk template frontmatter or a human-typed `/delegate --verify=`.
908
- */
909
- interface DelegateToolParams {
910
- harness?: string;
911
- task: string;
912
- mode?: string;
913
- scope?: string;
914
- model?: string;
915
- maxBudgetUsd?: number;
916
- allowDangerous?: boolean;
917
- sessionId?: string;
918
- pr?: string;
919
- }
920
-
921
- /** One `delegate()` call with the tool's live-feed progress reporting (`onUpdate`). Shared by the
922
- * single-harness tool path and the fan-out loop — `labelPrefix` tags fan-out feed lines by harness. */
923
- async function runDelegateForTool(
924
- pi: ExtensionAPI,
925
- ctx: ExtensionContext,
926
- config: DelegateConfig,
927
- callOpts: DelegateOptions,
928
- signal: AbortSignal | undefined,
929
- onUpdate: ((u: ToolProgressUpdate) => void) | undefined,
930
- labelPrefix: string,
931
- ): Promise<Awaited<ReturnType<typeof delegate>>> {
932
- const feed: string[] = [];
933
- const feedIndex = new ToolCallIndex();
934
- let liveTail = '';
935
- let thinkingChars = 0;
936
- let lastPushAt = 0;
937
- const THROTTLE_MS = 250;
938
- const pushFeed = () => {
939
- const now = Date.now();
940
- if (now - lastPushAt < THROTTLE_MS) return;
941
- lastPushAt = now;
942
- const lines: string[] = [...feed.slice(-6)];
943
- if (thinkingChars > 0)
944
- lines.push(config.inspectThinking ? `💭 thinking… (${thinkingChars} chars)` : '💭 thinking…');
945
- if (liveTail) lines.push(`✍ ${liveTail}`);
946
- if (lines.length === 0) return;
947
- onUpdate?.({
948
- content: [{ type: 'text', text: lines.map(l => `${labelPrefix}${l}`).join('\n') }],
949
- details: { progress: 0.5 },
950
- });
951
- };
952
- return delegate(pi, ctx, {
953
- ...callOpts,
954
- signal,
955
- onStream: t => {
956
- liveTail = (liveTail + t).slice(-400);
957
- pushFeed();
958
- },
959
- onActivity: ev => {
960
- if (ev.kind === 'tool_input') {
961
- feed.push(`▶ ${formatToolUse(ev.name, ev.input)}`);
962
- feedIndex.set(ev.id, feed.length - 1);
963
- if (feed.length > 40) {
964
- const removed = feed.length - 40;
965
- feed.splice(0, removed);
966
- feedIndex.shift(removed);
967
- }
968
- } else if (ev.kind === 'tool_result') {
969
- const idx = feedIndex.resolve(ev.id, feed.length - 1);
970
- if (idx >= 0 && feed[idx]?.startsWith('▶')) feed[idx] += ev.isError ? ' ✗' : ' ✓';
971
- } else if (ev.kind === 'thinking') thinkingChars += ev.chars;
972
- pushFeed();
973
- },
974
- });
975
- }
976
-
977
- /** `delegate({harness:"all"|"a,b"})` — resolve the requested harnesses to detected installs, run the
978
- * existing `delegate()` engine concurrently across all of them (bounded by `maxConcurrent` via
979
- * `acquireSlot({wait:true})` — see concurrency.ts), and mechanically synthesize one comparison
980
- * report ordered by the resolved harness list regardless of completion order. No second model call. */
981
- async function runFanoutTool(
982
- pi: ExtensionAPI,
983
- ctx: ExtensionContext,
984
- config: DelegateConfig,
985
- params: DelegateToolParams,
986
- signal: AbortSignal | undefined,
987
- onUpdate: ((u: ToolProgressUpdate) => void) | undefined,
988
- ): Promise<{ content: { type: string; text: string }[]; details: Record<string, unknown>; usage?: unknown }> {
989
- const detection = await detectAll();
990
- const { resolved, unknown, skipped } = resolveHarnessList(params.harness ?? 'all', {
991
- knownHarnesses: HARNESS_NAMES,
992
- aliasOf: resolveHarnessName,
993
- isKnown: isKnownHarness,
994
- detection,
995
- });
996
- if (resolved.length === 0) {
997
- throw new Error(
998
- `no harness available to fan out to (unknown: ${unknown.join(', ') || '—'}; not installed: ${skipped.join(', ') || '—'})`,
999
- );
1000
- }
1001
-
1002
- const mode = params.mode ?? config.defaultMode;
1003
-
1004
- type TaskResult = FanoutRunSummary & {
1005
- usage?: import('./harnesses/types.ts').StreamedUsage | null;
1006
- };
1007
- const tasks = resolved.map(async (h): Promise<TaskResult> => {
1008
- onUpdate?.({ content: [{ type: 'text', text: `[${h}] queued…` }], details: { progress: 0.5 } });
1009
- try {
1010
- const run = await runDelegateForTool(
1011
- pi,
1012
- ctx,
1013
- config,
1014
- {
1015
- harness: h,
1016
- task: params.task,
1017
- mode: params.mode,
1018
- scope: params.scope,
1019
- model: params.model,
1020
- maxBudgetUsd: params.maxBudgetUsd,
1021
- allowDangerous: params.allowDangerous === true,
1022
- sessionId: params.sessionId,
1023
- pr: params.pr,
1024
- // no verify: intentionally not model-settable — see DelegateToolParams
1025
- waitForSlot: true,
1026
- onAcquired: () =>
1027
- onUpdate?.({ content: [{ type: 'text', text: `[${h}] running…` }], details: { progress: 0.5 } }),
1028
- },
1029
- signal,
1030
- onUpdate,
1031
- `[${h}] `,
1032
- );
1033
- const summary = summarize(run.content);
1034
- return {
1035
- harness: h,
1036
- ok: !run.result.isError,
1037
- metrics: formatMetrics({
1038
- numTurns: run.result.numTurns,
1039
- totalCostUsd: run.result.totalCostUsd,
1040
- promptTokens: 0,
1041
- contextPercent: typeof run.details.contextPercent === 'number' ? run.details.contextPercent : null,
1042
- durationMs: run.result.durationMs,
1043
- }),
1044
- cost: run.result.totalCostUsd,
1045
- body: summary.text,
1046
- file: (run.details.file as string) ?? undefined,
1047
- sessionId: (run.details.sessionId as string) ?? undefined,
1048
- verify: run.verify,
1049
- usage: run.result.usage,
1050
- };
1051
- } catch (err) {
1052
- return { harness: h, ok: false, cost: null, error: err instanceof Error ? err.message : String(err) };
1053
- }
1054
- });
1055
-
1056
- const settled = await Promise.all(tasks);
1057
- const runs = orderFanoutResults(resolved, settled);
1058
-
1059
- let sumInput = 0;
1060
- let sumOutput = 0;
1061
- let sumCacheCreate = 0;
1062
- let sumCacheRead = 0;
1063
- let sumCost = 0;
1064
- let anyCostKnown = false;
1065
- for (const r of runs) {
1066
- if (r.usage) {
1067
- sumInput += r.usage.inputTokens;
1068
- sumOutput += r.usage.outputTokens;
1069
- sumCacheCreate += r.usage.cacheCreationInputTokens;
1070
- sumCacheRead += r.usage.cacheReadInputTokens;
1071
- }
1072
- if (r.cost !== null) {
1073
- sumCost += r.cost;
1074
- anyCostKnown = true;
1075
- }
1076
- }
1077
-
1078
- const report = buildFanoutReport({ runs, skipped, unknown });
1079
- const okCount = runs.filter(r => r.ok).length;
1080
- const head = `## delegate all — ${mode} (${okCount}/${runs.length} ok)`;
1081
- const usage = mapClaudeUsage({
1082
- inputTokens: sumInput,
1083
- outputTokens: sumOutput,
1084
- cacheCreationInputTokens: sumCacheCreate,
1085
- cacheReadInputTokens: sumCacheRead,
1086
- totalCostUsd: anyCostKnown ? sumCost : null,
1087
- });
1088
- return {
1089
- content: [{ type: 'text', text: `${head}\n\n${report}` }],
1090
- details: { fanout: true, harness: 'all', mode, harnesses: resolved, skipped, unknown, runs },
1091
- usage,
1092
- };
1093
- }
43
+ import { confirmDangerousCommand, confirmDangerousToolCall, confirmToolAddDirs } from './validate.ts';
1094
44
 
1095
45
  export default function (pi: ExtensionAPI) {
1096
- let activeRunId = 0;
1097
- let activeOverlay: { show(): void; focus(): void; runId: number } | null = null;
46
+ const ui: RunUiState = { activeRunId: 0, activeOverlay: null };
1098
47
 
1099
48
  // ── Tools ────────────────────────────────────────────────────────────────
1100
49
  const delegateToolDef = {
@@ -1108,8 +57,10 @@ export default function (pi: ExtensionAPI) {
1108
57
  'Pass harness (claude|codex|opencode|amp|devin) + focused task string + intent and constraints. Use scope: diff for current git diff, pr for PR diff, path list, or omit for whole repo.',
1109
58
  'mode selects the template and its permission level: review/plan/security-audit are readonly; implement/docs/general are edit. Custom template names also work. Some templates verify their own work (e.g. running tests) automatically after the harness finishes — that is not something you configure here.',
1110
59
  'harness: "all" or a comma list (e.g. "codex,opencode") fans the same task out to each detected harness and returns one synthesized comparison report — costs multiply, so only use it when the user actually wants a multi-harness comparison.',
1111
- 'sessionId resumes a previous delegated session instead of starting fresh.',
1112
- 'Do not set allowDangerous unless the user explicitly asks for unrestricted access (danger permission).',
60
+ 'sessionId resumes a previous delegated session instead of starting fresh — pass the exact session id from a previous run\'s details (letters, digits, . _ : - only). It cannot be combined with a fan-out harness ("all" or a comma list) — a session belongs to one harness.',
61
+ 'pr must be a PR number, an http(s) pull-request URL (https://<host>/<owner>/<repo>/pull/<n>), or owner/repo#123.',
62
+ 'addDirs inside the working directory are accepted as-is; any entry outside it asks the human to confirm interactively and is refused in a non-interactive session.',
63
+ 'Do not set allowDangerous unless the user explicitly asks for unrestricted access (danger permission). Setting it always asks the human to confirm interactively; in a non-interactive session it is refused outright.',
1113
64
  ],
1114
65
  parameters: Type.Object({
1115
66
  harness: Type.Optional(
@@ -1142,10 +93,19 @@ export default function (pi: ExtensionAPI) {
1142
93
  ),
1143
94
  allowDangerous: Type.Optional(
1144
95
  Type.Boolean({
1145
- description: 'Escalate to danger permission (unrestricted). Only with explicit user approval.',
96
+ description:
97
+ 'Escalate to danger permission (unrestricted). Always requires interactive human confirmation; refused without a UI.',
98
+ }),
99
+ ),
100
+ pr: Type.Optional(
101
+ Type.String({ description: 'GitHub PR number, http(s) PR URL, or owner/repo#123 (alternative to scope pr).' }),
102
+ ),
103
+ addDirs: Type.Optional(
104
+ Type.Array(Type.String(), {
105
+ description:
106
+ 'Extra directories the harness may access. Relative paths resolve against the working directory. Any entry that resolves (after symlinks) outside the working directory requires interactive human confirmation and is refused without a UI. Not every harness supports this (opencode ignores it; codex ignores it on resume).',
1146
107
  }),
1147
108
  ),
1148
- pr: Type.Optional(Type.String({ description: 'GitHub PR number/URL (alternative to scope pr).' })),
1149
109
  // Deliberately no `verify` param — see the trust-model comment on DelegateToolParams/runVerify.
1150
110
  }),
1151
111
  async execute(
@@ -1156,6 +116,12 @@ export default function (pi: ExtensionAPI) {
1156
116
  ctx: ExtensionContext,
1157
117
  ) {
1158
118
  const config = loadConfig();
119
+ // A model-set allowDangerous is never honored on its own — a human confirms it (or, with no
120
+ // UI to ask, it's refused). Checked once up front, before any fan-out. See validate.ts.
121
+ if (params.allowDangerous === true) await confirmDangerousToolCall(ctx, params);
122
+ // Same trust model for model-set addDirs: inside cwd is fine, anything outside needs a human
123
+ // (fail closed without a UI). Covers single, fan-out, and the claude_delegate alias.
124
+ await confirmToolAddDirs(ctx, params.addDirs);
1159
125
  if (params.harness && isFanoutSpec(params.harness)) {
1160
126
  return runFanoutTool(pi, ctx, config, params, signal, onUpdate);
1161
127
  }
@@ -1173,6 +139,7 @@ export default function (pi: ExtensionAPI) {
1173
139
  allowDangerous: params.allowDangerous === true, // invariant: never inherit from config.allowDangerous — danger requires explicit per-call approval
1174
140
  sessionId: params.sessionId,
1175
141
  pr: params.pr,
142
+ addDirs: params.addDirs,
1176
143
  // no verify: intentionally not model-settable — see DelegateToolParams
1177
144
  },
1178
145
  signal,
@@ -1306,16 +273,20 @@ export default function (pi: ExtensionAPI) {
1306
273
  budget?: number;
1307
274
  sessionId?: string;
1308
275
  pr?: string;
276
+ addDirs?: string[];
1309
277
  verify?: string;
1310
278
  template?: DelegateTemplate;
1311
279
  isDanger: boolean;
280
+ /** Only ever true after `confirmDangerousCommand` approved this invocation's --allow-dangerous. */
281
+ allowDangerous?: boolean;
1312
282
  },
1313
283
  ): Promise<{
1314
284
  result: Awaited<ReturnType<typeof delegate>> | null;
1315
285
  error: Error | null;
1316
286
  cancelled: boolean;
1317
287
  }> => {
1318
- const { harnessName, mode, task, scope, model, budget, sessionId, pr, verify, template, isDanger } = opts;
288
+ const { harnessName, mode, task, scope, model, budget, sessionId, pr, addDirs, verify, template, isDanger } = opts;
289
+ const allowDangerous = opts.allowDangerous === true;
1319
290
  const modeForDisplay = mode ?? 'general';
1320
291
 
1321
292
  const feed: FeedEntry[] = [];
@@ -1372,9 +343,9 @@ export default function (pi: ExtensionAPI) {
1372
343
  const ac = new AbortController();
1373
344
  let cancelled = false;
1374
345
  const runState: { error: Error | null } = { error: null };
1375
- const runId = ++activeRunId;
346
+ const runId = ++ui.activeRunId;
1376
347
  const clearActive = () => {
1377
- if (activeOverlay?.runId === runId) activeOverlay = null;
348
+ if (ui.activeOverlay?.runId === runId) ui.activeOverlay = null;
1378
349
  };
1379
350
  const run = delegate(pi, ctx, {
1380
351
  harness: harnessName,
@@ -1385,7 +356,9 @@ export default function (pi: ExtensionAPI) {
1385
356
  maxBudgetUsd: budget,
1386
357
  sessionId,
1387
358
  pr,
359
+ addDirs,
1388
360
  verify,
361
+ allowDangerous, // never from config.allowDangerous — only a confirmed --allow-dangerous
1389
362
  signal: ac.signal,
1390
363
  onStream: t => {
1391
364
  liveTail = (liveTail + t).slice(-400);
@@ -1427,7 +400,7 @@ export default function (pi: ExtensionAPI) {
1427
400
  overlayOptions: { width: '70%', maxHeight: '60%', anchor: 'top-center' },
1428
401
  onHandle: h => {
1429
402
  overlayHandle = h;
1430
- activeOverlay = { show: () => h.setHidden(false), focus: () => h.focus(), runId };
403
+ ui.activeOverlay = { show: () => h.setHidden(false), focus: () => h.focus(), runId };
1431
404
  h.focus();
1432
405
  },
1433
406
  },
@@ -1445,284 +418,6 @@ export default function (pi: ExtensionAPI) {
1445
418
  return { result: failed ? null : result, error: runState.error, cancelled };
1446
419
  };
1447
420
 
1448
- interface FanoutSpec {
1449
- harnessName: string;
1450
- task: string;
1451
- scope?: string;
1452
- model?: string;
1453
- budget?: number;
1454
- sessionId?: string;
1455
- pr?: string;
1456
- verify?: string;
1457
- isDanger: boolean;
1458
- }
1459
- interface FanoutOutcome {
1460
- harnessName: string;
1461
- result: Awaited<ReturnType<typeof delegate>> | null;
1462
- error: Error | null;
1463
- cancelled: boolean;
1464
- }
1465
-
1466
- /** Run `delegate()` concurrently across every spec in one multi-run overlay — the fan-out
1467
- * counterpart to `runOneDelegation`. Concurrency is bounded by `maxConcurrent`: every run passes
1468
- * `waitForSlot:true`, so `acquireSlot` (concurrency.ts) queues the ones that don't fit instead of
1469
- * failing them, and a fan-out never exceeds the configured cap just because it's a fan-out.
1470
- * Double-ESC cancel aborts every in-flight (and still-queued) run via one shared AbortController. */
1471
- const runFanoutConcurrent = async (ctx: ExtensionContext, mode: string | undefined, specs: FanoutSpec[]) => {
1472
- const ac = new AbortController();
1473
- let cancelledAll = false;
1474
- const runId = ++activeRunId;
1475
- const clearActive = () => {
1476
- if (activeOverlay?.runId === runId) activeOverlay = null;
1477
- };
1478
- const modeForDisplay = mode ?? 'general';
1479
- const anyDanger = specs.some(s => s.isDanger);
1480
- const overallStart = Date.now();
1481
- const rows: RunRow[] = specs.map(s => ({
1482
- harness: s.harnessName,
1483
- startedAt: null,
1484
- status: 'queued',
1485
- activity: '',
1486
- costUsd: null,
1487
- }));
1488
- let requestRender: (() => void) | null = null;
1489
-
1490
- let chipLastPush = 0;
1491
- const pushChip = () => {
1492
- if (!ctx.hasUI) return;
1493
- const now = Date.now();
1494
- if (now - chipLastPush < 500) return;
1495
- chipLastPush = now;
1496
- const theme = ctx.ui.theme;
1497
- ctx.ui.setStatus(
1498
- 'delegate',
1499
- theme.fg('accent', '●') + theme.fg('dim', ` ${formatFanoutChip(rows, now - overallStart)}`),
1500
- );
1501
- };
1502
-
1503
- const runOne = async (spec: FanoutSpec, idx: number): Promise<FanoutOutcome> => {
1504
- const setRow = (patch: Partial<RunRow>) => {
1505
- rows[idx] = { ...rows[idx], ...patch };
1506
- requestRender?.();
1507
- pushChip();
1508
- };
1509
- let liveTail = '';
1510
- const onActivity = (ev: ActivityEvent) => {
1511
- if (ev.kind === 'tool_input') setRow({ activity: `▶ ${formatToolUse(ev.name, ev.input)}` });
1512
- else if (ev.kind === 'tool_result')
1513
- setRow({
1514
- activity: rows[idx].activity ? `${rows[idx].activity}${ev.isError ? ' ✗' : ' ✓'}` : rows[idx].activity,
1515
- });
1516
- else if (ev.kind === 'thinking') setRow({ activity: '💭 thinking…' });
1517
- };
1518
- const runState: { error: Error | null } = { error: null };
1519
- const run = delegate(pi, ctx, {
1520
- harness: spec.harnessName,
1521
- task: spec.task,
1522
- mode,
1523
- scope: spec.scope,
1524
- model: spec.model,
1525
- maxBudgetUsd: spec.budget,
1526
- sessionId: spec.sessionId,
1527
- pr: spec.pr,
1528
- verify: spec.verify,
1529
- signal: ac.signal,
1530
- waitForSlot: true,
1531
- onAcquired: () => setRow({ status: 'running', startedAt: Date.now() }),
1532
- onStream: t => {
1533
- liveTail = (liveTail + t).slice(-200);
1534
- setRow({ activity: `✍ ${liveTail}` });
1535
- },
1536
- onActivity,
1537
- }).catch((err: unknown) => {
1538
- runState.error = err instanceof Error ? err : new Error(String(err));
1539
- return null;
1540
- });
1541
- const result = await run;
1542
- const failed = cancelledAll || !result;
1543
- // On failure keep context on the row: the reason if we have one, else whatever the run was
1544
- // last doing. Blanking it here would drop the only on-screen hint at *why* it failed.
1545
- const reason = runState.error ? runState.error.message.split('\n')[0].slice(0, 60) : '';
1546
- setRow({
1547
- status: failed ? 'failed' : 'done',
1548
- activity: failed ? reason || rows[idx].activity : '',
1549
- costUsd: !failed && result ? result.result.totalCostUsd : null,
1550
- });
1551
- return {
1552
- harnessName: spec.harnessName,
1553
- result: failed ? null : result,
1554
- error: runState.error,
1555
- cancelled: cancelledAll,
1556
- };
1557
- };
1558
-
1559
- const allSettled = Promise.all(specs.map((spec, idx) => runOne(spec, idx)));
1560
-
1561
- let closeWindow: (() => void) | null = null;
1562
- let outcomes: FanoutOutcome[];
1563
- if (ctx.hasUI) {
1564
- let overlayHandle: OverlayHandle | null = null;
1565
- let resolveDismiss = (): void => {};
1566
- const dismissed = new Promise<void>(resolve => {
1567
- resolveDismiss = () => resolve();
1568
- });
1569
- const uiPromise = ctx.ui
1570
- .custom(
1571
- (tui, theme, _kb, done) => {
1572
- requestRender = () => tui.requestRender();
1573
- closeWindow = () => done(undefined);
1574
- return multiProgressWindow(tui, theme, {
1575
- mode: modeForDisplay,
1576
- startedAt: overallStart,
1577
- getRows: () => rows,
1578
- dangerous: anyDanger,
1579
- onCancel: () => {
1580
- cancelledAll = true;
1581
- ac.abort();
1582
- },
1583
- onMinimize: () => {
1584
- overlayHandle?.setHidden(true);
1585
- overlayHandle?.unfocus();
1586
- },
1587
- onDismiss: () => resolveDismiss(),
1588
- });
1589
- },
1590
- {
1591
- overlay: true,
1592
- overlayOptions: { width: '70%', maxHeight: '60%', anchor: 'top-center' },
1593
- onHandle: h => {
1594
- overlayHandle = h;
1595
- activeOverlay = { show: () => h.setHidden(false), focus: () => h.focus(), runId };
1596
- h.focus();
1597
- },
1598
- },
1599
- )
1600
- .catch(() => {});
1601
- outcomes = await allSettled;
1602
- // Cancelling already means "I'm done watching" — skip the linger so the overlay closes
1603
- // right away instead of sitting on a cancelled board for FANOUT_LINGER_MS.
1604
- if (cancelledAll) resolveDismiss();
1605
- // Tear the overlay down after a short linger (or immediately on Esc/m/cancel) — in the
1606
- // background, so this doesn't delay the outcomes we're about to return (and thus the
1607
- // injected report). `activeOverlay` stays valid for `/delegate watch` until this settles.
1608
- void (async () => {
1609
- const timer = setTimeout(() => resolveDismiss(), FANOUT_LINGER_MS);
1610
- timer.unref?.();
1611
- await dismissed;
1612
- clearTimeout(timer);
1613
- await closeWhenMounted(() => closeWindow, 2000);
1614
- await uiPromise;
1615
- clearActive();
1616
- ctx.ui.setStatus('delegate', undefined);
1617
- })();
1618
- } else {
1619
- outcomes = await allSettled;
1620
- clearActive();
1621
- }
1622
- return outcomes;
1623
- };
1624
-
1625
- /** `/delegate all …` / `/delegate a,b …` — resolve to detected harnesses, run `delegate()`
1626
- * concurrently across all of them in one multi-run overlay (see `runFanoutConcurrent`), batch
1627
- * success notifications, and inject one synthesized comparison report ordered by the resolved
1628
- * harness list regardless of completion order. */
1629
- const runFanoutCommand = async (ctx: ExtensionContext, parsed: ReturnType<typeof parseDelegateCommand>) => {
1630
- const harnessSpec = parsed.harness as string;
1631
- const detection = await detectAll();
1632
- const { resolved, unknown, skipped } = resolveHarnessList(harnessSpec, {
1633
- knownHarnesses: HARNESS_NAMES,
1634
- aliasOf: resolveHarnessName,
1635
- isKnown: isKnownHarness,
1636
- detection,
1637
- });
1638
- if (resolved.length === 0) {
1639
- const msg = `no harness available to fan out to (unknown: ${unknown.join(', ') || '—'}; not installed: ${skipped.join(', ') || '—'})`;
1640
- if (ctx.hasUI) ctx.ui.notify(msg, 'error');
1641
- else process.stderr.write(`${msg}\n`);
1642
- return;
1643
- }
1644
-
1645
- const modeForReport = parsed.mode ?? loadConfig().defaultMode;
1646
- const batcher = new NotifyBatcher((text, level) => {
1647
- if (ctx.hasUI) ctx.ui.notify(text, level);
1648
- else process.stdout.write(`${text}\n`);
1649
- });
1650
-
1651
- // Resolve each harness's task/scope/danger flag up front — cheap and synchronous — so a
1652
- // harness that can't even start (e.g. mode needs a prompt) fails immediately instead of
1653
- // occupying a concurrency slot.
1654
- const specs: FanoutSpec[] = [];
1655
- const immediateFailures: FanoutRunSummary[] = [];
1656
- const trusted = isProjectTrusted(ctx);
1657
- for (const h of resolved) {
1658
- const templates = loadTemplates(ctx.cwd, h, trusted);
1659
- const resolvedTaskScope = resolveDefaults(parsed, templates);
1660
- const template = parsed.mode ? templates.get(parsed.mode) : undefined;
1661
- if (!resolvedTaskScope) {
1662
- const message = `mode "${parsed.mode ?? 'general'}" needs a prompt`;
1663
- immediateFailures.push({ harness: h, ok: false, cost: null, error: message });
1664
- batcher.failure(`${h}: ${message}`);
1665
- continue;
1666
- }
1667
- const isDanger =
1668
- template?.permission === 'danger' ||
1669
- (template?.nativePermission
1670
- ? ['bypassPermissions', 'danger-full-access', 'danger'].includes(template.nativePermission)
1671
- : false);
1672
- specs.push({
1673
- harnessName: h,
1674
- task: resolvedTaskScope.task,
1675
- scope: resolvedTaskScope.scope,
1676
- model: parsed.model,
1677
- budget: parsed.budget,
1678
- sessionId: parsed.sessionId,
1679
- pr: parsed.pr,
1680
- verify: parsed.verify,
1681
- isDanger,
1682
- });
1683
- }
1684
-
1685
- const outcomes = specs.length > 0 ? await runFanoutConcurrent(ctx, parsed.mode, specs) : [];
1686
- const completed: FanoutRunSummary[] = outcomes.map(outcome => {
1687
- if (outcome.cancelled || !outcome.result) {
1688
- const message = outcome.error ? outcome.error.message : outcome.cancelled ? 'cancelled' : 'delegation failed';
1689
- batcher.failure(`${outcome.harnessName}: ${outcome.cancelled ? 'cancelled' : 'failed'} — ${message}`);
1690
- return { harness: outcome.harnessName, ok: false, cost: null, error: message };
1691
- }
1692
- const { content, details, result, verify } = outcome.result;
1693
- const summary = summarize(content);
1694
- const metrics = formatMetrics({
1695
- numTurns: result.numTurns,
1696
- totalCostUsd: result.totalCostUsd,
1697
- promptTokens: 0,
1698
- contextPercent: typeof details.contextPercent === 'number' ? details.contextPercent : null,
1699
- durationMs: typeof details.durationMs === 'number' ? details.durationMs : null,
1700
- });
1701
- batcher.success(`${outcome.harnessName} ${parsed.mode ?? 'general'} — ${metrics}`);
1702
- return {
1703
- harness: outcome.harnessName,
1704
- ok: !result.isError,
1705
- metrics,
1706
- cost: result.totalCostUsd,
1707
- body: summary.text,
1708
- file: (details.file as string) ?? undefined,
1709
- sessionId: (details.sessionId as string) ?? undefined,
1710
- verify,
1711
- };
1712
- });
1713
-
1714
- const runs = orderFanoutResults(resolved, [...immediateFailures, ...completed]);
1715
- const okCount = runs.filter(r => r.ok).length;
1716
- const report = buildFanoutReport({ runs, skipped, unknown });
1717
- injectReport(ctx, {
1718
- harness: 'all',
1719
- mode: modeForReport,
1720
- metrics: `${okCount}/${runs.length} ok`,
1721
- body: report,
1722
- });
1723
- batcher.flush();
1724
- };
1725
-
1726
421
  const makeHandler = (forcedHarness?: string) => async (args: string, ctx: ExtensionContext) => {
1727
422
  const sub = args.trim();
1728
423
  const subLower = sub.toLowerCase();
@@ -1756,9 +451,9 @@ export default function (pi: ExtensionAPI) {
1756
451
  // extract --harness flag for list/history subcommands
1757
452
  const harnessFlag = sub.match(/--harness=([^\s]+)/)?.[1];
1758
453
  if (sub === 'watch' || sub === 'show') {
1759
- if (activeOverlay) {
1760
- activeOverlay.show();
1761
- activeOverlay.focus();
454
+ if (ui.activeOverlay) {
455
+ ui.activeOverlay.show();
456
+ ui.activeOverlay.focus();
1762
457
  } else {
1763
458
  ctx.ui.notify?.('No active delegate run to show — start one with /delegate <harness> <mode> <prompt>', 'info');
1764
459
  }
@@ -1811,7 +506,7 @@ export default function (pi: ExtensionAPI) {
1811
506
  // fan-out: harness field is `all` or a comma list — resolve to detected harnesses and run
1812
507
  // the engine once per harness instead of the single-harness flow below.
1813
508
  if (parsed.harness && isFanoutSpec(parsed.harness)) {
1814
- await runFanoutCommand(ctx, parsed);
509
+ await runFanoutCommand(pi, ui, ctx, parsed);
1815
510
  return;
1816
511
  }
1817
512
 
@@ -1833,12 +528,32 @@ export default function (pi: ExtensionAPI) {
1833
528
  );
1834
529
  else
1835
530
  ctx.ui.notify?.(
1836
- 'Usage: /delegate [--harness=claude|codex|opencode|amp|devin|all] [--mode=…] [--model=…] [--scope=…] [--verify=…] <prompt>',
531
+ 'Usage: /delegate [--harness=claude|codex|opencode|amp|devin|all] [--mode=…] [--model=…] [--scope=…] [--pr=…] [--budget=…] [--verify=…] [--resume=…] [--allow-dangerous] <prompt>',
1837
532
  'warning',
1838
533
  );
1839
534
  return;
1840
535
  }
1841
536
 
537
+ // --allow-dangerous: honored for this invocation only, and only once a human confirms it in an
538
+ // interactive dialog — headless refuses (fail closed). Escalates a non-danger template too (the
539
+ // engine's existing allowDangerous semantics), so the same confirm applies either way.
540
+ let allowDangerous = false;
541
+ if (parsed.allowDangerous) {
542
+ try {
543
+ await confirmDangerousCommand(ctx, {
544
+ harnesses: [harnessName],
545
+ mode: parsed.mode ?? loadConfig().defaultMode,
546
+ task: resolved.task,
547
+ });
548
+ allowDangerous = true;
549
+ } catch (err) {
550
+ const msg = err instanceof Error ? err.message : String(err);
551
+ if (ctx.hasUI) ctx.ui.notify(msg, 'warning');
552
+ else process.stderr.write(`${msg}\n`);
553
+ return;
554
+ }
555
+ }
556
+
1842
557
  const outcome = await runOneDelegation(ctx, {
1843
558
  harnessName,
1844
559
  mode: parsed.mode,
@@ -1848,9 +563,11 @@ export default function (pi: ExtensionAPI) {
1848
563
  budget: parsed.budget,
1849
564
  sessionId: parsed.sessionId,
1850
565
  pr: parsed.pr,
566
+ addDirs: parsed.addDirs,
1851
567
  verify: parsed.verify,
1852
568
  template,
1853
- isDanger,
569
+ isDanger: isDanger || allowDangerous,
570
+ allowDangerous,
1854
571
  });
1855
572
  if (outcome.cancelled || !outcome.result) {
1856
573
  const message = outcome.error ? outcome.error.message : outcome.cancelled ? 'cancelled' : 'delegation failed';
@@ -1903,7 +620,7 @@ export default function (pi: ExtensionAPI) {
1903
620
 
1904
621
  pi.registerCommand('delegate', {
1905
622
  description:
1906
- 'Delegate a task to any harness. Usage: /delegate [--harness=claude|codex|opencode|amp|devin|all] [--mode=review|plan|implement|security-audit|docs|general] [--model=...] [--scope=diff|pr|paths] [--verify=<cmd>] [--resume=<id>] <prompt> — or use harness as first word: /delegate codex review <prompt>. harness=all or a comma list (e.g. claude,codex) fans out to every detected harness and returns one comparison report.',
623
+ 'Delegate a task to any harness. Usage: /delegate [--harness=claude|codex|opencode|amp|devin|all] [--mode=review|plan|implement|security-audit|docs|general] [--model=...] [--scope=diff|pr|paths] [--pr=<n|url>] [--budget=<usd>] [--verify=<cmd>] [--resume=<id>] [--allow-dangerous] <prompt> — or use harness as first word: /delegate codex review <prompt>. harness=all or a comma list (e.g. claude,codex) fans out to every detected harness and returns one comparison report. --allow-dangerous runs this one invocation with danger (unrestricted) permission after an interactive confirm; refused headless.',
1907
624
  handler: makeHandler(),
1908
625
  });
1909
626
  pi.registerCommand('claude', {
@@ -1939,9 +656,8 @@ export default function (pi: ExtensionAPI) {
1939
656
  });
1940
657
 
1941
658
  pi.on('before_agent_start', async () => {
1942
- if (!pendingReport) return;
1943
- const report = pendingReport;
1944
- pendingReport = null;
659
+ const report = takePendingReport();
660
+ if (!report) return;
1945
661
  return { message: { customType: 'delegate', content: report.content, display: true, details: report.details } };
1946
662
  });
1947
663
  }