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

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/README.md CHANGED
@@ -1,3 +1,18 @@
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
+ CLI 使用 Node.js 24.9 或更新版本。npm 会一并安装原生任务运行时。
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
+ 在 Harness 的「设置 → 模型」保存账号模型和密钥,然后在输入框的「执行网关」选择设备和目录。模型请求通过账号授权转发。本机执行使用操作系统原生沙箱。Linux 需要系统支持 Landlock,或者已具备可用的 bubblewrap 沙箱。
13
+
14
+ 升级已配对的 OAuth CLI 后,运行 `vanclaw-device run` 即可用现有授权重新连接。
15
+
16
+ 使用 `vanclaw-device status` 查看状态和日志位置,使用 `vanclaw-device stop` 停止守护进程,使用 `vanclaw-device logout` 撤销配对。
17
+
18
+ 在设备上运行 `vanclaw-device workspace add /path/to/project` 可以新增授权目录。后台运行时会自动同步,可在「设备管理 → 文件目录」设为默认目录。
package/device-cli.mjs ADDED
@@ -0,0 +1,310 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { realpath, stat, statfs } from 'node:fs/promises'
3
+ import { arch, cpus, freemem, homedir, hostname, platform, totalmem } from 'node:os'
4
+ import { isAbsolute, parse, relative } from 'node:path'
5
+ import { createInterface } from 'node:readline/promises'
6
+ import { setTimeout as delay } from 'node:timers/promises'
7
+
8
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/u
9
+ const operationId = /^vch-exec:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/u
10
+ const instance = randomUUID()
11
+ const heartbeatEvery = 4500
12
+ const heartbeatDeadline = 22_000
13
+ const retryRuntimeEvery = 20_000
14
+ const deviceGrantType = 'urn:ietf:params:oauth:grant-type:device_code'
15
+ export const cliClient = 'vanclaw-device-cli'
16
+ export const desktopClient = 'vanclaw-desktop'
17
+ export const directoryLimit = 64
18
+
19
+ class GatewayError extends Error {
20
+ constructor(status, message) {
21
+ super(message)
22
+ this.status = status
23
+ }
24
+ }
25
+
26
+ export function serverOrigin(value) {
27
+ const url = new URL(value)
28
+ const local = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
29
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/'
30
+ || (url.protocol !== 'https:' && !(local && url.protocol === 'http:'))) {
31
+ throw new Error('请输入 HTTPS 的 Harness 原点地址。')
32
+ }
33
+ return url.origin
34
+ }
35
+
36
+ async function oauthPost(server, path, payload, signal) {
37
+ const timeout = AbortSignal.timeout(6500)
38
+ const res = await fetch(new URL(path, server), {
39
+ method: 'POST', redirect: 'error', signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
40
+ body: new URLSearchParams(payload),
41
+ })
42
+ const body = await res.json().catch(() => ({}))
43
+ return { status: res.status, body }
44
+ }
45
+
46
+ export async function requestDeviceAuthorization({ server, workspace, name, client = cliClient, signal }) {
47
+ server = serverOrigin(server)
48
+ workspace = await workspaceDirectory(workspace)
49
+ const { status, body } = await oauthPost(server, '/oauth/device_authorization', {
50
+ client_id: client,
51
+ device_info: JSON.stringify({
52
+ name: name || hostname().slice(0, 80), hostname: hostname(), platform: platform(), arch: arch(), workspace,
53
+ runtime: client === desktopClient ? 'VanClaw Harness Desktop · Native' : 'VanClaw Device CLI · Native',
54
+ }),
55
+ }, signal)
56
+ if (status !== 200) throw new Error(body.error_description ?? `设备授权暂不可用(HTTP ${status})。`)
57
+ const link = new URL(body.verification_uri_complete)
58
+ const code = /^[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}$/u
59
+ if (!tokenPattern.test(body.device_code ?? '') || !code.test(body.user_code ?? '') || link.origin !== server
60
+ || link.username || link.password || link.hash || link.pathname !== '/oauth/device' || link.searchParams.get('user_code') !== body.user_code
61
+ || !Number.isSafeInteger(body.expires_in) || body.expires_in < 1 || body.expires_in > 900
62
+ || !Number.isSafeInteger(body.interval) || body.interval < 5 || body.interval > 60) {
63
+ throw new Error('服务器返回的设备授权请求无效。')
64
+ }
65
+ return { server, workspace, client, code: body.device_code, userCode: body.user_code, url: link.href,
66
+ interval: body.interval, expiresAt: Date.now() + body.expires_in * 1000 }
67
+ }
68
+
69
+ export async function waitForDeviceAuthorization(grant, signal) {
70
+ let interval = grant.interval
71
+ while (grant.expiresAt - Date.now() > interval * 1000) {
72
+ await delay(interval * 1000, undefined, { signal })
73
+ let response
74
+ try {
75
+ response = await oauthPost(grant.server, '/oauth/token', {
76
+ client_id: grant.client, device_code: grant.code, grant_type: deviceGrantType,
77
+ }, signal)
78
+ } catch (error) {
79
+ signal?.throwIfAborted()
80
+ if (!(error instanceof TypeError) && error.name !== 'TimeoutError') throw error
81
+ interval *= 2
82
+ continue
83
+ }
84
+ const { status, body } = response
85
+ if (status === 200) {
86
+ const scope = grant.client === desktopClient ? 'device:connect desktop:workbench' : 'device:connect'
87
+ if (!tokenPattern.test(body.access_token ?? '') || body.token_type?.toLowerCase() !== 'bearer' || body.scope !== scope
88
+ || !Number.isSafeInteger(body.expires_in) || body.expires_in < 1) throw new Error('服务器返回的设备凭据无效。')
89
+ return { server: grant.server, workspace: grant.workspace, client: grant.client, credential: body.access_token,
90
+ id: body.device_id, expiresAt: Date.now() + body.expires_in * 1000 }
91
+ }
92
+ if (body.error === 'authorization_pending') continue
93
+ if (body.error === 'slow_down') { interval += 5; continue }
94
+ if (status >= 500) { interval *= 2; continue }
95
+ throw new Error({ access_denied: '已取消设备授权。', expired_token: '授权链接已过期,请重新发起连接。' }[body.error]
96
+ ?? body.error_description ?? '无法兑换设备授权,请重新连接。')
97
+ }
98
+ throw new Error('授权链接已过期,请重新发起连接。')
99
+ }
100
+
101
+ export async function revokeDeviceAuthorization(config) {
102
+ const { status } = await oauthPost(config.server, '/oauth/revoke', {
103
+ client_id: config.client ?? cliClient, token: config.credential,
104
+ })
105
+ if (status !== 200) throw new Error(`撤销设备授权失败(HTTP ${status})。`)
106
+ }
107
+
108
+ async function post(server, action, body, credential) {
109
+ const res = await fetch(new URL(`/vch/device/${action}`, server), {
110
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6500),
111
+ headers: { 'content-type': 'application/json', ...credential && { authorization: `Bearer ${credential}` } },
112
+ body: JSON.stringify(body),
113
+ })
114
+ const value = await res.json().catch(() => ({}))
115
+ if (!res.ok) throw new GatewayError(res.status, value.message ?? `设备网关返回 HTTP ${res.status}。`)
116
+ return value
117
+ }
118
+
119
+ export async function workspaceDirectory(value) {
120
+ if (!value) throw new Error('请通过 --workspace 指定允许 Harness 使用的目录。')
121
+ const path = await realpath(value)
122
+ const home = await realpath(homedir())
123
+ const relation = relative(path, home)
124
+ if (path.length > 1024 || /\p{Cc}/u.test(path) || !(await stat(path)).isDirectory()
125
+ || path === parse(path).root || (!isAbsolute(relation) && !relation.startsWith('..'))) {
126
+ throw new Error('请选择一个具体的工作区目录。')
127
+ }
128
+ return path
129
+ }
130
+
131
+ let cpuReading
132
+
133
+ async function metrics(workspace) {
134
+ const cpuList = cpus()
135
+ const current = cpuList.reduce((sum, { times }) => ({
136
+ idle: sum.idle + times.idle,
137
+ total: sum.total + Object.values(times).reduce((total, value) => total + value, 0),
138
+ }), { idle: 0, total: 0 })
139
+ const elapsed = current.total - (cpuReading?.total ?? 0)
140
+ const idle = current.idle - (cpuReading?.idle ?? 0)
141
+ const cpu = elapsed > 0 ? Math.max(0, Math.min(100, Math.round(100 * (1 - idle / elapsed)))) : null
142
+ cpuReading = current
143
+ const disk = await statfs(workspace).catch(() => null)
144
+ return {
145
+ cpu, cores: cpuList.length || null,
146
+ memory: Math.round(100 * (1 - freemem() / totalmem())), memoryBytes: totalmem(),
147
+ disk: disk?.blocks ? Math.round(100 * (1 - disk.bfree / disk.blocks)) : null,
148
+ diskBytes: disk?.blocks && disk.bsize ? disk.blocks * disk.bsize : null,
149
+ }
150
+ }
151
+
152
+ async function startTask(config, runtime, job) {
153
+ if (!operationId.test(job.id ?? '') || !['read-only', 'workspace-write'].includes(job.permission)
154
+ || !/^[\w./:-]{1,160}$/u.test(job.model ?? '') || typeof job.task !== 'string' || job.task.length > 48_000
155
+ || !/^[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}$/u.test(job.modelToken ?? '')) {
156
+ throw new Error('执行任务格式无效。')
157
+ }
158
+ const { child, done: exited, stop } = await runtime.start(config.server, job)
159
+ const task = { id: job.id, exited: false, lost: false, seq: 0 }
160
+ child.stdin.on('error', () => child.stdin.destroy())
161
+ child.stdin.end(job.task)
162
+
163
+ task.stop = async () => {
164
+ if (task.lost) return
165
+ task.lost = true
166
+ if (!task.exited) await stop()
167
+ }
168
+
169
+ async function emit(event) {
170
+ if (task.lost) return
171
+ const payload = { ...event, id: task.id, instance, seq: ++task.seq }
172
+ while (!task.lost) {
173
+ try {
174
+ const result = await post(config.server, 'event', payload, config.credential)
175
+ if (result.stop && !task.exited) await task.stop()
176
+ return
177
+ } catch (error) {
178
+ if (error instanceof GatewayError && error.status < 500) {
179
+ await task.stop()
180
+ return
181
+ }
182
+ await delay(800)
183
+ }
184
+ }
185
+ }
186
+
187
+ task.done = (async () => {
188
+ let final
189
+ let reports = 0
190
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity })
191
+ for await (const line of lines) {
192
+ let event
193
+ try { event = JSON.parse(line) } catch (error) {
194
+ if (error instanceof SyntaxError) continue
195
+ throw error
196
+ }
197
+ if (event.type === 'final') final = event
198
+ if (event.type === 'tool_call' && reports < 60 && /^[A-Za-z0-9_.:-]{1,80}$/u.test(event.tool ?? '')) {
199
+ reports++
200
+ await emit({ type: 'tool', label: event.tool })
201
+ }
202
+ }
203
+ const code = await exited
204
+ task.exited = true
205
+ const completed = code === 0 && final?.reason?.kind === 'completed' && typeof final.text === 'string'
206
+ await emit(completed ? { type: 'completed', text: final.text.slice(0, 96_000) }
207
+ : { type: 'failed', reason: code === 124 ? 'timeout' : code === 125 ? 'isolation' : 'runtime' })
208
+ console.log(completed && !task.lost ? '设备任务完成。' : '设备任务已结束。')
209
+ })()
210
+ return task
211
+ }
212
+
213
+ export async function connectDevice(config, { signal, onStatus = () => {}, getDirectories, runtime } = {}) {
214
+ config = { ...config, server: serverOrigin(config.server) }
215
+ if (![cliClient, desktopClient].includes(config.client) || !tokenPattern.test(config.credential ?? '')
216
+ || await workspaceDirectory(config.workspace) !== config.workspace
217
+ || (config.expiresAt && config.expiresAt <= Date.now())) throw new Error('设备授权或工作区路径已失效,请重新连接。')
218
+ signal?.throwIfAborted()
219
+ const runtimeController = new AbortController()
220
+ let preparedWorkspace
221
+ let issue = 'preparing'
222
+ let reason = '正在准备本机运行环境…'
223
+ let modelRelay
224
+ let runtimePromise
225
+ let retryAt = 0
226
+ let active
227
+ let stopping = signal?.aborted ?? false
228
+ let connected = false
229
+ let lastContact = Date.now()
230
+ let reported
231
+ let directories = getDirectories?.() ?? config
232
+ const ready = () => directories.workspace === preparedWorkspace && modelRelay === true
233
+ function report(message = modelRelay === false ? '服务器更新后即可使用账号模型执行本机任务。' : reason) {
234
+ const state = { connected, ready: ready(), reason: message }
235
+ const next = JSON.stringify(state)
236
+ if (reported !== next) { reported = next; onStatus(state) }
237
+ }
238
+ function prepareRuntime() {
239
+ const { workspace } = directories
240
+ issue = 'preparing'
241
+ reason = '正在准备本机运行环境…'
242
+ runtimePromise = runtime.check(workspace, runtimeController.signal)
243
+ .then(() => { preparedWorkspace = workspace; issue = undefined; reason = undefined })
244
+ .catch(error => { issue = error.issue ?? 'runtime'; reason = error.message; retryAt = Date.now() + retryRuntimeEvery })
245
+ .finally(() => { runtimePromise = undefined; if (!stopping) report() })
246
+ }
247
+ const stop = () => { stopping = true; runtimeController.abort() }
248
+ process.once('SIGINT', stop)
249
+ process.once('SIGTERM', stop)
250
+ signal?.addEventListener('abort', stop, { once: true })
251
+ report()
252
+ try {
253
+ while (!stopping) {
254
+ try {
255
+ const desired = getDirectories?.() ?? config
256
+ if (desired.workspace !== directories.workspace) retryAt = 0
257
+ directories = desired
258
+ const workspaces = directories.workspaces ?? [directories.workspace]
259
+ if (preparedWorkspace !== directories.workspace && !active && !runtimePromise && Date.now() >= retryAt) prepareRuntime()
260
+ const result = await post(config.server, 'heartbeat', {
261
+ instance, ready: ready() || Boolean(active), metrics: await metrics(directories.workspace), running: active?.id,
262
+ modelRelay: true, native: true, workspace: directories.workspace, workspaces,
263
+ issue: modelRelay === false ? 'server' : issue,
264
+ }, config.credential)
265
+ modelRelay = result.modelRelay === true
266
+ lastContact = Date.now()
267
+ connected = true
268
+ report()
269
+ if (result.stop && !active?.exited) await active?.stop()
270
+ if (result.job && ready() && !active && !stopping) {
271
+ const fail = reason => post(config.server, 'event', { instance, id: result.job.id, seq: 1, type: 'failed', reason }, config.credential)
272
+ if (!workspaces.includes(result.job.workspace)
273
+ || await workspaceDirectory(result.job.workspace).catch(() => undefined) !== result.job.workspace) {
274
+ await fail('workspace')
275
+ continue
276
+ }
277
+ let task
278
+ try { task = await startTask(config, runtime, result.job) }
279
+ catch (error) {
280
+ console.error('设备任务启动失败:', error.code ?? error.name)
281
+ await fail('runtime')
282
+ continue
283
+ }
284
+ active = task
285
+ void task.done.catch(error => {
286
+ console.error('设备任务:', error.code ?? error.name)
287
+ return task.stop()
288
+ }).finally(() => { if (active === task) active = undefined })
289
+ }
290
+ } catch (error) {
291
+ if (error instanceof GatewayError && error.status < 500 && error.status !== 409) throw error
292
+ if (error instanceof GatewayError && error.status === 409) report(error.message)
293
+ if (Date.now() - lastContact > heartbeatDeadline) {
294
+ await active?.stop()
295
+ if (connected) { connected = false; report('设备网关连接中断,正在重连。') }
296
+ }
297
+ }
298
+ if (!stopping) await delay(heartbeatEvery, undefined, { signal: runtimeController.signal }).catch(error => {
299
+ if (!stopping) throw error
300
+ })
301
+ }
302
+ } finally {
303
+ stop()
304
+ process.removeListener('SIGINT', stop)
305
+ process.removeListener('SIGTERM', stop)
306
+ signal?.removeEventListener('abort', stop)
307
+ await active?.stop()
308
+ await post(config.server, 'disconnect', { instance }, config.credential).catch(() => undefined)
309
+ }
310
+ }
@@ -0,0 +1,228 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
3
+ import { once } from 'node:events'
4
+ import { link, mkdir, open, readFile, rename, rm, writeFile } from 'node:fs/promises'
5
+ import { createConnection, createServer } from 'node:net'
6
+ import { homedir, tmpdir } from 'node:os'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { setTimeout as delay } from 'node:timers/promises'
9
+ import {
10
+ cliClient, connectDevice, directoryLimit, requestDeviceAuthorization, revokeDeviceAuthorization, waitForDeviceAuthorization, workspaceDirectory,
11
+ } from './device-cli.mjs'
12
+ import { createNativeRuntime } from './device-runtime.mjs'
13
+
14
+ const settings = resolve(process.env.VCH_DEVICE_CONFIG || join(homedir(), '.vch', 'device.json'))
15
+ const logPath = settings + '.log'
16
+ const controlKey = settings + '.control'
17
+ const controlId = 'vch-device-' + createHash('sha256').update(settings).digest('hex').slice(0, 22)
18
+ const address = process.platform === 'win32' ? '\\\\.\\pipe\\' + controlId
19
+ : process.platform === 'linux' ? '\0' + controlId : join(tmpdir(), controlId + '.sock')
20
+ const keyFormat = /^[A-Za-z0-9_-]{43}$/u
21
+
22
+ async function readOptional(file) {
23
+ return readFile(file, 'utf8').catch(error => {
24
+ if (error.code !== 'ENOENT') throw error
25
+ })
26
+ }
27
+
28
+ async function storedConnection() {
29
+ const stored = await readOptional(settings)
30
+ if (!stored) return undefined
31
+ const { image: _legacyImage, ...connection } = JSON.parse(stored)
32
+ return { ...connection, workspaces: connection.workspaces ?? [connection.workspace] }
33
+ }
34
+
35
+ async function save(connection) {
36
+ const staging = settings + '-' + randomUUID()
37
+ try {
38
+ await writeFile(staging, JSON.stringify(connection) + '\n', { flag: 'wx', mode: 0o600, flush: true })
39
+ await rename(staging, settings)
40
+ } finally { await rm(staging, { force: true }) }
41
+ }
42
+
43
+ async function ensureControlKey() {
44
+ await mkdir(dirname(settings), { recursive: true, mode: 0o700 })
45
+ if (keyFormat.test((await readOptional(controlKey)) ?? '')) return
46
+ const staging = controlKey + '-' + randomUUID()
47
+ try {
48
+ await writeFile(staging, randomBytes(32).toString('base64url'), { flag: 'wx', mode: 0o600 })
49
+ await link(staging, controlKey).catch(error => { if (error.code !== 'EEXIST') throw error })
50
+ } finally { await rm(staging, { force: true }) }
51
+ if (!keyFormat.test((await readOptional(controlKey)) ?? '')) throw new Error('守护进程控制密钥无效。')
52
+ }
53
+
54
+ async function readMessage(socket) {
55
+ socket.setEncoding('utf8')
56
+ let pending = ''
57
+ for await (const chunk of socket.iterator({ destroyOnReturn: false })) {
58
+ pending += chunk
59
+ if (pending.length > 260_000) throw new Error('守护进程请求过长。')
60
+ const end = pending.indexOf('\n')
61
+ if (end >= 0) return JSON.parse(pending.slice(0, end))
62
+ }
63
+ throw new Error('守护进程已断开。')
64
+ }
65
+
66
+ async function request(action, args) {
67
+ const key = await readOptional(controlKey)
68
+ if (!keyFormat.test(key ?? '')) return undefined
69
+ const socket = createConnection(address)
70
+ socket.setTimeout(28_000, () => socket.destroy(new Error('守护进程响应超时。')))
71
+ try {
72
+ await once(socket, 'connect')
73
+ socket.write(JSON.stringify({ key, action, args }) + '\n')
74
+ const { result, error } = await readMessage(socket)
75
+ if (error) throw new Error(error)
76
+ return result
77
+ } catch (error) {
78
+ if (['ENOENT', 'ECONNREFUSED'].includes(error.code)) return undefined
79
+ throw error
80
+ } finally { socket.destroy() }
81
+ }
82
+
83
+ export async function daemonCommand(entry, action, args, { start = false } = {}) {
84
+ let result = await request(action, args)
85
+ if (result !== undefined || !start) return result
86
+ await ensureControlKey()
87
+ const log = await open(logPath, 'a', 0o600)
88
+ try {
89
+ const child = spawn(process.execPath, [entry, '--daemon'], {
90
+ detached: true, windowsHide: true, stdio: ['ignore', log.fd, log.fd],
91
+ })
92
+ child.on('error', () => {})
93
+ child.unref()
94
+ } finally { await log.close() }
95
+ for (let attempt = 0; attempt < 60; attempt++) {
96
+ result = await request(action, args)
97
+ if (result !== undefined) return result
98
+ await delay(100)
99
+ }
100
+ throw new Error('无法启动守护进程。日志位于 ' + logPath)
101
+ }
102
+
103
+ export async function runDaemon() {
104
+ const key = Buffer.from(await readFile(controlKey, 'utf8'))
105
+ let connection = await storedConnection()
106
+ let runner
107
+ let authorization
108
+ let status = { connected: false, ready: false }
109
+ let stopping = false
110
+ let queue = Promise.resolve()
111
+ const serialize = task => {
112
+ const result = queue.then(task)
113
+ queue = result.catch(() => undefined)
114
+ return result
115
+ }
116
+
117
+ const startRunner = () => {
118
+ if (runner) return
119
+ if (!connection || connection.client !== cliClient) throw new Error('请先使用 connect 完成设备授权。')
120
+ const active = { controller: new AbortController() }
121
+ runner = active
122
+ status = { connected: false, ready: false, reason: '正在连接设备网关…' }
123
+ active.done = connectDevice(connection, {
124
+ runtime: createNativeRuntime(), signal: active.controller.signal, getDirectories: () => connection,
125
+ onStatus(next) { status = next },
126
+ }).catch(error => {
127
+ if (!active.controller.signal.aborted) {
128
+ status = { connected: false, ready: false, reason: error.message }
129
+ console.error(error.message)
130
+ }
131
+ }).finally(() => { if (runner === active) runner = undefined })
132
+ }
133
+ async function stopRunner() {
134
+ if (!runner) return
135
+ const active = runner
136
+ active.controller.abort()
137
+ await active.done
138
+ status = { connected: false, ready: false }
139
+ }
140
+ const view = () => ({ ...status, waiting: Boolean(authorization), running: Boolean(runner),
141
+ workspaces: connection?.workspaces ?? [], logPath })
142
+
143
+ async function manage(action, args) {
144
+ if (action === 'status') return view()
145
+ if (stopping) throw new Error('守护进程正在停止。')
146
+ if (action === 'connect') {
147
+ if (authorization) return { url: authorization.grant.url, code: authorization.grant.userCode }
148
+ const controller = new AbortController()
149
+ const grant = await requestDeviceAuthorization({ ...args, signal: controller.signal })
150
+ const attempt = { grant, controller }
151
+ authorization = attempt
152
+ void waitForDeviceAuthorization(grant, controller.signal).then(next => serialize(async () => {
153
+ if (stopping || authorization !== attempt) return
154
+ next.workspaces = [next.workspace]
155
+ await save(next)
156
+ await stopRunner()
157
+ connection = next
158
+ startRunner()
159
+ })).catch(error => {
160
+ if (!controller.signal.aborted) {
161
+ if (!runner) status.reason = error.message
162
+ console.error(error.message)
163
+ }
164
+ }).finally(() => { if (authorization === attempt) authorization = undefined })
165
+ return { url: grant.url, code: grant.userCode }
166
+ }
167
+ if (action === 'run') {
168
+ startRunner()
169
+ return view()
170
+ }
171
+ if (action === 'add') {
172
+ if (!connection || authorization) throw new Error('请先完成设备授权。')
173
+ const path = await workspaceDirectory(args.path)
174
+ const workspaces = [...new Set([...connection.workspaces, path])]
175
+ if (workspaces.length > directoryLimit) throw new Error('授权目录已达上限。')
176
+ const next = { ...connection, workspaces }
177
+ await save(next)
178
+ connection = next
179
+ startRunner()
180
+ return view()
181
+ }
182
+ if (action === 'stop' || action === 'logout') {
183
+ authorization?.controller.abort()
184
+ await stopRunner()
185
+ if (action === 'logout' && connection) {
186
+ await revokeDeviceAuthorization(connection)
187
+ await rm(settings, { force: true })
188
+ connection = undefined
189
+ }
190
+ stopping = true
191
+ server.close()
192
+ return { stopped: true }
193
+ }
194
+ throw new Error('未知守护进程请求。')
195
+ }
196
+
197
+ const server = createServer(socket => {
198
+ socket.setTimeout(28_000, () => socket.destroy())
199
+ socket.on('error', () => {})
200
+ void (async () => {
201
+ try {
202
+ const request = await readMessage(socket)
203
+ const candidate = Buffer.from(typeof request.key === 'string' ? request.key : '')
204
+ if (candidate.length !== key.length || !timingSafeEqual(candidate, key)) throw new Error('守护进程身份验证失败。')
205
+ const result = await serialize(() => manage(request.action, request.args))
206
+ socket.end(JSON.stringify({ result }) + '\n')
207
+ } catch (error) {
208
+ socket.end(JSON.stringify({ error: error.message }) + '\n')
209
+ }
210
+ })()
211
+ })
212
+ try {
213
+ await new Promise((resolve, reject) => {
214
+ server.once('error', reject)
215
+ server.listen(address, resolve)
216
+ })
217
+ } catch (error) {
218
+ if (error.code !== 'EADDRINUSE') throw error
219
+ if (process.platform === 'linux' || process.platform === 'win32' || await request('status')) return
220
+ // Only remove a filesystem socket after the prior listener has stopped.
221
+ await rm(address, { force: true })
222
+ server.listen(address)
223
+ await once(server, 'listening')
224
+ }
225
+ const quit = () => { void serialize(() => manage('stop')).catch(() => undefined) }
226
+ process.once('SIGTERM', quit)
227
+ process.once('SIGINT', quit)
228
+ }
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process'
3
+ import { platform } from 'node:os'
4
+ import { parseArgs } from 'node:util'
5
+ import { serverOrigin, workspaceDirectory } from './device-cli.mjs'
6
+ import { daemonCommand, runDaemon } from './device-daemon.mjs'
7
+
8
+ function openBrowser(link) {
9
+ const system = platform()
10
+ const [command, ...args] = system === 'darwin' ? ['open', link] : system === 'win32'
11
+ ? ['rundll32.exe', 'url.dll,FileProtocolHandler', link] : ['xdg-open', link]
12
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true })
13
+ child.once('error', () => {})
14
+ child.unref()
15
+ }
16
+
17
+ async function main() {
18
+ if (process.argv.slice(2).join(' ') === '--daemon') return runDaemon()
19
+ const { positionals, values } = parseArgs({
20
+ allowPositionals: true, options: {
21
+ server: { type: 'string' }, workspace: { type: 'string' }, name: { type: 'string' },
22
+ 'no-browser': { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
23
+ },
24
+ })
25
+ const [command, action, path] = positionals
26
+ if (values.help || !command) {
27
+ console.log('vanclaw-device connect --server <url> --workspace <directory> [--name <name>] [--no-browser]\n'
28
+ + 'vanclaw-device run | status | stop | logout\nvanclaw-device workspace add <directory>')
29
+ return
30
+ }
31
+ const daemon = (command, args, options) => daemonCommand(import.meta.filename, command, args, options)
32
+ if (positionals.length === 1) {
33
+ switch (command) {
34
+ case 'connect': {
35
+ const { url, code } = await daemon('connect', {
36
+ server: serverOrigin(values.server), workspace: await workspaceDirectory(values.workspace), name: values.name,
37
+ }, { start: true })
38
+ console.log('在浏览器中打开授权链接 ' + url + '\n确认代码 ' + code + '\n守护进程正在后台等待授权。')
39
+ if (!values['no-browser'] && process.stdout.isTTY) openBrowser(url)
40
+ return
41
+ }
42
+ case 'run':
43
+ await daemon('run', {}, { start: true })
44
+ console.log('设备守护进程正在后台运行。')
45
+ return
46
+ case 'status': {
47
+ const status = await daemon('status')
48
+ if (!status) console.log('设备守护进程未运行。')
49
+ else {
50
+ console.log(status.waiting ? '正在等待浏览器授权。' : status.ready ? '设备在线,可以执行任务。'
51
+ : status.connected ? '设备在线,执行尚未就绪。' : '设备未连接。')
52
+ if (status.reason) console.log(status.reason)
53
+ for (const directory of status.workspaces) console.log(directory)
54
+ console.log('日志 ' + status.logPath)
55
+ }
56
+ return
57
+ }
58
+ case 'stop':
59
+ await daemon('stop')
60
+ console.log('设备守护进程已停止。')
61
+ return
62
+ case 'logout':
63
+ await daemon('logout', {}, { start: true })
64
+ console.log('已退出设备授权。')
65
+ return
66
+ }
67
+ }
68
+ if (command === 'workspace' && action === 'add' && path && positionals.length === 3) {
69
+ const authorized = await workspaceDirectory(path)
70
+ await daemon('add', { path: authorized }, { start: true })
71
+ console.log('已授权工作目录 ' + authorized)
72
+ return
73
+ }
74
+ throw new Error('命令无效。请运行 vanclaw-device --help。')
75
+ }
76
+
77
+ await main().catch(error => {
78
+ console.error(error.message)
79
+ process.exitCode = 1
80
+ })
@@ -0,0 +1,19 @@
1
+ - id: agent-default-model
2
+ config:
3
+ provider: !!js process.env.VCH_NATIVE_MODEL_PROVIDER
4
+ model: !!js process.env.VCH_DEVICE_MODEL
5
+
6
+ - id: llm-deepseek
7
+ config:
8
+ apiKeyEnv: VCH_TASK_MODEL_GRANT
9
+ baseURL: !!js process.env.VCH_DEVICE_MODEL_BASE_URL
10
+
11
+ - id: pwsh-sandbox
12
+ config:
13
+ pwshPath: !!js process.env.VCH_POWERSHELL
14
+
15
+ - id: tool-plugin-manager
16
+ disabled: true
17
+
18
+ - id: remote-access
19
+ disabled: true
@@ -0,0 +1,79 @@
1
+ import { fork } from 'node:child_process'
2
+ import { mkdtemp, realpath, rm } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { delimiter, join } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ const entry = fileURLToPath(new URL('./device-task.mjs', import.meta.url))
8
+ const windows = process.platform === 'win32'
9
+ const systemRoot = process.env.SystemRoot || 'C:\\Windows'
10
+ const system32 = join(systemRoot, 'System32')
11
+ const powerShell = join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe')
12
+ const taskLimit = 28 * 60_000
13
+ const shutdownLimit = 9000
14
+
15
+ export function createNativeRuntime({ electron = false } = {}) {
16
+ async function launch(workspace, job, server) {
17
+ const home = await realpath(await mkdtemp(join(tmpdir(), 'vch-task-')))
18
+ const env = {
19
+ PATH: (windows ? [system32, systemRoot, join(system32, 'WindowsPowerShell', 'v1.0')]
20
+ : ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin', '/opt/homebrew/bin']).join(delimiter),
21
+ HOME: home, USERPROFILE: home, TMPDIR: home, TEMP: home, TMP: home,
22
+ LANG: process.env.LANG || 'en_US.UTF-8',
23
+ DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1',
24
+ VCH_NATIVE_MODEL_PROVIDER: process.env.VCH_NATIVE_MODEL_PROVIDER === 'vanclaw-official' ? 'vanclaw-official' : 'deepseek-official',
25
+ ...(windows && { SystemRoot: systemRoot, WINDIR: systemRoot, APPDATA: home, LOCALAPPDATA: home, VCH_POWERSHELL: powerShell }),
26
+ ...(electron && { ELECTRON_RUN_AS_NODE: '1' }),
27
+ ...(job && { VCH_DEVICE_MODEL: job.model, VCH_DEVICE_MODEL_BASE_URL: server + '/vch/device/model/v1' }),
28
+ }
29
+ let child
30
+ try {
31
+ child = fork(entry, job ? [job.permission] : [], {
32
+ cwd: workspace, env, execArgv: [], windowsHide: true,
33
+ stdio: [job ? 'pipe' : 'ignore', job ? 'pipe' : 'ignore', 'inherit', 'ipc'],
34
+ })
35
+ } catch (error) {
36
+ await rm(home, { recursive: true, force: true })
37
+ throw error
38
+ }
39
+ let killTimer
40
+ let timedOut = false
41
+ const timer = setTimeout(() => { timedOut = true; stop() }, job ? taskLimit : 25_000).unref()
42
+ const done = new Promise(resolve => {
43
+ child.once('error', () => {})
44
+ child.once('close', code => {
45
+ clearTimeout(timer)
46
+ clearTimeout(killTimer)
47
+ resolve(timedOut ? 124 : code ?? 1)
48
+ })
49
+ }).finally(async () => {
50
+ await rm(home, { recursive: true, force: true }).catch(() => undefined)
51
+ })
52
+ function stop() {
53
+ if (child.connected) child.disconnect()
54
+ killTimer ??= setTimeout(() => child.kill('SIGKILL'), shutdownLimit).unref()
55
+ return done
56
+ }
57
+ if (job) child.send({ modelToken: job.modelToken }, () => {})
58
+ return { child, done, stop }
59
+ }
60
+
61
+ return {
62
+ async check(workspace, signal) {
63
+ signal.throwIfAborted()
64
+ const process = await launch(workspace)
65
+ const cancel = () => { void process.stop() }
66
+ signal.addEventListener('abort', cancel, { once: true })
67
+ if (signal.aborted) cancel()
68
+ const code = await process.done
69
+ signal.removeEventListener('abort', cancel)
70
+ signal.throwIfAborted()
71
+ if (code !== 0) {
72
+ const error = new Error('本机沙箱无法启动。请检查系统是否支持 DSH 原生沙箱,以及工作目录权限。')
73
+ error.issue = 'isolation'
74
+ throw error
75
+ }
76
+ },
77
+ start: (server, job) => launch(job.workspace, job, server),
78
+ }
79
+ }
@@ -0,0 +1,46 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { once } from 'node:events'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { promisify } from 'node:util'
5
+ import { Context } from '@deepseek-ai/cordis'
6
+ import { runProfile } from '@deepseek-ai/dsh/profile-boot'
7
+ import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
8
+ import LocalSandboxProvider from '@deepseek-ai/dsh-sandbox-local'
9
+
10
+ const permission = process.argv[2]
11
+ const disconnected = new AbortController()
12
+ process.once('disconnect', () => disconnected.abort())
13
+
14
+ if (!permission) {
15
+ const ctx = new Context()
16
+ try {
17
+ const sandbox = new LocalSandboxProvider(ctx, { runnerCommand: [], runnerFailureSignatures: [], probeTimeoutMs: 5000 })
18
+ const shell = process.platform === 'win32'
19
+ ? [process.env.VCH_POWERSHELL, '-NoProfile', '-NonInteractive', '-Command', 'exit 0']
20
+ : ['/bin/bash', '--noprofile', '--norc', '-c', 'exit 0']
21
+ const { argv: [program, ...args] } = await sandbox.confine(shell, { mode: 'read-only', workspaceRoot: process.cwd() }, disconnected.signal)
22
+ await promisify(execFile)(program, args, { timeout: 12_000, windowsHide: true, signal: disconnected.signal })
23
+ } catch {
24
+ process.exitCode = 125
25
+ } finally {
26
+ await ctx.fiber.dispose()
27
+ if (process.connected) process.disconnect()
28
+ }
29
+ } else {
30
+ if (!['read-only', 'workspace-write'].includes(permission)) throw new Error('Invalid task permissions')
31
+ const [grant] = await once(process, 'message', { signal: disconnected.signal })
32
+ if (!/^[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}$/u.test(grant?.modelToken ?? '')) throw new Error('Invalid model grant')
33
+ // Supply the task grant to the model adapter only. Command subprocesses inherit no grant.
34
+ const environment = createLaunchEnvironmentSnapshot([
35
+ { source: 'process', values: { ...process.env, VCH_TASK_MODEL_GRANT: grant.modelToken } },
36
+ ])
37
+ const { shutdown } = await runProfile({
38
+ environment,
39
+ profile: 'headless',
40
+ patchFiles: [fileURLToPath(new URL('./device-native.patch.yml', import.meta.url))],
41
+ args: ['--permission-mode', permission, '--approval-policy', 'never', '--json', '-'],
42
+ })
43
+ disconnected.signal.addEventListener('abort', () => shutdown.interrupt(130), { once: true })
44
+ if (disconnected.signal.aborted) shutdown.interrupt(130)
45
+ process.channel?.unref()
46
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
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-15",
4
+ "description": "Connect a device to VanClaw Harness through browser authorization",
5
+ "type": "module",
6
+ "bin": {
7
+ "vanclaw-device": "device-main.mjs"
8
+ },
9
+ "files": [
10
+ "device-main.mjs",
11
+ "device-daemon.mjs",
12
+ "device-cli.mjs",
13
+ "device-runtime.mjs",
14
+ "device-task.mjs",
15
+ "device-native.patch.yml",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@deepseek-ai/dsh": "0.2.2-rc.5"
20
+ },
21
+ "engines": {
22
+ "node": ">=24.9.0"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ }
27
+ }