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