pi-agent-ide 0.5.0 → 0.5.1

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 (93) hide show
  1. package/README.md +74 -22
  2. package/assets/gallery/apply-editing.png +0 -0
  3. package/assets/gallery/debugging.png +0 -0
  4. package/assets/gallery/read-web.png +0 -0
  5. package/assets/gallery/search-replace.png +0 -0
  6. package/assets/gallery/terminal.png +0 -0
  7. package/assets/gallery/tool-editing.png +0 -0
  8. package/dist/chunk-7ALCBKCW.js +26 -0
  9. package/dist/{chunk-ZUMN6U77.js → chunk-IRECDTJG.js} +1 -1
  10. package/dist/chunk-NZYDMBM6.js +1 -0
  11. package/dist/chunk-P7XO5CIP.js +2 -0
  12. package/dist/entry-47.js +10 -10
  13. package/dist/entry-48.js +1 -1
  14. package/dist/entry-76.js +3 -1
  15. package/dist/pi-agent-ide.js +1 -1
  16. package/docs/development.md +0 -6
  17. package/node_modules/pi-agent-doctor/package.json +1 -1
  18. package/node_modules/pi-agent-filesystem/package.json +6 -6
  19. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  20. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  21. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  22. package/node_modules/pi-agent-ide-ast/package.json +9 -9
  23. package/node_modules/pi-agent-ide-changes/package.json +6 -6
  24. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  25. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  26. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  27. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  28. package/node_modules/pi-agent-image/package.json +2 -2
  29. package/node_modules/pi-agent-invariant/package.json +1 -1
  30. package/node_modules/pi-agent-pdf/package.json +2 -2
  31. package/node_modules/pi-agent-read/package.json +6 -6
  32. package/node_modules/pi-agent-resource/package.json +1 -1
  33. package/node_modules/pi-agent-search/package.json +3 -3
  34. package/node_modules/pi-agent-search-text/package.json +6 -6
  35. package/node_modules/pi-agent-search-text/src/resolvers.ts +32 -27
  36. package/node_modules/pi-agent-search-text/src/search-session.ts +27 -1
  37. package/node_modules/pi-agent-text/package.json +2 -2
  38. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  39. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  40. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  41. package/node_modules/pi-agent-text-editor/package.json +8 -8
  42. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  43. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  44. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  45. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  46. package/node_modules/pi-agent-web/package.json +6 -6
  47. package/node_modules/pi-agent-web/src/resolver.ts +128 -1
  48. package/node_modules/pi-agent-web-html/package.json +2 -2
  49. package/node_modules/pi-agent-web-image/package.json +3 -3
  50. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  51. package/node_modules/pi-agent-web-text/package.json +3 -3
  52. package/package.json +34 -34
  53. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  54. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  55. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  56. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  57. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +6 -6
  58. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  59. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  60. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  61. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  62. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +128 -1
  63. package/src/extensions/pi-agent-read/package.json +6 -6
  64. package/src/extensions/pi-agent-search/package.json +3 -3
  65. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
  66. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +32 -27
  67. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +27 -1
  68. package/src/extensions/pi-agent-text-editor/package.json +8 -8
  69. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  70. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  71. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  72. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  73. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  74. package/src/plugins/pi-agent-ide-ast/package.json +9 -9
  75. package/src/plugins/pi-agent-ide-changes/package.json +6 -6
  76. package/src/plugins/pi-agent-ide-debugger/index.ts +1 -1
  77. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  78. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  79. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  80. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  81. package/src/plugins/pi-agent-ide-processes/src/registry.ts +2 -0
  82. package/src/plugins/pi-agent-ide-processes/src/ui.ts +10 -2
  83. package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
  84. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +1 -0
  85. package/src/plugins/pi-agent-ide-terminal/src/search.ts +32 -2
  86. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +4 -4
  87. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
  88. package/src/plugins/pi-agent-ide-terminal/src/types.ts +2 -1
  89. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +1 -1
  90. package/dist/chunk-BGUSBUUD.js +0 -26
  91. package/dist/chunk-QH4ZUDOD.js +0 -1
  92. package/dist/chunk-ZG2MWXCR.js +0 -2
  93. package/docs/evaluation.md +0 -14
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-agent-ide-languages",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "dependencies": {
6
- "pi-agent-doctor": "0.5.0"
6
+ "pi-agent-doctor": "0.5.1"
7
7
  },
8
8
  "pi": {
9
9
  "extensions": [
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "pi-agent-ide-lint",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "dependencies": {
6
- "pi-agent-doctor": "0.5.0",
7
- "pi-agent-invariant": "0.5.0",
8
- "pi-agent-read": "0.5.0",
9
- "pi-agent-resource": "0.5.0",
10
- "pi-agent-text": "0.5.0"
6
+ "pi-agent-doctor": "0.5.1",
7
+ "pi-agent-invariant": "0.5.1",
8
+ "pi-agent-read": "0.5.1",
9
+ "pi-agent-resource": "0.5.1",
10
+ "pi-agent-text": "0.5.1"
11
11
  },
12
12
  "pi": {
13
13
  "extensions": [
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "peerDependencies": {
18
18
  "@earendil-works/pi-coding-agent": "*",
19
- "pi-agent-ide": "0.5.0"
19
+ "pi-agent-ide": "0.5.1"
20
20
  },
21
21
  "peerDependenciesMeta": {
22
22
  "pi-agent-ide": {
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "pi-agent-ide-lsp",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "dependencies": {
6
6
  "cross-spawn": "^7.0.6",
7
- "pi-agent-doctor": "0.5.0",
8
- "pi-agent-invariant": "0.5.0",
9
- "pi-agent-read": "0.5.0",
10
- "pi-agent-resource": "0.5.0",
11
- "pi-agent-search": "0.5.0",
12
- "pi-agent-text": "0.5.0",
13
- "pi-agent-text-editor": "0.5.0",
7
+ "pi-agent-doctor": "0.5.1",
8
+ "pi-agent-invariant": "0.5.1",
9
+ "pi-agent-read": "0.5.1",
10
+ "pi-agent-resource": "0.5.1",
11
+ "pi-agent-search": "0.5.1",
12
+ "pi-agent-text": "0.5.1",
13
+ "pi-agent-text-editor": "0.5.1",
14
14
  "vscode-jsonrpc": "^9.0.0",
15
15
  "vscode-uri": "^3.1.0"
16
16
  },
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "*",
24
- "pi-agent-ide": "0.5.0"
24
+ "pi-agent-ide": "0.5.1"
25
25
  },
26
26
  "peerDependenciesMeta": {
27
27
  "pi-agent-ide": {
@@ -13,6 +13,8 @@ export interface AgentIdeProcess {
13
13
  renderSummary(theme: Theme): readonly string[];
14
14
  renderDetail(theme: Theme): Component;
15
15
  stop(): Promise<void>;
16
+ /** Forward raw keyboard input when this process has an interactive terminal. */
17
+ sendInput?(data: string): void;
16
18
  }
17
19
 
18
20
  /** Supplies one process kind to the shared Agent IDE process surface. */
@@ -105,7 +105,7 @@ export class AgentIdeProcessesUi {
105
105
  action = await context.ui.custom<{ readonly source: string } | null>(
106
106
  (tui, theme, _keys, done) => {
107
107
  let active = this.#active();
108
- let page: "list" | "detail" | "confirm" = "list";
108
+ let page: "list" | "detail" | "input" | "confirm" = "list";
109
109
  let selected: AgentIdeProcess | undefined;
110
110
  const createList = (selectedSource?: string): SelectList => {
111
111
  const items: SelectItem[] = active.map((process) => ({
@@ -169,7 +169,11 @@ export class AgentIdeProcessesUi {
169
169
  page === "confirm" ? "warning" : "dim",
170
170
  page === "confirm"
171
171
  ? "Stop this process? y confirm · n/esc cancel"
172
- : "esc back · d stop",
172
+ : page === "input"
173
+ ? "input mode · type to send · esc stop input"
174
+ : selected.sendInput === undefined
175
+ ? "esc back · d stop"
176
+ : "i input · esc back · d stop",
173
177
  ),
174
178
  1,
175
179
  0,
@@ -190,6 +194,10 @@ export class AgentIdeProcessesUi {
190
194
  } else if (page === "detail") {
191
195
  if (matchesKey(data, Key.escape)) page = "list";
192
196
  else if (data === "d") page = "confirm";
197
+ else if (data === "i" && selected?.sendInput !== undefined) page = "input";
198
+ } else if (page === "input") {
199
+ if (matchesKey(data, Key.escape)) page = "detail";
200
+ else selected?.sendInput?.(data);
193
201
  } else if (data === "y" && selected !== undefined)
194
202
  done({ source: selected.source });
195
203
  else if (data === "n" || matchesKey(data, Key.escape)) page = "detail";
@@ -30,7 +30,7 @@ export default async function registerTerminal(pi: ExtensionAPI): Promise<void>
30
30
  pi.on("session_shutdown", async (event) => {
31
31
  ui.dispose();
32
32
  removeProcessProvider();
33
- if (event.reason === "reload") {
33
+ if (event.reason !== "quit") {
34
34
  retainReloadResource("terminal", manager);
35
35
  return;
36
36
  }
@@ -23,6 +23,7 @@ export function terminalProcessProvider(manager: TerminalSessionManager): AgentI
23
23
  status: snapshot.status === "stopping" ? ("stopping" as const) : ("running" as const),
24
24
  renderSummary: (theme) => renderActiveTerminal(snapshot, theme).split("\n"),
25
25
  renderDetail: (theme) => renderTerminalResult(snapshot, true, theme),
26
+ sendInput: (data) => manager.write(snapshot.source, data),
26
27
  stop: () => manager.delete(snapshot.source),
27
28
  };
28
29
  }),
@@ -7,6 +7,7 @@ import {
7
7
  import type { SearchRequest, SearchSelectionMatch } from "pi-agent-search/api/search";
8
8
 
9
9
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import type { Component } from "@earendil-works/pi-tui";
10
11
 
11
12
  import { renderTerminalAction } from "#src/plugins/pi-agent-ide-terminal/src/renderer.js";
12
13
  import type { TerminalSessionManager } from "#src/plugins/pi-agent-ide-terminal/src/session-manager.js";
@@ -85,22 +86,51 @@ function terminalSearchResolver(manager: TerminalSessionManager) {
85
86
  },
86
87
  renderResult(
87
88
  result: { details: unknown },
88
- _options: unknown,
89
+ options: { readonly expanded?: boolean },
89
90
  theme: Parameters<typeof renderTerminalAction>[4],
90
91
  ) {
91
92
  const details = result.details;
92
93
  const payload = isRecord(details) ? parsePayload(details.payload) : parsePayload(undefined);
93
- return renderTerminalAction(
94
+ const content = renderTerminalAction(
94
95
  payload.snapshot,
95
96
  "search",
96
97
  JSON.stringify(payload.query),
97
98
  payload.matches.slice(-6).map((match) => `${match.lineNumber}: ${match.lineText}`),
98
99
  theme,
99
100
  );
101
+ return new TerminalSearchPanel(content, options.expanded === true, theme);
100
102
  },
101
103
  };
102
104
  }
103
105
 
106
+ const COMPACT_TERMINAL_SEARCH_ROWS = 12;
107
+
108
+ /** Keep terminal search readable without changing the complete agent-facing result. */
109
+ export class TerminalSearchPanel implements Component {
110
+ public constructor(
111
+ private readonly content: Component,
112
+ private readonly expanded: boolean,
113
+ private readonly theme: Parameters<typeof renderTerminalAction>[4],
114
+ ) {}
115
+
116
+ public render(width: number): string[] {
117
+ const rows = this.content.render(width);
118
+ if (this.expanded || rows.length <= COMPACT_TERMINAL_SEARCH_ROWS) return rows;
119
+ const shown = COMPACT_TERMINAL_SEARCH_ROWS - 1;
120
+ return [
121
+ ...rows.slice(0, shown),
122
+ this.theme.fg(
123
+ "muted",
124
+ `… ${String(rows.length - shown)} visual rows omitted · ctrl+o to expand`,
125
+ ),
126
+ ];
127
+ }
128
+
129
+ public invalidate(): void {
130
+ this.content.invalidate();
131
+ }
132
+ }
133
+
104
134
  export function findTerminalMatches(
105
135
  snapshot: TerminalSessionSnapshot,
106
136
  request: SearchRequest,
@@ -13,7 +13,7 @@ import type {
13
13
  ShellProfile,
14
14
  TerminalSession,
15
15
  TerminalSessionSnapshot,
16
- TerminalWaitReason,
16
+ TerminalWaitOutcomeReason,
17
17
  } from "#src/plugins/pi-agent-ide-terminal/src/types.js";
18
18
 
19
19
  const require = createRequire(import.meta.url);
@@ -215,7 +215,7 @@ export class TerminalSessionManager {
215
215
  readonly timeoutMs: number;
216
216
  readonly interactiveDelayMs?: number;
217
217
  },
218
- ): Promise<{ readonly session: TerminalSession; readonly reason?: TerminalWaitReason }> {
218
+ ): Promise<{ readonly session: TerminalSession; readonly reason?: TerminalWaitOutcomeReason }> {
219
219
  const session = this.required(sourceOrId);
220
220
  if (isTerminalStatus(session.status)) return { session };
221
221
  const interactiveDelayMs = options.interactiveDelayMs ?? 3_000;
@@ -223,7 +223,7 @@ export class TerminalSessionManager {
223
223
  return await new Promise((resolve) => {
224
224
  let settled = false;
225
225
  let interactiveSince: number | undefined;
226
- const finish = (reason?: TerminalWaitReason): void => {
226
+ const finish = (reason?: TerminalWaitOutcomeReason): void => {
227
227
  if (settled) return;
228
228
  if (reason !== undefined && isTerminalStatus(session.status)) reason = undefined;
229
229
  settled = true;
@@ -232,7 +232,7 @@ export class TerminalSessionManager {
232
232
  options.signal?.removeEventListener("abort", onAbort);
233
233
  if (reason !== undefined) {
234
234
  session.background = true;
235
- session.waitReason = reason;
235
+ if (reason !== "aborted") session.waitReason = reason;
236
236
  this.#emitChanged(session);
237
237
  }
238
238
  resolve({ session, ...(reason === undefined ? {} : { reason }) });
@@ -65,9 +65,9 @@ export function registerTerminalTools(
65
65
  promptSnippet: `Execute ${profile.displayName} commands in synchronous or background terminal sessions`,
66
66
  promptGuidelines: [
67
67
  `Write commands for ${profile.displayName}; commands are not translated between shell languages.`,
68
- `Use ${toolName} with background for servers, watchers, and long builds. Foreground waits become background after timeoutSeconds (60 by default), on a stable interactive prompt, or when the turn is aborted. A background session with no output for two minutes wakes an idle agent so it can be inspected. Sessions survive extension reloads and keep the same shell: source. Large output returns a bounded tail and a fullOutput file path. Use the returned shell: source with read, write, insert, and delete.`,
68
+ `Use ${toolName} with background for servers, watchers, and long builds. Foreground waits become background after timeoutSeconds (60 by default), on a stable interactive prompt, or when the turn is aborted. After a session enters background, do not poll it continuously; continue other work or wait for its automatic completion notification. Keep a short task in foreground wait when it should finish soon and no independent work remains. A background session with no output for two minutes wakes an idle agent so it can be inspected. Sessions survive extension reloads and keep the same shell: source. Large output returns a bounded tail and a fullOutput file path. Use the returned shell: source with read, write, insert, and delete.`,
69
69
  ],
70
- description: `Use ${toolName} to execute a command in the user's configured ${profile.displayName} shell (${profile.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort; completion is delivered automatically and wakes the agent. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${shellSyntaxGuidance(profile)}`,
70
+ description: `Use ${toolName} to execute a command in the user's configured ${profile.displayName} shell (${profile.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort. Background completion is delivered automatically and wakes the agent, so background sessions do not need continuous polling. Keep short tasks in foreground wait when they should finish soon and no independent work remains. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${shellSyntaxGuidance(profile)}`,
71
71
  parameters: runParameters,
72
72
  async execute(_toolCallId, input, signal, onUpdate, context) {
73
73
  ui.bind(context);
@@ -1,7 +1,8 @@
1
1
  import type { IPty } from "node-pty";
2
2
  import type { Terminal } from "@xterm/headless";
3
3
 
4
- export type TerminalWaitReason = "timeout" | "interactive" | "aborted";
4
+ export type TerminalWaitReason = "timeout" | "interactive";
5
+ export type TerminalWaitOutcomeReason = TerminalWaitReason | "aborted";
5
6
  export type TerminalCompletionReason = "timeout";
6
7
 
7
8
  export type TerminalSessionStatus =
@@ -75,7 +75,7 @@ export class TerminalUi {
75
75
  {
76
76
  customType: "terminal-wait-transition",
77
77
  display: false,
78
- content: `Terminal wait aborted; ${snapshot.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,
78
+ content: `Terminal wait ended; ${snapshot.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,
79
79
  details: snapshot,
80
80
  },
81
81
  { triggerTurn: true, deliverAs: "steer" },
@@ -1,26 +0,0 @@
1
- import{a as ne,b as re,c as ie}from"./chunk-ESPNEJHK.js";import{a as te}from"./chunk-5PLV4HLG.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as V}from"./chunk-6CZO43OH.js";import{a as X,b as Y}from"./chunk-OBNING2A.js";import{a as ee}from"./chunk-ZTYWHL2F.js";import{a as Z,b as Q}from"./chunk-7UGNGK7Y.js";import{a as J}from"./chunk-L7JMDDSD.js";import{a as K,b as z}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Ue from"node:path";import{stripVTControlCharacters as We}from"node:util";import{truncateLine as Fe}from"@earendil-works/pi-coding-agent";import{Text as x}from"@earendil-works/pi-tui";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as oe,formatSize as Oe,truncateTail as Ne}from"@earendil-works/pi-coding-agent";function I(t){return Ne(t,{maxBytes:se-4096,maxLines:oe-32})}a(I,"terminalOutputTail");function v(t){let e=I(t.output),n=[`session: ${t.source}`,`status: ${t.status}`,`shell: ${t.shell}`,`cwd: ${t.cwd}`,`elapsedMs: ${t.elapsedMs}`,t.exitCode===void 0?void 0:`exitCode: ${t.exitCode}`,t.signal===void 0?void 0:`signal: ${t.signal}`,t.error===void 0?void 0:`error: ${t.error}`,t.waitReason===void 0?void 0:`reason: ${t.waitReason}`,t.completionReason===void 0?void 0:`completionReason: ${t.completionReason}`,t.waitReason===void 0?void 0:`next: Read ${t.source} to inspect it, then use write or insert to send input.`,`outputRange: ${t.outputStart}-${t.outputEnd}`,t.truncated?"retainedOutput: earlier data omitted from memory":void 0,e.truncated?`fullOutput: ${t.fullOutputPath}`:void 0].filter(s=>s!==void 0),r=e.content.trimEnd();if(!e.truncated)return`${n.join(`
2
- `)}
3
- output:${r.length===0?" (empty)":`
4
- ${r}`}`;let i=e.truncatedBy==="lines"?`${oe} line output budget`:`${Oe(se)} output budget`,o=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
5
- `)}
6
- output:
7
- ${o}${r.length===0?"":`
8
- ${r}`}`}a(v,"formatAgentTerminalSnapshot");var je=500;function ae(t,e,n,r,i){let o=e?"background":"wait",s=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${E(n)} \xB7 ${o}`)}`;return new x(`${s}
9
- ${i.fg("accent",O(r.family))} ${t}`,0,0)}a(ae,"renderRunCall");function le(t,e,n){let r=e.map(i=>` ${n.fg("dim",i)}`);return r.push(n.fg("success",t==="delete"?"\u2713 stopped":"\u2713 sent")),new x(r.join(`
10
- `),0,0)}a(le,"renderTerminalActionResult");function $(t,e,n,r,i){let o=[qe(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&o.push(...r.map(s=>` ${i.fg("dim",s)}`)),new x(o.join(`
11
- `),0,0)}a($,"renderTerminalAction");function S(t,e,n,r){let i=Ge(t,R,n);return r!==void 0&&i.splice(1,1,n.fg("accent",r)),new x(i.join(`
12
- `),0,0)}a(S,"renderTerminalResult");function ue(t,e,n){if(e)return S(t,!0,n);let r=_(t.output??"",R),i=[...r.omission===void 0?[]:[` ${n.fg("muted",r.omission)}`],...r.lines.map(o=>` ${n.fg("dim",o)}`)];return i.push(D(t,(o,s)=>n.fg(o,s))),new x(i.join(`
13
- `),0,0)}a(ue,"renderRunResult");function ce(t,e){let n=a((s,l)=>e?.fg(s,l)??l,"color"),i=[`${n("accent",t.shell.toLocaleLowerCase())} ${n("muted",`\xB7 ${E(t.cwd)} \xB7 ${t.background?"background":"wait"}`)}`,`${n("accent",O(t.shellFamily))} ${M(t.command,84)}`],o=He(t.output,2);return o.length>0&&i.push(...o.map(s=>` ${n("dim",M(s,90))}`)),i.push(D(t,n)),i.join(`
14
- `)}a(ce,"renderActiveTerminal");function Ge(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",o=t.cwd===void 0?"workspace":E(t.cwd),s=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${o} \xB7 ${i}`)}`,`${n.fg("accent",O(s))} ${t.command??""}`],u=_(t.output??"",e);return u.omission!==void 0&&l.push(` ${n.fg("muted",u.omission)}`),u.lines.length>0&&l.push(...u.lines.map(c=>` ${n.fg("dim",c)}`)),l.push(D(t,(c,d)=>n.fg(c,d))),l}a(Ge,"terminalCardLines");function He(t,e){return _(t,e).lines}a(He,"outputTail");function _(t,e){let n=I(We(t).replaceAll("\r","")),r=n.content.split(`
15
- `).map(u=>Fe(u.trimEnd(),je).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,o=Math.max(0,r.length-i),s=Math.max(0,n.totalLines-n.outputLines),l=o+s;return{lines:r.slice(o),...n.truncated||l>0?{omission:l>0?`\u2026 ${l} earlier lines`:"\u2026 earlier output omitted"}:{}}}a(_,"outputWindow");function D(t,e){let n=t.status??"running",r=Be(n),i=n==="completed"?"success":n==="running"?"accent":"error",o=[`${r} ${n}`,Xe(t.elapsedMs??0)];return t.waitReason!==void 0&&o.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&o.push(`reason ${t.completionReason}`),t.exitCode!==void 0?o.push(`exit ${t.exitCode}`):t.signal!==void 0&&o.push(`signal ${t.signal}`),e(i,o.join(" \xB7 "))}a(D,"statusLine");function Be(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Be,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function qe(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":E(t.cwd),i=t.background===!0?"background":"wait",o=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${o}`)}`}a(qe,"terminalIdentity");function E(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Ue.sep}`))?`~${t.slice(e.length)}`:t}a(E,"shortCwd");function M(t,e){let n=t.replaceAll(/\s+/gu," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}a(M,"oneLine");function Xe(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Xe,"formatElapsed");function de(t){return{id:"terminal",onDidChange:a(e=>t.onDidChange(e),"onDidChange"),list:a(()=>t.list().filter(e=>e.status==="running"||e.status==="stopping").map(e=>({source:e.source,kind:"terminal",title:e.shell.toLocaleLowerCase(),description:e.command,status:e.status==="stopping"?"stopping":"running",renderSummary:a(n=>ce(e,n).split(`
16
- `),"renderSummary"),renderDetail:a(n=>S(e,!0,n),"renderDetail"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(de,"terminalProcessProvider");var Ye="#d8dee9",N="#111418",Ve=["#000000","#cd0000","#00cd00","#cdcd00","#0000ee","#cd00cd","#00cdcd","#e5e5e5","#7f7f7f","#ff0000","#00ff00","#ffff00","#5c5cff","#ff00ff","#00ffff","#ffffff"];async function U(t,e,n){let r=t.get(e);if(r===void 0)throw new Error(`Unknown terminal session ${e}`);await r.screenReady;let{createCanvas:i}=await import("@napi-rs/canvas"),o=Math.max(0,Math.min(r.rows-1,n?.start??0)),s=Math.max(1,Math.min(r.rows-o,n?.count??r.rows)),l=i(r.cols*9+24,s*18+24),u=l.getContext("2d");u.fillStyle=N,u.fillRect(0,0,l.width,l.height),u.textBaseline="top";let c=r.screen.buffer.active,d=Math.max(0,c.baseY);for(let m=0;m<s;m+=1){let p=c.getLine(d+o+m);if(p!==void 0)for(let f=0;f<r.cols;f+=1){let h=p.getCell(f);h===void 0||h.getWidth()===0||Ke(u,h,f,m)}}return r.status==="running"&&c.cursorY>=o&&c.cursorY<o+s&&(u.fillStyle="rgba(216, 222, 233, 0.75)",u.fillRect(12+c.cursorX*9,12+(c.cursorY-o)*18+18-2,9,2)),l.toBuffer("image/png").toString("base64")}a(U,"renderTerminalScreen");function Ke(t,e,n,r){let i=me(e,"foreground"),o=me(e,"background");e.isInverse()&&([i,o]=[o,i]);let s=12+n*9,l=12+r*18;o!==N&&(t.fillStyle=o,t.fillRect(s,l,9*Math.max(1,e.getWidth()),18));let u=e.getChars();u.length!==0&&(t.font=`${e.isBold()?"bold ":""}14px monospace`,t.fillStyle=i,t.fillText(u,s,l),e.isUnderline()&&t.fillRect(s,l+18-2,9*Math.max(1,e.getWidth()),1))}a(Ke,"drawCell");function me(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ye:N;let i=n?t.isFgRGB():t.isBgRGB(),o=n?t.getFgColor():t.getBgColor();return i?`#${o.toString(16).padStart(6,"0")}`:ze(o)}a(me,"cellColor");function ze(t){let e=Ve[t];if(e!==void 0)return e;if(t>=232){let l=8+(t-232)*10;return pe(l,l,l)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),o=n%6,s=a(l=>l===0?0:55+l*40,"channel");return pe(s(r),s(i),s(o))}a(ze,"ansiColor");function pe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(pe,"rgb");var W="\0pi-terminal-write\0",F="\0pi-terminal-keys\0";async function we(t,e){let n=new Map,r=new Map,i={protocol:X,apiVersion:Y,id:"terminal",setup(s){s.addResolver({resolver:Je(e),preserveTruncatedOutput:!0,renderResult(l,u,c){let d=l.details,m=d.source===void 0?void 0:e.get(d.source),p=m===void 0?{}:e.snapshot(m);return S(m===void 0?p:{...p,output:e.screenTail(m).join(`
17
- `)},u.expanded,c,"read terminal")}}),s.addHandler({stage:"pre-read",async handler(l){let u=l.request.path;if(u===void 0||!y(u)||l.request.views?.includes("image")!==!0)return{kind:"continue",context:l};let c=e.get(u);if(c===void 0)return{kind:"return",result:fe(u,`Unknown terminal session ${u}`)};try{return e.markInspected(u),{kind:"return",result:{content:[{type:"image",data:await U(e,u),mimeType:"image/png"}],details:{source:c.source,resolvedBy:"terminal"}}}}catch(d){return{kind:"return",result:fe(u,d instanceof Error?d.message:String(d))}}}}),s.describe('shell:<session> \u2014 terminal session status and a bounded output tail with a full-log path when truncated. Use views: ["image"] to read the current virtual terminal screen as a PNG.'),s.addPromptGuideline("Use read with a returned shell:<session> source to inspect terminal status and output. Add the image view when cursor movement, ANSI layout, or a full-screen terminal interface matters.")}},o={protocol:K,apiVersion:z,id:"terminal",setup(s){s.addResolver({resolver:Ze(e)}),s.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(he(l.input,e,n),await ge(l.input,e,r),Qe(l,W)),"handler")}),s.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await ge(l.input,e,r),he(l.input,e,n),et(l)),"handler")});for(let l of["write","insert","delete"])s.addToolRenderer({tool:l,matches:a((u,c)=>it(u,c),"matches"),renderCall(u,c,d){let m=u,p=typeof m.path=="string"?e.get(m.path):void 0,f=d.state;return p!==void 0&&(f.snapshot=e.snapshot(p)),$(f.snapshot??{},l,ye(l,m),[],c)},renderResult(u,c,d){let m=rt(u.details);return le(m.action,m.changedLines,d)}});s.describe("For shell:<session> resources, write sends exact terminal input, insert sends named keys at end, and delete terminates and removes the session. replace is unsupported."),s.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),s.tool("insert").describe("When path is shell:<session>, omit anchor or use end, keep before false, and put whitespace- or comma-separated named keys and chords such as Enter, Ctrl+C, Ctrl+Left, Ctrl+Shift+Left, Up, or Backspace in text. Use Unix caret forms such as ^C and ^U for control characters.")}};await Promise.all([V(t,i),J(t,o)]),t.on("tool_result",async(s,l)=>{if(!w(s.input))return;let u=s.input.path;if(s.toolName==="replace"&&typeof u=="string"&&y(u))return{content:[{type:"text",text:`replace is unsupported for ${u}; use write for text, insert for keys, or delete to terminate and remove the session.`}],details:s.details,isError:!0};if(s.toolName==="delete"&&typeof u=="string"&&y(u)){let q=e.get(u);if(q===void 0)return;let De=e.snapshot(q);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:De,action:"delete",input:"session",changedLines:[]},isError:!1}),L=>({content:[{type:"text",text:L instanceof Error?L.message:String(L)}],details:{source:u,deleted:!1},isError:!0}))}if(s.toolName!=="write"&&s.toolName!=="insert"||s.isError)return;let c=s.input.path;if(typeof c!="string"||!y(c))return;let d=e.get(c);if(d===void 0)return;let m=r.get(c)??e.screenRows(d);r.delete(c);let p=n.get(c)??d.outputStart+d.output.length;n.delete(c),await e.waitForOutputAfter(d,p);let f=e.snapshot(d),h=s.toolName,P=ye(h,s.input),b=e.screenChangeRegion(d,m,6),B=[{type:"text",text:`Sent ${P} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&B.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:B,details:{source:d.source,action:h,status:d.status,snapshot:f,input:P,changedLines:b.lines},isError:s.isError}})}a(we,"registerTerminalResources");function Je(t){return{id:"terminal",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,async read(){t.markInspected(n.source);let r=t.snapshot(n);return[{type:"text",text:tt(r)}]}}}}}}a(Je,"createReadResolver");function Ze(t){return{id:"terminal-input",async tryResolve(e){if(!y(e))return{kind:"not-handled"};let n=t.get(e);return n===void 0?{kind:"failed",error:new Error(`Unknown terminal session ${e}`)}:{kind:"resolved",resource:{source:n.source,skipPostEdit:!0,async read(){return[{type:"text",text:"terminal input"}]},async write(r){let i=nt(r),o=i.indexOf(W),s=i.indexOf(F);if(o>=0){t.write(n.source,i.slice(o+W.length));return}if(s>=0){t.sendKeys(n.source,i.slice(s+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(Ze,"createInputResolver");function Qe(t,e){return!w(t.input)||!Se(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(Qe,"transformWriteInput");function et(t){if(!w(t.input)||!Se(t.input.path))return t;if(t.input.before===!0)throw new Error("Shell keys can only be inserted after the active input position");return{...t,input:{...t.input,anchor:"end",before:!1,text:`${F}${typeof t.input.text=="string"?t.input.text:""}`}}}a(et,"transformInsertInput");function tt(t){return v(t)}a(tt,"formatSnapshot");function nt(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(nt,"singleText");function fe(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(fe,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Se(t){return typeof t=="string"&&y(t)}a(Se,"isShellSourceValue");function rt(t){if(!w(t)||!w(t.snapshot))throw new TypeError("Invalid terminal action result");let e=t.snapshot,n=t.action;if(n!=="write"&&n!=="insert"&&n!=="delete")throw new TypeError("Invalid terminal action");return{source:typeof t.source=="string"?t.source:"shell:unknown",action:n,input:typeof t.input=="string"?t.input:"",changedLines:Array.isArray(t.changedLines)?t.changedLines.filter(r=>typeof r=="string"):[],snapshot:{...typeof e.shell=="string"?{shell:e.shell}:{},...typeof e.cwd=="string"?{cwd:e.cwd}:{},...typeof e.command=="string"?{command:e.command}:{},...typeof e.background=="boolean"?{background:e.background}:{},...typeof e.status=="string"?{status:e.status}:{}}}}a(rt,"terminalActionDetails");async function ge(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(ge,"rememberScreen");function he(t,e,n){if(!w(t)||typeof t.path!="string"||!y(t.path))return;let r=e.get(t.path);r!==void 0&&n.set(t.path,r.outputStart+r.output.length)}a(he,"rememberOutputEnd");function ye(t,e){if(t==="delete")return"session";let n=t==="write"?e.content:e.text,r=typeof n=="string"?n:"";return t==="write"?`text ${JSON.stringify(r)}`:`keys ${r}`}a(ye,"terminalInputLabel");function it(t,e){if(!w(t))return!1;if(e==="call")return typeof t.path=="string"&&y(t.path);let n=t.details;return w(n)&&typeof n.source=="string"&&y(n.source)}a(it,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Te(t,e){await ee(t,{protocol:Z,apiVersion:Q,id:"terminal",setup(r){r.addResolver({resolver:st(e),priority:100}),r.describe("path shell:<session> searches the retained text output of that terminal, including rows outside its current screen."),r.addPromptGuideline("Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.")}})}a(Te,"registerTerminalSearch");function st(t){return{id:"terminal",async tryResolve(e){if(e.path===void 0||!e.path.startsWith("shell:"))return{kind:"not-handled"};let n=t.get(e.path);if(n===void 0)return{kind:"failed",error:new Error(`Unknown terminal session ${e.path}`)};let r=t.snapshot(n),i=ot(r,e);return{kind:"resolved",payload:{snapshot:r,query:e.query,matches:i}}},format(e){let n=j(e),r=n.matches.map(i=>`${n.snapshot.source}:${i.lineNumber}: ${i.lineText}`);return{content:[{type:"text",text:r.length===0?`No matches in ${n.snapshot.source}`:`${r.join(`
18
- `)}
19
-
20
- ${r.length} match${r.length===1?"":"es"} in ${n.snapshot.source}`}],details:{source:n.snapshot.source,payload:n}}},renderResult(e,n,r){let i=e.details,o=G(i)?j(i.payload):j(void 0);return $(o.snapshot,"search",JSON.stringify(o.query),o.matches.slice(-6).map(s=>`${s.lineNumber}: ${s.lineText}`),r)}}}a(st,"terminalSearchResolver");function ot(t,e){let n=e.caseSensitive===!0?e.query:e.query.toLocaleLowerCase();if(n.length===0)return[];let r=[],i=e.limit??100;for(let[o,s]of t.output.replaceAll("\r","").split(`
21
- `).entries()){let l=e.caseSensitive===!0?s:s.toLocaleLowerCase(),u=0;for(;r.length<i;){let c=l.indexOf(n,u);if(c<0)break;let d=c+n.length;(e.wholeWord!==!0||at(l,c,d))&&r.push({source:t.source,lineNumber:o+1,startColumn:c,endColumn:d,matchedText:s.slice(c,d),lineText:s}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(ot,"findTerminalMatches");function at(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(at,"isWordBoundary");function j(t){if(!lt(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function lt(t){return G(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&G(t.snapshot)&&typeof t.snapshot.source=="string"}a(lt,"isTerminalSearchPayload");function G(t){return typeof t=="object"&&t!==null}a(G,"isRecord");import{spawn as ut}from"node:child_process";import{closeSync as ct,mkdirSync as dt,openSync as mt,rmSync as pt,writeSync as ft}from"node:fs";import gt from"node:os";import be from"node:path";import{createRequire as ht}from"node:module";import{randomUUID as yt}from"node:crypto";import{stripVTControlCharacters as wt}from"node:util";var Pe=ht(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),Re=1e6,St=100,Tt=30,bt=2e3,A=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#s=!1;constructor(e=Pt){this.#a=e}onDidChange(e){return this.#t.add(e),()=>this.#t.delete(e)}onDidComplete(e){return this.#r.add(e),()=>this.#r.delete(e)}list(){return[...this.#e.values()].sort((e,n)=>n.startedAt-e.startedAt).map(e=>this.snapshot(e))}get(e){return this.#e.get(vt(e))}snapshot(e,n=Date.now()){return{id:e.id,source:e.source,command:e.command,cwd:e.cwd,shell:e.shell.displayName,shellFamily:e.shell.family,background:e.background,status:e.status,...e.waitReason===void 0?{}:{waitReason:e.waitReason},...e.completionReason===void 0?{}:{completionReason:e.completionReason},lastActivityAt:e.lastActivityAt,idleMs:Math.max(0,n-e.lastActivityAt),startedAt:e.startedAt,...e.endedAt===void 0?{}:{endedAt:e.endedAt},elapsedMs:(e.endedAt??n)-e.startedAt,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.signal===void 0?{}:{signal:e.signal},...e.error===void 0?{}:{error:e.error},output:e.output,outputStart:e.outputStart,outputEnd:e.outputStart+e.output.length,truncated:e.outputStart>0,fullOutputPath:e.fullOutputPath,cols:e.cols,rows:e.rows}}start(e){if(this.#s)throw new Error("Terminal session manager is closed");let n=this.#a();if(!/^[a-f\d]{12}$/u.test(n)||this.#e.has(n))throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");let r=Lt(n);this.#i.set(n,mt(r,"a",384));let i=e.cols??St,o=e.rows??Tt,s=xt(i,o),l=a(p=>{},"resolveCompletion"),u=new Promise(p=>{l=p}),c={id:n,source:`shell:${n}`,command:e.command,background:e.background,cwd:e.cwd,shell:e.shell,startedAt:Date.now(),lastActivityAt:Date.now(),cols:i,rows:o,fullOutputPath:r,screen:s,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=Pe("node-pty"),f={name:"xterm-256color",cols:i,rows:o,cwd:e.cwd,env:Et($t())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:Ct(p)};return this.#e.set(n,f),this.#o(n),l(f),queueMicrotask(()=>this.#l(f)),f}let m={...c,process:d};return this.#e.set(n,m),d.onData(p=>this.#u(m,p)),d.onExit(({exitCode:p,signal:f})=>{T(m.status)||(m.endedAt=Date.now(),m.exitCode=p,f!==0&&(m.signal=f),m.status=m.status==="stopping"?"stopped":p===0?"completed":"failed",(p===124||p===137)&&(m.completionReason="timeout"),this.#o(m.id),m.resolveCompletion(m),this.#n(m),this.#l(m))}),this.#n(m),m}async wait(e,n){let r=this.required(e);return T(r.status)?r:n?.aborted===!0?(await this.stop(r.source,"cancelled"),r):await new Promise((i,o)=>{let s=a(()=>{this.stop(r.source,"cancelled").then(i,o)},"onAbort");n?.addEventListener("abort",s,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",s),i(l)},o)})}async waitForForeground(e,n){let r=this.required(e);if(T(r.status))return{session:r};let i=n.interactiveDelayMs??3e3;return await new Promise(o=>{let s=!1,l,u=a(p=>{s||(p!==void 0&&T(r.status)&&(p=void 0),s=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,r.waitReason=p,this.#n(r)),o({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!Rt(r)){l=void 0;return}l??=Date.now(),Date.now()-l>=i&&u("interactive")},Math.min(100,Math.max(10,i/2)));n.signal?.addEventListener("abort",c,{once:!0}),n.signal?.aborted===!0&&c(),r.completion.then(()=>u())})}async waitForOutputAfter(e,n){let r=Date.now()+300,i=n,o;for(;Date.now()<r;){let s=e.outputStart+e.output.length;if(s!==i)i=s,o=Date.now(),await e.screenReady;else if(o!==void 0&&Date.now()-o>=40)return;await H(10)}await e.screenReady}screenRows(e){let n=e.screen.buffer.active;return Array.from({length:e.rows},(r,i)=>(n.getLine(n.baseY+i)?.translateToString(!0)??"").trimEnd())}screenChangeRegion(e,n,r=6){let i=this.screenRows(e),o=Math.max(1,Math.min(e.rows,r)),s=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(o/2)),l=-1;for(let d=0;d<=e.rows-o;d+=1){let m=0;for(let p=d;p<d+o;p+=1){let f=n[p]??"",h=i[p]??"",P=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(P||b)&&(m+=1)}m>l&&(l=m,s=d)}let u=e.screen.buffer.active;return{lines:i.slice(s,s+o).map((d,m)=>{if(s+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:s}}screenChangeWindow(e,n,r=6){return this.screenChangeRegion(e,n,r).lines}screenTail(e,n=e.rows){let r=e.screen.buffer.active,i=Math.max(0,r.baseY),o=[];for(let s=0;s<e.rows;s+=1){let l=r.getLine(i+s)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&o.push(l)}return o.slice(-Math.max(0,n))}markInspected(e){let n=this.required(e);n.status==="running"&&(n.lastActivityAt=Date.now(),this.#n(n))}write(e,n){this.requiredRunning(e).process?.write(n)}sendKeys(e,n){this.requiredRunning(e).process?.write(At(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await xe(r,!1),await Promise.race([r.completion.then(()=>!0),H(bt).then(()=>!1)])||(await xe(r,!0),await Promise.race([r.completion,H(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#o(r.id),r.resolveCompletion(r),this.#l(r)),n==="cancelled"&&(r.status="cancelled"),this.#n(r)),r}async delete(e){let n=this.required(e);n.completionDelivered=!0,await this.stop(n.source),n.screen.dispose(),this.#o(n.id),pt(n.fullOutputPath,{force:!0}),this.#e.delete(n.id),this.#n(n)}async screenLines(e){let n=this.required(e);await n.screenReady;let r=n.screen.buffer.active,i=[],o=Math.max(0,r.baseY);for(let s=o;s<o+n.rows;s+=1)i.push(r.getLine(s)?.translateToString(!0)??"");return i}cursor(e){let n=this.required(e);return{x:n.screen.buffer.active.cursorX,y:n.screen.buffer.active.cursorY}}async dispose(){if(!this.#s){this.#s=!0,await Promise.all([...this.#e.values()].filter(e=>!T(e.status)).map(e=>this.stop(e.source)));for(let e of this.#e.values())e.screen.dispose(),this.#o(e.id);this.#t.clear(),this.#r.clear()}}required(e){let n=this.get(e);if(n===void 0)throw new Error(`Unknown terminal session ${e}`);return n}requiredRunning(e){let n=this.required(e);if(n.status!=="running")throw new Error(`Terminal session ${n.source} is ${n.status}; input is unavailable`);return n}#u(e,n){e.lastActivityAt=Date.now();let r=wt(n),i=this.#i.get(e.id);if(i!==void 0&&ft(i,r),e.output+=r,e.output.length>Re){let o=e.output.length-Re;e.output=e.output.slice(o),e.outputStart+=o}e.screenReady=e.screenReady.then(()=>new Promise(o=>{e.screen.write(n,o)})),this.#n(e)}#o(e){let n=this.#i.get(e);n!==void 0&&(ct(n),this.#i.delete(e))}#n(e){for(let n of this.#t)n(e)}#l(e){for(let n of this.#r)n(e)}};function Rt(t){if(t.status!=="running")return!1;let e=t.screen.buffer.active,n=e.getLine(e.baseY+e.cursorY)?.translateToString(!0).trimEnd()??"";return/\[[^\]\n]{1,20}(?:\/[^\]\n]{1,20})+\]\s*[:?>]?\s*$/iu.test(n)||/(?:choose|select|enter|password|confirm|continue|proceed)[^\n]{0,60}[:?]\s*$/iu.test(n)||/^(?:❯|›)\s+\S/u.test(n)}a(Rt,"looksInteractive");function xt(t,e){let{Terminal:n}=Pe("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(xt,"createScreen");function Pt(){return yt().replaceAll("-","").slice(0,12)}a(Pt,"defaultSessionId");function vt(t){return t.startsWith("shell:")?t.slice(6):t}a(vt,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function $t(){return process.env}a($t,"processEnvironment");function Et(t){return{...Object.fromEntries(Object.entries(t).filter(e=>e[1]!==void 0)),PAGER:"cat",GIT_PAGER:"cat",SYSTEMD_PAGER:"cat",GH_PAGER:"cat"}}a(Et,"cleanEnvironment");function At(t){return t.split(/[\s,]+/u).filter(Boolean).map(kt).join("")}a(At,"encodeTerminalKeys");function kt(t){if(/^\^[?@A-Z[\\\]^_]$/iu.test(t)){let d=t.slice(1).toUpperCase();return d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31)}let e=t.toLowerCase().split("+"),n=e.pop()??"",r=new Set(e);if([...r].some(d=>!["ctrl","control","alt","meta","shift"].includes(d)))throw new Error(`Unsupported terminal key ${t}`);let i=r.has("ctrl")||r.has("control"),o=r.has("alt")||r.has("meta"),s=r.has("shift");if(i&&n.length===1&&/[a-z@[\\\]^_?]/u.test(n)){let d=n.toUpperCase(),m=d==="?"?"\x7F":String.fromCharCode(d.charCodeAt(0)&31);return o?`\x1B${m}`:m}let l={enter:"\r",tab:" ",escape:"\x1B",esc:"\x1B",backspace:"\x7F",home:"\x1B[H",end:"\x1B[F",delete:"\x1B[3~"};if(!i&&!o&&!s&&l[n]!==void 0)return l[n];if(o&&!i&&!s&&l[n]!==void 0)return`\x1B${l[n]}`;let c={up:"A",down:"B",right:"C",left:"D",home:"H",end:"F"}[n];if(c!==void 0)return!i&&!o&&!s?`\x1B[${c}`:`\x1B[1;${1+(s?1:0)+(o?2:0)+(i?4:0)}${c}`;if(o&&!i&&n.length===1)return`\x1B${s?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(kt,"encodeTerminalKey");async function xe(t,e){let n=t.process;if(n!==void 0){if(globalThis.process.platform!=="win32")try{globalThis.process.kill(-n.pid,e?"SIGKILL":"SIGTERM");return}catch{try{n.kill(e?"SIGKILL":"SIGTERM")}catch{}return}await new Promise(r=>{let i=ut("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(xe,"terminateProcessTree");function H(t){return new Promise(e=>setTimeout(e,t))}a(H,"delay");function Ct(t){return t instanceof Error?t.message:String(t)}a(Ct,"errorMessage");function Lt(t){let e=be.join(gt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return dt(e,{recursive:!0,mode:448}),be.join(e,`${t}.log`)}a(Lt,"createOutputLog");import It from"node:os";import ve from"node:path";function $e(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",o=ve.win32.basename(i).toLowerCase();return o==="cmd"||o==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(s=>["/d","/s","/c",s],"commandArgs")}:{executable:i,displayName:o.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(s=>["-NoLogo","-NoProfile","-Command",s],"commandArgs")}}let n=e.SHELL?.trim()||It.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=ve.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a($e,"resolveShellProfile");function Ee(t){switch(t.family){case"powershell":return"Write PowerShell syntax. Use PowerShell cmdlets, `$env:NAME` for environment variables, and `;` or pipelines to compose commands.";case"cmd":return"Write Command Prompt syntax. Use `%NAME%` for environment variables and `&&` to chain successful commands.";case"posix":return`Write ${t.displayName} syntax. Use POSIX-style paths, \`$NAME\` for environment variables, and \`&&\` or pipelines to compose commands.`}}a(Ee,"shellSyntaxGuidance");import Ae from"node:path";import{stripVTControlCharacters as Mt}from"node:util";import{defineTool as _t}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Dt=g.Object({command:g.String({minLength:1,description:"Command written in the syntax of the configured system shell"}),background:g.Optional(g.Boolean({description:"Return immediately while the terminal session continues. Defaults to false."})),timeoutSeconds:g.Optional(g.Number({minimum:.1,maximum:86400,description:"Maximum foreground wait in seconds before returning the live session as background. Defaults to 60."})),cwd:g.Optional(g.String({description:"Working directory. Relative paths resolve from the current workspace."})),cols:g.Optional(g.Integer({minimum:20,maximum:300,description:"Virtual terminal width in cells"})),rows:g.Optional(g.Integer({minimum:5,maximum:120,description:"Virtual terminal height in cells"}))},{additionalProperties:!1});function ke(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(_t({name:i,label:n.displayName,promptSnippet:`Execute ${n.displayName} commands in synchronous or background terminal sessions`,promptGuidelines:[`Write commands for ${n.displayName}; commands are not translated between shell languages.`,`Use ${i} with background for servers, watchers, and long builds. Foreground waits become background after timeoutSeconds (60 by default), on a stable interactive prompt, or when the turn is aborted. A background session with no output for two minutes wakes an idle agent so it can be inspected. Sessions survive extension reloads and keep the same shell: source. Large output returns a bounded tail and a fullOutput file path. Use the returned shell: source with read, write, insert, and delete.`],description:`Use ${i} to execute a command in the user's configured ${n.displayName} shell (${n.executable}). Every call creates an addressable terminal session. Set background to true to continue without waiting. A foreground wait automatically returns the live session as background on timeout, a stable interactive prompt, or turn abort; completion is delivered automatically and wakes the agent. Sessions survive extension reloads and keep the same shell: source. Output uses the shared Read limits, keeps the tail, and links a complete log file when truncated. ${Ee(n)}`,parameters:Dt,async execute(o,s,l,u,c){r.bind(c);let d=s.cwd===void 0?c.cwd:Ae.resolve(c.cwd,s.cwd),m=e.start({command:s.command,background:s.background??!1,cwd:d,shell:n,...s.cols===void 0?{}:{cols:s.cols},...s.rows===void 0?{}:{rows:s.rows}});if(s.background===!0&&m.status!=="failed")return await Ot(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),k(e.snapshot(m));if(m.status==="failed")return k(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(s.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),k(e.snapshot(p.session))},renderCall(o,s){let l=typeof o.command=="string"?o.command:"",u=typeof o.cwd=="string"?Ae.resolve(process.cwd(),o.cwd):process.cwd();return ae(l,o.background===!0,u,n,s)},renderResult(o,s,l){return ue(o.details,s.expanded,l)}}))}a(ke,"registerTerminalTools");function k(t){return{content:[{type:"text",text:v(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(k,"terminalResult");async function Ot(t,e,n){await new Promise(r=>{let i=!1,o,s=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(o),s(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(k(c)),(Mt(c.output).replaceAll("\r","").split(`
22
- `).filter(m=>m.length>0).length>=R||c.status!=="running")&&l()},"publish");s=t.onDidChange(c=>{c.id===e.id&&u()}),o=setTimeout(l,2e3),u()})}a(Ot,"captureInitialBackgroundPreview");import{Box as Ce,Container as Le}from"@earendil-works/pi-tui";var Nt=120,Ut=12e4,C=class{constructor(e,n,r=Ut){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:o},s)=>{let l=Ie(i.details)?i.details:void 0,u=new Le;l!==void 0&&u.addChild(S(l,o,s,"stale \xB7 inspect session"));let c=new Ce(1,1,d=>s.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:o},s)=>{let l=new Le;for(let c of Wt(i.details))l.addChild(S(c,o,s));let u=new Ce(1,1,c=>s.bg("toolSuccessBg",c));return u.addChild(l),u}),this.#u=[n.onDidChange(i=>this.#o(i)),n.onDidComplete(i=>{this.#l(i.id),i.background&&this.#c(i)})]}static{a(this,"TerminalUi")}#a=new Map;#e;#t=new Map;#r=new Set;#i;#s=!1;#u;bind(e){this.#i=e}onAgentSettled(e){this.#i=e;for(let n of[...this.#r]){this.#r.delete(n);let r=this.manager.get(n);r!==void 0&&this.#o(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait aborted; ${n.source} is still running in background. Read it to inspect output, then use write or insert to send input.`,details:n},{triggerTurn:!0,deliverAs:"steer"})}dispose(){this.#s=!0,this.#e!==void 0&&clearTimeout(this.#e),this.#e=void 0,this.#a.clear();for(let e of this.#t.values())clearTimeout(e);this.#t.clear(),this.#r.clear(),this.#i=void 0;for(let e of this.#u)e()}#o(e,n=!1){if(this.#l(e.id),this.#s||!e.background||e.status!=="running")return;let r=this.manager.snapshot(e),i=Math.max(0,this.staleIntervalMs-r.idleMs);if(n&&i===0){this.#n(e);return}this.#t.set(e.id,setTimeout(()=>this.#n(e),i))}#n(e){if(this.#t.delete(e.id),this.#s||e.status!=="running"||!e.background)return;if(this.#i?.isIdle()!==!0){this.#r.add(e.id);return}let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-stale",display:!0,content:jt(n),details:n},{triggerTurn:!0,deliverAs:"followUp"}),this.#t.set(e.id,setTimeout(()=>this.#n(e),this.staleIntervalMs))}#l(e){let n=this.#t.get(e);n!==void 0&&clearTimeout(n),this.#t.delete(e),this.#r.delete(e)}#c(e){this.#s||e.completionDelivered||(this.#a.set(e.id,e),this.#e===void 0&&(this.#e=setTimeout(()=>{this.#e=void 0;let n=[...this.#a.values()].filter(i=>!i.completionDelivered);if(this.#a.clear(),this.#s||n.length===0)return;for(let i of n)i.completionDelivered=!0;let r=n.map(i=>this.manager.snapshot(i));this.pi.sendMessage({customType:"terminal-completion",display:!0,content:Ft(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},Nt)))}};function Wt(t){return!_e(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(Ie)}a(Wt,"completionSnapshots");function Ie(t){return _e(t)&&typeof t.id=="string"&&typeof t.source=="string"&&typeof t.command=="string"&&typeof t.cwd=="string"&&typeof t.shell=="string"&&typeof t.background=="boolean"&&typeof t.status=="string"&&typeof t.startedAt=="number"&&typeof t.elapsedMs=="number"&&typeof t.output=="string"}a(Ie,"isTerminalSessionSnapshot");function Ft(t){return`${t.length===1?"Background terminal completed:":"Background terminals completed:"}
23
- ${t.map(n=>{let r=n.exitCode===void 0?"":`, exit ${n.exitCode}`,i=n.completionReason===void 0?"":`, reason ${n.completionReason}`,o=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${Me(n.elapsedMs)}
24
- ${o||"(no output)"}`}).join(`
25
- `)}`}a(Ft,"formatCompletionMessage");function jt(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${Me(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
26
- ${e||"(no output)"}`}a(jt,"formatStaleMessage");function Me(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Me,"formatElapsed");function _e(t){return typeof t=="object"&&t!==null}a(_e,"isRecord");async function Gt(t){let e=re("terminal")??new A,n=$e(),r=new C(t,e),i=te(t).add(de(e));await Promise.all([we(t,e),Te(t,e)]),ke(t,e,n,r),t.on("session_start",(o,s)=>r.bind(s)),t.on("agent_settled",(o,s)=>r.onAgentSettled(s)),t.on("session_shutdown",async o=>{if(r.dispose(),i(),o.reason==="reload"){ne("terminal",e);return}ie("terminal",e),await e.dispose()})}a(Gt,"registerTerminal");export{Gt as default};
@@ -1 +0,0 @@
1
- import{a as w}from"./chunk-5PLV4HLG.js";import{a as C,b as E}from"./chunk-EJ5OACQM.js";import{a as n}from"./chunk-EI7MMDWY.js";import{DynamicBorder as $}from"@earendil-works/pi-coding-agent";import{Container as W,Key as S,matchesKey as M,SelectList as _,Text as m,truncateToWidth as D,visibleWidth as I}from"@earendil-works/pi-tui";var v=class{constructor(e,s,i){this.registry=e;this.activityMode=s;e.onDidChange(()=>this.#s()),i.registerCommand("agent-ide-processes",{description:"Show active terminal and debugger processes created by Agent IDE",handler:n(async(r,d)=>{if(this.bind(d),d.mode!=="tui"){d.ui.notify("The Agent IDE process overlay requires the TUI.","info");return}await this.#r(d)},"handler")})}static{n(this,"AgentIdeProcessesUi")}#t;#i=!1;#e;bind(e){this.#i||(this.#t=e,this.#s())}dispose(){this.#i=!0,this.#e!==void 0&&clearInterval(this.#e),this.#e=void 0,this.#t?.ui.setWidget("agent-ide-processes",void 0),this.#t?.ui.setStatus("agent-ide-processes",void 0),this.#t=void 0}#n(){return this.registry.list()}#s(){let e=this.#t;if(this.#i||e===void 0||!e.hasUI)return;let s=this.#n();if(this.activityMode==="off"||s.length===0){e.ui.setWidget("agent-ide-processes",void 0),e.ui.setStatus("agent-ide-processes",void 0),this.#e!==void 0&&clearInterval(this.#e),this.#e=void 0;return}if(this.activityMode==="compact"){e.ui.setWidget("agent-ide-processes",void 0),e.ui.setStatus("agent-ide-processes",`Agent IDE processes: ${s.length}`);return}e.ui.setStatus("agent-ide-processes",void 0),e.ui.setWidget("agent-ide-processes",(i,r)=>({invalidate(){},render:n(d=>k(s,d,r),"render")}),{placement:"belowEditor"}),this.#e??=setInterval(()=>this.#s(),1e3)}async#r(e){for(;;){if(this.#n().length===0){e.ui.notify("No active Agent IDE processes.","info");return}let s=n(()=>{},"disposeRefresh"),i,r;try{r=await e.ui.custom((u,c,O,x)=>{let y=this.#n(),f="list",g,P=n(l=>{let a=y.map(o=>({value:o.source,label:`${o.status} ${o.kind} ${o.title}`,description:o.description})),p=new _(a,Math.min(a.length,12),{selectedPrefix:n(o=>c.fg("accent",o),"selectedPrefix"),selectedText:n(o=>c.fg("accent",o),"selectedText"),description:n(o=>c.fg("muted",o),"description"),scrollInfo:n(o=>c.fg("dim",o),"scrollInfo"),noMatch:n(o=>c.fg("warning",o),"noMatch")}),b=a.findIndex(o=>o.value===l);return b>=0&&p.setSelectedIndex(b),p.onSelect=o=>{g=y.find(R=>R.source===o.value),f="detail",u.requestRender()},p.onCancel=()=>x(null),p},"createList"),h=P(),A=n(()=>{let l=g?.source??h.getSelectedItem()?.value;y=this.#n(),g=f==="list"?void 0:y.find(a=>a.source===l),h=P(l),u.requestRender()},"refresh");return s=this.registry.onDidChange(A),i=setInterval(A,1e3),{invalidate:n(()=>h.invalidate(),"invalidate"),render(l){let a=new W;return a.addChild(new $(p=>c.fg("accent",p))),f==="list"?(a.addChild(new m(c.fg("accent",c.bold("Agent IDE processes")),1,0)),a.addChild(h),a.addChild(new m(c.fg("dim","enter view \xB7 d stop \xB7 esc close"),1,0))):g===void 0?a.addChild(new m(c.fg("warning","Process is no longer active."),1,0)):(a.addChild(g.renderDetail(c)),a.addChild(new m(c.fg(f==="confirm"?"warning":"dim",f==="confirm"?"Stop this process? y confirm \xB7 n/esc cancel":"esc back \xB7 d stop"),1,0))),a.addChild(new $(p=>c.fg("accent",p))),a.render(l)},handleInput(l){f==="list"?l==="d"?(g=y.find(a=>a.source===h.getSelectedItem()?.value),g!==void 0&&(f="confirm")):h.handleInput(l):f==="detail"?M(l,S.escape)?f="list":l==="d"&&(f="confirm"):l==="y"&&g!==void 0?x({source:g.source}):(l==="n"||M(l,S.escape))&&(f="detail"),u.requestRender()}}},{overlay:!0,overlayOptions:{width:"75%",maxHeight:"80%",minWidth:52}})}finally{s(),i!==void 0&&clearInterval(i)}if(r===null)return;let d=this.#n().find(u=>u.source===r.source);d!==void 0&&await d.stop()}}};function k(t,e,s){if(t.length===0)return[];let i=n(d=>s.fg("accent",d),"accent"),r=[q("Agent IDE Processes",`${t.length} active`,e,i)];for(let[d,u]of t.entries()){for(let c of u.renderSummary(s))r.push(T(` ${c} `,e,i));d<t.length-1&&r.push(T("",e,i))}return r.push(L(e,i)),r}n(k,"renderProcessWidget");function q(t,e,s,i){if(s<=1)return i("\u256D");let r=s-2,d=`\u2500 ${t} `,u=` ${e} \u2500`,c="\u2500".repeat(Math.max(0,r-I(d)-I(u)));return i(`\u256D${D(`${d}${c}${u}`,r).padEnd(r,"\u2500")}\u256E`)}n(q,"borderTop");function T(t,e,s){if(e<=1)return s("\u2502");let i=e-2,r=D(t,i);return`${s("\u2502")}${r}${" ".repeat(Math.max(0,i-I(r)))}${s("\u2502")}`}n(T,"borderLine");function L(t,e){return e(t<=1?"\u2570":`\u2570${"\u2500".repeat(t-2)}\u256F`)}n(L,"borderBottom");async function B(t){let e=w(t),s=await E(C()),i=new v(e,K(s.preferences?.["processes.activity"]),t);t.on("session_start",(r,d)=>i.bind(d)),t.on("session_shutdown",()=>i.dispose())}n(B,"registerAgentIdeProcesses");function K(t){return t==="compact"||t==="off"?t:"detailed"}n(K,"activityMode");export{B as default};
@@ -1,2 +0,0 @@
1
- import{a as j}from"./chunk-GUTQ3PWL.js";import{m as S}from"./chunk-5VSE5X5R.js";import{a as g}from"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import{createHash as le}from"node:crypto";import{readFile as J}from"node:fs/promises";import f from"node:path";import{spawn as Z}from"node:child_process";import _ from"node:path";import{createInterface as ee}from"node:readline";import{existsSync as X}from"node:fs";import Y from"node:os";import H from"node:path";function F(e=process.env.PI_CODING_AGENT_DIR??H.join(Y.homedir(),".pi","agent"),t=process.platform){let n=H.join(e,"bin",t==="win32"?"rg.exe":"rg");return X(n)?n:"rg"}a(F,"resolveRipgrepExecutable");async function R(e,t,n){if(e.query.length===0)throw new Error("Search query must not be empty.");if(/\r|\n/u.test(e.query))throw new Error("Search supports one-line patterns only.");let r=_.resolve(t,re(e.path??".")),o=["--json","--no-config","--no-ignore-parent","--color=never","--with-filename","--line-number",e.caseSensitive===!0?"--case-sensitive":"--ignore-case",...e.wholeWord===!0?["--word-regexp"]:[],...O(e.include).flatMap(i=>["--glob",i]),...O(e.exclude).flatMap(i=>["--glob",`!${i}`]),"--",e.query,r];if(e.regex!==!0)return k(["--fixed-strings",...o],n);try{return await k(["--engine","auto",...o],n)}catch(i){if(!te(i))throw i;return k(["--engine","default",...o],n)}}a(R,"searchText");function k(e,t){return new Promise((n,r)=>{let o=Z(F(),e,{stdio:["ignore","pipe","pipe"]}),i=ee({input:o.stdout}),s=[],l="",c,u=a(()=>{o.kill()},"abort"),d=a(()=>{t?.removeEventListener("abort",u),i.close()},"cleanup");o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{l+=m}),i.on("line",m=>{if(!(c!==void 0||m.length===0))try{let h=JSON.parse(m);if(h.type!=="match")return;for(let b of ne(h))s.push(b)}catch(h){c=h,o.kill()}}),o.once("error",m=>{d(),r(m)}),o.once("close",m=>{if(d(),t?.aborted===!0){let h=new Error("Search was aborted.");h.name="AbortError",r(h);return}if(c!==void 0){r(new Error("Unable to parse ripgrep search output.",{cause:c}));return}if(m!==0&&m!==1){r(new Error(l.trim()||`ripgrep exited with code ${String(m)}.`));return}s.sort(oe),n({matches:s,complete:!0})}),t?.addEventListener("abort",u,{once:!0}),t?.aborted===!0&&u()})}a(k,"runRipgrep");function te(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}a(te,"isPcre2MatchLimitError");function ne(e){let t=e.data.path.text,n=e.data.lines.text;if(t===void 0||n===void 0||!Number.isSafeInteger(e.data.line_number))return[];let r=n.replace(/(?:\r\n|\n)$/u,""),o=Buffer.from(n),i=[];for(let s of e.data.submatches){if(s.start<0||s.end<=s.start||s.end>o.length)continue;let l=o.subarray(0,s.start).toString("utf8").length,c=o.subarray(0,s.end).toString("utf8").length;i.push({source:_.resolve(t),lineNumber:e.data.line_number,startColumn:l,endColumn:c,matchedText:r.slice(l,c),lineText:r})}return i}a(ne,"matchesFromEvent");function O(e){if(e===void 0)return[];let t=[],n=0,r="";for(let o of e){if(o==="{"?n+=1:o==="}"&&(n=Math.max(0,n-1)),n===0&&(o===","||/\s/u.test(o))){r.length>0&&(t.push(r),r="");continue}r+=o}return r.length>0&&t.push(r),t}a(O,"splitGlobList");function re(e){return e.startsWith("@")?e.slice(1):e}a(re,"stripFilePrefix");function oe(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}a(oe,"compareMatches");function E(e,t=!1){let n=C(e);if(!N(n))return t?e:$(e);let r=v(new A(e,n).parse(),t);return`^${r.condition}.*?\\K(${r.match})`}a(E,"compileSearchQuery");function W(e){if(N(C(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map($).join("|")})`:void 0}a(W,"compileSearchFallbackQuery");function N(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}a(N,"containsBooleanSyntax");var A=class{static{a(this,"BooleanQueryParser")}#t;#r;#i=0;constructor(t,n){this.#t=t,this.#r=n}parse(){let t=this.#s(),n=this.#e();if(n.type!=="end"){let r=n.type==="right"?"unexpected ')'.":`unexpected ${ce(n)}.`;throw p(n.offset,r)}return t}#s(){let t=this.#n();for(;this.#e().type==="or";){let n=this.#o(),r=this.#c(`after ${n.value}`);t={kind:"or",left:t,right:this.#a(r)}}return t}#n(){return this.#a(this.#c())}#a(t){let n=t;for(;;){let r=this.#e();if(r.type==="and"||r.type==="not"){this.#o();let o=this.#c(`after ${r.value}`);n={kind:r.type,left:n,right:o};continue}if(r.type==="term"||r.type==="left"){n={kind:"and",left:n,right:this.#c()};continue}return n}}#c(t){let n=this.#e();if(n.type==="term")return this.#o(),{kind:"term",value:n.value,quoted:n.quoted};if(n.type==="left"){if(this.#o(),this.#e().type==="right"||this.#e().type==="end")throw p(this.#e().offset,"expected a term after '('.");let o=this.#s();if(this.#e().type!=="right")throw p(this.#e().offset,"expected ')'.");return this.#o(),o}if(t===void 0&&(n.type==="and"||n.type==="or"||n.type==="not"))throw p(n.offset,`expected a term before ${n.value}.`);let r=t===void 0?"":` ${t}`;throw p(n.offset,`expected a term${r}.`)}#e(){return this.#r[this.#i]??{type:"end",value:"",offset:this.#t.length}}#o(){let t=this.#e();return this.#i+=1,t}};function C(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&ie(e,n)){t.push({type:"left",value:r,offset:n}),n+=1;continue}if(r===")"){t.push({type:"right",value:r,offset:n}),n+=1;continue}if(D(e,n)){let s=e.charAt(n+1)==="|"?2:1;t.push({type:"or",value:e.slice(n,n+s),offset:n}),n+=s;continue}if(r==="'"||r==='"'){let s=n,l=r,c="";for(n+=1;n<e.length&&e.charAt(n)!==l;)e.charAt(n)==="\\"&&(e.charAt(n+1)===l||e.charAt(n+1)==="\\")&&(n+=1),c+=e.charAt(n++);if(n>=e.length)throw p(s,`unterminated ${l==="'"?"single":"double"}-quoted term.`);if(n+=1,c.length===0)throw p(s,"quoted terms must not be empty.");t.push({type:"term",value:c,offset:s,quoted:!0});continue}let o=n;for(;n<e.length;){let s=e.charAt(n);if(/\s/u.test(s)||s===")"||D(e,n))break;s==="\\"&&n+1<e.length?n+=2:s==="["||s==="("?n=M(e,n)??n+1:n+=1}let i=e.slice(o,n);t.push({type:se(i),value:i,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}a(C,"tokenize");function D(e,t){return e.charAt(t)==="|"&&(e.charAt(t+1)==="|"||/\s/u.test(e.charAt(t-1))&&/\s/u.test(e.charAt(t+1)))}a(D,"isBooleanPipe");function M(e,t){let n=e.charAt(t)==="["?"]":")",r=t+1;for(;r<e.length;){let o=e.charAt(r);if(o==="\\")r+=2;else{if(o===n)return r+1;if(n===")"&&(o==="("||o==="[")){let i=M(e,r);if(i===void 0)return;r=i}else r+=1}}}a(M,"regexBlockEnd");function ie(e,t){let n=M(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:N(C(r))}a(ie,"isBooleanGroup");function se(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}a(se,"operatorType");function ce(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}a(ce,"quoteToken");function p(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(p,"syntaxError");function v(e,t){if(e.kind==="term"){let o=t&&!e.quoted?e.value:$(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let n=v(e.left,t),r=v(e.right,t);return e.kind==="or"?{condition:`(?:${n.condition}|${r.condition})`,match:`(?:${n.match}|${r.match})`}:e.kind==="not"?{condition:`${n.condition}(?!${r.condition})`,match:n.match}:{condition:`${n.condition}${r.condition}`,match:`(?:${n.match}|${r.match})`}}a(v,"compileExpression");function $(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}a($,"escapeRegex");function $e(e){let t=E(e.query),n=E(e.query,!0),r=W(e.query),o=[];return n!==t&&o.push({query:n,mode:"regex"}),r!==void 0&&r!==t&&r!==n&&o.push({query:r,mode:"words"}),{...e,query:t,regex:!0,fallbacks:o}}a($e,"createSearchRecipe");async function B(e,t,n){let r=e.query,o=await R(e,t,n),i=[];for(let s of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await R({...e,query:s.query,regex:!0},t,n),r=s.query,i.push(s.mode==="regex"?"Search fallback: no literal matches; tried unquoted terms as regex.":"Search fallback: no matches in earlier modes; tried separate words.")}catch(l){if(s.mode!=="regex"||!ae(l)||n?.aborted)throw l;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:i}}a(B,"runSearchRecipe");function ae(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}a(ae,"isRegexSyntaxError");var ue=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,z=4;function De(e,t,n,r){return U(e,t,n,r).slice(0,z)}a(De,"createSearchSessionId");function U(e,t,n,r){let o=n===void 0?me(t.map(c=>c.source)):f.resolve(n),i=t.map(c=>({match:c,source:f.relative(o,f.resolve(c.source))})).sort((c,u)=>c.source.localeCompare(u.source)||I(c.match,u.match)).map(({match:c,source:u})=>[u,c.lineNumber,c.startColumn,c.endLineNumber??c.lineNumber,c.endColumn,c.matchedText,c.lineText]),{limit:s,...l}=K(r??{query:e,regex:!0},o);return le("sha256").update(JSON.stringify([e,o,l,i])).digest("hex").toUpperCase()}a(U,"createSearchSessionIdentity");function de(e,t){if(!/^[A-F0-9]{64}$/u.test(e))throw new Error("Search session identity must be a 64-character uppercase hexadecimal value.");for(let n=z;n<=e.length;n+=1){let r=e.slice(0,n);if(!t.has(r))return r}throw new Error("Could not allocate a unique search session id.")}a(de,"allocateSearchSessionId");function K(e,t){return{query:e.query,path:f.resolve(t,e.path??"."),include:e.include??"",exclude:e.exclude??"",caseSensitive:e.caseSensitive===!0,wholeWord:e.wholeWord===!0,limit:e.limit??50,regex:e.regex===!0,fallbacks:e.fallbacks??[]}}a(K,"normalizeRecipe");var Q=class{constructor(t=U){this.createIdentity=t}static{a(this,"SearchSessionStore")}#t=new Map;#r=new Map;async register(t,n,r,o,i,s={query:t,regex:!0},l){let c=n.map(L=>({...L,source:f.resolve(L.source)})).sort(I),u=await G(c,i),d=this.createIdentity(t,c,o,s),h=this.#r.get(d)??de(d,new Set(this.#t.keys())),b={id:h,query:t,matches:c,complete:r,contentBySource:u,recipe:s,...l!==void 0&&{refresh:l},cwd:f.resolve(o)};return this.#r.set(d,h),this.#t.set(h,b),b}async observeAfterEdit(t,n){let r=new Set(t.flatMap(i=>{let s=typeof i=="string"?w(i):void 0;return s===void 0?[]:[s.id]})),o=[];for(let i of r){let s=this.#t.get(i);if(s===void 0)continue;let l={sessionId:i,query:s.recipe.originalQuery??s.query,scope:K(s.recipe,s.cwd)};try{let c=s.refresh===void 0?await B(s.recipe,s.cwd,n):await s.refresh(n);o.push({...l,matches:c.matches.length,complete:c.complete,notices:c.notices})}catch(c){o.push({...l,error:c instanceof Error?c.message:String(c)})}}return o}anchorResolver(){return{id:"search",description:["`SEARCH#HASH:N:line` selects one result's full line; `SEARCH#HASH:N:match` selects its exact match.","`SEARCH#HASH:all:line` selects each unique containing line; `SEARCH#HASH:all:match` selects every exact match.","Omit `path` when `all` spans files."].join(`
2
- `),renderFull(t){return t},renderCompact(t){let n=w(t);return n===void 0?"selected result":n.selector==="all"?n.mode==="match"?"all matches":"all lines":n.mode==="match"?`match ${String(n.selector)}`:`line ${String(n.selector)}`},tryResolve:a((t,n)=>this.#i(t,n.source,n.signal),"tryResolve")}}resourceResolver(){return{id:"search-targets",tryResolve:a((t,n)=>this.#s(t,n.cwd),"tryResolve")}}async#i(t,n,r){let o=w(t);if(o===void 0)return{kind:"not-handled"};let i=this.#t.get(o.id);if(i===void 0)return x();if(o.selector==="all"&&!i.complete)return y();let s=f.resolve(n),l=i;if(o.selector==="all"){if(i.refreshedComplete?.complete===!0)l=i.refreshedComplete;else if(i.refreshedComplete!==void 0&&(l=await this.#n(i,r),!l.complete))return y()}let c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s);if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};let d=await P(s,r);if(d===void 0)return x(g(u[0]).lineNumber);if(o.selector==="all"&&d!==l.contentBySource.get(s)){if(l=await this.#n(i,r),!l.complete)return y();c=T(l,o.selector,o.mode),u=c.filter(h=>h.source===s)}if(u.length===0)return{kind:"rejected",rejection:{code:"missing",reason:"search anchor does not select this resource"}};if(o.selector!=="all"&&d!==i.contentBySource.get(s))return x(g(u[0]).lineNumber);let m=S(s,d);return{kind:"resolved",anchor:new j(t,s,u.map(h=>q(m,h,o.mode)))}}async#s(t,n){let r=w(t);if(r===void 0)return{kind:"not-handled"};let o=this.#t.get(r.id);if(o===void 0)return x();if(r.selector==="all"&&!o.complete)return y();let i=o;if(r.selector==="all"){if(o.refreshedComplete?.complete===!0)i=o.refreshedComplete;else if(o.refreshedComplete!==void 0&&(i=await this.#n(o),!i.complete))return y();let u=new Set(T(i,r.selector,r.mode).map(d=>d.source));for(let d of u)if(await P(d)!==i.contentBySource.get(d)){if(i=await this.#n(o),!i.complete)return y();break}}let s=T(i,r.selector,r.mode);if(r.selector!=="all"){let u=s[0]?.source;if(u!==void 0&&await P(u)!==i.contentBySource.get(u))return x(s[0]?.lineNumber)}let l=new Map;for(let u of s){let d=l.get(u.source)??[];d.push(q(S(u.source,i.contentBySource.get(u.source)??u.lineText),u,r.mode)),l.set(u.source,d)}let c=[...l].map(([u,d])=>({source:u,ranges:d,expectedContent:i.contentBySource.get(u)}));return c.length===0?{kind:"rejected",rejection:{code:"missing",reason:"search anchor has no matches"}}:{kind:"resolved",targets:c}}async#n(t,n){let r=t.refresh===void 0?await B(t.recipe,t.cwd,n):await t.refresh(n),o=r.matches.map(s=>({...s,source:f.resolve(s.source)})).sort(I),i={matches:o,complete:r.complete,contentBySource:await G(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:i}),i}};function w(e){let t=ue.exec(e);if(t!==null)return{id:g(t[1]),selector:t[2]==="all"?"all":Number(t[2]),mode:t[3]==="line"?"line":"match"}}a(w,"parseSearchAnchor");function T(e,t,n){let r=t==="all"?e.matches:[e.matches[t-1]].filter(he);if(n==="match"||t!=="all")return r;let o=new Set;return r.flatMap(i=>{let s=S(i.source,e.contentBySource.get(i.source)??i.lineText),l=V(i);return s.lines.slice(i.lineNumber-1,l).flatMap(c=>{let u=`${i.source}\0${String(c.lineNumber)}`;return o.has(u)?[]:(o.add(u),[{...i,lineNumber:c.lineNumber,endLineNumber:c.lineNumber,startColumn:0,endColumn:c.content.length,lineText:c.content,matchedText:c.content}])})})}a(T,"selectMatches");function he(e){return e!==void 0}a(he,"isMatch");function V(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(V,"lastContainingLine");function q(e,t,n){if(n==="match")return{start:{lineNumber:t.lineNumber,column:t.startColumn},end:{lineNumber:t.endLineNumber??t.lineNumber,column:t.endColumn}};let r=V(t),o=g(e.lines[r-1]);return{start:{lineNumber:t.lineNumber,column:0},end:{lineNumber:r+(o.lineEnding.length>0?1:0),column:o.lineEnding.length>0?0:o.content.length},linewise:!0}}a(q,"selectionRange");function fe(e,t){let n=t.endLineNumber??t.lineNumber;return e.lines.slice(t.lineNumber-1,n).map(r=>{let o=r.lineNumber===t.lineNumber?t.startColumn:0,i=r.lineNumber===n?t.endColumn:r.content.length;return r.content.slice(o,i)+(r.lineNumber===n?"":r.lineEnding)}).join("")}a(fe,"matchedSourceText");async function G(e,t){let n=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await J(r,{encoding:"utf8",...t!==void 0&&{signal:t}}),i=S(r,o);for(let s of e.filter(l=>l.source===r))if(i.lines[s.lineNumber-1]?.content!==s.lineText||fe(i,s)!==s.matchedText)throw new Error(`Search result in ${r} changed before its anchors were registered.`);n.set(r,o)}return n}a(G,"snapshotContents");async function P(e,t){try{return await J(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(P,"readCurrent");function x(e=1){return{kind:"rejected",rejection:{code:"stale",reason:"search anchor is stale",contextRange:{offset:Math.max(1,e-2),limit:5}}}}a(x,"staleAnchor");function y(){return{kind:"rejected",rejection:{code:"missing",reason:"search did not register an all anchor because its result was limited"}}}a(y,"missingCompleteAnchor");function me(e){if(e.length===0)return".";let t=f.dirname(f.resolve(g(e[0])));for(let n of e.slice(1)){let r=f.resolve(n);for(;!pe(t,r);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}a(me,"commonSourceDirectory");function pe(e,t){let n=f.relative(e,t);return n!==".."&&!n.startsWith(`..${f.sep}`)&&!f.isAbsolute(n)}a(pe,"isWithin");function I(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||(e.endLineNumber??e.lineNumber)-(t.endLineNumber??t.lineNumber)||e.endColumn-t.endColumn}a(I,"compareMatches");export{F as a,$e as b,B as c,De as d,U as e,de as f,Q as g};
@@ -1,14 +0,0 @@
1
- # Evaluation
2
-
3
- Pi Agent IDE is still experimental. Evaluation compares it with vanilla Pi instead of assuming that richer tools always improve agent behavior.
4
-
5
- Current studies use repeatable coding tasks and editing gyms. They inspect:
6
-
7
- - task completion and correctness;
8
- - tool calls and failed tool calls;
9
- - input, output, and cache tokens;
10
- - unnecessary reads and repeated searches;
11
- - edit retries and recovery from stale context;
12
- - cases where specialized tools make a task harder.
13
-
14
- Results depend on the model, prompt, repository, and task. A result from one suite is evidence about that suite, not a universal performance claim.