pi-suite 0.3.3 → 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.
package/README.md CHANGED
@@ -61,12 +61,30 @@ A two-level task list (groups and child tasks) that the model maintains and the
61
61
 
62
62
  The Dock shows the goal, tasks, subagents, jobs and workflows; press ← in an empty editor to select a row. `/tasks`, `/jobs` and `/subagents` share one browser layout, whose detail pane colors names, IDs, states and errors.
63
63
 
64
- Each suite tool call and notification takes one line and expands to labeled fields; a failed tool shows the first line of its error. Results from all modules are merged into one notification per wake-up and delivered only to the session that owns the work.
65
-
66
- Commands in Pi's built-in `bash` / `powershell` calls and in jobs are highlighted by structure: program, options, variables, strings, operators and redirections. The highlighter only scans the text and never runs the command.
64
+ | The Dock | `/subagents` | Subagent transcript |
65
+ | :---: | :---: | :---: |
66
+ | ![The Dock shows the task tree above running subagents](docs/img/dock.png) | ![The /subagents browser with the run list on the left and details on the right](docs/img/subagent_list.png) | ![A subagent transcript with tool calls and their output](docs/img/subagent_page.png) |
67
+ | A task tree with group progress, and the subagents running for it. | Runs on the left; model, tokens, runtime, input and output on the right. | View the subagent's tool calls and their output. |
67
68
 
68
69
  The package also includes the `oh-my-pi` dark theme, and makes Pi's copy work inside tmux through OSC 52. See [Interface](docs/en/interface.md).
69
70
 
71
+ ## OpenAI Responses recovery
72
+
73
+ Some OpenAI Responses endpoints, typically behind a gateway that switches between upstream accounts, reject a request because the history was created under another account. Without help, the session keeps failing on the same history.
74
+
75
+ Off by default. Set `runtime.openAIResponsesAutoRecovery` to `true` (or toggle it in `/suite`) and run `/reload`. The suite then repairs the history and continues automatically in two cases:
76
+
77
+ - **Item IDs from another resource.** The endpoint reports a resource, ownership or missing-dependency error. The suite removes the upstream `id` from the history items that the failed request carried.
78
+ - **Encrypted reasoning that can't be decrypted.** The suite drops the reasoning items that the new account cannot verify and removes the upstream IDs from the other items. Reasoning produced afterwards is replayed as usual.
79
+
80
+ Messages, tool calls and tool outputs stay intact. The original history stays on disk; the failed message is only hidden from the model's context. The main session and subagents are both covered, and an active goal keeps its progress while the repair runs.
81
+
82
+ Recovery is conservative: it only acts on `openai-responses` models, only when the failed request can be replayed on its own, and never when the response already produced content or tool calls, so side effects are not repeated. Rate limits, auth and quota errors, context overflow and ordinary schema errors are left alone. Retries use Pi's own retry budget. Details are in [OpenAI Responses recovery](docs/en/configuration.md#openai-responses-recovery).
83
+
84
+ ## Reminders
85
+
86
+ When an agent finishes its work and the terminal is not in the foreground, a reminder notification is sent automatically. How it appears depends on the terminal, and you can turn it off in the settings (`/suite`).
87
+
70
88
  ## Commands
71
89
 
72
90
  | Command | What it does |
@@ -91,6 +109,7 @@ No configuration is required. Optional settings live in `~/.pi/agent/pi-suite.js
91
109
  | `ask.timeout` | `600000` | Default `ask_user` idle timeout in ms; `0` waits forever. |
92
110
  | `goal.display`, `agents.display`, `jobs.display` | `status` | Show the summary in the footer status, the Dock, or nowhere. |
93
111
  | `tasks.reminders` | `true` | Remind the model when it has not updated tasks for several turns. |
112
+ | `notify.enabled` | `true` | Enable notifications. |
94
113
  | `agents.maxConcurrent` | `10` | Background subagent concurrency limit. |
95
114
  | `agents.maxDepth` | `3` | Maximum session depth, including the main session. |
96
115
  | `agents.defaultModel`, `agents.types` | unset | Default subagent model; per-type model, thinking and enabled overrides. |
package/README.zh-CN.md CHANGED
@@ -61,12 +61,30 @@ job 以 pipe 或 PTY 模式在后台运行命令。模型可以分段读取有
61
61
 
62
62
  Dock 显示目标、任务、子代理、job 和 workflow;在空编辑器中按 ← 可选择某一行。`/tasks`、`/jobs` 和 `/subagents` 使用同一种浏览布局,详情面板为名称、ID、状态和错误着色。
63
63
 
64
- 每个套件工具调用和通知只占一行,展开后显示带标签的字段;工具失败时折叠行显示错误的第一行。各模块的结果每次唤醒合并为一条通知,只投递给拥有该工作的会话。
65
-
66
- Pi 内置 `bash` / `powershell` 调用和 job 中的命令按结构高亮:程序、选项、变量、字符串、运算符和重定向。高亮只扫描文本,从不执行命令。
64
+ | Dock | `/subagents` | 子代理会话 |
65
+ | :---: | :---: | :---: |
66
+ | ![Dock 显示任务树和运行中的子代理](docs/img/dock.png) | ![/subagents 浏览器,左侧是运行列表,右侧是详情](docs/img/subagent_list.png) | ![子代理会话,包含工具调用及其输出](docs/img/subagent_page.png) |
67
+ | 带分组进度的任务树,以及为任务运行的子代理。 | 左侧是运行列表,右侧是模型、token、运行时间、输入和输出。 | 可查看子代理的工具调用及其输出。 |
67
68
 
68
69
  扩展包还提供深色主题 `oh-my-pi`,并使 Pi 的复制在 tmux 中经 OSC 52 转发到本地终端。见[界面](docs/zh/interface.md)。
69
70
 
71
+ ## OpenAI Responses 故障自动恢复
72
+
73
+ 部分 OpenAI Responses 端点(通常是会在多个上游账号之间切换的网关)会因为历史由另一个账号创建而拒绝请求。不处理的话,会话会一直在同一段历史上失败。
74
+
75
+ 默认关闭。把 `runtime.openAIResponsesAutoRecovery` 设为 `true`(也可在 `/suite` 中切换)并执行 `/reload` 后,套件会在以下两种情况自动修复历史并继续:
76
+
77
+ - **来自其他资源的 item ID。** 端点返回资源、归属或依赖缺失错误时,移除失败请求所带历史项的上游 `id`。
78
+ - **无法解密的加密 reasoning。** 丢弃新账号无法验证的 reasoning 项,并移除其余历史项的上游 ID;之后产生的新 reasoning 照常重放。
79
+
80
+ 正文、工具调用和工具输出保持原样。原始历史仍保留在磁盘上,失败消息只是不再进入模型上下文。主会话和子代理都受保护,修复期间进行中的 goal 保留进度。
81
+
82
+ 恢复策略偏保守:只作用于 `openai-responses` 模型,只在失败请求可独立重放时进行,响应已产生正文或工具调用时不重试,避免重复副作用。限流、认证、额度、上下文超限和普通 schema 错误不处理。重试沿用 Pi 自身的重试预算。详见 [OpenAI Responses 恢复](docs/zh/configuration.md#openai-responses-恢复)。
83
+
84
+ ## 提醒
85
+
86
+ 在agent完成工作且终端没有位于前台时,会自动发送提醒通知,具体通知形式因不同终端而异,可在设置(`/suite`)中取消通知。
87
+
70
88
  ## 命令
71
89
 
72
90
  | 命令 | 作用 |
@@ -91,6 +109,7 @@ Pi 内置 `bash` / `powershell` 调用和 job 中的命令按结构高亮:程
91
109
  | `ask.timeout` | `600000` | `ask_user` 的默认空闲超时(毫秒),`0` 为一直等待。 |
92
110
  | `goal.display`、`agents.display`、`jobs.display` | `status` | 摘要显示在 footer 状态、Dock 还是隐藏。 |
93
111
  | `tasks.reminders` | `true` | 模型多轮未更新任务时附加提醒。 |
112
+ | `notify.enabled` | `true` | 启用通知。 |
94
113
  | `agents.maxConcurrent` | `10` | 后台子代理并发上限。 |
95
114
  | `agents.maxDepth` | `3` | 子代理最大嵌套层数(含主会话)。 |
96
115
  | `agents.defaultModel`、`agents.types` | 未设置 | 子代理默认模型;按类型覆盖模型、thinking 和启用状态。 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-suite",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Custom modular Pi extension suite",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,11 +30,14 @@ export function agentSummary(record: AgentRecord) {
30
30
  export function usageText({ usage }: Pick<AgentRecord, 'usage'>, prefix = 'usage: '): string | undefined {
31
31
  return usage && `${prefix}input ${usage.tokens.input} · output ${usage.tokens.output} · cacheRead ${usage.tokens.cacheRead} · cacheWrite ${usage.tokens.cacheWrite} · total ${usage.tokens.total} · cost $${usage.cost.toFixed(6)}`;
32
32
  }
33
- function resultLines(record: AgentRecord, error = record.error): string[] {
34
- return [record.error ? usageText(record) : undefined, record.error ? `error: ${error}` : undefined,
35
- record.result === undefined ? undefined : boundedText(record.result, 2048),
33
+ /** Final result text, bounded to 2048 bytes, with the agent_read call that returns all of it. */
34
+ export function resultBody(record: AgentRecord): string[] {
35
+ return [record.result === undefined ? undefined : boundedText(record.result, 2048),
36
36
  record.result && Buffer.byteLength(record.result) > 2048 ? `full: agent_read({"id":"${record.id}","runId":"${record.runId}","stream":"result","offset":0})` : undefined].filter(value => value !== undefined);
37
37
  }
38
+ function resultLines(record: AgentRecord, error = record.error): string[] {
39
+ return [record.error ? usageText(record) : undefined, record.error ? `error: ${error}` : undefined, ...resultBody(record)].filter(value => value !== undefined);
40
+ }
38
41
  function resultSummary(record: AgentRecord): string { return [summaryLine(record), ...resultLines(record)].join('\n'); }
39
42
  function providerErrorMessage(error: string): string {
40
43
  // Provider errors may be plain text or a JSON envelope prefixed with the HTTP status.
@@ -74,7 +74,8 @@ export const getRenderers = toolRenderers<Args & { detail?: boolean }, Details &
74
74
  });
75
75
  export const readRenderers = toolRenderers<Args & { stream?: string }, Details & ReadPage & { stream: string }>({
76
76
  call: args => ({ icon: '⟳', tone: 'accent', title: 'Agent read', summary: agentDisplayName(args.id, args.runId), meta: args.stream ? [args.stream] : [] }),
77
- collapsed: data => ({ icon: '', title: data.agent.name, summary: `read · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B` }),
77
+ collapsed: data => ({ icon: '', title: data.agent.name, summary: `read · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B`,
78
+ meta: data.firstLine !== undefined && data.lastLine !== undefined ? [`lines ${data.firstLine}–${data.lastLine}`] : [] }),
78
79
  expanded: data => [...readPageFields(data), data.text], // Transcript and log text are literal, never Markdown or inferred code.
79
80
  });
80
81
  export const sendRenderers = toolRenderers<Args, Details & { action: string }>({
@@ -2,14 +2,14 @@ import type { ExtensionAPI, ToolDefinition } from '@earendil-works/pi-coding-age
2
2
  import { Type } from 'typebox';
3
3
  import type { SuiteConfig } from '../runtime/config.ts';
4
4
  import { ToolError } from '../runtime/errors.ts';
5
- import { readBounded, readContinuation, textSource } from '../runtime/read.ts';
5
+ import { pageNote, readBounded, readContinuation, textSource } from '../runtime/read.ts';
6
6
  import { sanitizeText } from '../runtime/text.ts';
7
7
  import { checkedArguments, LIST_LIMITS, listFields, objectId, paginate, readFields, registerBoundTool, rejectContextWithoutSearch, textResult as text } from '../runtime/tools.ts';
8
8
  import type { WaitRegistry } from '../runtime/wait.ts';
9
9
  import { childId, generationSchema } from '../tasks/types.ts';
10
10
  import { thinkingSchema } from './schema.ts';
11
11
  import { questionText } from './questions.ts';
12
- import { AgentsModule, agentSummary, summaryLine, usageText } from './index.ts';
12
+ import { AgentsModule, agentSummary, resultBody, summaryLine, usageText } from './index.ts';
13
13
  import { active, executing, recordWorkspace } from './types.ts';
14
14
  import { transcript, transcriptText } from './records.ts';
15
15
  import type { AgentScheduler } from './schedules/index.ts';
@@ -109,14 +109,15 @@ export function registerAgentTools(pi: ExtensionAPI, agents: AgentsModule, waits
109
109
  nextCursor ? `more: agent_list(${JSON.stringify({ ...params, cursor: nextCursor })})` : undefined], { agents: page.map(agentSummary), nextCursor });
110
110
  } }, 'initial');
111
111
  registerBoundTool(pi, { name: 'agent_get', ...getRenderers, label: 'Agent',
112
- description: 'Inspect the current run or a specific runId, including pending questions. Set detail:true for model sources, context, usage, and active jobs. Find run IDs with agent_list; read output with agent_read.',
112
+ description: 'Inspect the current run or a specific runId, including pending questions and, once it has ended, its result (up to 2 KiB; more with agent_read). Set detail:true for model sources, context, usage, and active jobs. Find run IDs with agent_list; read output with agent_read.',
113
113
  parameters: getSchema, prepareArguments: checkedArguments(getSchema, queryHint),
114
114
  async execute(_id, params, signal, _update, ctx) {
115
115
  const scope = agents.scope(ctx), { record, run } = await agents.manager.lookup(params.id, scope, config(), params.runId, signal);
116
116
  const lines = [summaryLine(record) + (!agents.manager.visible(record, scope) ? ' · read-only' : ''),
117
117
  `model: ${record.model} · thinking: ${record.thinking} · turns ${record.turns ?? 0} · tools ${record.toolUses ?? 0}${record.taskId ? ` · task ${record.taskId} @ ${record.taskGeneration ?? 'unavailable (assignment expired)'}` : ''}`,
118
118
  record.activity ? `activity: ${record.activity}` : undefined, record.error,
119
- run?.question ? questionText(run) : undefined];
119
+ run?.question ? questionText(run) : undefined,
120
+ ...!active(record.state) && record.result ? ['result (untrusted data):', ...resultBody(record)] : []];
120
121
  let created: JobSummary[] = [], jobsUnavailable: string | undefined;
121
122
  if (params.detail) {
122
123
  lines.push(`sources: model ${record.modelSource} · thinking ${record.thinkingSource}`, usageText(record),
@@ -134,7 +135,7 @@ export function registerAgentTools(pi: ExtensionAPI, agents: AgentsModule, waits
134
135
  waitingFor: run?.question ? 'parent' : undefined });
135
136
  } }, 'initial');
136
137
  registerBoundTool(pi, { name: 'agent_read', ...readRenderers, label: 'Read agent',
137
- description: 'Read output without resuming. stream defaults to transcript until the run ends, then result. Pass runId for an earlier run. Byte paging and regex search work like job_read.',
138
+ description: 'Read output without resuming. stream defaults to transcript until the run ends, then result. Pass runId for an earlier run. Line paging (line, lines; negative line counts from the end), byte offset and regex search work like job_read.',
138
139
  parameters: Type.Object({ id, runId: Type.Optional(runId), stream: Type.Optional(Type.Union([Type.Literal('result'), Type.Literal('transcript')])), ...readFields }, { additionalProperties: false }),
139
140
  async execute(_id, params, signal, _update, ctx) {
140
141
  rejectContextWithoutSearch(params);
@@ -142,7 +143,7 @@ export function registerAgentTools(pi: ExtensionAPI, agents: AgentsModule, waits
142
143
  const output = stream === 'transcript' ? transcriptText(transcript(record, run)) : [record.error, record.result].filter(Boolean).join('\n');
143
144
  const page = await readBounded(textSource(output), params, sanitizeText);
144
145
  if (!active(record.state)) agents.consume({ id: record.id, runId: record.runId, state: record.state, summary: summaryLine(record), settled: true });
145
- return text([`${summaryLine(record)} · ${stream} bytes ${page.offset}-${page.nextOffset} of ${page.totalBytes}`, page.text,
146
+ return text([`${summaryLine(record)} · ${stream} bytes ${page.offset}-${page.nextOffset} of ${page.totalBytes}${pageNote(page)}`, page.text,
146
147
  page.truncated ? `full: agent_read(${JSON.stringify({ id: record.id, runId: record.runId, stream, ...readContinuation(params, 0) })})` : undefined,
147
148
  page.endOfStream ? undefined : `more: agent_read(${JSON.stringify({ id: record.id, runId: record.runId, stream, ...readContinuation(params, page.nextOffset) })})`], { ...page, stream, agent: agentSummary(record) });
148
149
  } }, 'initial');
@@ -25,7 +25,7 @@ export function agentDetails(record: AgentRecord, permissions?: {readonly: boole
25
25
  field('Created:', part(record.createdAt, 'meta')),
26
26
  record.startedAt ? field('Started:', part(record.startedAt, 'meta')) : undefined,
27
27
  ...(record.taskId || record.workflowId ? [null,
28
- 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,
29
29
  record.workflowId ? field('Workflow:', part(record.workflowId, 'id')) : undefined, null,
30
30
  ] : []),
31
31
  record.endedAt ? field('Ended:', part(record.endedAt, 'meta')) : undefined,
@@ -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
  });
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);
@@ -349,11 +351,13 @@ export class AskView extends Container {
349
351
  ], this.height);
350
352
  }
351
353
  override render(width: number): string[] {
354
+ if (this.closed) return [];
352
355
  if (!this.started) {
356
+ if (this.signal?.aborted) { this.abort(); return []; }
353
357
  this.started = true;
354
- if (this.signal?.aborted) this.abort();
355
- else if (this.timeout > 0) {
356
- // 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) {
357
361
  this.touch(); this.countdown = setInterval(() => this.tui.requestRender(), 1000);
358
362
  }
359
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
  }
@@ -84,7 +84,8 @@ export const getRenderers = toolRenderers<JobArgs, JobDetails & { live: boolean
84
84
  });
85
85
  export const readRenderers = toolRenderers<ReadArgs, ReadDetails>({
86
86
  call: args => ({ icon: '⟳', tone: 'accent', title: 'Job read', summary: args.id, meta: args.stream ? [args.stream] : [] }),
87
- 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`] : []] }),
88
89
  expanded: data => [...readPageFields(data),
89
90
  ...data.stderrBytes !== undefined ? [{ label: 'stderrBytes', value: String(data.stderrBytes) }] : [], data.text],
90
91
  });
@@ -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