acrylblends 0.9.2 → 0.11.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.js.map +1 -1
- package/docs/framework/cordis/node-server.md +25 -3
- package/lib/bun.d.ts +1 -1
- package/lib/cloudflare-workers.d.ts +1 -1
- package/lib/cordis/door.d.ts +2 -1
- package/lib/cordis/door.js +7 -4
- package/lib/cordis/inspect.js +1 -1
- package/lib/cordis/node-server.d.ts +14 -2
- package/lib/cordis/node-server.js +27 -3
- package/lib/cordis/router-http.d.ts +25 -2
- package/lib/cordis/router-http.js +54 -6
- package/lib/cordis/router.d.ts +1 -1
- package/lib/cordis/router.js +1 -1
- package/lib/cordis/state.js +1 -1
- package/lib/door/host.js +1 -1
- package/lib/{index-BvFh1Gfx.d.ts → index-C-SklY6u.d.ts} +3 -0
- package/lib/{index-BqVQkTnu.d.ts → index-D4nVR3wu.d.ts} +18 -3
- package/lib/node-server.d.ts +2 -38
- package/lib/node-server.js +2 -2
- package/lib/{snapshot-text-D3NspDyT.js → snapshot-text-yaWlezbd.js} +1 -1
- package/lib/{src-CwABFr6r.js → src-DNzw0Qsb.js} +3 -2
- package/lib/test-websocket-DyeS50Tr.d.ts +136 -0
- package/lib/{server-DvgMGtzo.js → test-websocket-ZXHNHQSU.js} +225 -3
- package/lib/ws.d.ts +1 -1
- package/lib/ws.js +3 -0
- package/package.json +6 -2
- package/plugins/acryl-door/src/host/door.ts +5 -3
- package/plugins/acryl-door/src/index.ts +1 -1
- package/plugins/acryl-node-server/plugin.json +1 -1
- package/plugins/acryl-node-server/src/adapter/websocket-types.ts +5 -1
- package/plugins/acryl-node-server/src/adapter/websocket.ts +33 -5
- package/plugins/acryl-node-server/src/index.ts +35 -1
- package/plugins/acryl-node-server/src/test-websocket.ts +110 -0
- package/plugins/acryl-node-server/src/upgrade-hub.ts +152 -0
- package/plugins/acryl-router/src/core/helper/websocket/index.ts +5 -0
- package/plugins/acryl-router/src/service.ts +18 -4
- package/plugins/acryl-router-http/plugin.json +2 -2
- package/plugins/acryl-router-http/src/index.ts +70 -6
- package/plugins/agent-panel/client/main.ts +70 -2
- package/plugins/agent-panel/drivers.ts +83 -0
- package/plugins/agent-panel/headless.ts +154 -0
- package/plugins/agent-panel/index.ts +42 -125
- package/plugins/agent-panel/plugin.json +1 -1
- package/plugins/driver-pty/client/terminal.ts +188 -0
- package/plugins/driver-pty/client/vendor/LICENSE +21 -0
- package/plugins/driver-pty/client/vendor/LICENSE-addon-fit +19 -0
- package/plugins/driver-pty/client/vendor/VERSION +4 -0
- package/plugins/driver-pty/client/vendor/addon-fit.d.mts +6 -0
- package/plugins/driver-pty/client/vendor/addon-fit.mjs +18 -0
- package/plugins/driver-pty/client/vendor/xterm-css.d.mts +2 -0
- package/plugins/driver-pty/client/vendor/xterm-css.mjs +2 -0
- package/plugins/driver-pty/client/vendor/xterm.d.mts +17 -0
- package/plugins/driver-pty/client/vendor/xterm.mjs +53 -0
- package/plugins/driver-pty/index.ts +249 -0
- package/plugins/driver-pty/plugin.json +13 -0
- package/plugins/driver-pty/spawn.ts +36 -0
- package/plugins/driver-pty/terminal.ts +84 -0
- package/shared/AGENTS.core.md +1 -1
- package/shared/DEFAULTS.md +1 -1
- package/lib/error-t4N2js2I.d.ts +0 -8
|
@@ -0,0 +1,154 @@
|
|
|
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 { spawn, spawnSync } from 'node:child_process'
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import type { ChatDriver, ChatEvent } from './drivers.ts'
|
|
5
|
+
|
|
6
|
+
export type HeadlessName = 'claude' | 'codex' | 'pi'
|
|
7
|
+
|
|
8
|
+
/** The command line of each coding agent started headless in the app folder (the same ones the product test uses). */
|
|
9
|
+
export function command(
|
|
10
|
+
driver: HeadlessName,
|
|
11
|
+
message: string,
|
|
12
|
+
root: string,
|
|
13
|
+
): { file: string; args: string[] } {
|
|
14
|
+
switch (driver) {
|
|
15
|
+
case 'claude':
|
|
16
|
+
return {
|
|
17
|
+
file: 'claude',
|
|
18
|
+
args: [
|
|
19
|
+
'-p',
|
|
20
|
+
message,
|
|
21
|
+
'--permission-mode',
|
|
22
|
+
'acceptEdits',
|
|
23
|
+
'--allowedTools',
|
|
24
|
+
'Read,Edit,Write,Glob,Grep,Bash(npm *),Bash(npx *),Bash(node *),Bash(.acryl/bin/acryl *),Bash(curl *)',
|
|
25
|
+
],
|
|
26
|
+
}
|
|
27
|
+
case 'codex':
|
|
28
|
+
return {
|
|
29
|
+
file: 'codex',
|
|
30
|
+
args: [
|
|
31
|
+
'exec',
|
|
32
|
+
'--skip-git-repo-check',
|
|
33
|
+
'-s',
|
|
34
|
+
'workspace-write',
|
|
35
|
+
'-c',
|
|
36
|
+
'sandbox_workspace_write.network_access=true',
|
|
37
|
+
'-C',
|
|
38
|
+
root,
|
|
39
|
+
message,
|
|
40
|
+
],
|
|
41
|
+
}
|
|
42
|
+
case 'pi':
|
|
43
|
+
return {
|
|
44
|
+
file: 'pi',
|
|
45
|
+
args: [
|
|
46
|
+
'-p',
|
|
47
|
+
message,
|
|
48
|
+
'--provider',
|
|
49
|
+
'deepseek',
|
|
50
|
+
'--model',
|
|
51
|
+
'deepseek-v4-pro',
|
|
52
|
+
'--no-session',
|
|
53
|
+
],
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function onPath(program: string): boolean {
|
|
59
|
+
const found = spawnSync(process.platform === 'win32' ? 'where' : 'which', [program], {
|
|
60
|
+
encoding: 'utf8',
|
|
61
|
+
})
|
|
62
|
+
return found.status === 0
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The headless programs this machine can offer: installed (pi also needs its key in the environment). */
|
|
66
|
+
export function availableHeadless(wanted?: readonly HeadlessName[]): HeadlessName[] {
|
|
67
|
+
const found: HeadlessName[] = []
|
|
68
|
+
for (const driver of wanted ?? (['claude', 'codex', 'pi'] as const)) {
|
|
69
|
+
if (driver === 'pi' && !process.env.DEEPSEEK_API_KEY) continue
|
|
70
|
+
if (onPath(driver)) found.push(driver)
|
|
71
|
+
}
|
|
72
|
+
return found
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The app's own agent as a chat driver: its tool calls, then its answer. Aborting the signal cancels the run. */
|
|
76
|
+
export function agentDriver(ctx: Context): ChatDriver {
|
|
77
|
+
return {
|
|
78
|
+
kind: 'chat',
|
|
79
|
+
name: 'agent',
|
|
80
|
+
async *start({ message, signal }) {
|
|
81
|
+
const result = await ctx.agent.run(message, { signal })
|
|
82
|
+
for (const call of result.trace)
|
|
83
|
+
yield {
|
|
84
|
+
event: 'tool',
|
|
85
|
+
data: {
|
|
86
|
+
tool: call.tool,
|
|
87
|
+
input: call.input,
|
|
88
|
+
...(call.error ? { error: call.error } : { result: call.result }),
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
yield {
|
|
92
|
+
event: 'text',
|
|
93
|
+
data: {
|
|
94
|
+
text:
|
|
95
|
+
result.status === 'completed'
|
|
96
|
+
? result.output
|
|
97
|
+
: result.status === 'cancelled'
|
|
98
|
+
? 'The run was cancelled.'
|
|
99
|
+
: `The run stopped after ${result.steps} steps without an answer.`,
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 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. */
|
|
107
|
+
export function headlessDriver(name: HeadlessName, root: string): ChatDriver {
|
|
108
|
+
return {
|
|
109
|
+
kind: 'chat',
|
|
110
|
+
name,
|
|
111
|
+
async *start({ message, signal }) {
|
|
112
|
+
const { file, args } = command(name, message, root)
|
|
113
|
+
const child = spawn(file, args, {
|
|
114
|
+
cwd: root,
|
|
115
|
+
env: process.env,
|
|
116
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
117
|
+
})
|
|
118
|
+
const queue: ChatEvent[] = []
|
|
119
|
+
let wake: (() => void) | undefined
|
|
120
|
+
let ended = false
|
|
121
|
+
const push = (event: ChatEvent): void => {
|
|
122
|
+
queue.push(event)
|
|
123
|
+
wake?.()
|
|
124
|
+
}
|
|
125
|
+
signal.addEventListener('abort', () => child.kill('SIGTERM'), { once: true })
|
|
126
|
+
child.stdout.on('data', (chunk: Buffer) =>
|
|
127
|
+
push({ event: 'text', data: { text: chunk.toString() } }),
|
|
128
|
+
)
|
|
129
|
+
child.stderr.on('data', (chunk: Buffer) =>
|
|
130
|
+
push({ event: 'tool', data: { tool: name, info: chunk.toString().slice(0, 500) } }),
|
|
131
|
+
)
|
|
132
|
+
child.on('error', () => {
|
|
133
|
+
ended = true
|
|
134
|
+
push({ event: 'error', data: { message: `${name} could not be started` } })
|
|
135
|
+
})
|
|
136
|
+
child.on('exit', (code) => {
|
|
137
|
+
ended = true
|
|
138
|
+
if (code !== 0 && !signal.aborted)
|
|
139
|
+
push({ event: 'error', data: { message: `${name} ended with exit code ${code ?? 1}` } })
|
|
140
|
+
else wake?.()
|
|
141
|
+
})
|
|
142
|
+
try {
|
|
143
|
+
for (;;) {
|
|
144
|
+
const next = queue.shift()
|
|
145
|
+
if (next) yield next
|
|
146
|
+
else if (ended) return
|
|
147
|
+
else await new Promise<void>((resolve) => (wake = resolve))
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
if (child.exitCode === null) child.kill('SIGTERM')
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
}
|
|
154
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The built-in agent (spec 049 slice 14): a chat panel inside the running app. The person says what they want; the app's own agent (`driver: 'agent'`) or a coding
|
|
3
3
|
* agent started in the app folder (`'claude'`, `'codex'`, `'pi'`) builds it through the door, and when a plugin was installed or removed the page reloads, so the new feature
|
|
4
|
-
* shows with no restart.
|
|
4
|
+
* shows with no restart. The drivers are entries of the `drivers` service this plugin provides (`drivers.ts`): chat drivers here, and other plugins (`driver-pty`) add more.
|
|
5
5
|
*
|
|
6
6
|
* - A middleware appends one script tag (`/api/agent-panel/panel.js`) to every HTML response of the routes mounted after it, so no page is edited.
|
|
7
7
|
* - `GET /api/agent-panel/session` gives the page the drivers it may use and a token; `POST /api/agent-panel/ask` runs one message and answers server-sent events:
|
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
* - Only the app's own page may ask (a same-origin request carrying the token), one run at a time, and every ask is written to `.acryl/audit/agent-panel.jsonl`.
|
|
10
10
|
* - Development only: the plugin does nothing with `NODE_ENV=production` or `ACRYL_DOOR=off`.
|
|
11
11
|
*/
|
|
12
|
-
import { spawn, spawnSync } from 'node:child_process'
|
|
13
12
|
import { randomBytes } from 'node:crypto'
|
|
14
13
|
import { appendFileSync, mkdirSync } from 'node:fs'
|
|
15
14
|
import { dirname, join } from 'node:path'
|
|
@@ -19,6 +18,17 @@ import { streamSSE } from '../acryl-router/src/helpers/index.ts'
|
|
|
19
18
|
import { Acryl } from '../acryl-router/src/index.ts'
|
|
20
19
|
import type {} from '../agent/index.ts'
|
|
21
20
|
import type {} from '../extensions/index.ts'
|
|
21
|
+
import { provideDrivers } from './drivers.ts'
|
|
22
|
+
import { agentDriver, availableHeadless, type HeadlessName, headlessDriver } from './headless.ts'
|
|
23
|
+
|
|
24
|
+
export type {
|
|
25
|
+
ChatDriver,
|
|
26
|
+
ChatEvent,
|
|
27
|
+
Driver,
|
|
28
|
+
Drivers,
|
|
29
|
+
TerminalDriver,
|
|
30
|
+
TerminalSession,
|
|
31
|
+
} from './drivers.ts'
|
|
22
32
|
|
|
23
33
|
export const name = 'agent-panel'
|
|
24
34
|
export const inject = ['router', 'agent', 'extensions', 'appInstance']
|
|
@@ -26,78 +36,9 @@ export const inject = ['router', 'agent', 'extensions', 'appInstance']
|
|
|
26
36
|
const PREFIX = '/api/agent-panel'
|
|
27
37
|
const CLIENT_DIR = join(import.meta.dirname, 'client')
|
|
28
38
|
|
|
29
|
-
export type DriverName = 'agent' | 'claude' | 'codex' | 'pi'
|
|
30
|
-
|
|
31
39
|
export interface PanelConfig {
|
|
32
|
-
/**
|
|
33
|
-
drivers?: readonly
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** The command line of each coding agent started headless in the app folder (the same ones the product test uses). */
|
|
37
|
-
function command(
|
|
38
|
-
driver: Exclude<DriverName, 'agent'>,
|
|
39
|
-
message: string,
|
|
40
|
-
root: string,
|
|
41
|
-
): { file: string; args: string[] } {
|
|
42
|
-
switch (driver) {
|
|
43
|
-
case 'claude':
|
|
44
|
-
return {
|
|
45
|
-
file: 'claude',
|
|
46
|
-
args: [
|
|
47
|
-
'-p',
|
|
48
|
-
message,
|
|
49
|
-
'--permission-mode',
|
|
50
|
-
'acceptEdits',
|
|
51
|
-
'--allowedTools',
|
|
52
|
-
'Read,Edit,Write,Glob,Grep,Bash(npm *),Bash(npx *),Bash(node *),Bash(.acryl/bin/acryl *),Bash(curl *)',
|
|
53
|
-
],
|
|
54
|
-
}
|
|
55
|
-
case 'codex':
|
|
56
|
-
return {
|
|
57
|
-
file: 'codex',
|
|
58
|
-
args: [
|
|
59
|
-
'exec',
|
|
60
|
-
'--skip-git-repo-check',
|
|
61
|
-
'-s',
|
|
62
|
-
'workspace-write',
|
|
63
|
-
'-c',
|
|
64
|
-
'sandbox_workspace_write.network_access=true',
|
|
65
|
-
'-C',
|
|
66
|
-
root,
|
|
67
|
-
message,
|
|
68
|
-
],
|
|
69
|
-
}
|
|
70
|
-
case 'pi':
|
|
71
|
-
return {
|
|
72
|
-
file: 'pi',
|
|
73
|
-
args: [
|
|
74
|
-
'-p',
|
|
75
|
-
message,
|
|
76
|
-
'--provider',
|
|
77
|
-
'deepseek',
|
|
78
|
-
'--model',
|
|
79
|
-
'deepseek-v4-pro',
|
|
80
|
-
'--no-session',
|
|
81
|
-
],
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function onPath(program: string): boolean {
|
|
87
|
-
const found = spawnSync(process.platform === 'win32' ? 'where' : 'which', [program], {
|
|
88
|
-
encoding: 'utf8',
|
|
89
|
-
})
|
|
90
|
-
return found.status === 0
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** The drivers this machine can offer: the app's own agent always; a program when it is installed (pi also needs its key in the environment). */
|
|
94
|
-
export function availableDrivers(wanted?: readonly Exclude<DriverName, 'agent'>[]): DriverName[] {
|
|
95
|
-
const found: DriverName[] = ['agent']
|
|
96
|
-
for (const driver of wanted ?? (['claude', 'codex', 'pi'] as const)) {
|
|
97
|
-
if (driver === 'pi' && !process.env.DEEPSEEK_API_KEY) continue
|
|
98
|
-
if (onPath(driver)) found.push(driver)
|
|
99
|
-
}
|
|
100
|
-
return found
|
|
40
|
+
/** Headless coding agents to offer besides the app's own agent; default: the ones found on the machine. */
|
|
41
|
+
drivers?: readonly HeadlessName[]
|
|
101
42
|
}
|
|
102
43
|
|
|
103
44
|
/** Whether a request comes from the app's own page: a browser says so itself (`Sec-Fetch-Site: same-origin`), or the Origin is the Host. */
|
|
@@ -122,7 +63,13 @@ export function apply(ctx: Context, config: PanelConfig = {}): void {
|
|
|
122
63
|
// The audit never stops a run.
|
|
123
64
|
}
|
|
124
65
|
}
|
|
125
|
-
const
|
|
66
|
+
const registry = provideDrivers(
|
|
67
|
+
ctx,
|
|
68
|
+
(headers) => fromOwnPage(headers) && headers.get('x-agent-panel-token') === token,
|
|
69
|
+
)
|
|
70
|
+
ctx.effect(() => registry.register(agentDriver(ctx)))
|
|
71
|
+
for (const program of availableHeadless(config.drivers))
|
|
72
|
+
ctx.effect(() => registry.register(headlessDriver(program, root)))
|
|
126
73
|
let running = false
|
|
127
74
|
|
|
128
75
|
const tag = `<script type="module" src="${PREFIX}/panel.js"></script>`
|
|
@@ -149,19 +96,29 @@ export function apply(ctx: Context, config: PanelConfig = {}): void {
|
|
|
149
96
|
.get(`${PREFIX}/session`, (c) => {
|
|
150
97
|
if (!fromOwnPage(c.req.raw.headers))
|
|
151
98
|
return c.json({ error: "only the app's own page may use the panel" }, 403)
|
|
152
|
-
return c.json({
|
|
99
|
+
return c.json({
|
|
100
|
+
token,
|
|
101
|
+
drivers: registry.list().map((driver) => ({ name: driver.name, kind: driver.kind })),
|
|
102
|
+
})
|
|
153
103
|
})
|
|
154
104
|
.post(`${PREFIX}/ask`, async (c) => {
|
|
155
105
|
if (!fromOwnPage(c.req.raw.headers) || c.req.header('x-agent-panel-token') !== token)
|
|
156
106
|
return c.json({ error: "only the app's own page may ask" }, 403)
|
|
157
107
|
const body = (await c.req.json().catch(() => ({}))) as { message?: unknown; driver?: unknown }
|
|
158
108
|
const message = typeof body.message === 'string' ? body.message.trim() : ''
|
|
159
|
-
const
|
|
109
|
+
const driverName = typeof body.driver === 'string' ? body.driver : 'agent'
|
|
160
110
|
if (message === '' || message.length > 8000)
|
|
161
111
|
return c.json({ error: 'write a message of at most 8000 characters' }, 400)
|
|
162
|
-
|
|
112
|
+
const driver = registry.get(driverName)
|
|
113
|
+
if (driver?.kind !== 'chat')
|
|
163
114
|
return c.json(
|
|
164
|
-
{
|
|
115
|
+
{
|
|
116
|
+
error: `the driver "${driverName}" is not available here (${registry
|
|
117
|
+
.list()
|
|
118
|
+
.filter((d) => d.kind === 'chat')
|
|
119
|
+
.map((d) => d.name)
|
|
120
|
+
.join(', ')})`,
|
|
121
|
+
},
|
|
165
122
|
400,
|
|
166
123
|
)
|
|
167
124
|
if (running) return c.json({ error: 'a run is already going; wait for it to end' }, 409)
|
|
@@ -174,60 +131,20 @@ export function apply(ctx: Context, config: PanelConfig = {}): void {
|
|
|
174
131
|
changed = true
|
|
175
132
|
void send('change', { extension, action })
|
|
176
133
|
})
|
|
177
|
-
audit({ ask: 'start', driver, characters: message.length })
|
|
134
|
+
audit({ ask: 'start', driver: driverName, characters: message.length })
|
|
135
|
+
// Stop in the page closes the stream; that cancels the run (the model call, the tool or the program in flight is dropped).
|
|
136
|
+
const cancel = new AbortController()
|
|
137
|
+
stream.onAbort(() => cancel.abort())
|
|
178
138
|
try {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
const cancel = new AbortController()
|
|
182
|
-
stream.onAbort(() => cancel.abort())
|
|
183
|
-
const result = await ctx.agent.run(message, { signal: cancel.signal })
|
|
184
|
-
for (const call of result.trace)
|
|
185
|
-
await send('tool', {
|
|
186
|
-
tool: call.tool,
|
|
187
|
-
input: call.input,
|
|
188
|
-
...(call.error ? { error: call.error } : { result: call.result }),
|
|
189
|
-
})
|
|
190
|
-
await send('text', {
|
|
191
|
-
text:
|
|
192
|
-
result.status === 'completed'
|
|
193
|
-
? result.output
|
|
194
|
-
: result.status === 'cancelled'
|
|
195
|
-
? 'The run was cancelled.'
|
|
196
|
-
: `The run stopped after ${result.steps} steps without an answer.`,
|
|
197
|
-
})
|
|
198
|
-
} else {
|
|
199
|
-
const { file, args } = command(driver, message, root)
|
|
200
|
-
const child = spawn(file, args, {
|
|
201
|
-
cwd: root,
|
|
202
|
-
env: process.env,
|
|
203
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
204
|
-
})
|
|
205
|
-
stream.onAbort(() => {
|
|
206
|
-
child.kill('SIGTERM')
|
|
207
|
-
})
|
|
208
|
-
child.stdout.on(
|
|
209
|
-
'data',
|
|
210
|
-
(chunk: Buffer) => void send('text', { text: chunk.toString() }),
|
|
211
|
-
)
|
|
212
|
-
child.stderr.on(
|
|
213
|
-
'data',
|
|
214
|
-
(chunk: Buffer) =>
|
|
215
|
-
void send('tool', { tool: driver, info: chunk.toString().slice(0, 500) }),
|
|
216
|
-
)
|
|
217
|
-
const code = await new Promise<number>((done) => {
|
|
218
|
-
child.on('error', () => done(1))
|
|
219
|
-
child.on('exit', (exit) => done(exit ?? 1))
|
|
220
|
-
})
|
|
221
|
-
if (code !== 0)
|
|
222
|
-
await send('error', { message: `${driver} ended with exit code ${code}` })
|
|
223
|
-
}
|
|
139
|
+
for await (const { event, data } of driver.start({ message, signal: cancel.signal }))
|
|
140
|
+
await send(event, data)
|
|
224
141
|
await send('done', { changed })
|
|
225
142
|
} catch (error) {
|
|
226
143
|
await send('error', { message: error instanceof Error ? error.message : String(error) })
|
|
227
144
|
} finally {
|
|
228
145
|
off()
|
|
229
146
|
running = false
|
|
230
|
-
audit({ ask: 'end', driver, changed })
|
|
147
|
+
audit({ ask: 'end', driver: driverName, changed })
|
|
231
148
|
}
|
|
232
149
|
})
|
|
233
150
|
})
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// The terminal tab of the agent panel: xterm.js in the page, a real terminal on the server (the `driver-pty` plugin). Output arrives as server-sent events with ids (fetch
|
|
2
|
+
// reads the stream, so the panel's token header can be sent; a dropped stream is reopened from the last id), keystrokes go up as POSTs batched per animation frame.
|
|
3
|
+
import { FitAddon } from './vendor/addon-fit.mjs'
|
|
4
|
+
import { Terminal } from './vendor/xterm.mjs'
|
|
5
|
+
import css from './vendor/xterm-css.mjs'
|
|
6
|
+
|
|
7
|
+
const PREFIX = '/api/driver-pty'
|
|
8
|
+
const REMEMBERED = 'driver-pty-session'
|
|
9
|
+
|
|
10
|
+
export interface TerminalView {
|
|
11
|
+
/** Ends the view (not the session): the server keeps the terminal for a re-attach. */
|
|
12
|
+
detach(): void
|
|
13
|
+
/** Stops the session on the server. */
|
|
14
|
+
stop(): Promise<void>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface Options {
|
|
18
|
+
/** Where the terminal goes: a node inside the panel's shadow root. */
|
|
19
|
+
container: HTMLElement
|
|
20
|
+
/** The panel's session token. */
|
|
21
|
+
token: string
|
|
22
|
+
/** The terminal driver's name (`pty:claude`). */
|
|
23
|
+
driver: string
|
|
24
|
+
/** Called with a line of status for the panel to show (`The terminal ended (exit 0).`). */
|
|
25
|
+
status(text: string): void
|
|
26
|
+
/** A plugin was installed or removed while the terminal was open. */
|
|
27
|
+
onChange(change: { extension: string; action: string }): void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Frame {
|
|
31
|
+
event: string
|
|
32
|
+
id?: string
|
|
33
|
+
data: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function* frames(response: Response): AsyncGenerator<Frame> {
|
|
37
|
+
const reader = response.body!.getReader()
|
|
38
|
+
const decoder = new TextDecoder()
|
|
39
|
+
let buffer = ''
|
|
40
|
+
for (;;) {
|
|
41
|
+
const { value, done } = await reader.read()
|
|
42
|
+
if (done) return
|
|
43
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/gu, '\n')
|
|
44
|
+
for (let end = buffer.indexOf('\n\n'); end !== -1; end = buffer.indexOf('\n\n')) {
|
|
45
|
+
const block = buffer.slice(0, end)
|
|
46
|
+
buffer = buffer.slice(end + 2)
|
|
47
|
+
const frame: Frame = { event: 'message', data: '' }
|
|
48
|
+
for (const line of block.split('\n')) {
|
|
49
|
+
if (line.startsWith('event:')) frame.event = line.slice(6).trim()
|
|
50
|
+
else if (line.startsWith('id:')) frame.id = line.slice(3).trim()
|
|
51
|
+
else if (line.startsWith('data:')) frame.data += line.slice(5).trimStart()
|
|
52
|
+
}
|
|
53
|
+
yield frame
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function openTerminal(options: Options): Promise<TerminalView> {
|
|
59
|
+
const { container, token, driver, status, onChange } = options
|
|
60
|
+
const headers = { 'content-type': 'application/json', 'x-agent-panel-token': token }
|
|
61
|
+
const call = (path: string, body: unknown = {}): Promise<Response> =>
|
|
62
|
+
fetch(`${PREFIX}${path}`, { method: 'POST', headers, body: JSON.stringify(body) })
|
|
63
|
+
|
|
64
|
+
const style = document.createElement('style')
|
|
65
|
+
style.textContent = `${css}\n.xterm { height: 100%; padding: 4px }`
|
|
66
|
+
container.append(style)
|
|
67
|
+
const host = document.createElement('div')
|
|
68
|
+
host.style.cssText = 'width:100%;height:100%'
|
|
69
|
+
container.append(host)
|
|
70
|
+
const term = new Terminal({ cursorBlink: true, fontSize: 13, convertEol: false })
|
|
71
|
+
const fit = new FitAddon()
|
|
72
|
+
term.loadAddon(fit)
|
|
73
|
+
term.open(host)
|
|
74
|
+
fit.fit()
|
|
75
|
+
|
|
76
|
+
// A terminal the page opened earlier is re-attached (a reload keeps the session on the server); otherwise a new one starts.
|
|
77
|
+
let id: string | undefined
|
|
78
|
+
try {
|
|
79
|
+
const remembered = JSON.parse(sessionStorage.getItem(REMEMBERED) ?? 'null') as {
|
|
80
|
+
id: string
|
|
81
|
+
driver: string
|
|
82
|
+
} | null
|
|
83
|
+
if (remembered?.driver === driver) id = remembered.id
|
|
84
|
+
} catch {
|
|
85
|
+
// No storage: always a new terminal.
|
|
86
|
+
}
|
|
87
|
+
let ended = false
|
|
88
|
+
let lastId = 0
|
|
89
|
+
const abort = new AbortController()
|
|
90
|
+
|
|
91
|
+
const start = async (): Promise<boolean> => {
|
|
92
|
+
const reply = await call('/sessions', { driver, cols: term.cols, rows: term.rows })
|
|
93
|
+
const body = (await reply.json().catch(() => ({}))) as { id?: string; error?: string }
|
|
94
|
+
if (!reply.ok || !body.id) {
|
|
95
|
+
status(body.error ?? `The terminal could not start (${reply.status}).`)
|
|
96
|
+
return false
|
|
97
|
+
}
|
|
98
|
+
id = body.id
|
|
99
|
+
lastId = 0
|
|
100
|
+
try {
|
|
101
|
+
sessionStorage.setItem(REMEMBERED, JSON.stringify({ id, driver }))
|
|
102
|
+
} catch {
|
|
103
|
+
// Not remembered.
|
|
104
|
+
}
|
|
105
|
+
return true
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Reads the output until the session ends; a dropped stream is opened again from the last id. */
|
|
109
|
+
const attach = async (): Promise<void> => {
|
|
110
|
+
let failures = 0
|
|
111
|
+
while (!ended && !abort.signal.aborted && id) {
|
|
112
|
+
try {
|
|
113
|
+
const response = await fetch(`${PREFIX}/${id}/output`, {
|
|
114
|
+
headers: { ...headers, ...(lastId > 0 ? { 'last-event-id': String(lastId) } : {}) },
|
|
115
|
+
signal: abort.signal,
|
|
116
|
+
})
|
|
117
|
+
if (response.status === 404 && lastId === 0) {
|
|
118
|
+
// The remembered terminal is gone: start a new one.
|
|
119
|
+
sessionStorage.removeItem(REMEMBERED)
|
|
120
|
+
if (!(await start())) return
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
if (!response.ok) throw new Error(String(response.status))
|
|
124
|
+
failures = 0
|
|
125
|
+
for await (const frame of frames(response)) {
|
|
126
|
+
if (frame.event === 'reset') term.reset()
|
|
127
|
+
else if (frame.event === 'change')
|
|
128
|
+
onChange(JSON.parse(frame.data) as { extension: string; action: string })
|
|
129
|
+
else if (frame.event === 'data') {
|
|
130
|
+
if (frame.id) lastId = Number(frame.id)
|
|
131
|
+
term.write(JSON.parse(frame.data) as string)
|
|
132
|
+
} else if (frame.event === 'exit') {
|
|
133
|
+
ended = true
|
|
134
|
+
const code = (JSON.parse(frame.data) as { code: number | null }).code
|
|
135
|
+
status(
|
|
136
|
+
code === null ? 'The terminal was closed.' : `The terminal ended (exit ${code}).`,
|
|
137
|
+
)
|
|
138
|
+
sessionStorage.removeItem(REMEMBERED)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} catch {
|
|
142
|
+
if (abort.signal.aborted) return
|
|
143
|
+
if (++failures > 5) {
|
|
144
|
+
status('The connection to the terminal was lost.')
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, 500 * failures))
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Keystrokes: one request per animation frame, in order.
|
|
153
|
+
let pending = ''
|
|
154
|
+
let scheduled = false
|
|
155
|
+
let sending: Promise<unknown> = Promise.resolve()
|
|
156
|
+
term.onData((data) => {
|
|
157
|
+
pending += data
|
|
158
|
+
if (scheduled) return
|
|
159
|
+
scheduled = true
|
|
160
|
+
requestAnimationFrame(() => {
|
|
161
|
+
scheduled = false
|
|
162
|
+
const batch = pending
|
|
163
|
+
pending = ''
|
|
164
|
+
if (id && !ended && batch !== '')
|
|
165
|
+
sending = sending.then(() => call(`/${id}/input`, { data: batch }))
|
|
166
|
+
})
|
|
167
|
+
})
|
|
168
|
+
const resize = new ResizeObserver(() => {
|
|
169
|
+
fit.fit()
|
|
170
|
+
if (id && !ended) void call(`/${id}/resize`, { cols: term.cols, rows: term.rows })
|
|
171
|
+
})
|
|
172
|
+
resize.observe(container)
|
|
173
|
+
|
|
174
|
+
if (!id && !(await start())) return { detach() {}, stop: async () => {} }
|
|
175
|
+
void attach()
|
|
176
|
+
term.focus()
|
|
177
|
+
return {
|
|
178
|
+
detach() {
|
|
179
|
+
abort.abort()
|
|
180
|
+
resize.disconnect()
|
|
181
|
+
term.dispose()
|
|
182
|
+
container.replaceChildren()
|
|
183
|
+
},
|
|
184
|
+
async stop() {
|
|
185
|
+
if (id) await call(`/${id}/stop`)
|
|
186
|
+
},
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
|
|
2
|
+
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
|
|
3
|
+
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
19
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
@xterm/xterm 6.0.0 (xterm.mjs, xterm-css.mjs = css/xterm.css as a string)
|
|
2
|
+
@xterm/addon-fit 0.11.0 (addon-fit.mjs)
|
|
3
|
+
Both MIT: LICENSE (xterm) and LICENSE-addon-fit. Vendored unmodified from the npm tarballs (npm pack @xterm/xterm@6.0.0 @xterm/addon-fit@0.11.0): lib/xterm.mjs, lib/addon-fit.mjs, css/xterm.css, LICENSE.
|
|
4
|
+
To update: pin a new exact version here, replace the files from the tarballs, update THIRD_PARTY_NOTICES.md.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
|
|
3
|
+
* @license MIT
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
|
6
|
+
* @license MIT
|
|
7
|
+
*
|
|
8
|
+
* Originally forked from (with the author's permission):
|
|
9
|
+
* Fabrice Bellard's javascript vt100 for jslinux:
|
|
10
|
+
* http://bellard.org/jslinux/
|
|
11
|
+
* Copyright (c) 2011 Fabrice Bellard
|
|
12
|
+
*/
|
|
13
|
+
/*---------------------------------------------------------------------------------------------
|
|
14
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
15
|
+
* Licensed under the MIT License. See License.txt in the project root for license information.
|
|
16
|
+
*--------------------------------------------------------------------------------------------*/
|
|
17
|
+
var h=2,_=1,o=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let t=this._terminal._core._renderService.dimensions;if(t.css.cell.width===0||t.css.cell.height===0)return;let s=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,r=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(r.getPropertyValue("height")),a=Math.max(0,parseInt(r.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),n={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},m=n.top+n.bottom,d=n.right+n.left,c=l-m,p=a-d-s;return{cols:Math.max(h,Math.floor(p/t.css.cell.width)),rows:Math.max(_,Math.floor(c/t.css.cell.height))}}};export{o as FitAddon};
|
|
18
|
+
//# sourceMappingURL=addon-fit.mjs.map
|