vanclaw-device 0.0.0-stage → 0.2.2-rc.5-13

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 (3) hide show
  1. package/README.md +13 -2
  2. package/device-cli.mjs +384 -0
  3. package/package.json +17 -4
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # VanClaw Device
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在要连接的电脑上安装 Node.js 20.11 或更新版本。
4
+
5
+ ```sh
6
+ npm install -g vanclaw-device
7
+ vanclaw-device connect --server https://vch.black.ac.cn --workspace .
8
+ ```
9
+
10
+ 将地址改成你的 VanClaw Harness 实例,并在允许执行任务的工作目录中运行命令。CLI 会显示授权链接和确认代码。用浏览器打开链接,通过凡智云统一认证登录后核对代码并授权。远程终端可以使用 `--no-browser`。
11
+
12
+ 需要在这台设备执行任务时,请启动本机 Docker,拉取当前发布对应的 VanClaw Harness 镜像,并在启动 CLI 的环境中设置 `VANCLAW_API_KEY`。连接后可在 Harness 输入框中的「执行网关」选择这台设备。
13
+
14
+ 用 `vanclaw-device run` 重新连接。用 `vanclaw-device logout` 撤销当前设备授权。
package/device-cli.mjs ADDED
@@ -0,0 +1,384 @@
1
+ #!/usr/bin/env node
2
+ import { execFile, spawn } from 'node:child_process'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { mkdir, open, readFile, realpath, rename, rm, stat, statfs } from 'node:fs/promises'
5
+ import { arch, cpus, freemem, homedir, hostname, platform, totalmem } from 'node:os'
6
+ import { dirname, isAbsolute, join, parse, relative } from 'node:path'
7
+ import { createInterface } from 'node:readline/promises'
8
+ import { setTimeout as delay } from 'node:timers/promises'
9
+ import { parseArgs, promisify } from 'node:util'
10
+
11
+ const exec = promisify(execFile)
12
+ const settings = process.env.VCH_DEVICE_CONFIG || join(homedir(), '.vch', 'device.json')
13
+ const bundledImage = 'mirror.lglws.cn/library/vch:0.2.2-rc.5-13'
14
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/u
15
+ const operationId = /^vch-exec:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/u
16
+ const instance = randomUUID()
17
+ const heartbeatEvery = 4500
18
+ const heartbeatDeadline = 22_000
19
+ const deviceGrantType = 'urn:ietf:params:oauth:grant-type:device_code'
20
+ export const cliClient = 'vanclaw-device-cli'
21
+ export const desktopClient = 'vanclaw-desktop'
22
+
23
+ class GatewayError extends Error {
24
+ constructor(status, message) {
25
+ super(message)
26
+ this.status = status
27
+ }
28
+ }
29
+
30
+ export function serverOrigin(value) {
31
+ const url = new URL(value)
32
+ const local = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
33
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/'
34
+ || (url.protocol !== 'https:' && !(local && url.protocol === 'http:'))) {
35
+ throw new Error('请输入 HTTPS 的 Harness 原点地址。')
36
+ }
37
+ return url.origin
38
+ }
39
+
40
+ async function oauthPost(server, path, payload, signal) {
41
+ const timeout = AbortSignal.timeout(6500)
42
+ const res = await fetch(new URL(path, server), {
43
+ method: 'POST', redirect: 'error', signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
44
+ body: new URLSearchParams(payload),
45
+ })
46
+ const body = await res.json().catch(() => ({}))
47
+ return { status: res.status, body }
48
+ }
49
+
50
+ export async function requestDeviceAuthorization({ server, workspace, name, client = cliClient, signal }) {
51
+ server = serverOrigin(server)
52
+ workspace = await workspaceDirectory(workspace)
53
+ const { status, body } = await oauthPost(server, '/oauth/device_authorization', {
54
+ client_id: client,
55
+ device_info: JSON.stringify({
56
+ name: name || hostname().slice(0, 80), hostname: hostname(), platform: platform(), arch: arch(), workspace,
57
+ runtime: client === desktopClient ? 'VanClaw Harness Desktop · Docker' : 'VanClaw Harness · Docker',
58
+ }),
59
+ }, signal)
60
+ if (status !== 200) throw new Error(body.error_description ?? `设备授权暂不可用(HTTP ${status})。`)
61
+ const link = new URL(body.verification_uri_complete)
62
+ const code = /^[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}$/u
63
+ if (!tokenPattern.test(body.device_code ?? '') || !code.test(body.user_code ?? '') || link.origin !== server
64
+ || link.username || link.password || link.hash || link.pathname !== '/oauth/device' || link.searchParams.get('user_code') !== body.user_code
65
+ || !Number.isSafeInteger(body.expires_in) || body.expires_in < 1 || body.expires_in > 900
66
+ || !Number.isSafeInteger(body.interval) || body.interval < 5 || body.interval > 60) {
67
+ throw new Error('服务器返回的设备授权请求无效。')
68
+ }
69
+ return { server, workspace, client, code: body.device_code, userCode: body.user_code, url: link.href,
70
+ interval: body.interval, expiresAt: Date.now() + body.expires_in * 1000 }
71
+ }
72
+
73
+ export async function waitForDeviceAuthorization(grant, signal) {
74
+ let interval = grant.interval
75
+ while (grant.expiresAt - Date.now() > interval * 1000) {
76
+ await delay(interval * 1000, undefined, { signal })
77
+ let response
78
+ try {
79
+ response = await oauthPost(grant.server, '/oauth/token', {
80
+ client_id: grant.client, device_code: grant.code, grant_type: deviceGrantType,
81
+ }, signal)
82
+ } catch (error) {
83
+ signal?.throwIfAborted()
84
+ if (!(error instanceof TypeError) && error.name !== 'TimeoutError') throw error
85
+ interval *= 2
86
+ continue
87
+ }
88
+ const { status, body } = response
89
+ if (status === 200) {
90
+ const scope = grant.client === desktopClient ? 'device:connect desktop:workbench' : 'device:connect'
91
+ if (!tokenPattern.test(body.access_token ?? '') || body.token_type?.toLowerCase() !== 'bearer' || body.scope !== scope
92
+ || !Number.isSafeInteger(body.expires_in) || body.expires_in < 1) throw new Error('服务器返回的设备凭据无效。')
93
+ return { server: grant.server, workspace: grant.workspace, client: grant.client, credential: body.access_token,
94
+ id: body.device_id, expiresAt: Date.now() + body.expires_in * 1000 }
95
+ }
96
+ if (body.error === 'authorization_pending') continue
97
+ if (body.error === 'slow_down') { interval += 5; continue }
98
+ if (status >= 500) { interval *= 2; continue }
99
+ throw new Error({ access_denied: '已取消设备授权。', expired_token: '授权链接已过期,请重新发起连接。' }[body.error]
100
+ ?? body.error_description ?? '无法兑换设备授权,请重新连接。')
101
+ }
102
+ throw new Error('授权链接已过期,请重新发起连接。')
103
+ }
104
+
105
+ export async function revokeDeviceAuthorization(config) {
106
+ const { status } = await oauthPost(config.server, '/oauth/revoke', {
107
+ client_id: config.client ?? cliClient, token: config.credential,
108
+ })
109
+ if (status !== 200) throw new Error(`撤销设备授权失败(HTTP ${status})。`)
110
+ }
111
+
112
+ function openBrowser(link) {
113
+ const system = platform()
114
+ const command = system === 'darwin' ? ['open', link] : system === 'win32'
115
+ ? ['rundll32.exe', 'url.dll,FileProtocolHandler', link] : ['xdg-open', link]
116
+ const child = spawn(command[0], command.slice(1), { detached: true, stdio: 'ignore' })
117
+ child.once('error', error => { if (error.code !== 'ENOENT') console.error('打开浏览器失败,请复制授权链接。') })
118
+ child.unref()
119
+ }
120
+
121
+ async function post(server, action, body, credential) {
122
+ const res = await fetch(new URL(`/vch/device/${action}`, server), {
123
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6500),
124
+ headers: { 'content-type': 'application/json', ...credential && { authorization: `Bearer ${credential}` } },
125
+ body: JSON.stringify(body),
126
+ })
127
+ const value = await res.json().catch(() => ({}))
128
+ if (!res.ok) throw new GatewayError(res.status, value.message ?? `设备网关返回 HTTP ${res.status}。`)
129
+ return value
130
+ }
131
+
132
+ async function workspaceDirectory(value) {
133
+ if (!value) throw new Error('请通过 --workspace 指定允许 Harness 使用的目录。')
134
+ const path = await realpath(value)
135
+ const home = await realpath(homedir())
136
+ const relation = relative(path, home)
137
+ if (!(await stat(path)).isDirectory() || path === parse(path).root || (!isAbsolute(relation) && !relation.startsWith('..'))) {
138
+ throw new Error('请选择一个具体的工作区目录。')
139
+ }
140
+ return path
141
+ }
142
+
143
+ async function save(config) {
144
+ const directory = dirname(settings)
145
+ await mkdir(directory, { recursive: true, mode: 0o700 })
146
+ const staging = join(directory, `.device-${randomUUID()}.json`)
147
+ const file = await open(staging, 'wx', 0o600)
148
+ try {
149
+ await file.writeFile(JSON.stringify(config) + '\n')
150
+ await file.sync()
151
+ await file.close()
152
+ await rename(staging, settings)
153
+ } finally {
154
+ await file.close()
155
+ await rm(staging, { force: true })
156
+ }
157
+ }
158
+
159
+ function dockerArgs(workspace, readOnly) {
160
+ const uid = process.getuid?.() || 1000
161
+ const gid = process.getgid?.() || 1000
162
+ const source = `"source=${workspace.replaceAll('"', '""')}"`
163
+ return [
164
+ '--init', '--rm', '--pull', 'never', '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true',
165
+ '--user', `${uid}:${gid}`, '--memory', '4g', '--cpus', '2', '--pids-limit', '256',
166
+ '--tmpfs', `/home/node:rw,nosuid,nodev,mode=700,uid=${uid},gid=${gid},size=256m`,
167
+ '--tmpfs', '/tmp:rw,nosuid,nodev,exec,mode=1777,size=256m',
168
+ '--mount', `type=bind,${source},target=/workspace,bind-recursive=disabled${readOnly ? ',readonly' : ''}`,
169
+ ]
170
+ }
171
+
172
+ async function checkRuntime(image, workspace) {
173
+ if (!process.env.VANCLAW_API_KEY?.trim()) throw new Error('请在这台设备上设置 VANCLAW_API_KEY。')
174
+ if (!image || !/^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,240}$/u.test(image)) throw new Error('请通过 --image 指定 VanClaw Harness 镜像。')
175
+ const context = await exec('docker', ['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'], { timeout: 5000 })
176
+ const endpoint = process.env.DOCKER_HOST || context.stdout.trim()
177
+ if (!endpoint.startsWith('unix://') && !endpoint.startsWith('npipe://')) throw new Error('请选择这台设备上的 Docker 引擎。')
178
+ let inspected
179
+ try {
180
+ inspected = await exec('docker', ['image', 'inspect', '--format', '{{.Id}} {{.Architecture}}', image], { timeout: 5000 })
181
+ } catch (error) {
182
+ if (error.code === 'ENOENT') throw new Error('此设备需要 Docker。')
183
+ throw new Error(`本地缺少 ${image},请先运行 docker pull ${image}。`)
184
+ }
185
+ const [id, architecture] = inspected.stdout.trim().split(' ')
186
+ if (architecture !== (arch() === 'x64' ? 'amd64' : arch())) throw new Error('请选择与这台设备处理器架构一致的镜像。')
187
+ try {
188
+ await exec('docker', ['run', ...dockerArgs(workspace, false), '--network', 'none', id, 'device-sandbox-check'], { timeout: 20_000 })
189
+ } catch (error) {
190
+ const detail = String(error.stderr ?? '').trim().split('\n').at(-1)
191
+ throw new Error(`设备沙箱检查未通过${detail ? `(${detail.slice(0, 180)})` : '。'}`)
192
+ }
193
+ return id
194
+ }
195
+
196
+ let cpuReading
197
+
198
+ async function metrics(workspace) {
199
+ const cpuList = cpus()
200
+ const current = cpuList.reduce((sum, { times }) => ({
201
+ idle: sum.idle + times.idle,
202
+ total: sum.total + Object.values(times).reduce((total, value) => total + value, 0),
203
+ }), { idle: 0, total: 0 })
204
+ const elapsed = current.total - (cpuReading?.total ?? 0)
205
+ const idle = current.idle - (cpuReading?.idle ?? 0)
206
+ const cpu = elapsed > 0 ? Math.max(0, Math.min(100, Math.round(100 * (1 - idle / elapsed)))) : null
207
+ cpuReading = current
208
+ const disk = await statfs(workspace).catch(() => null)
209
+ return {
210
+ cpu, cores: cpuList.length || null,
211
+ memory: Math.round(100 * (1 - freemem() / totalmem())), memoryBytes: totalmem(),
212
+ disk: disk?.blocks ? Math.round(100 * (1 - disk.bfree / disk.blocks)) : null,
213
+ diskBytes: disk?.blocks && disk.bsize ? disk.blocks * disk.bsize : null,
214
+ }
215
+ }
216
+
217
+ function startTask(config, imageId, job) {
218
+ if (!operationId.test(job.id ?? '') || !['read-only', 'workspace-write'].includes(job.permission)
219
+ || !/^[\w./:-]{1,160}$/u.test(job.model ?? '') || typeof job.task !== 'string' || job.task.length > 48_000) {
220
+ throw new Error('执行任务格式无效。')
221
+ }
222
+ const name = `vch-device-${randomUUID()}`
223
+ const child = spawn('docker', [
224
+ 'run', '-i', '--name', name, ...dockerArgs(config.workspace, job.permission === 'read-only'),
225
+ '-e', 'VANCLAW_API_KEY', '-e', `VCH_DEVICE_MODEL=${job.model}`, '-e', 'VCH_DEVICE_MODEL_BASE_URL',
226
+ imageId, 'device-task', job.permission,
227
+ ], { stdio: ['pipe', 'pipe', 'inherit'] })
228
+ const task = { id: job.id, exited: false, lost: false, seq: 0 }
229
+ const exited = new Promise(resolve => {
230
+ child.once('error', () => resolve(1))
231
+ child.once('close', resolve)
232
+ })
233
+ child.stdin.on('error', () => child.stdin.destroy())
234
+ child.stdin.end(job.task)
235
+
236
+ task.stop = async () => {
237
+ if (task.lost) return
238
+ task.lost = true
239
+ if (task.exited) return
240
+ child.kill('SIGTERM')
241
+ await exited
242
+ // The Docker client can exit while the container is still shutting down.
243
+ await exec('docker', ['rm', '-f', name], { timeout: 5000 }).catch(() => undefined)
244
+ }
245
+
246
+ async function emit(event) {
247
+ if (task.lost) return
248
+ const payload = { ...event, id: task.id, instance, seq: ++task.seq }
249
+ while (!task.lost) {
250
+ try {
251
+ const result = await post(config.server, 'event', payload, config.credential)
252
+ if (result.stop && !task.exited) await task.stop()
253
+ return
254
+ } catch (error) {
255
+ if (error instanceof GatewayError && error.status < 500) {
256
+ await task.stop()
257
+ return
258
+ }
259
+ await delay(800)
260
+ }
261
+ }
262
+ }
263
+
264
+ task.done = (async () => {
265
+ let final
266
+ let reports = 0
267
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity })
268
+ for await (const line of lines) {
269
+ let event
270
+ try { event = JSON.parse(line) } catch (error) {
271
+ if (error instanceof SyntaxError) continue
272
+ throw error
273
+ }
274
+ if (event.type === 'final') final = event
275
+ if (event.type === 'tool_call' && reports < 60 && /^[A-Za-z0-9_.:-]{1,80}$/u.test(event.tool ?? '')) {
276
+ reports++
277
+ await emit({ type: 'tool', label: event.tool })
278
+ }
279
+ }
280
+ const code = await exited
281
+ task.exited = true
282
+ const completed = code === 0 && final?.reason?.kind === 'completed' && typeof final.text === 'string'
283
+ await emit(completed ? { type: 'completed', text: final.text.slice(0, 96_000) }
284
+ : { type: 'failed', reason: code === 124 ? 'timeout' : 'runtime' })
285
+ console.log(completed && !task.lost ? '设备任务完成。' : '设备任务已结束。')
286
+ })()
287
+ return task
288
+ }
289
+
290
+ export async function connectDevice(config, { signal, onStatus = () => {} } = {}) {
291
+ config = { ...config, server: serverOrigin(config.server) }
292
+ if (!tokenPattern.test(config.credential ?? '') || await workspaceDirectory(config.workspace) !== config.workspace
293
+ || (config.expiresAt && config.expiresAt <= Date.now())) throw new Error('设备授权或工作区路径已失效,请重新连接。')
294
+ signal?.throwIfAborted()
295
+ let imageId
296
+ let reason
297
+ try { imageId = await checkRuntime(config.image, config.workspace) }
298
+ catch (error) { reason = error.message }
299
+ let active
300
+ let stopping = signal?.aborted ?? false
301
+ let connected = false
302
+ let lastContact = Date.now()
303
+ const stop = () => { stopping = true }
304
+ process.once('SIGINT', stop)
305
+ process.once('SIGTERM', stop)
306
+ signal?.addEventListener('abort', stop, { once: true })
307
+ onStatus({ connected: false, ready: Boolean(imageId), reason })
308
+ try {
309
+ while (!stopping) {
310
+ try {
311
+ const result = await post(config.server, 'heartbeat', {
312
+ instance, ready: Boolean(imageId), metrics: await metrics(config.workspace), running: active?.id,
313
+ }, config.credential)
314
+ lastContact = Date.now()
315
+ if (!connected) { connected = true; onStatus({ connected, ready: Boolean(imageId), reason }) }
316
+ if (result.stop && !active?.exited) await active?.stop()
317
+ if (result.job && imageId && !active && !stopping) {
318
+ const task = startTask(config, imageId, result.job)
319
+ active = task
320
+ void task.done.catch(error => {
321
+ console.error('设备任务:', error.message)
322
+ return task.stop()
323
+ }).finally(() => { if (active === task) active = undefined })
324
+ }
325
+ } catch (error) {
326
+ if (error instanceof GatewayError && error.status < 500) throw error
327
+ if (Date.now() - lastContact > heartbeatDeadline) {
328
+ await active?.stop()
329
+ if (connected) { connected = false; onStatus({ connected, ready: Boolean(imageId), reason: '设备网关连接中断,正在重连。' }) }
330
+ }
331
+ }
332
+ if (!stopping) await delay(heartbeatEvery)
333
+ }
334
+ } finally {
335
+ process.removeListener('SIGINT', stop)
336
+ process.removeListener('SIGTERM', stop)
337
+ signal?.removeEventListener('abort', stop)
338
+ await active?.stop()
339
+ await post(config.server, 'disconnect', { instance }, config.credential).catch(() => undefined)
340
+ }
341
+ }
342
+
343
+ async function main() {
344
+ const { positionals, values } = parseArgs({ allowPositionals: true, options: {
345
+ server: { type: 'string' }, workspace: { type: 'string' }, name: { type: 'string' },
346
+ image: { type: 'string' }, 'no-browser': { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
347
+ } })
348
+ const [command] = positionals
349
+ if (values.help || !command) {
350
+ console.log('vanclaw-device connect --server <url> --workspace <directory> [--image <image>] [--name <name>] [--no-browser]\nvanclaw-device run [--image <image>]\nvanclaw-device logout')
351
+ return
352
+ }
353
+ if (positionals.length !== 1 || !['connect', 'run', 'logout'].includes(command)) throw new Error('请使用 connect、run 或 logout。')
354
+ const image = values.image ?? (bundledImage.startsWith('__') ? undefined : bundledImage)
355
+ const report = ({ connected, ready, reason }) => {
356
+ if (connected) console.log(ready ? '设备已连接,可以执行任务。按 Ctrl+C 断开。' : '设备已连接。')
357
+ if (reason) console.log(reason)
358
+ }
359
+ if (command !== 'connect') {
360
+ const config = JSON.parse(await readFile(settings, 'utf8'))
361
+ config.server = serverOrigin(config.server)
362
+ if (command === 'logout') {
363
+ await revokeDeviceAuthorization(config)
364
+ await rm(settings, { force: true })
365
+ console.log('已退出设备授权。')
366
+ return
367
+ }
368
+ return connectDevice({ ...config, image: values.image ?? config.image ?? image }, { onStatus: report })
369
+ }
370
+
371
+ const grant = await requestDeviceAuthorization({ server: values.server, workspace: values.workspace, name: values.name })
372
+ console.log(`在浏览器中打开授权链接 ${grant.url}\n确认代码 ${grant.userCode}`)
373
+ if (!values['no-browser'] && process.stdout.isTTY) openBrowser(grant.url)
374
+ const config = { ...await waitForDeviceAuthorization(grant), image }
375
+ await save(config)
376
+ await connectDevice(config, { onStatus: report })
377
+ }
378
+
379
+ if (process.argv[1] && await realpath(process.argv[1]).catch(() => undefined) === import.meta.filename) {
380
+ main().catch(error => {
381
+ console.error(error.message)
382
+ process.exitCode = 1
383
+ })
384
+ }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "vanclaw-device",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2-rc.5-13",
4
+ "description": "Connect a device to VanClaw Harness through browser authorization",
5
+ "type": "module",
6
+ "bin": {
7
+ "vanclaw-device": "device-cli.mjs"
8
+ },
9
+ "files": [
10
+ "device-cli.mjs",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20.11.0"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ }
19
+ }