@aerode/pish 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +129 -0
- package/dist/agent.js +398 -0
- package/dist/app.js +473 -0
- package/dist/config.js +187 -0
- package/dist/hooks.js +198 -0
- package/dist/log.js +49 -0
- package/dist/main.js +89 -0
- package/dist/osc.js +157 -0
- package/dist/recorder.js +177 -0
- package/dist/render.js +455 -0
- package/dist/strip.js +46 -0
- package/dist/theme.js +64 -0
- package/dist/vterm.js +59 -0
- package/package.json +49 -0
- package/postinstall.sh +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dacapoday
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# pish
|
|
2
|
+
|
|
3
|
+
**Your shell, with AI built in.**
|
|
4
|
+
|
|
5
|
+
pish wraps bash or zsh transparently. Every command you know works exactly as before — zero overhead. When you type something the shell doesn't recognize, an AI agent ([pi](https://github.com/badlogic/pi-mono)) kicks in automatically.
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<img src="pish-example.gif" alt="pish demo" width="600">
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
pish runs your shell inside a PTY with lightweight hooks injected via rcfile. Normal commands flow through untouched. Only when `command_not_found` fires does pish intercept — it sends your recent shell history as context to the AI agent, which can read files, run commands, and edit code.
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
You ←→ pish (Node.js) ←→ PTY (bash/zsh + hooks)
|
|
17
|
+
↓
|
|
18
|
+
Agent (pi --mode rpc, on demand)
|
|
19
|
+
↓
|
|
20
|
+
Renderer → stderr
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Agent output goes to **stderr**, never contaminating your shell's stdout. Your prompt, pipes, and redirections work exactly as expected.
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
**Requirements:**
|
|
28
|
+
- Node.js ≥ 18
|
|
29
|
+
- bash ≥ 4.4 or zsh ≥ 5.0
|
|
30
|
+
- [`pi`](https://github.com/badlogic/pi-mono) installed and on PATH
|
|
31
|
+
|
|
32
|
+
### Install from npm
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm install -g pish
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Install from source
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git clone https://github.com/dacapoday/pish.git
|
|
42
|
+
cd pish
|
|
43
|
+
npm install
|
|
44
|
+
npm run build
|
|
45
|
+
npm link # makes `pish` available globally
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Run
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pish # start with $SHELL (or bash)
|
|
52
|
+
pish zsh # start with zsh
|
|
53
|
+
pish /usr/local/bin/bash # use a specific shell binary
|
|
54
|
+
pish --pi /path/to/pi # use a specific pi binary
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Usage
|
|
58
|
+
|
|
59
|
+
### Normal commands
|
|
60
|
+
|
|
61
|
+
Everything works exactly like your regular shell — aliases, functions, pipes, redirections, job control, history, tab completion.
|
|
62
|
+
|
|
63
|
+
### AI agent
|
|
64
|
+
|
|
65
|
+
Type anything the shell doesn't recognize. The agent sees your recent commands and their outputs as context:
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
❯ find all TODO comments in src/
|
|
69
|
+
⠋ Working...
|
|
70
|
+
$ grep -rn "TODO" src/
|
|
71
|
+
✓ done (2.1s)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Reverse to pi TUI
|
|
75
|
+
|
|
76
|
+
Type `pi` with no arguments to open the full pi TUI. Your conversation carries over — the AI remembers everything from the current session. When you exit pi, you're back in pish.
|
|
77
|
+
|
|
78
|
+
### Control commands
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
/compact [instructions] # compact agent context
|
|
82
|
+
/model provider/model # switch model
|
|
83
|
+
/think [level] # set thinking level (none/low/medium/high)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Keyboard shortcuts
|
|
87
|
+
|
|
88
|
+
| Key | Action |
|
|
89
|
+
|-----|--------|
|
|
90
|
+
| `Ctrl+C` | Abort running agent |
|
|
91
|
+
| `Ctrl+L` | Clear screen + reset context + reset session |
|
|
92
|
+
|
|
93
|
+
## Configuration
|
|
94
|
+
|
|
95
|
+
Priority: **CLI > ENV > defaults**
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
pish [options] [shell]
|
|
99
|
+
|
|
100
|
+
Options:
|
|
101
|
+
-s, --shell <name> Shell name or path
|
|
102
|
+
--pi <path> Path to pi binary
|
|
103
|
+
--no-agent Disable agent (for debugging)
|
|
104
|
+
-v, --version Show version
|
|
105
|
+
-h, --help Show help
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
| Environment variable | Description | Default |
|
|
109
|
+
|---------------------|-------------|---------|
|
|
110
|
+
| `PISH_SHELL` | Shell name or path | `$SHELL` or `bash` |
|
|
111
|
+
| `PISH_PI` | Path to pi binary | `pi` |
|
|
112
|
+
| `PISH_MAX_CONTEXT` | Max history entries sent to AI | `20` |
|
|
113
|
+
| `PISH_HEAD_LINES` | Output head lines kept | `50` |
|
|
114
|
+
| `PISH_TAIL_LINES` | Output tail lines kept | `30` |
|
|
115
|
+
| `PISH_LINE_WIDTH` | Max chars per line | `512` |
|
|
116
|
+
| `PISH_TOOL_LINES` | Max tool result lines shown | `10` |
|
|
117
|
+
| `PISH_LOG` | Event log (`stderr` or file path) | off |
|
|
118
|
+
| `PISH_DEBUG` | Debug log file path | off |
|
|
119
|
+
| `PISH_NO_BANNER` | Hide startup banner (set to `1`) | off |
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
## Known limitations
|
|
123
|
+
|
|
124
|
+
- **Bash keywords** — `do something` or `if something` triggers a syntax error instead of the AI agent. Rephrase as `please do something`.
|
|
125
|
+
- **CNF returns 0** — `$?` after an agent run is always 0, not 127.
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
[MIT](LICENSE) © [dacapoday](https://github.com/dacapoday)
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent subprocess manager.
|
|
3
|
+
*
|
|
4
|
+
* Spawns `pi --mode rpc`, communicates via stdin/stdout JSONL.
|
|
5
|
+
* Lifecycle: lazy spawn, restart on crash, abort on interrupt.
|
|
6
|
+
*
|
|
7
|
+
* Raw pi RPC events → flattened AgentEvent (consumed directly by renderer).
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from 'node:child_process';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
12
|
+
import { log } from './log.js';
|
|
13
|
+
/** Safely extract a string from an unknown value. */
|
|
14
|
+
function str(v) {
|
|
15
|
+
return typeof v === 'string' ? v : '';
|
|
16
|
+
}
|
|
17
|
+
/** Safely extract a number from an unknown value. */
|
|
18
|
+
function num(v) {
|
|
19
|
+
return typeof v === 'number' ? v : 0;
|
|
20
|
+
}
|
|
21
|
+
/** Convert a raw JSON message to a typed RpcResponse. */
|
|
22
|
+
function toRpcResponse(obj) {
|
|
23
|
+
return {
|
|
24
|
+
type: 'response',
|
|
25
|
+
id: typeof obj.id === 'string' ? obj.id : undefined,
|
|
26
|
+
command: typeof obj.command === 'string' ? obj.command : undefined,
|
|
27
|
+
success: obj.success === true,
|
|
28
|
+
data: (typeof obj.data === 'object' && obj.data !== null
|
|
29
|
+
? obj.data
|
|
30
|
+
: undefined),
|
|
31
|
+
error: typeof obj.error === 'string' ? obj.error : undefined,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export class AgentManager {
|
|
35
|
+
proc = null;
|
|
36
|
+
buf = '';
|
|
37
|
+
cb = null;
|
|
38
|
+
_running = false;
|
|
39
|
+
_submitted = false;
|
|
40
|
+
startTime = 0;
|
|
41
|
+
lastUsage = null;
|
|
42
|
+
piPath;
|
|
43
|
+
pendingRpc = new Map();
|
|
44
|
+
/** Current session file path. Maintained by pish across agent process restarts. */
|
|
45
|
+
sessionFile;
|
|
46
|
+
/** Crash info (in-memory), displayed on next enterAgentMode */
|
|
47
|
+
crashInfo;
|
|
48
|
+
constructor(piPath = 'pi') {
|
|
49
|
+
this.piPath = piPath;
|
|
50
|
+
}
|
|
51
|
+
get running() {
|
|
52
|
+
return this._running;
|
|
53
|
+
}
|
|
54
|
+
/** Whether the agent process is alive and writable. */
|
|
55
|
+
get alive() {
|
|
56
|
+
return this.proc !== null && !this.proc.killed;
|
|
57
|
+
}
|
|
58
|
+
onEvent(cb) {
|
|
59
|
+
this.cb = cb;
|
|
60
|
+
}
|
|
61
|
+
/** Ensure the pi process is alive (lazy spawn). */
|
|
62
|
+
ensureRunning() {
|
|
63
|
+
if (this.proc && !this.proc.killed)
|
|
64
|
+
return;
|
|
65
|
+
const args = ['--mode', 'rpc'];
|
|
66
|
+
if (this.sessionFile) {
|
|
67
|
+
args.push('--session', this.sessionFile);
|
|
68
|
+
}
|
|
69
|
+
log('agent_spawn', { args });
|
|
70
|
+
this.proc = spawn(this.piPath, args, {
|
|
71
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
72
|
+
env: { ...process.env },
|
|
73
|
+
});
|
|
74
|
+
this.buf = '';
|
|
75
|
+
const decoder = new StringDecoder('utf8');
|
|
76
|
+
this.proc.stdout.on('data', (data) => {
|
|
77
|
+
this.buf += decoder.write(data);
|
|
78
|
+
const lines = this.buf.split('\n');
|
|
79
|
+
this.buf = lines.pop();
|
|
80
|
+
for (const line of lines) {
|
|
81
|
+
if (!line.trim())
|
|
82
|
+
continue;
|
|
83
|
+
try {
|
|
84
|
+
const obj = JSON.parse(line);
|
|
85
|
+
this.parseLine(obj);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
log('agent_parse_error', { line });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
// Ignore pi stderr (its own debug output)
|
|
93
|
+
this.proc.stderr.on('data', () => { });
|
|
94
|
+
// Handle stdin errors (EPIPE if process dies before/during write)
|
|
95
|
+
this.proc.stdin.on('error', (err) => {
|
|
96
|
+
if (err.code === 'EPIPE' || err.code === 'ERR_STREAM_DESTROYED')
|
|
97
|
+
return;
|
|
98
|
+
log('agent_stdin_error', { error: String(err) });
|
|
99
|
+
});
|
|
100
|
+
this.proc.on('exit', (code, signal) => {
|
|
101
|
+
log('agent_exit', { code, signal });
|
|
102
|
+
const wasActive = this._running || this._submitted;
|
|
103
|
+
this.proc = null;
|
|
104
|
+
this._running = false;
|
|
105
|
+
this._submitted = false;
|
|
106
|
+
// Reject all pending RPC promises (process died)
|
|
107
|
+
for (const [, pending] of this.pendingRpc) {
|
|
108
|
+
clearTimeout(pending.timer);
|
|
109
|
+
pending.resolve({
|
|
110
|
+
type: 'response',
|
|
111
|
+
success: false,
|
|
112
|
+
error: `pi exited (code=${code})`,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
this.pendingRpc.clear();
|
|
116
|
+
if (wasActive) {
|
|
117
|
+
// Crashed while running or after submit but before agent_start
|
|
118
|
+
this.emitEvent({
|
|
119
|
+
type: 'agent_error',
|
|
120
|
+
error: `pi exited unexpectedly (code=${code}, signal=${signal})`,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
// Non-zero exit (not SIGTERM) → store crash info for next agent mode
|
|
124
|
+
if (code !== null &&
|
|
125
|
+
code !== 0 &&
|
|
126
|
+
signal !== 'SIGTERM' &&
|
|
127
|
+
signal !== 'SIGKILL') {
|
|
128
|
+
this.crashInfo = `agent process exited unexpectedly (code ${code})`;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
// ── JSONL event parsing + flattening ──
|
|
133
|
+
parseLine(obj) {
|
|
134
|
+
const type = obj.type;
|
|
135
|
+
if (!type)
|
|
136
|
+
return;
|
|
137
|
+
switch (type) {
|
|
138
|
+
case 'message_update':
|
|
139
|
+
this.handleMessageUpdate(obj);
|
|
140
|
+
break;
|
|
141
|
+
case 'tool_execution_start':
|
|
142
|
+
this.emitEvent({
|
|
143
|
+
type: 'tool_start',
|
|
144
|
+
toolCallId: str(obj.toolCallId),
|
|
145
|
+
toolName: str(obj.toolName),
|
|
146
|
+
args: (obj.args ?? {}),
|
|
147
|
+
});
|
|
148
|
+
break;
|
|
149
|
+
case 'tool_execution_update':
|
|
150
|
+
this.emitEvent({
|
|
151
|
+
type: 'tool_update',
|
|
152
|
+
toolCallId: str(obj.toolCallId),
|
|
153
|
+
toolName: str(obj.toolName),
|
|
154
|
+
partialResult: obj.partialResult,
|
|
155
|
+
});
|
|
156
|
+
break;
|
|
157
|
+
case 'tool_execution_end':
|
|
158
|
+
this.emitEvent({
|
|
159
|
+
type: 'tool_end',
|
|
160
|
+
toolCallId: str(obj.toolCallId),
|
|
161
|
+
toolName: str(obj.toolName),
|
|
162
|
+
result: obj.result,
|
|
163
|
+
isError: obj.isError ?? false,
|
|
164
|
+
});
|
|
165
|
+
break;
|
|
166
|
+
case 'turn_end':
|
|
167
|
+
this.emitEvent({ type: 'turn_end' });
|
|
168
|
+
break;
|
|
169
|
+
case 'message_end': {
|
|
170
|
+
const msg = obj.message;
|
|
171
|
+
if (msg?.role === 'assistant' && msg.usage) {
|
|
172
|
+
const u = msg.usage;
|
|
173
|
+
const cost = u.cost;
|
|
174
|
+
this.lastUsage = {
|
|
175
|
+
inputTokens: num(u.input),
|
|
176
|
+
outputTokens: num(u.output),
|
|
177
|
+
cacheRead: num(u.cacheRead),
|
|
178
|
+
cacheWrite: num(u.cacheWrite),
|
|
179
|
+
totalTokens: num(u.totalTokens),
|
|
180
|
+
cost: num(cost?.total),
|
|
181
|
+
model: str(msg.model),
|
|
182
|
+
provider: str(msg.provider),
|
|
183
|
+
thinkingLevel: '',
|
|
184
|
+
contextPercent: null,
|
|
185
|
+
contextWindow: 0,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case 'agent_start':
|
|
191
|
+
this._running = true;
|
|
192
|
+
this._submitted = false;
|
|
193
|
+
this.startTime = Date.now();
|
|
194
|
+
this.lastUsage = null;
|
|
195
|
+
break;
|
|
196
|
+
case 'agent_end':
|
|
197
|
+
this._running = false;
|
|
198
|
+
this.emitEvent({
|
|
199
|
+
type: 'agent_done',
|
|
200
|
+
durationMs: Date.now() - this.startTime,
|
|
201
|
+
usage: this.aggregateUsage(obj),
|
|
202
|
+
});
|
|
203
|
+
break;
|
|
204
|
+
case 'response': {
|
|
205
|
+
const rpc = toRpcResponse(obj);
|
|
206
|
+
// Match pending rpcWait() by id
|
|
207
|
+
if (rpc.id && this.pendingRpc.has(rpc.id)) {
|
|
208
|
+
const pending = this.pendingRpc.get(rpc.id);
|
|
209
|
+
this.pendingRpc.delete(rpc.id);
|
|
210
|
+
clearTimeout(pending.timer);
|
|
211
|
+
pending.resolve(rpc);
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
// Unmatched RPC error → emit agent_error
|
|
215
|
+
if (!rpc.success && rpc.error) {
|
|
216
|
+
this.emitEvent({ type: 'agent_error', error: rpc.error });
|
|
217
|
+
}
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
case 'auto_compaction_start':
|
|
221
|
+
this.emitEvent({
|
|
222
|
+
type: 'compaction_start',
|
|
223
|
+
reason: str(obj.reason) || 'threshold',
|
|
224
|
+
});
|
|
225
|
+
break;
|
|
226
|
+
case 'auto_compaction_end': {
|
|
227
|
+
const result = obj.result;
|
|
228
|
+
this.emitEvent({
|
|
229
|
+
type: 'compaction_end',
|
|
230
|
+
summary: result?.summary,
|
|
231
|
+
aborted: obj.aborted ?? false,
|
|
232
|
+
error: obj.errorMessage,
|
|
233
|
+
});
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
// Ignored: extension_ui_request, session header, etc.
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
handleMessageUpdate(obj) {
|
|
240
|
+
const ame = obj.assistantMessageEvent;
|
|
241
|
+
if (!ame)
|
|
242
|
+
return;
|
|
243
|
+
switch (ame.type) {
|
|
244
|
+
case 'thinking_start':
|
|
245
|
+
this.emitEvent({ type: 'thinking_start' });
|
|
246
|
+
break;
|
|
247
|
+
case 'thinking_delta':
|
|
248
|
+
this.emitEvent({ type: 'thinking_delta', delta: str(ame.delta) });
|
|
249
|
+
break;
|
|
250
|
+
case 'thinking_end':
|
|
251
|
+
this.emitEvent({ type: 'thinking_end', content: str(ame.content) });
|
|
252
|
+
break;
|
|
253
|
+
case 'text_start':
|
|
254
|
+
this.emitEvent({ type: 'text_start' });
|
|
255
|
+
break;
|
|
256
|
+
case 'text_delta':
|
|
257
|
+
this.emitEvent({ type: 'text_delta', delta: str(ame.delta) });
|
|
258
|
+
break;
|
|
259
|
+
case 'text_end':
|
|
260
|
+
this.emitEvent({ type: 'text_end', content: str(ame.content) });
|
|
261
|
+
break;
|
|
262
|
+
// toolcall_start/delta/end handled by tool_execution_* events
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** Aggregate usage from agent_end messages array. */
|
|
266
|
+
aggregateUsage(agentEnd) {
|
|
267
|
+
const messages = agentEnd.messages;
|
|
268
|
+
if (!Array.isArray(messages)) {
|
|
269
|
+
return this.lastUsage ?? undefined;
|
|
270
|
+
}
|
|
271
|
+
let input = 0;
|
|
272
|
+
let output = 0;
|
|
273
|
+
let cacheRead = 0;
|
|
274
|
+
let cacheWrite = 0;
|
|
275
|
+
let total = 0;
|
|
276
|
+
let cost = 0;
|
|
277
|
+
let model = '';
|
|
278
|
+
let provider = '';
|
|
279
|
+
for (const msg of messages) {
|
|
280
|
+
if (msg.role === 'assistant' && msg.usage) {
|
|
281
|
+
const u = msg.usage;
|
|
282
|
+
const c = u.cost;
|
|
283
|
+
input += num(u.input);
|
|
284
|
+
output += num(u.output);
|
|
285
|
+
cacheRead += num(u.cacheRead);
|
|
286
|
+
cacheWrite += num(u.cacheWrite);
|
|
287
|
+
total += num(u.totalTokens);
|
|
288
|
+
cost += num(c?.total);
|
|
289
|
+
if (msg.model)
|
|
290
|
+
model = str(msg.model);
|
|
291
|
+
if (msg.provider)
|
|
292
|
+
provider = str(msg.provider);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (total === 0)
|
|
296
|
+
return this.lastUsage ?? undefined;
|
|
297
|
+
return {
|
|
298
|
+
inputTokens: input,
|
|
299
|
+
outputTokens: output,
|
|
300
|
+
cacheRead,
|
|
301
|
+
cacheWrite,
|
|
302
|
+
totalTokens: total,
|
|
303
|
+
cost,
|
|
304
|
+
model,
|
|
305
|
+
provider,
|
|
306
|
+
thinkingLevel: '',
|
|
307
|
+
contextPercent: null,
|
|
308
|
+
contextWindow: 0,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
emitEvent(event) {
|
|
312
|
+
this.cb?.(event);
|
|
313
|
+
}
|
|
314
|
+
/** Submit a prompt to the agent. */
|
|
315
|
+
submit(message) {
|
|
316
|
+
this.ensureRunning();
|
|
317
|
+
if (!this.proc?.stdin?.writable) {
|
|
318
|
+
this.emitEvent({
|
|
319
|
+
type: 'agent_error',
|
|
320
|
+
error: 'pi process not available',
|
|
321
|
+
});
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
this._submitted = true;
|
|
325
|
+
const cmd = `${JSON.stringify({ type: 'prompt', message })}\n`;
|
|
326
|
+
this.proc.stdin.write(cmd);
|
|
327
|
+
}
|
|
328
|
+
/** Abort the current agent run. */
|
|
329
|
+
abort() {
|
|
330
|
+
if (!this.proc?.stdin?.writable)
|
|
331
|
+
return;
|
|
332
|
+
const cmd = `${JSON.stringify({ type: 'abort' })}\n`;
|
|
333
|
+
this.proc.stdin.write(cmd);
|
|
334
|
+
}
|
|
335
|
+
/** Send an RPC command (fire-and-forget). */
|
|
336
|
+
rpc(command) {
|
|
337
|
+
this.ensureRunning();
|
|
338
|
+
if (!this.proc?.stdin?.writable)
|
|
339
|
+
return;
|
|
340
|
+
this.proc.stdin.write(`${JSON.stringify(command)}\n`);
|
|
341
|
+
}
|
|
342
|
+
/** Send an RPC command and wait for the matching response. */
|
|
343
|
+
async rpcWait(command, timeoutMs = 30000) {
|
|
344
|
+
this.ensureRunning();
|
|
345
|
+
if (!this.proc?.stdin?.writable) {
|
|
346
|
+
return {
|
|
347
|
+
type: 'response',
|
|
348
|
+
success: false,
|
|
349
|
+
error: 'pi process not available',
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
const id = randomUUID();
|
|
353
|
+
return new Promise((resolve) => {
|
|
354
|
+
const timer = setTimeout(() => {
|
|
355
|
+
if (this.pendingRpc.delete(id)) {
|
|
356
|
+
resolve({ type: 'response', success: false, error: 'RPC timeout' });
|
|
357
|
+
}
|
|
358
|
+
}, timeoutMs);
|
|
359
|
+
this.pendingRpc.set(id, { resolve, timer });
|
|
360
|
+
this.proc.stdin.write(`${JSON.stringify({ ...command, id })}\n`);
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
/** Kill the process but preserve sessionFile. */
|
|
364
|
+
kill() {
|
|
365
|
+
// Resolve pending RPCs before killing
|
|
366
|
+
for (const [, pending] of this.pendingRpc) {
|
|
367
|
+
clearTimeout(pending.timer);
|
|
368
|
+
pending.resolve({
|
|
369
|
+
type: 'response',
|
|
370
|
+
success: false,
|
|
371
|
+
error: 'agent killed',
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
this.pendingRpc.clear();
|
|
375
|
+
if (this.proc && !this.proc.killed) {
|
|
376
|
+
const p = this.proc;
|
|
377
|
+
p.kill('SIGTERM');
|
|
378
|
+
// Escalate to SIGKILL if process doesn't exit within 2s
|
|
379
|
+
const forceKill = setTimeout(() => {
|
|
380
|
+
try {
|
|
381
|
+
p.kill('SIGKILL');
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
/* already exited */
|
|
385
|
+
}
|
|
386
|
+
}, 2000);
|
|
387
|
+
forceKill.unref(); // Don't prevent Node from exiting
|
|
388
|
+
this.proc = null;
|
|
389
|
+
}
|
|
390
|
+
this._running = false;
|
|
391
|
+
this._submitted = false;
|
|
392
|
+
}
|
|
393
|
+
/** Kill process + clear session (full reset via Ctrl+L). */
|
|
394
|
+
reset() {
|
|
395
|
+
this.kill();
|
|
396
|
+
this.sessionFile = undefined;
|
|
397
|
+
}
|
|
398
|
+
}
|