@dotlabo/agent-chat-relay 0.0.0-stage → 0.2.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/LICENSE +21 -0
  3. package/README.md +154 -2
  4. package/bin/agent-chat-relay +22 -0
  5. package/package.json +69 -4
  6. package/src/connectors/chatwork.ts +289 -0
  7. package/src/connectors/common.ts +106 -0
  8. package/src/connectors/discord.ts +335 -0
  9. package/src/connectors/http.ts +137 -0
  10. package/src/connectors/line-media.ts +63 -0
  11. package/src/connectors/line.ts +444 -0
  12. package/src/connectors/terminal.ts +367 -0
  13. package/src/core/access.ts +250 -0
  14. package/src/core/instructions.ts +21 -0
  15. package/src/core/mcp.ts +160 -0
  16. package/src/core/relay.ts +1063 -0
  17. package/src/core/retention.ts +44 -0
  18. package/src/harness/config.ts +137 -0
  19. package/src/harness/harness.ts +327 -0
  20. package/src/harness/log-file.ts +34 -0
  21. package/src/harness/pi/config.ts +51 -0
  22. package/src/harness/pi/state.ts +97 -0
  23. package/src/harness/pi/tool-approval.ts +128 -0
  24. package/src/harness/protect.ts +37 -0
  25. package/src/home.ts +67 -0
  26. package/src/jev.ts +201 -0
  27. package/src/main.ts +275 -0
  28. package/src/prompt.ts +12 -0
  29. package/src/serve-args.ts +56 -0
  30. package/src/shutdown.ts +52 -0
  31. package/src/terminal.ts +172 -0
  32. package/src/vendor/pi/adapter.js +3238 -0
  33. package/src/vendor/pi/managed-extension.ts +94 -0
  34. package/src/vendor/pi/managed-pi-rpc.ts +102 -0
  35. package/src/vendor/pi/managed-read.ts +99 -0
  36. package/src/vendor/pi/package.json +7 -0
  37. package/src/vendor/pi/pi-LICENSE +21 -0
  38. package/src/vendor/pi/pi-acp-LICENSE +21 -0
  39. package/src/version.ts +4 -0
  40. package/src/workspace.ts +117 -0
@@ -0,0 +1,3238 @@
1
+ // 生成物。更新手順は docs/pi-packaging.md を参照。
2
+
3
+ // src/index.ts
4
+ import { AgentSideConnection, ndJsonStream } from "pi-acp-protocol-sdk";
5
+
6
+ // src/acp/agent.ts
7
+ import {
8
+ RequestError as RequestError4
9
+ } from "pi-acp-protocol-sdk";
10
+
11
+ // src/acp/auth.ts
12
+ var PI_SETUP_METHOD_ID = "pi_terminal_login";
13
+ function getAuthMethods(opts) {
14
+ const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
15
+ const method = {
16
+ id: PI_SETUP_METHOD_ID,
17
+ name: "Launch pi in the terminal",
18
+ description: "Start pi in an interactive terminal to configure API keys or login",
19
+ // Registry-required fields
20
+ type: "terminal",
21
+ args: ["--terminal-login"],
22
+ env: {}
23
+ };
24
+ if (supportsTerminalAuthMeta) {
25
+ const launch = terminalAuthLaunchSpec();
26
+ method._meta = {
27
+ ...method._meta ?? {},
28
+ "terminal-auth": {
29
+ ...launch,
30
+ label: "Launch pi"
31
+ }
32
+ };
33
+ }
34
+ return [method];
35
+ }
36
+ function terminalAuthLaunchSpec() {
37
+ const argv0 = process.argv[0] || "node";
38
+ const argv1 = process.argv[1];
39
+ if (argv1 && argv0) {
40
+ const isNode = argv0.includes("node");
41
+ const isJs = argv1.endsWith(".js");
42
+ if (isNode && isJs) {
43
+ return { command: argv0, args: [argv1, "--terminal-login"] };
44
+ }
45
+ }
46
+ return { command: "pi-acp", args: ["--terminal-login"] };
47
+ }
48
+
49
+ // src/acp/session.ts
50
+ import { RequestError as RequestError3 } from "pi-acp-protocol-sdk";
51
+ import { readFileSync as readFileSync3 } from "fs";
52
+ import { isAbsolute as isAbsolute2, resolve as resolvePath } from "path";
53
+
54
+ // src/pi-rpc/process.ts
55
+ import { spawn } from "child_process";
56
+ import * as readline from "readline";
57
+ import { dirname } from "path";
58
+ import { fileURLToPath } from "url";
59
+
60
+ // src/pi-rpc/managed-chat.ts
61
+ import { lstatSync, realpathSync, statSync } from "fs";
62
+ import { isAbsolute, join, relative, sep } from "path";
63
+ import { RequestError } from "pi-acp-protocol-sdk";
64
+ function inside(parent, child) {
65
+ const rel = relative(parent, child);
66
+ return !!rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
67
+ }
68
+ function directory(path) {
69
+ if (!path || !isAbsolute(path)) throw new Error();
70
+ const real = realpathSync(path);
71
+ if (!statSync(real).isDirectory()) throw new Error();
72
+ return real;
73
+ }
74
+ function managedPiPaths() {
75
+ if (process.env.PI_ACP_MANAGED_CHAT_WORKSPACE === void 0) return;
76
+ try {
77
+ const workspace = directory(process.env.PI_ACP_MANAGED_CHAT_WORKSPACE);
78
+ const agentDir = directory(process.env.PI_CODING_AGENT_DIR);
79
+ const sessions = directory(join(agentDir, "sessions"));
80
+ const map = join(agentDir, "pi-acp-session-map.json");
81
+ if (workspace === agentDir || inside(workspace, agentDir) || inside(agentDir, workspace) || !inside(agentDir, sessions)) {
82
+ throw new Error();
83
+ }
84
+ const entry = lstatSync(map, { throwIfNoEntry: false });
85
+ if (entry && !entry.isFile()) throw new Error();
86
+ return { workspace, sessions, map };
87
+ } catch {
88
+ throw RequestError.internalError(void 0, "Managed Pi state is not configured");
89
+ }
90
+ }
91
+ function managedSessionFile(sessions, file) {
92
+ try {
93
+ if (!isAbsolute(file)) return;
94
+ const real = realpathSync(file);
95
+ if (inside(sessions, real) && statSync(real).isFile()) return real;
96
+ } catch {
97
+ }
98
+ }
99
+ function managedCwdMatches(cwd, workspace) {
100
+ try {
101
+ return directory(cwd) === workspace;
102
+ } catch {
103
+ return false;
104
+ }
105
+ }
106
+ function managedChatInput(cwd, servers) {
107
+ const managed = managedPiPaths();
108
+ if (!managed) return;
109
+ const server = servers?.[0];
110
+ if (!managedCwdMatches(cwd, managed.workspace) || servers?.length !== 1 || !server || !("type" in server) || server.type !== "http" || server.name !== "chat" || !/^http:\/\/127\.0\.0\.1:[0-9]+\/mcp$/.test(server.url) || server.headers.length !== 1 || server.headers[0]?.name.toLowerCase() !== "authorization" || !/^Bearer [A-Za-z0-9_-]{43}$/.test(server.headers[0].value)) {
111
+ throw RequestError.invalidParams("Managed chat requires relay loopback HTTP MCP on session/new or session/load");
112
+ }
113
+ return { url: server.url, authorization: server.headers[0].value };
114
+ }
115
+
116
+ // src/pi-rpc/process.ts
117
+ import crossSpawn from "cross-spawn";
118
+
119
+ // src/pi-rpc/command.ts
120
+ import { platform } from "os";
121
+ function defaultPiCommand() {
122
+ return platform() === "win32" ? "pi.cmd" : "pi";
123
+ }
124
+ function getPiCommand(override) {
125
+ return override ?? defaultPiCommand();
126
+ }
127
+ function shouldUseShellForPiCommand(cmd) {
128
+ if (platform() !== "win32") return false;
129
+ const normalized = cmd.trim().toLowerCase();
130
+ return normalized.endsWith(".cmd") || normalized.endsWith(".bat");
131
+ }
132
+
133
+ // src/pi-rpc/process.ts
134
+ var PiRpcSpawnError = class extends Error {
135
+ /** Underlying spawn error code, e.g. ENOENT, EACCES */
136
+ code;
137
+ constructor(message, opts) {
138
+ super(message);
139
+ this.name = "PiRpcSpawnError";
140
+ this.code = opts?.code;
141
+ this.cause = opts?.cause;
142
+ }
143
+ };
144
+ var ESC = String.fromCharCode(27);
145
+ var CSI = String.fromCharCode(155);
146
+ var ANSI_ESCAPE_REGEX = new RegExp(
147
+ `[${ESC}${CSI}][[\\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]`,
148
+ "g"
149
+ );
150
+ function stripAnsi(s) {
151
+ return s.replace(ANSI_ESCAPE_REGEX, "");
152
+ }
153
+ var SESSION_STATS_TIMEOUT_MS = 1e3;
154
+ var PiRpcProcess = class _PiRpcProcess {
155
+ child;
156
+ pending = /* @__PURE__ */ new Map();
157
+ eventHandlers = [];
158
+ preludeLines = [];
159
+ constructor(child) {
160
+ this.child = child;
161
+ const rl = readline.createInterface({ input: child.stdout });
162
+ rl.on("line", (line) => {
163
+ if (!line.trim()) return;
164
+ let msg;
165
+ try {
166
+ msg = JSON.parse(line);
167
+ } catch {
168
+ const cleaned = stripAnsi(String(line)).trimEnd();
169
+ if (cleaned) this.preludeLines.push(cleaned);
170
+ return;
171
+ }
172
+ if (msg?.type === "response") {
173
+ const id = typeof msg.id === "string" ? msg.id : void 0;
174
+ if (id !== void 0) this.pending.get(id)?.resolve(msg);
175
+ return;
176
+ }
177
+ for (const h of this.eventHandlers) h(msg);
178
+ });
179
+ child.on("exit", (code, signal) => {
180
+ const err = new Error(`pi process exited (code=${code}, signal=${signal})`);
181
+ for (const [, p] of this.pending) p.reject(err);
182
+ this.pending.clear();
183
+ });
184
+ child.on("error", (err) => {
185
+ for (const [, p] of this.pending) p.reject(err);
186
+ this.pending.clear();
187
+ });
188
+ }
189
+ static async spawn(params) {
190
+ const managed = managedPiPaths();
191
+ const isolation = managed ? await import(new URL("../../harness/config.ts", import.meta.url).href) : void 0;
192
+ const [cmd, ...args] = isolation ? [...isolation.BUN_ISOLATED, fileURLToPath(new URL("./managed-pi-rpc.ts", import.meta.url))] : [getPiCommand(params.piCommand), "--mode", "rpc", "--no-themes"];
193
+ if (params.sessionPath) args.push("--session", params.sessionPath);
194
+ if (managed && !params.managedChat) throw new PiRpcSpawnError("Missing managed chat MCP input");
195
+ const start = shouldUseShellForPiCommand(cmd) ? crossSpawn : spawn;
196
+ const child = start(cmd, args, {
197
+ cwd: params.cwd,
198
+ stdio: managed ? ["pipe", "pipe", "pipe", "pipe"] : "pipe",
199
+ env: process.env
200
+ });
201
+ try {
202
+ await new Promise((resolve4, reject) => {
203
+ const onSpawn = () => {
204
+ cleanup();
205
+ resolve4();
206
+ };
207
+ const onError = (err) => {
208
+ cleanup();
209
+ reject(err);
210
+ };
211
+ const cleanup = () => {
212
+ child.off("spawn", onSpawn);
213
+ child.off("error", onError);
214
+ };
215
+ child.once("spawn", onSpawn);
216
+ child.once("error", onError);
217
+ });
218
+ } catch (e) {
219
+ const code = typeof e?.code === "string" ? e.code : void 0;
220
+ if (code === "ENOENT") {
221
+ throw new PiRpcSpawnError(
222
+ `Could not start pi: executable not found (command: ${cmd}). Pi needs to be installed before it can run in ACP clients. Install it via \`npm install -g @earendil-works/pi-coding-agent\` or ensure \`pi\` is on your PATH. Then try again.`,
223
+ { code, cause: e }
224
+ );
225
+ }
226
+ if (code === "EACCES") {
227
+ throw new PiRpcSpawnError(`Could not start pi: permission denied (command: ${cmd}).`, { code, cause: e });
228
+ }
229
+ throw new PiRpcSpawnError(`Could not start pi (command: ${cmd}).`, { code, cause: e });
230
+ }
231
+ child.stderr.on("data", () => {
232
+ });
233
+ const proc = new _PiRpcProcess(child);
234
+ try {
235
+ if (managed && params.managedChat) {
236
+ await proc.prepareManagedChat(child.stdio[3], params.managedChat);
237
+ }
238
+ const state = await proc.getState(managed ? 5e3 : void 0);
239
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
240
+ if (managed && (!sessionFile || dirname(sessionFile) !== managed.sessions)) throw new Error("Missing managed session file");
241
+ if (sessionFile && !managed) {
242
+ const { mkdirSync: mkdirSync2 } = await import("fs");
243
+ mkdirSync2(dirname(sessionFile), { recursive: true });
244
+ }
245
+ } catch {
246
+ if (managed) {
247
+ proc.dispose();
248
+ throw new PiRpcSpawnError("Managed chat MCP did not become ready");
249
+ }
250
+ }
251
+ return proc;
252
+ }
253
+ async prepareManagedChat(pipe, input2) {
254
+ let finished;
255
+ const result = new Promise((resolve4) => {
256
+ finished = resolve4;
257
+ });
258
+ const onExit = () => finished(false);
259
+ const timeout = setTimeout(onExit, 1e4);
260
+ const unsubscribe = this.onEvent((ev) => {
261
+ if (ev.type !== "extension_ui_request" || ev.method !== "notify") return;
262
+ if (ev.message === "managed-chat:ready") finished(true);
263
+ if (ev.message === "managed-chat:failed") finished(false);
264
+ });
265
+ this.child.once("exit", onExit);
266
+ if (this.child.exitCode !== null || this.child.signalCode !== null) onExit();
267
+ pipe.on("error", onExit);
268
+ try {
269
+ pipe.end(JSON.stringify(input2));
270
+ if (!await result) throw new Error("Managed chat MCP initialization failed");
271
+ } finally {
272
+ clearTimeout(timeout);
273
+ unsubscribe();
274
+ this.child.off("exit", onExit);
275
+ pipe.destroy();
276
+ }
277
+ }
278
+ onEvent(handler) {
279
+ this.eventHandlers.push(handler);
280
+ return () => {
281
+ this.eventHandlers = this.eventHandlers.filter((h) => h !== handler);
282
+ };
283
+ }
284
+ dispose(signal = "SIGTERM") {
285
+ if (this.child.killed) return;
286
+ try {
287
+ this.child.kill(signal);
288
+ } catch {
289
+ }
290
+ }
291
+ /**
292
+ * Human-readable stdout lines emitted before RPC NDJSON begins (e.g. Context/Skills/Extensions info).
293
+ * Themes are typically noisy/less useful for ACP, so callers can filter as needed.
294
+ */
295
+ consumePreludeLines() {
296
+ const lines = this.preludeLines.splice(0, this.preludeLines.length);
297
+ return lines;
298
+ }
299
+ async prompt(message, images = []) {
300
+ const res = await this.request({ type: "prompt", message, images });
301
+ if (!res.success) throw new Error(`pi prompt failed: ${res.error ?? JSON.stringify(res.data)}`);
302
+ }
303
+ async abort() {
304
+ const res = await this.request({ type: "abort" });
305
+ if (!res.success) throw new Error(`pi abort failed: ${res.error ?? JSON.stringify(res.data)}`);
306
+ }
307
+ async getState(timeoutMs) {
308
+ const res = await this.request({ type: "get_state" }, { timeoutMs });
309
+ if (!res.success) throw new Error(`pi get_state failed: ${res.error ?? JSON.stringify(res.data)}`);
310
+ return res.data;
311
+ }
312
+ async getAvailableModels() {
313
+ const res = await this.request({ type: "get_available_models" });
314
+ if (!res.success) throw new Error(`pi get_available_models failed: ${res.error ?? JSON.stringify(res.data)}`);
315
+ return res.data;
316
+ }
317
+ async setModel(provider, modelId) {
318
+ const res = await this.request({ type: "set_model", provider, modelId });
319
+ if (!res.success) throw new Error(`pi set_model failed: ${res.error ?? JSON.stringify(res.data)}`);
320
+ return res.data;
321
+ }
322
+ async getAvailableThinkingLevels() {
323
+ const res = await this.request({ type: "get_available_thinking_levels" });
324
+ if (!res.success)
325
+ throw new Error(`pi get_available_thinking_levels failed: ${res.error ?? JSON.stringify(res.data)}`);
326
+ const data = res.data;
327
+ const levels = data && typeof data === "object" && "levels" in data ? data.levels : void 0;
328
+ if (!Array.isArray(levels) || levels.length === 0 || !levels.every((level) => typeof level === "string" && level.length > 0)) {
329
+ throw new Error("pi get_available_thinking_levels returned invalid levels");
330
+ }
331
+ return levels;
332
+ }
333
+ async setThinkingLevel(level) {
334
+ const res = await this.request({ type: "set_thinking_level", level });
335
+ if (!res.success) throw new Error(`pi set_thinking_level failed: ${res.error ?? JSON.stringify(res.data)}`);
336
+ }
337
+ async setFollowUpMode(mode) {
338
+ const res = await this.request({ type: "set_follow_up_mode", mode });
339
+ if (!res.success) throw new Error(`pi set_follow_up_mode failed: ${res.error ?? JSON.stringify(res.data)}`);
340
+ }
341
+ async setSteeringMode(mode) {
342
+ const res = await this.request({ type: "set_steering_mode", mode });
343
+ if (!res.success) throw new Error(`pi set_steering_mode failed: ${res.error ?? JSON.stringify(res.data)}`);
344
+ }
345
+ async compact(customInstructions) {
346
+ const res = await this.request({ type: "compact", customInstructions });
347
+ if (!res.success) throw new Error(`pi compact failed: ${res.error ?? JSON.stringify(res.data)}`);
348
+ return res.data;
349
+ }
350
+ async setAutoCompaction(enabled) {
351
+ const res = await this.request({ type: "set_auto_compaction", enabled });
352
+ if (!res.success) throw new Error(`pi set_auto_compaction failed: ${res.error ?? JSON.stringify(res.data)}`);
353
+ }
354
+ async getSessionStats(timeoutMs) {
355
+ const res = await this.request({ type: "get_session_stats" }, { timeoutMs });
356
+ if (!res.success) throw new Error(`pi get_session_stats failed: ${res.error ?? JSON.stringify(res.data)}`);
357
+ return res.data ?? {};
358
+ }
359
+ async setSessionName(name) {
360
+ const res = await this.request({ type: "set_session_name", name });
361
+ if (!res.success) throw new Error(`pi set_session_name failed: ${res.error ?? JSON.stringify(res.data)}`);
362
+ }
363
+ async exportHtml(outputPath) {
364
+ const res = await this.request({ type: "export_html", outputPath });
365
+ if (!res.success) throw new Error(`pi export_html failed: ${res.error ?? JSON.stringify(res.data)}`);
366
+ const data = res.data;
367
+ return { path: String(data?.path ?? "") };
368
+ }
369
+ async switchSession(sessionPath) {
370
+ const res = await this.request({ type: "switch_session", sessionPath });
371
+ if (!res.success) throw new Error(`pi switch_session failed: ${res.error ?? JSON.stringify(res.data)}`);
372
+ }
373
+ async getMessages() {
374
+ const res = await this.request({ type: "get_messages" });
375
+ if (!res.success) throw new Error(`pi get_messages failed: ${res.error ?? JSON.stringify(res.data)}`);
376
+ return res.data;
377
+ }
378
+ async getCommands() {
379
+ const res = await this.request({ type: "get_commands" });
380
+ if (!res.success) throw new Error(`pi get_commands failed: ${res.error ?? JSON.stringify(res.data)}`);
381
+ return res.data;
382
+ }
383
+ async sendExtensionUiResponse(response) {
384
+ await this.writeLine(`${JSON.stringify({ type: "extension_ui_response", ...response })}
385
+ `);
386
+ }
387
+ request(cmd, opts) {
388
+ const id = crypto.randomUUID();
389
+ const withId = { ...cmd, id };
390
+ const timeoutMs = opts?.timeoutMs;
391
+ const line = `${JSON.stringify(withId)}
392
+ `;
393
+ return new Promise((resolve4, reject) => {
394
+ let timer;
395
+ const drop = () => {
396
+ if (timer !== void 0) {
397
+ clearTimeout(timer);
398
+ timer = void 0;
399
+ }
400
+ return this.pending.delete(id);
401
+ };
402
+ this.pending.set(id, {
403
+ resolve: (res) => {
404
+ drop();
405
+ resolve4(res);
406
+ },
407
+ reject: (error) => {
408
+ drop();
409
+ reject(error);
410
+ }
411
+ });
412
+ if (timeoutMs !== void 0) {
413
+ timer = setTimeout(() => {
414
+ timer = void 0;
415
+ if (!this.pending.delete(id)) return;
416
+ reject(new Error(`pi ${cmd.type} timed out after ${timeoutMs}ms`));
417
+ }, timeoutMs);
418
+ timer.unref?.();
419
+ }
420
+ void this.writeLine(line).catch((error) => {
421
+ if (!drop()) return;
422
+ reject(error);
423
+ });
424
+ });
425
+ }
426
+ writeLine(line) {
427
+ return new Promise((resolve4, reject) => {
428
+ try {
429
+ this.child.stdin.write(line, (error) => {
430
+ if (error) {
431
+ reject(error);
432
+ return;
433
+ }
434
+ resolve4();
435
+ });
436
+ } catch (error) {
437
+ reject(error);
438
+ }
439
+ });
440
+ }
441
+ };
442
+
443
+ // src/acp/auth-required.ts
444
+ import { RequestError as RequestError2 } from "pi-acp-protocol-sdk";
445
+ function maybeAuthRequiredError(err) {
446
+ const msg = String(err?.message ?? err ?? "");
447
+ const s = msg.toLowerCase();
448
+ const patterns = [
449
+ "api key",
450
+ "apikey",
451
+ "missing key",
452
+ "no key",
453
+ "not configured",
454
+ "unauthorized",
455
+ "authentication",
456
+ "permission denied",
457
+ "forbidden",
458
+ "401",
459
+ "403"
460
+ ];
461
+ const hit = patterns.some((p) => s.includes(p));
462
+ if (!hit) return null;
463
+ return RequestError2.authRequired(
464
+ {
465
+ authMethods: getAuthMethods()
466
+ },
467
+ "Configure an API key or log in with an OAuth provider."
468
+ );
469
+ }
470
+
471
+ // src/acp/session-store.ts
472
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
473
+ import { dirname as dirname2 } from "path";
474
+
475
+ // src/acp/paths.ts
476
+ import { homedir } from "os";
477
+ import { join as join2 } from "path";
478
+ function getPiAcpDir() {
479
+ return join2(homedir(), ".pi", "pi-acp");
480
+ }
481
+ function getPiAcpSessionMapPath() {
482
+ return join2(getPiAcpDir(), "session-map.json");
483
+ }
484
+
485
+ // src/acp/session-store.ts
486
+ function ensureParentDir(path) {
487
+ mkdirSync(dirname2(path), { recursive: true });
488
+ }
489
+ function loadFile(path) {
490
+ try {
491
+ const raw = readFileSync(path, "utf-8");
492
+ const parsed = JSON.parse(raw);
493
+ if (parsed?.version !== 1 || typeof parsed.sessions !== "object" || !parsed.sessions) {
494
+ return { version: 1, sessions: {} };
495
+ }
496
+ return parsed;
497
+ } catch {
498
+ return { version: 1, sessions: {} };
499
+ }
500
+ }
501
+ function saveFile(path, data) {
502
+ ensureParentDir(path);
503
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
504
+ }
505
+ var SessionStore = class {
506
+ path;
507
+ constructor(path = getPiAcpSessionMapPath()) {
508
+ this.path = path;
509
+ }
510
+ list() {
511
+ return Object.values(loadFile(this.path).sessions);
512
+ }
513
+ get(sessionId) {
514
+ const db = loadFile(this.path);
515
+ return db.sessions[sessionId] ?? null;
516
+ }
517
+ upsert(entry) {
518
+ const db = loadFile(this.path);
519
+ db.sessions[entry.sessionId] = {
520
+ sessionId: entry.sessionId,
521
+ cwd: entry.cwd,
522
+ sessionFile: entry.sessionFile,
523
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
524
+ };
525
+ saveFile(this.path, db);
526
+ }
527
+ delete(sessionId) {
528
+ const db = loadFile(this.path);
529
+ if (!db.sessions[sessionId]) return;
530
+ delete db.sessions[sessionId];
531
+ saveFile(this.path, db);
532
+ }
533
+ };
534
+
535
+ // src/acp/slash-commands.ts
536
+ import { existsSync, readdirSync, readFileSync as readFileSync2 } from "fs";
537
+ import { homedir as homedir2 } from "os";
538
+ import { join as join3, resolve } from "path";
539
+ function parseFrontmatter(content) {
540
+ const frontmatter = {};
541
+ if (!content.startsWith("---")) return { frontmatter, content };
542
+ const endIndex = content.indexOf("\n---", 3);
543
+ if (endIndex === -1) return { frontmatter, content };
544
+ const frontmatterBlock = content.slice(4, endIndex);
545
+ const remaining = content.slice(endIndex + 4).trim();
546
+ for (const line of frontmatterBlock.split("\n")) {
547
+ const match = line.match(/^(\w+):\s*(.*)$/);
548
+ if (match) frontmatter[match[1]] = match[2].trim();
549
+ }
550
+ return { frontmatter, content: remaining };
551
+ }
552
+ function loadCommandsFromDir(dir, source, subdir = "") {
553
+ const commands = [];
554
+ if (!existsSync(dir)) return commands;
555
+ try {
556
+ const entries = readdirSync(dir, { withFileTypes: true });
557
+ for (const entry of entries) {
558
+ const fullPath = join3(dir, entry.name);
559
+ if (entry.isDirectory()) {
560
+ const newSubdir = subdir ? `${subdir}:${entry.name}` : entry.name;
561
+ commands.push(...loadCommandsFromDir(fullPath, source, newSubdir));
562
+ continue;
563
+ }
564
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
565
+ try {
566
+ const rawContent = readFileSync2(fullPath, "utf-8");
567
+ const { frontmatter, content } = parseFrontmatter(rawContent);
568
+ const name = entry.name.slice(0, -3);
569
+ const sourceStr = source === "user" ? subdir ? `(user:${subdir})` : "(user)" : subdir ? `(project:${subdir})` : "(project)";
570
+ let description = frontmatter.description || "";
571
+ if (!description) {
572
+ const firstLine = content.split("\n").find((l) => l.trim());
573
+ if (firstLine) {
574
+ description = firstLine.slice(0, 60);
575
+ if (firstLine.length > 60) description += "...";
576
+ }
577
+ }
578
+ description = description ? `${description} ${sourceStr}` : sourceStr;
579
+ commands.push({
580
+ name,
581
+ description,
582
+ content,
583
+ source: sourceStr
584
+ });
585
+ } catch {
586
+ }
587
+ }
588
+ } catch {
589
+ }
590
+ return commands;
591
+ }
592
+ function loadSlashCommands(cwd) {
593
+ const commands = [];
594
+ const userDir = join3(homedir2(), ".pi", "agent", "prompts");
595
+ const projectDir = resolve(cwd, ".pi", "prompts");
596
+ commands.push(...loadCommandsFromDir(userDir, "user"));
597
+ commands.push(...loadCommandsFromDir(projectDir, "project"));
598
+ return commands;
599
+ }
600
+ function toAvailableCommands(fileCommands) {
601
+ const seen = /* @__PURE__ */ new Set();
602
+ const out = [];
603
+ for (const c of fileCommands) {
604
+ if (seen.has(c.name)) continue;
605
+ seen.add(c.name);
606
+ out.push({
607
+ name: c.name,
608
+ description: c.description
609
+ // input: omitted for now (pi commands don't specify this)
610
+ });
611
+ }
612
+ return out;
613
+ }
614
+ function parseCommandArgs(argsString) {
615
+ const args = [];
616
+ let current = "";
617
+ let inQuote = null;
618
+ for (let i = 0; i < argsString.length; i++) {
619
+ const ch = argsString[i];
620
+ if (inQuote) {
621
+ if (ch === inQuote) inQuote = null;
622
+ else current += ch;
623
+ continue;
624
+ }
625
+ if (ch === '"' || ch === "'") {
626
+ inQuote = ch;
627
+ } else if (ch === " " || ch === " ") {
628
+ if (current) {
629
+ args.push(current);
630
+ current = "";
631
+ }
632
+ } else {
633
+ current += ch;
634
+ }
635
+ }
636
+ if (current) args.push(current);
637
+ return args;
638
+ }
639
+ function substituteArgs(content, args) {
640
+ let result = content;
641
+ result = result.replace(/\$@/g, args.join(" "));
642
+ result = result.replace(/\$(\d+)/g, (_m, num) => {
643
+ const idx = Number.parseInt(String(num), 10) - 1;
644
+ return args[idx] ?? "";
645
+ });
646
+ return result;
647
+ }
648
+ function expandSlashCommand(text, fileCommands) {
649
+ if (!text.startsWith("/")) return text;
650
+ const spaceIndex = text.indexOf(" ");
651
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
652
+ const argsString = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
653
+ const cmd = fileCommands.find((c) => c.name === commandName);
654
+ if (!cmd) return text;
655
+ const args = parseCommandArgs(argsString);
656
+ return substituteArgs(cmd.content, args);
657
+ }
658
+
659
+ // src/acp/translate/bash.ts
660
+ function isBashTool(toolName) {
661
+ return toolName.toLowerCase() === "bash";
662
+ }
663
+ function bashCommand(value) {
664
+ const record = value;
665
+ const command = record?.command ?? record?.cmd ?? record?.args?.command ?? record?.args?.cmd ?? record?.input?.command ?? record?.input?.cmd ?? record?.rawInput?.command ?? record?.rawInput?.cmd ?? record?.toolInput?.command ?? record?.toolInput?.cmd ?? record?.details?.command ?? record?.details?.cmd;
666
+ return typeof command === "string" && command.trim() ? command : void 0;
667
+ }
668
+ function bashResultText(result) {
669
+ const record = result;
670
+ const content = record?.content;
671
+ if (Array.isArray(content)) {
672
+ const texts = content.map((c) => {
673
+ const block = c;
674
+ return block.type === "text" && typeof block.text === "string" ? block.text : "";
675
+ }).filter(Boolean);
676
+ if (texts.length) return texts.join("");
677
+ }
678
+ const details = record?.details;
679
+ const stdout = (typeof details?.stdout === "string" ? details.stdout : void 0) ?? (typeof record?.stdout === "string" ? record.stdout : void 0) ?? (typeof details?.output === "string" ? details.output : void 0) ?? (typeof record?.output === "string" ? record.output : void 0);
680
+ const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof record?.stderr === "string" ? record.stderr : void 0);
681
+ return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
682
+ }
683
+ function bashExitCode(result, isError) {
684
+ const record = result;
685
+ const details = record?.details;
686
+ const exitCode = details?.exitCode ?? record?.exitCode ?? details?.code ?? record?.code;
687
+ return typeof exitCode === "number" ? exitCode : isError ? 1 : 0;
688
+ }
689
+ function bashOutputDelta(previous, next) {
690
+ return next.startsWith(previous) ? next.slice(previous.length) : next;
691
+ }
692
+ function bashTerminalContent(toolCallId) {
693
+ return [{ type: "terminal", terminalId: toolCallId }];
694
+ }
695
+ function bashTerminalInfoMeta(toolCallId, cwd) {
696
+ return { terminal_info: { terminal_id: toolCallId, cwd } };
697
+ }
698
+ function bashTerminalOutputMeta(toolCallId, data) {
699
+ return { terminal_output: { terminal_id: toolCallId, data } };
700
+ }
701
+ function bashTerminalExitMeta(toolCallId, exitCode) {
702
+ return { terminal_exit: { terminal_id: toolCallId, exit_code: exitCode, signal: null } };
703
+ }
704
+
705
+ // src/acp/translate/pi-tools.ts
706
+ function toolResultToText(result) {
707
+ if (!result) return "";
708
+ const details = result?.details;
709
+ const diff = details?.diff;
710
+ if (typeof diff === "string" && diff.trim()) {
711
+ return diff;
712
+ }
713
+ const content = result.content;
714
+ if (Array.isArray(content)) {
715
+ const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
716
+ if (texts.length) return texts.join("");
717
+ }
718
+ const stdout = (typeof details?.stdout === "string" ? details.stdout : void 0) ?? (typeof result?.stdout === "string" ? result.stdout : void 0) ?? (typeof details?.output === "string" ? details.output : void 0) ?? (typeof result?.output === "string" ? result.output : void 0);
719
+ const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
720
+ const exitCode = (typeof details?.exitCode === "number" ? details.exitCode : void 0) ?? (typeof result?.exitCode === "number" ? result.exitCode : void 0) ?? (typeof details?.code === "number" ? details.code : void 0) ?? (typeof result?.code === "number" ? result.code : void 0);
721
+ if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
722
+ const parts = [];
723
+ if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
724
+ if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
725
+ ${stderr}`);
726
+ if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
727
+ return parts.join("\n\n").trimEnd();
728
+ }
729
+ try {
730
+ return JSON.stringify(result, null, 2);
731
+ } catch {
732
+ return String(result);
733
+ }
734
+ }
735
+
736
+ // src/acp/session.ts
737
+ var CONFIRM_PERMISSION_OPTIONS = [
738
+ { optionId: "yes", name: "Yes", kind: "allow_once" },
739
+ { optionId: "no", name: "No", kind: "reject_once" }
740
+ ];
741
+ var EXTENSION_UI_RAW_INPUT_KEYS = ["title", "message", "options", "placeholder", "prefill"];
742
+ var CHOICE_OPTION_PREFIX = "choice-";
743
+ var MANAGED_SIGNAL_PREFIX = "managed-chat:";
744
+ var PROTECTED_SIGNAL_PREFIX = "managed-chat:protected:";
745
+ var PROTECTED_META_KEY = "io.github.dot-labo/protected";
746
+ function toUsageUpdate(stats) {
747
+ const used = stats?.contextUsage?.tokens;
748
+ const size = stats?.contextUsage?.contextWindow;
749
+ if (typeof used !== "number" || !Number.isSafeInteger(used) || used < 0) return null;
750
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size <= 0) return null;
751
+ return { sessionUpdate: "usage_update", used, size };
752
+ }
753
+ function findUniqueLineNumber(text, needle) {
754
+ if (!needle) return void 0;
755
+ const first = text.indexOf(needle);
756
+ if (first < 0) return void 0;
757
+ const second = text.indexOf(needle, first + needle.length);
758
+ if (second >= 0) return void 0;
759
+ let line = 1;
760
+ for (let i = 0; i < first; i += 1) {
761
+ if (text.charCodeAt(i) === 10) line += 1;
762
+ }
763
+ return line;
764
+ }
765
+ function getToolPath(args) {
766
+ const record = args;
767
+ if (typeof record?.path === "string") return record.path;
768
+ if (typeof record?.file_path === "string") return record.file_path;
769
+ return void 0;
770
+ }
771
+ function getParsedEdits(args) {
772
+ const record = args;
773
+ const parsed = [];
774
+ if (typeof record?.oldText === "string" && typeof record?.newText === "string") {
775
+ parsed.push({ oldText: record.oldText, newText: record.newText });
776
+ }
777
+ let edits = record?.edits;
778
+ if (typeof edits === "string") {
779
+ try {
780
+ edits = JSON.parse(edits);
781
+ } catch {
782
+ edits = void 0;
783
+ }
784
+ }
785
+ if (Array.isArray(edits)) {
786
+ for (const edit of edits) {
787
+ const item = edit;
788
+ if (typeof item?.oldText === "string" && typeof item?.newText === "string") {
789
+ parsed.push({ oldText: item.oldText, newText: item.newText });
790
+ }
791
+ }
792
+ }
793
+ return parsed;
794
+ }
795
+ function getEditOldTexts(args) {
796
+ const record = args;
797
+ const oldTexts = getParsedEdits(args).map((edit) => edit.oldText);
798
+ if (typeof record?.oldText === "string" && !oldTexts.includes(record.oldText)) oldTexts.push(record.oldText);
799
+ let edits = record?.edits;
800
+ if (typeof edits === "string") {
801
+ try {
802
+ edits = JSON.parse(edits);
803
+ } catch {
804
+ edits = void 0;
805
+ }
806
+ }
807
+ if (Array.isArray(edits)) {
808
+ for (const edit of edits) {
809
+ const oldText = edit?.oldText;
810
+ if (typeof oldText === "string" && !oldTexts.includes(oldText)) oldTexts.push(oldText);
811
+ }
812
+ }
813
+ return oldTexts;
814
+ }
815
+ function toToolCallLocations(args, cwd, line) {
816
+ const path = getToolPath(args);
817
+ if (!path) return void 0;
818
+ const resolvedPath = isAbsolute2(path) ? path : resolvePath(cwd, path);
819
+ return [{ path: resolvedPath, ...typeof line === "number" ? { line } : {} }];
820
+ }
821
+ var SessionManager = class {
822
+ constructor(store = new SessionStore()) {
823
+ this.store = store;
824
+ }
825
+ sessions = /* @__PURE__ */ new Map();
826
+ /** Dispose all sessions and their underlying pi subprocesses. */
827
+ disposeAll() {
828
+ for (const [id] of this.sessions) this.close(id);
829
+ }
830
+ /** Get a registered session if it exists (no throw). */
831
+ maybeGet(sessionId) {
832
+ return this.sessions.get(sessionId);
833
+ }
834
+ /**
835
+ * Dispose a session's underlying pi process and remove it from the manager.
836
+ * Used when clients explicitly reload a session and we want a fresh pi subprocess.
837
+ */
838
+ close(sessionId) {
839
+ const s = this.sessions.get(sessionId);
840
+ if (!s) return;
841
+ try {
842
+ s.proc.dispose?.();
843
+ } catch {
844
+ }
845
+ this.sessions.delete(sessionId);
846
+ }
847
+ /** Close all sessions except the one with `keepSessionId`. */
848
+ closeAllExcept(keepSessionId) {
849
+ for (const [id] of this.sessions) {
850
+ if (id === keepSessionId) continue;
851
+ this.close(id);
852
+ }
853
+ }
854
+ async create(params) {
855
+ let proc;
856
+ try {
857
+ proc = await PiRpcProcess.spawn({
858
+ cwd: params.cwd,
859
+ piCommand: params.piCommand,
860
+ managedChat: params.managedChat
861
+ });
862
+ } catch (e) {
863
+ if (e instanceof PiRpcSpawnError) {
864
+ throw RequestError3.internalError({ code: e.code }, e.message);
865
+ }
866
+ throw e;
867
+ }
868
+ let state = null;
869
+ try {
870
+ state = await proc.getState();
871
+ } catch {
872
+ state = null;
873
+ }
874
+ const sessionId = typeof state?.sessionId === "string" ? state.sessionId : crypto.randomUUID();
875
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
876
+ if (sessionFile) {
877
+ try {
878
+ this.store.upsert({ sessionId, cwd: params.cwd, sessionFile });
879
+ } catch {
880
+ proc.dispose();
881
+ throw RequestError3.internalError(void 0, "Pi session map could not be written");
882
+ }
883
+ }
884
+ const session = new PiAcpSession({
885
+ sessionId,
886
+ cwd: params.cwd,
887
+ mcpServers: params.mcpServers,
888
+ proc,
889
+ conn: params.conn,
890
+ fileCommands: params.fileCommands ?? []
891
+ });
892
+ this.sessions.set(sessionId, session);
893
+ return session;
894
+ }
895
+ get(sessionId) {
896
+ const s = this.sessions.get(sessionId);
897
+ if (!s) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
898
+ return s;
899
+ }
900
+ /**
901
+ * Used by session/load: create a session object bound to an existing sessionId/proc
902
+ * if it isn't already registered.
903
+ */
904
+ getOrCreate(sessionId, params) {
905
+ const existing = this.sessions.get(sessionId);
906
+ if (existing) return existing;
907
+ const session = new PiAcpSession({
908
+ sessionId,
909
+ cwd: params.cwd,
910
+ mcpServers: params.mcpServers,
911
+ proc: params.proc,
912
+ conn: params.conn,
913
+ fileCommands: params.fileCommands ?? []
914
+ });
915
+ this.sessions.set(sessionId, session);
916
+ return session;
917
+ }
918
+ };
919
+ var PiAcpSession = class {
920
+ sessionId;
921
+ cwd;
922
+ mcpServers;
923
+ startupInfo = null;
924
+ startupInfoSent = false;
925
+ proc;
926
+ conn;
927
+ fileCommands;
928
+ // Used to map abort semantics to ACP stopReason.
929
+ // Applies to the currently running turn.
930
+ cancelRequested = false;
931
+ // Current in-flight turn (if any). Additional prompts are queued.
932
+ pendingTurn = null;
933
+ turnQueue = [];
934
+ // Track tool call statuses and ensure they are monotonic (pending -> in_progress -> completed).
935
+ // Some pi events can arrive out of order (e.g. late toolcall_* deltas after execution starts),
936
+ // and clients may hide progress if we ever downgrade back to `pending`.
937
+ currentToolCalls = /* @__PURE__ */ new Map();
938
+ // pi can emit multiple `turn_end` and `agent_end` events for a single user prompt
939
+ // when retry, compaction, or queued continuations run. The session-level prompt
940
+ // completes only when `agent_settled` is emitted.
941
+ inAgentLoop = false;
942
+ // For ACP diff support: capture file contents before edit/write mutations,
943
+ // then emit ToolCallContent {type:"diff"}. Compatible structured edit/write
944
+ // events may need to be implemented in pi in the future.
945
+ // 管理済み起動では、承認前の先読みや diff 用の追加の読み取りを行わない。
946
+ captureFileDiffs = process.env.PI_ACP_MANAGED_CHAT_WORKSPACE === void 0;
947
+ fileSnapshots = /* @__PURE__ */ new Map();
948
+ fileMutationToolCallIds = /* @__PURE__ */ new Set();
949
+ bashToolCallIds = /* @__PURE__ */ new Set();
950
+ bashOutputSnapshots = /* @__PURE__ */ new Map();
951
+ protectedToolCallIds = /* @__PURE__ */ new Set();
952
+ // Ensure `session/update` notifications are sent in order and can be awaited
953
+ // before completing a `session/prompt` request.
954
+ lastEmit = Promise.resolve();
955
+ constructor(opts) {
956
+ this.sessionId = opts.sessionId;
957
+ this.cwd = opts.cwd;
958
+ this.mcpServers = opts.mcpServers;
959
+ this.proc = opts.proc;
960
+ this.conn = opts.conn;
961
+ this.fileCommands = opts.fileCommands ?? [];
962
+ this.proc.onEvent((ev) => this.handlePiEvent(ev));
963
+ }
964
+ setStartupInfo(text) {
965
+ this.startupInfo = text;
966
+ this.startupInfoSent = false;
967
+ }
968
+ /**
969
+ * Best-effort attempt to send startup info outside of a prompt turn.
970
+ * Some clients (e.g. Zed) may only render agent messages once the UI is ready;
971
+ * callers can invoke this shortly after session/new returns.
972
+ */
973
+ sendStartupInfoIfPending() {
974
+ if (this.startupInfoSent || !this.startupInfo) return;
975
+ this.startupInfoSent = true;
976
+ this.emit({
977
+ sessionUpdate: "agent_message_chunk",
978
+ content: { type: "text", text: this.startupInfo }
979
+ });
980
+ }
981
+ async prompt(message, images = []) {
982
+ const expandedMessage = expandSlashCommand(message, this.fileCommands);
983
+ const turnPromise = new Promise((resolve4, reject) => {
984
+ const queued = { message: expandedMessage, images, resolve: resolve4, reject };
985
+ if (this.pendingTurn) {
986
+ this.turnQueue.push(queued);
987
+ this.emit({
988
+ sessionUpdate: "agent_message_chunk",
989
+ content: {
990
+ type: "text",
991
+ text: `Queued message (position ${this.turnQueue.length}).`
992
+ }
993
+ });
994
+ this.emit({
995
+ sessionUpdate: "session_info_update",
996
+ _meta: { piAcp: { queueDepth: this.turnQueue.length, running: true } }
997
+ });
998
+ return;
999
+ }
1000
+ this.startTurn(queued);
1001
+ });
1002
+ return turnPromise;
1003
+ }
1004
+ async cancel() {
1005
+ this.cancelRequested = true;
1006
+ if (this.turnQueue.length) {
1007
+ const queued = this.turnQueue.splice(0, this.turnQueue.length);
1008
+ for (const t of queued) t.resolve("cancelled");
1009
+ this.emit({
1010
+ sessionUpdate: "agent_message_chunk",
1011
+ content: { type: "text", text: "Cleared queued prompts." }
1012
+ });
1013
+ this.emit({
1014
+ sessionUpdate: "session_info_update",
1015
+ _meta: { piAcp: { queueDepth: 0, running: Boolean(this.pendingTurn) } }
1016
+ });
1017
+ }
1018
+ await this.proc.abort();
1019
+ }
1020
+ wasCancelRequested() {
1021
+ return this.cancelRequested;
1022
+ }
1023
+ emit(update) {
1024
+ this.lastEmit = this.lastEmit.then(
1025
+ () => this.conn.sessionUpdate({
1026
+ sessionId: this.sessionId,
1027
+ update
1028
+ })
1029
+ ).catch(() => {
1030
+ });
1031
+ }
1032
+ async flushEmits() {
1033
+ await this.lastEmit;
1034
+ }
1035
+ /**
1036
+ * Best-effort: publish the real pi context-window occupancy as ACP `usage_update`.
1037
+ * Queued updates are flushed even when the stats query fails or times out, so callers
1038
+ * can await this before resolving `session/prompt`.
1039
+ */
1040
+ async publishContextUsage() {
1041
+ try {
1042
+ if (typeof this.proc.getSessionStats === "function") {
1043
+ const update = toUsageUpdate(await this.proc.getSessionStats(SESSION_STATS_TIMEOUT_MS));
1044
+ if (update) this.emit(update);
1045
+ }
1046
+ } catch {
1047
+ }
1048
+ await this.flushEmits();
1049
+ }
1050
+ async settleTurn() {
1051
+ await this.publishContextUsage();
1052
+ const reason = this.cancelRequested ? "cancelled" : "end_turn";
1053
+ this.pendingTurn?.resolve(reason);
1054
+ this.pendingTurn = null;
1055
+ this.inAgentLoop = false;
1056
+ const next = this.turnQueue.shift();
1057
+ if (next) {
1058
+ this.emit({
1059
+ sessionUpdate: "agent_message_chunk",
1060
+ content: { type: "text", text: `Starting queued message. (${this.turnQueue.length} remaining)` }
1061
+ });
1062
+ this.startTurn(next);
1063
+ } else {
1064
+ this.emit({
1065
+ sessionUpdate: "session_info_update",
1066
+ _meta: { piAcp: { queueDepth: 0, running: false } }
1067
+ });
1068
+ }
1069
+ }
1070
+ emitBashToolCall(params) {
1071
+ this.bashToolCallIds.add(params.toolCallId);
1072
+ this.emit({
1073
+ sessionUpdate: params.sessionUpdate,
1074
+ toolCallId: params.toolCallId,
1075
+ title: bashCommand(params.args) ?? params.toolName,
1076
+ kind: "execute",
1077
+ status: params.status,
1078
+ locations: params.locations,
1079
+ ...params.includeTerminal ? { content: bashTerminalContent(params.toolCallId) } : {},
1080
+ ...params.includeTerminal ? { _meta: bashTerminalInfoMeta(params.toolCallId, this.cwd) } : {}
1081
+ });
1082
+ }
1083
+ emitBashOutputUpdate(params) {
1084
+ const text = bashResultText(params.result);
1085
+ const previous = this.bashOutputSnapshots.get(params.toolCallId) ?? "";
1086
+ const delta = bashOutputDelta(previous, text);
1087
+ this.bashOutputSnapshots.set(params.toolCallId, text);
1088
+ this.emit({
1089
+ sessionUpdate: "tool_call_update",
1090
+ toolCallId: params.toolCallId,
1091
+ status: params.status,
1092
+ _meta: {
1093
+ ...delta ? bashTerminalOutputMeta(params.toolCallId, delta) : {},
1094
+ ...params.status === "completed" || params.status === "failed" ? bashTerminalExitMeta(params.toolCallId, bashExitCode(params.result, Boolean(params.isError))) : {}
1095
+ }
1096
+ });
1097
+ }
1098
+ cleanupToolCall(toolCallId) {
1099
+ this.currentToolCalls.delete(toolCallId);
1100
+ this.fileSnapshots.delete(toolCallId);
1101
+ this.fileMutationToolCallIds.delete(toolCallId);
1102
+ this.bashToolCallIds.delete(toolCallId);
1103
+ this.bashOutputSnapshots.delete(toolCallId);
1104
+ this.protectedToolCallIds.delete(toolCallId);
1105
+ }
1106
+ startTurn(t) {
1107
+ this.cancelRequested = false;
1108
+ this.inAgentLoop = false;
1109
+ this.pendingTurn = { resolve: t.resolve, reject: t.reject };
1110
+ this.emit({
1111
+ sessionUpdate: "session_info_update",
1112
+ _meta: { piAcp: { queueDepth: this.turnQueue.length, running: true } }
1113
+ });
1114
+ this.proc.prompt(t.message, t.images).catch((err) => {
1115
+ void this.flushEmits().finally(() => {
1116
+ const authErr = maybeAuthRequiredError(err);
1117
+ if (authErr) {
1118
+ this.pendingTurn?.reject(authErr);
1119
+ } else {
1120
+ const reason = this.cancelRequested ? "cancelled" : "error";
1121
+ this.pendingTurn?.resolve(reason);
1122
+ }
1123
+ this.pendingTurn = null;
1124
+ this.inAgentLoop = false;
1125
+ this.emit({
1126
+ sessionUpdate: "session_info_update",
1127
+ _meta: { piAcp: { queueDepth: this.turnQueue.length, running: false } }
1128
+ });
1129
+ });
1130
+ void err;
1131
+ });
1132
+ }
1133
+ handlePiEvent(ev) {
1134
+ const type = String(ev.type ?? "");
1135
+ switch (type) {
1136
+ case "message_update": {
1137
+ const ame = ev.assistantMessageEvent;
1138
+ if (ame?.type === "text_delta" && typeof ame.delta === "string") {
1139
+ this.emit({
1140
+ sessionUpdate: "agent_message_chunk",
1141
+ content: { type: "text", text: ame.delta }
1142
+ });
1143
+ break;
1144
+ }
1145
+ if (ame?.type === "thinking_delta" && typeof ame.delta === "string") {
1146
+ this.emit({
1147
+ sessionUpdate: "agent_thought_chunk",
1148
+ content: { type: "text", text: ame.delta }
1149
+ });
1150
+ break;
1151
+ }
1152
+ if (ame?.type === "toolcall_start" || ame?.type === "toolcall_delta" || ame?.type === "toolcall_end") {
1153
+ const toolCall = (
1154
+ // pi sometimes includes the tool call directly on the event
1155
+ ame?.toolCall ?? // ...and always includes it in the partial assistant message at contentIndex
1156
+ ame?.partial?.content?.[ame?.contentIndex ?? 0]
1157
+ );
1158
+ const toolCallId = String(toolCall?.id ?? "");
1159
+ const toolName = String(toolCall?.name ?? "tool");
1160
+ if (toolCallId) {
1161
+ const rawInput = toolCall?.arguments && typeof toolCall.arguments === "object" ? toolCall.arguments : (() => {
1162
+ const s = String(toolCall?.partialArgs ?? "");
1163
+ if (!s) return void 0;
1164
+ try {
1165
+ return JSON.parse(s);
1166
+ } catch {
1167
+ return { partialArgs: s };
1168
+ }
1169
+ })();
1170
+ const locations = toToolCallLocations(rawInput, this.cwd);
1171
+ const existingStatus = this.currentToolCalls.get(toolCallId);
1172
+ const status = existingStatus ?? "pending";
1173
+ if (isBashTool(toolName)) {
1174
+ if (!existingStatus) this.currentToolCalls.set(toolCallId, "pending");
1175
+ this.emitBashToolCall({
1176
+ sessionUpdate: existingStatus ? "tool_call_update" : "tool_call",
1177
+ toolCallId,
1178
+ toolName,
1179
+ args: rawInput,
1180
+ status,
1181
+ locations,
1182
+ includeTerminal: !existingStatus
1183
+ });
1184
+ } else if (!existingStatus) {
1185
+ this.currentToolCalls.set(toolCallId, "pending");
1186
+ this.emit({
1187
+ sessionUpdate: "tool_call",
1188
+ toolCallId,
1189
+ title: toolName,
1190
+ kind: toToolKind(toolName),
1191
+ status,
1192
+ locations,
1193
+ rawInput
1194
+ });
1195
+ } else {
1196
+ this.emit({
1197
+ sessionUpdate: "tool_call_update",
1198
+ toolCallId,
1199
+ status,
1200
+ locations,
1201
+ rawInput
1202
+ });
1203
+ }
1204
+ }
1205
+ break;
1206
+ }
1207
+ break;
1208
+ }
1209
+ case "tool_execution_start": {
1210
+ const toolCallId = String(ev.toolCallId ?? crypto.randomUUID());
1211
+ const toolName = String(ev.toolName ?? "tool");
1212
+ const args = ev.args;
1213
+ let line;
1214
+ if (isBashTool(toolName)) {
1215
+ const locations2 = toToolCallLocations(args, this.cwd);
1216
+ const existingStatus = this.currentToolCalls.get(toolCallId);
1217
+ this.currentToolCalls.set(toolCallId, "in_progress");
1218
+ this.emitBashToolCall({
1219
+ sessionUpdate: existingStatus ? "tool_call_update" : "tool_call",
1220
+ toolCallId,
1221
+ toolName,
1222
+ args,
1223
+ status: "in_progress",
1224
+ locations: locations2,
1225
+ includeTerminal: !existingStatus
1226
+ });
1227
+ break;
1228
+ }
1229
+ const isFileMutation = toolName === "edit" || toolName === "write";
1230
+ let snapshotOldText;
1231
+ if (isFileMutation) {
1232
+ this.fileMutationToolCallIds.add(toolCallId);
1233
+ const p = this.captureFileDiffs ? getToolPath(args) : void 0;
1234
+ if (p) {
1235
+ try {
1236
+ const abs = isAbsolute2(p) ? p : resolvePath(this.cwd, p);
1237
+ snapshotOldText = readFileSync3(abs, "utf8");
1238
+ this.fileSnapshots.set(toolCallId, { path: p, oldText: snapshotOldText });
1239
+ if (toolName === "edit") {
1240
+ for (const needle of getEditOldTexts(args)) {
1241
+ line = findUniqueLineNumber(snapshotOldText, needle);
1242
+ if (typeof line === "number") break;
1243
+ }
1244
+ }
1245
+ } catch {
1246
+ snapshotOldText = null;
1247
+ this.fileSnapshots.set(toolCallId, { path: p, oldText: null });
1248
+ }
1249
+ }
1250
+ }
1251
+ const locations = toToolCallLocations(args, this.cwd, line);
1252
+ if (!this.currentToolCalls.has(toolCallId)) {
1253
+ this.currentToolCalls.set(toolCallId, "in_progress");
1254
+ this.emit({
1255
+ sessionUpdate: "tool_call",
1256
+ toolCallId,
1257
+ title: toolName,
1258
+ kind: toToolKind(toolName),
1259
+ status: "in_progress",
1260
+ locations,
1261
+ rawInput: args
1262
+ });
1263
+ } else {
1264
+ this.currentToolCalls.set(toolCallId, "in_progress");
1265
+ this.emit({
1266
+ sessionUpdate: "tool_call_update",
1267
+ toolCallId,
1268
+ status: "in_progress",
1269
+ locations,
1270
+ rawInput: args
1271
+ });
1272
+ }
1273
+ break;
1274
+ }
1275
+ case "tool_execution_update": {
1276
+ const toolCallId = String(ev.toolCallId ?? "");
1277
+ if (!toolCallId) break;
1278
+ const partial = ev.partialResult;
1279
+ if (this.bashToolCallIds.has(toolCallId)) {
1280
+ this.emitBashOutputUpdate({ toolCallId, status: "in_progress", result: partial });
1281
+ break;
1282
+ }
1283
+ const text = this.fileMutationToolCallIds.has(toolCallId) ? "" : toolResultToText(partial);
1284
+ this.emit({
1285
+ sessionUpdate: "tool_call_update",
1286
+ toolCallId,
1287
+ status: "in_progress",
1288
+ content: text ? [{ type: "content", content: { type: "text", text } }] : void 0,
1289
+ ...this.fileMutationToolCallIds.has(toolCallId) ? {} : { rawOutput: partial }
1290
+ });
1291
+ break;
1292
+ }
1293
+ case "tool_execution_end": {
1294
+ const toolCallId = String(ev.toolCallId ?? "");
1295
+ if (!toolCallId) break;
1296
+ const result = ev.result;
1297
+ const isError = Boolean(ev.isError);
1298
+ if (this.bashToolCallIds.has(toolCallId)) {
1299
+ this.emitBashOutputUpdate({
1300
+ toolCallId,
1301
+ status: isError ? "failed" : "completed",
1302
+ result,
1303
+ isError
1304
+ });
1305
+ this.cleanupToolCall(toolCallId);
1306
+ break;
1307
+ }
1308
+ const text = toolResultToText(result);
1309
+ const snapshot = this.fileSnapshots.get(toolCallId);
1310
+ let content;
1311
+ let hasStructuredDiff = false;
1312
+ if (!isError && snapshot) {
1313
+ try {
1314
+ const abs = isAbsolute2(snapshot.path) ? snapshot.path : resolvePath(this.cwd, snapshot.path);
1315
+ const newText = readFileSync3(abs, "utf8");
1316
+ if (snapshot.oldText === null || newText !== snapshot.oldText) {
1317
+ hasStructuredDiff = true;
1318
+ content = [
1319
+ {
1320
+ type: "diff",
1321
+ path: snapshot.path,
1322
+ oldText: snapshot.oldText,
1323
+ newText
1324
+ }
1325
+ ];
1326
+ }
1327
+ } catch {
1328
+ }
1329
+ }
1330
+ if (!content && !hasStructuredDiff && text) {
1331
+ content = [{ type: "content", content: { type: "text", text } }];
1332
+ }
1333
+ this.emit({
1334
+ sessionUpdate: "tool_call_update",
1335
+ toolCallId,
1336
+ status: isError ? "failed" : "completed",
1337
+ content,
1338
+ ...hasStructuredDiff ? {} : { rawOutput: result },
1339
+ ...isError && this.protectedToolCallIds.has(toolCallId) ? { _meta: { [PROTECTED_META_KEY]: true } } : {}
1340
+ });
1341
+ this.cleanupToolCall(toolCallId);
1342
+ break;
1343
+ }
1344
+ case "extension_ui_request": {
1345
+ if (this.takeManagedSignal(ev)) break;
1346
+ void this.handleExtensionUiRequest(ev).catch(() => {
1347
+ const id = stringProp(ev, "id");
1348
+ if (!id) {
1349
+ return;
1350
+ }
1351
+ void this.proc.sendExtensionUiResponse({ id, cancelled: true }).catch(() => {
1352
+ });
1353
+ });
1354
+ break;
1355
+ }
1356
+ case "auto_retry_start": {
1357
+ this.emit({
1358
+ sessionUpdate: "agent_message_chunk",
1359
+ content: { type: "text", text: formatAutoRetryMessage(ev) }
1360
+ });
1361
+ break;
1362
+ }
1363
+ case "auto_retry_end": {
1364
+ this.emit({
1365
+ sessionUpdate: "agent_message_chunk",
1366
+ content: { type: "text", text: "Retry finished, resuming." }
1367
+ });
1368
+ break;
1369
+ }
1370
+ case "auto_compaction_start": {
1371
+ this.emit({
1372
+ sessionUpdate: "agent_message_chunk",
1373
+ content: {
1374
+ type: "text",
1375
+ text: "Context nearing limit, running automatic compaction..."
1376
+ }
1377
+ });
1378
+ break;
1379
+ }
1380
+ case "auto_compaction_end": {
1381
+ this.emit({
1382
+ sessionUpdate: "agent_message_chunk",
1383
+ content: {
1384
+ type: "text",
1385
+ text: "Automatic compaction finished; context was summarized to continue the session."
1386
+ }
1387
+ });
1388
+ break;
1389
+ }
1390
+ case "agent_start": {
1391
+ this.inAgentLoop = true;
1392
+ break;
1393
+ }
1394
+ case "turn_end": {
1395
+ break;
1396
+ }
1397
+ case "agent_end": {
1398
+ this.inAgentLoop = false;
1399
+ break;
1400
+ }
1401
+ case "agent_settled": {
1402
+ void this.settleTurn();
1403
+ break;
1404
+ }
1405
+ default:
1406
+ break;
1407
+ }
1408
+ }
1409
+ /** 中継の拡張の合図なら覚えて true を返す。合図は応答を求めない notify なので、応答も送らない。 */
1410
+ takeManagedSignal(ev) {
1411
+ const message = stringProp(ev, "message");
1412
+ if (stringProp(ev, "method") !== "notify" || !message?.startsWith(MANAGED_SIGNAL_PREFIX)) return false;
1413
+ const toolCallId = message.startsWith(PROTECTED_SIGNAL_PREFIX) ? message.slice(PROTECTED_SIGNAL_PREFIX.length) : "";
1414
+ if (toolCallId) this.protectedToolCallIds.add(toolCallId);
1415
+ return true;
1416
+ }
1417
+ async handleExtensionUiRequest(ev) {
1418
+ const id = stringProp(ev, "id");
1419
+ const method = stringProp(ev, "method");
1420
+ if (!id) {
1421
+ return;
1422
+ }
1423
+ if (method === "select") {
1424
+ await this.handleExtensionSelect(ev, id);
1425
+ return;
1426
+ }
1427
+ if (method === "confirm") {
1428
+ await this.handleExtensionConfirm(ev, id);
1429
+ return;
1430
+ }
1431
+ if (method === "input" || method === "editor") {
1432
+ this.emit({
1433
+ sessionUpdate: "agent_message_chunk",
1434
+ content: {
1435
+ type: "text",
1436
+ text: `Pi ${method} UI request is not supported in ACP yet; cancelling it.`
1437
+ }
1438
+ });
1439
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1440
+ return;
1441
+ }
1442
+ if (method === "notify") {
1443
+ this.emit({
1444
+ sessionUpdate: "agent_message_chunk",
1445
+ content: { type: "text", text: stringProp(ev, "message") ?? "Pi notification" },
1446
+ _meta: { piAcp: { notify: { level: stringProp(ev, "notifyType") ?? "info" } } }
1447
+ });
1448
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1449
+ return;
1450
+ }
1451
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1452
+ }
1453
+ async handleExtensionSelect(ev, id) {
1454
+ const rawOptions = ev.options;
1455
+ const options = Array.isArray(rawOptions) ? rawOptions.map((option) => String(option)) : [];
1456
+ if (!options.length) {
1457
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1458
+ return;
1459
+ }
1460
+ const permissionOptions = options.map((name, index2) => ({
1461
+ optionId: `${CHOICE_OPTION_PREFIX}${index2}`,
1462
+ name,
1463
+ kind: "allow_once"
1464
+ }));
1465
+ const selected = await this.requestExtensionPermission(id, ev, permissionOptions);
1466
+ if (selected === null) {
1467
+ return;
1468
+ }
1469
+ const selectedOptionId = selected.outcome.outcome === "selected" ? selected.outcome.optionId : null;
1470
+ const index = selectedOptionId === null ? null : optionIndex(selectedOptionId);
1471
+ const value = index === null ? null : options.at(index) ?? null;
1472
+ await this.proc.sendExtensionUiResponse(value === null ? { id, cancelled: true } : { id, value });
1473
+ }
1474
+ async handleExtensionConfirm(ev, id) {
1475
+ const selected = await this.requestExtensionPermission(id, ev, CONFIRM_PERMISSION_OPTIONS);
1476
+ if (selected === null) {
1477
+ return;
1478
+ }
1479
+ if (selected.outcome.outcome === "cancelled") {
1480
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1481
+ return;
1482
+ }
1483
+ await this.proc.sendExtensionUiResponse({ id, confirmed: selected.outcome.optionId === "yes" });
1484
+ }
1485
+ async requestExtensionPermission(id, ev, options) {
1486
+ try {
1487
+ return await this.conn.requestPermission({
1488
+ sessionId: this.sessionId,
1489
+ toolCall: extensionUiToolCall(id, ev),
1490
+ options
1491
+ });
1492
+ } catch {
1493
+ await this.proc.sendExtensionUiResponse({ id, cancelled: true });
1494
+ return null;
1495
+ }
1496
+ }
1497
+ };
1498
+ function extensionUiToolCall(id, ev) {
1499
+ const method = stringProp(ev, "method") ?? "ui";
1500
+ const title = stringProp(ev, "title") ?? `Pi ${method}`;
1501
+ const rawInput = { method };
1502
+ for (const key of EXTENSION_UI_RAW_INPUT_KEYS) {
1503
+ if (Object.hasOwn(ev, key)) rawInput[key] = ev[key];
1504
+ }
1505
+ return {
1506
+ toolCallId: `pi-ui-${id}`,
1507
+ title,
1508
+ kind: "other",
1509
+ status: "pending",
1510
+ rawInput
1511
+ };
1512
+ }
1513
+ function stringProp(source, key) {
1514
+ const value = source[key];
1515
+ return typeof value === "string" ? value : null;
1516
+ }
1517
+ function optionIndex(optionId) {
1518
+ if (!optionId.startsWith(CHOICE_OPTION_PREFIX)) {
1519
+ return null;
1520
+ }
1521
+ const rawIndex = optionId.slice(CHOICE_OPTION_PREFIX.length);
1522
+ if (!rawIndex) {
1523
+ return null;
1524
+ }
1525
+ const index = Number(rawIndex);
1526
+ return Number.isSafeInteger(index) && index >= 0 && String(index) === rawIndex ? index : null;
1527
+ }
1528
+ function formatAutoRetryMessage(ev) {
1529
+ const attempt = Number(ev.attempt);
1530
+ const maxAttempts = Number(ev.maxAttempts);
1531
+ const delayMs = Number(ev.delayMs);
1532
+ if (!Number.isFinite(attempt) || !Number.isFinite(maxAttempts) || !Number.isFinite(delayMs)) {
1533
+ return "Retrying...";
1534
+ }
1535
+ let delaySeconds = Math.round(delayMs / 1e3);
1536
+ if (delayMs > 0 && delaySeconds === 0) delaySeconds = 1;
1537
+ return `Retrying (attempt ${attempt}/${maxAttempts}, waiting ${delaySeconds}s)...`;
1538
+ }
1539
+ function toToolKind(toolName) {
1540
+ switch (toolName) {
1541
+ case "read":
1542
+ return "read";
1543
+ case "write":
1544
+ case "edit":
1545
+ return "edit";
1546
+ case "bash":
1547
+ return "execute";
1548
+ default:
1549
+ return "other";
1550
+ }
1551
+ }
1552
+
1553
+ // src/acp/pi-sessions.ts
1554
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2, openSync, readSync, closeSync, existsSync as existsSync2 } from "fs";
1555
+ import { homedir as homedir3 } from "os";
1556
+ import { join as join4, resolve as resolve2, isAbsolute as isAbsolute3 } from "path";
1557
+ var DEFAULT_TAIL_BYTES = 256 * 1024;
1558
+ var DEFAULT_HEAD_BYTES = 64 * 1024;
1559
+ function getPiAgentDir() {
1560
+ return process.env.PI_CODING_AGENT_DIR ? resolve2(process.env.PI_CODING_AGENT_DIR) : join4(homedir3(), ".pi", "agent");
1561
+ }
1562
+ function readSessionDirFromSettings(agentDir) {
1563
+ const settingsPath = join4(agentDir, "settings.json");
1564
+ try {
1565
+ if (!existsSync2(settingsPath)) return null;
1566
+ const raw = readFileSync4(settingsPath, "utf8");
1567
+ const data = JSON.parse(raw);
1568
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
1569
+ const sessionDir = data.sessionDir;
1570
+ if (typeof sessionDir !== "string" || !sessionDir.trim()) return null;
1571
+ return isAbsolute3(sessionDir) ? sessionDir : resolve2(agentDir, sessionDir);
1572
+ } catch {
1573
+ return null;
1574
+ }
1575
+ }
1576
+ function getPiSessionsDir() {
1577
+ const agentDir = getPiAgentDir();
1578
+ return readSessionDirFromSettings(agentDir) ?? join4(agentDir, "sessions");
1579
+ }
1580
+ function walkJsonlFiles(dir, out) {
1581
+ let entries;
1582
+ try {
1583
+ entries = readdirSync2(dir, { withFileTypes: true, encoding: "utf8" });
1584
+ } catch {
1585
+ return;
1586
+ }
1587
+ for (const e of entries) {
1588
+ const name = typeof e.name === "string" ? e.name : String(e.name);
1589
+ const p = join4(dir, name);
1590
+ if (e.isDirectory()) walkJsonlFiles(p, out);
1591
+ else if (e.isFile() && name.endsWith(".jsonl")) out.push(p);
1592
+ }
1593
+ }
1594
+ function readFirstLine(path) {
1595
+ const fd = openSync(path, "r");
1596
+ try {
1597
+ const buf = Buffer.alloc(DEFAULT_HEAD_BYTES);
1598
+ const n = readSync(fd, buf, 0, buf.length, 0);
1599
+ if (n <= 0) return null;
1600
+ const s = buf.subarray(0, n).toString("utf-8");
1601
+ const idx = s.indexOf("\n");
1602
+ return idx === -1 ? s.trim() : s.slice(0, idx).trim();
1603
+ } catch {
1604
+ return null;
1605
+ } finally {
1606
+ try {
1607
+ closeSync(fd);
1608
+ } catch {
1609
+ }
1610
+ }
1611
+ }
1612
+ function readTail(path, tailBytes = DEFAULT_TAIL_BYTES) {
1613
+ const st = statSync2(path);
1614
+ const start = Math.max(0, st.size - tailBytes);
1615
+ const len = st.size - start;
1616
+ const fd = openSync(path, "r");
1617
+ try {
1618
+ const buf = Buffer.alloc(len);
1619
+ const n = readSync(fd, buf, 0, buf.length, start);
1620
+ return buf.subarray(0, n).toString("utf-8");
1621
+ } finally {
1622
+ try {
1623
+ closeSync(fd);
1624
+ } catch {
1625
+ }
1626
+ }
1627
+ }
1628
+ function parseSessionHeader(firstLine) {
1629
+ try {
1630
+ const obj = JSON.parse(firstLine);
1631
+ if (obj?.type !== "session") return null;
1632
+ const sessionId = typeof obj?.id === "string" ? obj.id : null;
1633
+ const cwd = typeof obj?.cwd === "string" ? obj.cwd : null;
1634
+ if (!sessionId || !cwd) return null;
1635
+ return { sessionId, cwd };
1636
+ } catch {
1637
+ return null;
1638
+ }
1639
+ }
1640
+ function pickTitleFromTail(tail) {
1641
+ const lines = tail.split(/\r?\n/);
1642
+ for (let i = lines.length - 1; i >= 0; i--) {
1643
+ const line = lines[i].trim();
1644
+ if (!line) continue;
1645
+ try {
1646
+ const obj = JSON.parse(line);
1647
+ if (obj?.type === "session_info" && typeof obj?.name === "string" && obj.name.trim()) {
1648
+ return obj.name.trim();
1649
+ }
1650
+ } catch {
1651
+ }
1652
+ }
1653
+ return null;
1654
+ }
1655
+ function scanSessionInfoNameFromFile(path) {
1656
+ const fd = openSync(path, "r");
1657
+ try {
1658
+ const buf = Buffer.alloc(256 * 1024);
1659
+ let leftover = "";
1660
+ let offset = 0;
1661
+ let lastName = null;
1662
+ while (true) {
1663
+ const n = readSync(fd, buf, 0, buf.length, offset);
1664
+ if (n <= 0) break;
1665
+ offset += n;
1666
+ const chunk = leftover + buf.subarray(0, n).toString("utf8");
1667
+ const lines = chunk.split(/\r?\n/);
1668
+ leftover = lines.pop() ?? "";
1669
+ for (const line0 of lines) {
1670
+ const line = line0.trim();
1671
+ if (!line) continue;
1672
+ try {
1673
+ const obj = JSON.parse(line);
1674
+ if (obj?.type === "session_info" && typeof obj?.name === "string" && obj.name.trim()) {
1675
+ lastName = obj.name.trim();
1676
+ }
1677
+ } catch {
1678
+ }
1679
+ }
1680
+ }
1681
+ const tailLine = leftover.trim();
1682
+ if (tailLine) {
1683
+ try {
1684
+ const obj = JSON.parse(tailLine);
1685
+ if (obj?.type === "session_info" && typeof obj?.name === "string" && obj.name.trim()) {
1686
+ lastName = obj.name.trim();
1687
+ }
1688
+ } catch {
1689
+ }
1690
+ }
1691
+ return lastName;
1692
+ } catch {
1693
+ return null;
1694
+ } finally {
1695
+ try {
1696
+ closeSync(fd);
1697
+ } catch {
1698
+ }
1699
+ }
1700
+ }
1701
+ function pickUpdatedAtFromTail(tail) {
1702
+ const lines = tail.split(/\r?\n/);
1703
+ for (let i = lines.length - 1; i >= 0; i--) {
1704
+ const line = lines[i].trim();
1705
+ if (!line) continue;
1706
+ try {
1707
+ const obj = JSON.parse(line);
1708
+ if (obj?.type !== "message") continue;
1709
+ const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
1710
+ if (!ts) continue;
1711
+ const d = new Date(ts);
1712
+ if (Number.isFinite(d.getTime())) return d.toISOString();
1713
+ } catch {
1714
+ }
1715
+ }
1716
+ for (let i = lines.length - 1; i >= 0; i--) {
1717
+ const line = lines[i].trim();
1718
+ if (!line) continue;
1719
+ try {
1720
+ const obj = JSON.parse(line);
1721
+ const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
1722
+ if (!ts) continue;
1723
+ const d = new Date(ts);
1724
+ if (Number.isFinite(d.getTime())) return d.toISOString();
1725
+ } catch {
1726
+ }
1727
+ }
1728
+ return null;
1729
+ }
1730
+ function pickFallbackTitleFromHead(path) {
1731
+ try {
1732
+ const raw = readFileSync4(path, { encoding: "utf8" });
1733
+ const lines = raw.split(/\r?\n/);
1734
+ for (const line0 of lines) {
1735
+ const line = line0.trim();
1736
+ if (!line) continue;
1737
+ try {
1738
+ const obj = JSON.parse(line);
1739
+ if (obj?.type === "message" && obj?.message?.role === "user") {
1740
+ const content = obj?.message?.content;
1741
+ if (typeof content === "string") return content.slice(0, 80);
1742
+ if (Array.isArray(content)) {
1743
+ const t = content.find((c) => c?.type === "text" && typeof c?.text === "string");
1744
+ if (t?.text) return String(t.text).slice(0, 80);
1745
+ }
1746
+ }
1747
+ } catch {
1748
+ }
1749
+ if (lines.length > 2e3) break;
1750
+ }
1751
+ } catch {
1752
+ }
1753
+ return null;
1754
+ }
1755
+ function listPiSessions() {
1756
+ const sessionsDir = getPiSessionsDir();
1757
+ const files = [];
1758
+ walkJsonlFiles(sessionsDir, files);
1759
+ const items = [];
1760
+ for (const file of files) {
1761
+ const first = readFirstLine(file);
1762
+ if (!first) continue;
1763
+ const header = parseSessionHeader(first);
1764
+ if (!header) continue;
1765
+ let updatedAt = null;
1766
+ let title = null;
1767
+ try {
1768
+ const tail = readTail(file);
1769
+ title = pickTitleFromTail(tail);
1770
+ updatedAt = pickUpdatedAtFromTail(tail);
1771
+ } catch {
1772
+ }
1773
+ if (!title) {
1774
+ title = scanSessionInfoNameFromFile(file);
1775
+ }
1776
+ if (!updatedAt) {
1777
+ try {
1778
+ updatedAt = statSync2(file).mtime.toISOString();
1779
+ } catch {
1780
+ updatedAt = null;
1781
+ }
1782
+ }
1783
+ if (!title) {
1784
+ title = pickFallbackTitleFromHead(file);
1785
+ }
1786
+ items.push({
1787
+ sessionId: header.sessionId,
1788
+ cwd: header.cwd,
1789
+ title,
1790
+ updatedAt,
1791
+ sessionFile: file
1792
+ });
1793
+ }
1794
+ items.sort((a, b) => {
1795
+ const aa = a.updatedAt ?? "";
1796
+ const bb = b.updatedAt ?? "";
1797
+ return bb.localeCompare(aa);
1798
+ });
1799
+ return items;
1800
+ }
1801
+ function findPiSession(sessionId) {
1802
+ const all = listPiSessions();
1803
+ return all.find((s) => s.sessionId === sessionId) ?? null;
1804
+ }
1805
+
1806
+ // src/acp/translate/pi-messages.ts
1807
+ function normalizePiMessageText(content) {
1808
+ if (typeof content === "string") return content;
1809
+ if (!Array.isArray(content)) return "";
1810
+ return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
1811
+ }
1812
+ function normalizePiAssistantText(content) {
1813
+ if (!Array.isArray(content)) return "";
1814
+ return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
1815
+ }
1816
+
1817
+ // src/acp/translate/prompt.ts
1818
+ function promptToPiMessage(blocks) {
1819
+ let message = "";
1820
+ const images = [];
1821
+ for (const b of blocks) {
1822
+ switch (b.type) {
1823
+ case "text":
1824
+ message += b.text;
1825
+ break;
1826
+ case "resource_link":
1827
+ message += `
1828
+ [Context] ${b.uri}`;
1829
+ break;
1830
+ case "image": {
1831
+ images.push({
1832
+ type: "image",
1833
+ mimeType: b.mimeType,
1834
+ data: b.data
1835
+ });
1836
+ break;
1837
+ }
1838
+ case "resource": {
1839
+ const r = b.resource;
1840
+ const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
1841
+ if (typeof r?.text === "string") {
1842
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
1843
+ message += `
1844
+ [Embedded Context] ${uri} (${mime})
1845
+ ${r.text}`;
1846
+ } else if (typeof r?.blob === "string") {
1847
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
1848
+ const bytes = Buffer.byteLength(r.blob, "base64");
1849
+ message += `
1850
+ [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
1851
+ } else {
1852
+ message += `
1853
+ [Embedded Context] ${uri}`;
1854
+ }
1855
+ break;
1856
+ }
1857
+ case "audio": {
1858
+ const bytes = Buffer.byteLength(b.data, "base64");
1859
+ message += `
1860
+ [Audio] (${b.mimeType}, ${bytes} bytes) not supported by pi-acp`;
1861
+ break;
1862
+ }
1863
+ default:
1864
+ break;
1865
+ }
1866
+ }
1867
+ return { message, images };
1868
+ }
1869
+
1870
+ // src/acp/pi-settings.ts
1871
+ import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
1872
+ import { homedir as homedir4 } from "os";
1873
+ import { join as join5, resolve as resolve3 } from "path";
1874
+ function isObject(x) {
1875
+ return Boolean(x) && typeof x === "object" && !Array.isArray(x);
1876
+ }
1877
+ function deepMerge(a, b) {
1878
+ const out = { ...a };
1879
+ for (const [k, v] of Object.entries(b)) {
1880
+ const av = out[k];
1881
+ if (isObject(av) && isObject(v)) out[k] = deepMerge(av, v);
1882
+ else out[k] = v;
1883
+ }
1884
+ return out;
1885
+ }
1886
+ function readJsonFile(path) {
1887
+ try {
1888
+ if (!existsSync3(path)) return {};
1889
+ const raw = readFileSync5(path, "utf-8");
1890
+ const data = JSON.parse(raw);
1891
+ return isObject(data) ? data : {};
1892
+ } catch {
1893
+ return {};
1894
+ }
1895
+ }
1896
+ function getMergedSettings(cwd) {
1897
+ const globalSettingsPath = join5(getAgentDir(), "settings.json");
1898
+ const projectSettingsPath = resolve3(cwd, ".pi", "settings.json");
1899
+ const global = readJsonFile(globalSettingsPath);
1900
+ const project = readJsonFile(projectSettingsPath);
1901
+ return deepMerge(global, project);
1902
+ }
1903
+ function getAgentDir() {
1904
+ return process.env.PI_CODING_AGENT_DIR ? resolve3(process.env.PI_CODING_AGENT_DIR) : join5(homedir4(), ".pi", "agent");
1905
+ }
1906
+ function getEnableSkillCommands(cwd) {
1907
+ const merged = getMergedSettings(cwd);
1908
+ const direct = merged.enableSkillCommands;
1909
+ if (typeof direct === "boolean") return direct;
1910
+ const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
1911
+ if (typeof nested === "boolean") return nested;
1912
+ return true;
1913
+ }
1914
+ function getQuietStartup(cwd) {
1915
+ const merged = getMergedSettings(cwd);
1916
+ const direct = merged.quietStartup;
1917
+ if (typeof direct === "boolean") return direct;
1918
+ const legacy = merged.quietStart;
1919
+ if (typeof legacy === "boolean") return legacy;
1920
+ return false;
1921
+ }
1922
+
1923
+ // src/acp/pi-commands.ts
1924
+ function describeFallback(c) {
1925
+ const source = typeof c.source === "string" ? c.source : "";
1926
+ const location = typeof c.location === "string" ? c.location : "";
1927
+ const parts = [];
1928
+ if (source) parts.push(source);
1929
+ if (location) parts.push(location);
1930
+ return parts.length ? `(${parts.join(":")})` : "(command)";
1931
+ }
1932
+ function toAvailableCommandsFromPiGetCommands(data, opts) {
1933
+ const enableSkillCommands = opts?.enableSkillCommands ?? true;
1934
+ const includeExtensionCommands = opts?.includeExtensionCommands ?? false;
1935
+ const root = data;
1936
+ const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
1937
+ const out = [];
1938
+ for (const c of commandsRaw) {
1939
+ const name = typeof c?.name === "string" ? c.name.trim() : "";
1940
+ if (!name) continue;
1941
+ const source = typeof c?.source === "string" ? c.source : "";
1942
+ if (!includeExtensionCommands && source === "extension") continue;
1943
+ if (!enableSkillCommands && name.startsWith("skill:")) continue;
1944
+ const desc = typeof c?.description === "string" ? c.description.trim() : "";
1945
+ out.push({
1946
+ name,
1947
+ description: desc || describeFallback(c)
1948
+ });
1949
+ }
1950
+ return { commands: out, raw: commandsRaw };
1951
+ }
1952
+
1953
+ // src/acp/agent.ts
1954
+ import { isAbsolute as isAbsolute4 } from "path";
1955
+ import { existsSync as existsSync4, readFileSync as readFileSync6, realpathSync as realpathSync2, readdirSync as readdirSync3, statSync as statSync3, unlinkSync } from "fs";
1956
+ import { join as join6, dirname as dirname3, basename } from "path";
1957
+ import { spawnSync } from "child_process";
1958
+ import { fileURLToPath as fileURLToPath2 } from "url";
1959
+ var MODEL_CONFIG_ID = "model";
1960
+ var THOUGHT_LEVEL_CONFIG_ID = "thought_level";
1961
+ function builtinAvailableCommands() {
1962
+ return [
1963
+ {
1964
+ name: "compact",
1965
+ description: "Manually compact the session context",
1966
+ input: { hint: "optional custom instructions" }
1967
+ },
1968
+ {
1969
+ name: "autocompact",
1970
+ description: "Toggle automatic context compaction",
1971
+ input: { hint: "on|off|toggle" }
1972
+ },
1973
+ {
1974
+ name: "export",
1975
+ description: "Export session to an HTML file in the session cwd"
1976
+ },
1977
+ {
1978
+ name: "session",
1979
+ description: "Show session stats (messages, tokens, cost, session file)"
1980
+ },
1981
+ {
1982
+ name: "name",
1983
+ description: "Set session display name",
1984
+ input: { hint: "<name>" }
1985
+ },
1986
+ {
1987
+ name: "steering",
1988
+ description: "Get/set pi steering message delivery mode (how queued steering messages are delivered)",
1989
+ input: { hint: "(no args to show) all | one-at-a-time" }
1990
+ },
1991
+ {
1992
+ name: "follow-up",
1993
+ description: "Get/set pi follow-up message delivery mode (how queued follow-up messages are delivered)",
1994
+ input: { hint: "(no args to show) all | one-at-a-time" }
1995
+ },
1996
+ {
1997
+ name: "changelog",
1998
+ description: "Show pi changelog"
1999
+ }
2000
+ ];
2001
+ }
2002
+ function mergeCommands(a, b) {
2003
+ const out = [];
2004
+ const seen = /* @__PURE__ */ new Set();
2005
+ for (const c of [...a, ...b]) {
2006
+ if (seen.has(c.name)) continue;
2007
+ seen.add(c.name);
2008
+ out.push(c);
2009
+ }
2010
+ return out;
2011
+ }
2012
+ var pkg = readNearestPackageJson(import.meta.url);
2013
+ var PiAcpAgent = class {
2014
+ conn;
2015
+ managed = managedPiPaths();
2016
+ store = new SessionStore(this.managed?.map);
2017
+ sessions = new SessionManager(this.store);
2018
+ restoringSessions = /* @__PURE__ */ new Map();
2019
+ dispose() {
2020
+ this.sessions.disposeAll();
2021
+ }
2022
+ // Remember recent session cwd and use it as the default filter.
2023
+ lastSessionCwd = null;
2024
+ constructor(conn, _config) {
2025
+ this.conn = conn;
2026
+ void _config;
2027
+ }
2028
+ cleanupFailedNewSession(sessionId, state) {
2029
+ this.sessions.close(sessionId);
2030
+ const sessionFile = typeof state?.sessionFile === "string" && state.sessionFile.trim() ? state.sessionFile : this.store.get(sessionId)?.sessionFile;
2031
+ if (typeof sessionFile === "string" && sessionFile.trim()) {
2032
+ try {
2033
+ if (existsSync4(sessionFile)) unlinkSync(sessionFile);
2034
+ } catch {
2035
+ }
2036
+ }
2037
+ this.store.delete(sessionId);
2038
+ }
2039
+ managedStoredFile(stored) {
2040
+ if (this.managed && stored?.cwd === this.managed.workspace && typeof stored.sessionFile === "string") {
2041
+ return managedSessionFile(this.managed.sessions, stored.sessionFile);
2042
+ }
2043
+ }
2044
+ findStoredSession(sessionId) {
2045
+ const stored = this.store.get(sessionId);
2046
+ if (this.managed) {
2047
+ const sessionFile = this.managedStoredFile(stored);
2048
+ return sessionFile ? { cwd: this.managed.workspace, sessionFile } : null;
2049
+ }
2050
+ if (stored?.cwd && stored?.sessionFile) {
2051
+ return { cwd: stored.cwd, sessionFile: stored.sessionFile };
2052
+ }
2053
+ const piSession = findPiSession(sessionId);
2054
+ if (!piSession) return null;
2055
+ this.store.upsert({
2056
+ sessionId,
2057
+ cwd: piSession.cwd,
2058
+ sessionFile: piSession.sessionFile
2059
+ });
2060
+ return {
2061
+ cwd: piSession.cwd,
2062
+ sessionFile: piSession.sessionFile
2063
+ };
2064
+ }
2065
+ async restoreSession(sessionId, opts) {
2066
+ const existing = this.sessions.maybeGet(sessionId);
2067
+ if (existing) return existing;
2068
+ const inFlight = this.restoringSessions.get(sessionId);
2069
+ if (inFlight) return inFlight;
2070
+ const restorePromise = (async () => {
2071
+ const stored = this.findStoredSession(sessionId);
2072
+ if (!stored) {
2073
+ throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2074
+ }
2075
+ const requestedCwd = opts?.cwd ?? stored.cwd;
2076
+ const managedChat = managedChatInput(requestedCwd, opts?.mcpServers);
2077
+ const cwd = this.managed?.workspace ?? requestedCwd;
2078
+ let proc;
2079
+ try {
2080
+ proc = await PiRpcProcess.spawn({
2081
+ cwd,
2082
+ sessionPath: stored.sessionFile,
2083
+ managedChat,
2084
+ piCommand: process.env.PI_ACP_PI_COMMAND
2085
+ });
2086
+ } catch (e) {
2087
+ if (e?.name === "PiRpcSpawnError") {
2088
+ throw RequestError4.internalError({ code: e?.code }, String(e?.message ?? e));
2089
+ }
2090
+ throw e;
2091
+ }
2092
+ const fileCommands = managedChat ? [] : loadSlashCommands(cwd);
2093
+ const session = this.sessions.getOrCreate(sessionId, {
2094
+ cwd,
2095
+ mcpServers: managedChat ? [] : opts?.mcpServers ?? [],
2096
+ conn: this.conn,
2097
+ proc,
2098
+ fileCommands
2099
+ });
2100
+ this.lastSessionCwd = cwd;
2101
+ this.store.upsert({ sessionId, cwd, sessionFile: stored.sessionFile });
2102
+ return session;
2103
+ })();
2104
+ this.restoringSessions.set(sessionId, restorePromise);
2105
+ try {
2106
+ return await restorePromise;
2107
+ } finally {
2108
+ this.restoringSessions.delete(sessionId);
2109
+ }
2110
+ }
2111
+ async initialize(params) {
2112
+ const supportedVersion = 1;
2113
+ const requested = params.protocolVersion;
2114
+ return {
2115
+ protocolVersion: requested === supportedVersion ? requested : supportedVersion,
2116
+ agentInfo: {
2117
+ name: pkg.name ?? "pi-acp",
2118
+ title: "pi ACP adapter",
2119
+ version: pkg.version ?? "0.0.0"
2120
+ },
2121
+ // Zed currently uses ClientCapabilities._meta["terminal-auth"] to decide whether to show
2122
+ // the "Authenticate" banner/button. If not supported, we still return the method for the registry.
2123
+ authMethods: this.managed ? [] : getAuthMethods({
2124
+ supportsTerminalAuthMeta: params?.clientCapabilities?._meta?.["terminal-auth"] === true
2125
+ }),
2126
+ agentCapabilities: {
2127
+ loadSession: true,
2128
+ mcpCapabilities: { http: !!this.managed, sse: false },
2129
+ promptCapabilities: {
2130
+ image: true,
2131
+ audio: false,
2132
+ embeddedContext: !this.managed && process.env.PI_ACP_ENABLE_EMBEDDED_CONTEXT === "true"
2133
+ },
2134
+ sessionCapabilities: {
2135
+ // **UNSTABLE** ACP capability used by Zed's codex-acp adapter.
2136
+ // Enables a native session picker in clients that support it.
2137
+ list: {},
2138
+ ...this.managed ? {} : { delete: {} }
2139
+ }
2140
+ }
2141
+ };
2142
+ }
2143
+ async newSession(params) {
2144
+ if (!isAbsolute4(params.cwd)) {
2145
+ throw RequestError4.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2146
+ }
2147
+ const managedChat = managedChatInput(params.cwd, params.mcpServers);
2148
+ const cwd = this.managed?.workspace ?? params.cwd;
2149
+ this.lastSessionCwd = cwd;
2150
+ const fileCommands = managedChat ? [] : loadSlashCommands(params.cwd);
2151
+ const enableSkillCommands = !managedChat && getEnableSkillCommands(params.cwd);
2152
+ const session = await this.sessions.create({
2153
+ cwd,
2154
+ mcpServers: managedChat ? [] : params.mcpServers,
2155
+ managedChat,
2156
+ conn: this.conn,
2157
+ fileCommands,
2158
+ piCommand: process.env.PI_ACP_PI_COMMAND
2159
+ });
2160
+ let state = null;
2161
+ let availableModels = null;
2162
+ let stateErr = null;
2163
+ let availableModelsErr = null;
2164
+ await Promise.all([
2165
+ session.proc.getState().then((s) => {
2166
+ state = s;
2167
+ }).catch((err) => {
2168
+ stateErr = err;
2169
+ state = null;
2170
+ }),
2171
+ session.proc.getAvailableModels().then((m) => {
2172
+ availableModels = m;
2173
+ }).catch((err) => {
2174
+ availableModelsErr = err;
2175
+ availableModels = null;
2176
+ })
2177
+ ]);
2178
+ const availableModelsAuthErr = maybeAuthRequiredError(availableModelsErr);
2179
+ if (availableModelsAuthErr) {
2180
+ this.cleanupFailedNewSession(session.sessionId, state);
2181
+ throw availableModelsAuthErr;
2182
+ }
2183
+ if (availableModelsErr) {
2184
+ this.cleanupFailedNewSession(session.sessionId, state);
2185
+ throw RequestError4.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2186
+ }
2187
+ const rawModelsCount = Array.isArray(availableModels?.models) ? availableModels.models.length : 0;
2188
+ if (rawModelsCount === 0) {
2189
+ this.cleanupFailedNewSession(session.sessionId, state);
2190
+ throw RequestError4.authRequired(
2191
+ { authMethods: getAuthMethods() },
2192
+ "Configure an API key or log in with an OAuth provider."
2193
+ );
2194
+ }
2195
+ if (stateErr && maybeAuthRequiredError(stateErr)) {
2196
+ this.cleanupFailedNewSession(session.sessionId, state);
2197
+ throw RequestError4.authRequired(
2198
+ { authMethods: getAuthMethods() },
2199
+ "Configure an API key or log in with an OAuth provider."
2200
+ );
2201
+ }
2202
+ let configuration;
2203
+ try {
2204
+ if (stateErr) throw stateErr;
2205
+ configuration = await getSessionConfiguration(session.proc, { state, availableModels });
2206
+ } catch (err) {
2207
+ this.cleanupFailedNewSession(session.sessionId, state);
2208
+ throw maybeAuthRequiredError(err) ?? RequestError4.internalError({}, String(err?.message ?? err));
2209
+ }
2210
+ const { configOptions, models, modes } = configuration;
2211
+ const quietStartup = !!managedChat || getQuietStartup(params.cwd);
2212
+ const updateNotice = managedChat ? null : buildUpdateNotice();
2213
+ const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
2214
+ cwd: params.cwd,
2215
+ fileCommands,
2216
+ updateNotice
2217
+ });
2218
+ if (preludeText)
2219
+ session.setStartupInfo(preludeText);
2220
+ this.sessions.closeAllExcept?.(session.sessionId);
2221
+ const response = {
2222
+ sessionId: session.sessionId,
2223
+ configOptions,
2224
+ models,
2225
+ modes,
2226
+ _meta: {
2227
+ piAcp: {
2228
+ startupInfo: preludeText || null
2229
+ }
2230
+ }
2231
+ };
2232
+ if (preludeText) setTimeout(() => session.sendStartupInfoIfPending(), 0);
2233
+ setTimeout(() => {
2234
+ void (async () => {
2235
+ await session.publishContextUsage();
2236
+ if (this.managed) return;
2237
+ try {
2238
+ const pi = await session.proc.getCommands();
2239
+ const { commands } = toAvailableCommandsFromPiGetCommands(pi, {
2240
+ enableSkillCommands,
2241
+ includeExtensionCommands: false
2242
+ });
2243
+ await this.conn.sessionUpdate({
2244
+ sessionId: session.sessionId,
2245
+ update: {
2246
+ sessionUpdate: "available_commands_update",
2247
+ availableCommands: mergeCommands(commands, builtinAvailableCommands())
2248
+ }
2249
+ });
2250
+ return;
2251
+ } catch {
2252
+ }
2253
+ await this.conn.sessionUpdate({
2254
+ sessionId: session.sessionId,
2255
+ update: {
2256
+ sessionUpdate: "available_commands_update",
2257
+ availableCommands: mergeCommands(toAvailableCommands(fileCommands), builtinAvailableCommands())
2258
+ }
2259
+ });
2260
+ })();
2261
+ }, 0);
2262
+ return response;
2263
+ }
2264
+ async authenticate(_params) {
2265
+ return;
2266
+ }
2267
+ async prompt(params) {
2268
+ const session = await this.restoreSession(params.sessionId);
2269
+ const { message, images } = promptToPiMessage(params.prompt);
2270
+ if (!this.managed && images.length === 0 && message.trimStart().startsWith("/")) {
2271
+ const trimmed = message.trim();
2272
+ const space = trimmed.indexOf(" ");
2273
+ const cmd = space === -1 ? trimmed.slice(1) : trimmed.slice(1, space);
2274
+ const argsString = space === -1 ? "" : trimmed.slice(space + 1);
2275
+ const args = parseCommandArgs(argsString);
2276
+ if (cmd === "compact") {
2277
+ const customInstructions = args.join(" ").trim() || void 0;
2278
+ const res = await session.proc.compact(customInstructions);
2279
+ const r = res && typeof res === "object" ? res : null;
2280
+ const tokensBefore = typeof r?.tokensBefore === "number" ? r.tokensBefore : null;
2281
+ const summary = typeof r?.summary === "string" ? r.summary : null;
2282
+ const headerLines = [
2283
+ `Compaction completed.${customInstructions ? " (custom instructions applied)" : ""}`,
2284
+ tokensBefore !== null ? `Tokens before: ${tokensBefore}` : null
2285
+ ].filter(Boolean);
2286
+ const text = headerLines.join("\n") + (summary ? `
2287
+
2288
+ ${summary}` : "");
2289
+ await this.conn.sessionUpdate({
2290
+ sessionId: session.sessionId,
2291
+ update: {
2292
+ sessionUpdate: "agent_message_chunk",
2293
+ content: { type: "text", text }
2294
+ }
2295
+ });
2296
+ return { stopReason: "end_turn" };
2297
+ }
2298
+ if (cmd === "session") {
2299
+ const stats = await session.proc.getSessionStats();
2300
+ const lines = [];
2301
+ if (stats?.sessionId) lines.push(`Session: ${stats.sessionId}`);
2302
+ if (stats?.sessionFile) lines.push(`Session file: ${stats.sessionFile}`);
2303
+ if (typeof stats?.totalMessages === "number") lines.push(`Messages: ${stats.totalMessages}`);
2304
+ if (typeof stats?.cost === "number") lines.push(`Cost: ${stats.cost}`);
2305
+ const t = stats?.tokens;
2306
+ if (t && typeof t === "object") {
2307
+ const parts = [];
2308
+ if (typeof t.input === "number") parts.push(`in ${t.input}`);
2309
+ if (typeof t.output === "number") parts.push(`out ${t.output}`);
2310
+ if (typeof t.cacheRead === "number") parts.push(`cache read ${t.cacheRead}`);
2311
+ if (typeof t.cacheWrite === "number") parts.push(`cache write ${t.cacheWrite}`);
2312
+ if (typeof t.total === "number") parts.push(`total ${t.total}`);
2313
+ if (parts.length) lines.push(`Tokens: ${parts.join(", ")}`);
2314
+ }
2315
+ const text = lines.length ? lines.join("\n") : `Session stats:
2316
+ ${JSON.stringify(stats, null, 2)}`;
2317
+ await this.conn.sessionUpdate({
2318
+ sessionId: session.sessionId,
2319
+ update: {
2320
+ sessionUpdate: "agent_message_chunk",
2321
+ content: { type: "text", text }
2322
+ }
2323
+ });
2324
+ return { stopReason: "end_turn" };
2325
+ }
2326
+ if (cmd === "name") {
2327
+ const name = args.join(" ").trim();
2328
+ if (!name) {
2329
+ await this.conn.sessionUpdate({
2330
+ sessionId: session.sessionId,
2331
+ update: {
2332
+ sessionUpdate: "agent_message_chunk",
2333
+ content: { type: "text", text: "Usage: /name <name>" }
2334
+ }
2335
+ });
2336
+ return { stopReason: "end_turn" };
2337
+ }
2338
+ try {
2339
+ await session.proc.setSessionName(name);
2340
+ } catch (e) {
2341
+ const msg = String(e?.message ?? e);
2342
+ const hint = /set_session_name/i.test(msg) ? " This requires a newer pi version that supports `set_session_name` in RPC mode." : "";
2343
+ await this.conn.sessionUpdate({
2344
+ sessionId: session.sessionId,
2345
+ update: {
2346
+ sessionUpdate: "agent_message_chunk",
2347
+ content: { type: "text", text: `Failed to set session name: ${msg}${hint}` }
2348
+ }
2349
+ });
2350
+ return { stopReason: "end_turn" };
2351
+ }
2352
+ await this.conn.sessionUpdate({
2353
+ sessionId: session.sessionId,
2354
+ update: {
2355
+ sessionUpdate: "session_info_update",
2356
+ title: name,
2357
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2358
+ }
2359
+ });
2360
+ await this.conn.sessionUpdate({
2361
+ sessionId: session.sessionId,
2362
+ update: {
2363
+ sessionUpdate: "agent_message_chunk",
2364
+ content: { type: "text", text: `Session name set: ${name}` }
2365
+ }
2366
+ });
2367
+ return { stopReason: "end_turn" };
2368
+ }
2369
+ if (cmd === "steering") {
2370
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2371
+ const state = await session.proc.getState();
2372
+ const current = String(state?.steeringMode ?? "");
2373
+ if (!modeRaw) {
2374
+ await this.conn.sessionUpdate({
2375
+ sessionId: session.sessionId,
2376
+ update: {
2377
+ sessionUpdate: "agent_message_chunk",
2378
+ content: {
2379
+ type: "text",
2380
+ text: `Steering mode: ${current || "unknown"}`
2381
+ }
2382
+ }
2383
+ });
2384
+ return { stopReason: "end_turn" };
2385
+ }
2386
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2387
+ await this.conn.sessionUpdate({
2388
+ sessionId: session.sessionId,
2389
+ update: {
2390
+ sessionUpdate: "agent_message_chunk",
2391
+ content: {
2392
+ type: "text",
2393
+ text: "Usage: /steering all | /steering one-at-a-time"
2394
+ }
2395
+ }
2396
+ });
2397
+ return { stopReason: "end_turn" };
2398
+ }
2399
+ await session.proc.setSteeringMode(modeRaw);
2400
+ await this.conn.sessionUpdate({
2401
+ sessionId: session.sessionId,
2402
+ update: {
2403
+ sessionUpdate: "agent_message_chunk",
2404
+ content: { type: "text", text: `Steering mode set to: ${modeRaw}` }
2405
+ }
2406
+ });
2407
+ return { stopReason: "end_turn" };
2408
+ }
2409
+ if (cmd === "follow-up") {
2410
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2411
+ const state = await session.proc.getState();
2412
+ const current = String(state?.followUpMode ?? "");
2413
+ if (!modeRaw) {
2414
+ await this.conn.sessionUpdate({
2415
+ sessionId: session.sessionId,
2416
+ update: {
2417
+ sessionUpdate: "agent_message_chunk",
2418
+ content: {
2419
+ type: "text",
2420
+ text: `Follow-up mode: ${current || "unknown"}`
2421
+ }
2422
+ }
2423
+ });
2424
+ return { stopReason: "end_turn" };
2425
+ }
2426
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2427
+ await this.conn.sessionUpdate({
2428
+ sessionId: session.sessionId,
2429
+ update: {
2430
+ sessionUpdate: "agent_message_chunk",
2431
+ content: {
2432
+ type: "text",
2433
+ text: "Usage: /follow-up all | /follow-up one-at-a-time"
2434
+ }
2435
+ }
2436
+ });
2437
+ return { stopReason: "end_turn" };
2438
+ }
2439
+ await session.proc.setFollowUpMode(modeRaw);
2440
+ await this.conn.sessionUpdate({
2441
+ sessionId: session.sessionId,
2442
+ update: {
2443
+ sessionUpdate: "agent_message_chunk",
2444
+ content: { type: "text", text: `Follow-up mode set to: ${modeRaw}` }
2445
+ }
2446
+ });
2447
+ return { stopReason: "end_turn" };
2448
+ }
2449
+ if (cmd === "changelog") {
2450
+ const findChangelog = () => {
2451
+ try {
2452
+ const whichCmd = process.platform === "win32" ? "where" : "which";
2453
+ const which = spawnSync(whichCmd, ["pi"], { encoding: "utf-8" });
2454
+ const piPath = String(which.stdout ?? "").split(/\r?\n/)[0]?.trim();
2455
+ if (piPath) {
2456
+ const resolved = realpathSync2(piPath);
2457
+ const pkgRoot = dirname3(dirname3(resolved));
2458
+ const p = join6(pkgRoot, "CHANGELOG.md");
2459
+ if (existsSync4(p)) return p;
2460
+ }
2461
+ } catch {
2462
+ }
2463
+ try {
2464
+ const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
2465
+ const root = String(npmRoot.stdout ?? "").trim();
2466
+ if (root) {
2467
+ const p = join6(root, "@earendil-works", "pi-coding-agent", "CHANGELOG.md");
2468
+ if (existsSync4(p)) return p;
2469
+ }
2470
+ } catch {
2471
+ }
2472
+ return null;
2473
+ };
2474
+ const changelogPath = findChangelog();
2475
+ if (!changelogPath) {
2476
+ await this.conn.sessionUpdate({
2477
+ sessionId: session.sessionId,
2478
+ update: {
2479
+ sessionUpdate: "agent_message_chunk",
2480
+ content: { type: "text", text: "Changelog not found (couldn't locate pi installation)." }
2481
+ }
2482
+ });
2483
+ return { stopReason: "end_turn" };
2484
+ }
2485
+ let text = "";
2486
+ try {
2487
+ text = readFileSync6(changelogPath, "utf-8");
2488
+ } catch (e) {
2489
+ await this.conn.sessionUpdate({
2490
+ sessionId: session.sessionId,
2491
+ update: {
2492
+ sessionUpdate: "agent_message_chunk",
2493
+ content: { type: "text", text: `Failed to read changelog: ${String(e?.message ?? e)}` }
2494
+ }
2495
+ });
2496
+ return { stopReason: "end_turn" };
2497
+ }
2498
+ const maxChars = 2e4;
2499
+ if (text.length > maxChars) text = text.slice(0, maxChars) + "\n\n...(truncated)...";
2500
+ await this.conn.sessionUpdate({
2501
+ sessionId: session.sessionId,
2502
+ update: {
2503
+ sessionUpdate: "agent_message_chunk",
2504
+ content: { type: "text", text }
2505
+ }
2506
+ });
2507
+ return { stopReason: "end_turn" };
2508
+ }
2509
+ if (cmd === "export") {
2510
+ const state = await session.proc.getState();
2511
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
2512
+ const messageCount = typeof state?.messageCount === "number" ? state.messageCount : 0;
2513
+ if (!sessionFile || messageCount === 0 || !existsSync4(sessionFile)) {
2514
+ await this.conn.sessionUpdate({
2515
+ sessionId: session.sessionId,
2516
+ update: {
2517
+ sessionUpdate: "agent_message_chunk",
2518
+ content: {
2519
+ type: "text",
2520
+ text: "Nothing to export yet (no session messages). Send a prompt first."
2521
+ }
2522
+ }
2523
+ });
2524
+ return { stopReason: "end_turn" };
2525
+ }
2526
+ try {
2527
+ const raw = readFileSync6(sessionFile, "utf-8");
2528
+ if (raw.trim().length === 0) {
2529
+ await this.conn.sessionUpdate({
2530
+ sessionId: session.sessionId,
2531
+ update: {
2532
+ sessionUpdate: "agent_message_chunk",
2533
+ content: {
2534
+ type: "text",
2535
+ text: "Nothing to export yet (empty session file). Send a prompt first."
2536
+ }
2537
+ }
2538
+ });
2539
+ return { stopReason: "end_turn" };
2540
+ }
2541
+ } catch {
2542
+ await this.conn.sessionUpdate({
2543
+ sessionId: session.sessionId,
2544
+ update: {
2545
+ sessionUpdate: "agent_message_chunk",
2546
+ content: {
2547
+ type: "text",
2548
+ text: "Couldn't read session file for export. Try sending a prompt first."
2549
+ }
2550
+ }
2551
+ });
2552
+ return { stopReason: "end_turn" };
2553
+ }
2554
+ const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
2555
+ const outputPath = join6(session.cwd, `pi-session-${safeSessionId}.html`);
2556
+ let resultPath = "";
2557
+ try {
2558
+ const result2 = await session.proc.exportHtml(outputPath);
2559
+ resultPath = result2.path;
2560
+ } catch (e) {
2561
+ await this.conn.sessionUpdate({
2562
+ sessionId: session.sessionId,
2563
+ update: {
2564
+ sessionUpdate: "agent_message_chunk",
2565
+ content: {
2566
+ type: "text",
2567
+ text: `Export failed: ${String(e?.message ?? e)}`
2568
+ }
2569
+ }
2570
+ });
2571
+ return { stopReason: "end_turn" };
2572
+ }
2573
+ if (!resultPath) {
2574
+ await this.conn.sessionUpdate({
2575
+ sessionId: session.sessionId,
2576
+ update: {
2577
+ sessionUpdate: "agent_message_chunk",
2578
+ content: {
2579
+ type: "text",
2580
+ text: "Export failed: no output path returned by pi."
2581
+ }
2582
+ }
2583
+ });
2584
+ return { stopReason: "end_turn" };
2585
+ }
2586
+ const uri = `file://${resultPath}`;
2587
+ await this.conn.sessionUpdate({
2588
+ sessionId: session.sessionId,
2589
+ update: {
2590
+ sessionUpdate: "agent_message_chunk",
2591
+ content: {
2592
+ type: "text",
2593
+ text: "Session exported: "
2594
+ }
2595
+ }
2596
+ });
2597
+ await this.conn.sessionUpdate({
2598
+ sessionId: session.sessionId,
2599
+ update: {
2600
+ sessionUpdate: "agent_message_chunk",
2601
+ content: {
2602
+ type: "resource_link",
2603
+ name: `pi-session-${safeSessionId}.html`,
2604
+ uri,
2605
+ mimeType: "text/html",
2606
+ title: "Session exported"
2607
+ }
2608
+ }
2609
+ });
2610
+ return { stopReason: "end_turn" };
2611
+ }
2612
+ if (cmd === "autocompact") {
2613
+ const mode = (args[0] ?? "toggle").toLowerCase();
2614
+ let enabled = null;
2615
+ if (mode === "on" || mode === "true" || mode === "enable" || mode === "enabled") enabled = true;
2616
+ else if (mode === "off" || mode === "false" || mode === "disable" || mode === "disabled") enabled = false;
2617
+ if (enabled === null) {
2618
+ const state = await session.proc.getState();
2619
+ const current = Boolean(state?.autoCompactionEnabled);
2620
+ enabled = !current;
2621
+ }
2622
+ await session.proc.setAutoCompaction(enabled);
2623
+ await this.conn.sessionUpdate({
2624
+ sessionId: session.sessionId,
2625
+ update: {
2626
+ sessionUpdate: "agent_message_chunk",
2627
+ content: {
2628
+ type: "text",
2629
+ text: `Auto-compaction ${enabled ? "enabled" : "disabled"}.`
2630
+ }
2631
+ }
2632
+ });
2633
+ return { stopReason: "end_turn" };
2634
+ }
2635
+ }
2636
+ const result = await session.prompt(message, images);
2637
+ const stopReason = result === "error" ? session.wasCancelRequested() ? "cancelled" : "end_turn" : result;
2638
+ return { stopReason };
2639
+ }
2640
+ async cancel(params) {
2641
+ const session = this.sessions.maybeGet(params.sessionId);
2642
+ if (!session) return;
2643
+ await session.cancel();
2644
+ }
2645
+ async listSessions(params) {
2646
+ if (this.managed) {
2647
+ const workspace = this.managed.workspace;
2648
+ const explicitCwd = params.cwd;
2649
+ if (explicitCwd && !managedCwdMatches(explicitCwd, workspace)) return { sessions: [] };
2650
+ return { sessions: this.store.list().flatMap((s) => this.managedStoredFile(s) ? [{ sessionId: s.sessionId, cwd: workspace, updatedAt: s.updatedAt }] : []) };
2651
+ }
2652
+ const all = listPiSessions();
2653
+ const effectiveCwd = params.cwd ?? this.lastSessionCwd;
2654
+ const filtered = effectiveCwd ? all.filter((s) => s.cwd === effectiveCwd) : all;
2655
+ const offset = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
2656
+ const start = Number.isFinite(offset) && offset > 0 ? offset : 0;
2657
+ const PAGE_SIZE = 50;
2658
+ const page = filtered.slice(start, start + PAGE_SIZE);
2659
+ const sessions = page.map((s) => ({
2660
+ sessionId: s.sessionId,
2661
+ cwd: s.cwd,
2662
+ title: s.title,
2663
+ updatedAt: s.updatedAt
2664
+ }));
2665
+ const nextCursor = start + PAGE_SIZE < filtered.length ? String(start + PAGE_SIZE) : null;
2666
+ return { sessions, nextCursor, _meta: {} };
2667
+ }
2668
+ async loadSession(params) {
2669
+ if (!isAbsolute4(params.cwd)) {
2670
+ throw RequestError4.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2671
+ }
2672
+ if (this.managed) managedChatInput(params.cwd, params.mcpServers);
2673
+ this.sessions.close(params.sessionId);
2674
+ this.lastSessionCwd = params.cwd;
2675
+ const stored = this.findStoredSession(params.sessionId);
2676
+ if (!stored) {
2677
+ throw RequestError4.invalidParams(`Unknown sessionId: ${params.sessionId}`);
2678
+ }
2679
+ const managed = !!this.managed;
2680
+ const enableSkillCommands = !managed && getEnableSkillCommands(params.cwd);
2681
+ const session = await this.restoreSession(params.sessionId, {
2682
+ cwd: params.cwd,
2683
+ mcpServers: params.mcpServers
2684
+ });
2685
+ const proc = session.proc;
2686
+ let configuration;
2687
+ try {
2688
+ configuration = await getSessionConfiguration(proc);
2689
+ } catch (err) {
2690
+ this.sessions.close(session.sessionId);
2691
+ throw err;
2692
+ }
2693
+ const { configOptions, models, modes } = configuration;
2694
+ const fileCommands = managed ? [] : loadSlashCommands(params.cwd);
2695
+ this.sessions.closeAllExcept?.(session.sessionId);
2696
+ this.store.upsert({
2697
+ sessionId: params.sessionId,
2698
+ cwd: this.managed?.workspace ?? params.cwd,
2699
+ sessionFile: stored.sessionFile
2700
+ });
2701
+ const data = await proc.getMessages();
2702
+ const messages = Array.isArray(data?.messages) ? data.messages : [];
2703
+ for (const m of messages) {
2704
+ const role = String(m?.role ?? "");
2705
+ if (role === "user") {
2706
+ const text = normalizePiMessageText(m?.content);
2707
+ if (text) {
2708
+ await this.conn.sessionUpdate({
2709
+ sessionId: session.sessionId,
2710
+ update: {
2711
+ sessionUpdate: "user_message_chunk",
2712
+ content: { type: "text", text }
2713
+ }
2714
+ });
2715
+ }
2716
+ }
2717
+ if (role === "assistant") {
2718
+ const text = normalizePiAssistantText(m?.content);
2719
+ if (text) {
2720
+ await this.conn.sessionUpdate({
2721
+ sessionId: session.sessionId,
2722
+ update: {
2723
+ sessionUpdate: "agent_message_chunk",
2724
+ content: { type: "text", text }
2725
+ }
2726
+ });
2727
+ }
2728
+ }
2729
+ if (role === "toolResult") {
2730
+ const toolName = String(m?.toolName ?? "tool");
2731
+ const toolCallId = String(m?.toolCallId ?? crypto.randomUUID());
2732
+ const isError = Boolean(m?.isError);
2733
+ const isBash = isBashTool(toolName);
2734
+ if (isBash) {
2735
+ const text2 = bashResultText(m);
2736
+ await this.conn.sessionUpdate({
2737
+ sessionId: session.sessionId,
2738
+ update: {
2739
+ sessionUpdate: "tool_call",
2740
+ toolCallId,
2741
+ title: bashCommand(m) ?? toolName,
2742
+ kind: "execute",
2743
+ status: "completed",
2744
+ content: bashTerminalContent(toolCallId),
2745
+ _meta: bashTerminalInfoMeta(toolCallId, params.cwd)
2746
+ }
2747
+ });
2748
+ await this.conn.sessionUpdate({
2749
+ sessionId: session.sessionId,
2750
+ update: {
2751
+ sessionUpdate: "tool_call_update",
2752
+ toolCallId,
2753
+ status: isError ? "failed" : "completed",
2754
+ _meta: {
2755
+ ...text2 ? bashTerminalOutputMeta(toolCallId, text2) : {},
2756
+ ...bashTerminalExitMeta(toolCallId, bashExitCode(m, isError))
2757
+ }
2758
+ }
2759
+ });
2760
+ continue;
2761
+ }
2762
+ await this.conn.sessionUpdate({
2763
+ sessionId: session.sessionId,
2764
+ update: {
2765
+ sessionUpdate: "tool_call",
2766
+ toolCallId,
2767
+ title: toolName,
2768
+ kind: toolName === "read" ? "read" : toolName === "write" || toolName === "edit" ? "edit" : "other",
2769
+ status: "completed",
2770
+ rawInput: null,
2771
+ rawOutput: m
2772
+ }
2773
+ });
2774
+ const text = toolResultToText(m);
2775
+ await this.conn.sessionUpdate({
2776
+ sessionId: session.sessionId,
2777
+ update: {
2778
+ sessionUpdate: "tool_call_update",
2779
+ toolCallId,
2780
+ status: isError ? "failed" : "completed",
2781
+ content: text ? [{ type: "content", content: { type: "text", text } }] : null,
2782
+ rawOutput: m
2783
+ }
2784
+ });
2785
+ }
2786
+ }
2787
+ const response = {
2788
+ configOptions,
2789
+ models,
2790
+ modes,
2791
+ _meta: {
2792
+ piAcp: {
2793
+ startupInfo: null
2794
+ }
2795
+ }
2796
+ };
2797
+ setTimeout(() => {
2798
+ void (async () => {
2799
+ await session.publishContextUsage();
2800
+ if (this.managed) return;
2801
+ try {
2802
+ const pi = await proc.getCommands();
2803
+ const { commands } = toAvailableCommandsFromPiGetCommands(pi, {
2804
+ enableSkillCommands,
2805
+ includeExtensionCommands: false
2806
+ });
2807
+ await this.conn.sessionUpdate({
2808
+ sessionId: session.sessionId,
2809
+ update: {
2810
+ sessionUpdate: "available_commands_update",
2811
+ availableCommands: mergeCommands(commands, builtinAvailableCommands())
2812
+ }
2813
+ });
2814
+ return;
2815
+ } catch {
2816
+ }
2817
+ await this.conn.sessionUpdate({
2818
+ sessionId: session.sessionId,
2819
+ update: {
2820
+ sessionUpdate: "available_commands_update",
2821
+ availableCommands: mergeCommands(toAvailableCommands(fileCommands), builtinAvailableCommands())
2822
+ }
2823
+ });
2824
+ })();
2825
+ }, 0);
2826
+ return response;
2827
+ }
2828
+ async deleteSession(params) {
2829
+ if (this.managed) throw RequestError4.methodNotFound("session/delete");
2830
+ const stored = this.store.get(params.sessionId);
2831
+ const piSession = findPiSession(params.sessionId);
2832
+ if (!stored && !piSession) {
2833
+ return {};
2834
+ }
2835
+ const sessionFile = stored?.sessionFile ?? piSession?.sessionFile;
2836
+ if (sessionFile) {
2837
+ try {
2838
+ if (existsSync4(sessionFile)) unlinkSync(sessionFile);
2839
+ } catch {
2840
+ }
2841
+ }
2842
+ this.store.delete(params.sessionId);
2843
+ return {};
2844
+ }
2845
+ async unstable_setSessionModel(params) {
2846
+ const session = await this.restoreSession(params.sessionId);
2847
+ await setSessionModel(session.proc, params.modelId);
2848
+ await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
2849
+ await session.publishContextUsage();
2850
+ }
2851
+ async setSessionMode(params) {
2852
+ const session = await this.restoreSession(params.sessionId);
2853
+ const mode = params.modeId;
2854
+ if (typeof mode !== "string" || mode.length === 0) {
2855
+ throw RequestError4.invalidParams("Expected nonempty string modeId");
2856
+ }
2857
+ await session.proc.setThinkingLevel(mode);
2858
+ await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
2859
+ return {};
2860
+ }
2861
+ async setSessionConfigOption(params) {
2862
+ const session = await this.restoreSession(params.sessionId);
2863
+ const configId = String(params.configId);
2864
+ let modelChanged = false;
2865
+ if (typeof params.value !== "string") {
2866
+ throw RequestError4.invalidParams(`Expected string value for config option: ${configId}`);
2867
+ }
2868
+ if (configId === MODEL_CONFIG_ID) {
2869
+ await setSessionModel(session.proc, params.value);
2870
+ modelChanged = true;
2871
+ } else if (configId === THOUGHT_LEVEL_CONFIG_ID) {
2872
+ if (params.value.length === 0) {
2873
+ throw RequestError4.invalidParams("Expected nonempty thinking level");
2874
+ }
2875
+ await session.proc.setThinkingLevel(params.value);
2876
+ } else {
2877
+ throw RequestError4.invalidParams(`Unknown config option: ${configId}`);
2878
+ }
2879
+ const configOptions = await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
2880
+ if (modelChanged) await session.publishContextUsage();
2881
+ return { configOptions };
2882
+ }
2883
+ };
2884
+ async function getThinkingState(proc, pre) {
2885
+ const state = pre?.state ?? await proc.getState();
2886
+ const available = await proc.getAvailableThinkingLevels();
2887
+ const current = state && typeof state === "object" && "thinkingLevel" in state ? state.thinkingLevel : void 0;
2888
+ if (typeof current !== "string" || current.length === 0 || !available.includes(current)) {
2889
+ throw new Error("pi returned a thinking level absent from available levels");
2890
+ }
2891
+ return {
2892
+ currentModeId: current,
2893
+ availableModes: available.map((id) => ({
2894
+ id,
2895
+ name: `Thinking: ${id}`,
2896
+ description: null
2897
+ }))
2898
+ };
2899
+ }
2900
+ async function getSessionConfiguration(proc, pre) {
2901
+ const state = pre?.state ?? await proc.getState();
2902
+ const [models, modes] = await Promise.all([getModelState(proc, { ...pre, state }), getThinkingState(proc, { state })]);
2903
+ return {
2904
+ configOptions: buildConfigOptions({ models, modes }),
2905
+ models,
2906
+ modes
2907
+ };
2908
+ }
2909
+ function buildConfigOptions(state) {
2910
+ const configOptions = [
2911
+ {
2912
+ type: "select",
2913
+ id: THOUGHT_LEVEL_CONFIG_ID,
2914
+ category: "thought_level",
2915
+ name: "Thinking",
2916
+ description: "Set the reasoning effort for this session",
2917
+ currentValue: state.modes.currentModeId,
2918
+ options: state.modes.availableModes.map((mode) => ({
2919
+ value: mode.id,
2920
+ name: mode.name,
2921
+ description: mode.description ?? null
2922
+ }))
2923
+ }
2924
+ ];
2925
+ if (state.models?.availableModels.length) {
2926
+ configOptions.unshift({
2927
+ type: "select",
2928
+ id: MODEL_CONFIG_ID,
2929
+ category: "model",
2930
+ name: "Model",
2931
+ description: "Select the model for this session",
2932
+ currentValue: state.models.currentModelId,
2933
+ options: state.models.availableModels.map((model) => ({
2934
+ value: model.modelId,
2935
+ name: model.name,
2936
+ description: model.description ?? null
2937
+ }))
2938
+ });
2939
+ }
2940
+ return configOptions;
2941
+ }
2942
+ async function getModelState(proc, pre) {
2943
+ let availableModels = [];
2944
+ const data = pre?.availableModels ?? await (async () => {
2945
+ try {
2946
+ return await proc.getAvailableModels();
2947
+ } catch {
2948
+ return null;
2949
+ }
2950
+ })();
2951
+ const models = Array.isArray(data?.models) ? data.models : [];
2952
+ availableModels = models.map((m) => {
2953
+ const provider = String(m?.provider ?? "").trim();
2954
+ const id = String(m?.id ?? "").trim();
2955
+ if (!provider || !id) return null;
2956
+ const name = String(m?.name ?? id);
2957
+ return {
2958
+ modelId: `${provider}/${id}`,
2959
+ name: `${provider}/${name}`,
2960
+ description: null
2961
+ };
2962
+ }).filter(Boolean);
2963
+ let currentModelId = null;
2964
+ const state = pre?.state ?? await (async () => {
2965
+ try {
2966
+ return await proc.getState();
2967
+ } catch {
2968
+ return null;
2969
+ }
2970
+ })();
2971
+ const model = state?.model;
2972
+ if (model && typeof model === "object") {
2973
+ const provider = String(model.provider ?? "").trim();
2974
+ const id = String(model.id ?? "").trim();
2975
+ if (provider && id) currentModelId = `${provider}/${id}`;
2976
+ }
2977
+ if (!availableModels.length && !currentModelId) return null;
2978
+ if (!currentModelId) currentModelId = availableModels[0]?.modelId ?? "default";
2979
+ return {
2980
+ availableModels,
2981
+ currentModelId: currentModelId ?? availableModels[0]?.modelId ?? "default"
2982
+ };
2983
+ }
2984
+ async function emitConfigOptionsUpdate(conn, sessionId, proc) {
2985
+ const { configOptions, modes } = await getSessionConfiguration(proc);
2986
+ await conn.sessionUpdate({
2987
+ sessionId,
2988
+ update: { sessionUpdate: "current_mode_update", currentModeId: modes.currentModeId }
2989
+ });
2990
+ await conn.sessionUpdate({
2991
+ sessionId,
2992
+ update: {
2993
+ sessionUpdate: "config_option_update",
2994
+ configOptions
2995
+ }
2996
+ });
2997
+ return configOptions;
2998
+ }
2999
+ async function setSessionModel(proc, requestedModelId) {
3000
+ let provider = null;
3001
+ let modelId = null;
3002
+ if (requestedModelId.includes("/")) {
3003
+ const [candidateProvider, ...rest] = requestedModelId.split("/");
3004
+ provider = candidateProvider;
3005
+ modelId = rest.join("/");
3006
+ } else {
3007
+ modelId = requestedModelId;
3008
+ }
3009
+ if (!provider) {
3010
+ const data = await proc.getAvailableModels();
3011
+ const models = Array.isArray(data?.models) ? data.models : [];
3012
+ const found = models.find((m) => String(m?.id) === modelId);
3013
+ if (found) {
3014
+ provider = String(found.provider);
3015
+ modelId = String(found.id);
3016
+ }
3017
+ }
3018
+ if (!provider || !modelId) {
3019
+ throw RequestError4.invalidParams(`Unknown modelId: ${requestedModelId}`);
3020
+ }
3021
+ await proc.setModel(provider, modelId);
3022
+ }
3023
+ function isSemver(v) {
3024
+ return /^\d+\.\d+\.\d+(?:[-+].+)?$/.test(v);
3025
+ }
3026
+ function compareSemver(a, b) {
3027
+ const pa = a.split(/[.-]/).slice(0, 3).map((n) => Number(n));
3028
+ const pb = b.split(/[.-]/).slice(0, 3).map((n) => Number(n));
3029
+ for (let i = 0; i < 3; i++) {
3030
+ const da = pa[i] ?? 0;
3031
+ const db = pb[i] ?? 0;
3032
+ if (da > db) return 1;
3033
+ if (da < db) return -1;
3034
+ }
3035
+ return 0;
3036
+ }
3037
+ function buildUpdateNotice() {
3038
+ try {
3039
+ const piVersion = spawnSync("pi", ["--version"], { encoding: "utf-8" });
3040
+ const installed = (String(piVersion.stdout ?? "").trim() || String(piVersion.stderr ?? "").trim()).replace(
3041
+ /^v/i,
3042
+ ""
3043
+ );
3044
+ if (!installed || !isSemver(installed)) return null;
3045
+ const latestRes = spawnSync("npm", ["view", "@earendil-works/pi-coding-agent", "version"], {
3046
+ encoding: "utf-8",
3047
+ timeout: 800
3048
+ });
3049
+ const latest = String(latestRes.stdout ?? "").trim().replace(/^v/i, "");
3050
+ if (!latest || !isSemver(latest)) return null;
3051
+ if (compareSemver(latest, installed) <= 0) return null;
3052
+ return `New version available: v${latest} (installed v${installed}). Run: \`npm i -g @earendil-works/pi-coding-agent\``;
3053
+ } catch {
3054
+ return null;
3055
+ }
3056
+ }
3057
+ function buildStartupInfo(opts) {
3058
+ void opts.fileCommands;
3059
+ const md = [];
3060
+ try {
3061
+ const piVersion = spawnSync("pi", ["--version"], { encoding: "utf-8" });
3062
+ const installed = (String(piVersion.stdout ?? "").trim() || String(piVersion.stderr ?? "").trim()).replace(
3063
+ /^v/i,
3064
+ ""
3065
+ );
3066
+ if (installed) {
3067
+ md.push(`pi v${installed}`);
3068
+ md.push("---");
3069
+ md.push("");
3070
+ }
3071
+ } catch {
3072
+ }
3073
+ const addSection = (title, items) => {
3074
+ const cleaned = items.map((s) => s.trim()).filter(Boolean);
3075
+ if (!cleaned.length) return;
3076
+ md.push(`## ${title}`);
3077
+ for (const item of cleaned) md.push(`- ${item}`);
3078
+ md.push("");
3079
+ };
3080
+ const contextItems = [];
3081
+ const contextPath = join6(opts.cwd, "AGENTS.md");
3082
+ if (existsSync4(contextPath)) contextItems.push(contextPath);
3083
+ addSection("Context", contextItems);
3084
+ const skillsItems = [];
3085
+ const pushSkillFromRoot = (root) => {
3086
+ try {
3087
+ for (const e of readdirSync3(root)) {
3088
+ const p = join6(root, e);
3089
+ try {
3090
+ const st = statSync3(p);
3091
+ if (st.isFile() && e.toLowerCase().endsWith(".md")) {
3092
+ skillsItems.push(p);
3093
+ }
3094
+ } catch {
3095
+ }
3096
+ }
3097
+ const stack = [root];
3098
+ while (stack.length) {
3099
+ const dir = stack.pop();
3100
+ let entries = [];
3101
+ try {
3102
+ entries = readdirSync3(dir);
3103
+ } catch {
3104
+ continue;
3105
+ }
3106
+ for (const name of entries) {
3107
+ if (name === "node_modules" || name === ".git") continue;
3108
+ const p = join6(dir, name);
3109
+ let st;
3110
+ try {
3111
+ st = statSync3(p);
3112
+ } catch {
3113
+ continue;
3114
+ }
3115
+ if (st.isDirectory()) {
3116
+ stack.push(p);
3117
+ } else if (st.isFile() && name === "SKILL.md") {
3118
+ skillsItems.push(p);
3119
+ }
3120
+ }
3121
+ }
3122
+ } catch {
3123
+ }
3124
+ };
3125
+ const globalSkillsDir = join6(getAgentDir(), "skills");
3126
+ pushSkillFromRoot(globalSkillsDir);
3127
+ const legacyAgentsSkillsDir = join6(process.env.HOME ?? "", ".agents", "skills");
3128
+ pushSkillFromRoot(legacyAgentsSkillsDir);
3129
+ const projectSkillsDir = join6(opts.cwd, ".pi", "skills");
3130
+ pushSkillFromRoot(projectSkillsDir);
3131
+ addSection("Skills", skillsItems);
3132
+ const promptsItems = [];
3133
+ const promptsDir = join6(process.env.HOME ?? "", ".pi", "agent", "prompts");
3134
+ try {
3135
+ const prompts = readdirSync3(promptsDir).filter((f) => f.endsWith(".md"));
3136
+ for (const f of prompts) promptsItems.push(`/${basename(f, ".md")}`);
3137
+ } catch {
3138
+ }
3139
+ addSection("Prompts", promptsItems);
3140
+ const extItems = [];
3141
+ const extDir = join6(process.env.HOME ?? "", ".pi", "agent", "extensions");
3142
+ try {
3143
+ const exts = readdirSync3(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3144
+ for (const f of exts) extItems.push(join6(extDir, f));
3145
+ } catch {
3146
+ }
3147
+ const settingsPaths = [join6(getAgentDir(), "settings.json"), join6(opts.cwd, ".pi", "settings.json")];
3148
+ for (const settingsPath of settingsPaths) {
3149
+ try {
3150
+ const settings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
3151
+ const pkgs = Array.isArray(settings?.packages) ? settings.packages : [];
3152
+ for (const pkg2 of pkgs) {
3153
+ const s = String(pkg2);
3154
+ if (s.startsWith("npm:")) {
3155
+ extItems.push(`${s}
3156
+ - index.ts`);
3157
+ } else {
3158
+ extItems.push(s);
3159
+ }
3160
+ }
3161
+ } catch {
3162
+ }
3163
+ }
3164
+ addSection("Extensions", extItems);
3165
+ if (opts.updateNotice) {
3166
+ md.push("---");
3167
+ md.push(opts.updateNotice);
3168
+ md.push("");
3169
+ }
3170
+ return md.join("\n").trim() + "\n";
3171
+ }
3172
+ function readNearestPackageJson(metaUrl) {
3173
+ try {
3174
+ let dir = dirname3(fileURLToPath2(metaUrl));
3175
+ for (let i = 0; i < 6; i++) {
3176
+ const p = join6(dir, "package.json");
3177
+ if (existsSync4(p)) {
3178
+ const json = JSON.parse(readFileSync6(p, "utf-8"));
3179
+ return { name: json?.name, version: json?.version };
3180
+ }
3181
+ dir = dirname3(dir);
3182
+ }
3183
+ } catch {
3184
+ }
3185
+ return { name: "pi-acp", version: "0.0.0" };
3186
+ }
3187
+
3188
+ // src/index.ts
3189
+ if (!process.versions.bun || !managedPiPaths() || process.argv.length !== 2) {
3190
+ process.stderr.write("Managed Pi ACP requires Bun and managed state\n");
3191
+ process.exit(1);
3192
+ }
3193
+ var input = new WritableStream({
3194
+ write(chunk) {
3195
+ return new Promise((resolve4) => {
3196
+ if (process.stdout.destroyed || !process.stdout.writable) return resolve4();
3197
+ try {
3198
+ process.stdout.write(chunk, (err) => {
3199
+ void err;
3200
+ resolve4();
3201
+ });
3202
+ } catch {
3203
+ resolve4();
3204
+ }
3205
+ });
3206
+ }
3207
+ });
3208
+ var output = new ReadableStream({
3209
+ start(controller) {
3210
+ process.stdin.on("data", (chunk) => controller.enqueue(new Uint8Array(chunk)));
3211
+ process.stdin.on("end", () => controller.close());
3212
+ process.stdin.on("error", (err) => controller.error(err));
3213
+ }
3214
+ });
3215
+ var stream = ndJsonStream(input, output);
3216
+ var agent = new AgentSideConnection((conn) => new PiAcpAgent(conn), stream);
3217
+ function shutdown() {
3218
+ try {
3219
+ ;
3220
+ agent?.agent?.dispose?.();
3221
+ } catch {
3222
+ }
3223
+ try {
3224
+ process.exit(0);
3225
+ } catch {
3226
+ }
3227
+ }
3228
+ process.stdin.on("end", shutdown);
3229
+ process.stdin.on("close", shutdown);
3230
+ process.stdin.resume();
3231
+ process.on("SIGINT", shutdown);
3232
+ process.on("SIGTERM", shutdown);
3233
+ process.stdout.on("error", () => {
3234
+ try {
3235
+ process.exit(0);
3236
+ } catch {
3237
+ }
3238
+ });