@acryldev/agent-panel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/client/describe.ts +101 -0
  3. package/client/driver-pick.ts +22 -0
  4. package/client/frame.ts +51 -0
  5. package/client/main.ts +707 -0
  6. package/client/markdown.ts +219 -0
  7. package/headless.ts +220 -0
  8. package/index.ts +523 -0
  9. package/launch.ts +67 -0
  10. package/lib/client/describe.ts +101 -0
  11. package/lib/client/driver-pick.ts +22 -0
  12. package/lib/client/frame.ts +51 -0
  13. package/lib/client/main.ts +707 -0
  14. package/lib/client/markdown.ts +219 -0
  15. package/lib/headless-B_RGxZFU.js +252 -0
  16. package/lib/headless-B_RGxZFU.js.map +1 -0
  17. package/lib/headless.js +2 -0
  18. package/lib/index.js +562 -0
  19. package/lib/index.js.map +1 -0
  20. package/lib/mount.js +25 -0
  21. package/lib/mount.js.map +1 -0
  22. package/lib/registry.js +13 -0
  23. package/lib/registry.js.map +1 -0
  24. package/lib/types/headless.d.ts +22 -0
  25. package/lib/types/index.d.ts +22 -0
  26. package/lib/types/launch.d.ts +18 -0
  27. package/lib/types/mount.d.ts +12 -0
  28. package/lib/types/registry.d.ts +10 -0
  29. package/lib/types/tsdown.config.d.ts +2 -0
  30. package/lib/types/visitors.d.ts +82 -0
  31. package/mount.ts +27 -0
  32. package/package.json +62 -3
  33. package/plugin.json +28 -0
  34. package/registry.ts +17 -0
  35. package/scripts/copy-assets.mjs +5 -0
  36. package/test/client-guards.test.ts +13 -0
  37. package/test/describe.test.ts +105 -0
  38. package/test/driver-pick.test.ts +24 -0
  39. package/test/frame.test.ts +35 -0
  40. package/test/launch.test.ts +90 -0
  41. package/test/markdown.test.ts +79 -0
  42. package/test/panel-client.test.ts +150 -0
  43. package/test/panel.test.ts +534 -0
  44. package/test/socket.test.ts +209 -0
  45. package/test/visitors.test.ts +112 -0
  46. package/test/why.test.ts +61 -0
  47. package/tsconfig.json +21 -0
  48. package/tsdown.config.ts +23 -0
  49. package/visitors.ts +231 -0
  50. package/README.md +0 -3
@@ -0,0 +1,219 @@
1
+ /**
2
+ * A small, safe Markdown for the agent's answers. The parser turns text into a tree of blocks and inlines; nothing in it is HTML: the panel builds elements from the tree with
3
+ * `createElement` and `textContent`, so an answer can never put markup, a script or an event handler into the page. A link keeps its address only for `http:`, `https:` and `mailto:`.
4
+ * What it knows: headings, paragraphs, fenced code, bullet and numbered lists, block quotes, and `code`, **bold**, *italic*, [links](https://...) inside a line.
5
+ */
6
+
7
+ export type Inline =
8
+ | { readonly type: 'text'; readonly text: string }
9
+ | { readonly type: 'code'; readonly text: string }
10
+ | { readonly type: 'strong'; readonly children: readonly Inline[] }
11
+ | { readonly type: 'em'; readonly children: readonly Inline[] }
12
+ | {
13
+ readonly type: 'link'
14
+ readonly href: string | undefined
15
+ readonly children: readonly Inline[]
16
+ }
17
+
18
+ export type Block =
19
+ | { readonly type: 'heading'; readonly level: number; readonly children: readonly Inline[] }
20
+ | { readonly type: 'paragraph'; readonly children: readonly Inline[] }
21
+ | { readonly type: 'code'; readonly language: string; readonly text: string }
22
+ | {
23
+ readonly type: 'list'
24
+ readonly ordered: boolean
25
+ readonly items: readonly (readonly Inline[])[]
26
+ }
27
+ | { readonly type: 'quote'; readonly children: readonly Inline[] }
28
+
29
+ const SAFE_LINK = /^(?:https?:\/\/|mailto:)/iu
30
+
31
+ /** The address of a link if it is one the panel will open, else nothing (a `javascript:` or `data:` address is shown as text). */
32
+ export function safeHref(href: string): string | undefined {
33
+ const trimmed = href.trim()
34
+ return SAFE_LINK.test(trimmed) && !/[\s<>"]/u.test(trimmed) ? trimmed : undefined
35
+ }
36
+
37
+ /** Inline syntax inside one line or paragraph. An opener with no closer is plain text. */
38
+ export function parseInline(text: string): Inline[] {
39
+ const out: Inline[] = []
40
+ let plain = ''
41
+ const flush = (): void => {
42
+ if (plain !== '') out.push({ type: 'text', text: plain })
43
+ plain = ''
44
+ }
45
+ let at = 0
46
+ while (at < text.length) {
47
+ const char = text[at] as string
48
+ if (char === '`') {
49
+ const end = text.indexOf('`', at + 1)
50
+ if (end > at + 1) {
51
+ flush()
52
+ out.push({ type: 'code', text: text.slice(at + 1, end) })
53
+ at = end + 1
54
+ continue
55
+ }
56
+ } else if (char === '*' && text[at + 1] === '*') {
57
+ const end = text.indexOf('**', at + 2)
58
+ if (end > at + 2) {
59
+ flush()
60
+ out.push({ type: 'strong', children: parseInline(text.slice(at + 2, end)) })
61
+ at = end + 2
62
+ continue
63
+ }
64
+ } else if (
65
+ (char === '*' || char === '_') &&
66
+ text[at + 1] !== ' ' &&
67
+ (at === 0 || !/\w/u.test(text[at - 1] as string))
68
+ ) {
69
+ const end = text.indexOf(char, at + 1)
70
+ if (end > at + 1 && text[end - 1] !== ' ' && !/\w/u.test(text[end + 1] ?? ' ')) {
71
+ flush()
72
+ out.push({ type: 'em', children: parseInline(text.slice(at + 1, end)) })
73
+ at = end + 1
74
+ continue
75
+ }
76
+ } else if (char === '[') {
77
+ const close = text.indexOf('](', at + 1)
78
+ const end = close === -1 ? -1 : text.indexOf(')', close + 2)
79
+ if (close > at + 1 && end > close) {
80
+ flush()
81
+ out.push({
82
+ type: 'link',
83
+ href: safeHref(text.slice(close + 2, end)),
84
+ children: parseInline(text.slice(at + 1, close)),
85
+ })
86
+ at = end + 1
87
+ continue
88
+ }
89
+ }
90
+ plain += char
91
+ at += 1
92
+ }
93
+ flush()
94
+ return out
95
+ }
96
+
97
+ /** Blocks of a whole answer. A fence that is still open (the answer is streaming) shows what it has so far. */
98
+ export function parseMarkdown(source: string): Block[] {
99
+ const lines = source.replaceAll('\r\n', '\n').split('\n')
100
+ const blocks: Block[] = []
101
+ let paragraph: string[] = []
102
+ const endParagraph = (): void => {
103
+ if (paragraph.length > 0)
104
+ blocks.push({ type: 'paragraph', children: parseInline(paragraph.join('\n')) })
105
+ paragraph = []
106
+ }
107
+ for (let at = 0; at < lines.length; at += 1) {
108
+ const line = lines[at] as string
109
+ const fence = /^\s*```\s*([\w+-]*)\s*$/u.exec(line)
110
+ if (fence) {
111
+ endParagraph()
112
+ const body: string[] = []
113
+ for (at += 1; at < lines.length && !/^\s*```\s*$/u.test(lines[at] as string); at += 1)
114
+ body.push(lines[at] as string)
115
+ blocks.push({ type: 'code', language: fence[1] ?? '', text: body.join('\n') })
116
+ continue
117
+ }
118
+ const heading = /^(#{1,6})\s+(.*?)\s*#*\s*$/u.exec(line)
119
+ if (heading) {
120
+ endParagraph()
121
+ blocks.push({
122
+ type: 'heading',
123
+ level: (heading[1] as string).length,
124
+ children: parseInline(heading[2] as string),
125
+ })
126
+ continue
127
+ }
128
+ const bullet = /^\s*[-*+]\s+(.*)$/u.exec(line)
129
+ const numbered = /^\s*\d{1,3}[.)]\s+(.*)$/u.exec(line)
130
+ if (bullet || numbered) {
131
+ endParagraph()
132
+ const ordered = numbered !== null
133
+ const items: Inline[][] = []
134
+ for (; at < lines.length; at += 1) {
135
+ const item = (ordered ? /^\s*\d{1,3}[.)]\s+(.*)$/u : /^\s*[-*+]\s+(.*)$/u).exec(
136
+ lines[at] as string,
137
+ )
138
+ if (!item) break
139
+ items.push(parseInline(item[1] as string))
140
+ }
141
+ at -= 1
142
+ blocks.push({ type: 'list', ordered, items })
143
+ continue
144
+ }
145
+ const quote = /^\s*>\s?(.*)$/u.exec(line)
146
+ if (quote) {
147
+ endParagraph()
148
+ const quoted: string[] = []
149
+ for (; at < lines.length; at += 1) {
150
+ const next = /^\s*>\s?(.*)$/u.exec(lines[at] as string)
151
+ if (!next) break
152
+ quoted.push(next[1] as string)
153
+ }
154
+ at -= 1
155
+ blocks.push({ type: 'quote', children: parseInline(quoted.join('\n')) })
156
+ continue
157
+ }
158
+ if (line.trim() === '') endParagraph()
159
+ else paragraph.push(line)
160
+ }
161
+ endParagraph()
162
+ return blocks
163
+ }
164
+
165
+ /** Build the elements of a parsed answer. Only `createElement`, `textContent` and attributes set here: no HTML string reaches the page. */
166
+ export function renderMarkdown(source: string, document: Document): DocumentFragment {
167
+ const fragment = document.createDocumentFragment()
168
+ const inline = (parent: Node, nodes: readonly Inline[]): void => {
169
+ for (const node of nodes) {
170
+ if (node.type === 'text') parent.appendChild(document.createTextNode(node.text))
171
+ else if (node.type === 'code') {
172
+ const code = document.createElement('code')
173
+ code.textContent = node.text
174
+ parent.appendChild(code)
175
+ } else if (node.type === 'strong' || node.type === 'em') {
176
+ const element = document.createElement(node.type)
177
+ inline(element, node.children)
178
+ parent.appendChild(element)
179
+ } else if (node.href === undefined) {
180
+ inline(parent, node.children)
181
+ } else {
182
+ const anchor = document.createElement('a')
183
+ anchor.href = node.href
184
+ anchor.target = '_blank'
185
+ anchor.rel = 'noopener noreferrer'
186
+ inline(anchor, node.children)
187
+ parent.appendChild(anchor)
188
+ }
189
+ }
190
+ }
191
+ for (const block of parseMarkdown(source)) {
192
+ if (block.type === 'code') {
193
+ const pre = document.createElement('pre')
194
+ const code = document.createElement('code')
195
+ code.textContent = block.text
196
+ pre.appendChild(code)
197
+ fragment.appendChild(pre)
198
+ } else if (block.type === 'list') {
199
+ const list = document.createElement(block.ordered ? 'ol' : 'ul')
200
+ for (const item of block.items) {
201
+ const li = document.createElement('li')
202
+ inline(li, item)
203
+ list.appendChild(li)
204
+ }
205
+ fragment.appendChild(list)
206
+ } else {
207
+ const element = document.createElement(
208
+ block.type === 'heading'
209
+ ? `h${String(Math.min(block.level + 2, 6))}`
210
+ : block.type === 'quote'
211
+ ? 'blockquote'
212
+ : 'p',
213
+ )
214
+ inline(element, block.children)
215
+ fragment.appendChild(element)
216
+ }
217
+ }
218
+ return fragment
219
+ }
@@ -0,0 +1,252 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, win32 } from "node:path";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { personHome } from "@acryldev/instance/storage";
5
+ //#region launch.ts
6
+ /**
7
+ * Starting a coding agent (`claude`, `codex`, `pi`) without a shell. Off Windows the program is spawned by name. On Windows an npm-installed CLI is a `.cmd` shim, which CreateProcess
8
+ * cannot start, and a shell would pass the person's message through cmd.exe quoting (`& | < > ^ "` would run or break). So the shim is read: npm writes the script it runs
9
+ * (`"%dp0%\node_modules\<package>\dist\cli.js"`), and that script is started with Node directly, as one process. A native `.exe` (the Windows installer of claude) is started as it is.
10
+ */
11
+ /** The script an npm `.cmd` shim runs: the quoted path after `%dp0%\`, ending in .js, .cjs or .mjs. */
12
+ const SHIM_SCRIPT = /"%dp0%[\\/]([^"\r\n]+?\.(?:mjs|cjs|js))"/iu;
13
+ /**
14
+ * @returns how to start `program` with `args`, or a sentence saying why it cannot be started here. A program that is not found is also a sentence.
15
+ */
16
+ function resolveLaunch(program, args, deps = {}) {
17
+ if ((deps.platform ?? process.platform) !== "win32") return {
18
+ file: program,
19
+ args: [...args]
20
+ };
21
+ const env = deps.env ?? process.env;
22
+ const exists = deps.exists ?? existsSync;
23
+ const read = deps.read ?? ((path) => readFileSync(path, "utf8"));
24
+ const execPath = deps.execPath ?? process.execPath;
25
+ const folders = (env.PATH ?? env.Path ?? "").split(";").filter(Boolean);
26
+ for (const folder of folders) for (const extension of [
27
+ ".exe",
28
+ ".com",
29
+ ".cmd",
30
+ ".bat"
31
+ ]) {
32
+ const found = win32.join(folder, `${program}${extension}`);
33
+ if (!exists(found)) continue;
34
+ if (extension === ".exe" || extension === ".com") return {
35
+ file: found,
36
+ args: [...args]
37
+ };
38
+ let text;
39
+ try {
40
+ text = read(found);
41
+ } catch {
42
+ return { error: `${program} is installed as ${found} but that file cannot be read` };
43
+ }
44
+ const script = SHIM_SCRIPT.exec(text)?.[1];
45
+ if (script === void 0) return { error: `${program} is installed as ${found}, a batch file the panel cannot start without a shell (a shell would pass the message through cmd.exe quoting). Install the native program, or an npm package that creates an npm shim` };
46
+ const directory = win32.dirname(found);
47
+ const node = win32.join(directory, "node.exe");
48
+ return {
49
+ file: exists(node) ? node : execPath,
50
+ args: [win32.join(directory, script), ...args]
51
+ };
52
+ }
53
+ return { error: `${program} was not found on the PATH` };
54
+ }
55
+ //#endregion
56
+ //#region headless.ts
57
+ /** The panel's own drivers, all `chat`: the app's agent, and the coding agents (`claude`, `codex`, `pi`) started headless in the app folder. */
58
+ /** The command line of each coding agent started headless in the app folder (the same ones the product test uses). */
59
+ function command(driver, message, root) {
60
+ switch (driver) {
61
+ case "claude": return {
62
+ file: "claude",
63
+ args: [
64
+ "-p",
65
+ message,
66
+ "--permission-mode",
67
+ "acceptEdits",
68
+ "--allowedTools",
69
+ "Read,Edit,Write,Glob,Grep,Bash(npm *),Bash(npx *),Bash(node *),Bash(.acryl/bin/acryl *),Bash(curl *)"
70
+ ]
71
+ };
72
+ case "codex": return {
73
+ file: "codex",
74
+ args: [
75
+ "exec",
76
+ "--skip-git-repo-check",
77
+ "-s",
78
+ "workspace-write",
79
+ "-c",
80
+ "sandbox_workspace_write.network_access=true",
81
+ "-C",
82
+ root,
83
+ message
84
+ ]
85
+ };
86
+ case "pi": return {
87
+ file: "pi",
88
+ args: [
89
+ "-p",
90
+ message,
91
+ "--provider",
92
+ "deepseek",
93
+ "--model",
94
+ "deepseek-v4-pro",
95
+ "--no-session"
96
+ ]
97
+ };
98
+ }
99
+ }
100
+ /** Stop a program and what it started: Windows has no process groups, so the tree goes by its root (`SIGTERM` there ends only the one process). */
101
+ function stopProgram(child) {
102
+ if (process.platform === "win32" && child.pid !== void 0) {
103
+ spawnSync("taskkill", [
104
+ "/PID",
105
+ String(child.pid),
106
+ "/T",
107
+ "/F"
108
+ ], { stdio: "ignore" });
109
+ return;
110
+ }
111
+ child.kill("SIGTERM");
112
+ }
113
+ function onPath(program) {
114
+ return spawnSync(process.platform === "win32" ? "where" : "which", [program], { encoding: "utf8" }).status === 0;
115
+ }
116
+ /** Whether pi can reach DeepSeek: the key in the environment, or the one pi stored for itself when its owner logged in (`~/.pi/agent/auth.json`, a `deepseek` entry). */
117
+ function piHasDeepseekKey(env = process.env, home = personHome(env)) {
118
+ if (env.DEEPSEEK_API_KEY) return true;
119
+ try {
120
+ const stored = JSON.parse(readFileSync(join(env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent"), "auth.json"), "utf8"));
121
+ return typeof stored.deepseek?.key === "string" && stored.deepseek.key !== "";
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ /** The headless programs this machine can offer: installed (an executable on the PATH; a wrapper function around it is fine) and, for pi, able to reach its model. */
127
+ function availableHeadless(wanted) {
128
+ const found = [];
129
+ for (const driver of wanted ?? [
130
+ "claude",
131
+ "codex",
132
+ "pi"
133
+ ]) {
134
+ if (driver === "pi" && !piHasDeepseekKey()) continue;
135
+ if (!onPath(driver)) continue;
136
+ if ("error" in resolveLaunch(driver, [])) continue;
137
+ found.push(driver);
138
+ }
139
+ return found;
140
+ }
141
+ /** The app's own agent as a chat driver: its tool calls, then its answer. Aborting the signal cancels the run. */
142
+ function agentDriver(ctx) {
143
+ return {
144
+ kind: "chat",
145
+ name: "agent",
146
+ async *start({ message, signal, page }) {
147
+ const result = await ctx.agent.run(message, {
148
+ signal,
149
+ ...page === void 0 ? {} : { page }
150
+ });
151
+ for (const call of result.trace) yield {
152
+ event: "tool",
153
+ data: {
154
+ tool: call.tool,
155
+ input: call.input,
156
+ ...call.error ? { error: call.error } : { result: call.result }
157
+ }
158
+ };
159
+ yield {
160
+ event: "text",
161
+ data: { text: result.status === "completed" ? result.output : result.status === "cancelled" ? "The run was cancelled." : `The run stopped after ${result.steps} steps without an answer.` }
162
+ };
163
+ }
164
+ };
165
+ }
166
+ /** A coding agent run headless in the app folder: its stdout is the answer, its stderr the tool lines. Aborting the signal ends the program. */
167
+ function headlessDriver(name, root) {
168
+ return {
169
+ kind: "chat",
170
+ name,
171
+ async *start({ message, signal }) {
172
+ const wanted = command(name, message, root);
173
+ const launch = resolveLaunch(wanted.file, wanted.args);
174
+ if ("error" in launch) {
175
+ yield {
176
+ event: "error",
177
+ data: { message: launch.error }
178
+ };
179
+ return;
180
+ }
181
+ const child = spawn(launch.file, launch.args, {
182
+ cwd: root,
183
+ env: process.env,
184
+ stdio: [
185
+ "ignore",
186
+ "pipe",
187
+ "pipe"
188
+ ]
189
+ });
190
+ const queue = [];
191
+ let wake;
192
+ let ended = false;
193
+ const push = (event) => {
194
+ queue.push(event);
195
+ wake?.();
196
+ };
197
+ signal.addEventListener("abort", () => stopProgram(child), { once: true });
198
+ child.stdout.on("data", (chunk) => push({
199
+ event: "text",
200
+ data: { text: chunk.toString() }
201
+ }));
202
+ child.stderr.on("data", (chunk) => push({
203
+ event: "tool",
204
+ data: {
205
+ tool: name,
206
+ info: chunk.toString().slice(0, 500)
207
+ }
208
+ }));
209
+ child.on("error", (cause) => {
210
+ ended = true;
211
+ push({
212
+ event: "error",
213
+ data: { message: `${name} could not be started: ${cause.message}` }
214
+ });
215
+ });
216
+ child.on("exit", (code) => {
217
+ ended = true;
218
+ if (code !== 0 && !signal.aborted) push({
219
+ event: "error",
220
+ data: { message: `${name} ended with exit code ${code ?? 1}` }
221
+ });
222
+ else wake?.();
223
+ });
224
+ try {
225
+ for (;;) {
226
+ const next = queue.shift();
227
+ if (next) yield next;
228
+ else if (ended) return;
229
+ else await new Promise((resolve) => wake = resolve);
230
+ }
231
+ } finally {
232
+ if (child.exitCode === null) stopProgram(child);
233
+ }
234
+ }
235
+ };
236
+ }
237
+ /**
238
+ * Why a driver name cannot be used to ask a question, in a sentence: it is a terminal (picked in the panel, not asked over `/ask`), it is a coding agent that is not installed or not
239
+ * able to start, or pi without a key to reach its model. Nothing when the name is not one of the headless agents.
240
+ */
241
+ function whyNotChat(name, kind) {
242
+ if (kind === "terminal") return `"${name}" is a terminal driver: pick it in the panel to open its terminal; /ask runs the chat drivers`;
243
+ if (name !== "claude" && name !== "codex" && name !== "pi") return void 0;
244
+ if (!onPath(name)) return `${name} was not found on the PATH of the app, so the panel cannot start it`;
245
+ const launch = resolveLaunch(name, []);
246
+ if ("error" in launch) return launch.error;
247
+ if (name === "pi" && !piHasDeepseekKey()) return "pi needs a DeepSeek key: set DEEPSEEK_API_KEY in the environment of the app, or log in with pi once (it keeps the key in ~/.pi/agent/auth.json)";
248
+ }
249
+ //#endregion
250
+ export { onPath as a, headlessDriver as i, availableHeadless as n, piHasDeepseekKey as o, command as r, whyNotChat as s, agentDriver as t };
251
+
252
+ //# sourceMappingURL=headless-B_RGxZFU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headless-B_RGxZFU.js","names":[],"sources":["../launch.ts","../headless.ts"],"sourcesContent":["/**\n * Starting a coding agent (`claude`, `codex`, `pi`) without a shell. Off Windows the program is spawned by name. On Windows an npm-installed CLI is a `.cmd` shim, which CreateProcess\n * cannot start, and a shell would pass the person's message through cmd.exe quoting (`& | < > ^ \"` would run or break). So the shim is read: npm writes the script it runs\n * (`\"%dp0%\\node_modules\\<package>\\dist\\cli.js\"`), and that script is started with Node directly, as one process. A native `.exe` (the Windows installer of claude) is started as it is.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { win32 } from 'node:path'\n\nexport interface Launch {\n readonly file: string\n readonly args: string[]\n}\n\nexport interface LaunchDeps {\n readonly platform?: NodeJS.Platform\n readonly env?: NodeJS.ProcessEnv\n readonly exists?: (path: string) => boolean\n readonly read?: (path: string) => string\n /** The Node that starts a shim's script (this process's). */\n readonly execPath?: string\n}\n\n/** The script an npm `.cmd` shim runs: the quoted path after `%dp0%\\`, ending in .js, .cjs or .mjs. */\nconst SHIM_SCRIPT = /\"%dp0%[\\\\/]([^\"\\r\\n]+?\\.(?:mjs|cjs|js))\"/iu\n\n/**\n * @returns how to start `program` with `args`, or a sentence saying why it cannot be started here. A program that is not found is also a sentence.\n */\nexport function resolveLaunch(\n program: string,\n args: readonly string[],\n deps: LaunchDeps = {},\n): Launch | { readonly error: string } {\n const platform = deps.platform ?? process.platform\n if (platform !== 'win32') return { file: program, args: [...args] }\n const env = deps.env ?? process.env\n const exists = deps.exists ?? existsSync\n const read = deps.read ?? ((path: string) => readFileSync(path, 'utf8'))\n const execPath = deps.execPath ?? process.execPath\n const folders = (env.PATH ?? env.Path ?? '').split(';').filter(Boolean)\n for (const folder of folders) {\n for (const extension of ['.exe', '.com', '.cmd', '.bat']) {\n const found = win32.join(folder, `${program}${extension}`)\n if (!exists(found)) continue\n if (extension === '.exe' || extension === '.com') return { file: found, args: [...args] }\n let text: string\n try {\n text = read(found)\n } catch {\n return { error: `${program} is installed as ${found} but that file cannot be read` }\n }\n const script = SHIM_SCRIPT.exec(text)?.[1]\n if (script === undefined) {\n return {\n error: `${program} is installed as ${found}, a batch file the panel cannot start without a shell (a shell would pass the message through cmd.exe quoting). Install the native program, or an npm package that creates an npm shim`,\n }\n }\n const directory = win32.dirname(found)\n const node = win32.join(directory, 'node.exe')\n return {\n file: exists(node) ? node : execPath,\n args: [win32.join(directory, script), ...args],\n }\n }\n }\n return { error: `${program} was not found on the PATH` }\n}\n","/** The panel's own drivers, all `chat`: the app's agent, and the coding agents (`claude`, `codex`, `pi`) started headless in the app folder. */\nimport { type ChildProcess, spawn, spawnSync } from 'node:child_process'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { ChatDriver, ChatEvent } from '@acryldev/drivers'\nimport { personHome } from '@acryldev/instance/storage'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { resolveLaunch } from './launch.ts'\n\nexport type HeadlessName = 'claude' | 'codex' | 'pi'\n\n/** The command line of each coding agent started headless in the app folder (the same ones the product test uses). */\nexport function command(\n driver: HeadlessName,\n message: string,\n root: string,\n): { file: string; args: string[] } {\n switch (driver) {\n case 'claude':\n return {\n file: 'claude',\n args: [\n '-p',\n message,\n '--permission-mode',\n 'acceptEdits',\n '--allowedTools',\n 'Read,Edit,Write,Glob,Grep,Bash(npm *),Bash(npx *),Bash(node *),Bash(.acryl/bin/acryl *),Bash(curl *)',\n ],\n }\n case 'codex':\n return {\n file: 'codex',\n args: [\n 'exec',\n '--skip-git-repo-check',\n '-s',\n 'workspace-write',\n '-c',\n 'sandbox_workspace_write.network_access=true',\n '-C',\n root,\n message,\n ],\n }\n case 'pi':\n return {\n file: 'pi',\n args: [\n '-p',\n message,\n '--provider',\n 'deepseek',\n '--model',\n 'deepseek-v4-pro',\n '--no-session',\n ],\n }\n }\n}\n\n/** Stop a program and what it started: Windows has no process groups, so the tree goes by its root (`SIGTERM` there ends only the one process). */\nfunction stopProgram(child: ChildProcess): void {\n if (process.platform === 'win32' && child.pid !== undefined) {\n spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore' })\n return\n }\n child.kill('SIGTERM')\n}\n\nexport function onPath(program: string): boolean {\n const found = spawnSync(process.platform === 'win32' ? 'where' : 'which', [program], {\n encoding: 'utf8',\n })\n return found.status === 0\n}\n\n/** Whether pi can reach DeepSeek: the key in the environment, or the one pi stored for itself when its owner logged in (`~/.pi/agent/auth.json`, a `deepseek` entry). */\nexport function piHasDeepseekKey(\n env: NodeJS.ProcessEnv = process.env,\n home: string = personHome(env),\n): boolean {\n if (env.DEEPSEEK_API_KEY) return true\n try {\n const stored = JSON.parse(\n readFileSync(\n join(env.PI_CODING_AGENT_DIR ?? join(home, '.pi', 'agent'), 'auth.json'),\n 'utf8',\n ),\n ) as Record<string, { key?: unknown } | undefined>\n return typeof stored.deepseek?.key === 'string' && stored.deepseek.key !== ''\n } catch {\n return false\n }\n}\n\n/** The headless programs this machine can offer: installed (an executable on the PATH; a wrapper function around it is fine) and, for pi, able to reach its model. */\nexport function availableHeadless(wanted?: readonly HeadlessName[]): HeadlessName[] {\n const found: HeadlessName[] = []\n for (const driver of wanted ?? (['claude', 'codex', 'pi'] as const)) {\n if (driver === 'pi' && !piHasDeepseekKey()) continue\n if (!onPath(driver)) continue\n // On Windows an npm-installed program is offered only when its script can be started directly: a driver that is listed must start.\n if ('error' in resolveLaunch(driver, [])) continue\n found.push(driver)\n }\n return found\n}\n\n/** The app's own agent as a chat driver: its tool calls, then its answer. Aborting the signal cancels the run. */\nexport function agentDriver(ctx: Context): ChatDriver {\n return {\n kind: 'chat',\n name: 'agent',\n async *start({ message, signal, page }) {\n const result = await ctx.agent.run(message, {\n signal,\n ...(page === undefined ? {} : { page }),\n })\n for (const call of result.trace)\n yield {\n event: 'tool',\n data: {\n tool: call.tool,\n input: call.input,\n ...(call.error ? { error: call.error } : { result: call.result }),\n },\n }\n yield {\n event: 'text',\n data: {\n text:\n result.status === 'completed'\n ? result.output\n : result.status === 'cancelled'\n ? 'The run was cancelled.'\n : `The run stopped after ${result.steps} steps without an answer.`,\n },\n }\n },\n }\n}\n\n/** A coding agent run headless in the app folder: its stdout is the answer, its stderr the tool lines. Aborting the signal ends the program. */\nexport function headlessDriver(name: HeadlessName, root: string): ChatDriver {\n return {\n kind: 'chat',\n name,\n async *start({ message, signal }) {\n const wanted = command(name, message, root)\n const launch = resolveLaunch(wanted.file, wanted.args)\n if ('error' in launch) {\n yield { event: 'error', data: { message: launch.error } }\n return\n }\n const child = spawn(launch.file, launch.args, {\n cwd: root,\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const queue: ChatEvent[] = []\n let wake: (() => void) | undefined\n let ended = false\n const push = (event: ChatEvent): void => {\n queue.push(event)\n wake?.()\n }\n signal.addEventListener('abort', () => stopProgram(child), { once: true })\n child.stdout.on('data', (chunk: Buffer) =>\n push({ event: 'text', data: { text: chunk.toString() } }),\n )\n child.stderr.on('data', (chunk: Buffer) =>\n push({ event: 'tool', data: { tool: name, info: chunk.toString().slice(0, 500) } }),\n )\n child.on('error', (cause) => {\n ended = true\n push({\n event: 'error',\n data: { message: `${name} could not be started: ${cause.message}` },\n })\n })\n child.on('exit', (code) => {\n ended = true\n if (code !== 0 && !signal.aborted)\n push({ event: 'error', data: { message: `${name} ended with exit code ${code ?? 1}` } })\n else wake?.()\n })\n try {\n for (;;) {\n const next = queue.shift()\n if (next) yield next\n else if (ended) return\n else await new Promise<void>((resolve) => (wake = resolve))\n }\n } finally {\n if (child.exitCode === null) stopProgram(child)\n }\n },\n }\n}\n\n/**\n * Why a driver name cannot be used to ask a question, in a sentence: it is a terminal (picked in the panel, not asked over `/ask`), it is a coding agent that is not installed or not\n * able to start, or pi without a key to reach its model. Nothing when the name is not one of the headless agents.\n */\nexport function whyNotChat(\n name: string,\n kind: 'chat' | 'terminal' | undefined,\n): string | undefined {\n if (kind === 'terminal')\n return `\"${name}\" is a terminal driver: pick it in the panel to open its terminal; /ask runs the chat drivers`\n if (name !== 'claude' && name !== 'codex' && name !== 'pi') return undefined\n if (!onPath(name))\n return `${name} was not found on the PATH of the app, so the panel cannot start it`\n const launch = resolveLaunch(name, [])\n if ('error' in launch) return launch.error\n if (name === 'pi' && !piHasDeepseekKey())\n return 'pi needs a DeepSeek key: set DEEPSEEK_API_KEY in the environment of the app, or log in with pi once (it keeps the key in ~/.pi/agent/auth.json)'\n return undefined\n}\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,cAAc;;;;AAKpB,SAAgB,cACd,SACA,MACA,OAAmB,CAAC,GACiB;CAErC,KADiB,KAAK,YAAY,QAAQ,cACzB,SAAS,OAAO;EAAE,MAAM;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;CAClE,MAAM,MAAM,KAAK,OAAO,QAAQ;CAChC,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,OAAO,KAAK,UAAU,SAAiB,aAAa,MAAM,MAAM;CACtE,MAAM,WAAW,KAAK,YAAY,QAAQ;CAC1C,MAAM,WAAW,IAAI,QAAQ,IAAI,QAAQ,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CACtE,KAAK,MAAM,UAAU,SACnB,KAAK,MAAM,aAAa;EAAC;EAAQ;EAAQ;EAAQ;CAAM,GAAG;EACxD,MAAM,QAAQ,MAAM,KAAK,QAAQ,GAAG,UAAU,WAAW;EACzD,IAAI,CAAC,OAAO,KAAK,GAAG;EACpB,IAAI,cAAc,UAAU,cAAc,QAAQ,OAAO;GAAE,MAAM;GAAO,MAAM,CAAC,GAAG,IAAI;EAAE;EAC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M,IAAI,SAAe,YAAa,OAAO,OAAQ;IAC5D;GACF,UAAU;IACR,IAAI,MAAM,aAAa,MAAM,YAAY,KAAK;GAChD;EACF;CACF;AACF;;;;;AAMA,SAAgB,WACd,MACA,MACoB;CACpB,IAAI,SAAS,YACX,OAAO,IAAI,KAAK;CAClB,IAAI,SAAS,YAAY,SAAS,WAAW,SAAS,MAAM,OAAO,KAAA;CACnE,IAAI,CAAC,OAAO,IAAI,GACd,OAAO,GAAG,KAAK;CACjB,MAAM,SAAS,cAAc,MAAM,CAAC,CAAC;CACrC,IAAI,WAAW,QAAQ,OAAO,OAAO;CACrC,IAAI,SAAS,QAAQ,CAAC,iBAAiB,GACrC,OAAO;AAEX"}
@@ -0,0 +1,2 @@
1
+ import { a as onPath, i as headlessDriver, n as availableHeadless, o as piHasDeepseekKey, r as command, s as whyNotChat, t as agentDriver } from "./headless-B_RGxZFU.js";
2
+ export { agentDriver, availableHeadless, command, headlessDriver, onPath, piHasDeepseekKey, whyNotChat };