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.
- package/README.md +74 -22
- package/assets/gallery/apply-editing.png +0 -0
- package/assets/gallery/debugging.png +0 -0
- package/assets/gallery/read-web.png +0 -0
- package/assets/gallery/search-replace.png +0 -0
- package/assets/gallery/terminal.png +0 -0
- package/assets/gallery/tool-editing.png +0 -0
- package/dist/chunk-7ALCBKCW.js +26 -0
- package/dist/{chunk-ZUMN6U77.js → chunk-IRECDTJG.js} +1 -1
- package/dist/chunk-NZYDMBM6.js +1 -0
- package/dist/chunk-P7XO5CIP.js +2 -0
- package/dist/entry-47.js +10 -10
- package/dist/entry-48.js +1 -1
- package/dist/entry-76.js +3 -1
- package/dist/pi-agent-ide.js +1 -1
- package/docs/development.md +0 -6
- package/node_modules/pi-agent-doctor/package.json +1 -1
- package/node_modules/pi-agent-filesystem/package.json +6 -6
- package/node_modules/pi-agent-filesystem-image/package.json +3 -3
- package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
- package/node_modules/pi-agent-filesystem-text/package.json +3 -3
- package/node_modules/pi-agent-ide-ast/package.json +9 -9
- package/node_modules/pi-agent-ide-changes/package.json +6 -6
- package/node_modules/pi-agent-ide-formatter/package.json +3 -3
- package/node_modules/pi-agent-ide-languages/package.json +2 -2
- package/node_modules/pi-agent-ide-lint/package.json +7 -7
- package/node_modules/pi-agent-ide-lsp/package.json +9 -9
- package/node_modules/pi-agent-image/package.json +2 -2
- package/node_modules/pi-agent-invariant/package.json +1 -1
- package/node_modules/pi-agent-pdf/package.json +2 -2
- package/node_modules/pi-agent-read/package.json +6 -6
- package/node_modules/pi-agent-resource/package.json +1 -1
- package/node_modules/pi-agent-search/package.json +3 -3
- package/node_modules/pi-agent-search-text/package.json +6 -6
- package/node_modules/pi-agent-search-text/src/resolvers.ts +32 -27
- package/node_modules/pi-agent-search-text/src/search-session.ts +27 -1
- package/node_modules/pi-agent-text/package.json +2 -2
- package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
- package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
- package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
- package/node_modules/pi-agent-text-editor/package.json +8 -8
- package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
- package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
- package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
- package/node_modules/pi-agent-tool-ui/package.json +1 -1
- package/node_modules/pi-agent-web/package.json +6 -6
- package/node_modules/pi-agent-web/src/resolver.ts +128 -1
- package/node_modules/pi-agent-web-html/package.json +2 -2
- package/node_modules/pi-agent-web-image/package.json +3 -3
- package/node_modules/pi-agent-web-pdf/package.json +3 -3
- package/node_modules/pi-agent-web-text/package.json +3 -3
- package/package.json +34 -34
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +6 -6
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
- package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +128 -1
- package/src/extensions/pi-agent-read/package.json +6 -6
- package/src/extensions/pi-agent-search/package.json +3 -3
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +32 -27
- package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +27 -1
- package/src/extensions/pi-agent-text-editor/package.json +8 -8
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
- package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
- package/src/plugins/pi-agent-ide-ast/package.json +9 -9
- package/src/plugins/pi-agent-ide-changes/package.json +6 -6
- package/src/plugins/pi-agent-ide-debugger/index.ts +1 -1
- package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
- package/src/plugins/pi-agent-ide-languages/package.json +2 -2
- package/src/plugins/pi-agent-ide-lint/package.json +7 -7
- package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
- package/src/plugins/pi-agent-ide-processes/src/registry.ts +2 -0
- package/src/plugins/pi-agent-ide-processes/src/ui.ts +10 -2
- package/src/plugins/pi-agent-ide-terminal/index.ts +1 -1
- package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +1 -0
- package/src/plugins/pi-agent-ide-terminal/src/search.ts +32 -2
- package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +4 -4
- package/src/plugins/pi-agent-ide-terminal/src/tools.ts +2 -2
- package/src/plugins/pi-agent-ide-terminal/src/types.ts +2 -1
- package/src/plugins/pi-agent-ide-terminal/src/ui.ts +1 -1
- package/dist/chunk-BGUSBUUD.js +0 -26
- package/dist/chunk-QH4ZUDOD.js +0 -1
- package/dist/chunk-ZG2MWXCR.js +0 -2
- package/docs/evaluation.md +0 -14
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
<h1 align="center">Pi Agent IDE</h1>
|
|
6
6
|
|
|
7
|
-
<p align="center">
|
|
7
|
+
<p align="center">IDE capabilities for coding agents in <a href="https://pi.dev/">Pi</a>.</p>
|
|
8
8
|
|
|
9
9
|
<p align="center">
|
|
10
10
|
<a href="https://www.npmjs.com/package/pi-agent-ide"><img src="https://img.shields.io/npm/v/pi-agent-ide" alt="npm version"></a>
|
|
@@ -12,31 +12,81 @@
|
|
|
12
12
|
<a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI status"></a>
|
|
13
13
|
<a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgist.githubusercontent.com%2Falexshpunt%2F0d28d39557e2a9976c4548e7737c102d%2Fraw%2Funit.json" alt="Unit test count"></a>
|
|
14
14
|
<a href="https://github.com/alexshpunt/pi-agent-ide/actions/workflows/ci.yml"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fgist.githubusercontent.com%2Falexshpunt%2F0d28d39557e2a9976c4548e7737c102d%2Fraw%2Fintegration.json" alt="Integration test count"></a>
|
|
15
|
+
<a href="https://alexshpunt-benchmark-explorer.static.hf.space/?filter.harness=pi-agent-ide"><img src="https://img.shields.io/badge/Explicit%20Edit%20Benchmark-v0.5.1%20%E2%80%A2%20not%20tested-lightgrey?style=flat-square" alt="Explicit Edit Benchmark: pi-agent-ide v0.5.1 is not tested yet"></a>
|
|
15
16
|
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/pi-agent-ide" alt="MIT license"></a>
|
|
16
17
|
</p>
|
|
17
18
|
|
|
18
|
-
##
|
|
19
|
+
## Summary
|
|
19
20
|
|
|
20
|
-
Pi Agent IDE is
|
|
21
|
+
Pi Agent IDE is a set of agent-facing tools built to give a coding agent the same practical capabilities that a programmer expects from an IDE.
|
|
21
22
|
|
|
22
|
-
|
|
23
|
+
There are two common views of coding agents. One says that an agent only needs a shell and can build everything else for itself. The other says that useful tooling makes an agent more effective. Both are partly right. Stronger models can often make precise edits and recover with little help. Smaller models are more likely to lose context, choose an unsafe edit, or fail on the mechanics of the task. Pi Agent IDE gives models direct tools without taking the shell away.
|
|
23
24
|
|
|
24
|
-
|
|
25
|
+
The project started as another take on hash-based editing. It later brought back edits by exact string occurrence, with every occurrence checked before a change is applied. The result is a hybrid approach rather than one required selection method.
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
## Gallery
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
-
|
|
35
|
-
- `/agent-ide-processes` shows terminal and debugger activity, while `/pi-agent-ide-doctor` checks the languages and tools available in the current project.
|
|
29
|
+
| Read and guarded tool editing | Transactional Apply |
|
|
30
|
+
| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
31
|
+
|  |  |
|
|
32
|
+
| Web reading | Search and replace |
|
|
33
|
+
|  |  |
|
|
34
|
+
| Background processes | Source-level debugging |
|
|
35
|
+
|  |  |
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
## Core principles
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
### One interface for each intent
|
|
40
|
+
|
|
41
|
+
The agent should express what it wants to do without choosing a different tool for every implementation behind it.
|
|
42
|
+
|
|
43
|
+
`read` is the main interface to the environment. It reads text, source code, raw bytes, web pages, images, PDFs, terminal sessions, debugger sessions, and diagnostics. The same interface can ask for AST structure, language-server information, anchors, or other views. The agent chooses the information it needs while the parsing, conversion, and resource handling stay behind one facade.
|
|
44
|
+
|
|
45
|
+
`search` follows the same rule. It searches files, text, symbols, syntax trees, and supported live resources through one interface.
|
|
46
|
+
|
|
47
|
+
Editing tools state concrete intentions such as `write`, `replace`, `insert`, `delete`, `copy`, and `move`. Simple edits use guarded operations that verify the selected text or resource. Independent edits can be submitted together as a tool-call batch. For conditional or multi-file work, `apply` gives the agent isolated JavaScript over immutable file snapshots and the same guarded editing model, then validates and commits the staged changes as one transaction. This lets models use scripts for complex work without reducing an edit to an unchecked rewrite.
|
|
48
|
+
|
|
49
|
+
### IDE tools
|
|
50
|
+
|
|
51
|
+
The shell remains available, but it behaves like part of an IDE. The agent can start long-running and interactive processes, leave them in the background, reconnect after an extension reload, and receive completion or stale-process notifications. Aborting an agent turn does not kill the process.
|
|
52
|
+
|
|
53
|
+
Debugger sessions are also addressable resources. The agent can set breakpoints, inspect source and variables, step through a program, and reconnect after a reload. Formatting, diagnostics, AST views, language-server views, terminal output, and debugger state work through the same resource model. This support is currently focused on Linux and WSL.
|
|
54
|
+
|
|
55
|
+
### Extensible by protocol
|
|
56
|
+
|
|
57
|
+
The visible tools stay small because their internals are protocols. HTTP reads, filesystem reads, terminal and debugger resources, file formats, AST views, language-server views, converters, search backends, anchors, formatters, and diagnostics can be added or replaced independently.
|
|
58
|
+
|
|
59
|
+
The goal is simple primitives on the outside and composable complexity on the inside. New capabilities should extend an existing intent-shaped interface instead of adding another one-off tool.
|
|
60
|
+
|
|
61
|
+
### Make recovery cheap
|
|
62
|
+
|
|
63
|
+
Agents can edit through exact strings, hash anchors, search results, AST matches, and language-server symbols. If one method fails, the tool explains why, shows the available alternatives, and points the agent to a more precise method. The goal is not to punish a bad selection with stricter guardrails. Smaller models will make mistakes. Recovery should cost as little time and context as possible.
|
|
64
|
+
|
|
65
|
+
The tools are designed to combine. A common flow is `search` followed by `replace`: the agent finds the intended occurrences, then edits all selected matches in one guarded operation. The same model supports structural changes and renames through search, AST, and LSP without requiring a separate workflow for each one.
|
|
66
|
+
|
|
67
|
+
### Observability
|
|
68
|
+
|
|
69
|
+
Powerful agents still need to be observable. A person should be able to see whether the harness is efficient, whether the agent is solving the real task, which tools fit its work, and where weak points or corner cases appear.
|
|
70
|
+
|
|
71
|
+
This is more than presentation. Observable behavior provides the evidence that drives tool design, regression fixes, and benchmark work.
|
|
72
|
+
|
|
73
|
+
### Data-driven development
|
|
74
|
+
|
|
75
|
+
Daily use and judgement still matter, but features should not be built on vibes alone. Changes are measured on real tasks to find where agents fail, which model families work better or worse with the tools, and how Pi Agent IDE compares with other harnesses.
|
|
76
|
+
|
|
77
|
+
The [Explicit Edit Benchmark](https://github.com/alexshpunt/explicit-edit-benchmark) was created for this purpose. It measures how easily agents can use editing tools on exact, deterministic tasks. These tasks are especially useful for smaller models and models with limited reasoning, where tool design has a larger effect on reliability.
|
|
78
|
+
|
|
79
|
+
Agent results are stochastic and no benchmark captures everything. We publish the score we actually get and build broader statistics instead of selecting only favorable runs.
|
|
80
|
+
|
|
81
|
+
Pi Agent IDE is experimental and under active development. Interfaces and behavior may change.
|
|
82
|
+
|
|
83
|
+
## Customization
|
|
84
|
+
|
|
85
|
+
Pi Agent IDE follows Pi's permissive, YOLO-style default: the agent can use the tools without asking for approval at every step. You can make it as strict as your work requires.
|
|
86
|
+
|
|
87
|
+
- [Settings](./docs/configuration.md) control built-in tools, project mappings, search, and presentation.
|
|
88
|
+
- [File hooks](./docs/user-hooks.md) can inspect, change, or deny reads and edits.
|
|
89
|
+
- [Extensions](./docs/extensions.md) can add or replace protocols, resolvers, anchors, search backends, and other behavior.
|
|
40
90
|
|
|
41
91
|
## Installation
|
|
42
92
|
|
|
@@ -50,7 +100,7 @@ Pi packages run with your full system permissions. Review the package before ins
|
|
|
50
100
|
|
|
51
101
|
## Check project tools
|
|
52
102
|
|
|
53
|
-
Pi Agent IDE includes formatter, linter, and
|
|
103
|
+
Pi Agent IDE includes formatter, linter, LSP, and debugger mappings. It finds each tool from the project that owns the file, including project-local binaries and commands on your `PATH`. Settings from one project do not leak into another.
|
|
54
104
|
|
|
55
105
|
Start Pi in your project directory, then run:
|
|
56
106
|
|
|
@@ -66,6 +116,12 @@ Doctor also reports optional system Chrome/Chromium support for browser-rendered
|
|
|
66
116
|
|
|
67
117
|
Run doctor again after installing or changing project tools. For configuration paths, precedence, and command flags, see [Configuration](./docs/configuration.md#doctor).
|
|
68
118
|
|
|
119
|
+
## Feedback and contributions
|
|
120
|
+
|
|
121
|
+
Pi Agent IDE is used actively in real development, but I can only reproduce the models, tools, environments, and workflows available to me. Everyone works differently, and I cannot find or cover every case on my own. I can fix problems when I encounter them or when someone reports them.
|
|
122
|
+
|
|
123
|
+
If something breaks, behaves badly, or does not fit your workflow, please [open an issue](https://github.com/alexshpunt/pi-agent-ide/issues). Bug reports, ideas, and questions are welcome. Pull requests are welcome too. Every contribution will be considered, and I am fully open to making the project much better with help from its users.
|
|
124
|
+
|
|
69
125
|
## Documentation
|
|
70
126
|
|
|
71
127
|
| Document | Contents |
|
|
@@ -73,13 +129,9 @@ Run doctor again after installing or changing project tools. For configuration p
|
|
|
73
129
|
| [Tools and workflow](./docs/tools.md) | Read, search, editing, anchors, and feedback |
|
|
74
130
|
| [Architecture](./docs/architecture.md) | Module boundaries, protocols, and the umbrella extension |
|
|
75
131
|
| [Configuration](./docs/configuration.md) | Run doctor, configure project tools and search, or disable built-ins |
|
|
132
|
+
| [File hooks](./docs/user-hooks.md) | Inspect, change, or deny reads and edits |
|
|
76
133
|
| [Writing extensions](./docs/extensions.md) | Add resolvers, anchors, search backends, and IDE plugins |
|
|
77
134
|
| [Development](./docs/development.md) | Work from a checkout, test, and run modular mode |
|
|
78
|
-
| [Evaluation](./docs/evaluation.md) | Compare Pi Agent IDE with vanilla Pi on repeatable tasks |
|
|
79
|
-
|
|
80
|
-
## Repository
|
|
81
|
-
|
|
82
|
-
Executable behavior is defined by the source and tests. The documents above explain the intended boundaries, extension contracts, and development workflows.
|
|
83
135
|
|
|
84
136
|
## License
|
|
85
137
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{a as re,b as ie,c as oe}from"./chunk-ESPNEJHK.js";import{a as ne}from"./chunk-5PLV4HLG.js";import{b as R}from"./chunk-526E364R.js";import"./chunk-YHUTTZC6.js";import{a as K}from"./chunk-6CZO43OH.js";import{a as Y,b as V}from"./chunk-OBNING2A.js";import{a as te}from"./chunk-ZTYWHL2F.js";import{a as Q,b as ee}from"./chunk-7UGNGK7Y.js";import{a as Z}from"./chunk-L7JMDDSD.js";import{a as z,b as J}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import{a}from"./chunk-EI7MMDWY.js";import Fe from"node:path";import{stripVTControlCharacters as je}from"node:util";import{truncateLine as Ge}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 ae,formatSize as Ue,truncateTail as We}from"@earendil-works/pi-coding-agent";function I(t){return We(t,{maxBytes:se-4096,maxLines:ae-32})}a(I,"terminalOutputTail");function P(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(o=>o!==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"?`${ae} line output budget`:`${Ue(se)} output budget`,s=`[Earlier output omitted: showing the last ${e.outputLines} of ${e.totalLines} lines (${i}). Full output: ${t.fullOutputPath}]`;return`${n.join(`
|
|
5
|
+
`)}
|
|
6
|
+
output:
|
|
7
|
+
${s}${r.length===0?"":`
|
|
8
|
+
${r}`}`}a(P,"formatAgentTerminalSnapshot");var He=500;function le(t,e,n,r,i){let s=e?"background":"wait",o=`${i.fg("toolTitle",r.displayName.toLocaleLowerCase())} ${i.fg("muted",`\xB7 ${E(n)} \xB7 ${s}`)}`;return new x(`${o}
|
|
9
|
+
${i.fg("accent",O(r.family))} ${t}`,0,0)}a(le,"renderRunCall");function ue(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(ue,"renderTerminalActionResult");function $(t,e,n,r,i){let s=[Ye(t,i),i.fg("accent",`${e} ${n}`)];return r.length>0&&s.push(...r.map(o=>` ${i.fg("dim",o)}`)),new x(s.join(`
|
|
11
|
+
`),0,0)}a($,"renderTerminalAction");function S(t,e,n,r){let i=Be(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 ce(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(s=>` ${n.fg("dim",s)}`)];return i.push(D(t,(s,o)=>n.fg(s,o))),new x(i.join(`
|
|
13
|
+
`),0,0)}a(ce,"renderRunResult");function de(t,e){let n=a((o,l)=>e?.fg(o,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)}`],s=qe(t.output,2);return s.length>0&&i.push(...s.map(o=>` ${n("dim",M(o,90))}`)),i.push(D(t,n)),i.join(`
|
|
14
|
+
`)}a(de,"renderActiveTerminal");function Be(t,e,n){let r=(t.shell??"terminal").toLocaleLowerCase(),i=t.background===!0?"background":"wait",s=t.cwd===void 0?"workspace":E(t.cwd),o=t.shellFamily??"posix",l=[`${n.fg("accent",r)} ${n.fg("muted",`\xB7 ${s} \xB7 ${i}`)}`,`${n.fg("accent",O(o))} ${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(Be,"terminalCardLines");function qe(t,e){return _(t,e).lines}a(qe,"outputTail");function _(t,e){let n=I(je(t).replaceAll("\r","")),r=n.content.split(`
|
|
15
|
+
`).map(u=>Ge(u.trimEnd(),He).text);r.at(-1)===""&&r.pop();let i=Number.isFinite(e)?Math.max(0,e):r.length,s=Math.max(0,r.length-i),o=Math.max(0,n.totalLines-n.outputLines),l=s+o;return{lines:r.slice(s),...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=Xe(n),i=n==="completed"?"success":n==="running"?"accent":"error",s=[`${r} ${n}`,Ve(t.elapsedMs??0)];return t.waitReason!==void 0&&s.push(`background \xB7 ${t.waitReason}`),t.completionReason!==void 0&&s.push(`reason ${t.completionReason}`),t.exitCode!==void 0?s.push(`exit ${t.exitCode}`):t.signal!==void 0&&s.push(`signal ${t.signal}`),e(i,s.join(" \xB7 "))}a(D,"statusLine");function Xe(t){return t==="completed"?"\u2713":t==="running"?"\u25CF":t==="stopping"?"\u25CC":"\u2717"}a(Xe,"statusIcon");function O(t){return t==="powershell"?"PS>":t==="cmd"?">":"$"}a(O,"promptMarker");function Ye(t,e){let n=(t.shell??"terminal").toLocaleLowerCase(),r=t.cwd===void 0?"workspace":E(t.cwd),i=t.background===!0?"background":"wait",s=M(t.command??"process",48);return`${e.fg("toolTitle",n)} ${e.fg("muted",`\xB7 ${r} \xB7 ${i} \xB7 ${s}`)}`}a(Ye,"terminalIdentity");function E(t){let e=process.env.HOME;return e!==void 0&&(t===e||t.startsWith(`${e}${Fe.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 Ve(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(Ve,"formatElapsed");function me(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=>de(e,n).split(`
|
|
16
|
+
`),"renderSummary"),renderDetail:a(n=>S(e,!0,n),"renderDetail"),sendInput:a(n=>t.write(e.source,n),"sendInput"),stop:a(()=>t.delete(e.source),"stop")})),"list")}}a(me,"terminalProcessProvider");var Ke="#d8dee9",N="#111418",ze=["#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"),s=Math.max(0,Math.min(r.rows-1,n?.start??0)),o=Math.max(1,Math.min(r.rows-s,n?.count??r.rows)),l=i(r.cols*9+24,o*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<o;m+=1){let p=c.getLine(d+s+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||Je(u,h,f,m)}}return r.status==="running"&&c.cursorY>=s&&c.cursorY<s+o&&(u.fillStyle="rgba(216, 222, 233, 0.75)",u.fillRect(12+c.cursorX*9,12+(c.cursorY-s)*18+18-2,9,2)),l.toBuffer("image/png").toString("base64")}a(U,"renderTerminalScreen");function Je(t,e,n,r){let i=pe(e,"foreground"),s=pe(e,"background");e.isInverse()&&([i,s]=[s,i]);let o=12+n*9,l=12+r*18;s!==N&&(t.fillStyle=s,t.fillRect(o,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,o,l),e.isUnderline()&&t.fillRect(o,l+18-2,9*Math.max(1,e.getWidth()),1))}a(Je,"drawCell");function pe(t,e){let n=e==="foreground";if(n?t.isFgDefault():t.isBgDefault())return n?Ke:N;let i=n?t.isFgRGB():t.isBgRGB(),s=n?t.getFgColor():t.getBgColor();return i?`#${s.toString(16).padStart(6,"0")}`:Ze(s)}a(pe,"cellColor");function Ze(t){let e=ze[t];if(e!==void 0)return e;if(t>=232){let l=8+(t-232)*10;return fe(l,l,l)}let n=Math.max(0,t-16),r=Math.floor(n/36),i=Math.floor(n%36/6),s=n%6,o=a(l=>l===0?0:55+l*40,"channel");return fe(o(r),o(i),o(s))}a(Ze,"ansiColor");function fe(t,e,n){return`#${[t,e,n].map(r=>r.toString(16).padStart(2,"0")).join("")}`}a(fe,"rgb");var W="\0pi-terminal-write\0",F="\0pi-terminal-keys\0";async function Se(t,e){let n=new Map,r=new Map,i={protocol:Y,apiVersion:V,id:"terminal",setup(o){o.addResolver({resolver:Qe(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")}}),o.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:ge(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:ge(u,d instanceof Error?d.message:String(d))}}}}),o.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.'),o.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.")}},s={protocol:z,apiVersion:J,id:"terminal",setup(o){o.addResolver({resolver:et(e)}),o.tool("write").addHandler({stage:"text-pre-edit",handler:a(async l=>(ye(l.input,e,n),await he(l.input,e,r),tt(l,W)),"handler")}),o.tool("insert").addHandler({stage:"text-pre-edit",handler:a(async l=>(await he(l.input,e,r),ye(l.input,e,n),nt(l)),"handler")});for(let l of["write","insert","delete"])o.addToolRenderer({tool:l,matches:a((u,c)=>st(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,we(l,m),[],c)},renderResult(u,c,d){let m=ot(u.details);return ue(m.action,m.changedLines,d)}});o.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."),o.tool("write").describe("When path is shell:<session>, send content exactly as terminal input without adding Enter."),o.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([K(t,i),Z(t,s)]),t.on("tool_result",async(o,l)=>{if(!w(o.input))return;let u=o.input.path;if(o.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:o.details,isError:!0};if(o.toolName==="delete"&&typeof u=="string"&&y(u)){let X=e.get(u);if(X===void 0)return;let Ne=e.snapshot(X);return e.delete(u).then(()=>({content:[{type:"text",text:`Deleted terminal session ${u}.`}],details:{source:u,deleted:!0,snapshot:Ne,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(o.toolName!=="write"&&o.toolName!=="insert"||o.isError)return;let c=o.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=o.toolName,v=we(h,o.input),b=e.screenChangeRegion(d,m,6),q=[{type:"text",text:`Sent ${v} to ${d.source}.`}];return l.model?.input.includes("image")===!0&&q.push({type:"image",data:await U(e,c,{start:b.startRow,count:b.lines.length}),mimeType:"image/png"}),{content:q,details:{source:d.source,action:h,status:d.status,snapshot:f,input:v,changedLines:b.lines},isError:o.isError}})}a(Se,"registerTerminalResources");function Qe(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:rt(r)}]}}}}}}a(Qe,"createReadResolver");function et(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=it(r),s=i.indexOf(W),o=i.indexOf(F);if(s>=0){t.write(n.source,i.slice(s+W.length));return}if(o>=0){t.sendKeys(n.source,i.slice(o+F.length).trim());return}throw new Error(`Unsupported text operation for ${n.source}`)}}}}}}a(et,"createInputResolver");function tt(t,e){return!w(t.input)||!Te(t.input.path)?t:{...t,input:{...t.input,content:`${e}${typeof t.input.content=="string"?t.input.content:""}`}}}a(tt,"transformWriteInput");function nt(t){if(!w(t.input)||!Te(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(nt,"transformInsertInput");function rt(t){return P(t)}a(rt,"formatSnapshot");function it(t){if(t.length!==1||t[0].type!=="text")throw new Error("Terminal input must contain one text block");return t[0].text}a(it,"singleText");function ge(t,e){return{content:[{type:"text",text:e}],details:{source:t,failure:{code:"READ_FAILED",source:t,resolverId:"terminal",message:e}},isError:!0}}a(ge,"failure");function y(t){return/^shell:[a-f\d]{12}$/u.test(t)}a(y,"isShellSource");function Te(t){return typeof t=="string"&&y(t)}a(Te,"isShellSourceValue");function ot(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(ot,"terminalActionDetails");async 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&&await r.screenReady,r!==void 0&&n.set(t.path,e.screenRows(r))}a(he,"rememberScreen");function ye(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(ye,"rememberOutputEnd");function we(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(we,"terminalInputLabel");function st(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(st,"isTerminalRenderValue");function w(t){return typeof t=="object"&&t!==null}a(w,"isRecord");async function Re(t,e){await te(t,{protocol:Q,apiVersion:ee,id:"terminal",setup(r){r.addResolver({resolver:at(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(Re,"registerTerminalSearch");function at(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=lt(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,s=H(i)?j(i.payload):j(void 0),o=$(s.snapshot,"search",JSON.stringify(s.query),s.matches.slice(-6).map(l=>`${l.lineNumber}: ${l.lineText}`),r);return new G(o,n.expanded===!0,r)}}}a(at,"terminalSearchResolver");var be=12,G=class{constructor(e,n,r){this.content=e;this.expanded=n;this.theme=r}static{a(this,"TerminalSearchPanel")}render(e){let n=this.content.render(e);if(this.expanded||n.length<=be)return n;let r=be-1;return[...n.slice(0,r),this.theme.fg("muted",`\u2026 ${String(n.length-r)} visual rows omitted \xB7 ctrl+o to expand`)]}invalidate(){this.content.invalidate()}};function lt(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[s,o]of t.output.replaceAll("\r","").split(`
|
|
21
|
+
`).entries()){let l=e.caseSensitive===!0?o:o.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||ut(l,c,d))&&r.push({source:t.source,lineNumber:s+1,startColumn:c,endColumn:d,matchedText:o.slice(c,d),lineText:o}),u=Math.max(d,c+1)}if(r.length>=i)break}return r}a(lt,"findTerminalMatches");function ut(t,e,n){return!/[\p{L}\p{N}_]/u.test(t[e-1]??"")&&!/[\p{L}\p{N}_]/u.test(t[n]??"")}a(ut,"isWordBoundary");function j(t){if(!ct(t))throw new TypeError("Invalid terminal search result");return t}a(j,"parsePayload");function ct(t){return H(t)&&typeof t.query=="string"&&Array.isArray(t.matches)&&H(t.snapshot)&&typeof t.snapshot.source=="string"}a(ct,"isTerminalSearchPayload");function H(t){return typeof t=="object"&&t!==null}a(H,"isRecord");import{spawn as dt}from"node:child_process";import{closeSync as mt,mkdirSync as pt,openSync as ft,rmSync as gt,writeSync as ht}from"node:fs";import yt from"node:os";import xe from"node:path";import{createRequire as wt}from"node:module";import{randomUUID as St}from"node:crypto";import{stripVTControlCharacters as Tt}from"node:util";var $e=wt(new URL("../src/plugins/pi-agent-ide-terminal/src/session-manager.ts",import.meta.url).href),ve=1e6,bt=100,Rt=30,xt=2e3,k=class{static{a(this,"TerminalSessionManager")}#a;#e=new Map;#t=new Set;#r=new Set;#i=new Map;#o=!1;constructor(e=$t){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(Et(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.#o)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=Mt(n);this.#i.set(n,ft(r,"a",384));let i=e.cols??bt,s=e.rows??Rt,o=Pt(i,s),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:s,fullOutputPath:r,screen:o,status:"running",output:"",outputStart:0,screenReady:Promise.resolve(),completion:u,resolveCompletion:l,completionDelivered:!1},d;try{let p=$e("node-pty"),f={name:"xterm-256color",cols:i,rows:s,cwd:e.cwd,env:At(kt())};d=p.spawn(e.shell.executable,[...e.shell.commandArgs(e.command)],f)}catch(p){let f={...c,status:"failed",endedAt:Date.now(),error:It(p)};return this.#e.set(n,f),this.#s(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.#s(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,s)=>{let o=a(()=>{this.stop(r.source,"cancelled").then(i,s)},"onAbort");n?.addEventListener("abort",o,{once:!0}),r.completion.then(l=>{n?.removeEventListener("abort",o),i(l)},s)})}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(s=>{let o=!1,l,u=a(p=>{o||(p!==void 0&&T(r.status)&&(p=void 0),o=!0,clearTimeout(d),clearInterval(m),n.signal?.removeEventListener("abort",c),p!==void 0&&(r.background=!0,p!=="aborted"&&(r.waitReason=p),this.#n(r)),s({session:r,...p===void 0?{}:{reason:p}}))},"finish"),c=a(()=>u("aborted"),"onAbort"),d=setTimeout(()=>u("timeout"),n.timeoutMs),m=setInterval(()=>{if(!vt(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,s;for(;Date.now()<r;){let o=e.outputStart+e.output.length;if(o!==i)i=o,s=Date.now(),await e.screenReady;else if(s!==void 0&&Date.now()-s>=40)return;await B(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),s=Math.max(1,Math.min(e.rows,r)),o=Math.max(0,e.screen.buffer.active.cursorY-Math.floor(s/2)),l=-1;for(let d=0;d<=e.rows-s;d+=1){let m=0;for(let p=d;p<d+s;p+=1){let f=n[p]??"",h=i[p]??"",v=h.length>0&&!n.includes(h),b=f.length>0&&h.length===0;f!==h&&(v||b)&&(m+=1)}m>l&&(l=m,o=d)}let u=e.screen.buffer.active;return{lines:i.slice(o,o+s).map((d,m)=>{if(o+m!==u.cursorY)return d;let f=d.padEnd(u.cursorX," ");return`${f.slice(0,u.cursorX)}\u258C${f.slice(u.cursorX)}`}),startRow:o}}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),s=[];for(let o=0;o<e.rows;o+=1){let l=r.getLine(i+o)?.translateToString(!0).trimEnd();l!==void 0&&l.length>0&&s.push(l)}return s.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(Ct(n))}async stop(e,n="stopped"){let r=this.required(e);return T(r.status)||(r.status="stopping",this.#n(r),await Pe(r,!1),await Promise.race([r.completion.then(()=>!0),B(xt).then(()=>!1)])||(await Pe(r,!0),await Promise.race([r.completion,B(1e3)])),T(r.status)||(r.status=n,r.endedAt=Date.now(),this.#s(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.#s(n.id),gt(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=[],s=Math.max(0,r.baseY);for(let o=s;o<s+n.rows;o+=1)i.push(r.getLine(o)?.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.#o){this.#o=!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.#s(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=Tt(n),i=this.#i.get(e.id);if(i!==void 0&&ht(i,r),e.output+=r,e.output.length>ve){let s=e.output.length-ve;e.output=e.output.slice(s),e.outputStart+=s}e.screenReady=e.screenReady.then(()=>new Promise(s=>{e.screen.write(n,s)})),this.#n(e)}#s(e){let n=this.#i.get(e);n!==void 0&&(mt(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 vt(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(vt,"looksInteractive");function Pt(t,e){let{Terminal:n}=$e("@xterm/headless");return new n({cols:t,rows:e,scrollback:2e3,allowProposedApi:!0})}a(Pt,"createScreen");function $t(){return St().replaceAll("-","").slice(0,12)}a($t,"defaultSessionId");function Et(t){return t.startsWith("shell:")?t.slice(6):t}a(Et,"normalizeSessionId");function T(t){return t!=="running"&&t!=="stopping"}a(T,"isTerminalStatus");function kt(){return process.env}a(kt,"processEnvironment");function At(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(At,"cleanEnvironment");function Ct(t){return t.split(/[\s,]+/u).filter(Boolean).map(Lt).join("")}a(Ct,"encodeTerminalKeys");function Lt(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"),s=r.has("alt")||r.has("meta"),o=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 s?`\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&&!s&&!o&&l[n]!==void 0)return l[n];if(s&&!i&&!o&&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&&!s&&!o?`\x1B[${c}`:`\x1B[1;${1+(o?1:0)+(s?2:0)+(i?4:0)}${c}`;if(s&&!i&&n.length===1)return`\x1B${o?n.toUpperCase():n}`;throw new Error(`Unsupported terminal key ${t}`)}a(Lt,"encodeTerminalKey");async function Pe(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=dt("taskkill.exe",["/PID",String(n.pid),"/T",...e?["/F"]:[]],{windowsHide:!0,stdio:"ignore"});i.once("error",()=>r()),i.once("exit",()=>r())})}}a(Pe,"terminateProcessTree");function B(t){return new Promise(e=>setTimeout(e,t))}a(B,"delay");function It(t){return t instanceof Error?t.message:String(t)}a(It,"errorMessage");function Mt(t){let e=xe.join(yt.tmpdir(),`pi-agent-ide-terminal-${process.pid}`);return pt(e,{recursive:!0,mode:448}),xe.join(e,`${t}.log`)}a(Mt,"createOutputLog");import _t from"node:os";import Ee from"node:path";function ke(t=process.platform,e=process.env){if(t==="win32"){let i=e.SHELL?.trim()||"powershell.exe",s=Ee.win32.basename(i).toLowerCase();return s==="cmd"||s==="cmd.exe"?{executable:i,displayName:"Command Prompt",family:"cmd",commandArgs:a(o=>["/d","/s","/c",o],"commandArgs")}:{executable:i,displayName:s.startsWith("pwsh")?"PowerShell":"Windows PowerShell",family:"powershell",commandArgs:a(o=>["-NoLogo","-NoProfile","-Command",o],"commandArgs")}}let n=e.SHELL?.trim()||_t.userInfo().shell||(t==="darwin"?"/bin/zsh":"/bin/bash"),r=Ee.basename(n);return{executable:n,displayName:r==="zsh"?"zsh":r==="bash"?"Bash":r,family:"posix",commandArgs:a(i=>["-c",i],"commandArgs")}}a(ke,"resolveShellProfile");function Ae(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(Ae,"shellSyntaxGuidance");import Ce from"node:path";import{stripVTControlCharacters as Dt}from"node:util";import{defineTool as Ot}from"@earendil-works/pi-coding-agent";import{Type as g}from"typebox";var Nt=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 Le(t,e,n,r){let i=process.platform==="win32"?"powershell":"bash";t.registerTool(Ot({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. 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.`],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. 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. ${Ae(n)}`,parameters:Nt,async execute(s,o,l,u,c){r.bind(c);let d=o.cwd===void 0?c.cwd:Ce.resolve(c.cwd,o.cwd),m=e.start({command:o.command,background:o.background??!1,cwd:d,shell:n,...o.cols===void 0?{}:{cols:o.cols},...o.rows===void 0?{}:{rows:o.rows}});if(o.background===!0&&m.status!=="failed")return await Ut(e,m,u),m.status!=="running"&&(m.completionDelivered=!0),A(e.snapshot(m));if(m.status==="failed")return A(e.snapshot(m));let p=await e.waitForForeground(m.source,{signal:l,timeoutMs:(o.timeoutSeconds??60)*1e3});return p.reason==="aborted"&&r.notifyWaitTransition(p.session),A(e.snapshot(p.session))},renderCall(s,o){let l=typeof s.command=="string"?s.command:"",u=typeof s.cwd=="string"?Ce.resolve(process.cwd(),s.cwd):process.cwd();return le(l,s.background===!0,u,n,o)},renderResult(s,o,l){return ce(s.details,o.expanded,l)}}))}a(Le,"registerTerminalTools");function A(t){return{content:[{type:"text",text:P(t)}],details:t,isError:t.status==="failed"||t.status==="lost"}}a(A,"terminalResult");async function Ut(t,e,n){await new Promise(r=>{let i=!1,s,o=a(()=>{},"unsubscribe"),l=a(()=>{i||(i=!0,clearTimeout(s),o(),r())},"finish"),u=a(()=>{let c=t.snapshot(e);n?.(A(c)),(Dt(c.output).replaceAll("\r","").split(`
|
|
22
|
+
`).filter(m=>m.length>0).length>=R||c.status!=="running")&&l()},"publish");o=t.onDidChange(c=>{c.id===e.id&&u()}),s=setTimeout(l,2e3),u()})}a(Ut,"captureInitialBackgroundPreview");import{Box as Ie,Container as Me}from"@earendil-works/pi-tui";var Wt=120,Ft=12e4,C=class{constructor(e,n,r=Ft){this.pi=e;this.manager=n;this.staleIntervalMs=r;e.registerMessageRenderer("terminal-stale",(i,{expanded:s},o)=>{let l=_e(i.details)?i.details:void 0,u=new Me;l!==void 0&&u.addChild(S(l,s,o,"stale \xB7 inspect session"));let c=new Ie(1,1,d=>o.bg("toolPendingBg",d));return c.addChild(u),c}),e.registerMessageRenderer("terminal-completion",(i,{expanded:s},o)=>{let l=new Me;for(let c of jt(i.details))l.addChild(S(c,s,o));let u=new Ie(1,1,c=>o.bg("toolSuccessBg",c));return u.addChild(l),u}),this.#u=[n.onDidChange(i=>this.#s(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;#o=!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.#s(r,!0)}}notifyWaitTransition(e){let n=this.manager.snapshot(e);this.pi.sendMessage({customType:"terminal-wait-transition",display:!1,content:`Terminal wait ended; ${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.#o=!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()}#s(e,n=!1){if(this.#l(e.id),this.#o||!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.#o||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:Ht(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.#o||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.#o||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:Gt(r),details:{sessions:r}},{triggerTurn:!0,deliverAs:"steer"})},Wt)))}};function jt(t){return!Oe(t)||!Array.isArray(t.sessions)?[]:t.sessions.filter(_e)}a(jt,"completionSnapshots");function _e(t){return Oe(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(_e,"isTerminalSessionSnapshot");function Gt(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}`,s=n.output.trimEnd().slice(-2e3);return`- ${n.source}: ${n.status}${r}${i}, ${De(n.elapsedMs)}
|
|
24
|
+
${s||"(no output)"}`}).join(`
|
|
25
|
+
`)}`}a(Gt,"formatCompletionMessage");function Ht(t){let e=t.output.trimEnd().slice(-2e3);return`Background terminal ${t.source} has produced no output for ${De(t.idleMs)}. Inspect it with read. If it is healthy, keep waiting; otherwise send input or stop it.
|
|
26
|
+
${e||"(no output)"}`}a(Ht,"formatStaleMessage");function De(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}a(De,"formatElapsed");function Oe(t){return typeof t=="object"&&t!==null}a(Oe,"isRecord");async function Bt(t){let e=ie("terminal")??new k,n=ke(),r=new C(t,e),i=ne(t).add(me(e));await Promise.all([Se(t,e),Re(t,e)]),Le(t,e,n,r),t.on("session_start",(s,o)=>r.bind(o)),t.on("agent_settled",(s,o)=>r.onAgentSettled(o)),t.on("session_shutdown",async s=>{if(r.dispose(),i(),s.reason!=="quit"){re("terminal",e);return}oe("terminal",e),await e.dispose()})}a(Bt,"registerTerminal");export{Bt as default};
|
|
@@ -20,7 +20,7 @@ ${e}`}i(Xe,"dapFrame");function we(r,e,t){return r.request("initialize",{clientI
|
|
|
20
20
|
Source: ${w.sourceResource}
|
|
21
21
|
Breakpoints: ${w.breakpointsResource}
|
|
22
22
|
|
|
23
|
-
Next: read ${w.sourceResource} with views ["anchors"], then insert a breakpoint at an anchor.`}],details:w}}catch(v){return{content:[{type:"text",text:v instanceof Error?v.message:String(v)}],details:{adapter:c.adapter,program:h,cwd:f,status:"failed"},isError:!0}}},renderCall(u,c){let b=S.resolve(process.cwd(),typeof u.cwd=="string"?u.cwd:"."),p=S.resolve(b,typeof u.program=="string"?u.program:"program");return G(typeof u.adapter=="string"?u.adapter:"debugger",p,b,c)},renderResult(u,c,b){let p=A(u.details)?u.details.snapshot:void 0;if(typeof p=="object"&&p!==null)return C(p,c.expanded,b);let g=u.details;return G(g.adapter,g.program,g.cwd,b)}})),r.on("session_shutdown",u=>{if(o(),u.reason
|
|
23
|
+
Next: read ${w.sourceResource} with views ["anchors"], then insert a breakpoint at an anchor.`}],details:w}}catch(v){return{content:[{type:"text",text:v instanceof Error?v.message:String(v)}],details:{adapter:c.adapter,program:h,cwd:f,status:"failed"},isError:!0}}},renderCall(u,c){let b=S.resolve(process.cwd(),typeof u.cwd=="string"?u.cwd:"."),p=S.resolve(b,typeof u.program=="string"?u.program:"program");return G(typeof u.adapter=="string"?u.adapter:"debugger",p,b,c)},renderResult(u,c,b){let p=A(u.details)?u.details.snapshot:void 0;if(typeof p=="object"&&p!==null)return C(p,c.expanded,b);let g=u.details;return G(g.adapter,g.program,g.cwd,b)}})),r.on("session_shutdown",u=>{if(o(),u.reason!=="quit"){ae("debugger",e);return}ie("debugger",e),e.dispose()})}i(at,"registerDebugger");function _e(r,e){return{id:e,tryResolve(t){let n=r.get(t);return n===void 0?Promise.resolve({kind:"not-handled"}):Promise.resolve({kind:"resolved",resource:{source:t,async read(){let a=r.sourceFile(t);if(a!==void 0)return[pt(a,await r.readSource(t))];if(t===`${n.source}/breakpoints`)return[{type:"text",text:lt(n)}];let o=r.breakpoint(t);if(t!==n.source&&o===void 0)throw new Error(`Unknown debug resource ${t}`);return[{type:"text",text:o===void 0?F(n):`Breakpoint: ${o.source}
|
|
24
24
|
File: ${o.file}
|
|
25
25
|
Line: ${o.line}
|
|
26
26
|
Status: ${o.verified?"verified":"pending"}`}]}}})}}}i(_e,"createDebugResourceResolver");function ot(r,e){if(!A(r)||typeof r.path!="string"||typeof r.text!="string")return!1;let t=e.get(r.path);return t!==void 0&&(r.path===t.source||e.sourceFile(r.path)!==void 0)}i(ot,"matchesDebugInsert");function it(r,e){if(!A(r)||typeof r.path!="string")return!1;let t=e.get(r.path);return t!==void 0&&(r.path===t.source||r.path.startsWith(`${t.source}/breakpoint/`))}i(it,"matchesDebugDelete");async function st(r,e,t,n){switch(t.trim().toLowerCase()){case"start":{await r.start(e,n);return}case"continue":{await r.command(e,"continue",n);return}case"step over":{await r.command(e,"next",n);return}case"step into":{await r.command(e,"stepIn",n);return}case"step out":{await r.command(e,"stepOut",n);return}default:throw new Error(`Unknown debug command ${JSON.stringify(t)}`)}}i(st,"executeSessionCommand");function dt(r,e){return{source:e.source,sourceResource:r.sourceResource(e),breakpointsResource:`${e.source}/breakpoints`,adapter:e.options.adapter,program:e.options.program,cwd:e.options.cwd,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:t,file:n,line:a,verified:o})=>({source:t,file:n,line:a,verified:o})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(dt,"debugDetails");function ut(r,e,t){return{kind:"debug-command",command:t,status:e.status,breakpoints:[...e.breakpoints.values()].map(({source:n,file:a,line:o,verified:s})=>({source:n,file:a,line:o,verified:s})),...e.stop===void 0?{}:{stop:e.stop},snapshot:r.snapshot(e)}}i(ut,"debugActionData");function lt(r){return r.breakpoints.size===0?`No breakpoints in ${r.source}.`:[...r.breakpoints.values()].map(e=>`${e.verified?"\u25CF":"\u25CB"} ${e.file}:${e.line} \xB7 ${e.source}`).join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as S}from"./chunk-5PLV4HLG.js";import{a as w,b as $}from"./chunk-EJ5OACQM.js";import{a as n}from"./chunk-EI7MMDWY.js";import{DynamicBorder as M}from"@earendil-works/pi-coding-agent";import{Container as W,Key as I,matchesKey as x,SelectList as _,Text as m,truncateToWidth as D,visibleWidth as P}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((g,c,O,A)=>{let y=this.#n(),u="list",f,b=n(a=>{let l=y.map(o=>({value:o.source,label:`${o.status} ${o.kind} ${o.title}`,description:o.description})),p=new _(l,Math.min(l.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")}),E=l.findIndex(o=>o.value===a);return E>=0&&p.setSelectedIndex(E),p.onSelect=o=>{f=y.find(R=>R.source===o.value),u="detail",g.requestRender()},p.onCancel=()=>A(null),p},"createList"),h=b(),C=n(()=>{let a=f?.source??h.getSelectedItem()?.value;y=this.#n(),f=u==="list"?void 0:y.find(l=>l.source===a),h=b(a),g.requestRender()},"refresh");return s=this.registry.onDidChange(C),i=setInterval(C,1e3),{invalidate:n(()=>h.invalidate(),"invalidate"),render(a){let l=new W;return l.addChild(new M(p=>c.fg("accent",p))),u==="list"?(l.addChild(new m(c.fg("accent",c.bold("Agent IDE processes")),1,0)),l.addChild(h),l.addChild(new m(c.fg("dim","enter view \xB7 d stop \xB7 esc close"),1,0))):f===void 0?l.addChild(new m(c.fg("warning","Process is no longer active."),1,0)):(l.addChild(f.renderDetail(c)),l.addChild(new m(c.fg(u==="confirm"?"warning":"dim",u==="confirm"?"Stop this process? y confirm \xB7 n/esc cancel":u==="input"?"input mode \xB7 type to send \xB7 esc stop input":f.sendInput===void 0?"esc back \xB7 d stop":"i input \xB7 esc back \xB7 d stop"),1,0))),l.addChild(new M(p=>c.fg("accent",p))),l.render(a)},handleInput(a){u==="list"?a==="d"?(f=y.find(l=>l.source===h.getSelectedItem()?.value),f!==void 0&&(u="confirm")):h.handleInput(a):u==="detail"?x(a,I.escape)?u="list":a==="d"?u="confirm":a==="i"&&f?.sendInput!==void 0&&(u="input"):u==="input"?x(a,I.escape)?u="detail":f?.sendInput?.(a):a==="y"&&f!==void 0?A({source:f.source}):(a==="n"||x(a,I.escape))&&(u="detail"),g.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(g=>g.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,g]of t.entries()){for(let c of g.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} `,g=` ${e} \u2500`,c="\u2500".repeat(Math.max(0,r-P(d)-P(g)));return i(`\u256D${D(`${d}${c}${g}`,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-P(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=S(t),s=await $(w()),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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as H}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 ue}from"node:crypto";import{readFile as z}from"node:fs/promises";import f from"node:path";import{spawn as ee}from"node:child_process";import D from"node:path";import{createInterface as te}from"node:readline";import{existsSync as Y}from"node:fs";import Z from"node:os";import F from"node:path";function O(e=process.env.PI_CODING_AGENT_DIR??F.join(Z.homedir(),".pi","agent"),t=process.platform){let n=F.join(e,"bin",t==="win32"?"rg.exe":"rg");return Y(n)?n:"rg"}a(O,"resolveRipgrepExecutable");async function A(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=D.resolve(t,oe(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"]:[],..._(e.include).flatMap(i=>["--glob",i]),..._(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(!ne(i))throw i;return k(["--engine","default",...o],n)}}a(A,"searchText");function k(e,t){return new Promise((n,r)=>{let o=ee(O(),e,{stdio:["ignore","pipe","pipe"]}),i=te({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 re(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(ie),n({matches:s,complete:!0})}),t?.addEventListener("abort",u,{once:!0}),t?.aborted===!0&&u()})}a(k,"runRipgrep");function ne(e){return e instanceof Error&&/PCRE2: error matching: match limit exceeded/iu.test(e.message)}a(ne,"isPcre2MatchLimitError");function re(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:D.resolve(t),lineNumber:e.data.line_number,startColumn:l,endColumn:c,matchedText:r.slice(l,c),lineText:r})}return i}a(re,"matchesFromEvent");function _(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(_,"splitGlobList");function oe(e){return e.startsWith("@")?e.slice(1):e}a(oe,"stripFilePrefix");function ie(e,t){return e.source.localeCompare(t.source)||e.lineNumber-t.lineNumber||e.startColumn-t.startColumn||e.endColumn-t.endColumn}a(ie,"compareMatches");function N(e,t=!1){let n=M(e);if(!C(n))return t?e:B(e);let r=E(new v(e,n).parse(),t);return`^${r.condition}.*?\\K(${r.match})`}a(N,"compileSearchQuery");function Q(e){if(C(M(e)))return;let t=[...new Set(e.trim().split(/\s+/u).filter(Boolean))];return t.length>1?`(?:${t.map(B).join("|")})`:void 0}a(Q,"compileSearchFallbackQuery");function C(e){return e.some(t=>t.quoted===!0||t.type==="and"||t.type==="or"||t.type==="not")}a(C,"containsBooleanSyntax");var v=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 ${ae(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 M(e){let t=[],n=0;for(;n<e.length;){let r=e.charAt(n);if(/\s/u.test(r)){n+=1;continue}if(r==="("&&se(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(W(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===")"||W(e,n))break;s==="\\"&&n+1<e.length?n+=2:s==="["||s==="("?n=$(e,n)??n+1:n+=1}let i=e.slice(o,n);t.push({type:ce(i),value:i,offset:o})}return t.push({type:"end",value:"",offset:e.length}),t}a(M,"tokenize");function W(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(W,"isBooleanPipe");function $(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=$(e,r);if(i===void 0)return;r=i}else r+=1}}}a($,"regexBlockEnd");function se(e,t){let n=$(e,t);if(n===void 0)return!0;let r=e.slice(t+1,n-1);return r.trim().length===0?!0:C(M(r))}a(se,"isBooleanGroup");function ce(e){return e==="AND"?"and":e==="OR"?"or":e==="NOT"?"not":"term"}a(ce,"operatorType");function ae(e){return e.value.length>0?JSON.stringify(e.value):"the end of the query"}a(ae,"quoteToken");function p(e,t){return new SyntaxError(`Invalid Boolean search query at column ${String(e+1)}: ${t}`)}a(p,"syntaxError");function E(e,t){if(e.kind==="term"){let o=t&&!e.quoted?e.value:B(e.value);return{condition:`(?=.*(?:${o}))`,match:o}}let n=E(e.left,t),r=E(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(E,"compileExpression");function B(e){return e.replace(/[\\^$.*+?()[\]{}|]/gu,"\\$&")}a(B,"escapeRegex");function Be(e){let t=N(e.query),n=N(e.query,!0),r=Q(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(Be,"createSearchRecipe");async function P(e,t,n){let r=e.query,o=await A(e,t,n),i=[];for(let s of e.fallbacks??[]){if(o.matches.length>0||!o.complete)break;n?.throwIfAborted();try{o=await A({...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"||!le(l)||n?.aborted)throw l;i.push("Search fallback: invalid regex skipped; literal search found no matches.")}}return{...o,query:r,notices:i}}a(P,"runSearchRecipe");function le(e){return e instanceof Error&&/regex parse error:|PCRE2: error compiling pattern/iu.test(e.message)}a(le,"isRegexSyntaxError");var de=/^SEARCH#([A-F0-9]{4,64}):(all|[1-9]\d*):(line|match)$/u,U=4;function We(e,t,n,r){return K(e,t,n,r).slice(0,U)}a(We,"createSearchSessionId");function K(e,t,n,r){let o=n===void 0?pe(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)||L(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}=V(r??{query:e,regex:!0},o);return ue("sha256").update(JSON.stringify([e,o,l,i])).digest("hex").toUpperCase()}a(K,"createSearchSessionIdentity");function he(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=U;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(he,"allocateSearchSessionId");function V(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(V,"normalizeRecipe");var R=class extends Error{static{a(this,"SearchSnapshotChangedError")}constructor(t){super(`Search result in ${t} changed before its anchors were registered.`),this.name="SearchSnapshotChangedError"}},q=class{constructor(t=K){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(j=>({...j,source:f.resolve(j.source)})).sort(L),u=await J(c,i),d=this.createIdentity(t,c,o,s),h=this.#r.get(d)??he(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 registerIfCurrent(t,n,r,o,i,s,l){try{return await this.register(t,n,r,o,i,s,l)}catch(c){if(c instanceof R)return;throw c}}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:V(s.recipe,s.cwd)};try{let c=s.refresh===void 0?await P(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 I(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 H(t,s,u.map(h=>G(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 I(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 I(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(G(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 P(t.recipe,t.cwd,n):await t.refresh(n),o=r.matches.map(s=>({...s,source:f.resolve(s.source)})).sort(L),i={matches:o,complete:r.complete,contentBySource:await J(o,n)};return this.#t.set(t.id,{...t,refreshedComplete:i}),i}};function w(e){let t=de.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(fe);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=X(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 fe(e){return e!==void 0}a(fe,"isMatch");function X(e){let t=e.endLineNumber??e.lineNumber;return t>e.lineNumber&&e.endColumn===0?t-1:t}a(X,"lastContainingLine");function G(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=X(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(G,"selectionRange");function me(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(me,"matchedSourceText");async function J(e,t){let n=new Map;for(let r of new Set(e.map(o=>o.source))){let o=await z(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||me(i,s)!==s.matchedText)throw new R(r);n.set(r,o)}return n}a(J,"snapshotContents");async function I(e,t){try{return await z(e,{encoding:"utf8",...t!==void 0&&{signal:t}})}catch{return}}a(I,"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 pe(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(;!ge(t,r);){let o=f.dirname(t);if(o===t)return t;t=o}}return t}a(pe,"commonSourceDirectory");function ge(e,t){let n=f.relative(e,t);return n!==".."&&!n.startsWith(`..${f.sep}`)&&!f.isAbsolute(n)}a(ge,"isWithin");function L(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(L,"compareMatches");export{O as a,Be as b,P as c,We as d,K as e,he as f,R as g,q as h};
|
package/dist/entry-47.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`).filter(Boolean).map(
|
|
3
|
-
`)),
|
|
4
|
-
`)}],details:{query:t.query,files:t.files,complete:t.complete}}}}}
|
|
5
|
-
`)}],details:E(o.request.query,[],o.complete,
|
|
6
|
-
`)}],details:E(
|
|
7
|
-
`)}
|
|
1
|
+
import{a as x,b as J,c as X,d as fe,h as Q}from"./chunk-P7XO5CIP.js";import"./chunk-GUTQ3PWL.js";import{a as H}from"./chunk-MGCHOGQD.js";import{a as F,b as I}from"./chunk-T6LX2RX5.js";import{a as z}from"./chunk-ZTYWHL2F.js";import{a as G,b as V}from"./chunk-7UGNGK7Y.js";import{a as W}from"./chunk-L7JMDDSD.js";import{a as _,b as j,d as B}from"./chunk-O6LE42GK.js";import"./chunk-S3ZPXWX7.js";import{t as L,u as O}from"./chunk-5VSE5X5R.js";import{d as N,e as v}from"./chunk-N34ATN52.js";import{a as M}from"./chunk-ZC65Z3CK.js";import{a as c}from"./chunk-EI7MMDWY.js";var U={protocol:F,apiVersion:1,id:"search-text",setup(e){e.addSetupCheck({id:"ripgrep",async inspect(t){let r=x(t.env.PI_CODING_AGENT_DIR);return await N(r,t.cwd,t.env)?{}:{actions:[{id:"ripgrep-unavailable",message:"Local search is unavailable because ripgrep was not found"}]}}}),e.addCheck({id:"ripgrep",title:"Local search",async run(t){let r=t.env.PI_CODING_AGENT_DIR,n=x(r),a=await v(n,["--version"],t.cwd,t.env);return[a.ok?{status:"pass",message:"ripgrep is available",detail:a.detail}:{status:"fail",message:"ripgrep is not available",detail:a.detail}]}})}};import ce from"node:path";import{spawn as ge}from"node:child_process";import T from"node:path";function Y(e,t,r,n){let a=t.limit??100,o=["--files","--hidden","--no-config","--no-ignore-parent","--glob","!.git/**"];for(let i of K(t.include))o.push("--glob",i);for(let i of K(t.exclude))o.push("--glob",`!${i}`);return t.path!==void 0&&o.push(t.path),new Promise((i,s)=>{let l=ge(x(),o,{cwd:r,stdio:["ignore","pipe","pipe"]}),u="",h="";l.stdout.setEncoding("utf8"),l.stderr.setEncoding("utf8"),l.stdout.on("data",d=>u+=d),l.stderr.on("data",d=>h+=d);let p=c(()=>{l.kill("SIGTERM")},"abort");n?.addEventListener("abort",p,{once:!0}),l.once("error",s),l.once("close",d=>{if(n?.removeEventListener("abort",p),n?.aborted===!0){s(n.reason instanceof Error?n.reason:new Error("File search aborted"));return}if(d!==0&&d!==1){s(new Error(h.trim()||`rg exited with code ${String(d)}`));return}let g=u.split(`
|
|
2
|
+
`).filter(Boolean).map(m=>T.relative(r,T.resolve(r,m))).filter(m=>ye(m,e)).sort((m,b)=>m.localeCompare(b));i({files:g.slice(0,a),complete:g.length<=a})})})}c(Y,"searchFiles");function K(e){return e?.split(",").map(t=>t.trim()).filter(Boolean)??[]}c(K,"splitGlobs");function ye(e,t){if(/[*?[\]{}]/u.test(t)){let r=t.replace(/^\.\//u,"");return T.matchesGlob(r.includes("/")?e:T.basename(e),r)}return Se(e,t)}c(ye,"matchFile");function Se(e,t){if(t.length===0)return!0;let r=0,n=e.toLowerCase();for(let a of t.toLowerCase()){if(r=n.indexOf(a,r),r===-1)return!1;r+=1}return!0}c(Se,"fuzzyMatch");import Te from"node:path";import{keyText as ie}from"@earendil-works/pi-coding-agent";import{Text as $e,truncateToWidth as C,visibleWidth as f,wrapTextWithAnsi as Ae}from"@earendil-works/pi-tui";import Z from"node:path";import{pathToFileURL as ee}from"node:url";function $(e,t){let r=new Map;for(let s of e){let l=r.get(s.source)??[];l.push(s),r.set(s.source,l)}let n=new Set,a=e.length,o=[...r].sort(([s,l],[u,h])=>h.length-l.length||s.localeCompare(u));for(let[s,l]of o){if(a<=t)break;n.add(s),a-=l.length}return{files:[...r].sort(([s],[l])=>s.localeCompare(l)).map(([s,l])=>{if(!n.has(s))return{kind:"detailed",source:s,matches:l};let u=new Map;for(let h of l)u.set(h.lineText,(u.get(h.lineText)??0)+1);return{kind:"compacted",source:s,matchCount:l.length,uniqueLineCount:u.size,groups:r.size===1?[...u].sort(([h,p],[d,g])=>g-p||h.localeCompare(d)).slice(0,t).map(([h,p])=>({text:h,matchCount:p})):[]}})}}c($,"planSearchPresentation");function E(e,t,r,n,a,o=50){let s=$(t,o).files.map(l=>l.kind==="detailed"?be(l.source,l.matches,n):{path:te(l.source,n),link:ee(l.source).href,matchCount:l.matchCount,uniqueLineCount:l.uniqueLineCount,groups:l.groups,lines:[]});return{...a!==void 0&&{sessionId:a},query:e,matchCount:t.length,fileCount:s.length,complete:r,files:s}}c(E,"createSearchToolDetails");function A(e){if(!R(e)||typeof e.query!="string"||!y(e.matchCount)||!y(e.fileCount)||typeof e.complete!="boolean"||e.sessionId!==void 0&&typeof e.sessionId!="string"||!Array.isArray(e.files)||!e.files.every(xe))return!1;let t=e.files;return e.fileCount===t.length&&e.matchCount===t.reduce((r,n)=>r+n.matchCount,0)}c(A,"isSearchToolDetails");function be(e,t,r){let n=new Map;for(let o of t){let i=n.get(o.lineNumber);if(i!==void 0&&i.text!==o.lineText)throw new Error(`Search results disagree about line ${String(o.lineNumber)} in ${e}.`);let s=i??{lineNumber:o.lineNumber,text:o.lineText,ranges:[]};s.ranges.push({from:o.startColumn,to:o.endColumn}),n.set(o.lineNumber,s)}let a=[...n.values()].sort((o,i)=>o.lineNumber-i.lineNumber).map(o=>{let i=[...o.ranges].sort((s,l)=>s.from-l.from||s.to-l.to);return{lineNumber:o.lineNumber,text:o.text,matchCount:i.length,ranges:i}});return{path:te(e,r),link:ee(e).href,matchCount:t.length,lines:a}}c(be,"createSearchResultFile");function xe(e){if(!R(e)||typeof e.path!="string"||typeof e.link!="string"||!y(e.matchCount)||!Array.isArray(e.lines)||!e.lines.every(Re))return!1;let t=e.lines,r=e.groups;return(r===void 0||Array.isArray(r)&&r.every(n=>R(n)&&typeof n.text=="string"&&y(n.matchCount)))&&(e.uniqueLineCount===void 0||y(e.uniqueLineCount))&&(t.length===0||e.matchCount===t.reduce((n,a)=>n+a.matchCount,0))}c(xe,"isSearchResultFile");function Re(e){return R(e)&&Number.isSafeInteger(e.lineNumber)&&e.lineNumber>=1&&typeof e.text=="string"&&y(e.matchCount)&&Array.isArray(e.ranges)&&e.ranges.length===e.matchCount&&e.ranges.every(t=>Ce(t,e.text))}c(Re,"isSearchResultLine");function Ce(e,t){return R(e)&&Number.isSafeInteger(e.from)&&Number.isSafeInteger(e.to)&&e.from>=0&&e.to>e.from&&e.to<=t.length}c(Ce,"isSearchResultRange");function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(R,"isRecord");function y(e){return Number.isSafeInteger(e)&&e>=0}c(y,"isCount");function te(e,t){let r=Z.relative(t,e);return r.length>0&&!r.startsWith("..")&&!Z.isAbsolute(r)?r:e}c(te,"displaySource");function re(e){return e.replaceAll("\u27E6","").replaceAll("\u27E7","")}c(re,"sourceText");function ne(e,t){let{files:r,...n}=e,a=re(t);return{...n,storedFiles:r.map(({lines:o,...i})=>({...i,lines:o.map(s=>[s.lineNumber,L(s.text,a),s.ranges])}))}}c(ne,"compactSearchDetails");function oe(e,t){if("files"in e)return e;let{storedFiles:r,...n}=e,a=re(t);return{...n,files:r.map(({lines:o,...i})=>({...i,lines:o.map(([s,l,u])=>({lineNumber:s,text:O(l,a),ranges:u,matchCount:u.length}))}))}}c(oe,"restoreSearchDetails");var ae=new WeakMap,k=12,we={".ts":{label:"TS",color:"accent"},".tsx":{label:"TX",color:"accent"},".js":{label:"JS",color:"warning"},".jsx":{label:"JX",color:"warning"},".json":{label:"{}",color:"warning"},".md":{label:"MD",color:"mdHeading"},".py":{label:"PY",color:"accent"},".rs":{label:"RS",color:"accent"},".go":{label:"GO",color:"accent"},".css":{label:"CS",color:"accent"},".html":{label:"<>",color:"accent"}};function se(e,t,r,n){if(typeof e.details=="object"){let i=ae.get(e.details);i===void 0&&(i=oe(e.details,e.content.flatMap(s=>s.type==="text"?[s.text]:[]).join(`
|
|
3
|
+
`)),ae.set(e.details,i)),e={...e,details:i}}if(t.isPartial||n.isError||!A(e.details)){let i=e.content[0],s=i?.type==="text"?i.text:"",l=n.isError?"error":t.isPartial?"dim":"toolOutput";return new $e(r.fg(l,s),0,0)}let o=(n.lastComponent instanceof q?n.lastComponent:void 0)??new q(e.details,r,t.expanded);return o.update(e.details,r,t.expanded),o}c(se,"renderSearchResult");var q=class{constructor(t,r,n){this.details=t;this.theme=r;this.expanded=n}static{c(this,"SearchResultPanel")}cached;update(t,r,n){this.details===t&&this.theme===r&&this.expanded===n||(this.details=t,this.theme=r,this.expanded=n,this.invalidate())}render(t){if(this.cached?.width===t)return this.cached.lines;if(t<4){let u=[C(le(this.details),Math.max(1,t))];return this.cached={width:t,lines:u},u}let r=t-2,n=ke(this.details,this.expanded),a=Fe(this.details.files),o=n.flatMap(u=>Ee(u,r,a,this.theme)),i=qe(o,this.expanded,r,this.theme),s=[Le(this.details,r,this.theme),...i];s.push(this.theme.fg("borderMuted",`\u2570${"\u2500".repeat(r)}\u256F`));let l=s.map(u=>C(u,t));return this.cached={width:t,lines:l},l}invalidate(){this.cached=void 0}};function ke(e,t){let r=e.files.length===0?[{kind:"empty"}]:e.files.flatMap(o=>[{kind:"file",file:o},...o.uniqueLineCount===void 0?o.lines.map(i=>({kind:"line",file:o,line:i})):[{kind:"summary",text:`${String(o.uniqueLineCount)} unique line texts \xB7 search this path with a narrower query`},...(o.groups??[]).map(i=>({kind:"summary",text:`\xD7${String(i.matchCount)} ${i.text}`}))]]);if(t||r.length<=k)return r;let n=r.slice(0,k-1);for(;n.at(-1)?.kind==="file";)n.pop();let a=n.reduce((o,i)=>o+(i.kind==="line"?i.line.matchCount:0),0);return[...n,{kind:"omitted",matches:e.matchCount-a}]}c(ke,"searchViewport");function qe(e,t,r,n){if(t||e.length<=k)return e;let a=`${ie("app.tools.expand")} to expand`,o=S(n.fg("dim",` \u2026 output truncated \xB7 ${a}`),r,n);return[...e.slice(0,k-1),o]}c(qe,"compactRenderedRows");function Ee(e,t,r,n){if(e.kind==="file")return[S(Pe(e.file,t,n),t,n,!0)];if(e.kind==="line")return De(e.line,t,r,n);if(e.kind==="summary")return[S(n.fg("dim",` ${w(e.text)}`),t,n)];if(e.kind==="omitted"){let a=`${ie("app.tools.expand")} to expand`;return[S(n.fg("dim",` \u2026 ${String(e.matches)} more ${P(e.matches,"match","matches")} \xB7 ${a}`),t,n)]}return[S(n.fg("dim"," No matches found"),t,n)]}c(Ee,"renderPanelRow");function Pe(e,t,r){let n=Oe(e.path,r),a=r.fg("accent",r.bold(String(e.matchCount))),o=f(n)+f(a)+4,i=Math.max(1,t-o),s=ve(e.path,i),l=Ne(s,e.link,r),u=` ${n} ${l}`,h=" ".repeat(Math.max(1,t-f(u)-f(a)-1));return C(`${u}${h}${a} `,t)}c(Pe,"renderFileHeader");function De(e,t,r,n){let a=String(e.lineNumber).padStart(r),o=` ${n.fg("dim",a)} ${n.fg("borderMuted","\u2502")} `,i=Math.max(1,t-f(o)-1),s=Ae(Me(e,n),i),l=" ".repeat(f(o));return s.map((u,h)=>S(`${h===0?o:l}${u}`,t,n))}c(De,"renderMatchLine");function Me(e,t){let r="",n=0;for(let a of e.ranges){a.from>n&&(r+=t.fg("toolOutput",w(e.text.slice(n,a.from))));let o=w(e.text.slice(a.from,a.to));r+=t.bg("selectedBg",t.fg("accent",t.bold(o))),n=a.to}return n<e.text.length&&(r+=t.fg("toolOutput",w(e.text.slice(n)))),r}c(Me,"renderHighlightedLine");function Le(e,t,r){let n=c(i=>r.fg("borderMuted",i),"frame"),a=C(` ${le(e)} `,Math.max(0,t-1),""),o="\u2500".repeat(Math.max(0,t-f(a)-1));return`${n("\u256D\u2500")}${r.fg("accent",a)}${n(`${o}\u256E`)}`}c(Le,"renderTopBorder");function le(e){return e.matchCount===0?"No matches":`${`${String(e.matchCount)}${e.complete?"":"+"}`} ${P(e.matchCount,"match","matches")} in ${String(e.fileCount)} ${P(e.fileCount,"file","files")}`}c(le,"searchSummary");function S(e,t,r,n=!1){let a=C(e,t),o=`${a}${" ".repeat(Math.max(0,t-f(a)))}`,i=n?r.bg("selectedBg",o):o,s=r.fg("borderMuted","\u2502");return`${s}${i}${s}`}c(S,"framed");function Oe(e,t){let r=Te.extname(e).toLowerCase(),n=we[r]??{label:"\u25C7 ",color:r.length===0?"muted":"accent"};return t.fg(n.color,t.bold(n.label))}c(Oe,"fileBadge");function Ne(e,t,r){let n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),a=n===-1?"":e.slice(0,n+1),o=n===-1?e:e.slice(n+1),i=r.fg("muted",a)+r.underline(r.fg("accent",o));return t.includes("\x07")||t.includes("\x1B")?i:`\x1B]8;;${t}\x07${i}\x1B]8;;\x07`}c(Ne,"fileLink");function ve(e,t){return f(e)<=t?e:t<=1?"\u2026":`\u2026${e.slice(-(t-1))}`}c(ve,"truncatePath");function w(e){let t="";for(let r of e){if(r===" "){t+=" ".repeat(4);continue}let n=M(r.codePointAt(0));t+=n<32||n===127?"\uFFFD":r}return t}c(w,"safeText");function Fe(e){let t=1;for(let r of e)for(let n of r.lines)t=Math.max(t,n.lineNumber);return Math.max(3,String(t).length)}c(Fe,"maximumLineNumberWidth");function P(e,t,r){return e===1?t:r}c(P,"plural");function de(e){return pe("text",e,J)}c(de,"createTextResolver");function he(e){return pe("regex",e,t=>t.query.startsWith("regex:")?{...t,query:t.query.slice(6),regex:!0}:void 0)}c(he,"createRegexResolver");function me(){return{id:"files",async tryResolve(e,t){if(!e.query.startsWith("files:"))return{kind:"not-handled"};let r=e.query.slice(6).trim(),n=await Y(r,e,t.cwd,t.signal);return{kind:"resolved",payload:{query:r,...n}}},format(e){let t=e;return{content:[{type:"text",text:[t.complete?`${String(t.files.length)} files`:`${String(t.files.length)}+ files (limit reached)`,...t.files].join(`
|
|
4
|
+
`)}],details:{query:t.query,files:t.files,complete:t.complete}}}}}c(me,"createFileResolver");function pe(e,t,r){return{id:e,async tryResolve(n,a){let o=r(n);if(o===void 0)return{kind:"not-handled"};let i=await X(o,a.cwd,a.signal);return{kind:"resolved",payload:{request:{...n,query:i.query},...i,recipe:{...o,originalQuery:n.query}}}},async format(n,a){let o=n;if(o.matches.length===0)return{content:[{type:"text",text:[...o.notices,"No matches found."].join(`
|
|
5
|
+
`)}],details:E(o.request.query,[],o.complete,a.cwd)};let i=o.request.limit??50,s=await t.registerIfCurrent(o.request.query,o.matches,o.complete,a.cwd,a.signal,o.recipe),l=s??{query:o.request.query,matches:o.matches,complete:o.complete};return{content:[{type:"text",text:[...o.notices,Ie(l,a.cwd,i,s!==void 0)].join(`
|
|
6
|
+
`)}],details:E(l.query,l.matches,l.complete,a.cwd,s?.id,i)}},renderResult:se}}c(pe,"createMatchResolver");function Ie(e,t,r,n=!0){let a=new Set(e.matches.map(p=>p.source)).size,o=e.matches.length,i=`${String(o)}${e.complete?"":"+"} ${ue(o,"match","matches")} in ${String(a)} ${ue(a,"file","files")}`,s=n?e.complete?`SEARCH#${e.id}:all:line / SEARCH#${e.id}:all:match \u2014 ${i}`:`${i} (limit reached; no all anchors were registered)`:`${i} (files changed during search; results shown without anchors)`,l=n?["Anchors: SEARCH#HASH:N:line (line), SEARCH#HASH:N:match (exact match), SEARCH#HASH:all:line (each unique containing line), SEARCH#HASH:all:match (every exact match)",s]:[s],u=new Map(e.matches.map((p,d)=>[p,d+1])),h=$(e.matches,r);for(let[p,d]of h.files.entries()){p>0&&l.push("");let g=je(d.source,t);if(d.kind==="compacted"){l.push(`${g}: ${String(d.matchCount)} matches across ${String(d.uniqueLineCount)} unique line texts (compacted)`);for(let m of d.groups)l.push(` \xD7${String(m.matchCount)} ${_e(m.text)}`);d.groups.length<d.uniqueLineCount&&l.push(` \u2026 ${String(d.uniqueLineCount-d.groups.length)} more unique line texts`),l.push(` Search again with path: ${JSON.stringify(g)} and a narrower query to see individual matches.`);continue}for(let m of d.matches){let b=u.get(m);if(b===void 0)continue;let D=`${g}:${String(m.lineNumber)}:${String(m.startColumn+1)}-${String(m.endColumn+1)}`;l.push(n?`${D} SEARCH#${e.id}:${String(b)}:line SEARCH#${e.id}:${String(b)}:match`:D,` ${He(m)}`)}}return l.join(`
|
|
7
|
+
`)}c(Ie,"formatSearchSession");function He(e){let r=Math.max(0,e.startColumn-64),n=Math.min(e.lineText.length,e.endColumn+64);return`${r>0?"\u2026":""}${e.lineText.slice(r,e.startColumn)}\u27E6${e.lineText.slice(e.startColumn,e.endColumn)}\u27E7${e.lineText.slice(e.endColumn,n)}${n<e.lineText.length?"\u2026":""}`}c(He,"previewMatch");function _e(e){return`${e.slice(0,129)}${e.length>129?"\u2026":""}`}c(_e,"previewLine");function je(e,t){let r=ce.relative(t,e);return r.length>0&&!r.startsWith("..")&&!ce.isAbsolute(r)?r:e}c(je,"displaySource");function ue(e,t,r){return e===1?t:r}c(ue,"plural");async function Be(e){let t=new Q;e.on("tool_result",async(r,n)=>{if(r.toolName!=="replace"||r.isError||typeof r.details!="object"||r.details===null)return;let a="metadata"in r.details?r.details.metadata:void 0,o=a&&typeof a=="object"&&"searchObservations"in a?a.searchObservations:void 0,i=Array.isArray(o)?o:await t.observeAfterEdit([r.input.path,r.input.start,r.input.end],n.signal);if(i.length!==0)return{content:[...r.content,{type:"text",text:["Original search observed after editing (not task validation):",...i.map(s=>{let{query:l,fallbacks:u,...h}=s.scope;return[`SEARCH#${s.sessionId}: ${JSON.stringify(s.query)}`,`Scope and options: ${JSON.stringify(h)}`,s.error===void 0?`Matches: ${s.matches}${s.complete===!0?"; complete search.":"+; incomplete search, lower bound only."}`:`Search failed: ${s.error}. Applied edits remain applied.`,...s.notices??[]].join(`
|
|
8
8
|
`)})].join(`
|
|
9
|
-
`)}],details:{...r.details,searchObservations:
|
|
10
|
-
`))}}}),await Promise.all([H(e,
|
|
11
|
-
`))}}),
|
|
9
|
+
`)}],details:{...r.details,searchObservations:i}}}),e.on("tool_result",r=>{if(r.toolName!=="search"||typeof r.details!="object"||r.details===null)return;let n=r.details;if(A(n.payload))return{details:{...n,payload:ne(n.payload,r.content.flatMap(a=>a.type==="text"?[a.text]:[]).join(`
|
|
10
|
+
`))}}}),await Promise.all([H(e,U),z(e,{protocol:G,apiVersion:V,id:"local",setup(r){r.addSelectionProvider((n,a)=>t.register(n.request.query,n.matches,n.complete,a.cwd,a.signal,{...n.request,regex:!1},n.refresh)),r.addResolver({resolver:he(t),priority:-10}),r.addResolver({resolver:me(),priority:-10}),r.addResolver({resolver:de(t),fallback:!0}),r.describe(["Local queries try literal terms first, then unquoted terms as regex when no literal results exist, then separate words for ordinary multi-word queries. Quoted terms stay literal. Boolean conditions stay intact across fallback. Uppercase AND/OR, infix NOT, ||, and space-separated | are Boolean operators; unspaced | and regex groups/classes belong to regex terms. Parentheses containing Boolean operators group Boolean conditions. regex:<pattern> forces regex-only matching; files:<pattern> searches file paths: glob patterns use *, **, ?, character classes and braces; other queries use case-insensitive subsequence matching. Slash-containing globs match cwd-relative paths; basename globs match at any depth.","The result says when a query was broadened. Empty or unknown prefixes are searched as plain text. A recognized prefixed query returns its own results or error; it does not silently become a text search.","SEARCH#HASH:N:line selects one containing line; :match selects its exact match. :all:line selects all unique containing lines and :all:match selects all matches. Read returns containing lines for both forms. A SEARCH resource can be used as a read path or mutation path/anchor; omit the file path for an all-selection spanning files.","Use SEARCH references exactly as returned to select the matching content. A single-result reference becomes stale when its file changes; obtain a fresh result before using it again. An :all reference refreshes the original query when a selected file changes. Search compacts noisy files when the detail limit is exceeded; narrow the query to that file to see individual matches. Compaction does not remove complete :all selections."].join(`
|
|
11
|
+
`))}}),W(e,{protocol:_,apiVersion:j,id:"search-anchors",setup(r){r.tool("replace").addHandler({stage:"text-post-edit",async handler(n){if(!n.result||typeof n.result!="object"||!("kind"in n.result)||n.result.kind!=="completed"||!n.input||typeof n.input!="object")return n;let a=n.input,o=await t.observeAfterEdit([a.path,a.start,a.end],n.signal);return o.length===0?n:{...n,metadata:{...n.metadata,searchObservations:o}}}}),r.addAnchorResolver({resolver:t.anchorResolver(),resources:t.resourceResolver(),kind:B,type:"auxiliary",describeInPrompt:!1})}})])}c(Be,"registerTextSearch");export{fe as createSearchSessionId,Be as default};
|
package/dist/entry-48.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as a,e as b,f as c,g as d}from"./chunk-
|
|
1
|
+
import{d as a,e as b,f as c,g as d,h as e}from"./chunk-P7XO5CIP.js";import"./chunk-GUTQ3PWL.js";import"./chunk-5VSE5X5R.js";import"./chunk-ZC65Z3CK.js";import"./chunk-EI7MMDWY.js";export{e as SearchSessionStore,d as SearchSnapshotChangedError,c as allocateSearchSessionId,a as createSearchSessionId,b as createSearchSessionIdentity};
|