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