pi-suite 0.3.1 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +76 -29
  2. package/README.zh-CN.md +79 -32
  3. package/package.json +1 -1
  4. package/src/agents/index.ts +8 -6
  5. package/src/agents/render.ts +18 -8
  6. package/src/agents/schedules/menu.ts +2 -1
  7. package/src/agents/tools.ts +7 -6
  8. package/src/agents/ui/runs.ts +6 -7
  9. package/src/agents/ui/types.ts +5 -11
  10. package/src/agents/viewer-info.ts +12 -10
  11. package/src/agents/viewer.ts +4 -2
  12. package/src/agents/workflow/ui/progress.ts +5 -5
  13. package/src/ask/index.ts +4 -2
  14. package/src/ask/view.ts +13 -5
  15. package/src/goal/manager.ts +8 -0
  16. package/src/jobs/index.ts +6 -2
  17. package/src/jobs/output.ts +19 -7
  18. package/src/jobs/query.ts +27 -20
  19. package/src/jobs/render.ts +13 -4
  20. package/src/jobs/terminal/session.ts +73 -27
  21. package/src/jobs/tools.ts +9 -6
  22. package/src/jobs/viewer/component.ts +3 -1
  23. package/src/notify/index.ts +85 -0
  24. package/src/runtime/config.ts +5 -0
  25. package/src/runtime/notifications.ts +6 -1
  26. package/src/runtime/read.ts +163 -25
  27. package/src/runtime/responses/index.ts +19 -23
  28. package/src/runtime/responses/payload.ts +10 -7
  29. package/src/runtime/suite.ts +17 -6
  30. package/src/runtime/tools.ts +7 -2
  31. package/src/tasks/presentation.ts +5 -0
  32. package/src/tasks/query.ts +16 -8
  33. package/src/tasks/render.ts +14 -5
  34. package/src/tasks/tools.ts +5 -2
  35. package/src/tasks/viewer.ts +18 -9
  36. package/src/ui/browser.ts +14 -10
  37. package/src/ui/details.ts +22 -7
  38. package/src/ui/dock.ts +6 -1
  39. package/src/ui/rendering/read-page.ts +2 -1
  40. package/src/ui/structured-details.ts +57 -11
  41. package/src/ui/working.ts +11 -0
  42. package/third-party/UPSTREAM.md +17 -66
@@ -1,36 +1,38 @@
1
1
  import type { AgentRecord } from './types.ts';
2
- import { field, part, section, statePart, type StructuredDetails } from '../ui/structured-details.ts';
2
+ import { field, outputRow, part, section, statePart, type StructuredDetails } from '../ui/structured-details.ts';
3
+ import { countText, elapsedText } from '../ui/format.ts';
3
4
 
4
5
  /** Runtime statistics are run-scoped; current type configuration cannot rewrite history. */
5
6
  export function agentDetails(record: AgentRecord, permissions?: {readonly: boolean; canMessage: boolean; canStop: boolean}, readOnlyBanner = false): StructuredDetails {
6
7
  const context = record.contextUsage;
7
8
  const tokens = record.usage?.tokens;
9
+ // Pi tracks uncached input, cache reads and cache writes as separate prompt token counts.
10
+ const promptTokens = tokens ? tokens.input + tokens.cacheRead + tokens.cacheWrite : 0;
8
11
  return {rows: [
9
12
  readOnlyBanner ? [part('Read only', 'meta')] : undefined,
10
13
  [part(record.name, 'heading')], field('Type:', record.type), field('ID:', part(record.id, 'id')),
11
- field('Run:', part(record.runId, 'id')), field('State:', statePart(record.state)), null,
12
- field('Model:', record.model, part(` (${record.modelSource})`, 'meta')),
13
- field('Thinking:', record.thinking, part(` (${record.thinkingSource})`, 'meta')), null,
14
+ field('State:', statePart(record.state)), null,
15
+ field('Model:', `${record.model} · ${record.thinking}`), null,
14
16
  ...(permissions ? [field('Read only:', permissions.readonly), field('Can message:', permissions.canMessage), field('Can stop:', permissions.canStop)] : []),
15
- field('Owner session:', part(record.ownerSessionId, 'id')),
16
17
  record.parentRunId ? field('Parent run:', part(record.parentRunId, 'id')) : undefined, null,
17
- tokens ? field('Tokens:', part(`input ${tokens.input} · output ${tokens.output} · cache read ${tokens.cacheRead} · cache write ${tokens.cacheWrite} · total ${tokens.total}`, 'number')) : undefined,
18
+ tokens ? field('Tokens:', part(`input ${countText(tokens.input)} · output ${countText(tokens.output)} · cache read ${countText(tokens.cacheRead)} · cache write ${countText(tokens.cacheWrite)} · total ${countText(tokens.total)}`, 'number')) : undefined,
19
+ tokens ? field('Cache hit rate:', promptTokens > 0 ? part(`${(tokens.cacheRead / promptTokens * 100).toFixed(1)}%`, 'number') : 'unavailable') : undefined,
18
20
  record.usage ? field('Cost:', part(`$${record.usage.cost.toFixed(6)}`, 'number')) : undefined,
19
21
  field('Context:', context ? part(`${context.tokens ?? 'unknown'} / ${context.contextWindow} tokens${context.percent === null ? '' : ` (${context.percent.toFixed(1)}%)`}`, 'number') : 'unavailable'),
20
22
  field('Tool calls:', part(record.toolUses ?? (record.state === 'queued' || record.state === 'starting' ? 0 : 'unavailable'), 'number')), null,
21
- field('Runtime:', record.elapsedMs === undefined ? 'not started' : part(`${(record.elapsedMs / 1000).toFixed(1)}s`, 'number')),
23
+ field('Runtime:', record.elapsedMs === undefined ? 'not started' : part(elapsedText(record.elapsedMs), 'number')),
22
24
  record.state === 'queued' ? field('Queued:', part(`${Math.max(0, Date.now() - Date.parse(record.createdAt)) / 1000}s`, 'number')) : undefined,
23
25
  field('Created:', part(record.createdAt, 'meta')),
24
26
  record.startedAt ? field('Started:', part(record.startedAt, 'meta')) : undefined,
25
27
  ...(record.taskId || record.workflowId ? [null,
26
- record.taskId ? field('Task:', part(record.taskId, 'id'), part(' · source generation: ', 'label'), part(record.taskGeneration ?? 'unavailable (assignment expired)', 'id')) : undefined,
28
+ record.taskId ? field('Task:', part(record.taskId, 'id')) : undefined,
27
29
  record.workflowId ? field('Workflow:', part(record.workflowId, 'id')) : undefined, null,
28
30
  ] : []),
29
31
  record.endedAt ? field('Ended:', part(record.endedAt, 'meta')) : undefined,
30
- field('Cwd:', part(record.cwd, 'meta')),
31
32
  // Prompt and result are free text; titled sections keep them apart from the fields above.
32
33
  section('Input'), record.prompt,
33
34
  ...(record.result !== undefined || record.error ? [section('Output'),
34
- record.error ? field('Error:', part(record.error, 'error')) : undefined, record.result] : []),
35
+ record.error ? field('Error:', part(record.error, 'error')) : undefined,
36
+ record.result === undefined ? undefined : outputRow(record.result, {markdown: true})] : []),
35
37
  ]};
36
38
  }
@@ -15,6 +15,7 @@ import { jobActions, type ViewerDeps } from '../jobs/viewer.ts';
15
15
  import { isActive as jobActive } from '../jobs/state.ts';
16
16
  import { ViewerNavigation } from '../ui/viewer/navigation.ts';
17
17
  import { agentInformation } from '../ui/viewer/agent-information.ts';
18
+ import { WORKING_INTERVAL_MS, workingLine } from '../ui/working.ts';
18
19
  import { agentDetails } from './viewer-info.ts';
19
20
  import { showDetails } from '../ui/details.ts';
20
21
  import { displayName as jobName, jobCompactStatus, jobLabel, jobStatus } from '../jobs/index.ts';
@@ -124,7 +125,8 @@ async function readAgent(ctx: ExtensionContext, agents: Pick<AgentsModule, 'mana
124
125
  { label: 'Background', key: 'b', available: () => !readonly && agents.manager.canSendToBackground(id, runId), run: () => { agents.manager.sendToBackground(id, runId); } },
125
126
  { label: 'Stop subtree', key: 'x', confirm: true, available: canStop, run: () => { action = 'stop'; done(); } },
126
127
  ], reader, theme, {title: false, navigation, keys,
127
- bottom: width => agentInformation(get().record, Boolean(get().run?.question), readonly, view.reader, width, theme)});
128
+ bottom: width => agentInformation(get().record, Boolean(get().run?.question), readonly, view.reader, width, theme),
129
+ status: () => ['starting', 'running'].includes(get().record.state) ? workingLine(theme) : undefined});
128
130
  if (!reader) view.reader.follow();
129
131
  view.reader.setContent(content);
130
132
  reader = view.reader;
@@ -144,7 +146,7 @@ async function readAgent(ctx: ExtensionContext, agents: Pick<AgentsModule, 'mana
144
146
  const clock = active(get().record.state) ? setInterval(() => {
145
147
  if (!active(get().record.state)) clearInterval(clock);
146
148
  tui.requestRender();
147
- }, 1000).unref() : undefined;
149
+ }, WORKING_INTERVAL_MS).unref() : undefined;
148
150
  const dispose = view.dispose.bind(view);
149
151
  return Object.assign(view, { dispose: () => {dispose(); unsubscribe(); clearInterval(clock);} });
150
152
  });
@@ -3,7 +3,7 @@
3
3
  import type { Theme } from '@earendil-works/pi-coding-agent';
4
4
  import { toolLine, stateLine, type ToolExpandedRow, type ToolLine } from '../../../ui/tool-render.ts';
5
5
  import { Text } from '@earendil-works/pi-tui';
6
- import { detailsText, field, part, statePart, type DetailRow, type StructuredDetails } from '../../../ui/structured-details.ts';
6
+ import { detailsText, field, part, section, statePart, type DetailRow, type StructuredDetails } from '../../../ui/structured-details.ts';
7
7
  import { workflowActive } from '../manager.ts';
8
8
  import { buildPhaseGroups, displayState, formatDuration, header } from '../progress/index.ts';
9
9
  import { workflowResultText, type WorkflowTask } from '../task.ts';
@@ -12,14 +12,14 @@ export function workflowDetails(task: WorkflowTask, expanded = true, now = Date.
12
12
  const groups = buildPhaseGroups(task.workflowProgress, task.meta?.phases);
13
13
  const title = header(task, task.meta, groups, task.agentCount, now);
14
14
  const active = workflowActive(task);
15
- const rows: DetailRow[] = [
15
+ const rows: (DetailRow | null)[] = [
16
16
  [part(title.name, 'heading'), part(' · '), part(title.stats, 'number'), ...(title.state ? [part(' · '), statePart(title.state)] : [])],
17
17
  title.subtext,
18
18
  [part(`${task.totalTokens} tokens · ${task.totalToolCalls} tools${task.replayedCount ? ` · ${task.replayedCount} replayed` : ''}`, 'number')],
19
19
  ];
20
20
  if (expanded) {
21
21
  for (const group of groups) {
22
- rows.push('', [part(group.title, 'heading'), part(' · '), statePart(group.status, group.status === 'not-started' ? 'queued' : group.status),
22
+ rows.push(null, [part(group.title, 'heading'), part(' · '), statePart(group.status, group.status === 'not-started' ? 'queued' : group.status),
23
23
  part(' · '), part(`${group.doneCount}/${group.totalCount} · ${formatDuration(group.durationMs)}`, 'number')]);
24
24
  for (const agent of group.agents) {
25
25
  const state = displayState(agent, active);
@@ -39,8 +39,8 @@ export function workflowDetails(task: WorkflowTask, expanded = true, now = Date.
39
39
  if (agent.error) rows.push(field(' Error:', part(agent.error, 'error')));
40
40
  }
41
41
  }
42
- if (task.logs.length) rows.push('', [part('Logs', 'label')], ...task.logs);
43
- if (!active) rows.push('', [part('Result', 'label')], [part(workflowResultText(task), task.error === undefined ? undefined : 'error')]);
42
+ if (task.logs.length) rows.push(null, section('Logs'), ...task.logs);
43
+ if (!active) rows.push(null, section('Result'), [part(workflowResultText(task), task.error === undefined ? undefined : 'error')]);
44
44
  }
45
45
  return {rows};
46
46
  }
package/src/ask/index.ts CHANGED
@@ -16,7 +16,8 @@ export class AskManager {
16
16
  private active?: AskView;
17
17
  private rendererApi?: ExtensionAPI;
18
18
  constructor(private binding: SessionBinding, private notifications: Notifications, private dock: Dock,
19
- private onResult?: (status: AskResult["status"], ctx: ExtensionContext) => void | Promise<void>) {}
19
+ private onResult?: (status: AskResult["status"], ctx: ExtensionContext) => void | Promise<void>,
20
+ private onShown?: () => void) {}
20
21
  setRendererApi(pi: ExtensionAPI): void { this.rendererApi = pi; }
21
22
  cancel(): void { this.active?.cancel(); }
22
23
 
@@ -41,7 +42,8 @@ export class AskManager {
41
42
  pi && { theme, ...customRendererLookup(pi) });
42
43
  transcript.setEntries(ctx.sessionManager.getBranch());
43
44
  this.active = new AskView(new AskForm(questions), tui, theme, this.dock, config, transcript,
44
- done, params.timeoutMs ?? config.ask.timeout, signal, params.allowComment, requester, params.questions ? params.question : undefined);
45
+ done, params.timeoutMs ?? config.ask.timeout, signal, params.allowComment, requester, params.questions ? params.question : undefined,
46
+ () => { if (this.binding.isCurrent(captured)) this.onShown?.(); });
45
47
  return this.active;
46
48
  }, { blocked: { kind: "question", message: questions[0].question } });
47
49
  } finally {
package/src/ask/view.ts CHANGED
@@ -57,6 +57,7 @@ export class AskView extends Container {
57
57
  private dock: Dock, private config: SuiteConfig, private transcript: Transcript,
58
58
  private done: (result: AskResult) => void, private timeout: number,
59
59
  private signal?: AbortSignal, private allowComment = false, private requester = "main", private heading?: string,
60
+ private onShown?: () => void,
60
61
  ) {
61
62
  super();
62
63
  const editorTheme = { borderColor: (text: string) => theme.fg("accent", text), selectList: {
@@ -88,6 +89,7 @@ export class AskView extends Container {
88
89
  this.closed = true; this.dispose(); this.done(result);
89
90
  }
90
91
  dispose(): void {
92
+ this.closed = true;
91
93
  clearTimeout(this.timer); clearInterval(this.countdown);
92
94
  this.history.dispose(); for (const reader of this.descriptions.values()) reader.dispose();
93
95
  this.signal?.removeEventListener("abort", this.abort);
@@ -268,10 +270,14 @@ export class AskView extends Container {
268
270
  }
269
271
  private editorLines(width: number, height: number): string[] {
270
272
  const editor = this.editors[this.form.index]; editor.focused = this.focus === "answer";
271
- const rendered = editor.render(Math.max(1, width - 2)).slice(1, -1);
273
+ const prompt = "✎ ", promptWidth = visibleWidth(prompt);
274
+ const rendered = editor.render(Math.max(1, width - promptWidth)).slice(1, -1);
272
275
  const cursor = rendered.findIndex(line => line.includes(CURSOR_MARKER));
273
276
  const start = Math.max(0, cursor - height + 1);
274
- return rendered.slice(start, start + height).map(line => this.theme.fg("accent", "✎ ") + line);
277
+ const indent = " ".repeat(promptWidth);
278
+ // Decorate the viewport after slicing so the prompt stays at its top as the cursor scrolls.
279
+ return rendered.slice(start, start + height).map((line, index) =>
280
+ (index === 0 ? this.theme.fg("accent", prompt) : indent) + line);
275
281
  }
276
282
  private answerLine(width: number): string {
277
283
  if (this.focus === "search") { this.search.focused = true; return this.search.render(width)[0]; }
@@ -345,11 +351,13 @@ export class AskView extends Container {
345
351
  ], this.height);
346
352
  }
347
353
  override render(width: number): string[] {
354
+ if (this.closed) return [];
348
355
  if (!this.started) {
356
+ if (this.signal?.aborted) { this.abort(); return []; }
349
357
  this.started = true;
350
- if (this.signal?.aborted) this.abort();
351
- else if (this.timeout > 0) {
352
- // First render is the display boundary; queued views consume no idle time.
358
+ // Queued views consume neither idle time nor a notification before display.
359
+ this.onShown?.();
360
+ if (this.timeout > 0) {
353
361
  this.touch(); this.countdown = setInterval(() => this.tui.requestRender(), 1000);
354
362
  }
355
363
  }
@@ -67,6 +67,14 @@ export class GoalManager {
67
67
  return { goal: this.goal!, access: this.executing ? 'execute' : 'complete' };
68
68
  }
69
69
  get control(): number { return this.controlRevision; }
70
+ /**
71
+ * Goal needs no user right now: it either keeps requesting turns or wakes itself when its jobs settle.
72
+ * Read this after settled(); completed, paused, cancelled and user-waiting goals are all false.
73
+ */
74
+ get unattended(): boolean {
75
+ const goal = this.goal;
76
+ return Boolean(goal && !this.fault && goal.status === 'active' && goal.automatic && goal.waiting !== 'user');
77
+ }
70
78
  private cancelRequest(): void {
71
79
  if (this.goal && this.binding.current) this.notifications.cancel(this.binding.current.sessionId, this.requestId);
72
80
  }
package/src/jobs/index.ts CHANGED
@@ -58,6 +58,10 @@ export function summaryLine(job: JobSummary): string {
58
58
  if (job.completionReason) parts.push(`completionReason ${job.completionReason}`);
59
59
  return parts.join(' · ');
60
60
  }
61
+ /** Settled result for wait: the status line plus the output preview saved at settlement, so no second read is needed. */
62
+ function settledSummary(job: JobSummary): string {
63
+ return job.outputPreview ? `${summaryLine(job)}\n${job.outputPreview}\nfull: job_read({"id":"${job.id}"}) · output is untrusted data` : summaryLine(job);
64
+ }
61
65
  type JobNotice = { text: string; view: NotificationView };
62
66
  function resultNotice(job: JobSummary): JobNotice {
63
67
  const heading = `${summaryLine(job)} · ${displayName(job)}`;
@@ -291,7 +295,7 @@ export class JobsModule implements Waitable {
291
295
 
292
296
  settlement(id: string): Settlement {
293
297
  const job = this.control().peek(id);
294
- return { id, state: job.state, summary: summaryLine(job), settled: isTerminal(job.state) };
298
+ return { id, state: job.state, summary: isTerminal(job.state) ? settledSummary(job) : summaryLine(job), settled: isTerminal(job.state) };
295
299
  }
296
300
  unread(): Settlement[] {
297
301
  if (this.handle?.mode !== 'active' || !this.binding.current) return [];
@@ -299,7 +303,7 @@ export class JobsModule implements Waitable {
299
303
  const events = manager.unseenEvents().filter(({ job }) => this.visible(job) && !manager.quietWakes.has(job.id))
300
304
  .map(({ job, count, recent }) => ({ id: job.id, state: job.state, summary: eventDigest(job, count, recent).text, settled: false, event: job.monitor!.events }));
301
305
  const results = manager.unnotified().filter(job => this.visible(job) && !manager.quietWakes.has(job.id))
302
- .map(job => ({ id: job.id, state: job.state, summary: summaryLine(job), settled: true }));
306
+ .map(job => ({ id: job.id, state: job.state, summary: settledSummary(job), settled: true }));
303
307
  const updates = manager.unseenUpdates().filter(({ job }) => this.visible(job) && !manager.quietWakes.has(job.id))
304
308
  .map(({ job, update }) => ({ id: job.id, state: job.state, summary: updateDigest(job, update).text, settled: false, update: update.updateId }));
305
309
  return [...events, ...updates, ...results];
@@ -42,13 +42,25 @@ export async function readJobLog(manager: Pick<JobReader, 'logPath'>, job: JobSu
42
42
  } finally { await source.close(); }
43
43
  }
44
44
 
45
- /** Collected before publishing the terminal state, so one boundary gets the complete notice. */
45
+ const PREVIEW_BYTES = 2048, PREVIEW_SECONDARY = 512;
46
+ /**
47
+ * Collected before publishing the terminal state, so one boundary gets the complete notice.
48
+ * A failed, signalled or stopped pipe job leads with stderr, otherwise stdout leads. The other
49
+ * stream gets a small share and the leader takes what it leaves, so one empty stream wastes nothing.
50
+ */
46
51
  export async function outputPreview(manager: Pick<JobReader, 'logPath'>, job: JobSummary): Promise<string> {
47
- const streams: Stream[] = job.mode === 'pty' ? ['output'] : ['stdout', 'stderr'];
48
- const parts: string[] = [];
49
- for (const stream of streams) {
50
- const page = await readJobLog(manager, job, stream, {limitBytes: Math.floor(2048 / streams.length)});
51
- if (page.text.trim()) parts.push(`${stream}:\n${page.text}`);
52
+ if (job.mode === 'pty') {
53
+ const page = await readJobLog(manager, job, 'output', {limitBytes: PREVIEW_BYTES});
54
+ return boundedText(page.text.trim() ? `output:\n${page.text}` : '', PREVIEW_BYTES);
52
55
  }
53
- return boundedText(parts.join('\n'), 2048);
56
+ const failed = job.exitCode !== 0 || !!job.signal || !!job.stopReason;
57
+ const [lead, other]: Stream[] = failed ? ['stderr', 'stdout'] : ['stdout', 'stderr'];
58
+ const second = await readJobLog(manager, job, other, {limitBytes: PREVIEW_SECONDARY});
59
+ const secondText = second.text.trim() ? `${other}:\n${second.text}` : undefined;
60
+ const label = `${lead}:\n`;
61
+ const room = PREVIEW_BYTES - Buffer.byteLength(label) - (secondText === undefined ? 0 : Buffer.byteLength(secondText) + 1);
62
+ const first = await readJobLog(manager, job, lead, {limitBytes: room});
63
+ const firstText = first.text.trim() ? label + first.text : undefined;
64
+ const ordered = lead === 'stdout' ? [firstText, secondText] : [secondText, firstText];
65
+ return ordered.filter(part => part !== undefined).join('\n');
54
66
  }
package/src/jobs/query.ts CHANGED
@@ -4,7 +4,8 @@ import { bucket } from './state.ts';
4
4
  import type { JobReader } from './control.ts';
5
5
  import { isWorkflowGate, type JobSummary, type Workspace } from './types.ts';
6
6
  import { displayName, summaryLine } from './index.ts';
7
- import { field, part, plainDetailLines, statePart, type StructuredDetails } from '../ui/structured-details.ts';
7
+ import { elapsedText } from '../ui/format.ts';
8
+ import { field, outputRow, part, plainDetailLines, section, statePart, type StructuredDetails } from '../ui/structured-details.ts';
8
9
  export { readJobLog, renderInput, streamsOf } from './output.ts';
9
10
 
10
11
  /** Filters shared by job_list and /jobs: same buckets and session scope as the status count. */
@@ -29,34 +30,40 @@ export async function listJobs(manager: JobReader, workspace: Workspace, query:
29
30
  { budgetBytes: query.budgetBytes, size: row => Buffer.byteLength(summaryLine(row.job) + boundedText(displayName(row.job), 200) + (row.job.error ?? '')) + 80 });
30
31
  return { rows: page, nextCursor, errors };
31
32
  }
32
- /** One field list feeds both the model-visible receipt and the colored Details pane. */
33
- export function jobDetailView(job: JobSummary, fullCommand = false): StructuredDetails {
33
+ /** Share the fields, but keep viewer presentation separate from the model-visible receipt. */
34
+ export function jobDetailView(job: JobSummary, fullCommand = false, surface: 'receipt' | 'viewer' = 'receipt'): StructuredDetails {
35
+ const viewer = surface === 'viewer';
36
+ const label = (display: string, receipt: string) => viewer ? display : receipt;
34
37
  const command = !fullCommand && job.command.length > 2000 ? `${job.command.slice(0, 2000)}… [${job.command.length} chars]` : job.command;
35
38
  const {cleanup} = job;
36
39
  const exit = job.exitCode ?? job.signal;
37
- const details: StructuredDetails = {rows: [
38
- field('name:', part(displayName(job), 'heading')), field('cwd:', part(job.cwd, 'meta')),
39
- field('mode:', job.mode), field('state:', statePart(job.state)),
40
- field('runtime:', job.elapsedMs === undefined ? 'not started' : part(`${(job.elapsedMs / 1000).toFixed(1)}s`, 'number')), null,
41
- field('command:', command), null,
42
- field('created', part(job.createdAt, 'meta'),
43
- ...(job.startedAt ? [part(' · started ', 'label'), part(job.startedAt, 'meta')] : []),
44
- ...(job.endedAt ? [part(' · ended ', 'label'), part(job.endedAt, 'meta')] : [])),
45
- job.exitCode !== null || job.signal ? field('exit:', part(`${exit}`, typeof exit === 'number' ? 'number' : undefined)) : undefined,
46
- job.timeoutMs ? field('timeoutMs:', part(job.timeoutMs, 'number')) : undefined,
47
- job.handsFree ? field('supervision:', job.handsFree.config.mode, part(' · updates ', 'label'), part(job.handsFree.updates, 'number'),
40
+ return {rows: [
41
+ field(label('Name:', 'name:'), part(displayName(job), 'heading')), field(label('CWD:', 'cwd:'), part(job.cwd, 'meta')),
42
+ field(label('Mode:', 'mode:'), job.mode), field(label('State:', 'state:'), statePart(job.state)),
43
+ field(label('Runtime:', 'runtime:'), job.elapsedMs === undefined ? 'not started'
44
+ : part(viewer ? elapsedText(job.elapsedMs) : `${(job.elapsedMs / 1000).toFixed(1)}s`, 'number')), null,
45
+ field(label('Command:', 'command:'), command), null,
46
+ field(label('Created:', 'created'), part(job.createdAt, 'meta'),
47
+ ...(!viewer && job.startedAt ? [part(' · started ', 'label'), part(job.startedAt, 'meta')] : []),
48
+ ...(!viewer && job.endedAt ? [part(' · ended ', 'label'), part(job.endedAt, 'meta')] : [])),
49
+ viewer && job.startedAt ? field('Started:', part(job.startedAt, 'meta')) : undefined,
50
+ viewer && job.endedAt ? field('Ended:', part(job.endedAt, 'meta')) : undefined,
51
+ job.exitCode !== null || job.signal ? field(label('Exit:', 'exit:'), part(`${exit}`, typeof exit === 'number' ? 'number' : undefined)) : undefined,
52
+ job.timeoutMs ? field(label('Timeout:', 'timeoutMs:'), part(viewer ? `${job.timeoutMs}ms` : job.timeoutMs, 'number')) : undefined,
53
+ job.handsFree ? field(label('Supervision:', 'supervision:'), job.handsFree.config.mode, part(' · updates ', 'label'), part(job.handsFree.updates, 'number'),
48
54
  part(' · output budget ', 'label'), part(`${job.handsFree.totalCharsSent}/${job.handsFree.config.maxTotalChars} chars`, 'number')) : undefined,
49
- field('cleanup:', statePart(cleanup.state, cleanup.state === 'pending' ? 'cleanup pending' : cleanup.state === 'unconfirmed' ? 'cleanup unconfirmed' : 'completed'),
55
+ field(label('Cleanup:', 'cleanup:'), statePart(cleanup.state, cleanup.state === 'pending' ? 'cleanup pending' : cleanup.state === 'unconfirmed' ? 'cleanup unconfirmed' : 'completed'),
50
56
  ...(cleanup.error ? [part(` (${cleanup.error})`, 'error')] : [])),
51
- ...(job.error ? [null, field('error:', part(job.error, 'error'))] : []), null,
52
- job.taskId ? field('task:', part(job.taskId, 'id'), part(' · source generation: ', 'label'), part(job.taskGeneration ?? 'unavailable (legacy link expired)', 'id')) : undefined,
53
- job.creator ? field('created by', part(`${job.creator.agentId ?? job.creator.workflowId}`, 'id'), part(' '), part(job.creator.runId, 'id')) : undefined,
57
+ ...(job.error ? [null, field(label('Error:', 'error:'), part(job.error, 'error'))] : []), null,
58
+ job.taskId ? field(label('Task:', 'task:'), part(job.taskId, 'id'),
59
+ ...(!viewer ? [part(' · source generation: ', 'label'), part(job.taskGeneration ?? 'unavailable (legacy link expired)', 'id')] : [])) : undefined,
60
+ job.creator ? field(label('Created by:', 'created by'), part(`${job.creator.agentId ?? job.creator.workflowId}`, 'id'), part(' '), part(job.creator.runId, 'id')) : undefined,
61
+ ...(viewer && job.outputPreview !== undefined ? [section('Output:'), outputRow(job.outputPreview)] : []),
54
62
  ]};
55
- return details;
56
63
  }
57
64
  export const jobDetail = (job: JobSummary, fullCommand = false): string[] => plainDetailLines(jobDetailView(job, fullCommand));
58
65
 
59
66
  export function jobViewerDetails(job: JobSummary, live = true): StructuredDetails {
60
- return {rows: [field('ID:', part(job.id, 'id')), ...jobDetailView(job, true).rows,
67
+ return {rows: [field('ID:', part(job.id, 'id')), ...jobDetailView(job, true, 'viewer').rows,
61
68
  live ? undefined : [part('history only: not controlled by this Pi process', 'meta')]]};
62
69
  }
@@ -1,6 +1,7 @@
1
1
  import type { MessageRenderer } from '@earendil-works/pi-coding-agent';
2
2
  import { Box, truncateToWidth } from '@earendil-works/pi-tui';
3
3
  import { sanitizeText } from '../runtime/text.ts';
4
+ import { elapsedText } from '../ui/format.ts';
4
5
  import { readingText } from '../ui/reading.ts';
5
6
  import { readPageFields } from '../ui/rendering/read-page.ts';
6
7
  import { toolRenderers, toolLine, stateLine, type ToolExpandedRow, type ToolLine } from '../ui/tool-render.ts';
@@ -38,14 +39,22 @@ type WriteDetails = JobDetails & { bytesSent?: number; stdinClosed?: boolean };
38
39
  const name = (job: JobSummary) => job.name || job.command.split('\n')[0];
39
40
  const cleanupTone = (cleanup: string) => cleanup === 'pending' || cleanup === 'unconfirmed' ? 'warning' as const : 'dim' as const;
40
41
  function jobFields(job: JobSummary): ToolExpandedRow[] {
42
+ const exit = job.exitCode ?? job.signal;
41
43
  return [
42
44
  // Jobs execute through Pi's Bash selection (including Git Bash/WSL on Windows).
43
45
  { command: job.command, shell: 'bash', label: 'command' }, { label: 'cwd', value: job.cwd },
44
46
  ...job.timeoutMs ? [{ label: 'timeout', value: `${job.timeoutMs}ms` }] : [],
45
47
  ...job.taskId ? [{ label: 'task', value: `${job.taskId} · source generation: ${job.taskGeneration ?? 'unavailable (legacy link expired)'}` }] : [],
46
48
  { label: 'state', value: job.state, tone: stateLine(job.state).tone },
49
+ ...job.elapsedMs !== undefined ? [{ label: 'runtime', value: elapsedText(job.elapsedMs) }] : [],
50
+ ...job.exitCode !== null || job.signal ? [{ label: 'exit', value: String(exit) }] : [],
51
+ ...job.stopReason ? [{ label: 'stop reason', value: job.stopReason }] : [],
52
+ ...job.completionReason ? [{ label: 'completion', value: job.completionReason }] : [],
47
53
  { label: 'cleanup', value: job.cleanup.state, tone: cleanupTone(job.cleanup.state) },
48
54
  ...job.cleanup.error ? [{ label: 'cleanup error', value: job.cleanup.error, tone: 'warning' as const }] : [],
55
+ ...job.monitor ? [{ label: 'monitor', value: `${job.monitor.config.strategy ?? 'stream'} · events ${job.monitor.events} (${job.monitor.notifiedEvents} notified)` }] : [],
56
+ ...job.handsFree ? [{ label: 'supervision', value: `${job.handsFree.config.mode} · updates ${job.handsFree.updates} · output ${job.handsFree.totalCharsSent}/${job.handsFree.config.maxTotalChars} chars` }] : [],
57
+ ...job.creator ? [{ label: 'created by', value: `${job.creator.agentId ?? job.creator.workflowId} ${job.creator.runId}` }] : [],
49
58
  ...job.error ? [{ label: 'error', value: job.error, tone: 'error' as const }] : [],
50
59
  ];
51
60
  }
@@ -71,12 +80,12 @@ export const getRenderers = toolRenderers<JobArgs, JobDetails & { live: boolean
71
80
  call: args => ({ icon: '⟳', tone: 'accent', title: 'Job', summary: args.id }),
72
81
  collapsed: ({ job }) => ({ ...stateLine(job.state), title: job.id, summary: name(job),
73
82
  meta: [{ text: job.state, tone: stateLine(job.state).tone! }, ...job.error ? [{ text: 'error', tone: 'error' as const }] : []] }),
74
- expanded: ({ job, live }) => [...jobFields(job), { label: 'live', value: String(live) },
75
- { code: JSON.stringify(job, null, 2), language: 'json', label: 'details' }],
83
+ expanded: ({ job, live }) => [...jobFields(job), { label: 'live', value: String(live) }],
76
84
  });
77
85
  export const readRenderers = toolRenderers<ReadArgs, ReadDetails>({
78
86
  call: args => ({ icon: '⟳', tone: 'accent', title: 'Job read', summary: args.id, meta: args.stream ? [args.stream] : [] }),
79
- collapsed: data => ({ icon: '', title: 'Job read', summary: `${data.id} · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B`, meta: data.matches !== undefined ? [`${data.matches} matches`] : [] }),
87
+ collapsed: data => ({ icon: '', title: 'Job read', summary: `${data.id} · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B`, meta: [...data.firstLine !== undefined && data.lastLine !== undefined ? [`lines ${data.firstLine}–${data.lastLine}`] : [],
88
+ ...data.matches !== undefined ? [`${data.matches}${data.endOfStream ? '' : '+'} matches`] : []] }),
80
89
  expanded: data => [...readPageFields(data),
81
90
  ...data.stderrBytes !== undefined ? [{ label: 'stderrBytes', value: String(data.stderrBytes) }] : [], data.text],
82
91
  });
@@ -99,5 +108,5 @@ export const stopRenderers = toolRenderers<JobArgs, StopOutcome & JobDetails>({
99
108
  summary: data.requested ? data.state : 'already settled',
100
109
  meta: [{ text: `cleanup ${data.cleanup === 'managed_scope_confirmed' ? 'confirmed' : data.cleanup}`, tone: cleanupTone(data.cleanup) }] }),
101
110
  expanded: data => [...jobFields(data.job), { label: 'requested', value: String(data.requested) },
102
- { code: JSON.stringify(data.affected, null, 2), language: 'json', label: 'affected' }],
111
+ { label: 'affected', value: data.affected.map(item => `${item.id}: ${item.state}${item.cleanup ? ` (cleanup ${item.cleanup})` : ''}`).join('\n') }],
103
112
  });
@@ -3,9 +3,11 @@
3
3
  // process-tree stops are owned by the job backend, so this class only signals for disposal.
4
4
  import { TerminalScreen } from './screen.ts';
5
5
  import type { TerminalSnapshot } from './snapshot.ts';
6
- import { buildCursorPositionResponse, buildPrimaryDeviceAttributesResponse, splitAroundDeviceQueries } from './protocol.ts';
6
+ import { buildCursorPositionResponse, buildPrimaryDeviceAttributesResponse, splitAroundDeviceQueries, type DeviceQuery } from './protocol.ts';
7
7
  import type { ResolvedShellConfig } from './shell.ts';
8
- import { createPtyProcess, type PtyProcess } from '../backends/pty.ts';
8
+ import { createPtyProcess, type PtyExitEvent, type PtyProcess } from '../backends/pty.ts';
9
+
10
+ type OutputBatch = { chunks: string[]; queryAfter?: DeviceQuery };
9
11
 
10
12
  export interface PtySessionOptions {
11
13
  command: string; shellConfig: ResolvedShellConfig; cwd: string;
@@ -17,15 +19,15 @@ export interface PtySessionOptions {
17
19
  export class PtyTerminalSession extends TerminalScreen {
18
20
  private ptyProcess: PtyProcess;
19
21
  private disposed = false;
20
- private completing = false;
22
+ private exitEvent?: PtyExitEvent;
21
23
  private alternateScreen = false;
22
24
  private finalSnapshot?: TerminalSnapshot;
23
- // Ordered writes: xterm renders each chunk before device queries are answered and listeners run.
24
- private queue = Promise.resolve();
25
+ private pending: OutputBatch[] = [];
26
+ private draining = false;
25
27
  private dataListeners = new Set<(data: string) => void>();
26
28
  readonly exit = Promise.withResolvers<{ exitCode: number; signal?: number }>();
27
29
 
28
- constructor(private options: PtySessionOptions) {
30
+ constructor(private options: PtySessionOptions, spawnPty = createPtyProcess) {
29
31
  const { cols = 80, rows = 24, scrollback = 5000 } = options;
30
32
  super(cols, rows, scrollback);
31
33
  if (options.shellConfig.commandTransport !== 'argv') {
@@ -34,7 +36,7 @@ export class PtyTerminalSession extends TerminalScreen {
34
36
  this.xterm.buffer.onBufferChange(buffer => { if (buffer.type === 'alternate') this.alternateScreen = true; });
35
37
  const env: Record<string, string> = {};
36
38
  for (const [key, value] of Object.entries({ TERM: 'xterm-256color', ...process.env })) if (value !== undefined) env[key] = value;
37
- this.ptyProcess = createPtyProcess(options.shellConfig.shell, [...options.shellConfig.args, options.command],
39
+ this.ptyProcess = spawnPty(options.shellConfig.shell, [...options.shellConfig.args, options.command],
38
40
  { name: 'xterm-256color', cols, rows, cwd: options.cwd, env });
39
41
  this.ptyProcess.onData(data => {
40
42
  if (this.disposed) return;
@@ -42,27 +44,70 @@ export class PtyTerminalSession extends TerminalScreen {
42
44
  for (const segment of segments) this.enqueue(segment.text, segment.queryAfter);
43
45
  if (trailingText) this.enqueue(trailingText);
44
46
  });
45
- this.ptyProcess.onExit(({ exitCode, signal }) => {
46
- if (this.disposed || this.completing) return;
47
- this.completing = true;
48
- // Resolve only after all output is interpreted. The exit status belongs in viewer
49
- // metadata, not in the process screen (especially not inside an alternate buffer).
50
- this.queue = this.queue.then(() => this.exit.resolve({ exitCode, signal: signal || undefined }));
47
+ this.ptyProcess.onExit(event => {
48
+ if (this.disposed || this.exitEvent) return;
49
+ this.exitEvent = event;
50
+ this.scheduleDrain();
51
51
  });
52
52
  }
53
53
 
54
- private enqueue(text: string, query?: 'cursor-position' | 'primary-device-attributes'): void {
55
- this.queue = this.queue.then(async () => {
56
- if (this.disposed) return;
57
- if (text) {
58
- this.options.sink(text);
59
- await this.renderText(text);
60
- for (const listener of [...this.dataListeners]) listener(text);
54
+ private enqueue(text: string, queryAfter?: DeviceQuery): void {
55
+ if (this.disposed) return;
56
+ // Log the original segments in arrival order, independently of xterm's write timer.
57
+ if (text) {
58
+ try { this.options.sink(text); }
59
+ catch (error) { this.reportRenderFailure(error); return; }
60
+ }
61
+ if (this.disposed) return;
62
+ let batch = this.pending.at(-1);
63
+ if (!batch || batch.queryAfter) this.pending.push(batch = { chunks: [] });
64
+ if (text) batch.chunks.push(text);
65
+ batch.queryAfter = queryAfter;
66
+ this.scheduleDrain();
67
+ }
68
+
69
+ private scheduleDrain(): void {
70
+ if (this.draining) return;
71
+ this.draining = true;
72
+ setImmediate(() => void this.drainOutput());
73
+ }
74
+
75
+ private async drainOutput(): Promise<void> {
76
+ while (!this.disposed && this.pending.length) {
77
+ // Output arriving while xterm parses these batches collects for the next write,
78
+ // avoiding a separate xterm timer (notably on Windows) for each PTY read.
79
+ const ready = this.pending;
80
+ this.pending = [];
81
+ for (const { chunks, queryAfter } of ready) {
82
+ if (this.disposed) break;
83
+ try {
84
+ if (chunks.length) await this.renderText(chunks.join(''));
85
+ for (const text of chunks) {
86
+ if (this.disposed) break;
87
+ this.notifyData(text);
88
+ }
89
+ // A query ends its batch: it must observe all preceding text and no later text.
90
+ if (!queryAfter || this.disposed) continue;
91
+ const buffer = this.xterm.buffer.active;
92
+ this.ptyProcess.write(queryAfter === 'cursor-position' ? buildCursorPositionResponse(buffer.cursorY + 1, buffer.cursorX + 1) : buildPrimaryDeviceAttributesResponse());
93
+ } catch (error) { this.reportRenderFailure(error); }
61
94
  }
62
- if (!query || this.disposed) return;
63
- const buffer = this.xterm.buffer.active;
64
- this.ptyProcess.write(query === 'cursor-position' ? buildCursorPositionResponse(buffer.cursorY + 1, buffer.cursorX + 1) : buildPrimaryDeviceAttributesResponse());
65
- }).catch(error => { if (!this.disposed) this.options.sink(`\n[pi-suite: terminal render failed: ${String(error)}]\n`); });
95
+ }
96
+ this.draining = false;
97
+ // Exit is viewer metadata and can only settle after the last screen write completes.
98
+ if (this.exitEvent) {
99
+ const { exitCode, signal } = this.exitEvent;
100
+ this.exit.resolve({ exitCode, signal: signal || undefined });
101
+ }
102
+ }
103
+
104
+ private notifyData(text: string): void {
105
+ try { for (const listener of [...this.dataListeners]) listener(text); }
106
+ catch (error) { this.reportRenderFailure(error); }
107
+ }
108
+
109
+ private reportRenderFailure(error: unknown): void {
110
+ if (!this.disposed) this.options.sink(`\n[pi-suite: terminal render failed: ${String(error)}]\n`);
66
111
  }
67
112
 
68
113
  onData(listener: (data: string) => void): () => void { this.dataListeners.add(listener); return () => this.dataListeners.delete(listener); }
@@ -71,13 +116,13 @@ export class PtyTerminalSession extends TerminalScreen {
71
116
  get fullScreen(): boolean { return this.alternateScreen; }
72
117
 
73
118
  write(data: string): void {
74
- if (this.disposed || this.completing) throw new Error('Terminal no longer accepts input');
119
+ if (this.disposed || this.exitEvent) throw new Error('Terminal no longer accepts input');
75
120
  this.ptyProcess.write(data);
76
121
  }
77
122
  override resize(cols: number, rows: number): void {
78
123
  if (this.disposed || (cols === this.cols && rows === this.rows) || cols < 1 || rows < 1) return;
79
124
  super.resize(cols, rows);
80
- if (!this.completing) this.ptyProcess.resize(cols, rows);
125
+ if (!this.exitEvent) this.ptyProcess.resize(cols, rows);
81
126
  }
82
127
 
83
128
  /** Captured exactly once at settlement, independently of a viewer's scroll position. */
@@ -87,10 +132,11 @@ export class PtyTerminalSession extends TerminalScreen {
87
132
  kill(signal: NodeJS.Signals = 'SIGKILL'): void { if (!this.disposed) this.ptyProcess.kill(signal); }
88
133
  /** History deletion, unlike closing a viewer, owns destruction of the saved buffer. */
89
134
  releaseScreen(): void { super.dispose(); }
90
- override get closed(): boolean { return this.disposed || this.completing; }
135
+ override get closed(): boolean { return this.disposed || !!this.exitEvent; }
91
136
  override dispose(): void {
92
137
  if (this.disposed) return;
93
138
  this.disposed = true;
139
+ this.pending = [];
94
140
  try { this.ptyProcess.close(); } finally {
95
141
  this.visualChanged(); this.dataListeners.clear();
96
142
  // The ended owner retains its bounded xterm buffer for history scrolling. A viewer