@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
+ }
package/headless.ts ADDED
@@ -0,0 +1,220 @@
1
+ /** The panel's own drivers, all `chat`: the app's agent, and the coding agents (`claude`, `codex`, `pi`) started headless in the app folder. */
2
+ import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
3
+ import { readFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import type { ChatDriver, ChatEvent } from '@acryldev/drivers'
6
+ import { personHome } from '@acryldev/instance/storage'
7
+ import type { Context } from '@deepseek-ai/cordis'
8
+ import { resolveLaunch } from './launch.ts'
9
+
10
+ export type HeadlessName = 'claude' | 'codex' | 'pi'
11
+
12
+ /** The command line of each coding agent started headless in the app folder (the same ones the product test uses). */
13
+ export function command(
14
+ driver: HeadlessName,
15
+ message: string,
16
+ root: string,
17
+ ): { file: string; args: string[] } {
18
+ switch (driver) {
19
+ case 'claude':
20
+ return {
21
+ file: 'claude',
22
+ args: [
23
+ '-p',
24
+ message,
25
+ '--permission-mode',
26
+ 'acceptEdits',
27
+ '--allowedTools',
28
+ 'Read,Edit,Write,Glob,Grep,Bash(npm *),Bash(npx *),Bash(node *),Bash(.acryl/bin/acryl *),Bash(curl *)',
29
+ ],
30
+ }
31
+ case 'codex':
32
+ return {
33
+ file: 'codex',
34
+ args: [
35
+ 'exec',
36
+ '--skip-git-repo-check',
37
+ '-s',
38
+ 'workspace-write',
39
+ '-c',
40
+ 'sandbox_workspace_write.network_access=true',
41
+ '-C',
42
+ root,
43
+ message,
44
+ ],
45
+ }
46
+ case 'pi':
47
+ return {
48
+ file: 'pi',
49
+ args: [
50
+ '-p',
51
+ message,
52
+ '--provider',
53
+ 'deepseek',
54
+ '--model',
55
+ 'deepseek-v4-pro',
56
+ '--no-session',
57
+ ],
58
+ }
59
+ }
60
+ }
61
+
62
+ /** 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). */
63
+ function stopProgram(child: ChildProcess): void {
64
+ if (process.platform === 'win32' && child.pid !== undefined) {
65
+ spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore' })
66
+ return
67
+ }
68
+ child.kill('SIGTERM')
69
+ }
70
+
71
+ export function onPath(program: string): boolean {
72
+ const found = spawnSync(process.platform === 'win32' ? 'where' : 'which', [program], {
73
+ encoding: 'utf8',
74
+ })
75
+ return found.status === 0
76
+ }
77
+
78
+ /** 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). */
79
+ export function piHasDeepseekKey(
80
+ env: NodeJS.ProcessEnv = process.env,
81
+ home: string = personHome(env),
82
+ ): boolean {
83
+ if (env.DEEPSEEK_API_KEY) return true
84
+ try {
85
+ const stored = JSON.parse(
86
+ readFileSync(
87
+ join(env.PI_CODING_AGENT_DIR ?? join(home, '.pi', 'agent'), 'auth.json'),
88
+ 'utf8',
89
+ ),
90
+ ) as Record<string, { key?: unknown } | undefined>
91
+ return typeof stored.deepseek?.key === 'string' && stored.deepseek.key !== ''
92
+ } catch {
93
+ return false
94
+ }
95
+ }
96
+
97
+ /** 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. */
98
+ export function availableHeadless(wanted?: readonly HeadlessName[]): HeadlessName[] {
99
+ const found: HeadlessName[] = []
100
+ for (const driver of wanted ?? (['claude', 'codex', 'pi'] as const)) {
101
+ if (driver === 'pi' && !piHasDeepseekKey()) continue
102
+ if (!onPath(driver)) continue
103
+ // On Windows an npm-installed program is offered only when its script can be started directly: a driver that is listed must start.
104
+ if ('error' in resolveLaunch(driver, [])) continue
105
+ found.push(driver)
106
+ }
107
+ return found
108
+ }
109
+
110
+ /** The app's own agent as a chat driver: its tool calls, then its answer. Aborting the signal cancels the run. */
111
+ export function agentDriver(ctx: Context): ChatDriver {
112
+ return {
113
+ kind: 'chat',
114
+ name: 'agent',
115
+ async *start({ message, signal, page }) {
116
+ const result = await ctx.agent.run(message, {
117
+ signal,
118
+ ...(page === undefined ? {} : { page }),
119
+ })
120
+ for (const call of result.trace)
121
+ yield {
122
+ event: 'tool',
123
+ data: {
124
+ tool: call.tool,
125
+ input: call.input,
126
+ ...(call.error ? { error: call.error } : { result: call.result }),
127
+ },
128
+ }
129
+ yield {
130
+ event: 'text',
131
+ data: {
132
+ text:
133
+ result.status === 'completed'
134
+ ? result.output
135
+ : result.status === 'cancelled'
136
+ ? 'The run was cancelled.'
137
+ : `The run stopped after ${result.steps} steps without an answer.`,
138
+ },
139
+ }
140
+ },
141
+ }
142
+ }
143
+
144
+ /** 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. */
145
+ export function headlessDriver(name: HeadlessName, root: string): ChatDriver {
146
+ return {
147
+ kind: 'chat',
148
+ name,
149
+ async *start({ message, signal }) {
150
+ const wanted = command(name, message, root)
151
+ const launch = resolveLaunch(wanted.file, wanted.args)
152
+ if ('error' in launch) {
153
+ yield { event: 'error', data: { message: launch.error } }
154
+ return
155
+ }
156
+ const child = spawn(launch.file, launch.args, {
157
+ cwd: root,
158
+ env: process.env,
159
+ stdio: ['ignore', 'pipe', 'pipe'],
160
+ })
161
+ const queue: ChatEvent[] = []
162
+ let wake: (() => void) | undefined
163
+ let ended = false
164
+ const push = (event: ChatEvent): void => {
165
+ queue.push(event)
166
+ wake?.()
167
+ }
168
+ signal.addEventListener('abort', () => stopProgram(child), { once: true })
169
+ child.stdout.on('data', (chunk: Buffer) =>
170
+ push({ event: 'text', data: { text: chunk.toString() } }),
171
+ )
172
+ child.stderr.on('data', (chunk: Buffer) =>
173
+ push({ event: 'tool', data: { tool: name, info: chunk.toString().slice(0, 500) } }),
174
+ )
175
+ child.on('error', (cause) => {
176
+ ended = true
177
+ push({
178
+ event: 'error',
179
+ data: { message: `${name} could not be started: ${cause.message}` },
180
+ })
181
+ })
182
+ child.on('exit', (code) => {
183
+ ended = true
184
+ if (code !== 0 && !signal.aborted)
185
+ push({ event: 'error', data: { message: `${name} ended with exit code ${code ?? 1}` } })
186
+ else wake?.()
187
+ })
188
+ try {
189
+ for (;;) {
190
+ const next = queue.shift()
191
+ if (next) yield next
192
+ else if (ended) return
193
+ else await new Promise<void>((resolve) => (wake = resolve))
194
+ }
195
+ } finally {
196
+ if (child.exitCode === null) stopProgram(child)
197
+ }
198
+ },
199
+ }
200
+ }
201
+
202
+ /**
203
+ * 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
204
+ * able to start, or pi without a key to reach its model. Nothing when the name is not one of the headless agents.
205
+ */
206
+ export function whyNotChat(
207
+ name: string,
208
+ kind: 'chat' | 'terminal' | undefined,
209
+ ): string | undefined {
210
+ if (kind === 'terminal')
211
+ return `"${name}" is a terminal driver: pick it in the panel to open its terminal; /ask runs the chat drivers`
212
+ if (name !== 'claude' && name !== 'codex' && name !== 'pi') return undefined
213
+ if (!onPath(name))
214
+ return `${name} was not found on the PATH of the app, so the panel cannot start it`
215
+ const launch = resolveLaunch(name, [])
216
+ if ('error' in launch) return launch.error
217
+ if (name === 'pi' && !piHasDeepseekKey())
218
+ 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)'
219
+ return undefined
220
+ }