@leavewhite9088/harness-bus 0.2.0 → 0.2.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/ARCHITECTURE.md +81 -81
- package/LICENSE +21 -21
- package/README.md +86 -86
- package/SETUP_FOR_AI.md +79 -79
- package/package.json +4 -2
- package/packages/agentd/agentd.config.json +3 -1
- package/packages/agentd/cli/commands.mjs +854 -810
- package/packages/agentd/cli/format.mjs +294 -238
- package/packages/agentd/cli/hbus.mjs +14 -14
- package/packages/agentd/cli/index.mjs +4 -4
- package/packages/agentd/cli/skill/SKILL.md +66 -61
- package/packages/agentd/cli/skill/references/custom.md +12 -0
- package/packages/agentd/cli/skill/references/playbooks.md +89 -86
- package/packages/agentd/cli/skill/references/routing.md +43 -35
- package/packages/agentd/cli/skill-install.mjs +157 -140
- package/packages/agentd/cli/update.mjs +221 -221
- package/packages/agentd/client/index.mjs +3 -3
- package/packages/agentd/contexts/executor.md +13 -12
- package/packages/agentd/contexts/templates/architect.md +12 -12
- package/packages/agentd/contexts/templates/coder.md +12 -12
- package/packages/agentd/contexts/templates/debugger.md +12 -12
- package/packages/agentd/contexts/templates/researcher.md +12 -12
- package/packages/agentd/contexts/templates/reviewer.md +12 -12
- package/packages/agentd/contexts/templates/tester.md +12 -12
- package/packages/agentd/core/base/data-dir.mjs +39 -39
- package/packages/agentd/core/base/index.mjs +5 -5
- package/packages/agentd/core/base/protocol.mjs +13 -13
- package/packages/agentd/core/env/config.mjs +52 -1
- package/packages/agentd/core/env/index.mjs +6 -1
- package/packages/agentd/core/env/install.mjs +82 -4
- package/packages/agentd/core/pi/index.mjs +1 -1
- package/packages/agentd/core/pi/rpc.mjs +206 -206
- package/packages/agentd/core/pool/acp/client.mjs +7 -9
- package/packages/agentd/core/pool/acp/process.mjs +27 -18
- package/packages/agentd/core/pool/acp/run-tracker.mjs +293 -293
- package/packages/agentd/core/pool/acp/sessions.mjs +465 -465
- package/packages/agentd/core/pool/acp/turn-runner.mjs +5 -3
- package/packages/agentd/core/pool/index.mjs +2 -2
- package/packages/agentd/core/pool/instances.mjs +3 -5
- package/packages/agentd/core/pool/probe.mjs +91 -85
- package/packages/agentd/core/pool/registry.mjs +45 -1
- package/packages/agentd/core/pool/support/compaction.mjs +2 -43
- package/packages/agentd/core/pool/support/index.mjs +1 -1
- package/packages/agentd/core/prompts/index.mjs +12 -12
- package/packages/agentd/core/prompts/rules.mjs +22 -22
- package/packages/agentd/core/prompts/templates.mjs +172 -172
- package/packages/agentd/core/providers/index.mjs +14 -14
- package/packages/agentd/core/providers/store.mjs +206 -206
- package/packages/agentd/core/records/cleanup.mjs +51 -51
- package/packages/agentd/core/records/index.mjs +8 -8
- package/packages/agentd/core/records/metrics.mjs +73 -73
- package/packages/agentd/core/records/recovery.mjs +39 -39
- package/packages/agentd/core/records/transcripts.mjs +122 -122
- package/packages/agentd/core/threads/index.mjs +18 -17
- package/packages/agentd/core/threads/manager.mjs +498 -476
- package/packages/agentd/core/threads/paths.mjs +78 -78
- package/packages/agentd/core/threads/store.mjs +146 -125
- package/packages/agentd/daemon/agentd.mjs +58 -58
- package/packages/agentd/daemon/events.mjs +126 -126
- package/packages/agentd/daemon/guard.mjs +127 -127
- package/packages/agentd/daemon/lifecycle.mjs +61 -61
- package/packages/agentd/daemon/ops/index.mjs +15 -15
- package/packages/agentd/daemon/ops/providers.mjs +46 -46
- package/packages/agentd/daemon/ops/run.mjs +413 -400
- package/packages/agentd/daemon/ops/system.mjs +76 -69
- package/packages/agentd/daemon/ops/threads.mjs +156 -153
- package/packages/agentd/daemon/server.mjs +130 -130
- package/packages/agentd/package.json +1 -1
- package/packages/agentd/pi-adapter/acp-adapter.mjs +501 -501
- package/packages/agentd/scripts/restart-daemon.mjs +74 -74
- package/packages/agentd/scripts/run-isolated.mjs +42 -42
- package/packages/agentd/scripts/run-unit.mjs +28 -28
- package/packages/backend/src/daemon.mjs +69 -69
- package/packages/backend/src/server.mjs +270 -270
- package/packages/drivers/{agy.mjs → agy/index.mjs} +2 -1
- package/packages/drivers/{claude.mjs → claude/index.mjs} +23 -1
- package/packages/drivers/{codex.mjs → codex/index.mjs} +2 -1
- package/packages/drivers/{dsh.mjs → dsh/index.mjs} +3 -2
- package/packages/drivers/grok/index.mjs +96 -0
- package/packages/drivers/index.mjs +25 -12
- package/packages/drivers/{kimi.mjs → kimi/index.mjs} +2 -1
- package/packages/drivers/{mcode.mjs → mcode/index.mjs} +2 -1
- package/packages/drivers/{opencode.mjs → opencode/index.mjs} +2 -1
- package/packages/drivers/{pi.mjs → pi/index.mjs} +3 -2
- package/packages/drivers/probes/acp.mjs +109 -109
- package/packages/drivers/probes/index.mjs +131 -129
- package/packages/drivers/probes/provider.mjs +222 -222
- package/packages/drivers/qoder/index.mjs +32 -0
- package/packages/drivers/{bin.mjs → shared/bin.mjs} +2 -0
- package/packages/drivers/shared/index.mjs +2 -0
- package/packages/preflight/bin/preflight.mjs +116 -116
- package/packages/preflight/src/index.mjs +5 -5
- package/packages/preflight/src/report.mjs +18 -1
- package/packages/web/dist/apple-touch-icon.png +0 -0
- package/packages/web/dist/assets/index-CT8dIwav.css +2 -0
- package/packages/web/dist/assets/index-CypTUMFB.js +79 -0
- package/packages/web/dist/favicon-32.png +0 -0
- package/packages/web/dist/favicon.svg +19 -15
- package/packages/web/dist/index.html +5 -5
- package/packages/web/dist/assets/index-B2kdkHNw.js +0 -79
- package/packages/web/dist/assets/index-DQTyjC4x.css +0 -2
- /package/packages/drivers/{dsh-sessions.mjs → dsh/sessions.mjs} +0 -0
- /package/packages/drivers/{pi-catalog.mjs → pi/catalog.mjs} +0 -0
- /package/packages/drivers/{lib.mjs → shared/lib.mjs} +0 -0
|
@@ -1,501 +1,501 @@
|
|
|
1
|
-
import { PiRpc } from '../core/pi/index.mjs';
|
|
2
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'node:fs';
|
|
3
|
-
import { homedir } from 'node:os';
|
|
4
|
-
import { basename, dirname, join, resolve } from 'node:path';
|
|
5
|
-
import { fileURLToPath } from 'node:url';
|
|
6
|
-
|
|
7
|
-
export const ACP_ADAPTER_PATH = fileURLToPath(import.meta.url);
|
|
8
|
-
export const MCP_BRIDGE_PATH = join(dirname(ACP_ADAPTER_PATH), 'mcp-bridge.ts');
|
|
9
|
-
|
|
10
|
-
const NODE_BIN = process.env.PI_NODE_BIN || process.execPath;
|
|
11
|
-
const PI_CLI =
|
|
12
|
-
process.env.PI_CLI ||
|
|
13
|
-
join(dirname(NODE_BIN), 'node_modules', '@earendil-works', 'pi-coding-agent', 'dist', 'bundle', 'cli.js');
|
|
14
|
-
|
|
15
|
-
const SESSION_DIR =
|
|
16
|
-
process.env.PI_SESSION_DIR ||
|
|
17
|
-
join(process.env.AGENTD_DATA_DIR || join(homedir(), '.harness-bus'), 'global', 'pi-sessions');
|
|
18
|
-
|
|
19
|
-
const MAP_FILE = join(SESSION_DIR, 'acp-session-map.json');
|
|
20
|
-
const MCP_BRIDGE = MCP_BRIDGE_PATH;
|
|
21
|
-
const DEFAULT_CWD = process.env.AGENTD_BASE_CWD || dirname(dirname(dirname(dirname(ACP_ADAPTER_PATH))));
|
|
22
|
-
|
|
23
|
-
const log = (...a) => process.stderr.write(`[pi-acp] ${a.join(' ')}\n`);
|
|
24
|
-
|
|
25
|
-
let map = {};
|
|
26
|
-
function loadMap() {
|
|
27
|
-
try {
|
|
28
|
-
if (existsSync(MAP_FILE)) map = JSON.parse(readFileSync(MAP_FILE, 'utf8')) ?? {};
|
|
29
|
-
} catch {
|
|
30
|
-
map = {};
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function saveMap() {
|
|
34
|
-
try {
|
|
35
|
-
mkdirSync(SESSION_DIR, { recursive: true });
|
|
36
|
-
writeFileSync(MAP_FILE, JSON.stringify(map, null, 2));
|
|
37
|
-
} catch (err) {
|
|
38
|
-
log('map save failed:', err.message);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
const idOf = (file) => {
|
|
43
|
-
const base = basename(file).replace(/\.jsonl$/, '');
|
|
44
|
-
const i = base.lastIndexOf('_');
|
|
45
|
-
return i >= 0 ? base.slice(i + 1) : base;
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
function findSessionFile(sessionId) {
|
|
49
|
-
try {
|
|
50
|
-
const walk = (dir) => {
|
|
51
|
-
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
52
|
-
const p = join(dir, e.name);
|
|
53
|
-
if (e.isDirectory()) {
|
|
54
|
-
const hit = walk(p);
|
|
55
|
-
if (hit) return hit;
|
|
56
|
-
} else if (e.name.includes(sessionId)) {
|
|
57
|
-
return p;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
return null;
|
|
61
|
-
};
|
|
62
|
-
return walk(SESSION_DIR);
|
|
63
|
-
} catch {
|
|
64
|
-
return null;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
class AdapterPi extends PiRpc {
|
|
69
|
-
constructor() {
|
|
70
|
-
super({ label: 'pi', log });
|
|
71
|
-
this.textListeners = [];
|
|
72
|
-
this.eventListeners = [];
|
|
73
|
-
this.cwd = DEFAULT_CWD;
|
|
74
|
-
this.sessionId = null;
|
|
75
|
-
this.sessionFile = null;
|
|
76
|
-
this.activeAcpId = null;
|
|
77
|
-
this.addListener((rec) => this._fanOut(rec));
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
ensureStarted(cwd) {
|
|
81
|
-
if (this.running) {
|
|
82
|
-
if (cwd && cwd !== this.cwd) {
|
|
83
|
-
throw new Error(
|
|
84
|
-
`pi adapter is pinned to cwd ${this.cwd}; asked for ${cwd}. ` +
|
|
85
|
-
'Restart agentd with a different AGENTD_BASE_CWD to change it.',
|
|
86
|
-
);
|
|
87
|
-
}
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
this.cwd = cwd || DEFAULT_CWD;
|
|
91
|
-
|
|
92
|
-
const withMcp = Boolean(process.env.AGENTD_MCP_SERVERS);
|
|
93
|
-
const args = withMcp
|
|
94
|
-
? [PI_CLI, '--mode', 'rpc', '--no-extensions', '-e', 'builtin:mcp', '-e', MCP_BRIDGE, '--session-dir', SESSION_DIR]
|
|
95
|
-
: [PI_CLI, '--mode', 'rpc', '--no-mcp', '--no-extensions', '--session-dir', SESSION_DIR];
|
|
96
|
-
if (process.env.AGENTD_APPEND_SYSTEM_PROMPT_FILE) args.push('--append-system-prompt', process.env.AGENTD_APPEND_SYSTEM_PROMPT_FILE);
|
|
97
|
-
log(`spawning pi rpc (cwd=${this.cwd})`);
|
|
98
|
-
this.start({ cmd: NODE_BIN, args, cwd: this.cwd, env: process.env });
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
_fanOut(rec) {
|
|
102
|
-
if (rec.type === 'message_end' && rec.message?.role === 'assistant') {
|
|
103
|
-
this.modelError = rec.message.stopReason === 'error' ? String(rec.message.errorMessage || 'the model call failed') : null;
|
|
104
|
-
}
|
|
105
|
-
if (
|
|
106
|
-
this.eventListeners.length &&
|
|
107
|
-
(rec.type === 'tool_execution_start' ||
|
|
108
|
-
rec.type === 'tool_execution_update' ||
|
|
109
|
-
rec.type === 'tool_execution_end' ||
|
|
110
|
-
(rec.type === 'message_update' && rec.assistantMessageEvent?.type === 'thinking_delta'))
|
|
111
|
-
) {
|
|
112
|
-
for (const fn of this.eventListeners) fn(rec);
|
|
113
|
-
}
|
|
114
|
-
if (rec.type === 'message_update') {
|
|
115
|
-
const ev = rec.assistantMessageEvent;
|
|
116
|
-
if (ev?.type === 'text_delta' && ev.delta) {
|
|
117
|
-
for (const fn of this.textListeners) fn(ev.delta);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
command(type, params = {}, timeoutMs = 300_000) {
|
|
123
|
-
return super.command(type, params, timeoutMs);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const rpc = new AdapterPi();
|
|
128
|
-
|
|
129
|
-
const THINKING_FALLBACK = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
130
|
-
|
|
131
|
-
async function buildConfigOptions() {
|
|
132
|
-
const [modelsData, state] = await Promise.all([
|
|
133
|
-
rpc.command('get_available_models', {}, 60_000).catch(() => ({ models: [] })),
|
|
134
|
-
rpc.state().catch(() => ({})),
|
|
135
|
-
]);
|
|
136
|
-
|
|
137
|
-
const models = modelsData?.models ?? [];
|
|
138
|
-
const cur = state?.model;
|
|
139
|
-
const curValue = cur ? `${cur.provider}/${cur.id}` : null;
|
|
140
|
-
|
|
141
|
-
const options = [];
|
|
142
|
-
for (const [id, name] of [
|
|
143
|
-
['model', 'Model'],
|
|
144
|
-
['thinking', 'Thinking level'],
|
|
145
|
-
]) {
|
|
146
|
-
if (id === 'model') {
|
|
147
|
-
options.push({
|
|
148
|
-
id: 'model',
|
|
149
|
-
name,
|
|
150
|
-
category: 'model',
|
|
151
|
-
type: 'select',
|
|
152
|
-
currentValue: curValue,
|
|
153
|
-
options: models.map((m) => ({
|
|
154
|
-
value: `${m.provider}/${m.id}`,
|
|
155
|
-
name: m.name ?? m.id,
|
|
156
|
-
description: `${m.provider}${m.reasoning ? ' · reasoning' : ''}`,
|
|
157
|
-
})),
|
|
158
|
-
});
|
|
159
|
-
} else {
|
|
160
|
-
let levels = THINKING_FALLBACK;
|
|
161
|
-
try {
|
|
162
|
-
const d = await rpc.command('get_available_thinking_levels', {}, 30_000);
|
|
163
|
-
if (Array.isArray(d?.levels) && d.levels.length) levels = d.levels;
|
|
164
|
-
} catch {
|
|
165
|
-
}
|
|
166
|
-
options.push({
|
|
167
|
-
id: 'thinking',
|
|
168
|
-
name,
|
|
169
|
-
category: 'thought_level',
|
|
170
|
-
type: 'select',
|
|
171
|
-
currentValue: state?.thinkingLevel ?? null,
|
|
172
|
-
options: levels.map((l) => ({ value: l, name: l })),
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
return options;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
const send = (obj) => process.stdout.write(JSON.stringify(obj) + '\n');
|
|
180
|
-
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
181
|
-
const replyError = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
182
|
-
const notify = (method, params) => send({ jsonrpc: '2.0', method, params });
|
|
183
|
-
|
|
184
|
-
function emitChunk(sessionId, text) {
|
|
185
|
-
notify('session/update', {
|
|
186
|
-
sessionId,
|
|
187
|
-
update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } },
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
const TOOL_KIND = { read: 'read', edit: 'edit', write: 'edit', bash: 'execute', grep: 'search', find: 'search', ls: 'search' };
|
|
192
|
-
let toolSeq = 0;
|
|
193
|
-
let currentTool = null;
|
|
194
|
-
let lastToolPing = 0;
|
|
195
|
-
|
|
196
|
-
function emitActivity(sessionId, rec) {
|
|
197
|
-
const update = (u) => notify('session/update', { sessionId, update: u });
|
|
198
|
-
if (rec.type === 'message_update') {
|
|
199
|
-
const text = rec.assistantMessageEvent?.delta;
|
|
200
|
-
if (text) update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } });
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
if (rec.type === 'tool_execution_start') {
|
|
204
|
-
currentTool = rec.toolCallId ?? rec.id ?? `pi-${++toolSeq}`;
|
|
205
|
-
const a = rec.args ?? {};
|
|
206
|
-
const hint = String(a.command ?? a.path ?? a.file_path ?? a.pattern ?? '').split(String.fromCharCode(10))[0].slice(0, 70);
|
|
207
|
-
update({
|
|
208
|
-
sessionUpdate: 'tool_call',
|
|
209
|
-
toolCallId: currentTool,
|
|
210
|
-
title: hint ? `${rec.toolName}: ${hint}` : String(rec.toolName ?? 'tool'),
|
|
211
|
-
kind: TOOL_KIND[rec.toolName] ?? 'other',
|
|
212
|
-
status: 'in_progress',
|
|
213
|
-
rawInput: rec.args ?? null,
|
|
214
|
-
});
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
const toolCallId = rec.toolCallId ?? rec.id ?? currentTool;
|
|
218
|
-
if (rec.type === 'tool_execution_update') {
|
|
219
|
-
if (Date.now() - lastToolPing < 1000) return;
|
|
220
|
-
lastToolPing = Date.now();
|
|
221
|
-
update({ sessionUpdate: 'tool_call_update', toolCallId, status: 'in_progress' });
|
|
222
|
-
} else if (rec.type === 'tool_execution_end') {
|
|
223
|
-
const out = (Array.isArray(rec.result?.content) ? rec.result.content : []).map((c) => c?.text ?? '').filter(Boolean).join(String.fromCharCode(10));
|
|
224
|
-
update({
|
|
225
|
-
sessionUpdate: 'tool_call_update',
|
|
226
|
-
toolCallId,
|
|
227
|
-
status: rec.isError ? 'failed' : 'completed',
|
|
228
|
-
...(out ? { content: [{ type: 'content', content: { type: 'text', text: out } }] } : {}),
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
async function emitUsage(sessionId) {
|
|
234
|
-
try {
|
|
235
|
-
const stats = await rpc.command('get_session_stats', {}, 30_000);
|
|
236
|
-
const ctx = stats?.contextUsage;
|
|
237
|
-
if (ctx?.tokens == null) return;
|
|
238
|
-
notify('session/update', { sessionId, update: { sessionUpdate: 'usage_update', used: ctx.tokens, size: ctx.contextWindow ?? null, tokens: stats?.tokens ?? null, cost: stats?.cost != null ? { amount: stats.cost, currency: 'USD' } : null } });
|
|
239
|
-
} catch (err) {
|
|
240
|
-
log(`stats unavailable: ${err.message}`);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async function ensureSession(sessionId) {
|
|
245
|
-
rpc.ensureStarted();
|
|
246
|
-
|
|
247
|
-
if (rpc.activeAcpId === sessionId && rpc.sessionFile) return;
|
|
248
|
-
|
|
249
|
-
const path = map[sessionId] ?? findSessionFile(sessionId);
|
|
250
|
-
if (!path) throw new Error(`unknown session ${sessionId}`);
|
|
251
|
-
|
|
252
|
-
const r = await rpc.command('switch_session', { sessionPath: path });
|
|
253
|
-
if (r?.cancelled) throw new Error('pi canceled the session switch');
|
|
254
|
-
|
|
255
|
-
const st = await rpc.state();
|
|
256
|
-
rpc.sessionId = st?.sessionId ?? null;
|
|
257
|
-
rpc.sessionFile = path;
|
|
258
|
-
rpc.activeAcpId = sessionId;
|
|
259
|
-
map[sessionId] = path;
|
|
260
|
-
saveMap();
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
const cancelling = new Set();
|
|
264
|
-
|
|
265
|
-
async function handle(method, params, id) {
|
|
266
|
-
switch (method) {
|
|
267
|
-
case 'initialize':
|
|
268
|
-
reply(id, {
|
|
269
|
-
protocolVersion: 1,
|
|
270
|
-
agentInfo: { name: 'pi', title: 'pi (RPC adapter)', version: '0.1.0' },
|
|
271
|
-
agentCapabilities: {
|
|
272
|
-
sessionCapabilities: { list: {}, resume: {}, close: {} },
|
|
273
|
-
promptCapabilities: { image: false, audio: false, embeddedContext: false },
|
|
274
|
-
},
|
|
275
|
-
});
|
|
276
|
-
return;
|
|
277
|
-
|
|
278
|
-
case 'session/new': {
|
|
279
|
-
rpc.ensureStarted(params?.cwd);
|
|
280
|
-
await rpc.command('new_session', {}, 60_000);
|
|
281
|
-
const st = await rpc.state();
|
|
282
|
-
rpc.sessionId = st?.sessionId ?? null;
|
|
283
|
-
rpc.sessionFile = st?.sessionFile ?? null;
|
|
284
|
-
const acpId = st?.sessionFile ? idOf(st.sessionFile) : st.sessionId;
|
|
285
|
-
rpc.activeAcpId = acpId;
|
|
286
|
-
map[acpId] = st?.sessionFile ?? null;
|
|
287
|
-
saveMap();
|
|
288
|
-
log(`new session ${acpId}`);
|
|
289
|
-
reply(id, {
|
|
290
|
-
sessionId: acpId,
|
|
291
|
-
configOptions: await buildConfigOptions(),
|
|
292
|
-
});
|
|
293
|
-
return;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
case 'session/list': {
|
|
297
|
-
const sessions = Object.entries(map)
|
|
298
|
-
.filter(([, file]) => file && existsSync(file))
|
|
299
|
-
.map(([sessionId, file]) => ({ sessionId, cwd: rpc.cwd, _file: file }));
|
|
300
|
-
reply(id, { sessions });
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
case 'session/resume': {
|
|
305
|
-
await ensureSession(params.sessionId);
|
|
306
|
-
reply(id, {
|
|
307
|
-
sessionId: params.sessionId,
|
|
308
|
-
configOptions: await buildConfigOptions(),
|
|
309
|
-
});
|
|
310
|
-
await emitUsage(params.sessionId);
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
case 'session/cancel': {
|
|
315
|
-
cancelling.add(params?.sessionId);
|
|
316
|
-
await rpc.command('abort', {}, 30_000).catch((err) => log(`abort failed: ${err.message}`));
|
|
317
|
-
return;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
case 'session/prompt': {
|
|
321
|
-
const sid = params.sessionId;
|
|
322
|
-
cancelling.delete(sid);
|
|
323
|
-
const text = (params.prompt ?? [])
|
|
324
|
-
.map((p) => p.text ?? '')
|
|
325
|
-
.join('')
|
|
326
|
-
.trim();
|
|
327
|
-
await ensureSession(sid);
|
|
328
|
-
|
|
329
|
-
const onText = (delta) => emitChunk(sid, delta);
|
|
330
|
-
rpc.textListeners.push(onText);
|
|
331
|
-
|
|
332
|
-
if (text === '/compact') {
|
|
333
|
-
try {
|
|
334
|
-
await rpc.command('compact', {}, 600_000);
|
|
335
|
-
const stats = await rpc.command('get_session_stats', {}, 30_000).catch(() => null);
|
|
336
|
-
const ctx = stats?.contextUsage;
|
|
337
|
-
if (ctx) notify('session/update', { sessionId: sid, update: { sessionUpdate: 'usage_update', used: ctx.tokens ?? null, size: ctx.contextWindow ?? null } });
|
|
338
|
-
emitChunk(sid, '已压缩对话。');
|
|
339
|
-
reply(id, { stopReason: 'end_turn' });
|
|
340
|
-
} catch (err) {
|
|
341
|
-
replyError(id, -32000, `compact failed: ${err.message}`);
|
|
342
|
-
} finally {
|
|
343
|
-
const i = rpc.textListeners.indexOf(onText);
|
|
344
|
-
if (i >= 0) rpc.textListeners.splice(i, 1);
|
|
345
|
-
}
|
|
346
|
-
return;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
const onEvent = (rec) => emitActivity(sid, rec);
|
|
350
|
-
rpc.eventListeners.push(onEvent);
|
|
351
|
-
|
|
352
|
-
try {
|
|
353
|
-
rpc.modelError = null;
|
|
354
|
-
const settled = rpc.waitSettled(0);
|
|
355
|
-
settled.catch(() => {}); // if pi dies before the command is answered, the failure surfaces there, not as an unhandled rejection
|
|
356
|
-
const r = await rpc.command('prompt', { message: text });
|
|
357
|
-
if (r?.disposition !== 'handled') await settled;
|
|
358
|
-
|
|
359
|
-
if (!map[sid]) {
|
|
360
|
-
const st = await rpc.state();
|
|
361
|
-
if (st?.sessionFile) {
|
|
362
|
-
map[sid] = st.sessionFile;
|
|
363
|
-
rpc.sessionFile = st.sessionFile;
|
|
364
|
-
saveMap();
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
try {
|
|
369
|
-
const stats = await rpc.command('get_session_stats', {}, 30_000);
|
|
370
|
-
const ctx = stats?.contextUsage;
|
|
371
|
-
notify('session/update', {
|
|
372
|
-
sessionId: sid,
|
|
373
|
-
update: {
|
|
374
|
-
sessionUpdate: 'usage_update',
|
|
375
|
-
used: ctx?.tokens ?? null,
|
|
376
|
-
size: ctx?.contextWindow ?? null,
|
|
377
|
-
tokens: stats?.tokens ?? null,
|
|
378
|
-
cost: stats?.cost != null ? { amount: stats.cost, currency: 'USD' } : null,
|
|
379
|
-
},
|
|
380
|
-
});
|
|
381
|
-
} catch (err) {
|
|
382
|
-
log(`stats unavailable: ${err.message}`);
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
if (rpc.modelError && !cancelling.has(sid)) {
|
|
386
|
-
const msg = rpc.modelError;
|
|
387
|
-
rpc.modelError = null;
|
|
388
|
-
replyError(id, -32000, `model call failed: ${msg.slice(0, 500)}`);
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
reply(id, { stopReason: cancelling.delete(sid) ? 'cancelled' : 'end_turn' });
|
|
392
|
-
} finally {
|
|
393
|
-
const i = rpc.textListeners.indexOf(onText);
|
|
394
|
-
if (i >= 0) rpc.textListeners.splice(i, 1);
|
|
395
|
-
const j = rpc.eventListeners.indexOf(onEvent);
|
|
396
|
-
if (j >= 0) rpc.eventListeners.splice(j, 1);
|
|
397
|
-
}
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
case 'session/set_config_option': {
|
|
402
|
-
await ensureSession(params.sessionId);
|
|
403
|
-
const { configId, value } = params;
|
|
404
|
-
|
|
405
|
-
if (configId === 'model') {
|
|
406
|
-
const slash = String(value).indexOf('/');
|
|
407
|
-
if (slash < 1) throw new Error(`model value must be "provider/model", got ${value}`);
|
|
408
|
-
const provider = String(value).slice(0, slash);
|
|
409
|
-
const modelId = String(value).slice(slash + 1);
|
|
410
|
-
await rpc.command('set_model', { provider, modelId }, 60_000);
|
|
411
|
-
} else if (configId === 'thinking') {
|
|
412
|
-
await rpc.command('set_thinking_level', { level: value }, 60_000);
|
|
413
|
-
} else {
|
|
414
|
-
throw new Error(`unsupported configId: ${configId}`);
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
reply(id, { configOptions: await buildConfigOptions() });
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
case 'session/close': {
|
|
422
|
-
delete map[params.sessionId];
|
|
423
|
-
saveMap();
|
|
424
|
-
reply(id, {});
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
default:
|
|
429
|
-
replyError(id, -32601, `Method not found: ${method}`);
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
let buf = '';
|
|
434
|
-
let inflight = 0;
|
|
435
|
-
let ended = false;
|
|
436
|
-
|
|
437
|
-
function maybeExit() {
|
|
438
|
-
if (ended && inflight === 0) {
|
|
439
|
-
try {
|
|
440
|
-
rpc.stop();
|
|
441
|
-
} catch {
|
|
442
|
-
}
|
|
443
|
-
process.exit(0);
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
export function startAcpAdapter() {
|
|
448
|
-
loadMap();
|
|
449
|
-
process.stdin.setEncoding('utf8');
|
|
450
|
-
process.stdin.on('data', (chunk) => {
|
|
451
|
-
buf += chunk;
|
|
452
|
-
let i;
|
|
453
|
-
while ((i = buf.indexOf('\n')) !== -1) {
|
|
454
|
-
const line = buf.slice(0, i).trim();
|
|
455
|
-
buf = buf.slice(i + 1);
|
|
456
|
-
if (!line) continue;
|
|
457
|
-
let msg;
|
|
458
|
-
try {
|
|
459
|
-
msg = JSON.parse(line);
|
|
460
|
-
} catch {
|
|
461
|
-
continue;
|
|
462
|
-
}
|
|
463
|
-
inflight++;
|
|
464
|
-
handle(msg.method, msg.params, msg.id)
|
|
465
|
-
.catch((err) => {
|
|
466
|
-
log(`${msg.method} failed: ${err.message}`);
|
|
467
|
-
if (msg.id != null) replyError(msg.id, -32603, err.message);
|
|
468
|
-
})
|
|
469
|
-
.finally(() => {
|
|
470
|
-
inflight--;
|
|
471
|
-
maybeExit();
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
|
|
476
|
-
process.stdin.on('end', () => {
|
|
477
|
-
ended = true;
|
|
478
|
-
maybeExit();
|
|
479
|
-
});
|
|
480
|
-
|
|
481
|
-
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
482
|
-
process.on(sig, () => {
|
|
483
|
-
try {
|
|
484
|
-
rpc.stop();
|
|
485
|
-
} catch {}
|
|
486
|
-
process.exit(0);
|
|
487
|
-
});
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
log('ready');
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
const realPath = (p) => {
|
|
494
|
-
try {
|
|
495
|
-
return realpathSync(p);
|
|
496
|
-
} catch {
|
|
497
|
-
return resolve(p);
|
|
498
|
-
}
|
|
499
|
-
};
|
|
500
|
-
const sameFile = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
501
|
-
if (process.argv[1] && sameFile(realPath(process.argv[1]), realPath(ACP_ADAPTER_PATH))) startAcpAdapter();
|
|
1
|
+
import { PiRpc } from '../core/pi/index.mjs';
|
|
2
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
export const ACP_ADAPTER_PATH = fileURLToPath(import.meta.url);
|
|
8
|
+
export const MCP_BRIDGE_PATH = join(dirname(ACP_ADAPTER_PATH), 'mcp-bridge.ts');
|
|
9
|
+
|
|
10
|
+
const NODE_BIN = process.env.PI_NODE_BIN || process.execPath;
|
|
11
|
+
const PI_CLI =
|
|
12
|
+
process.env.PI_CLI ||
|
|
13
|
+
join(dirname(NODE_BIN), 'node_modules', '@earendil-works', 'pi-coding-agent', 'dist', 'bundle', 'cli.js');
|
|
14
|
+
|
|
15
|
+
const SESSION_DIR =
|
|
16
|
+
process.env.PI_SESSION_DIR ||
|
|
17
|
+
join(process.env.AGENTD_DATA_DIR || join(homedir(), '.harness-bus'), 'global', 'pi-sessions');
|
|
18
|
+
|
|
19
|
+
const MAP_FILE = join(SESSION_DIR, 'acp-session-map.json');
|
|
20
|
+
const MCP_BRIDGE = MCP_BRIDGE_PATH;
|
|
21
|
+
const DEFAULT_CWD = process.env.AGENTD_BASE_CWD || dirname(dirname(dirname(dirname(ACP_ADAPTER_PATH))));
|
|
22
|
+
|
|
23
|
+
const log = (...a) => process.stderr.write(`[pi-acp] ${a.join(' ')}\n`);
|
|
24
|
+
|
|
25
|
+
let map = {};
|
|
26
|
+
function loadMap() {
|
|
27
|
+
try {
|
|
28
|
+
if (existsSync(MAP_FILE)) map = JSON.parse(readFileSync(MAP_FILE, 'utf8')) ?? {};
|
|
29
|
+
} catch {
|
|
30
|
+
map = {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function saveMap() {
|
|
34
|
+
try {
|
|
35
|
+
mkdirSync(SESSION_DIR, { recursive: true });
|
|
36
|
+
writeFileSync(MAP_FILE, JSON.stringify(map, null, 2));
|
|
37
|
+
} catch (err) {
|
|
38
|
+
log('map save failed:', err.message);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const idOf = (file) => {
|
|
43
|
+
const base = basename(file).replace(/\.jsonl$/, '');
|
|
44
|
+
const i = base.lastIndexOf('_');
|
|
45
|
+
return i >= 0 ? base.slice(i + 1) : base;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
function findSessionFile(sessionId) {
|
|
49
|
+
try {
|
|
50
|
+
const walk = (dir) => {
|
|
51
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
52
|
+
const p = join(dir, e.name);
|
|
53
|
+
if (e.isDirectory()) {
|
|
54
|
+
const hit = walk(p);
|
|
55
|
+
if (hit) return hit;
|
|
56
|
+
} else if (e.name.includes(sessionId)) {
|
|
57
|
+
return p;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
};
|
|
62
|
+
return walk(SESSION_DIR);
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
class AdapterPi extends PiRpc {
|
|
69
|
+
constructor() {
|
|
70
|
+
super({ label: 'pi', log });
|
|
71
|
+
this.textListeners = [];
|
|
72
|
+
this.eventListeners = [];
|
|
73
|
+
this.cwd = DEFAULT_CWD;
|
|
74
|
+
this.sessionId = null;
|
|
75
|
+
this.sessionFile = null;
|
|
76
|
+
this.activeAcpId = null;
|
|
77
|
+
this.addListener((rec) => this._fanOut(rec));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
ensureStarted(cwd) {
|
|
81
|
+
if (this.running) {
|
|
82
|
+
if (cwd && cwd !== this.cwd) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`pi adapter is pinned to cwd ${this.cwd}; asked for ${cwd}. ` +
|
|
85
|
+
'Restart agentd with a different AGENTD_BASE_CWD to change it.',
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
this.cwd = cwd || DEFAULT_CWD;
|
|
91
|
+
|
|
92
|
+
const withMcp = Boolean(process.env.AGENTD_MCP_SERVERS);
|
|
93
|
+
const args = withMcp
|
|
94
|
+
? [PI_CLI, '--mode', 'rpc', '--no-extensions', '-e', 'builtin:mcp', '-e', MCP_BRIDGE, '--session-dir', SESSION_DIR]
|
|
95
|
+
: [PI_CLI, '--mode', 'rpc', '--no-mcp', '--no-extensions', '--session-dir', SESSION_DIR];
|
|
96
|
+
if (process.env.AGENTD_APPEND_SYSTEM_PROMPT_FILE) args.push('--append-system-prompt', process.env.AGENTD_APPEND_SYSTEM_PROMPT_FILE);
|
|
97
|
+
log(`spawning pi rpc (cwd=${this.cwd})`);
|
|
98
|
+
this.start({ cmd: NODE_BIN, args, cwd: this.cwd, env: process.env });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
_fanOut(rec) {
|
|
102
|
+
if (rec.type === 'message_end' && rec.message?.role === 'assistant') {
|
|
103
|
+
this.modelError = rec.message.stopReason === 'error' ? String(rec.message.errorMessage || 'the model call failed') : null;
|
|
104
|
+
}
|
|
105
|
+
if (
|
|
106
|
+
this.eventListeners.length &&
|
|
107
|
+
(rec.type === 'tool_execution_start' ||
|
|
108
|
+
rec.type === 'tool_execution_update' ||
|
|
109
|
+
rec.type === 'tool_execution_end' ||
|
|
110
|
+
(rec.type === 'message_update' && rec.assistantMessageEvent?.type === 'thinking_delta'))
|
|
111
|
+
) {
|
|
112
|
+
for (const fn of this.eventListeners) fn(rec);
|
|
113
|
+
}
|
|
114
|
+
if (rec.type === 'message_update') {
|
|
115
|
+
const ev = rec.assistantMessageEvent;
|
|
116
|
+
if (ev?.type === 'text_delta' && ev.delta) {
|
|
117
|
+
for (const fn of this.textListeners) fn(ev.delta);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
command(type, params = {}, timeoutMs = 300_000) {
|
|
123
|
+
return super.command(type, params, timeoutMs);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const rpc = new AdapterPi();
|
|
128
|
+
|
|
129
|
+
const THINKING_FALLBACK = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
130
|
+
|
|
131
|
+
async function buildConfigOptions() {
|
|
132
|
+
const [modelsData, state] = await Promise.all([
|
|
133
|
+
rpc.command('get_available_models', {}, 60_000).catch(() => ({ models: [] })),
|
|
134
|
+
rpc.state().catch(() => ({})),
|
|
135
|
+
]);
|
|
136
|
+
|
|
137
|
+
const models = modelsData?.models ?? [];
|
|
138
|
+
const cur = state?.model;
|
|
139
|
+
const curValue = cur ? `${cur.provider}/${cur.id}` : null;
|
|
140
|
+
|
|
141
|
+
const options = [];
|
|
142
|
+
for (const [id, name] of [
|
|
143
|
+
['model', 'Model'],
|
|
144
|
+
['thinking', 'Thinking level'],
|
|
145
|
+
]) {
|
|
146
|
+
if (id === 'model') {
|
|
147
|
+
options.push({
|
|
148
|
+
id: 'model',
|
|
149
|
+
name,
|
|
150
|
+
category: 'model',
|
|
151
|
+
type: 'select',
|
|
152
|
+
currentValue: curValue,
|
|
153
|
+
options: models.map((m) => ({
|
|
154
|
+
value: `${m.provider}/${m.id}`,
|
|
155
|
+
name: m.name ?? m.id,
|
|
156
|
+
description: `${m.provider}${m.reasoning ? ' · reasoning' : ''}`,
|
|
157
|
+
})),
|
|
158
|
+
});
|
|
159
|
+
} else {
|
|
160
|
+
let levels = THINKING_FALLBACK;
|
|
161
|
+
try {
|
|
162
|
+
const d = await rpc.command('get_available_thinking_levels', {}, 30_000);
|
|
163
|
+
if (Array.isArray(d?.levels) && d.levels.length) levels = d.levels;
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
options.push({
|
|
167
|
+
id: 'thinking',
|
|
168
|
+
name,
|
|
169
|
+
category: 'thought_level',
|
|
170
|
+
type: 'select',
|
|
171
|
+
currentValue: state?.thinkingLevel ?? null,
|
|
172
|
+
options: levels.map((l) => ({ value: l, name: l })),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return options;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const send = (obj) => process.stdout.write(JSON.stringify(obj) + '\n');
|
|
180
|
+
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
181
|
+
const replyError = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
182
|
+
const notify = (method, params) => send({ jsonrpc: '2.0', method, params });
|
|
183
|
+
|
|
184
|
+
function emitChunk(sessionId, text) {
|
|
185
|
+
notify('session/update', {
|
|
186
|
+
sessionId,
|
|
187
|
+
update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } },
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const TOOL_KIND = { read: 'read', edit: 'edit', write: 'edit', bash: 'execute', grep: 'search', find: 'search', ls: 'search' };
|
|
192
|
+
let toolSeq = 0;
|
|
193
|
+
let currentTool = null;
|
|
194
|
+
let lastToolPing = 0;
|
|
195
|
+
|
|
196
|
+
function emitActivity(sessionId, rec) {
|
|
197
|
+
const update = (u) => notify('session/update', { sessionId, update: u });
|
|
198
|
+
if (rec.type === 'message_update') {
|
|
199
|
+
const text = rec.assistantMessageEvent?.delta;
|
|
200
|
+
if (text) update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } });
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (rec.type === 'tool_execution_start') {
|
|
204
|
+
currentTool = rec.toolCallId ?? rec.id ?? `pi-${++toolSeq}`;
|
|
205
|
+
const a = rec.args ?? {};
|
|
206
|
+
const hint = String(a.command ?? a.path ?? a.file_path ?? a.pattern ?? '').split(String.fromCharCode(10))[0].slice(0, 70);
|
|
207
|
+
update({
|
|
208
|
+
sessionUpdate: 'tool_call',
|
|
209
|
+
toolCallId: currentTool,
|
|
210
|
+
title: hint ? `${rec.toolName}: ${hint}` : String(rec.toolName ?? 'tool'),
|
|
211
|
+
kind: TOOL_KIND[rec.toolName] ?? 'other',
|
|
212
|
+
status: 'in_progress',
|
|
213
|
+
rawInput: rec.args ?? null,
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const toolCallId = rec.toolCallId ?? rec.id ?? currentTool;
|
|
218
|
+
if (rec.type === 'tool_execution_update') {
|
|
219
|
+
if (Date.now() - lastToolPing < 1000) return;
|
|
220
|
+
lastToolPing = Date.now();
|
|
221
|
+
update({ sessionUpdate: 'tool_call_update', toolCallId, status: 'in_progress' });
|
|
222
|
+
} else if (rec.type === 'tool_execution_end') {
|
|
223
|
+
const out = (Array.isArray(rec.result?.content) ? rec.result.content : []).map((c) => c?.text ?? '').filter(Boolean).join(String.fromCharCode(10));
|
|
224
|
+
update({
|
|
225
|
+
sessionUpdate: 'tool_call_update',
|
|
226
|
+
toolCallId,
|
|
227
|
+
status: rec.isError ? 'failed' : 'completed',
|
|
228
|
+
...(out ? { content: [{ type: 'content', content: { type: 'text', text: out } }] } : {}),
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function emitUsage(sessionId) {
|
|
234
|
+
try {
|
|
235
|
+
const stats = await rpc.command('get_session_stats', {}, 30_000);
|
|
236
|
+
const ctx = stats?.contextUsage;
|
|
237
|
+
if (ctx?.tokens == null) return;
|
|
238
|
+
notify('session/update', { sessionId, update: { sessionUpdate: 'usage_update', used: ctx.tokens, size: ctx.contextWindow ?? null, tokens: stats?.tokens ?? null, cost: stats?.cost != null ? { amount: stats.cost, currency: 'USD' } : null } });
|
|
239
|
+
} catch (err) {
|
|
240
|
+
log(`stats unavailable: ${err.message}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function ensureSession(sessionId) {
|
|
245
|
+
rpc.ensureStarted();
|
|
246
|
+
|
|
247
|
+
if (rpc.activeAcpId === sessionId && rpc.sessionFile) return;
|
|
248
|
+
|
|
249
|
+
const path = map[sessionId] ?? findSessionFile(sessionId);
|
|
250
|
+
if (!path) throw new Error(`unknown session ${sessionId}`);
|
|
251
|
+
|
|
252
|
+
const r = await rpc.command('switch_session', { sessionPath: path });
|
|
253
|
+
if (r?.cancelled) throw new Error('pi canceled the session switch');
|
|
254
|
+
|
|
255
|
+
const st = await rpc.state();
|
|
256
|
+
rpc.sessionId = st?.sessionId ?? null;
|
|
257
|
+
rpc.sessionFile = path;
|
|
258
|
+
rpc.activeAcpId = sessionId;
|
|
259
|
+
map[sessionId] = path;
|
|
260
|
+
saveMap();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const cancelling = new Set();
|
|
264
|
+
|
|
265
|
+
async function handle(method, params, id) {
|
|
266
|
+
switch (method) {
|
|
267
|
+
case 'initialize':
|
|
268
|
+
reply(id, {
|
|
269
|
+
protocolVersion: 1,
|
|
270
|
+
agentInfo: { name: 'pi', title: 'pi (RPC adapter)', version: '0.1.0' },
|
|
271
|
+
agentCapabilities: {
|
|
272
|
+
sessionCapabilities: { list: {}, resume: {}, close: {} },
|
|
273
|
+
promptCapabilities: { image: false, audio: false, embeddedContext: false },
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
return;
|
|
277
|
+
|
|
278
|
+
case 'session/new': {
|
|
279
|
+
rpc.ensureStarted(params?.cwd);
|
|
280
|
+
await rpc.command('new_session', {}, 60_000);
|
|
281
|
+
const st = await rpc.state();
|
|
282
|
+
rpc.sessionId = st?.sessionId ?? null;
|
|
283
|
+
rpc.sessionFile = st?.sessionFile ?? null;
|
|
284
|
+
const acpId = st?.sessionFile ? idOf(st.sessionFile) : st.sessionId;
|
|
285
|
+
rpc.activeAcpId = acpId;
|
|
286
|
+
map[acpId] = st?.sessionFile ?? null;
|
|
287
|
+
saveMap();
|
|
288
|
+
log(`new session ${acpId}`);
|
|
289
|
+
reply(id, {
|
|
290
|
+
sessionId: acpId,
|
|
291
|
+
configOptions: await buildConfigOptions(),
|
|
292
|
+
});
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
case 'session/list': {
|
|
297
|
+
const sessions = Object.entries(map)
|
|
298
|
+
.filter(([, file]) => file && existsSync(file))
|
|
299
|
+
.map(([sessionId, file]) => ({ sessionId, cwd: rpc.cwd, _file: file }));
|
|
300
|
+
reply(id, { sessions });
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
case 'session/resume': {
|
|
305
|
+
await ensureSession(params.sessionId);
|
|
306
|
+
reply(id, {
|
|
307
|
+
sessionId: params.sessionId,
|
|
308
|
+
configOptions: await buildConfigOptions(),
|
|
309
|
+
});
|
|
310
|
+
await emitUsage(params.sessionId);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
case 'session/cancel': {
|
|
315
|
+
cancelling.add(params?.sessionId);
|
|
316
|
+
await rpc.command('abort', {}, 30_000).catch((err) => log(`abort failed: ${err.message}`));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
case 'session/prompt': {
|
|
321
|
+
const sid = params.sessionId;
|
|
322
|
+
cancelling.delete(sid);
|
|
323
|
+
const text = (params.prompt ?? [])
|
|
324
|
+
.map((p) => p.text ?? '')
|
|
325
|
+
.join('')
|
|
326
|
+
.trim();
|
|
327
|
+
await ensureSession(sid);
|
|
328
|
+
|
|
329
|
+
const onText = (delta) => emitChunk(sid, delta);
|
|
330
|
+
rpc.textListeners.push(onText);
|
|
331
|
+
|
|
332
|
+
if (text === '/compact') {
|
|
333
|
+
try {
|
|
334
|
+
await rpc.command('compact', {}, 600_000);
|
|
335
|
+
const stats = await rpc.command('get_session_stats', {}, 30_000).catch(() => null);
|
|
336
|
+
const ctx = stats?.contextUsage;
|
|
337
|
+
if (ctx) notify('session/update', { sessionId: sid, update: { sessionUpdate: 'usage_update', used: ctx.tokens ?? null, size: ctx.contextWindow ?? null } });
|
|
338
|
+
emitChunk(sid, '已压缩对话。');
|
|
339
|
+
reply(id, { stopReason: 'end_turn' });
|
|
340
|
+
} catch (err) {
|
|
341
|
+
replyError(id, -32000, `compact failed: ${err.message}`);
|
|
342
|
+
} finally {
|
|
343
|
+
const i = rpc.textListeners.indexOf(onText);
|
|
344
|
+
if (i >= 0) rpc.textListeners.splice(i, 1);
|
|
345
|
+
}
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const onEvent = (rec) => emitActivity(sid, rec);
|
|
350
|
+
rpc.eventListeners.push(onEvent);
|
|
351
|
+
|
|
352
|
+
try {
|
|
353
|
+
rpc.modelError = null;
|
|
354
|
+
const settled = rpc.waitSettled(0);
|
|
355
|
+
settled.catch(() => {}); // if pi dies before the command is answered, the failure surfaces there, not as an unhandled rejection
|
|
356
|
+
const r = await rpc.command('prompt', { message: text });
|
|
357
|
+
if (r?.disposition !== 'handled') await settled;
|
|
358
|
+
|
|
359
|
+
if (!map[sid]) {
|
|
360
|
+
const st = await rpc.state();
|
|
361
|
+
if (st?.sessionFile) {
|
|
362
|
+
map[sid] = st.sessionFile;
|
|
363
|
+
rpc.sessionFile = st.sessionFile;
|
|
364
|
+
saveMap();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
try {
|
|
369
|
+
const stats = await rpc.command('get_session_stats', {}, 30_000);
|
|
370
|
+
const ctx = stats?.contextUsage;
|
|
371
|
+
notify('session/update', {
|
|
372
|
+
sessionId: sid,
|
|
373
|
+
update: {
|
|
374
|
+
sessionUpdate: 'usage_update',
|
|
375
|
+
used: ctx?.tokens ?? null,
|
|
376
|
+
size: ctx?.contextWindow ?? null,
|
|
377
|
+
tokens: stats?.tokens ?? null,
|
|
378
|
+
cost: stats?.cost != null ? { amount: stats.cost, currency: 'USD' } : null,
|
|
379
|
+
},
|
|
380
|
+
});
|
|
381
|
+
} catch (err) {
|
|
382
|
+
log(`stats unavailable: ${err.message}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (rpc.modelError && !cancelling.has(sid)) {
|
|
386
|
+
const msg = rpc.modelError;
|
|
387
|
+
rpc.modelError = null;
|
|
388
|
+
replyError(id, -32000, `model call failed: ${msg.slice(0, 500)}`);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
reply(id, { stopReason: cancelling.delete(sid) ? 'cancelled' : 'end_turn' });
|
|
392
|
+
} finally {
|
|
393
|
+
const i = rpc.textListeners.indexOf(onText);
|
|
394
|
+
if (i >= 0) rpc.textListeners.splice(i, 1);
|
|
395
|
+
const j = rpc.eventListeners.indexOf(onEvent);
|
|
396
|
+
if (j >= 0) rpc.eventListeners.splice(j, 1);
|
|
397
|
+
}
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
case 'session/set_config_option': {
|
|
402
|
+
await ensureSession(params.sessionId);
|
|
403
|
+
const { configId, value } = params;
|
|
404
|
+
|
|
405
|
+
if (configId === 'model') {
|
|
406
|
+
const slash = String(value).indexOf('/');
|
|
407
|
+
if (slash < 1) throw new Error(`model value must be "provider/model", got ${value}`);
|
|
408
|
+
const provider = String(value).slice(0, slash);
|
|
409
|
+
const modelId = String(value).slice(slash + 1);
|
|
410
|
+
await rpc.command('set_model', { provider, modelId }, 60_000);
|
|
411
|
+
} else if (configId === 'thinking') {
|
|
412
|
+
await rpc.command('set_thinking_level', { level: value }, 60_000);
|
|
413
|
+
} else {
|
|
414
|
+
throw new Error(`unsupported configId: ${configId}`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
reply(id, { configOptions: await buildConfigOptions() });
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
case 'session/close': {
|
|
422
|
+
delete map[params.sessionId];
|
|
423
|
+
saveMap();
|
|
424
|
+
reply(id, {});
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
default:
|
|
429
|
+
replyError(id, -32601, `Method not found: ${method}`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
let buf = '';
|
|
434
|
+
let inflight = 0;
|
|
435
|
+
let ended = false;
|
|
436
|
+
|
|
437
|
+
function maybeExit() {
|
|
438
|
+
if (ended && inflight === 0) {
|
|
439
|
+
try {
|
|
440
|
+
rpc.stop();
|
|
441
|
+
} catch {
|
|
442
|
+
}
|
|
443
|
+
process.exit(0);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function startAcpAdapter() {
|
|
448
|
+
loadMap();
|
|
449
|
+
process.stdin.setEncoding('utf8');
|
|
450
|
+
process.stdin.on('data', (chunk) => {
|
|
451
|
+
buf += chunk;
|
|
452
|
+
let i;
|
|
453
|
+
while ((i = buf.indexOf('\n')) !== -1) {
|
|
454
|
+
const line = buf.slice(0, i).trim();
|
|
455
|
+
buf = buf.slice(i + 1);
|
|
456
|
+
if (!line) continue;
|
|
457
|
+
let msg;
|
|
458
|
+
try {
|
|
459
|
+
msg = JSON.parse(line);
|
|
460
|
+
} catch {
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
inflight++;
|
|
464
|
+
handle(msg.method, msg.params, msg.id)
|
|
465
|
+
.catch((err) => {
|
|
466
|
+
log(`${msg.method} failed: ${err.message}`);
|
|
467
|
+
if (msg.id != null) replyError(msg.id, -32603, err.message);
|
|
468
|
+
})
|
|
469
|
+
.finally(() => {
|
|
470
|
+
inflight--;
|
|
471
|
+
maybeExit();
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
process.stdin.on('end', () => {
|
|
477
|
+
ended = true;
|
|
478
|
+
maybeExit();
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
for (const sig of ['SIGINT', 'SIGTERM']) {
|
|
482
|
+
process.on(sig, () => {
|
|
483
|
+
try {
|
|
484
|
+
rpc.stop();
|
|
485
|
+
} catch {}
|
|
486
|
+
process.exit(0);
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
log('ready');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const realPath = (p) => {
|
|
494
|
+
try {
|
|
495
|
+
return realpathSync(p);
|
|
496
|
+
} catch {
|
|
497
|
+
return resolve(p);
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
const sameFile = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
501
|
+
if (process.argv[1] && sameFile(realPath(process.argv[1]), realPath(ACP_ADAPTER_PATH))) startAcpAdapter();
|