@anhlp/alp-cli 0.0.0-beta.1 → 0.0.1-beta.3

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.
@@ -22,8 +22,16 @@ export type AcpAgentOptions = {
22
22
  export declare function hostServers(servers?: acp.McpServer[]): Record<string, HostMcpServer>;
23
23
  /** A prompt's content as the text ALP gives the agent: files the editor attaches are named or inlined. */
24
24
  export declare function promptText(blocks: acp.ContentBlock[]): string;
25
- /** What kind of work a tool call is, from its name or its command's first word (Claude reports tools as `Read {…}`). */
26
- export declare function toolKind(item: Extract<TimelineItem, {
25
+ type ToolItem = Extract<TimelineItem, {
27
26
  kind: 'tool_call';
28
- }>): acp.ToolKind;
27
+ }>;
28
+ /** What kind of work a tool call is: from its typed detail, else its name or its command's first word (older Claude items are `Read {…}` commands). */
29
+ export declare function toolKind(item: ToolItem): acp.ToolKind;
30
+ export declare function toolTitle(item: ToolItem, cwd?: string): string;
31
+ export declare function toolOutput(item: ToolItem): acp.ToolCallContent[];
32
+ /** The call's input as the editor shows it raw: a command, a typed call's own fields without its long texts, or the tool's input. */
33
+ export declare function toolInput(item: ToolItem): unknown;
34
+ /** The file a typed call read or changed, for the editor to follow. */
35
+ export declare function toolLocations(item: ToolItem): acp.ToolCallLocation[] | undefined;
29
36
  export declare function createAcpAgent(options: AcpAgentOptions): acp.AgentApp;
37
+ export {};
package/dist/acp/agent.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import * as acp from "@agentclientprotocol/sdk";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import path from "node:path";
5
+ var unlistedOf = ({ teams, team, teamLabel }) => teams.some((entry) => entry.id === team) ? void 0 : { id: team, label: teamLabel ?? (team === "custom" ? "Custom" : team) };
5
6
  var MODES = [
6
7
  { id: "read-only", name: "Read only", description: "Agents read and search; nothing is changed" },
7
8
  { id: "workspace-write", name: "Workspace write", description: "Agents change files and run commands inside the project" },
@@ -43,34 +44,120 @@ ${resource.text}
43
44
  }
44
45
  return text.trim();
45
46
  }
47
+ function shown(file, cwd) {
48
+ if (!cwd || !path.isAbsolute(file)) return file;
49
+ const relative = path.relative(cwd, file);
50
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative) ? relative : file;
51
+ }
46
52
  function toolKind(item) {
47
- const word = item.detail.type === "shell" ? String(item.detail.command ?? "").trim().split(/[\s{(]/)[0] : item.name;
53
+ const detail = item.detail;
54
+ switch (detail.type) {
55
+ case "read":
56
+ return "read";
57
+ case "edit":
58
+ case "write":
59
+ return "edit";
60
+ case "search":
61
+ return detail.toolName === "web_search" ? "fetch" : "search";
62
+ case "fetch":
63
+ return "fetch";
64
+ case "plan":
65
+ return "think";
66
+ case "sub_agent":
67
+ case "plain_text":
68
+ return "other";
69
+ }
70
+ const word = detail.type === "shell" ? String(detail.command ?? "").trim().split(/[\s{(]/)[0] : item.name;
48
71
  if (/^(Read|NotebookRead|LS)$/.test(word)) return "read";
49
72
  if (/^(Edit|MultiEdit|Write|NotebookEdit)$/.test(word)) return "edit";
50
73
  if (/^(Grep|Glob)$/.test(word)) return "search";
51
74
  if (/^(WebFetch|WebSearch)$/.test(word)) return "fetch";
52
75
  if (/^(Skill|Task|TodoWrite)$/.test(word) || item.name.startsWith("alp_")) return "other";
53
- return item.detail.type === "shell" ? "execute" : "other";
76
+ return detail.type === "shell" ? "execute" : "other";
54
77
  }
55
- function toolTitle(item) {
56
- if (item.detail.type === "shell") return clip(String(item.detail.command ?? "").split("\n")[0], 160);
57
- const input = item.detail.input ?? {};
78
+ function toolTitle(item, cwd) {
79
+ const detail = item.detail;
80
+ switch (detail.type) {
81
+ case "shell":
82
+ return clip(String(detail.command ?? "").split("\n")[0], 160);
83
+ case "read":
84
+ return clip(`Read ${shown(detail.filePath, cwd)}`, 160);
85
+ case "edit":
86
+ return clip(`Edit ${shown(detail.filePath, cwd)}`, 160);
87
+ case "write":
88
+ return clip(`Write ${shown(detail.filePath, cwd)}`, 160);
89
+ case "search":
90
+ return clip(`${detail.toolName === "web_search" ? "Search the web" : "Search"} ${detail.query}`, 160);
91
+ case "fetch":
92
+ return clip(`Fetch ${detail.url}`, 160);
93
+ case "sub_agent":
94
+ return clip(`${detail.subAgentType ?? "Sub-agent"}${detail.description ? `: ${detail.description.split("\n")[0]}` : ""}`, 160);
95
+ case "plan":
96
+ return "Plan";
97
+ case "plain_text":
98
+ return clip(`${item.name}${detail.label ? `: ${detail.label}` : ""}`, 160);
99
+ }
100
+ const input = detail.input ?? {};
58
101
  if (item.name === "alp_delegate") return clip(`Delegate to ${input.agent ?? "an agent"}: ${String(input.task ?? "").split("\n")[0]}`, 160);
59
102
  return clip(`${item.name} ${JSON.stringify(input)}`, 160);
60
103
  }
104
+ var bounded = (text) => text.length > OUTPUT_CHARS ? `${text.slice(0, OUTPUT_CHARS)}
105
+ \u2026 (${text.length - OUTPUT_CHARS} more characters)` : text;
61
106
  function toolOutput(item) {
107
+ const detail = item.detail;
108
+ const parts = [];
62
109
  let text = "";
63
- if (item.detail.type === "shell") text = item.detail.output ?? "";
64
- else {
65
- const output = item.detail.output;
66
- text = Array.isArray(output) ? output.map((part) => typeof part?.text === "string" ? part.text : JSON.stringify(part)).join("\n") : output == null ? "" : typeof output === "string" ? output : JSON.stringify(output, null, 2);
110
+ switch (detail.type) {
111
+ case "shell":
112
+ text = detail.output ?? "";
113
+ break;
114
+ case "read":
115
+ text = detail.content ?? "";
116
+ break;
117
+ case "edit":
118
+ if (detail.newString !== void 0 || detail.oldString !== void 0) parts.push({ type: "diff", path: detail.filePath, oldText: detail.oldString ?? null, newText: detail.newString ?? "" });
119
+ else if (detail.unifiedDiff) text = "```diff\n" + detail.unifiedDiff + (detail.unifiedDiff.endsWith("\n") ? "" : "\n") + "```";
120
+ break;
121
+ case "write":
122
+ if (detail.content !== void 0) parts.push({ type: "diff", path: detail.filePath, oldText: null, newText: detail.content });
123
+ break;
124
+ case "search":
125
+ text = detail.content ?? [...detail.filePaths ?? [], ...(detail.webResults ?? []).map((hit) => `${hit.title} \u2014 ${hit.url}`)].join("\n");
126
+ break;
127
+ case "fetch":
128
+ text = detail.result ?? "";
129
+ break;
130
+ case "sub_agent":
131
+ text = detail.log || detail.description || "";
132
+ break;
133
+ case "plan":
134
+ text = detail.text;
135
+ break;
136
+ case "plain_text":
137
+ text = detail.text ?? "";
138
+ break;
139
+ default: {
140
+ const output = detail.output;
141
+ text = Array.isArray(output) ? output.map((part) => typeof part?.text === "string" ? part.text : JSON.stringify(part)).join("\n") : output == null ? "" : typeof output === "string" ? output : JSON.stringify(output, null, 2);
142
+ }
67
143
  }
68
144
  if (item.error) text = text ? `${text}
69
145
  ${item.error}` : item.error;
70
- if (!text) return [];
71
- if (text.length > OUTPUT_CHARS) text = `${text.slice(0, OUTPUT_CHARS)}
72
- \u2026 (${text.length - OUTPUT_CHARS} more characters)`;
73
- return [{ type: "content", content: { type: "text", text } }];
146
+ if (text) parts.push({ type: "content", content: { type: "text", text: bounded(text) } });
147
+ return parts.map((part) => part.type === "diff" ? { ...part, newText: bounded(part.newText), ...part.oldText ? { oldText: bounded(part.oldText) } : {} } : part);
148
+ }
149
+ function toolInput(item) {
150
+ const detail = item.detail;
151
+ if (detail.type === "shell") return { command: detail.command, cwd: detail.cwd };
152
+ if (detail.type === "unknown" || !["read", "edit", "write", "search", "fetch", "sub_agent", "plan", "plain_text"].includes(detail.type)) return detail.input;
153
+ const { type: _type, content: _content, oldString: _old, newString: _new, unifiedDiff: _diff, result: _result, log: _log, text: _text, filePaths: _paths, webResults: _hits, ...rest } = detail;
154
+ return rest;
155
+ }
156
+ function toolLocations(item) {
157
+ const detail = item.detail;
158
+ if (detail.type !== "read" && detail.type !== "edit" && detail.type !== "write") return void 0;
159
+ const filePath = String(detail.filePath);
160
+ return [{ path: filePath, ...detail.type === "read" && typeof detail.offset === "number" ? { line: detail.offset } : {} }];
74
161
  }
75
162
  var clip = (text, chars) => text.length > chars ? `${text.slice(0, chars - 1)}\u2026` : text;
76
163
  var status = (state) => state === "running" ? "in_progress" : state;
@@ -109,7 +196,7 @@ function createAcpAgent(options) {
109
196
  }
110
197
  const say = (session, text) => send(session, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
111
198
  function configOptions(session) {
112
- const teams = session.opened ? session.preview.teams.filter((team) => team.id === session.preview.team) : session.preview.teams;
199
+ const teams = session.opened ? choices(session).filter((team) => team.id === session.preview.team) : choices(session);
113
200
  return [
114
201
  {
115
202
  id: "team",
@@ -118,14 +205,21 @@ function createAcpAgent(options) {
118
205
  type: "select",
119
206
  currentValue: session.preview.team,
120
207
  description: session.opened ? "A session keeps its team; start a new one for another team" : "The team that works on this session",
121
- options: (teams.length ? teams : [{ id: session.preview.team, label: session.preview.teamLabel ?? session.preview.team }]).map((team) => ({ value: team.id, name: team.label, ...team.description ? { description: team.description } : {} }))
208
+ options: teams.map((team) => ({ value: team.id, name: team.label, ...team.description ? { description: team.description } : {} }))
122
209
  },
123
210
  { id: "mode", name: "Permissions", category: "mode", type: "select", currentValue: session.preview.mode, options: MODES.map((mode) => ({ value: mode.id, name: mode.name, description: mode.description })) }
124
211
  ];
125
212
  }
213
+ function choices(session) {
214
+ const { teams, team } = session.preview;
215
+ const own = unlistedOf(session.preview);
216
+ const first = session.unlisted && session.unlisted.id !== team && !teams.some((entry) => entry.id === session.unlisted.id) ? [session.unlisted] : [];
217
+ return [...first, ...own ? [own] : [], ...teams];
218
+ }
126
219
  const modeState = (session) => ({ currentModeId: session.preview.mode, availableModes: MODES });
127
220
  function track(id, cwd, mcpServers, preview2, opened) {
128
- const session = { id, cwd, mcpServers, preview: preview2, opened, ours: /* @__PURE__ */ new Set(), texts: /* @__PURE__ */ new Map(), tools: /* @__PURE__ */ new Set(), questions: /* @__PURE__ */ new Map(), queue: Promise.resolve() };
221
+ const unlisted = unlistedOf(preview2);
222
+ const session = { id, cwd, mcpServers, preview: preview2, opened, ...unlisted ? { unlisted } : {}, ours: /* @__PURE__ */ new Set(), texts: /* @__PURE__ */ new Map(), tools: /* @__PURE__ */ new Set(), questions: /* @__PURE__ */ new Map(), queue: Promise.resolve() };
129
223
  sessions.set(id, session);
130
224
  return session;
131
225
  }
@@ -223,7 +317,8 @@ ${item2.text}`;
223
317
  send(session, { sessionUpdate: "plan", entries: item2.items.map((entry) => ({ content: entry.text, priority: "medium", status: entry.status })) });
224
318
  return;
225
319
  case "tool_call": {
226
- const fields = { title: toolTitle(item2), kind: toolKind(item2), status: status(item2.status), content: toolOutput(item2), rawInput: item2.detail.type === "shell" ? { command: item2.detail.command, cwd: item2.detail.cwd } : item2.detail.input };
320
+ const locations = toolLocations(item2);
321
+ const fields = { title: toolTitle(item2, session.cwd), kind: toolKind(item2), status: status(item2.status), content: toolOutput(item2), rawInput: toolInput(item2), ...locations ? { locations } : {} };
227
322
  if (session.tools.has(item2.id)) send(session, { sessionUpdate: "tool_call_update", toolCallId: item2.id, ...fields });
228
323
  else {
229
324
  session.tools.add(item2.id);
@@ -356,7 +451,7 @@ ${item2.text}`;
356
451
  if (params.configId === "mode") await setMode(session, value);
357
452
  else if (params.configId === "team") {
358
453
  if (session.opened && value !== session.preview.team) throw acp.RequestError.invalidParams(void 0, "A session keeps its team; start a new one for another team");
359
- if (!session.preview.teams.some((team) => team.id === value)) throw acp.RequestError.invalidParams(void 0, `Unknown team ${value}`);
454
+ if (!choices(session).some((team) => team.id === value)) throw acp.RequestError.invalidParams(void 0, `Unknown team ${value}`);
360
455
  session.preview = { ...await preview(session.cwd, session.mcpServers, value), mode: session.preview.mode };
361
456
  } else throw acp.RequestError.invalidParams(void 0, `Unknown option ${params.configId}`);
362
457
  return { configOptions: configOptions(session) };
@@ -386,5 +481,9 @@ export {
386
481
  createAcpAgent,
387
482
  hostServers,
388
483
  promptText,
389
- toolKind
484
+ toolInput,
485
+ toolKind,
486
+ toolLocations,
487
+ toolOutput,
488
+ toolTitle
390
489
  };
package/dist/acp/main.js CHANGED
@@ -6,7 +6,7 @@ import { startDaemon } from "@anhlp/alp-client/supervise";
6
6
  import { createLogger } from "@anhlp/alp-core/log";
7
7
  import { createAcpAgent } from "./agent.js";
8
8
  async function runAcp({ daemonEntry }) {
9
- const version = true ? "0.0.0-beta.1" : "0.0.0";
9
+ const version = true ? "0.0.1-beta.3" : "0.0.0";
10
10
  const logger = createLogger({ component: "acp" });
11
11
  const log = (message, fields) => logger.warn(message, fields);
12
12
  const app = createAcpAgent({
package/dist/acp.js CHANGED
@@ -18419,8 +18419,8 @@ import { Readable, Writable } from "node:stream";
18419
18419
 
18420
18420
  // packages/client/src/index.js
18421
18421
  import { spawn } from "node:child_process";
18422
- import { createHash } from "node:crypto";
18423
- import { open, readFile, realpath, stat, lstat, mkdir, readlink, unlink } from "node:fs/promises";
18422
+ import { createHash, randomUUID } from "node:crypto";
18423
+ import { open, readFile, writeFile, realpath, stat, lstat, mkdir, readlink, unlink, readdir, rename, rmdir, link } from "node:fs/promises";
18424
18424
  import net from "node:net";
18425
18425
  import os from "node:os";
18426
18426
  import path from "node:path";
@@ -18552,8 +18552,10 @@ var AlpRpcError = class extends Error {
18552
18552
  };
18553
18553
  var ERROR = Object.freeze({ failed: 1e3, notFound: 1001, forbidden: 1003, conflict: 1004, unavailable: 1005, protocol: 1006 });
18554
18554
  var RPC_ERROR = Object.freeze({ parseError: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602 });
18555
- var CAPABILITY = Object.freeze({ attachAfter: "attach.after", promptReceipts: "prompt.receipts", extensionMethods: "extension.methods", team: "team", task: "task", library: "library", settingsLanguage: "settings.language" });
18556
- var RPC_METHODS = Object.freeze(["assignment.recall", "board.list", "catalog.get", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "question.answer", "question.list", "session.archive", "session.attach", "session.close", "session.configure", "session.create", "session.get", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.rename", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list"]);
18555
+ var CAPABILITY = Object.freeze({ attachAfter: "attach.after", promptReceipts: "prompt.receipts", extensionMethods: "extension.methods", team: "team", task: "task", library: "library", libraryProjectWrite: "library.project.write", settingsLanguage: "settings.language", sessionListPage: "session.list.page", questionWatch: "question.watch", questionWatchTurns: "question.watch.turns", workspaceFiles: "workspace.files", workspaceFilesRead: "workspace.files.read", promptImages: "prompt.images" });
18556
+ var PROMPT_IMAGES = Object.freeze({ mimeTypes: Object.freeze(["image/png", "image/jpeg", "image/gif", "image/webp"]), maxCount: 8, maxBytes: 5 * 1024 * 1024, maxTotalBytes: 11 * 1024 * 1024 });
18557
+ var RPC_METHODS = Object.freeze(["assignment.recall", "board.list", "catalog.get", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "question.answer", "question.list", "question.watch", "session.archive", "session.attach", "session.close", "session.configure", "session.create", "session.get", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.rename", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list", "workspace.files.list", "workspace.files.read", "workspace.files.search"]);
18558
+ var WORKSPACE_FILES = Object.freeze({ maxReadBytes: 1024 * 1024, maxListEntries: 1e3, maxPathLength: 4096 });
18557
18559
 
18558
18560
  // packages/client/src/rpc/errors.js
18559
18561
  var BRAND = Symbol.for("@anhlp/alp-client/AlpClientError");
@@ -19156,10 +19158,86 @@ async function tail(file2, lines = 30) {
19156
19158
  return "";
19157
19159
  }
19158
19160
  }
19161
+ async function lifecycleOwners(home) {
19162
+ const directory = path.join(home, "state", "alpd.starting");
19163
+ const names = await readdir(directory).catch((error51) => {
19164
+ if (error51.code === "ENOENT") return [];
19165
+ throw error51;
19166
+ });
19167
+ return names.map((token) => {
19168
+ const match = /^owner-(\d+)-(\d+)-(start|stop)-[a-f0-9-]+$/.exec(token);
19169
+ if (!match) throw new Error("Invalid alpd startup admission owner");
19170
+ return { token, pid: Number(match[1]), bootTime: Number(match[2]), action: match[3] };
19171
+ });
19172
+ }
19173
+ async function readDaemonLifecycle(home) {
19174
+ return (await lifecycleOwners(home)).find((owner) => lockAlive(owner));
19175
+ }
19176
+ async function withDaemonLifecycle(home, action, run, { joinStart = false } = {}) {
19177
+ try {
19178
+ await assertPrivateDirectory(home, { create: true });
19179
+ } catch (cause) {
19180
+ throw Object.assign(new Error(`ALP_HOME_UNUSABLE, alpd failed to start while preparing its home: ${cause.message}`, { cause }), { code: "ALP_HOME_UNUSABLE" });
19181
+ }
19182
+ const state = path.join(home, "state");
19183
+ await assertPrivateDirectory(state, { create: true });
19184
+ const directory = path.join(state, "alpd.starting");
19185
+ const token = `owner-${process.pid}-${bootTime()}-${action}-${randomUUID()}`;
19186
+ const candidate = path.join(state, `alpd.starting-${token}`);
19187
+ await mkdir(candidate, { mode: 448 });
19188
+ await writeFile(path.join(candidate, token), JSON.stringify({ pid: process.pid, bootTime: bootTime(), action }), { mode: 384 });
19189
+ try {
19190
+ let joined = false;
19191
+ if (joinStart) {
19192
+ const owner = await readDaemonLifecycle(home);
19193
+ if (owner?.action === "start") {
19194
+ try {
19195
+ await link(path.join(directory, owner.token), path.join(directory, token));
19196
+ joined = true;
19197
+ } catch (error51) {
19198
+ if (error51.code !== "ENOENT") throw error51;
19199
+ }
19200
+ }
19201
+ }
19202
+ while (!joined) {
19203
+ try {
19204
+ await rename(candidate, directory);
19205
+ break;
19206
+ } catch (error51) {
19207
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "EACCES"].includes(error51.code)) throw error51;
19208
+ for (const owner of await lifecycleOwners(home)) {
19209
+ if (!lockAlive(owner)) await unlink(path.join(directory, owner.token)).catch((error52) => {
19210
+ if (error52.code !== "ENOENT") throw error52;
19211
+ });
19212
+ }
19213
+ await rmdir(directory).catch((error52) => {
19214
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error52.code)) throw error52;
19215
+ });
19216
+ await new Promise((resolve) => setTimeout(resolve, 25));
19217
+ }
19218
+ }
19219
+ try {
19220
+ return await run();
19221
+ } finally {
19222
+ await unlink(path.join(directory, token));
19223
+ await rmdir(directory).catch((error51) => {
19224
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error51.code)) throw error51;
19225
+ });
19226
+ }
19227
+ } finally {
19228
+ await unlink(path.join(candidate, token)).catch((error51) => {
19229
+ if (error51.code !== "ENOENT") throw error51;
19230
+ });
19231
+ await rmdir(candidate).catch((error51) => {
19232
+ if (error51.code !== "ENOENT") throw error51;
19233
+ });
19234
+ }
19235
+ }
19159
19236
  async function ensureDaemon({ home = alpHome(), entry = (
19160
19237
  /** @type {string | undefined} */
19161
19238
  void 0
19162
- ), env = process.env, execPath = process.execPath, timeoutMs = 15e3 } = {}) {
19239
+ ), env = process.env, execPath = process.execPath, timeoutMs = 15e3, lifecycleLocked = false } = {}) {
19240
+ if (!lifecycleLocked) return withDaemonLifecycle(home, "start", () => ensureDaemon({ home, entry, env, execPath, timeoutMs, lifecycleLocked: true }));
19163
19241
  const ready = async () => {
19164
19242
  const lock = await readLock(home);
19165
19243
  return lockAlive(lock) && lock.ready ? lock.socket : void 0;
@@ -19172,7 +19250,7 @@ async function ensureDaemon({ home = alpHome(), entry = (
19172
19250
  entry ??= await findDaemonEntry({ home, env });
19173
19251
  if (!entry) throw new Error("ALP daemon is not running and alpd.js was not found. Install the ALP CLI and run `alp daemon start`, or set ALP_DAEMON_ENTRY to alpd.js");
19174
19252
  await new Promise((resolve, reject) => {
19175
- const launcher = spawn(execPath, [entry, "--detach"], {
19253
+ const launcher = spawn(execPath, [entry, "--detach", `--startup-timeout=${timeoutMs}`], {
19176
19254
  env: { ...env, ALP_HOME: home, ELECTRON_RUN_AS_NODE: "1" },
19177
19255
  stdio: ["ignore", "ignore", "pipe"],
19178
19256
  windowsHide: true
@@ -19197,12 +19275,12 @@ ${log}` : ""}`);
19197
19275
  }
19198
19276
 
19199
19277
  // packages/client/src/supervise.js
19200
- import { mkdir as mkdir3, unlink as unlink3, writeFile as writeFile2, stat as stat2 } from "node:fs/promises";
19278
+ import { mkdir as mkdir3, unlink as unlink3, writeFile as writeFile3, stat as stat2 } from "node:fs/promises";
19201
19279
  import path3 from "node:path";
19202
19280
 
19203
19281
  // packages/client/src/service.js
19204
19282
  import { createHash as createHash2 } from "node:crypto";
19205
- import { mkdir as mkdir2, readFile as readFile2, unlink as unlink2, writeFile } from "node:fs/promises";
19283
+ import { mkdir as mkdir2, readFile as readFile2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
19206
19284
  import os2 from "node:os";
19207
19285
  import path2 from "node:path";
19208
19286
 
@@ -19299,6 +19377,9 @@ async function releaseHold(home) {
19299
19377
  await unlink3(holdFile(home)).catch(() => {
19300
19378
  });
19301
19379
  }
19380
+ async function daemonHeld(home) {
19381
+ return stat2(holdFile(home)).then(() => true, () => false);
19382
+ }
19302
19383
  async function whenReady(home, timeoutMs) {
19303
19384
  const deadline = Date.now() + timeoutMs;
19304
19385
  while (Date.now() < deadline) {
@@ -19308,21 +19389,26 @@ async function whenReady(home, timeoutMs) {
19308
19389
  }
19309
19390
  throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path3.join(home, "logs")}`);
19310
19391
  }
19311
- async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3 }) {
19312
- await releaseHold(home);
19313
- const lock = await readLock(home);
19314
- if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
19315
- const service = serviceFor({ home, env });
19316
- if (service && await installedProgram(service)) {
19317
- await startService(service);
19318
- return whenReady(home, timeoutMs);
19319
- }
19320
- return ensureDaemon({ home, entry, env, timeoutMs });
19392
+ async function startDaemon({ home, entry, env = process.env, timeoutMs = 15e3, automatic = false }) {
19393
+ return withDaemonLifecycle(home, "start", async () => {
19394
+ if (automatic) {
19395
+ if (await daemonHeld(home)) return;
19396
+ } else await releaseHold(home);
19397
+ const lock = await readLock(home);
19398
+ if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs);
19399
+ const service = serviceFor({ home, env });
19400
+ if (service && await installedProgram(service)) {
19401
+ await startService(service);
19402
+ return whenReady(home, timeoutMs);
19403
+ }
19404
+ return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true });
19405
+ });
19321
19406
  }
19322
19407
 
19323
19408
  // packages/cli/src/acp/agent.ts
19324
- import { randomUUID } from "node:crypto";
19409
+ import { randomUUID as randomUUID2 } from "node:crypto";
19325
19410
  import path4 from "node:path";
19411
+ var unlistedOf = ({ teams, team, teamLabel }) => teams.some((entry) => entry.id === team) ? void 0 : { id: team, label: teamLabel ?? (team === "custom" ? "Custom" : team) };
19326
19412
  var MODES = [
19327
19413
  { id: "read-only", name: "Read only", description: "Agents read and search; nothing is changed" },
19328
19414
  { id: "workspace-write", name: "Workspace write", description: "Agents change files and run commands inside the project" },
@@ -19364,34 +19450,120 @@ ${resource.text}
19364
19450
  }
19365
19451
  return text.trim();
19366
19452
  }
19453
+ function shown(file2, cwd) {
19454
+ if (!cwd || !path4.isAbsolute(file2)) return file2;
19455
+ const relative = path4.relative(cwd, file2);
19456
+ return relative && !relative.startsWith("..") && !path4.isAbsolute(relative) ? relative : file2;
19457
+ }
19367
19458
  function toolKind(item) {
19368
- const word = item.detail.type === "shell" ? String(item.detail.command ?? "").trim().split(/[\s{(]/)[0] : item.name;
19459
+ const detail = item.detail;
19460
+ switch (detail.type) {
19461
+ case "read":
19462
+ return "read";
19463
+ case "edit":
19464
+ case "write":
19465
+ return "edit";
19466
+ case "search":
19467
+ return detail.toolName === "web_search" ? "fetch" : "search";
19468
+ case "fetch":
19469
+ return "fetch";
19470
+ case "plan":
19471
+ return "think";
19472
+ case "sub_agent":
19473
+ case "plain_text":
19474
+ return "other";
19475
+ }
19476
+ const word = detail.type === "shell" ? String(detail.command ?? "").trim().split(/[\s{(]/)[0] : item.name;
19369
19477
  if (/^(Read|NotebookRead|LS)$/.test(word)) return "read";
19370
19478
  if (/^(Edit|MultiEdit|Write|NotebookEdit)$/.test(word)) return "edit";
19371
19479
  if (/^(Grep|Glob)$/.test(word)) return "search";
19372
19480
  if (/^(WebFetch|WebSearch)$/.test(word)) return "fetch";
19373
19481
  if (/^(Skill|Task|TodoWrite)$/.test(word) || item.name.startsWith("alp_")) return "other";
19374
- return item.detail.type === "shell" ? "execute" : "other";
19375
- }
19376
- function toolTitle(item) {
19377
- if (item.detail.type === "shell") return clip(String(item.detail.command ?? "").split("\n")[0], 160);
19378
- const input = item.detail.input ?? {};
19482
+ return detail.type === "shell" ? "execute" : "other";
19483
+ }
19484
+ function toolTitle(item, cwd) {
19485
+ const detail = item.detail;
19486
+ switch (detail.type) {
19487
+ case "shell":
19488
+ return clip(String(detail.command ?? "").split("\n")[0], 160);
19489
+ case "read":
19490
+ return clip(`Read ${shown(detail.filePath, cwd)}`, 160);
19491
+ case "edit":
19492
+ return clip(`Edit ${shown(detail.filePath, cwd)}`, 160);
19493
+ case "write":
19494
+ return clip(`Write ${shown(detail.filePath, cwd)}`, 160);
19495
+ case "search":
19496
+ return clip(`${detail.toolName === "web_search" ? "Search the web" : "Search"} ${detail.query}`, 160);
19497
+ case "fetch":
19498
+ return clip(`Fetch ${detail.url}`, 160);
19499
+ case "sub_agent":
19500
+ return clip(`${detail.subAgentType ?? "Sub-agent"}${detail.description ? `: ${detail.description.split("\n")[0]}` : ""}`, 160);
19501
+ case "plan":
19502
+ return "Plan";
19503
+ case "plain_text":
19504
+ return clip(`${item.name}${detail.label ? `: ${detail.label}` : ""}`, 160);
19505
+ }
19506
+ const input = detail.input ?? {};
19379
19507
  if (item.name === "alp_delegate") return clip(`Delegate to ${input.agent ?? "an agent"}: ${String(input.task ?? "").split("\n")[0]}`, 160);
19380
19508
  return clip(`${item.name} ${JSON.stringify(input)}`, 160);
19381
19509
  }
19510
+ var bounded = (text) => text.length > OUTPUT_CHARS ? `${text.slice(0, OUTPUT_CHARS)}
19511
+ \u2026 (${text.length - OUTPUT_CHARS} more characters)` : text;
19382
19512
  function toolOutput(item) {
19513
+ const detail = item.detail;
19514
+ const parts = [];
19383
19515
  let text = "";
19384
- if (item.detail.type === "shell") text = item.detail.output ?? "";
19385
- else {
19386
- const output = item.detail.output;
19387
- text = Array.isArray(output) ? output.map((part) => typeof part?.text === "string" ? part.text : JSON.stringify(part)).join("\n") : output == null ? "" : typeof output === "string" ? output : JSON.stringify(output, null, 2);
19516
+ switch (detail.type) {
19517
+ case "shell":
19518
+ text = detail.output ?? "";
19519
+ break;
19520
+ case "read":
19521
+ text = detail.content ?? "";
19522
+ break;
19523
+ case "edit":
19524
+ if (detail.newString !== void 0 || detail.oldString !== void 0) parts.push({ type: "diff", path: detail.filePath, oldText: detail.oldString ?? null, newText: detail.newString ?? "" });
19525
+ else if (detail.unifiedDiff) text = "```diff\n" + detail.unifiedDiff + (detail.unifiedDiff.endsWith("\n") ? "" : "\n") + "```";
19526
+ break;
19527
+ case "write":
19528
+ if (detail.content !== void 0) parts.push({ type: "diff", path: detail.filePath, oldText: null, newText: detail.content });
19529
+ break;
19530
+ case "search":
19531
+ text = detail.content ?? [...detail.filePaths ?? [], ...(detail.webResults ?? []).map((hit) => `${hit.title} \u2014 ${hit.url}`)].join("\n");
19532
+ break;
19533
+ case "fetch":
19534
+ text = detail.result ?? "";
19535
+ break;
19536
+ case "sub_agent":
19537
+ text = detail.log || detail.description || "";
19538
+ break;
19539
+ case "plan":
19540
+ text = detail.text;
19541
+ break;
19542
+ case "plain_text":
19543
+ text = detail.text ?? "";
19544
+ break;
19545
+ default: {
19546
+ const output = detail.output;
19547
+ text = Array.isArray(output) ? output.map((part) => typeof part?.text === "string" ? part.text : JSON.stringify(part)).join("\n") : output == null ? "" : typeof output === "string" ? output : JSON.stringify(output, null, 2);
19548
+ }
19388
19549
  }
19389
19550
  if (item.error) text = text ? `${text}
19390
19551
  ${item.error}` : item.error;
19391
- if (!text) return [];
19392
- if (text.length > OUTPUT_CHARS) text = `${text.slice(0, OUTPUT_CHARS)}
19393
- \u2026 (${text.length - OUTPUT_CHARS} more characters)`;
19394
- return [{ type: "content", content: { type: "text", text } }];
19552
+ if (text) parts.push({ type: "content", content: { type: "text", text: bounded(text) } });
19553
+ return parts.map((part) => part.type === "diff" ? { ...part, newText: bounded(part.newText), ...part.oldText ? { oldText: bounded(part.oldText) } : {} } : part);
19554
+ }
19555
+ function toolInput(item) {
19556
+ const detail = item.detail;
19557
+ if (detail.type === "shell") return { command: detail.command, cwd: detail.cwd };
19558
+ if (detail.type === "unknown" || !["read", "edit", "write", "search", "fetch", "sub_agent", "plan", "plain_text"].includes(detail.type)) return detail.input;
19559
+ const { type: _type, content: _content, oldString: _old, newString: _new, unifiedDiff: _diff, result: _result, log: _log, text: _text, filePaths: _paths, webResults: _hits, ...rest } = detail;
19560
+ return rest;
19561
+ }
19562
+ function toolLocations(item) {
19563
+ const detail = item.detail;
19564
+ if (detail.type !== "read" && detail.type !== "edit" && detail.type !== "write") return void 0;
19565
+ const filePath = String(detail.filePath);
19566
+ return [{ path: filePath, ...detail.type === "read" && typeof detail.offset === "number" ? { line: detail.offset } : {} }];
19395
19567
  }
19396
19568
  var clip = (text, chars) => text.length > chars ? `${text.slice(0, chars - 1)}\u2026` : text;
19397
19569
  var status = (state) => state === "running" ? "in_progress" : state;
@@ -19430,7 +19602,7 @@ function createAcpAgent(options) {
19430
19602
  }
19431
19603
  const say = (session, text) => send(session, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
19432
19604
  function configOptions(session) {
19433
- const teams = session.opened ? session.preview.teams.filter((team) => team.id === session.preview.team) : session.preview.teams;
19605
+ const teams = session.opened ? choices(session).filter((team) => team.id === session.preview.team) : choices(session);
19434
19606
  return [
19435
19607
  {
19436
19608
  id: "team",
@@ -19439,14 +19611,21 @@ function createAcpAgent(options) {
19439
19611
  type: "select",
19440
19612
  currentValue: session.preview.team,
19441
19613
  description: session.opened ? "A session keeps its team; start a new one for another team" : "The team that works on this session",
19442
- options: (teams.length ? teams : [{ id: session.preview.team, label: session.preview.teamLabel ?? session.preview.team }]).map((team) => ({ value: team.id, name: team.label, ...team.description ? { description: team.description } : {} }))
19614
+ options: teams.map((team) => ({ value: team.id, name: team.label, ...team.description ? { description: team.description } : {} }))
19443
19615
  },
19444
19616
  { id: "mode", name: "Permissions", category: "mode", type: "select", currentValue: session.preview.mode, options: MODES.map((mode) => ({ value: mode.id, name: mode.name, description: mode.description })) }
19445
19617
  ];
19446
19618
  }
19619
+ function choices(session) {
19620
+ const { teams, team } = session.preview;
19621
+ const own2 = unlistedOf(session.preview);
19622
+ const first = session.unlisted && session.unlisted.id !== team && !teams.some((entry) => entry.id === session.unlisted.id) ? [session.unlisted] : [];
19623
+ return [...first, ...own2 ? [own2] : [], ...teams];
19624
+ }
19447
19625
  const modeState = (session) => ({ currentModeId: session.preview.mode, availableModes: MODES });
19448
19626
  function track(id, cwd, mcpServers, preview2, opened) {
19449
- const session = { id, cwd, mcpServers, preview: preview2, opened, ours: /* @__PURE__ */ new Set(), texts: /* @__PURE__ */ new Map(), tools: /* @__PURE__ */ new Set(), questions: /* @__PURE__ */ new Map(), queue: Promise.resolve() };
19627
+ const unlisted = unlistedOf(preview2);
19628
+ const session = { id, cwd, mcpServers, preview: preview2, opened, ...unlisted ? { unlisted } : {}, ours: /* @__PURE__ */ new Set(), texts: /* @__PURE__ */ new Map(), tools: /* @__PURE__ */ new Set(), questions: /* @__PURE__ */ new Map(), queue: Promise.resolve() };
19450
19629
  sessions.set(id, session);
19451
19630
  return session;
19452
19631
  }
@@ -19544,7 +19723,8 @@ ${item2.text}`;
19544
19723
  send(session, { sessionUpdate: "plan", entries: item2.items.map((entry) => ({ content: entry.text, priority: "medium", status: entry.status })) });
19545
19724
  return;
19546
19725
  case "tool_call": {
19547
- const fields = { title: toolTitle(item2), kind: toolKind(item2), status: status(item2.status), content: toolOutput(item2), rawInput: item2.detail.type === "shell" ? { command: item2.detail.command, cwd: item2.detail.cwd } : item2.detail.input };
19726
+ const locations = toolLocations(item2);
19727
+ const fields = { title: toolTitle(item2, session.cwd), kind: toolKind(item2), status: status(item2.status), content: toolOutput(item2), rawInput: toolInput(item2), ...locations ? { locations } : {} };
19548
19728
  if (session.tools.has(item2.id)) send(session, { sessionUpdate: "tool_call_update", toolCallId: item2.id, ...fields });
19549
19729
  else {
19550
19730
  session.tools.add(item2.id);
@@ -19584,7 +19764,7 @@ ${item2.text}`;
19584
19764
  send(session, { sessionUpdate: "config_option_update", configOptions: configOptions(session) });
19585
19765
  }
19586
19766
  if (session.waiting) throw RequestError.invalidRequest(void 0, "A prompt is already running in this session");
19587
- const clientMessageId = randomUUID();
19767
+ const clientMessageId = randomUUID2();
19588
19768
  session.ours.add(clientMessageId);
19589
19769
  let done;
19590
19770
  const ended = new Promise((resolve) => {
@@ -19629,7 +19809,7 @@ ${item2.text}`;
19629
19809
  })).onRequest("authenticate", () => ({})).onRequest("session/new", async ({ params }) => {
19630
19810
  const cwd = absolute(params.cwd);
19631
19811
  const mcpServers = hostServers(params.mcpServers);
19632
- const session = track(`acp-${randomUUID()}`, cwd, mcpServers, await preview(cwd, mcpServers), false);
19812
+ const session = track(`acp-${randomUUID2()}`, cwd, mcpServers, await preview(cwd, mcpServers), false);
19633
19813
  queueMicrotask(() => send(session, { sessionUpdate: "available_commands_update", availableCommands: COMMANDS }));
19634
19814
  return { sessionId: session.id, configOptions: configOptions(session), modes: modeState(session) };
19635
19815
  }).onRequest("session/load", async ({ params }) => {
@@ -19677,7 +19857,7 @@ ${item2.text}`;
19677
19857
  if (params.configId === "mode") await setMode(session, value);
19678
19858
  else if (params.configId === "team") {
19679
19859
  if (session.opened && value !== session.preview.team) throw RequestError.invalidParams(void 0, "A session keeps its team; start a new one for another team");
19680
- if (!session.preview.teams.some((team) => team.id === value)) throw RequestError.invalidParams(void 0, `Unknown team ${value}`);
19860
+ if (!choices(session).some((team) => team.id === value)) throw RequestError.invalidParams(void 0, `Unknown team ${value}`);
19681
19861
  session.preview = { ...await preview(session.cwd, session.mcpServers, value), mode: session.preview.mode };
19682
19862
  } else throw RequestError.invalidParams(void 0, `Unknown option ${params.configId}`);
19683
19863
  return { configOptions: configOptions(session) };
@@ -19706,7 +19886,7 @@ ${item2.text}`;
19706
19886
 
19707
19887
  // packages/cli/src/acp/main.ts
19708
19888
  async function runAcp({ daemonEntry }) {
19709
- const version2 = true ? "0.0.0-beta.1" : "0.0.0";
19889
+ const version2 = true ? "0.0.1-beta.3" : "0.0.0";
19710
19890
  const logger = createLogger({ component: "acp" });
19711
19891
  const log = (message, fields) => logger.warn(message, fields);
19712
19892
  const app = createAcpAgent({