@ccgv2/pi-acp 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2640 @@
1
+ #!/usr/bin/env node
2
+ import { homedir, platform } from "node:os";
3
+ import { AgentSideConnection, RequestError, ndJsonStream } from "@agentclientprotocol/sdk";
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
6
+ import { dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { SessionManager, createAgentSession, defineTool } from "@earendil-works/pi-coding-agent";
8
+ import * as z from "zod";
9
+ import { createHash } from "node:crypto";
10
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
12
+ import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
13
+ import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
14
+ import { Unsafe } from "typebox";
15
+ //#region src/acp/auth.ts
16
+ const AUTH_METHOD_ID = "pi_terminal_login";
17
+ function buildAuthMethods(opts) {
18
+ const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
19
+ const method = {
20
+ id: AUTH_METHOD_ID,
21
+ name: "Launch pi in the terminal",
22
+ description: "Start pi in an interactive terminal to configure API keys or login",
23
+ type: "terminal",
24
+ args: ["--terminal-login"],
25
+ env: {}
26
+ };
27
+ if (supportsTerminalAuthMeta) method._meta = { "terminal-auth": {
28
+ ...resolveTerminalLaunchCommand(),
29
+ label: "Launch pi"
30
+ } };
31
+ return [method];
32
+ }
33
+ function resolveTerminalLaunchCommand() {
34
+ const argv0 = process.argv[0] ?? "node";
35
+ const argv1 = process.argv[1];
36
+ if (argv1 !== void 0 && argv0.includes("node") && argv1.endsWith(".js")) return {
37
+ command: argv0,
38
+ args: [argv1, "--terminal-login"]
39
+ };
40
+ return {
41
+ command: "pi-acp",
42
+ args: ["--terminal-login"]
43
+ };
44
+ }
45
+ //#endregion
46
+ //#region src/acp/auth-required.ts
47
+ /**
48
+ * Detect common auth/credential errors from pi and surface them as ACP AUTH_REQUIRED.
49
+ */
50
+ const AUTH_ERROR_PATTERNS = [
51
+ "api key",
52
+ "apikey",
53
+ "missing key",
54
+ "no key",
55
+ "not configured",
56
+ "unauthorized",
57
+ "authentication",
58
+ "permission denied",
59
+ "forbidden",
60
+ "401",
61
+ "403"
62
+ ];
63
+ function detectAuthError(err) {
64
+ const lower = (err instanceof Error ? err.message : String(err ?? "")).toLowerCase();
65
+ if (!AUTH_ERROR_PATTERNS.some((p) => lower.includes(p))) return null;
66
+ return RequestError.authRequired({ authMethods: buildAuthMethods() }, "Configure an API key or log in with an OAuth provider.");
67
+ }
68
+ //#endregion
69
+ //#region src/acp/client-capabilities.ts
70
+ /**
71
+ * Extract well-known capability flags from ACP `ClientCapabilities`.
72
+ *
73
+ * Reads from:
74
+ * - `_meta.terminal_output` (terminal output rendering)
75
+ * - `_meta.terminal-auth` (terminal auth with command metadata)
76
+ * - `auth._meta.gateway` (gateway auth, future use)
77
+ */
78
+ function parseClientCapabilities(caps) {
79
+ if (caps === void 0 || caps === null) return {
80
+ terminalOutput: false,
81
+ terminalAuth: false,
82
+ gatewayAuth: false
83
+ };
84
+ const meta = caps._meta;
85
+ const terminalOutput = typeof meta === "object" && meta !== null && meta["terminal_output"] === true;
86
+ const terminalAuth = typeof meta === "object" && meta !== null && meta["terminal-auth"] === true;
87
+ let gatewayAuth = false;
88
+ if ("auth" in caps) {
89
+ const auth = caps.auth;
90
+ if (typeof auth === "object" && auth !== null && "_meta" in auth) {
91
+ const authMeta = auth._meta;
92
+ if (typeof authMeta === "object" && authMeta !== null && "gateway" in authMeta) gatewayAuth = authMeta["gateway"] === true;
93
+ }
94
+ }
95
+ return {
96
+ terminalOutput,
97
+ terminalAuth,
98
+ gatewayAuth
99
+ };
100
+ }
101
+ //#endregion
102
+ //#region src/acp/model-alias.ts
103
+ /**
104
+ * Tokenize a string: split on non-alphanumeric, lowercase, strip "claude".
105
+ */
106
+ function tokenize(input) {
107
+ return input.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t !== "" && t !== "claude");
108
+ }
109
+ /**
110
+ * Extract a context hint in square brackets, e.g. "opus[1m]" -> { base: "opus", hint: "1m" }.
111
+ */
112
+ function extractContextHint(input) {
113
+ const match = /^(.+?)\[([^\]]+)\]$/.exec(input);
114
+ if (match !== null && match[1] !== void 0 && match[2] !== void 0) return {
115
+ base: match[1],
116
+ hint: match[2]
117
+ };
118
+ return {
119
+ base: input,
120
+ hint: null
121
+ };
122
+ }
123
+ /** Check if a string is purely numeric. */
124
+ function isNumeric(s) {
125
+ return /^\d+$/.test(s);
126
+ }
127
+ /**
128
+ * Score how well a model matches the given preference tokens.
129
+ *
130
+ * Returns a score >= 0 (higher is better), or -1 for no match.
131
+ * Requires at least one non-numeric token to match to avoid false positives
132
+ * from bare version numbers (e.g. "4" matching model version suffixes).
133
+ */
134
+ function scoreModel(model, prefTokens, hint) {
135
+ const modelStr = `${model.provider}/${model.id}/${model.name ?? ""}`.toLowerCase();
136
+ const modelTokens = tokenize(modelStr);
137
+ let matched = 0;
138
+ let hasNonNumericMatch = false;
139
+ for (const pt of prefTokens) if (modelTokens.some((mt) => mt.includes(pt) || pt.includes(mt))) {
140
+ matched++;
141
+ if (!isNumeric(pt)) hasNonNumericMatch = true;
142
+ }
143
+ if (matched === 0) return -1;
144
+ if (!hasNonNumericMatch) return -1;
145
+ let score = matched / prefTokens.length;
146
+ if (hint !== null && modelStr.includes(hint.toLowerCase())) score += .5;
147
+ const pref = prefTokens.join("");
148
+ if (model.id.toLowerCase().includes(pref)) score += .25;
149
+ return score;
150
+ }
151
+ /**
152
+ * Resolve a user-friendly model preference to a concrete model.
153
+ *
154
+ * Matching strategy (in order):
155
+ * 1. Exact match on "provider/id"
156
+ * 2. Exact match on "id" alone
157
+ * 3. Tokenized scored match with optional context hint
158
+ *
159
+ * Returns null if no model matches.
160
+ */
161
+ function resolveModelPreference(models, preference) {
162
+ const trimmed = preference.trim();
163
+ if (trimmed === "") return null;
164
+ if (trimmed.includes("/")) {
165
+ const [p, ...rest] = trimmed.split("/");
166
+ const provider = p ?? "";
167
+ const id = rest.join("/");
168
+ const exact = models.find((m) => m.provider.toLowerCase() === provider.toLowerCase() && m.id.toLowerCase() === id.toLowerCase());
169
+ if (exact !== void 0) return {
170
+ provider: exact.provider,
171
+ id: exact.id
172
+ };
173
+ }
174
+ const byId = models.find((m) => m.id.toLowerCase() === trimmed.toLowerCase());
175
+ if (byId !== void 0) return {
176
+ provider: byId.provider,
177
+ id: byId.id
178
+ };
179
+ const { base, hint } = extractContextHint(trimmed);
180
+ const prefTokens = tokenize(base);
181
+ if (prefTokens.length === 0) return null;
182
+ let bestModel = null;
183
+ let bestScore = -1;
184
+ for (const model of models) {
185
+ const s = scoreModel(model, prefTokens, hint);
186
+ if (s > bestScore) {
187
+ bestScore = s;
188
+ bestModel = model;
189
+ }
190
+ }
191
+ if (bestModel === null || bestScore < .5) return null;
192
+ return {
193
+ provider: bestModel.provider,
194
+ id: bestModel.id
195
+ };
196
+ }
197
+ //#endregion
198
+ //#region src/acp/pi-settings.ts
199
+ /**
200
+ * Read pi settings from global and project config files.
201
+ *
202
+ * Settings are merged: project overrides global.
203
+ * Paths follow pi-mono conventions:
204
+ * Global: ~/.pi/agent/settings.json
205
+ * Project: <cwd>/.pi/settings.json
206
+ */
207
+ const piSettingsSchema = z.object({
208
+ enableSkillCommands: z.boolean().optional(),
209
+ quietStartup: z.boolean().optional(),
210
+ quietStart: z.boolean().optional(),
211
+ skills: z.object({ enableSkillCommands: z.boolean().optional() }).optional()
212
+ });
213
+ function isRecord(x) {
214
+ return typeof x === "object" && x !== null && !Array.isArray(x);
215
+ }
216
+ function merge(base, override) {
217
+ const result = { ...base };
218
+ for (const [key, val] of Object.entries(override)) {
219
+ const existing = result[key];
220
+ if (isRecord(existing) && isRecord(val)) result[key] = merge(existing, val);
221
+ else result[key] = val;
222
+ }
223
+ return result;
224
+ }
225
+ function readJson(path) {
226
+ try {
227
+ if (!existsSync(path)) return {};
228
+ const data = JSON.parse(readFileSync(path, "utf-8"));
229
+ return isRecord(data) ? data : {};
230
+ } catch {
231
+ return {};
232
+ }
233
+ }
234
+ function piAgentDir() {
235
+ return process.env.PI_CODING_AGENT_DIR !== void 0 ? resolve(process.env.PI_CODING_AGENT_DIR) : join(homedir(), ".pi", "agent");
236
+ }
237
+ function resolvedSettings(cwd) {
238
+ const globalPath = join(piAgentDir(), "settings.json");
239
+ const projectPath = resolve(cwd, ".pi", "settings.json");
240
+ const merged = merge(readJson(globalPath), readJson(projectPath));
241
+ const result = piSettingsSchema.safeParse(merged);
242
+ return result.success ? result.data : {};
243
+ }
244
+ function skillCommandsEnabled(cwd) {
245
+ const settings = resolvedSettings(cwd);
246
+ if (typeof settings.enableSkillCommands === "boolean") return settings.enableSkillCommands;
247
+ if (typeof settings.skills?.enableSkillCommands === "boolean") return settings.skills.enableSkillCommands;
248
+ return true;
249
+ }
250
+ //#endregion
251
+ //#region src/acp/translate/tool-content.ts
252
+ const textBlockSchema = z.object({
253
+ type: z.literal("text"),
254
+ text: z.string()
255
+ });
256
+ const imageBlockSchema = z.object({ type: z.literal("image") });
257
+ const contentBlockSchema = z.union([textBlockSchema, imageBlockSchema]);
258
+ const bashDetailsSchema = z.object({
259
+ stdout: z.string().optional(),
260
+ stderr: z.string().optional(),
261
+ output: z.string().optional(),
262
+ exitCode: z.number().optional(),
263
+ code: z.number().optional()
264
+ });
265
+ const bashResultSchema = z.object({
266
+ content: z.array(z.unknown()).optional(),
267
+ details: bashDetailsSchema.optional(),
268
+ stdout: z.string().optional(),
269
+ stderr: z.string().optional(),
270
+ output: z.string().optional(),
271
+ exitCode: z.number().optional(),
272
+ code: z.number().optional()
273
+ });
274
+ /**
275
+ * Extract stdout/stderr and exit code from a pi bash/tmux result.
276
+ */
277
+ function extractBashOutput(result) {
278
+ if (result === null || result === void 0 || typeof result !== "object") return {
279
+ output: "",
280
+ exitCode: void 0
281
+ };
282
+ const parsed = bashResultSchema.safeParse(result);
283
+ if (!parsed.success) return {
284
+ output: "",
285
+ exitCode: void 0
286
+ };
287
+ const r = parsed.data;
288
+ const d = r.details;
289
+ if (r.content !== void 0) {
290
+ const texts = r.content.map((block) => textBlockSchema.safeParse(block)).filter((res) => res.success).map((res) => res.data.text);
291
+ if (texts.length > 0) {
292
+ const exitCode = d?.exitCode ?? r.exitCode ?? d?.code ?? r.code;
293
+ return {
294
+ output: texts.join(""),
295
+ exitCode
296
+ };
297
+ }
298
+ }
299
+ const stdout = d?.stdout ?? r.stdout ?? d?.output ?? r.output;
300
+ const stderr = d?.stderr ?? r.stderr;
301
+ const exitCode = d?.exitCode ?? r.exitCode ?? d?.code ?? r.code;
302
+ const parts = [];
303
+ if (stdout !== void 0 && stdout.trim() !== "") parts.push(stdout);
304
+ if (stderr !== void 0 && stderr.trim() !== "") parts.push(stderr);
305
+ return {
306
+ output: parts.join("\n"),
307
+ exitCode
308
+ };
309
+ }
310
+ /**
311
+ * Extract text content from a pi tool result (generic).
312
+ */
313
+ function extractTextContent(result) {
314
+ if (result === null || result === void 0 || typeof result !== "object") return "";
315
+ if ("content" in result && Array.isArray(result.content)) {
316
+ const texts = [];
317
+ for (const block of result.content) {
318
+ const parsed = textBlockSchema.safeParse(block);
319
+ if (parsed.success) texts.push(parsed.data.text);
320
+ }
321
+ if (texts.length > 0) return texts.join("");
322
+ }
323
+ try {
324
+ return JSON.stringify(result, null, 2);
325
+ } catch {
326
+ return String(result);
327
+ }
328
+ }
329
+ /**
330
+ * Extract content blocks from a pi result, preserving type information.
331
+ * Used for read results where images need to be preserved.
332
+ */
333
+ function extractContentBlocks(result) {
334
+ if (result === null || result === void 0 || typeof result !== "object") return [];
335
+ if (!("content" in result) || !Array.isArray(result.content)) return [];
336
+ const blocks = [];
337
+ for (const raw of result.content) {
338
+ const parsed = contentBlockSchema.safeParse(raw);
339
+ if (parsed.success) blocks.push(parsed.data);
340
+ }
341
+ return blocks;
342
+ }
343
+ /**
344
+ * Find the longest consecutive backtick sequence in a string.
345
+ */
346
+ function longestBacktickRun(text) {
347
+ let max = 0;
348
+ let current = 0;
349
+ for (const ch of text) if (ch === "`") {
350
+ current++;
351
+ if (current > max) max = current;
352
+ } else current = 0;
353
+ return max;
354
+ }
355
+ /**
356
+ * Wrap text in a dynamically-sized backtick fence to prevent markdown rendering.
357
+ *
358
+ * Instead of character-level escaping (which fails on files containing backtick
359
+ * sequences, indented code blocks, blockquotes, and list markers), this wraps
360
+ * the entire text in a backtick fence whose length exceeds any backtick sequence
361
+ * in the content. This approach is simpler and strictly more correct (following
362
+ * the claude-agent-acp pattern).
363
+ */
364
+ function markdownEscape(text) {
365
+ if (text === "") return "";
366
+ const fenceLen = Math.max(3, longestBacktickRun(text) + 1);
367
+ const fence = "`".repeat(fenceLen);
368
+ return `${fence}\n${text.endsWith("\n") ? text.slice(0, -1) : text}\n${fence}`;
369
+ }
370
+ /**
371
+ * Format tool output into `ToolCallContent[]` by tool name.
372
+ *
373
+ * Returns the appropriate content shape for each tool type:
374
+ * - bash/tmux: console code fences
375
+ * - read: markdown-escaped text (images preserved)
376
+ * - edit/write: empty (diff handled separately)
377
+ * - lsp: code fences
378
+ * - errors: code fences with failed status
379
+ * - everything else: plain text
380
+ */
381
+ function formatToolContent(toolName, result, isError) {
382
+ if (isError) {
383
+ const text = extractTextContent(result);
384
+ if (text === "") return [];
385
+ return [{
386
+ type: "content",
387
+ content: {
388
+ type: "text",
389
+ text: `\`\`\`\n${text}\n\`\`\``
390
+ }
391
+ }];
392
+ }
393
+ switch (toolName) {
394
+ case "bash":
395
+ case "tmux": return formatBashContent(result);
396
+ case "read": return formatReadContent(result);
397
+ case "edit":
398
+ case "write": return [];
399
+ case "lsp": return formatLspContent(result);
400
+ default: return formatFallbackContent(result);
401
+ }
402
+ }
403
+ function formatBashContent(result) {
404
+ const { output, exitCode } = extractBashOutput(result);
405
+ if (output === "" && exitCode === void 0) return [];
406
+ const parts = [];
407
+ if (output !== "") parts.push(`\`\`\`console\n${output}\n\`\`\``);
408
+ if (exitCode !== void 0 && exitCode !== 0) parts.push(`exit code: ${exitCode}`);
409
+ const text = parts.join("\n\n");
410
+ if (text === "") return [];
411
+ return [{
412
+ type: "content",
413
+ content: {
414
+ type: "text",
415
+ text
416
+ }
417
+ }];
418
+ }
419
+ function formatReadContent(result) {
420
+ const blocks = extractContentBlocks(result);
421
+ if (blocks.length === 0) {
422
+ if (typeof result === "object" && result !== null && "content" in result && Array.isArray(result.content) && result.content.length === 0) return [];
423
+ const text = extractTextContent(result);
424
+ if (text === "") return [];
425
+ return [{
426
+ type: "content",
427
+ content: {
428
+ type: "text",
429
+ text: markdownEscape(text)
430
+ }
431
+ }];
432
+ }
433
+ const content = [];
434
+ for (const block of blocks) if (block.type === "text") content.push({
435
+ type: "content",
436
+ content: {
437
+ type: "text",
438
+ text: markdownEscape(block.text)
439
+ }
440
+ });
441
+ return content;
442
+ }
443
+ function formatLspContent(result) {
444
+ const text = extractTextContent(result);
445
+ if (text === "") return [];
446
+ return [{
447
+ type: "content",
448
+ content: {
449
+ type: "text",
450
+ text: `\`\`\`\n${text}\n\`\`\``
451
+ }
452
+ }];
453
+ }
454
+ function formatFallbackContent(result) {
455
+ const text = extractTextContent(result);
456
+ if (text === "") return [];
457
+ return [{
458
+ type: "content",
459
+ content: {
460
+ type: "text",
461
+ text
462
+ }
463
+ }];
464
+ }
465
+ /**
466
+ * Wrap streaming output text in a console code fence for bash/tmux.
467
+ *
468
+ * Each streaming update is self-contained (full accumulated buffer),
469
+ * following the codex-acp pattern.
470
+ */
471
+ function wrapStreamingBashOutput(text) {
472
+ if (text === "") return "";
473
+ return `\`\`\`console\n${text}\n\`\`\``;
474
+ }
475
+ //#endregion
476
+ //#region src/acp/unreachable.ts
477
+ /**
478
+ * Exhaustive switch/case helper.
479
+ *
480
+ * Writes unknown values to stderr instead of silently ignoring them, aiding
481
+ * debugging when the pi SDK adds new event types. Never write to stdout: it
482
+ * carries the ACP NDJSON stream and any other byte poisons the protocol.
483
+ */
484
+ function unreachable(value, context) {
485
+ const label = context !== void 0 ? `[${context}] ` : "";
486
+ process.stderr.write(`${label}Unhandled value: ${String(value)}\n`);
487
+ }
488
+ //#endregion
489
+ //#region src/acp/session.ts
490
+ function findUniqueLineNumber(text, needle) {
491
+ if (!needle) return void 0;
492
+ const first = text.indexOf(needle);
493
+ if (first < 0) return void 0;
494
+ if (text.indexOf(needle, first + needle.length) >= 0) return void 0;
495
+ let line = 1;
496
+ for (let i = 0; i < first; i++) if (text.charCodeAt(i) === 10) line++;
497
+ return line;
498
+ }
499
+ function resolveToolPath(args, cwd, line) {
500
+ const p = args.path;
501
+ if (p === void 0) return void 0;
502
+ return [{
503
+ path: isAbsolute(p) ? p : resolve(cwd, p),
504
+ ...typeof line === "number" ? { line } : {}
505
+ }];
506
+ }
507
+ function toToolKind(toolName) {
508
+ switch (toolName) {
509
+ case "read": return "read";
510
+ case "write":
511
+ case "edit": return "edit";
512
+ case "bash":
513
+ case "tmux": return "execute";
514
+ case "lsp": return "search";
515
+ default: return "other";
516
+ }
517
+ }
518
+ const MAX_TITLE_LEN = 80;
519
+ function truncateTitle(text) {
520
+ const oneLine = text.replace(/\n/g, " ").trim();
521
+ if (oneLine.length <= MAX_TITLE_LEN) return oneLine;
522
+ return `${oneLine.slice(0, MAX_TITLE_LEN - 1)}…`;
523
+ }
524
+ function capitalize(s) {
525
+ if (s.length === 0) return s;
526
+ return s.charAt(0).toUpperCase() + s.slice(1);
527
+ }
528
+ /**
529
+ * Build a descriptive tool title from tool name and args.
530
+ *
531
+ * Returns a short human-readable label like "Read src/index.ts" or "Run ls -la".
532
+ */
533
+ function buildToolTitle(toolName, args) {
534
+ const p = args.path;
535
+ switch (toolName) {
536
+ case "read": return p !== void 0 ? `Read ${p}` : "Read";
537
+ case "write": return p !== void 0 ? `Write ${p}` : "Write";
538
+ case "edit": return p !== void 0 ? `Edit ${p}` : "Edit";
539
+ case "bash": {
540
+ const command = typeof args["command"] === "string" ? args["command"] : typeof args["cmd"] === "string" ? args["cmd"] : void 0;
541
+ return command !== void 0 ? truncateTitle(`Run ${command}`) : "bash";
542
+ }
543
+ case "lsp": {
544
+ const action = typeof args["action"] === "string" ? args["action"] : void 0;
545
+ const file = typeof args["file"] === "string" ? args["file"] : void 0;
546
+ const query = typeof args["query"] === "string" ? args["query"] : void 0;
547
+ const line = typeof args["line"] === "number" ? args["line"] : void 0;
548
+ if (action !== void 0) {
549
+ const target = file !== void 0 ? line !== void 0 ? `${file}:${line}` : file : query;
550
+ return target !== void 0 ? truncateTitle(`${capitalize(action)} ${target}`) : capitalize(action);
551
+ }
552
+ return "LSP";
553
+ }
554
+ case "tmux": {
555
+ const action = typeof args["action"] === "string" ? args["action"] : void 0;
556
+ const command = typeof args["command"] === "string" ? args["command"] : void 0;
557
+ const name = typeof args["name"] === "string" ? args["name"] : void 0;
558
+ if (action === "run" && command !== void 0) return truncateTitle(`Tmux: ${command}`);
559
+ if (action !== void 0 && name !== void 0) return truncateTitle(`Tmux ${action} ${name}`);
560
+ if (action !== void 0) return `Tmux ${action}`;
561
+ return "Tmux";
562
+ }
563
+ case "context_tag": {
564
+ const name = typeof args["name"] === "string" ? args["name"] : void 0;
565
+ return name !== void 0 ? `Tag ${name}` : "Tag";
566
+ }
567
+ case "context_log": return "Context log";
568
+ case "context_checkout": {
569
+ const target = typeof args["target"] === "string" ? args["target"] : void 0;
570
+ return target !== void 0 ? truncateTitle(`Checkout ${target}`) : "Checkout";
571
+ }
572
+ case "claudemon": return "Check quota";
573
+ default: return toolName;
574
+ }
575
+ }
576
+ /**
577
+ * Map pi assistant stopReason to ACP StopReason.
578
+ * pi: "stop" | "length" | "toolUse" | "error" | "aborted"
579
+ * ACP: "end_turn" | "cancelled" | "max_tokens" | "error"
580
+ */
581
+ function mapPiStopReason(piReason) {
582
+ switch (piReason) {
583
+ case "stop":
584
+ case "toolUse": return "end_turn";
585
+ case "length": return "max_tokens";
586
+ case "aborted": return "cancelled";
587
+ case "error": return "error";
588
+ default: return "end_turn";
589
+ }
590
+ }
591
+ function extractToolCallFromPartial(ame) {
592
+ if (!("partial" in ame)) return void 0;
593
+ const block = ame.partial.content["contentIndex" in ame ? ame.contentIndex : 0];
594
+ if (block && "type" in block && block.type === "toolCall") return block;
595
+ }
596
+ function parseToolInput(tc) {
597
+ return tc.arguments;
598
+ }
599
+ const toolArgsSchema = z.object({
600
+ path: z.string().trim().optional(),
601
+ oldText: z.string().trim().optional()
602
+ }).loose();
603
+ function toToolArgs(raw) {
604
+ const result = toolArgsSchema.safeParse(raw);
605
+ return result.success ? result.data : {};
606
+ }
607
+ /** Build the `_meta.piAcp` tool name metadata. */
608
+ function buildToolMeta(toolName, extra) {
609
+ const base = { piAcp: { toolName } };
610
+ if (extra !== void 0) return {
611
+ ...base,
612
+ ...extra
613
+ };
614
+ return base;
615
+ }
616
+ /** Tools that produce terminal-style output. */
617
+ function isTerminalTool(toolName) {
618
+ return toolName === "bash" || toolName === "tmux";
619
+ }
620
+ var SessionManager$1 = class {
621
+ sessions = /* @__PURE__ */ new Map();
622
+ disposeAll() {
623
+ for (const id of this.sessions.keys()) this.close(id);
624
+ }
625
+ async disposeAllAsync() {
626
+ await Promise.all([...this.sessions.keys()].map((id) => this.closeAsync(id)));
627
+ }
628
+ maybeGet(sessionId) {
629
+ return this.sessions.get(sessionId);
630
+ }
631
+ close(sessionId) {
632
+ const s = this.sessions.get(sessionId);
633
+ if (!s) return;
634
+ try {
635
+ s.dispose();
636
+ } catch {}
637
+ this.sessions.delete(sessionId);
638
+ }
639
+ async closeAsync(sessionId) {
640
+ const session = this.sessions.get(sessionId);
641
+ if (session === void 0) return;
642
+ this.sessions.delete(sessionId);
643
+ await session.disposeAsync();
644
+ }
645
+ closeAllExcept(keepSessionId) {
646
+ for (const id of this.sessions.keys()) if (id !== keepSessionId) this.close(id);
647
+ }
648
+ register(session) {
649
+ this.sessions.set(session.sessionId, session);
650
+ }
651
+ get(sessionId) {
652
+ const s = this.sessions.get(sessionId);
653
+ if (!s) throw RequestError.invalidParams(`Unknown sessionId: ${sessionId}`);
654
+ return s;
655
+ }
656
+ };
657
+ var PiAcpSession = class {
658
+ sessionId;
659
+ cwd;
660
+ mcpServers;
661
+ piSession;
662
+ supportsTerminalOutput;
663
+ mcpFingerprint;
664
+ conn;
665
+ mcpManager;
666
+ cancelRequested = false;
667
+ promptRunning = false;
668
+ pendingTurn = null;
669
+ /** Queued prompts waiting for the active turn to complete. */
670
+ pendingMessages = [];
671
+ currentToolCalls = /* @__PURE__ */ new Map();
672
+ /** Map of toolCallId -> toolName for streaming updates (Phase 5). */
673
+ toolCallNames = /* @__PURE__ */ new Map();
674
+ editSnapshots = /* @__PURE__ */ new Map();
675
+ lastAssistantStopReason = null;
676
+ lastEmit = Promise.resolve();
677
+ unsubscribe;
678
+ constructor(opts) {
679
+ this.sessionId = opts.sessionId;
680
+ this.cwd = opts.cwd;
681
+ this.mcpServers = opts.mcpServers;
682
+ this.piSession = opts.piSession;
683
+ this.mcpManager = opts.mcpManager;
684
+ this.mcpFingerprint = opts.mcpManager?.fingerprint ?? "";
685
+ this.conn = opts.conn;
686
+ this.supportsTerminalOutput = opts.supportsTerminalOutput ?? false;
687
+ this.unsubscribe = this.piSession.subscribe((ev) => this.handlePiEvent(ev));
688
+ }
689
+ dispose() {
690
+ this.unsubscribe?.();
691
+ this.piSession.dispose();
692
+ this.mcpManager?.close();
693
+ }
694
+ async disposeAsync() {
695
+ this.unsubscribe?.();
696
+ this.piSession.dispose();
697
+ await this.mcpManager?.close();
698
+ }
699
+ async prompt(message, images = []) {
700
+ if (this.promptRunning) return new Promise((resolve, reject) => {
701
+ this.pendingMessages.push({
702
+ message,
703
+ images,
704
+ resolve,
705
+ reject
706
+ });
707
+ });
708
+ return this.executePrompt(message, images);
709
+ }
710
+ async cancel() {
711
+ this.cancelRequested = true;
712
+ for (const pending of this.pendingMessages) pending.resolve("cancelled");
713
+ this.pendingMessages = [];
714
+ await this.piSession.abort();
715
+ }
716
+ executePrompt(message, images) {
717
+ this.promptRunning = true;
718
+ const turnPromise = new Promise((resolve, reject) => {
719
+ this.cancelRequested = false;
720
+ this.pendingTurn = {
721
+ resolve,
722
+ reject
723
+ };
724
+ });
725
+ const imageContents = Array.isArray(images) ? images.filter((img) => typeof img === "object" && img !== null && "type" in img && img.type === "image") : [];
726
+ this.piSession.prompt(message, { images: imageContents }).catch(() => {
727
+ this.flushEmits().finally(() => {
728
+ const reason = this.cancelRequested ? "cancelled" : "error";
729
+ this.pendingTurn?.resolve(reason);
730
+ this.pendingTurn = null;
731
+ });
732
+ });
733
+ return turnPromise;
734
+ }
735
+ /**
736
+ * Dequeue and execute the next pending prompt, if any.
737
+ * Called after a turn completes.
738
+ */
739
+ dequeueNextPrompt() {
740
+ const next = this.pendingMessages.shift();
741
+ if (next === void 0) {
742
+ this.promptRunning = false;
743
+ return;
744
+ }
745
+ this.executePrompt(next.message, next.images).then(next.resolve, next.reject);
746
+ }
747
+ wasCancelRequested() {
748
+ return this.cancelRequested;
749
+ }
750
+ emit(update) {
751
+ this.lastEmit = this.lastEmit.then(() => this.conn.sessionUpdate({
752
+ sessionId: this.sessionId,
753
+ update
754
+ })).catch(() => {});
755
+ }
756
+ async flushEmits() {
757
+ await this.lastEmit;
758
+ }
759
+ handlePiEvent(ev) {
760
+ if (!isAgentEvent(ev)) return;
761
+ switch (ev.type) {
762
+ case "message_update":
763
+ this.handleMessageUpdate(ev.assistantMessageEvent);
764
+ break;
765
+ case "message_end":
766
+ this.handleMessageEnd(ev.message);
767
+ break;
768
+ case "tool_execution_start":
769
+ this.handleToolStart(ev.toolCallId, ev.toolName, toToolArgs(ev.args));
770
+ break;
771
+ case "tool_execution_update":
772
+ this.handleToolUpdate(ev.toolCallId, ev.toolName, ev.partialResult);
773
+ break;
774
+ case "tool_execution_end":
775
+ this.handleToolEnd(ev.toolCallId, ev.toolName, ev.result, ev.isError);
776
+ break;
777
+ case "agent_end":
778
+ this.handleAgentEnd();
779
+ break;
780
+ default:
781
+ unreachable(ev, "handlePiEvent");
782
+ break;
783
+ }
784
+ }
785
+ handleMessageUpdate(ame) {
786
+ if (ame.type === "text_delta") {
787
+ this.emit({
788
+ sessionUpdate: "agent_message_chunk",
789
+ content: {
790
+ type: "text",
791
+ text: ame.delta
792
+ }
793
+ });
794
+ return;
795
+ }
796
+ if (ame.type === "thinking_delta") {
797
+ this.emit({
798
+ sessionUpdate: "agent_thought_chunk",
799
+ content: {
800
+ type: "text",
801
+ text: ame.delta
802
+ }
803
+ });
804
+ return;
805
+ }
806
+ if (ame.type === "toolcall_start" || ame.type === "toolcall_delta" || ame.type === "toolcall_end") {
807
+ const toolCall = ame.type === "toolcall_end" ? ame.toolCall : extractToolCallFromPartial(ame);
808
+ if (!toolCall) return;
809
+ const rawInput = parseToolInput(toolCall);
810
+ const locations = resolveToolPath(rawInput, this.cwd);
811
+ const existingStatus = this.currentToolCalls.get(toolCall.id);
812
+ const status = existingStatus ?? "pending";
813
+ if (!existingStatus) {
814
+ this.currentToolCalls.set(toolCall.id, "pending");
815
+ this.emit({
816
+ sessionUpdate: "tool_call",
817
+ toolCallId: toolCall.id,
818
+ title: buildToolTitle(toolCall.name, rawInput),
819
+ kind: toToolKind(toolCall.name),
820
+ status,
821
+ ...locations ? { locations } : {},
822
+ rawInput,
823
+ _meta: buildToolMeta(toolCall.name)
824
+ });
825
+ } else this.emit({
826
+ sessionUpdate: "tool_call_update",
827
+ toolCallId: toolCall.id,
828
+ status,
829
+ ...locations ? { locations } : {},
830
+ rawInput,
831
+ _meta: buildToolMeta(toolCall.name)
832
+ });
833
+ }
834
+ }
835
+ handleMessageEnd(msg) {
836
+ if ("role" in msg && msg.role === "assistant") this.lastAssistantStopReason = msg.stopReason;
837
+ }
838
+ handleToolStart(toolCallId, toolName, args) {
839
+ this.toolCallNames.set(toolCallId, toolName);
840
+ let line;
841
+ if ((toolName === "edit" || toolName === "write") && args.path !== void 0) try {
842
+ const abs = isAbsolute(args.path) ? args.path : resolve(this.cwd, args.path);
843
+ let oldText = "";
844
+ try {
845
+ oldText = readFileSync(abs, "utf8");
846
+ } catch {}
847
+ this.editSnapshots.set(toolCallId, {
848
+ path: abs,
849
+ oldText
850
+ });
851
+ if (toolName === "edit") line = findUniqueLineNumber(oldText, args.oldText ?? "");
852
+ } catch {}
853
+ const locations = resolveToolPath(args, this.cwd, line);
854
+ const meta = buildToolMeta(toolName, this.supportsTerminalOutput && isTerminalTool(toolName) ? { terminal_info: {
855
+ terminal_id: toolCallId,
856
+ cwd: this.cwd
857
+ } } : void 0);
858
+ const terminalContent = this.supportsTerminalOutput && isTerminalTool(toolName) ? [{
859
+ type: "terminal",
860
+ terminalId: toolCallId
861
+ }] : void 0;
862
+ if (!this.currentToolCalls.has(toolCallId)) {
863
+ this.currentToolCalls.set(toolCallId, "in_progress");
864
+ this.emit({
865
+ sessionUpdate: "tool_call",
866
+ toolCallId,
867
+ title: buildToolTitle(toolName, args),
868
+ kind: toToolKind(toolName),
869
+ status: "in_progress",
870
+ ...locations ? { locations } : {},
871
+ ...terminalContent !== void 0 ? { content: terminalContent } : {},
872
+ rawInput: args,
873
+ _meta: meta
874
+ });
875
+ } else {
876
+ this.currentToolCalls.set(toolCallId, "in_progress");
877
+ this.emit({
878
+ sessionUpdate: "tool_call_update",
879
+ toolCallId,
880
+ title: buildToolTitle(toolName, args),
881
+ status: "in_progress",
882
+ ...locations ? { locations } : {},
883
+ ...terminalContent !== void 0 ? { content: terminalContent } : {},
884
+ rawInput: args,
885
+ _meta: meta
886
+ });
887
+ }
888
+ }
889
+ handleToolUpdate(toolCallId, toolName, partialResult) {
890
+ const name = this.toolCallNames.get(toolCallId) ?? toolName;
891
+ if (this.supportsTerminalOutput && isTerminalTool(name)) {
892
+ const text = extractStreamingText(partialResult);
893
+ this.emit({
894
+ sessionUpdate: "tool_call_update",
895
+ toolCallId,
896
+ status: "in_progress",
897
+ _meta: buildToolMeta(name, { terminal_output: {
898
+ terminal_id: toolCallId,
899
+ data: text
900
+ } }),
901
+ rawOutput: partialResult
902
+ });
903
+ } else if (isTerminalTool(name)) {
904
+ const wrapped = wrapStreamingBashOutput(extractStreamingText(partialResult));
905
+ this.emit({
906
+ sessionUpdate: "tool_call_update",
907
+ toolCallId,
908
+ status: "in_progress",
909
+ content: wrapped ? [{
910
+ type: "content",
911
+ content: {
912
+ type: "text",
913
+ text: wrapped
914
+ }
915
+ }] : null,
916
+ _meta: buildToolMeta(name),
917
+ rawOutput: partialResult
918
+ });
919
+ } else {
920
+ const text = extractStreamingText(partialResult);
921
+ this.emit({
922
+ sessionUpdate: "tool_call_update",
923
+ toolCallId,
924
+ status: "in_progress",
925
+ content: text ? [{
926
+ type: "content",
927
+ content: {
928
+ type: "text",
929
+ text
930
+ }
931
+ }] : null,
932
+ _meta: buildToolMeta(name),
933
+ rawOutput: partialResult
934
+ });
935
+ }
936
+ }
937
+ handleToolEnd(toolCallId, toolName, result, isError) {
938
+ const snapshot = this.editSnapshots.get(toolCallId);
939
+ let content = null;
940
+ if (!isError && snapshot) try {
941
+ const newText = readFileSync(snapshot.path, "utf8");
942
+ if (newText !== snapshot.oldText) {
943
+ const formatted = formatToolContent(toolName, result, isError);
944
+ content = [{
945
+ type: "diff",
946
+ path: snapshot.path,
947
+ oldText: snapshot.oldText,
948
+ newText
949
+ }, ...formatted];
950
+ }
951
+ } catch {}
952
+ if (content === null) {
953
+ const formatted = formatToolContent(toolName, result, isError);
954
+ content = formatted.length > 0 ? formatted : null;
955
+ }
956
+ if (content === null && !isError && toolName !== "edit" && toolName !== "write") {
957
+ const text = extractStreamingText(result);
958
+ if (text) content = [{
959
+ type: "content",
960
+ content: {
961
+ type: "text",
962
+ text
963
+ }
964
+ }];
965
+ }
966
+ if (this.supportsTerminalOutput && isTerminalTool(toolName)) {
967
+ const outputText = extractStreamingText(result);
968
+ if (outputText !== "") this.emit({
969
+ sessionUpdate: "tool_call_update",
970
+ toolCallId,
971
+ status: "in_progress",
972
+ _meta: buildToolMeta(toolName, { terminal_output: {
973
+ terminal_id: toolCallId,
974
+ data: outputText
975
+ } }),
976
+ rawOutput: result
977
+ });
978
+ }
979
+ const meta = buildToolMeta(toolName, this.supportsTerminalOutput && isTerminalTool(toolName) ? { terminal_exit: {
980
+ terminal_id: toolCallId,
981
+ exit_code: extractExitCode(result),
982
+ signal: null
983
+ } } : void 0);
984
+ this.emit({
985
+ sessionUpdate: "tool_call_update",
986
+ toolCallId,
987
+ status: isError ? "failed" : "completed",
988
+ content,
989
+ _meta: meta,
990
+ rawOutput: result
991
+ });
992
+ this.currentToolCalls.delete(toolCallId);
993
+ this.editSnapshots.delete(toolCallId);
994
+ this.toolCallNames.delete(toolCallId);
995
+ }
996
+ handleAgentEnd() {
997
+ this.emitUsageUpdate();
998
+ this.flushEmits().finally(() => {
999
+ const reason = this.cancelRequested ? "cancelled" : mapPiStopReason(this.lastAssistantStopReason);
1000
+ this.lastAssistantStopReason = null;
1001
+ this.pendingTurn?.resolve(reason);
1002
+ this.pendingTurn = null;
1003
+ this.dequeueNextPrompt();
1004
+ });
1005
+ }
1006
+ /**
1007
+ * Emit a usage_update notification with current context and cost data.
1008
+ */
1009
+ emitUsageUpdate() {
1010
+ const contextUsage = this.piSession.getContextUsage?.();
1011
+ const stats = this.piSession.getSessionStats();
1012
+ const used = contextUsage?.tokens ?? 0;
1013
+ const size = contextUsage?.contextWindow ?? 0;
1014
+ this.emit({
1015
+ sessionUpdate: "usage_update",
1016
+ used,
1017
+ size,
1018
+ cost: stats.cost > 0 ? {
1019
+ amount: stats.cost,
1020
+ currency: "USD"
1021
+ } : null
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Build ACP Usage data from pi session stats for prompt response.
1026
+ */
1027
+ getUsage() {
1028
+ const stats = this.piSession.getSessionStats();
1029
+ return {
1030
+ inputTokens: stats.tokens.input,
1031
+ outputTokens: stats.tokens.output,
1032
+ cachedReadTokens: stats.tokens.cacheRead,
1033
+ cachedWriteTokens: stats.tokens.cacheWrite
1034
+ };
1035
+ }
1036
+ /**
1037
+ * Get cumulative session cost.
1038
+ */
1039
+ getCost() {
1040
+ return this.piSession.getSessionStats().cost;
1041
+ }
1042
+ };
1043
+ function isTextBlock$1(v) {
1044
+ return typeof v === "object" && v !== null && "type" in v && v.type === "text" && "text" in v && typeof v.text === "string";
1045
+ }
1046
+ function extractStreamingText(result) {
1047
+ if (result === null || result === void 0) return "";
1048
+ if (typeof result === "string") return result;
1049
+ if (typeof result !== "object") return String(result);
1050
+ if ("content" in result && Array.isArray(result.content)) {
1051
+ const texts = [];
1052
+ for (const raw of result.content) if (isTextBlock$1(raw)) texts.push(raw.text);
1053
+ if (texts.length > 0) return texts.join("");
1054
+ }
1055
+ if ("details" in result) {
1056
+ const details = result.details;
1057
+ if (typeof details === "object" && details !== null) {
1058
+ if ("stdout" in details && typeof details.stdout === "string" && details.stdout.trim() !== "") return details.stdout;
1059
+ if ("output" in details && typeof details.output === "string" && details.output.trim() !== "") return details.output;
1060
+ }
1061
+ }
1062
+ if ("output" in result && typeof result.output === "string" && result.output.trim() !== "") return result.output;
1063
+ if ("stdout" in result && typeof result.stdout === "string" && result.stdout.trim() !== "") return result.stdout;
1064
+ return "";
1065
+ }
1066
+ function extractExitCode(result) {
1067
+ if (result === null || result === void 0 || typeof result !== "object") return null;
1068
+ if ("details" in result) {
1069
+ const details = result.details;
1070
+ if (typeof details === "object" && details !== null) {
1071
+ if ("exitCode" in details && typeof details.exitCode === "number") return details.exitCode;
1072
+ if ("code" in details && typeof details.code === "number") return details.code;
1073
+ }
1074
+ }
1075
+ if ("exitCode" in result && typeof result.exitCode === "number") return result.exitCode;
1076
+ if ("code" in result && typeof result.code === "number") return result.code;
1077
+ return null;
1078
+ }
1079
+ /**
1080
+ * Type guard to narrow AgentSessionEvent to the AgentEvent subset
1081
+ * (the variants we handle). Session-specific events like auto_compaction
1082
+ * are ignored.
1083
+ */
1084
+ function isAgentEvent(ev) {
1085
+ return ev.type === "message_update" || ev.type === "message_end" || ev.type === "tool_execution_start" || ev.type === "tool_execution_update" || ev.type === "tool_execution_end" || ev.type === "agent_end";
1086
+ }
1087
+ //#endregion
1088
+ //#region src/acp/translate/pi-messages.ts
1089
+ function isTextBlock(block) {
1090
+ if (typeof block !== "object" || block === null) return false;
1091
+ return "type" in block && block.type === "text" && "text" in block && typeof block.text === "string";
1092
+ }
1093
+ function extractUserMessageText(content) {
1094
+ if (typeof content === "string") return content;
1095
+ if (!Array.isArray(content)) return "";
1096
+ return content.filter(isTextBlock).map((b) => b.text).join("");
1097
+ }
1098
+ //#endregion
1099
+ //#region src/acp/translate/prompt.ts
1100
+ function acpPromptToPiMessage(blocks) {
1101
+ let message = "";
1102
+ const images = [];
1103
+ for (const block of blocks) switch (block.type) {
1104
+ case "text":
1105
+ message += block.text;
1106
+ break;
1107
+ case "resource_link":
1108
+ message += `\n[Context] ${block.uri}`;
1109
+ break;
1110
+ case "image":
1111
+ images.push({
1112
+ type: "image",
1113
+ mimeType: block.mimeType,
1114
+ data: block.data
1115
+ });
1116
+ break;
1117
+ case "resource": {
1118
+ const resource = block.resource;
1119
+ const uri = resource.uri;
1120
+ const mime = resource.mimeType ?? null;
1121
+ if ("text" in resource) message += `\n[Embedded Context] ${uri} (${mime ?? "text/plain"})\n${resource.text}`;
1122
+ else if ("blob" in resource) {
1123
+ const bytes = Buffer.byteLength(resource.blob, "base64");
1124
+ message += `\n[Embedded Context] ${uri} (${mime ?? "application/octet-stream"}, ${bytes} bytes)`;
1125
+ } else message += `\n[Embedded Context] ${uri}`;
1126
+ break;
1127
+ }
1128
+ case "audio": {
1129
+ const bytes = Buffer.byteLength(block.data, "base64");
1130
+ message += `\n[Audio] (${block.mimeType}, ${bytes} bytes) not supported`;
1131
+ break;
1132
+ }
1133
+ default: break;
1134
+ }
1135
+ return {
1136
+ message,
1137
+ images
1138
+ };
1139
+ }
1140
+ //#endregion
1141
+ //#region src/mcp/fingerprint.ts
1142
+ function sortedEntries(values) {
1143
+ return Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
1144
+ }
1145
+ function fingerprintMcpServers(servers) {
1146
+ const canonical = [...servers].sort((left, right) => left.stableName.localeCompare(right.stableName)).map((server) => server.kind === "stdio" ? {
1147
+ kind: server.kind,
1148
+ originalName: server.originalName,
1149
+ stableName: server.stableName,
1150
+ command: server.command,
1151
+ args: server.args,
1152
+ env: sortedEntries(server.env),
1153
+ cwd: server.cwd
1154
+ } : {
1155
+ kind: server.kind,
1156
+ originalName: server.originalName,
1157
+ stableName: server.stableName,
1158
+ url: server.url,
1159
+ headers: sortedEntries(server.headers)
1160
+ });
1161
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
1162
+ }
1163
+ //#endregion
1164
+ //#region src/mcp/types.ts
1165
+ var McpConfigurationError = class extends Error {
1166
+ constructor(message) {
1167
+ super(message);
1168
+ this.name = "McpConfigurationError";
1169
+ }
1170
+ };
1171
+ //#endregion
1172
+ //#region src/mcp/normalize.ts
1173
+ const INVALID_HEADER_CHARACTER = /[\r\n]/;
1174
+ const LOOPBACK_HOSTS = new Set([
1175
+ "localhost",
1176
+ "127.0.0.1",
1177
+ "[::1]"
1178
+ ]);
1179
+ function stableServerName(name) {
1180
+ return name.replaceAll(/[^A-Za-z0-9_-]/g, "_");
1181
+ }
1182
+ function validateCwd(cwd) {
1183
+ if (!isAbsolute(cwd)) throw new McpConfigurationError(`MCP cwd must be an absolute path: ${cwd}`);
1184
+ try {
1185
+ if (!statSync(cwd).isDirectory()) throw new McpConfigurationError(`MCP cwd is not a directory: ${cwd}`);
1186
+ } catch (error) {
1187
+ if (error instanceof McpConfigurationError) throw error;
1188
+ throw new McpConfigurationError(`MCP cwd does not exist: ${cwd}`);
1189
+ }
1190
+ }
1191
+ function normalizeName(name) {
1192
+ const originalName = name.trim();
1193
+ if (originalName.length === 0) throw new McpConfigurationError("MCP server name must not be empty");
1194
+ const stableName = stableServerName(originalName);
1195
+ if (stableName.length === 0) throw new McpConfigurationError(`MCP server name cannot be normalized safely: ${name}`);
1196
+ return {
1197
+ originalName,
1198
+ stableName
1199
+ };
1200
+ }
1201
+ function normalizeKeyValuePairs(pairs, kind) {
1202
+ const result = {};
1203
+ const seen = /* @__PURE__ */ new Set();
1204
+ for (const pair of pairs) {
1205
+ const key = pair.name.trim();
1206
+ if (key.length === 0) throw new McpConfigurationError(`MCP ${kind} name must not be empty`);
1207
+ if (INVALID_HEADER_CHARACTER.test(key) || INVALID_HEADER_CHARACTER.test(pair.value)) throw new McpConfigurationError(`MCP ${kind} contains a forbidden newline`);
1208
+ const identity = kind === "header" ? key.toLowerCase() : key;
1209
+ if (seen.has(identity)) throw new McpConfigurationError(`Duplicate MCP ${kind} key: ${key}`);
1210
+ seen.add(identity);
1211
+ result[key] = pair.value;
1212
+ }
1213
+ return Object.fromEntries(Object.entries(result).sort(([left], [right]) => left.localeCompare(right)));
1214
+ }
1215
+ function normalizeStdioServer(server, cwd) {
1216
+ const names = normalizeName(server.name);
1217
+ if (server.command.trim().length === 0) throw new McpConfigurationError(`MCP stdio server "${names.originalName}" command must not be empty`);
1218
+ return {
1219
+ kind: "stdio",
1220
+ ...names,
1221
+ command: server.command,
1222
+ args: [...server.args],
1223
+ env: normalizeKeyValuePairs(server.env, "environment"),
1224
+ cwd
1225
+ };
1226
+ }
1227
+ function normalizeHttpServer(server) {
1228
+ const names = normalizeName(server.name);
1229
+ let url;
1230
+ try {
1231
+ url = new URL(server.url);
1232
+ } catch {
1233
+ throw new McpConfigurationError(`Invalid MCP HTTP URL for "${names.originalName}"`);
1234
+ }
1235
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) throw new McpConfigurationError(`MCP HTTP server "${names.originalName}" must use HTTPS unless it is loopback`);
1236
+ return {
1237
+ kind: "http",
1238
+ ...names,
1239
+ url: url.toString(),
1240
+ headers: normalizeKeyValuePairs(server.headers, "header")
1241
+ };
1242
+ }
1243
+ function normalizeMcpServers(servers, cwd) {
1244
+ validateCwd(cwd);
1245
+ if ((servers?.length ?? 0) > 32) throw new McpConfigurationError(`A session may configure at most 32 MCP servers`);
1246
+ const normalized = (servers ?? []).map((server) => {
1247
+ if (!("type" in server)) return normalizeStdioServer(server, cwd);
1248
+ if (server.type === "http") return normalizeHttpServer(server);
1249
+ throw new McpConfigurationError(`Unsupported MCP transport "${server.type}"`);
1250
+ });
1251
+ const originalNames = /* @__PURE__ */ new Set();
1252
+ const stableNames = /* @__PURE__ */ new Set();
1253
+ for (const server of normalized) {
1254
+ if (originalNames.has(server.originalName)) throw new McpConfigurationError(`Duplicate MCP server name: ${server.originalName}`);
1255
+ if (stableNames.has(server.stableName)) throw new McpConfigurationError(`Duplicate MCP server stable name: ${server.stableName}`);
1256
+ originalNames.add(server.originalName);
1257
+ stableNames.add(server.stableName);
1258
+ }
1259
+ return normalized;
1260
+ }
1261
+ //#endregion
1262
+ //#region src/mcp/http-connection.ts
1263
+ var HttpTransportBridge = class {
1264
+ onclose;
1265
+ onerror;
1266
+ onmessage;
1267
+ constructor(transport) {
1268
+ this.transport = transport;
1269
+ }
1270
+ start() {
1271
+ this.transport.onclose = () => this.onclose?.();
1272
+ this.transport.onerror = (error) => this.onerror?.(error);
1273
+ this.transport.onmessage = (message) => this.onmessage?.(message);
1274
+ return this.transport.start();
1275
+ }
1276
+ close() {
1277
+ return this.transport.close();
1278
+ }
1279
+ send(message) {
1280
+ return this.transport.send(message);
1281
+ }
1282
+ };
1283
+ var McpHttpConnection = class McpHttpConnection {
1284
+ client;
1285
+ server;
1286
+ #state = "starting";
1287
+ #closePromise;
1288
+ constructor(server, client) {
1289
+ this.server = server;
1290
+ this.client = client;
1291
+ }
1292
+ static async open(server) {
1293
+ const client = new Client({
1294
+ name: "pi-acp",
1295
+ version: "0.5.0"
1296
+ });
1297
+ const connection = new McpHttpConnection(server, client);
1298
+ const transport = new HttpTransportBridge(new StreamableHTTPClientTransport(new URL(server.url), { requestInit: { headers: server.headers } }));
1299
+ try {
1300
+ await client.connect(transport);
1301
+ connection.#state = "ready";
1302
+ return connection;
1303
+ } catch (error) {
1304
+ connection.#state = "failed";
1305
+ await connection.close();
1306
+ throw error;
1307
+ }
1308
+ }
1309
+ get state() {
1310
+ return this.#state;
1311
+ }
1312
+ get pid() {
1313
+ return 0;
1314
+ }
1315
+ async close() {
1316
+ if (this.#closePromise !== void 0) return this.#closePromise;
1317
+ this.#state = "closing";
1318
+ this.#closePromise = this.client.close().finally(() => {
1319
+ this.#state = "closed";
1320
+ });
1321
+ return this.#closePromise;
1322
+ }
1323
+ };
1324
+ //#endregion
1325
+ //#region src/mcp/stdio-connection.ts
1326
+ const DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4;
1327
+ const DEFAULT_STDERR_LIMIT_BYTES = 64 * 1024;
1328
+ var McpConnectionError = class extends Error {
1329
+ constructor(message, options) {
1330
+ super(message, options);
1331
+ this.name = "McpConnectionError";
1332
+ }
1333
+ };
1334
+ var McpStdioConnection = class McpStdioConnection {
1335
+ client;
1336
+ server;
1337
+ #state = "starting";
1338
+ #stderr = "";
1339
+ #closePromise;
1340
+ #stderrLimitBytes;
1341
+ #transport;
1342
+ constructor(server, transport, client, stderrLimitBytes) {
1343
+ this.server = server;
1344
+ this.#transport = transport;
1345
+ this.client = client;
1346
+ this.#stderrLimitBytes = stderrLimitBytes;
1347
+ transport.stderr?.on("data", (chunk) => {
1348
+ this.#appendStderr(chunk);
1349
+ });
1350
+ }
1351
+ static async open(server, options = {}) {
1352
+ const transport = new StdioClientTransport({
1353
+ command: server.command,
1354
+ args: server.args,
1355
+ env: {
1356
+ ...getDefaultEnvironment(),
1357
+ ...server.env
1358
+ },
1359
+ cwd: server.cwd,
1360
+ stderr: "pipe"
1361
+ });
1362
+ const client = new Client({
1363
+ name: "pi-acp",
1364
+ version: "0.5.0"
1365
+ });
1366
+ const connection = new McpStdioConnection(server, transport, client, options.stderrLimitBytes ?? DEFAULT_STDERR_LIMIT_BYTES);
1367
+ try {
1368
+ await client.connect(transport, { timeout: options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS });
1369
+ connection.#state = "ready";
1370
+ return connection;
1371
+ } catch (cause) {
1372
+ connection.#state = "failed";
1373
+ await connection.close();
1374
+ throw new McpConnectionError(`MCP server "${server.originalName}" failed to initialize${connection.#stderrSuffix()}`, { cause });
1375
+ }
1376
+ }
1377
+ get state() {
1378
+ return this.#state;
1379
+ }
1380
+ get pid() {
1381
+ return this.#transport.pid ?? 0;
1382
+ }
1383
+ get stderr() {
1384
+ return this.#stderr;
1385
+ }
1386
+ async close() {
1387
+ if (this.#closePromise !== void 0) return this.#closePromise;
1388
+ this.#state = "closing";
1389
+ this.#closePromise = this.client.close().finally(() => {
1390
+ this.#state = "closed";
1391
+ });
1392
+ return this.#closePromise;
1393
+ }
1394
+ #appendStderr(chunk) {
1395
+ let text;
1396
+ if (typeof chunk === "string") text = chunk;
1397
+ else if (chunk instanceof Uint8Array) text = Buffer.from(chunk).toString("utf8");
1398
+ else return;
1399
+ this.#stderr = `${this.#stderr}${text}`.slice(-this.#stderrLimitBytes);
1400
+ }
1401
+ #stderrSuffix() {
1402
+ const diagnostic = this.#stderr.trim();
1403
+ return diagnostic.length === 0 ? "" : `: ${diagnostic}`;
1404
+ }
1405
+ };
1406
+ //#endregion
1407
+ //#region src/mcp/session-manager.ts
1408
+ var McpSessionManager = class McpSessionManager {
1409
+ fingerprint;
1410
+ #state = "starting";
1411
+ #closePromise;
1412
+ #connections = /* @__PURE__ */ new Map();
1413
+ constructor(servers) {
1414
+ this.fingerprint = fingerprintMcpServers(servers);
1415
+ }
1416
+ static async open(servers, options = {}) {
1417
+ const manager = new McpSessionManager(servers);
1418
+ for (const server of servers) try {
1419
+ const connection = server.kind === "stdio" ? await McpStdioConnection.open(server, options.connection) : await McpHttpConnection.open(server);
1420
+ manager.#connections.set(server.stableName, connection);
1421
+ } catch (cause) {
1422
+ await manager.close();
1423
+ throw new McpConnectionError(`MCP session startup failed at server "${server.originalName}"`, { cause });
1424
+ }
1425
+ manager.#state = "ready";
1426
+ return manager;
1427
+ }
1428
+ get state() {
1429
+ return this.#state;
1430
+ }
1431
+ get connections() {
1432
+ return [...this.#connections.values()];
1433
+ }
1434
+ get(stableName) {
1435
+ const connection = this.#connections.get(stableName);
1436
+ if (connection === void 0) throw new McpConnectionError(`Unknown MCP server: ${stableName}`);
1437
+ return connection;
1438
+ }
1439
+ async close() {
1440
+ if (this.#closePromise !== void 0) return this.#closePromise;
1441
+ this.#state = "closing";
1442
+ this.#closePromise = Promise.allSettled([...this.#connections.values()].map((connection) => connection.close())).then(() => {
1443
+ this.#connections.clear();
1444
+ this.#state = "closed";
1445
+ });
1446
+ return this.#closePromise;
1447
+ }
1448
+ };
1449
+ //#endregion
1450
+ //#region src/mcp/tool-adapter.ts
1451
+ var McpToolExecutionError = class extends Error {
1452
+ serverName;
1453
+ toolName;
1454
+ constructor(serverName, toolName, message) {
1455
+ super(message);
1456
+ this.name = "McpToolExecutionError";
1457
+ this.serverName = serverName;
1458
+ this.toolName = toolName;
1459
+ }
1460
+ };
1461
+ function sanitizeToolNamePart(value) {
1462
+ return value.replaceAll(/[^A-Za-z0-9_]/g, "_");
1463
+ }
1464
+ function mcpToolName(serverName, toolName) {
1465
+ return `mcp__${sanitizeToolNamePart(serverName)}__${sanitizeToolNamePart(toolName)}`;
1466
+ }
1467
+ function validateUniqueMcpToolNames(tools) {
1468
+ const names = /* @__PURE__ */ new Set();
1469
+ for (const tool of tools) {
1470
+ const name = mcpToolName(tool.serverName, tool.toolName);
1471
+ if (names.has(name)) throw new McpToolExecutionError(tool.serverName, tool.toolName, `MCP tool name collision after sanitization: ${name}`);
1472
+ names.add(name);
1473
+ }
1474
+ }
1475
+ function mcpResultToPiContent(result) {
1476
+ const content = [];
1477
+ for (const block of result.content) switch (block.type) {
1478
+ case "text":
1479
+ content.push({
1480
+ type: "text",
1481
+ text: block.text
1482
+ });
1483
+ break;
1484
+ case "image":
1485
+ content.push({
1486
+ type: "image",
1487
+ data: block.data,
1488
+ mimeType: block.mimeType
1489
+ });
1490
+ break;
1491
+ case "audio":
1492
+ content.push({
1493
+ type: "text",
1494
+ text: `[MCP audio: ${block.mimeType}]`
1495
+ });
1496
+ break;
1497
+ case "resource_link":
1498
+ content.push({
1499
+ type: "text",
1500
+ text: `[MCP resource link: ${block.name}](${block.uri})`
1501
+ });
1502
+ break;
1503
+ case "resource":
1504
+ content.push({
1505
+ type: "text",
1506
+ text: "text" in block.resource ? `[MCP resource: ${block.resource.uri}]\n${block.resource.text}` : `[MCP binary resource: ${block.resource.uri}${block.resource.mimeType === void 0 ? "" : ` (${block.resource.mimeType})`}]`
1507
+ });
1508
+ break;
1509
+ }
1510
+ if (result.structuredContent !== void 0) content.push({
1511
+ type: "text",
1512
+ text: `[MCP structured content]\n${JSON.stringify(result.structuredContent)}`
1513
+ });
1514
+ return content;
1515
+ }
1516
+ function errorMessage(content) {
1517
+ const text = content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
1518
+ return text.length === 0 ? "MCP tool returned an error" : text;
1519
+ }
1520
+ async function invokeMcpTool(connection, toolName, arguments_, signal) {
1521
+ const rawResult = await connection.client.callTool({
1522
+ name: toolName,
1523
+ arguments: arguments_
1524
+ }, CallToolResultSchema, signal === void 0 ? void 0 : { signal });
1525
+ const result = CallToolResultSchema.parse(rawResult);
1526
+ const content = mcpResultToPiContent(result);
1527
+ if (result.isError === true) throw new McpToolExecutionError(connection.server.originalName, toolName, errorMessage(content));
1528
+ return {
1529
+ content,
1530
+ details: {
1531
+ serverName: connection.server.originalName,
1532
+ toolName,
1533
+ ...result.structuredContent === void 0 ? {} : { structuredContent: result.structuredContent }
1534
+ }
1535
+ };
1536
+ }
1537
+ async function buildMcpTools(manager) {
1538
+ const discovered = await Promise.all(manager.connections.map(async (connection) => ({
1539
+ connection,
1540
+ tools: (await connection.client.listTools()).tools
1541
+ })));
1542
+ validateUniqueMcpToolNames(discovered.flatMap(({ connection, tools }) => tools.map((tool) => ({
1543
+ serverName: connection.server.stableName,
1544
+ toolName: tool.name
1545
+ }))));
1546
+ return discovered.flatMap(({ connection, tools }) => tools.map((tool) => defineTool({
1547
+ name: mcpToolName(connection.server.stableName, tool.name),
1548
+ label: `${connection.server.originalName} / ${tool.name}`,
1549
+ description: tool.description ?? `MCP tool ${tool.name}`,
1550
+ parameters: Unsafe(tool.inputSchema),
1551
+ execute: async (_toolCallId, params, signal) => invokeMcpTool(connection, tool.name, params, signal)
1552
+ })));
1553
+ }
1554
+ //#endregion
1555
+ //#region package.json
1556
+ var name = "@ccgv2/pi-acp";
1557
+ var version = "0.5.0";
1558
+ //#endregion
1559
+ //#region src/acp/agent.ts
1560
+ function assertResumeMcpCompatible(existing, requested) {
1561
+ if (existing !== requested) throw RequestError.invalidParams("MCP configuration does not match the live session; close and load it with the new configuration");
1562
+ }
1563
+ /** Builtin ACP slash commands handled directly by the adapter. */
1564
+ const BUILTIN_COMMANDS = [
1565
+ {
1566
+ name: "compact",
1567
+ description: "Manually compact the session context",
1568
+ input: { hint: "optional custom instructions" }
1569
+ },
1570
+ {
1571
+ name: "autocompact",
1572
+ description: "Toggle automatic context compaction",
1573
+ input: { hint: "on|off|toggle" }
1574
+ },
1575
+ {
1576
+ name: "export",
1577
+ description: "Export session to an HTML file in the session cwd"
1578
+ },
1579
+ {
1580
+ name: "session",
1581
+ description: "Show session stats (messages, tokens, cost, session file)"
1582
+ },
1583
+ {
1584
+ name: "name",
1585
+ description: "Set session display name",
1586
+ input: { hint: "<name>" }
1587
+ },
1588
+ {
1589
+ name: "steering",
1590
+ description: "Get/set pi steering message delivery mode",
1591
+ input: { hint: "(no args to show) all | one-at-a-time" }
1592
+ },
1593
+ {
1594
+ name: "follow-up",
1595
+ description: "Get/set pi follow-up message delivery mode",
1596
+ input: { hint: "(no args to show) all | one-at-a-time" }
1597
+ },
1598
+ {
1599
+ name: "changelog",
1600
+ description: "Show pi changelog"
1601
+ }
1602
+ ];
1603
+ /**
1604
+ * Deduplicate commands by name. First occurrence wins.
1605
+ */
1606
+ function deduplicateCommands(commands) {
1607
+ const seen = /* @__PURE__ */ new Set();
1608
+ const out = [];
1609
+ for (const c of commands) {
1610
+ if (seen.has(c.name)) continue;
1611
+ seen.add(c.name);
1612
+ out.push(c);
1613
+ }
1614
+ return out;
1615
+ }
1616
+ function parseArgs(input) {
1617
+ const args = [];
1618
+ let current = "";
1619
+ let quote = null;
1620
+ for (const ch of input) if (quote !== null) if (ch === quote) quote = null;
1621
+ else current += ch;
1622
+ else if (ch === "\"" || ch === "'") quote = ch;
1623
+ else if (ch === " " || ch === " ") {
1624
+ if (current !== "") {
1625
+ args.push(current);
1626
+ current = "";
1627
+ }
1628
+ } else current += ch;
1629
+ if (current !== "") args.push(current);
1630
+ return args;
1631
+ }
1632
+ const SESSION_TITLE_MAX = 100;
1633
+ function truncateSessionTitle(text) {
1634
+ const trimmed = text.trim();
1635
+ if (trimmed === "") return null;
1636
+ const oneLine = trimmed.replace(/\n/g, " ");
1637
+ if (oneLine.length <= SESSION_TITLE_MAX) return oneLine;
1638
+ return `${oneLine.slice(0, SESSION_TITLE_MAX - 1)}…`;
1639
+ }
1640
+ var PiAcpAgent = class {
1641
+ conn;
1642
+ sessions = new SessionManager$1();
1643
+ createPiSession;
1644
+ mcpInitializeTimeoutMs;
1645
+ /** Cache of sessionId → file path, populated by listSessions and newSession. */
1646
+ sessionPaths = /* @__PURE__ */ new Map();
1647
+ /** Parsed client capability flags from initialize(). */
1648
+ clientCapabilities = {
1649
+ terminalOutput: false,
1650
+ terminalAuth: false,
1651
+ gatewayAuth: false
1652
+ };
1653
+ dispose() {
1654
+ this.sessions.disposeAll();
1655
+ }
1656
+ constructor(conn, config = {}) {
1657
+ this.conn = conn;
1658
+ this.createPiSession = config.createAgentSession ?? createAgentSession;
1659
+ this.mcpInitializeTimeoutMs = config.mcpInitializeTimeoutMs;
1660
+ }
1661
+ async initialize(params) {
1662
+ const supportedVersion = 1;
1663
+ const requested = params.protocolVersion;
1664
+ this.clientCapabilities = parseClientCapabilities(params.clientCapabilities);
1665
+ return {
1666
+ protocolVersion: requested === supportedVersion ? requested : supportedVersion,
1667
+ agentInfo: {
1668
+ name,
1669
+ title: "pi ACP adapter",
1670
+ version
1671
+ },
1672
+ authMethods: buildAuthMethods({ supportsTerminalAuthMeta: this.clientCapabilities.terminalAuth }),
1673
+ agentCapabilities: {
1674
+ loadSession: true,
1675
+ mcpCapabilities: {
1676
+ http: true,
1677
+ sse: false
1678
+ },
1679
+ promptCapabilities: {
1680
+ image: true,
1681
+ audio: false,
1682
+ embeddedContext: true
1683
+ },
1684
+ sessionCapabilities: {
1685
+ list: {},
1686
+ close: {},
1687
+ resume: {},
1688
+ fork: {}
1689
+ }
1690
+ }
1691
+ };
1692
+ }
1693
+ async newSession(params) {
1694
+ if (!isAbsolute(params.cwd)) throw RequestError.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
1695
+ const { manager: mcpManager, tools: customTools } = await this.openMcpRuntime(params.mcpServers, params.cwd);
1696
+ let result;
1697
+ try {
1698
+ result = await this.createPiSession({
1699
+ cwd: params.cwd,
1700
+ customTools
1701
+ });
1702
+ } catch (e) {
1703
+ await mcpManager.close();
1704
+ const authErr = detectAuthError(e);
1705
+ if (authErr !== null) throw authErr;
1706
+ const msg = e instanceof Error ? e.message : String(e);
1707
+ throw RequestError.internalError({}, `Failed to create pi session: ${msg}`);
1708
+ }
1709
+ const piSession = result.session;
1710
+ if (piSession.modelRegistry.getAvailable().length === 0) {
1711
+ piSession.dispose();
1712
+ throw RequestError.authRequired({ authMethods: buildAuthMethods() }, "Configure an API key or log in with an OAuth provider.");
1713
+ }
1714
+ const sessionId = piSession.sessionManager.getSessionId();
1715
+ const sessionFile = piSession.sessionManager.getSessionFile();
1716
+ if (sessionFile !== void 0) this.sessionPaths.set(sessionId, sessionFile);
1717
+ const session = new PiAcpSession({
1718
+ sessionId,
1719
+ cwd: params.cwd,
1720
+ mcpServers: params.mcpServers,
1721
+ piSession,
1722
+ mcpManager,
1723
+ conn: this.conn,
1724
+ supportsTerminalOutput: this.clientCapabilities.terminalOutput
1725
+ });
1726
+ this.sessions.register(session);
1727
+ const modes = buildThinkingModes(piSession);
1728
+ const models = buildModelState(piSession);
1729
+ const configOptions = buildConfigOptions(modes, models);
1730
+ const enableSkillCommands = skillCommandsEnabled(params.cwd);
1731
+ setTimeout(() => {
1732
+ (async () => {
1733
+ try {
1734
+ const commands = buildCommandList(piSession, enableSkillCommands);
1735
+ await this.conn.sessionUpdate({
1736
+ sessionId: session.sessionId,
1737
+ update: {
1738
+ sessionUpdate: "available_commands_update",
1739
+ availableCommands: deduplicateCommands([...commands, ...BUILTIN_COMMANDS])
1740
+ }
1741
+ });
1742
+ } catch {}
1743
+ })();
1744
+ }, 0);
1745
+ return {
1746
+ sessionId: session.sessionId,
1747
+ configOptions,
1748
+ modes,
1749
+ models
1750
+ };
1751
+ }
1752
+ async authenticate(_params) {
1753
+ return {};
1754
+ }
1755
+ async prompt(params) {
1756
+ const session = this.sessions.get(params.sessionId);
1757
+ const { message, images } = acpPromptToPiMessage(params.prompt);
1758
+ if (images.length === 0 && message.trimStart().startsWith("/")) {
1759
+ const trimmed = message.trim();
1760
+ const space = trimmed.indexOf(" ");
1761
+ const cmd = space === -1 ? trimmed.slice(1) : trimmed.slice(1, space);
1762
+ const args = parseArgs(space === -1 ? "" : trimmed.slice(space + 1));
1763
+ const handled = await this.handleBuiltinCommand(session, cmd, args);
1764
+ if (handled) return handled;
1765
+ }
1766
+ const result = await session.prompt(message, images);
1767
+ const stopReason = result === "error" ? "end_turn" : result;
1768
+ const usage = session.getUsage();
1769
+ const cost = session.getCost();
1770
+ return {
1771
+ stopReason,
1772
+ usage: {
1773
+ inputTokens: usage.inputTokens,
1774
+ outputTokens: usage.outputTokens,
1775
+ cachedReadTokens: usage.cachedReadTokens,
1776
+ cachedWriteTokens: usage.cachedWriteTokens,
1777
+ totalTokens: usage.inputTokens + usage.outputTokens
1778
+ },
1779
+ _meta: cost > 0 ? { cost: {
1780
+ amount: cost,
1781
+ currency: "USD"
1782
+ } } : {}
1783
+ };
1784
+ }
1785
+ async cancel(params) {
1786
+ await this.sessions.get(params.sessionId).cancel();
1787
+ }
1788
+ /**
1789
+ * Resolve a session ID to a file path.
1790
+ * Checks the local cache first (populated by listSessions/newSession),
1791
+ * falls back to a full listAll() scan on cache miss.
1792
+ */
1793
+ async resolveSessionFile(sessionId) {
1794
+ const cached = this.sessionPaths.get(sessionId);
1795
+ if (cached !== void 0) return cached;
1796
+ const all = await SessionManager.listAll();
1797
+ for (const s of all) this.sessionPaths.set(s.id, s.path);
1798
+ return this.sessionPaths.get(sessionId) ?? null;
1799
+ }
1800
+ /**
1801
+ * Replay persisted session messages as ACP session updates.
1802
+ *
1803
+ * Iterates through the message history, emitting structured updates for each
1804
+ * content block type: text, thinking, tool calls, and tool results. A map of
1805
+ * tool call IDs to their invocation data (from assistant messages) is built
1806
+ * to enrich subsequent tool result updates with rawInput and locations.
1807
+ */
1808
+ async replaySessionHistory(session, messages) {
1809
+ const toolCallMap = /* @__PURE__ */ new Map();
1810
+ for (const m of messages) {
1811
+ if (!("role" in m)) continue;
1812
+ if (m.role === "user") {
1813
+ const text = extractUserMessageText(m.content);
1814
+ if (text) await this.conn.sessionUpdate({
1815
+ sessionId: session.sessionId,
1816
+ update: {
1817
+ sessionUpdate: "user_message_chunk",
1818
+ content: {
1819
+ type: "text",
1820
+ text
1821
+ }
1822
+ }
1823
+ });
1824
+ continue;
1825
+ }
1826
+ if (m.role === "assistant") {
1827
+ const am = m;
1828
+ for (const block of am.content) if (block.type === "text" && block.text) await this.conn.sessionUpdate({
1829
+ sessionId: session.sessionId,
1830
+ update: {
1831
+ sessionUpdate: "agent_message_chunk",
1832
+ content: {
1833
+ type: "text",
1834
+ text: block.text
1835
+ }
1836
+ }
1837
+ });
1838
+ else if (block.type === "thinking" && block.thinking) await this.conn.sessionUpdate({
1839
+ sessionId: session.sessionId,
1840
+ update: {
1841
+ sessionUpdate: "agent_thought_chunk",
1842
+ content: {
1843
+ type: "text",
1844
+ text: block.thinking
1845
+ }
1846
+ }
1847
+ });
1848
+ else if (block.type === "toolCall") {
1849
+ const args = toToolArgs(block.arguments);
1850
+ toolCallMap.set(block.id, {
1851
+ name: block.name,
1852
+ args
1853
+ });
1854
+ const locations = resolveToolPath(args, session.cwd);
1855
+ await this.conn.sessionUpdate({
1856
+ sessionId: session.sessionId,
1857
+ update: {
1858
+ sessionUpdate: "tool_call",
1859
+ toolCallId: block.id,
1860
+ title: buildToolTitle(block.name, args),
1861
+ kind: toToolKind(block.name),
1862
+ status: "completed",
1863
+ rawInput: args,
1864
+ ...locations ? { locations } : {},
1865
+ _meta: { piAcp: { toolName: block.name } }
1866
+ }
1867
+ });
1868
+ }
1869
+ continue;
1870
+ }
1871
+ if (m.role === "toolResult") {
1872
+ const tr = m;
1873
+ const toolName = tr.toolName;
1874
+ const toolCallId = tr.toolCallId;
1875
+ const isError = tr.isError;
1876
+ const invocation = toolCallMap.get(toolCallId);
1877
+ const args = invocation?.args;
1878
+ const locations = args !== void 0 ? resolveToolPath(args, session.cwd) : void 0;
1879
+ if (invocation === void 0) await this.conn.sessionUpdate({
1880
+ sessionId: session.sessionId,
1881
+ update: {
1882
+ sessionUpdate: "tool_call",
1883
+ toolCallId,
1884
+ title: buildToolTitle(toolName, {}),
1885
+ kind: toToolKind(toolName),
1886
+ status: "completed",
1887
+ rawInput: null,
1888
+ rawOutput: m,
1889
+ _meta: { piAcp: { toolName } }
1890
+ }
1891
+ });
1892
+ const content = formatToolContent(toolName, m, isError);
1893
+ await this.conn.sessionUpdate({
1894
+ sessionId: session.sessionId,
1895
+ update: {
1896
+ sessionUpdate: "tool_call_update",
1897
+ toolCallId,
1898
+ status: isError ? "failed" : "completed",
1899
+ content: content.length > 0 ? content : null,
1900
+ rawOutput: m,
1901
+ ...locations ? { locations } : {},
1902
+ _meta: { piAcp: { toolName } }
1903
+ }
1904
+ });
1905
+ }
1906
+ }
1907
+ }
1908
+ async listSessions(params) {
1909
+ const cwd = params.cwd;
1910
+ const raw = cwd !== void 0 && cwd !== null ? await SessionManager.list(cwd) : await SessionManager.listAll();
1911
+ for (const s of raw) this.sessionPaths.set(s.id, s.path);
1912
+ const sessions = raw.map((s) => ({
1913
+ id: s.id,
1914
+ cwd: s.cwd,
1915
+ name: s.name,
1916
+ firstMessage: s.firstMessage,
1917
+ modified: s.modified,
1918
+ messageCount: s.messageCount
1919
+ }));
1920
+ if (params.cursor !== void 0 && params.cursor !== null) {
1921
+ const parsed = Number.parseInt(params.cursor, 10);
1922
+ if (!Number.isFinite(parsed) || parsed < 0) throw RequestError.invalidParams(`Invalid cursor: ${params.cursor}`);
1923
+ }
1924
+ const start = params.cursor !== void 0 && params.cursor !== null ? Number.parseInt(params.cursor, 10) : 0;
1925
+ const PAGE_SIZE = 50;
1926
+ return {
1927
+ sessions: sessions.slice(start, start + PAGE_SIZE).map((s) => ({
1928
+ sessionId: s.id,
1929
+ cwd: s.cwd,
1930
+ title: (s.name !== void 0 && s.name !== "" ? s.name : null) ?? truncateSessionTitle(s.firstMessage) ?? null,
1931
+ updatedAt: s.modified.toISOString()
1932
+ })),
1933
+ nextCursor: start + PAGE_SIZE < sessions.length ? String(start + PAGE_SIZE) : null,
1934
+ _meta: {}
1935
+ };
1936
+ }
1937
+ async loadSession(params) {
1938
+ if (!isAbsolute(params.cwd)) throw RequestError.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
1939
+ await this.sessions.closeAsync(params.sessionId);
1940
+ const sessionFile = await this.resolveSessionFile(params.sessionId);
1941
+ if (sessionFile === null) throw RequestError.invalidParams(`Unknown sessionId: ${params.sessionId}`);
1942
+ const { manager: mcpManager, tools: customTools } = await this.openMcpRuntime(params.mcpServers, params.cwd);
1943
+ let result;
1944
+ try {
1945
+ const sm = SessionManager.open(sessionFile);
1946
+ result = await this.createPiSession({
1947
+ cwd: params.cwd,
1948
+ sessionManager: sm,
1949
+ customTools
1950
+ });
1951
+ } catch (e) {
1952
+ await mcpManager.close();
1953
+ const authErr = detectAuthError(e);
1954
+ if (authErr !== null) throw authErr;
1955
+ const msg = e instanceof Error ? e.message : String(e);
1956
+ throw RequestError.internalError({}, `Failed to load pi session: ${msg}`);
1957
+ }
1958
+ const piSession = result.session;
1959
+ const session = new PiAcpSession({
1960
+ sessionId: params.sessionId,
1961
+ cwd: params.cwd,
1962
+ mcpServers: params.mcpServers,
1963
+ piSession,
1964
+ mcpManager,
1965
+ conn: this.conn,
1966
+ supportsTerminalOutput: this.clientCapabilities.terminalOutput
1967
+ });
1968
+ this.sessions.register(session);
1969
+ await this.replaySessionHistory(session, piSession.messages);
1970
+ const modes = buildThinkingModes(piSession);
1971
+ const models = buildModelState(piSession);
1972
+ const configOptions = buildConfigOptions(modes, models);
1973
+ const enableSkillCommands = skillCommandsEnabled(params.cwd);
1974
+ setTimeout(() => {
1975
+ (async () => {
1976
+ try {
1977
+ const commands = buildCommandList(piSession, enableSkillCommands);
1978
+ await this.conn.sessionUpdate({
1979
+ sessionId: session.sessionId,
1980
+ update: {
1981
+ sessionUpdate: "available_commands_update",
1982
+ availableCommands: deduplicateCommands([...commands, ...BUILTIN_COMMANDS])
1983
+ }
1984
+ });
1985
+ } catch {}
1986
+ })();
1987
+ }, 0);
1988
+ return {
1989
+ configOptions,
1990
+ modes,
1991
+ models
1992
+ };
1993
+ }
1994
+ async closeSession(params) {
1995
+ if (this.sessions.maybeGet(params.sessionId) === void 0) throw RequestError.invalidParams(`Unknown sessionId: ${params.sessionId}`);
1996
+ await this.sessions.closeAsync(params.sessionId);
1997
+ return {};
1998
+ }
1999
+ async resumeSession(params) {
2000
+ if (!isAbsolute(params.cwd)) throw RequestError.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2001
+ const existing = this.sessions.maybeGet(params.sessionId);
2002
+ if (existing !== void 0) {
2003
+ if (params.mcpServers !== void 0) {
2004
+ const requestedFingerprint = fingerprintMcpServers(normalizeMcpServers(params.mcpServers, params.cwd));
2005
+ assertResumeMcpCompatible(existing.mcpFingerprint, requestedFingerprint);
2006
+ }
2007
+ const modes = buildThinkingModes(existing.piSession);
2008
+ const models = buildModelState(existing.piSession);
2009
+ return {
2010
+ configOptions: buildConfigOptions(modes, models),
2011
+ modes,
2012
+ models
2013
+ };
2014
+ }
2015
+ const sessionFile = await this.resolveSessionFile(params.sessionId);
2016
+ if (sessionFile === null) throw RequestError.invalidParams(`Unknown sessionId: ${params.sessionId}`);
2017
+ const resumeMcpServers = params.mcpServers ?? [];
2018
+ const { manager: mcpManager, tools: customTools } = await this.openMcpRuntime(resumeMcpServers, params.cwd);
2019
+ let result;
2020
+ try {
2021
+ const sm = SessionManager.open(sessionFile);
2022
+ result = await this.createPiSession({
2023
+ cwd: params.cwd,
2024
+ sessionManager: sm,
2025
+ customTools
2026
+ });
2027
+ } catch (e) {
2028
+ await mcpManager.close();
2029
+ const authErr = detectAuthError(e);
2030
+ if (authErr !== null) throw authErr;
2031
+ const msg = e instanceof Error ? e.message : String(e);
2032
+ throw RequestError.internalError({}, `Failed to resume pi session: ${msg}`);
2033
+ }
2034
+ const piSession = result.session;
2035
+ const session = new PiAcpSession({
2036
+ sessionId: params.sessionId,
2037
+ cwd: params.cwd,
2038
+ mcpServers: resumeMcpServers,
2039
+ piSession,
2040
+ mcpManager,
2041
+ conn: this.conn,
2042
+ supportsTerminalOutput: this.clientCapabilities.terminalOutput
2043
+ });
2044
+ this.sessions.register(session);
2045
+ this.sessionPaths.set(params.sessionId, sessionFile);
2046
+ const enableSkillCommands = skillCommandsEnabled(params.cwd);
2047
+ setTimeout(() => {
2048
+ (async () => {
2049
+ try {
2050
+ const commands = buildCommandList(piSession, enableSkillCommands);
2051
+ await this.conn.sessionUpdate({
2052
+ sessionId: session.sessionId,
2053
+ update: {
2054
+ sessionUpdate: "available_commands_update",
2055
+ availableCommands: deduplicateCommands([...commands, ...BUILTIN_COMMANDS])
2056
+ }
2057
+ });
2058
+ } catch {}
2059
+ })();
2060
+ }, 0);
2061
+ const modes = buildThinkingModes(piSession);
2062
+ const models = buildModelState(piSession);
2063
+ return {
2064
+ configOptions: buildConfigOptions(modes, models),
2065
+ modes,
2066
+ models
2067
+ };
2068
+ }
2069
+ async unstable_forkSession(params) {
2070
+ if (!isAbsolute(params.cwd)) throw RequestError.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2071
+ const sourceFile = await this.resolveSessionFile(params.sessionId);
2072
+ if (sourceFile === null) throw RequestError.invalidParams(`Unknown sessionId: ${params.sessionId}`);
2073
+ const forkMcpServers = params.mcpServers ?? [];
2074
+ const { manager: mcpManager, tools: customTools } = await this.openMcpRuntime(forkMcpServers, params.cwd);
2075
+ let result;
2076
+ try {
2077
+ const sm = SessionManager.forkFrom(sourceFile, params.cwd);
2078
+ result = await this.createPiSession({
2079
+ cwd: params.cwd,
2080
+ sessionManager: sm,
2081
+ customTools
2082
+ });
2083
+ } catch (e) {
2084
+ await mcpManager.close();
2085
+ const authErr = detectAuthError(e);
2086
+ if (authErr !== null) throw authErr;
2087
+ const msg = e instanceof Error ? e.message : String(e);
2088
+ throw RequestError.internalError({}, `Failed to fork pi session: ${msg}`);
2089
+ }
2090
+ const piSession = result.session;
2091
+ const newSessionId = piSession.sessionManager.getSessionId();
2092
+ const newSessionFile = piSession.sessionManager.getSessionFile();
2093
+ if (newSessionFile !== void 0) this.sessionPaths.set(newSessionId, newSessionFile);
2094
+ const session = new PiAcpSession({
2095
+ sessionId: newSessionId,
2096
+ cwd: params.cwd,
2097
+ mcpServers: forkMcpServers,
2098
+ piSession,
2099
+ mcpManager,
2100
+ conn: this.conn,
2101
+ supportsTerminalOutput: this.clientCapabilities.terminalOutput
2102
+ });
2103
+ this.sessions.register(session);
2104
+ const enableSkillCommands = skillCommandsEnabled(params.cwd);
2105
+ setTimeout(() => {
2106
+ (async () => {
2107
+ try {
2108
+ const commands = buildCommandList(piSession, enableSkillCommands);
2109
+ await this.conn.sessionUpdate({
2110
+ sessionId: session.sessionId,
2111
+ update: {
2112
+ sessionUpdate: "available_commands_update",
2113
+ availableCommands: deduplicateCommands([...commands, ...BUILTIN_COMMANDS])
2114
+ }
2115
+ });
2116
+ } catch {}
2117
+ })();
2118
+ }, 0);
2119
+ const modes = buildThinkingModes(piSession);
2120
+ const models = buildModelState(piSession);
2121
+ return {
2122
+ sessionId: newSessionId,
2123
+ configOptions: buildConfigOptions(modes, models),
2124
+ modes,
2125
+ models
2126
+ };
2127
+ }
2128
+ async openMcpRuntime(mcpServers, cwd) {
2129
+ let manager;
2130
+ try {
2131
+ const normalized = normalizeMcpServers(mcpServers, cwd);
2132
+ manager = await McpSessionManager.open(normalized, this.mcpInitializeTimeoutMs === void 0 ? {} : { connection: { initializeTimeoutMs: this.mcpInitializeTimeoutMs } });
2133
+ return {
2134
+ manager,
2135
+ tools: await buildMcpTools(manager)
2136
+ };
2137
+ } catch (error) {
2138
+ await manager?.close();
2139
+ const message = error instanceof Error ? error.message : "Invalid MCP server configuration";
2140
+ throw RequestError.invalidParams(message);
2141
+ }
2142
+ }
2143
+ async setSessionMode(params) {
2144
+ const session = this.sessions.get(params.sessionId);
2145
+ const mode = String(params.modeId);
2146
+ if (!isThinkingLevel(mode)) throw RequestError.invalidParams(`Unknown modeId: ${mode}`);
2147
+ session.piSession.setThinkingLevel(mode);
2148
+ this.conn.sessionUpdate({
2149
+ sessionId: session.sessionId,
2150
+ update: {
2151
+ sessionUpdate: "current_mode_update",
2152
+ currentModeId: mode
2153
+ }
2154
+ });
2155
+ this.emitConfigOptionUpdate(session);
2156
+ return {};
2157
+ }
2158
+ async unstable_setSessionModel(params) {
2159
+ const session = this.sessions.get(params.sessionId);
2160
+ const available = session.piSession.modelRegistry.getAvailable();
2161
+ const resolved = resolveModelPreference(available, params.modelId);
2162
+ if (resolved === null) throw RequestError.invalidParams(`Unknown modelId: ${params.modelId}`);
2163
+ const model = available.find((m) => m.provider === resolved.provider && m.id === resolved.id);
2164
+ if (!model) throw RequestError.invalidParams(`Unknown modelId: ${params.modelId}`);
2165
+ await session.piSession.setModel(model);
2166
+ this.emitConfigOptionUpdate(session);
2167
+ }
2168
+ async setSessionConfigOption(params) {
2169
+ const session = this.sessions.get(params.sessionId);
2170
+ const configId = String(params.configId);
2171
+ const value = String(params.value);
2172
+ if (configId === "model") {
2173
+ const available = session.piSession.modelRegistry.getAvailable();
2174
+ const resolved = resolveModelPreference(available, value);
2175
+ if (resolved === null) throw RequestError.invalidParams(`Unknown model: ${value}`);
2176
+ const model = available.find((m) => m.provider === resolved.provider && m.id === resolved.id);
2177
+ if (!model) throw RequestError.invalidParams(`Unknown model: ${value}`);
2178
+ await session.piSession.setModel(model);
2179
+ } else if (configId === "thought_level") {
2180
+ if (!isThinkingLevel(value)) throw RequestError.invalidParams(`Unknown thinking level: ${value}`);
2181
+ session.piSession.setThinkingLevel(value);
2182
+ } else throw RequestError.invalidParams(`Unknown config option: ${configId}`);
2183
+ return { configOptions: buildConfigOptions(buildThinkingModes(session.piSession), buildModelState(session.piSession)) };
2184
+ }
2185
+ emitConfigOptionUpdate(session) {
2186
+ const configOptions = buildConfigOptions(buildThinkingModes(session.piSession), buildModelState(session.piSession));
2187
+ this.conn.sessionUpdate({
2188
+ sessionId: session.sessionId,
2189
+ update: {
2190
+ sessionUpdate: "config_option_update",
2191
+ configOptions
2192
+ }
2193
+ });
2194
+ }
2195
+ async handleBuiltinCommand(session, cmd, args) {
2196
+ const piSession = session.piSession;
2197
+ if (cmd === "compact") {
2198
+ const customInstructions = args.join(" ").trim() || void 0;
2199
+ const res = await piSession.compact(customInstructions);
2200
+ const text = [`Compaction completed.${customInstructions !== void 0 && customInstructions !== "" ? " (custom instructions applied)" : ""}`, typeof res?.tokensBefore === "number" ? `Tokens before: ${res.tokensBefore}` : null].filter(Boolean).join("\n") + (res?.summary ? `\n\n${res.summary}` : "");
2201
+ await this.conn.sessionUpdate({
2202
+ sessionId: session.sessionId,
2203
+ update: {
2204
+ sessionUpdate: "agent_message_chunk",
2205
+ content: {
2206
+ type: "text",
2207
+ text
2208
+ }
2209
+ }
2210
+ });
2211
+ return { stopReason: "end_turn" };
2212
+ }
2213
+ if (cmd === "session") {
2214
+ const stats = piSession.getSessionStats();
2215
+ const lines = [];
2216
+ if (stats.sessionId !== void 0 && stats.sessionId !== "") lines.push(`Session: ${stats.sessionId}`);
2217
+ if (stats.sessionFile !== void 0 && stats.sessionFile !== "") lines.push(`Session file: ${stats.sessionFile}`);
2218
+ lines.push(`Messages: ${stats.totalMessages}`);
2219
+ lines.push(`Cost: ${stats.cost}`);
2220
+ const t = stats.tokens;
2221
+ const parts = [];
2222
+ if (t.input) parts.push(`in ${t.input}`);
2223
+ if (t.output) parts.push(`out ${t.output}`);
2224
+ if (t.cacheRead) parts.push(`cache read ${t.cacheRead}`);
2225
+ if (t.cacheWrite) parts.push(`cache write ${t.cacheWrite}`);
2226
+ if (t.total) parts.push(`total ${t.total}`);
2227
+ if (parts.length > 0) lines.push(`Tokens: ${parts.join(", ")}`);
2228
+ const text = lines.join("\n");
2229
+ await this.conn.sessionUpdate({
2230
+ sessionId: session.sessionId,
2231
+ update: {
2232
+ sessionUpdate: "agent_message_chunk",
2233
+ content: {
2234
+ type: "text",
2235
+ text
2236
+ }
2237
+ }
2238
+ });
2239
+ return { stopReason: "end_turn" };
2240
+ }
2241
+ if (cmd === "name") {
2242
+ const name = args.join(" ").trim();
2243
+ if (!name) {
2244
+ await this.conn.sessionUpdate({
2245
+ sessionId: session.sessionId,
2246
+ update: {
2247
+ sessionUpdate: "agent_message_chunk",
2248
+ content: {
2249
+ type: "text",
2250
+ text: "Usage: /name <name>"
2251
+ }
2252
+ }
2253
+ });
2254
+ return { stopReason: "end_turn" };
2255
+ }
2256
+ piSession.setSessionName(name);
2257
+ await this.conn.sessionUpdate({
2258
+ sessionId: session.sessionId,
2259
+ update: {
2260
+ sessionUpdate: "session_info_update",
2261
+ title: name,
2262
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2263
+ }
2264
+ });
2265
+ await this.conn.sessionUpdate({
2266
+ sessionId: session.sessionId,
2267
+ update: {
2268
+ sessionUpdate: "agent_message_chunk",
2269
+ content: {
2270
+ type: "text",
2271
+ text: `Session name set: ${name}`
2272
+ }
2273
+ }
2274
+ });
2275
+ return { stopReason: "end_turn" };
2276
+ }
2277
+ if (cmd === "steering") {
2278
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2279
+ if (!modeRaw) {
2280
+ await this.conn.sessionUpdate({
2281
+ sessionId: session.sessionId,
2282
+ update: {
2283
+ sessionUpdate: "agent_message_chunk",
2284
+ content: {
2285
+ type: "text",
2286
+ text: `Steering mode: ${piSession.steeringMode}`
2287
+ }
2288
+ }
2289
+ });
2290
+ return { stopReason: "end_turn" };
2291
+ }
2292
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2293
+ await this.conn.sessionUpdate({
2294
+ sessionId: session.sessionId,
2295
+ update: {
2296
+ sessionUpdate: "agent_message_chunk",
2297
+ content: {
2298
+ type: "text",
2299
+ text: "Usage: /steering all | /steering one-at-a-time"
2300
+ }
2301
+ }
2302
+ });
2303
+ return { stopReason: "end_turn" };
2304
+ }
2305
+ piSession.setSteeringMode(modeRaw);
2306
+ await this.conn.sessionUpdate({
2307
+ sessionId: session.sessionId,
2308
+ update: {
2309
+ sessionUpdate: "agent_message_chunk",
2310
+ content: {
2311
+ type: "text",
2312
+ text: `Steering mode set to: ${modeRaw}`
2313
+ }
2314
+ }
2315
+ });
2316
+ return { stopReason: "end_turn" };
2317
+ }
2318
+ if (cmd === "follow-up") {
2319
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2320
+ if (!modeRaw) {
2321
+ await this.conn.sessionUpdate({
2322
+ sessionId: session.sessionId,
2323
+ update: {
2324
+ sessionUpdate: "agent_message_chunk",
2325
+ content: {
2326
+ type: "text",
2327
+ text: `Follow-up mode: ${piSession.followUpMode}`
2328
+ }
2329
+ }
2330
+ });
2331
+ return { stopReason: "end_turn" };
2332
+ }
2333
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2334
+ await this.conn.sessionUpdate({
2335
+ sessionId: session.sessionId,
2336
+ update: {
2337
+ sessionUpdate: "agent_message_chunk",
2338
+ content: {
2339
+ type: "text",
2340
+ text: "Usage: /follow-up all | /follow-up one-at-a-time"
2341
+ }
2342
+ }
2343
+ });
2344
+ return { stopReason: "end_turn" };
2345
+ }
2346
+ piSession.setFollowUpMode(modeRaw);
2347
+ await this.conn.sessionUpdate({
2348
+ sessionId: session.sessionId,
2349
+ update: {
2350
+ sessionUpdate: "agent_message_chunk",
2351
+ content: {
2352
+ type: "text",
2353
+ text: `Follow-up mode set to: ${modeRaw}`
2354
+ }
2355
+ }
2356
+ });
2357
+ return { stopReason: "end_turn" };
2358
+ }
2359
+ if (cmd === "autocompact") {
2360
+ const mode = (args[0] ?? "toggle").toLowerCase();
2361
+ let enabled = null;
2362
+ if (mode === "on" || mode === "true" || mode === "enable") enabled = true;
2363
+ else if (mode === "off" || mode === "false" || mode === "disable") enabled = false;
2364
+ if (enabled === null) enabled = !piSession.autoCompactionEnabled;
2365
+ piSession.setAutoCompactionEnabled(enabled);
2366
+ await this.conn.sessionUpdate({
2367
+ sessionId: session.sessionId,
2368
+ update: {
2369
+ sessionUpdate: "agent_message_chunk",
2370
+ content: {
2371
+ type: "text",
2372
+ text: `Auto-compaction ${enabled ? "enabled" : "disabled"}.`
2373
+ }
2374
+ }
2375
+ });
2376
+ return { stopReason: "end_turn" };
2377
+ }
2378
+ if (cmd === "changelog") {
2379
+ const changelogPath = findChangelog();
2380
+ if (changelogPath === null) {
2381
+ await this.conn.sessionUpdate({
2382
+ sessionId: session.sessionId,
2383
+ update: {
2384
+ sessionUpdate: "agent_message_chunk",
2385
+ content: {
2386
+ type: "text",
2387
+ text: "Changelog not found."
2388
+ }
2389
+ }
2390
+ });
2391
+ return { stopReason: "end_turn" };
2392
+ }
2393
+ let text = "";
2394
+ try {
2395
+ text = readFileSync(changelogPath, "utf-8");
2396
+ } catch (e) {
2397
+ const msg = e instanceof Error ? e.message : String(e);
2398
+ await this.conn.sessionUpdate({
2399
+ sessionId: session.sessionId,
2400
+ update: {
2401
+ sessionUpdate: "agent_message_chunk",
2402
+ content: {
2403
+ type: "text",
2404
+ text: `Failed to read changelog: ${msg}`
2405
+ }
2406
+ }
2407
+ });
2408
+ return { stopReason: "end_turn" };
2409
+ }
2410
+ const maxChars = 2e4;
2411
+ if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n\n...(truncated)...`;
2412
+ await this.conn.sessionUpdate({
2413
+ sessionId: session.sessionId,
2414
+ update: {
2415
+ sessionUpdate: "agent_message_chunk",
2416
+ content: {
2417
+ type: "text",
2418
+ text
2419
+ }
2420
+ }
2421
+ });
2422
+ return { stopReason: "end_turn" };
2423
+ }
2424
+ if (cmd === "export") {
2425
+ if (piSession.messages.length === 0) {
2426
+ await this.conn.sessionUpdate({
2427
+ sessionId: session.sessionId,
2428
+ update: {
2429
+ sessionUpdate: "agent_message_chunk",
2430
+ content: {
2431
+ type: "text",
2432
+ text: "Nothing to export yet. Send a prompt first."
2433
+ }
2434
+ }
2435
+ });
2436
+ return { stopReason: "end_turn" };
2437
+ }
2438
+ try {
2439
+ const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
2440
+ const outputPath = join(session.cwd, `pi-session-${safeSessionId}.html`);
2441
+ const resultPath = await piSession.exportToHtml(outputPath);
2442
+ await this.conn.sessionUpdate({
2443
+ sessionId: session.sessionId,
2444
+ update: {
2445
+ sessionUpdate: "agent_message_chunk",
2446
+ content: {
2447
+ type: "text",
2448
+ text: "Session exported: "
2449
+ }
2450
+ }
2451
+ });
2452
+ await this.conn.sessionUpdate({
2453
+ sessionId: session.sessionId,
2454
+ update: {
2455
+ sessionUpdate: "agent_message_chunk",
2456
+ content: {
2457
+ type: "resource_link",
2458
+ name: `pi-session-${safeSessionId}.html`,
2459
+ uri: `file://${resultPath}`,
2460
+ mimeType: "text/html",
2461
+ title: "Session exported"
2462
+ }
2463
+ }
2464
+ });
2465
+ } catch (e) {
2466
+ const msg = e instanceof Error ? e.message : String(e);
2467
+ await this.conn.sessionUpdate({
2468
+ sessionId: session.sessionId,
2469
+ update: {
2470
+ sessionUpdate: "agent_message_chunk",
2471
+ content: {
2472
+ type: "text",
2473
+ text: `Export failed: ${msg}`
2474
+ }
2475
+ }
2476
+ });
2477
+ }
2478
+ return { stopReason: "end_turn" };
2479
+ }
2480
+ return null;
2481
+ }
2482
+ };
2483
+ function isThinkingLevel(x) {
2484
+ return x === "off" || x === "minimal" || x === "low" || x === "medium" || x === "high" || x === "xhigh";
2485
+ }
2486
+ function buildThinkingModes(piSession) {
2487
+ const levels = piSession.getAvailableThinkingLevels();
2488
+ return {
2489
+ currentModeId: piSession.thinkingLevel,
2490
+ availableModes: levels.map((id) => ({
2491
+ id,
2492
+ name: `Thinking: ${id}`,
2493
+ description: null
2494
+ }))
2495
+ };
2496
+ }
2497
+ function buildModelState(piSession) {
2498
+ const available = piSession.modelRegistry.getAvailable();
2499
+ const current = piSession.model;
2500
+ const availableModels = available.map((m) => ({
2501
+ modelId: `${m.provider}/${m.id}`,
2502
+ name: `${m.provider}/${m.name ?? m.id}`,
2503
+ description: null
2504
+ }));
2505
+ let currentModelId = "default";
2506
+ if (current !== void 0) currentModelId = `${current.provider}/${current.id}`;
2507
+ else if (availableModels.length > 0 && availableModels[0] !== void 0) currentModelId = availableModels[0].modelId;
2508
+ return {
2509
+ availableModels,
2510
+ currentModelId
2511
+ };
2512
+ }
2513
+ function buildConfigOptions(modes, models) {
2514
+ return [{
2515
+ id: "model",
2516
+ name: "Model",
2517
+ description: "AI model to use",
2518
+ category: "model",
2519
+ type: "select",
2520
+ currentValue: models.currentModelId,
2521
+ options: models.availableModels.map((m) => ({
2522
+ value: m.modelId,
2523
+ name: m.name,
2524
+ description: m.description ?? null
2525
+ }))
2526
+ }, {
2527
+ id: "thought_level",
2528
+ name: "Thinking Level",
2529
+ description: "Reasoning depth for models that support it",
2530
+ category: "thought_level",
2531
+ type: "select",
2532
+ currentValue: modes.currentModeId,
2533
+ options: modes.availableModes.map((m) => ({
2534
+ value: m.id,
2535
+ name: m.name,
2536
+ description: m.description ?? null
2537
+ }))
2538
+ }];
2539
+ }
2540
+ function buildCommandList(piSession, enableSkillCommands) {
2541
+ const commands = [];
2542
+ for (const template of piSession.promptTemplates) commands.push({
2543
+ name: template.name,
2544
+ description: template.description ?? `(prompt)`
2545
+ });
2546
+ if (enableSkillCommands) {
2547
+ const skills = piSession.resourceLoader.getSkills();
2548
+ for (const skill of skills.skills) commands.push({
2549
+ name: `skill:${skill.name}`,
2550
+ description: skill.description ?? `(skill)`
2551
+ });
2552
+ }
2553
+ for (const cmd of piSession.extensionRunner.getRegisteredCommands()) commands.push({
2554
+ name: cmd.name,
2555
+ description: cmd.description ?? "(extension)"
2556
+ });
2557
+ return commands;
2558
+ }
2559
+ function findChangelog() {
2560
+ try {
2561
+ const which = spawnSync(process.platform === "win32" ? "where" : "which", ["pi"], { encoding: "utf-8" });
2562
+ const piPath = String(which.stdout ?? "").split(/\r?\n/)[0]?.trim();
2563
+ if (piPath !== void 0 && piPath !== "") {
2564
+ const p = join(dirname(dirname(realpathSync(piPath))), "CHANGELOG.md");
2565
+ if (existsSync(p)) return p;
2566
+ }
2567
+ } catch {}
2568
+ try {
2569
+ const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
2570
+ const root = String(npmRoot.stdout ?? "").trim();
2571
+ if (root) {
2572
+ const p = join(root, "@mariozechner", "pi-coding-agent", "CHANGELOG.md");
2573
+ if (existsSync(p)) return p;
2574
+ }
2575
+ } catch {}
2576
+ return null;
2577
+ }
2578
+ //#endregion
2579
+ //#region src/index.ts
2580
+ {
2581
+ const toStderr = (...args) => {
2582
+ process.stderr.write(`${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}\n`);
2583
+ };
2584
+ console.log = toStderr;
2585
+ console.info = toStderr;
2586
+ console.warn = toStderr;
2587
+ console.debug = toStderr;
2588
+ }
2589
+ if (process.argv.includes("--terminal-login")) {
2590
+ const { spawnSync } = await import("node:child_process");
2591
+ const isWindows = platform() === "win32";
2592
+ const cmd = process.env.PI_ACP_PI_COMMAND ?? (isWindows ? "pi.cmd" : "pi");
2593
+ const res = spawnSync(cmd, [], {
2594
+ stdio: "inherit",
2595
+ env: process.env
2596
+ });
2597
+ if (res.error && "code" in res.error && res.error.code === "ENOENT") {
2598
+ process.stderr.write(`pi-acp: could not start pi (command not found: ${cmd}). Install via \`npm install -g @earendil-works/pi-coding-agent\` or ensure \`pi\` is on your PATH.
2599
+ `);
2600
+ process.exit(1);
2601
+ }
2602
+ process.exit(typeof res.status === "number" ? res.status : 1);
2603
+ }
2604
+ const agent = new AgentSideConnection((conn) => new PiAcpAgent(conn), ndJsonStream(new WritableStream({ write(chunk) {
2605
+ return new Promise((resolve) => {
2606
+ if (process.stdout.destroyed || !process.stdout.writable) {
2607
+ resolve();
2608
+ return;
2609
+ }
2610
+ try {
2611
+ process.stdout.write(chunk, () => resolve());
2612
+ } catch {
2613
+ resolve();
2614
+ }
2615
+ });
2616
+ } }), new ReadableStream({ start(controller) {
2617
+ process.stdin.on("data", (chunk) => controller.enqueue(new Uint8Array(chunk)));
2618
+ process.stdin.on("end", () => controller.close());
2619
+ process.stdin.on("error", (err) => controller.error(err));
2620
+ } })));
2621
+ let shuttingDown = false;
2622
+ function shutdown() {
2623
+ if (shuttingDown) return;
2624
+ shuttingDown = true;
2625
+ try {
2626
+ if ("agent" in agent) {
2627
+ const inner = agent.agent;
2628
+ if (typeof inner === "object" && inner !== null && "dispose" in inner && typeof inner.dispose === "function") inner.dispose();
2629
+ }
2630
+ } catch {}
2631
+ process.exit(0);
2632
+ }
2633
+ agent.closed.then(shutdown);
2634
+ process.on("SIGINT", shutdown);
2635
+ process.on("SIGTERM", shutdown);
2636
+ process.stdout.on("error", () => process.exit(0));
2637
+ //#endregion
2638
+ export {};
2639
+
2640
+ //# sourceMappingURL=index.mjs.map