dsh-rayrun-bots 0.1.1-alpha → 0.1.1-alpha.2
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 +111 -255
- package/client.js +570 -146
- package/cloud-host/README.md +7 -1
- package/cloud-host/lib/host.mjs +13 -0
- package/cloud-host/lib/proposal.mjs +13 -6
- package/index.js +79 -10
- package/lib/cloud-host-runtime.js +19 -3
- package/lib/computer-update.js +322 -0
- package/lib/dependency.js +19 -0
- package/lib/errors.js +3 -0
- package/lib/rayrun-detached-runtime.js +128 -6
- package/lib/sessions.js +147 -9
- package/lib/update-check.js +117 -0
- package/locale/en.json +73 -25
- package/locale/zh.json +73 -25
- package/package.json +1 -1
package/cloud-host/README.md
CHANGED
|
@@ -69,7 +69,7 @@ DSH session spike on the same dev image (DSH 0.2.0-rc.2):
|
|
|
69
69
|
- the host with `DSH_BOT_AGENT=dsh` answered `HOST1_OK` then `BETA`, stored the
|
|
70
70
|
DSH session id, and wrote the expected transcript/outbox;
|
|
71
71
|
- automatic projection (2026-11-23): the adapter uploaded these assets to
|
|
72
|
-
`/workspace/.rayrun/host/0.1.1-alpha/`, verified the SHA-256 manifest, and
|
|
72
|
+
`/workspace/.rayrun/host/0.1.1-alpha.1/`, verified the SHA-256 manifest, and
|
|
73
73
|
the page E2E replied `HOST_E2E_OK`.
|
|
74
74
|
|
|
75
75
|
The dependency's `dsh.start` produced no `reply.md` on this image because its
|
|
@@ -127,6 +127,12 @@ execute it (ADR-019). `bin/propose.mjs` remains an optional shell path for
|
|
|
127
127
|
images where the agent can run commands. The prompt uses the structured block;
|
|
128
128
|
the live E2E did not rely on shell execution. A proposal file is not an authorization.
|
|
129
129
|
|
|
130
|
+
If a reply contains a malformed or unsupported block, the host strips the block,
|
|
131
|
+
writes no proposal, and appends the visible
|
|
132
|
+
`[[rayrun-approval-parse-error]]` marker. The Bots client replaces that marker
|
|
133
|
+
with a localized "approval request could not be parsed" notice, so a failed
|
|
134
|
+
proposal is never silently swallowed.
|
|
135
|
+
|
|
130
136
|
```bash
|
|
131
137
|
DSH_BOT_ROOT=/workspace/.rayrun DSH_BOT_ID=my-bot \
|
|
132
138
|
node bin/propose.mjs --kind rayrun.machine.stop --machine my-computer
|
package/cloud-host/lib/host.mjs
CHANGED
|
@@ -428,6 +428,19 @@ export function createCloudHost(options = {}) {
|
|
|
428
428
|
log('routine-result-failed', { botId, taskId: task.id, message: redact(writeError.message) })
|
|
429
429
|
}
|
|
430
430
|
}
|
|
431
|
+
if (task.origin !== 'routine') {
|
|
432
|
+
try {
|
|
433
|
+
atomicJson(path.join(paths.outbox, `${task.id}.json`), {
|
|
434
|
+
schema: 1,
|
|
435
|
+
botId,
|
|
436
|
+
taskId: task.id,
|
|
437
|
+
error: redact(error.message) || 'The cloud bot host failed the turn.',
|
|
438
|
+
at: now(),
|
|
439
|
+
})
|
|
440
|
+
} catch (writeError) {
|
|
441
|
+
log('outbox-failed', { botId, taskId: task.id, message: redact(writeError.message) })
|
|
442
|
+
}
|
|
443
|
+
}
|
|
431
444
|
renameSync(file, path.join(paths.failed, `${task.id || name}.json`))
|
|
432
445
|
log('task-failed', { botId, taskId: task.id, message: redact(error.message) })
|
|
433
446
|
return { botId, taskId: task.id, error: redact(error.message) }
|
|
@@ -18,6 +18,8 @@ const MACHINE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
|
|
|
18
18
|
const KINDS = new Set(['rayrun.machine.start', 'rayrun.machine.stop', 'rayrun.machine.pause', 'rayrun.machine.resume'])
|
|
19
19
|
const ORIGINS = new Set(['chat', 'background'])
|
|
20
20
|
const MARKER = /```rayrun-approval\s*\r?\n([\s\S]*?)\r?\n```/
|
|
21
|
+
export const APPROVAL_PARSE_ERROR = '[[rayrun-approval-parse-error]]'
|
|
22
|
+
const PARSE_ERROR_FALLBACK = 'The approval request in this reply could not be parsed. No action was requested.'
|
|
21
23
|
|
|
22
24
|
function invalid(message) {
|
|
23
25
|
return { text: message, proposal: null, error: message }
|
|
@@ -35,25 +37,30 @@ export function extractProposal(text, { botId, defaultMachine = '', origin = 'ch
|
|
|
35
37
|
if (!ORIGINS.has(origin)) return invalid('proposal origin is invalid.')
|
|
36
38
|
const match = MARKER.exec(reply)
|
|
37
39
|
if (!match) return { text: reply, proposal: null, error: null }
|
|
40
|
+
const cleaned = `${reply.slice(0, match.index)}${reply.slice(match.index + match[0].length)}`.trim()
|
|
41
|
+
const reject = (message) => ({
|
|
42
|
+
text: `${cleaned ? `${cleaned}\n\n` : ''}${APPROVAL_PARSE_ERROR} ${PARSE_ERROR_FALLBACK}`,
|
|
43
|
+
proposal: null,
|
|
44
|
+
error: message,
|
|
45
|
+
})
|
|
38
46
|
let value
|
|
39
47
|
try {
|
|
40
48
|
value = JSON.parse(match[1].trim())
|
|
41
49
|
} catch {
|
|
42
|
-
return
|
|
50
|
+
return reject('approval block is not valid JSON.')
|
|
43
51
|
}
|
|
44
52
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
45
|
-
return
|
|
53
|
+
return reject('approval block must be an object.')
|
|
46
54
|
}
|
|
47
55
|
for (const key of Object.keys(value)) {
|
|
48
|
-
if (key !== 'kind' && key !== 'machine') return
|
|
56
|
+
if (key !== 'kind' && key !== 'machine') return reject(`unsupported approval field: ${key}.`)
|
|
49
57
|
}
|
|
50
|
-
if (!KINDS.has(value.kind)) return
|
|
58
|
+
if (!KINDS.has(value.kind)) return reject('unsupported approval kind.')
|
|
51
59
|
const machine = typeof value.machine === 'string' && value.machine.trim() !== ''
|
|
52
60
|
? value.machine.trim()
|
|
53
61
|
: String(defaultMachine ?? '').trim()
|
|
54
|
-
if (!MACHINE.test(machine)) return
|
|
62
|
+
if (!MACHINE.test(machine)) return reject('approval machine is invalid.')
|
|
55
63
|
const id = `prop-${randomUUID()}`
|
|
56
|
-
const cleaned = `${reply.slice(0, match.index)}${reply.slice(match.index + match[0].length)}`.trim()
|
|
57
64
|
return {
|
|
58
65
|
text: cleaned || 'Waiting for approval.',
|
|
59
66
|
proposal: {
|
package/index.js
CHANGED
|
@@ -17,12 +17,15 @@
|
|
|
17
17
|
import { readFileSync } from 'node:fs'
|
|
18
18
|
import { createApprovalActionExecutor, normalizeApprovalAction } from './lib/approval-actions.js'
|
|
19
19
|
import { createCloudApprovalBridge } from './lib/cloud-approval-bridge.js'
|
|
20
|
+
import { CLOUD_HOST_IMAGE, openComputerUpdater } from './lib/computer-update.js'
|
|
20
21
|
import { createCloudRoutineBridge } from './lib/cloud-routine-bridge.js'
|
|
21
22
|
import { openApprovalExecutor } from './lib/approval-executor.js'
|
|
22
23
|
import { openApprovalStore } from './lib/approvals.js'
|
|
23
24
|
import { openBotStore } from './lib/bots.js'
|
|
24
25
|
import { createCloudHostRuntime } from './lib/cloud-host-runtime.js'
|
|
25
|
-
import {
|
|
26
|
+
import {
|
|
27
|
+
checkDependency, supportsDetached, supportsMachineCredentials, supportsRuntimeRpc,
|
|
28
|
+
} from './lib/dependency.js'
|
|
26
29
|
import { ERROR_CODES } from './lib/errors.js'
|
|
27
30
|
import { resolveStateRoot } from './lib/local-store.js'
|
|
28
31
|
import { createRayrunDetachedRuntime } from './lib/rayrun-detached-runtime.js'
|
|
@@ -33,6 +36,7 @@ import { createRoutineScheduler } from './lib/routine-scheduler.js'
|
|
|
33
36
|
import { openRoutineStore } from './lib/routines.js'
|
|
34
37
|
import { validateRuntime } from './lib/runtime.js'
|
|
35
38
|
import { openSessionRunner } from './lib/sessions.js'
|
|
39
|
+
import { checkForUpdate, updateCommand } from './lib/update-check.js'
|
|
36
40
|
|
|
37
41
|
export const name = 'rayrun-bots'
|
|
38
42
|
|
|
@@ -70,7 +74,7 @@ function profileDirectory(ctx) {
|
|
|
70
74
|
}
|
|
71
75
|
|
|
72
76
|
/** Run one roster action and return the success body. */
|
|
73
|
-
function botAction(action, payload, ctx) {
|
|
77
|
+
function botAction(action, payload, ctx, computerFor = () => null) {
|
|
74
78
|
const stateRoot = resolveStateRoot({ profileDir: profileDirectory(ctx) })
|
|
75
79
|
const store = openBotStore(stateRoot)
|
|
76
80
|
const routines = openRoutineStore(stateRoot)
|
|
@@ -81,11 +85,12 @@ function botAction(action, payload, ctx) {
|
|
|
81
85
|
ok: true,
|
|
82
86
|
bots,
|
|
83
87
|
routines: Object.fromEntries(bots.map((bot) => [bot.id, routines.list(bot.id)])),
|
|
88
|
+
computers: Object.fromEntries(bots.map((bot) => [bot.id, computerFor(bot.id)])),
|
|
84
89
|
}
|
|
85
90
|
}
|
|
86
91
|
case 'bots.get': {
|
|
87
92
|
const bot = store.get(payload.id)
|
|
88
|
-
return { ok: true, bot, routines: routines.list(bot.id) }
|
|
93
|
+
return { ok: true, bot, routines: routines.list(bot.id), computer: computerFor(bot.id) }
|
|
89
94
|
}
|
|
90
95
|
case 'bots.create': {
|
|
91
96
|
const input = { ...payload }
|
|
@@ -176,6 +181,7 @@ const STATUS_BY_CODE = new Map([
|
|
|
176
181
|
[ERROR_CODES.approvalReplay, 409],
|
|
177
182
|
[ERROR_CODES.approvalUnknown, 404],
|
|
178
183
|
[ERROR_CODES.approvalExecution, 502],
|
|
184
|
+
[ERROR_CODES.computerUpdate, 409],
|
|
179
185
|
])
|
|
180
186
|
|
|
181
187
|
function sendActionError(res, error) {
|
|
@@ -187,7 +193,7 @@ function sendActionError(res, error) {
|
|
|
187
193
|
}
|
|
188
194
|
|
|
189
195
|
/** Run one session action against the bot's durable local session. */
|
|
190
|
-
function sessionAction(action, payload, getService) {
|
|
196
|
+
async function sessionAction(action, payload, getService) {
|
|
191
197
|
if (action !== 'session.send' && action !== 'session.history' && action !== 'session.status') {
|
|
192
198
|
const error = new Error(`Unknown action: ${action}`)
|
|
193
199
|
error.status = 404
|
|
@@ -197,7 +203,7 @@ function sessionAction(action, payload, getService) {
|
|
|
197
203
|
const bot = service.bots.get(payload.botId)
|
|
198
204
|
switch (action) {
|
|
199
205
|
case 'session.send':
|
|
200
|
-
return { ok: true, ...service.runner.
|
|
206
|
+
return { ok: true, ...(await service.runner.sendAccepted(bot.id, payload.text)) }
|
|
201
207
|
case 'session.history':
|
|
202
208
|
return {
|
|
203
209
|
ok: true,
|
|
@@ -315,9 +321,19 @@ export function apply(ctx, options = {}) {
|
|
|
315
321
|
let webServer
|
|
316
322
|
const injectedRuntime = options.runtime === undefined ? undefined : validateRuntime(options.runtime)
|
|
317
323
|
const installed = checkDependency(profileDirectory(ctx))
|
|
324
|
+
// The persistent cloud host is the default execution path on a dependency
|
|
325
|
+
// with the runtime RPC. `cloudHost: false` keeps the detached/one-shot
|
|
326
|
+
// fallback; an explicit object still pins or configures the host.
|
|
327
|
+
const cloudHostExplicit = options.cloudHost !== undefined && options.cloudHost !== null && options.cloudHost !== false
|
|
328
|
+
const cloudHostEnabled = options.cloudHost !== false && options.cloudHost !== null
|
|
329
|
+
&& (cloudHostExplicit || (
|
|
330
|
+
injectedRuntime === undefined
|
|
331
|
+
&& supportsRuntimeRpc(installed.version)
|
|
332
|
+
&& supportsMachineCredentials(installed.version)
|
|
333
|
+
))
|
|
318
334
|
let cloudHostRuntime
|
|
319
|
-
if (
|
|
320
|
-
const config = options.cloudHost === true ? {} : options.cloudHost
|
|
335
|
+
if (cloudHostEnabled) {
|
|
336
|
+
const config = options.cloudHost === undefined || options.cloudHost === true ? {} : options.cloudHost
|
|
321
337
|
if (typeof config !== 'object' || Array.isArray(config)) {
|
|
322
338
|
throw new TypeError('cloudHost config must be an object.')
|
|
323
339
|
}
|
|
@@ -334,7 +350,10 @@ export function apply(ctx, options = {}) {
|
|
|
334
350
|
}
|
|
335
351
|
const runtime = injectedRuntime ?? validateRuntime(
|
|
336
352
|
cloudHostRuntime ?? (supportsDetached(installed.version)
|
|
337
|
-
? createRayrunDetachedRuntime({
|
|
353
|
+
? createRayrunDetachedRuntime({
|
|
354
|
+
getOrigin: () => webServer?.getOrigin?.(),
|
|
355
|
+
getTools: () => ctx.get?.('tools'),
|
|
356
|
+
})
|
|
338
357
|
: createRayrunAgentRuntime({
|
|
339
358
|
getTools: () => ctx.get?.('tools'),
|
|
340
359
|
getOrigin: () => webServer?.getOrigin?.(),
|
|
@@ -355,6 +374,25 @@ export function apply(ctx, options = {}) {
|
|
|
355
374
|
return sessionService
|
|
356
375
|
}
|
|
357
376
|
|
|
377
|
+
function computerFor(botId) {
|
|
378
|
+
const pinned = cloudHostRuntime?.machineName
|
|
379
|
+
if (typeof pinned === 'string' && pinned !== '') return pinned
|
|
380
|
+
return sessions().runner.computer(botId) ?? null
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
let computerUpdateService
|
|
384
|
+
function computerUpdater() {
|
|
385
|
+
if (computerUpdateService === undefined) {
|
|
386
|
+
computerUpdateService = openComputerUpdater({
|
|
387
|
+
rpc: createRayrunRpc({ getOrigin: () => webServer?.getOrigin?.() }),
|
|
388
|
+
getTools: () => ctx.get?.('tools'),
|
|
389
|
+
logger: ctx.logger,
|
|
390
|
+
...(cloudHostRuntime === undefined ? {} : { image: CLOUD_HOST_IMAGE }),
|
|
391
|
+
})
|
|
392
|
+
}
|
|
393
|
+
return computerUpdateService
|
|
394
|
+
}
|
|
395
|
+
|
|
358
396
|
let approvalService
|
|
359
397
|
function approvals() {
|
|
360
398
|
if (approvalService === undefined) {
|
|
@@ -455,9 +493,40 @@ export function apply(ctx, options = {}) {
|
|
|
455
493
|
sendJson(res, 200, hostHealth())
|
|
456
494
|
return
|
|
457
495
|
}
|
|
496
|
+
if (payload?.action === 'update.check') {
|
|
497
|
+
try {
|
|
498
|
+
const result = await checkForUpdate({ current: VERSION })
|
|
499
|
+
const command = result.updateAvailable
|
|
500
|
+
? updateCommand({ latest: result.latest })
|
|
501
|
+
: null
|
|
502
|
+
sendJson(res, 200, { ok: true, ...result, command })
|
|
503
|
+
} catch (error) {
|
|
504
|
+
sendError(res, 502, ERROR_CODES.internal, `Could not check npm: ${String(error?.message ?? error).slice(0, 200)}`)
|
|
505
|
+
}
|
|
506
|
+
return
|
|
507
|
+
}
|
|
508
|
+
if (payload?.action === 'computer.update') {
|
|
509
|
+
try {
|
|
510
|
+
if (hasStateRoot) {
|
|
511
|
+
const service = sessions()
|
|
512
|
+
const busy = service.bots.list().some((bot) => {
|
|
513
|
+
const status = service.runner.status(bot.id)
|
|
514
|
+
return status?.state === 'running' || status?.state === 'queued'
|
|
515
|
+
})
|
|
516
|
+
if (busy) {
|
|
517
|
+
sendError(res, 409, ERROR_CODES.computerUpdate, 'Stop running or queued bot turns before updating the computer.')
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
sendJson(res, 200, { ok: true, ...(await computerUpdater().update(payload)) })
|
|
522
|
+
} catch (error) {
|
|
523
|
+
sendActionError(res, error)
|
|
524
|
+
}
|
|
525
|
+
return
|
|
526
|
+
}
|
|
458
527
|
if (typeof payload?.action === 'string' && payload.action.startsWith('bots.')) {
|
|
459
528
|
try {
|
|
460
|
-
sendJson(res, 200, botAction(payload.action, payload, ctx))
|
|
529
|
+
sendJson(res, 200, botAction(payload.action, payload, ctx, computerFor))
|
|
461
530
|
} catch (error) {
|
|
462
531
|
sendActionError(res, error)
|
|
463
532
|
}
|
|
@@ -465,7 +534,7 @@ export function apply(ctx, options = {}) {
|
|
|
465
534
|
}
|
|
466
535
|
if (typeof payload?.action === 'string' && payload.action.startsWith('session.')) {
|
|
467
536
|
try {
|
|
468
|
-
sendJson(res, 200, sessionAction(payload.action, payload, sessions))
|
|
537
|
+
sendJson(res, 200, await sessionAction(payload.action, payload, sessions))
|
|
469
538
|
} catch (error) {
|
|
470
539
|
sendActionError(res, error)
|
|
471
540
|
}
|
|
@@ -27,6 +27,7 @@ import { createRuntimeRpc } from './runtime-rpc.js'
|
|
|
27
27
|
import { RUNTIME_CONTRACT_VERSION } from './runtime.js'
|
|
28
28
|
|
|
29
29
|
const TASK_TIMEOUT_SECONDS = 900
|
|
30
|
+
const HOST_READY_ATTEMPTS = 30
|
|
30
31
|
const HOST_PROFILE = 'bot'
|
|
31
32
|
const HOST_RUNTIME = 'bot-host'
|
|
32
33
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
@@ -214,6 +215,13 @@ export function createCloudHostRuntime({
|
|
|
214
215
|
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name) ? name : String(machine.id)
|
|
215
216
|
}
|
|
216
217
|
|
|
218
|
+
function machineCredentialNames(machine) {
|
|
219
|
+
if (!Array.isArray(machine?.credentials)) return []
|
|
220
|
+
return machine.credentials
|
|
221
|
+
.map((name) => (typeof name === 'string' ? name.trim() : ''))
|
|
222
|
+
.filter((name) => name !== '')
|
|
223
|
+
}
|
|
224
|
+
|
|
217
225
|
function spec(script, machine) {
|
|
218
226
|
return {
|
|
219
227
|
argv: ['node', script],
|
|
@@ -229,7 +237,7 @@ export function createCloudHostRuntime({
|
|
|
229
237
|
DSH_BOT_PROPOSE: `${path.posix.dirname(String(script))}/bin/propose.mjs`,
|
|
230
238
|
DSH_BOT_MACHINE: machineRef(machine),
|
|
231
239
|
},
|
|
232
|
-
credentials: [...credentials],
|
|
240
|
+
credentials: [...(credentials.length > 0 ? credentials : machineCredentialNames(machine).slice(0, 1))],
|
|
233
241
|
restart: 'always',
|
|
234
242
|
autostart: true,
|
|
235
243
|
keep_alive: true,
|
|
@@ -307,13 +315,15 @@ export function createCloudHostRuntime({
|
|
|
307
315
|
|
|
308
316
|
async function waitHostReady(sandbox) {
|
|
309
317
|
const statePath = '.rayrun/host/state.json'
|
|
310
|
-
|
|
318
|
+
// A previous host leaves `stopped` behind. A newly started host may not
|
|
319
|
+
// have overwritten it yet, so wait for a fresh `running`, not the first
|
|
320
|
+
// value read. The bound covers a cold worker bootstrap.
|
|
321
|
+
for (let attempt = 0; attempt < HOST_READY_ATTEMPTS; attempt += 1) {
|
|
311
322
|
const text = await readFile(sandbox, statePath)
|
|
312
323
|
if (text !== null) {
|
|
313
324
|
let state
|
|
314
325
|
try { state = JSON.parse(text) } catch { state = null }
|
|
315
326
|
if (state?.state === 'running') return
|
|
316
|
-
if (state?.state === 'stopped') break
|
|
317
327
|
}
|
|
318
328
|
await sleep(1000)
|
|
319
329
|
}
|
|
@@ -327,6 +337,9 @@ export function createCloudHostRuntime({
|
|
|
327
337
|
get available() {
|
|
328
338
|
return supported && Boolean(getOrigin?.()) && filesTool() !== undefined
|
|
329
339
|
},
|
|
340
|
+
get machineName() {
|
|
341
|
+
return pinnedMachine ?? null
|
|
342
|
+
},
|
|
330
343
|
async start({ bot, text, history = [], messageSeq, origin, botId, stateRoot } = {}) {
|
|
331
344
|
if (typeof botId !== 'string' || botId === '') throw rayrunFailure(ERROR_CODES.runtimeUnavailable, 'botId is required.')
|
|
332
345
|
const { machine, host } = await prepareHost()
|
|
@@ -374,6 +387,9 @@ export function createCloudHostRuntime({
|
|
|
374
387
|
} catch {
|
|
375
388
|
throw rayrunFailure(ERROR_CODES.internal, 'The cloud bot host wrote an invalid outbox file.')
|
|
376
389
|
}
|
|
390
|
+
if (typeof value?.error === 'string' && value.error.trim() !== '') {
|
|
391
|
+
throw rayrunFailure(ERROR_CODES.workerNoReply, `The cloud bot host failed the turn: ${value.error.slice(0, 500)}`)
|
|
392
|
+
}
|
|
377
393
|
if (typeof value?.reply !== 'string' || value.reply.trim() === '') {
|
|
378
394
|
throw rayrunFailure(ERROR_CODES.internal, 'The cloud bot host returned no reply.')
|
|
379
395
|
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replace the bots' shared cloud computer with a fresh image while keeping the
|
|
3
|
+
* workspace and common sign-in/config directories.
|
|
4
|
+
*
|
|
5
|
+
* Rayrun has no in-place image rebuild. The safe path is:
|
|
6
|
+
* 1. rename the current computer to a rollback name;
|
|
7
|
+
* 2. create a new computer with the original name and selected image/credential;
|
|
8
|
+
* 3. tar the preserved paths from the old computer, copy them through the
|
|
9
|
+
* dependency's `rayrun_files` tool, and extract them on the new computer;
|
|
10
|
+
* 4. destroy the old computer only after the new one is ready and verified.
|
|
11
|
+
*
|
|
12
|
+
* The user's Update confirmation is the explicit request for that destruction.
|
|
13
|
+
* Any failure before that point restores the old name and leaves the old
|
|
14
|
+
* computer available; the new computer is stopped and renamed so it cannot take
|
|
15
|
+
* the original name. If only the final destroy fails, the new computer stays in
|
|
16
|
+
* place and the old one is stopped; the result reports that cleanup failed. This
|
|
17
|
+
* module only uses the published dependency tools/RPC; the Rayrun token never
|
|
18
|
+
* enters this module or its results.
|
|
19
|
+
*/
|
|
20
|
+
import { mkdtempSync, rmSync, statSync } from 'node:fs'
|
|
21
|
+
import { tmpdir } from 'node:os'
|
|
22
|
+
import path from 'node:path'
|
|
23
|
+
import { ERROR_CODES } from './errors.js'
|
|
24
|
+
import { rayrunFailure } from './rayrun-rpc.js'
|
|
25
|
+
|
|
26
|
+
const NAME_MAX = 64
|
|
27
|
+
const TIMEOUT_MS = 30 * 60 * 1000
|
|
28
|
+
const PRESERVE = ['workspace', 'root/.config', 'root/.local/share', 'root/.mozilla', 'root/.ssh']
|
|
29
|
+
const BOT_IMAGE = 'deepseek-harness@1'
|
|
30
|
+
const CLOUD_HOST_IMAGE = 'dsh-bot@1'
|
|
31
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/
|
|
32
|
+
|
|
33
|
+
function machineName(machine) {
|
|
34
|
+
const name = typeof machine?.name === 'string' ? machine.name.trim() : ''
|
|
35
|
+
if (!name || name.length > NAME_MAX || CONTROL.test(name)) {
|
|
36
|
+
throw rayrunFailure(ERROR_CODES.internal, 'The current cloud computer has no usable name.')
|
|
37
|
+
}
|
|
38
|
+
return name
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function updateError(message) {
|
|
42
|
+
return rayrunFailure(ERROR_CODES.computerUpdate, message)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function credentialNameOf(item) {
|
|
46
|
+
if (typeof item === 'string') return item.trim()
|
|
47
|
+
return typeof item?.name === 'string' ? item.name.trim() : ''
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function pickCredential(list, machine) {
|
|
51
|
+
const names = list.map(credentialNameOf).filter(Boolean)
|
|
52
|
+
const bound = Array.isArray(machine?.credentials)
|
|
53
|
+
? machine.credentials.filter((name) => typeof name === 'string' && names.includes(name))
|
|
54
|
+
: []
|
|
55
|
+
if (bound.length > 0) return bound[0]
|
|
56
|
+
const preferred = names.find((name) => /deepseek|model/i.test(name))
|
|
57
|
+
if (preferred) return preferred
|
|
58
|
+
return names.length === 1 ? names[0] : ''
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function toolOf(registry, name) {
|
|
62
|
+
let tool
|
|
63
|
+
try {
|
|
64
|
+
tool = registry?.get?.(name)
|
|
65
|
+
} catch {
|
|
66
|
+
tool = undefined
|
|
67
|
+
}
|
|
68
|
+
if (typeof tool?.execute !== 'function') {
|
|
69
|
+
throw updateError(`dsh-rayrun-computer is missing the ${name} tool; the computer was not updated.`)
|
|
70
|
+
}
|
|
71
|
+
return tool
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function backupName(name, stamp) {
|
|
75
|
+
const suffix = `-pre-update-${stamp}`
|
|
76
|
+
return `${name.slice(0, Math.max(1, NAME_MAX - suffix.length))}${suffix}`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function failedName(name, stamp) {
|
|
80
|
+
const suffix = `-failed-update-${stamp}`
|
|
81
|
+
return `${name.slice(0, Math.max(1, NAME_MAX - suffix.length))}${suffix}`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function sameMachine(machine, wanted) {
|
|
85
|
+
return machine?.name === wanted || machine?.id === wanted
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function shellFailure(result, action) {
|
|
89
|
+
if (result?.timed_out) throw updateError(`${action} timed out; the computer was not updated.`)
|
|
90
|
+
if (Number(result?.exit_code) !== 0) {
|
|
91
|
+
const detail = String(result?.stderr || result?.stdout || '').trim().slice(0, 300)
|
|
92
|
+
throw updateError(`${action} failed${detail ? `: ${detail}` : '.'}`)
|
|
93
|
+
}
|
|
94
|
+
return result
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @param {{
|
|
99
|
+
* rpc: { call: Function, resolveMachine?: Function },
|
|
100
|
+
* getTools: () => object,
|
|
101
|
+
* logger?: object,
|
|
102
|
+
* }} options
|
|
103
|
+
*/
|
|
104
|
+
export function openComputerUpdater({ rpc, getTools, logger, image: requestedImage = BOT_IMAGE } = {}) {
|
|
105
|
+
if (typeof rpc?.call !== 'function') throw new TypeError('computer updater needs a Rayrun RPC client.')
|
|
106
|
+
if (typeof getTools !== 'function') throw new TypeError('computer updater needs a tool registry.')
|
|
107
|
+
if (typeof requestedImage !== 'string' || requestedImage.trim() === '' || CONTROL.test(requestedImage)) {
|
|
108
|
+
throw new TypeError('computer updater needs a valid image name.')
|
|
109
|
+
}
|
|
110
|
+
const image = requestedImage.trim()
|
|
111
|
+
let running = false
|
|
112
|
+
|
|
113
|
+
async function overview(signal) {
|
|
114
|
+
return rpc.call('overview', {}, { timeoutMs: 30_000, signal })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function findMachine(machineRef, signal) {
|
|
118
|
+
const body = await overview(signal)
|
|
119
|
+
const machines = Array.isArray(body?.machines) ? body.machines.filter((item) => item?.status !== 'Terminated') : []
|
|
120
|
+
const wanted = String(machineRef ?? '').trim()
|
|
121
|
+
const machine = wanted
|
|
122
|
+
? machines.find((item) => sameMachine(item, wanted))
|
|
123
|
+
: machines[0]
|
|
124
|
+
if (!machine) throw updateError('The cloud computer to update was not found; nothing was changed.')
|
|
125
|
+
return { body, machine }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function waitRunning(machineId, signal) {
|
|
129
|
+
for (let attempt = 0; attempt < 60; attempt += 1) {
|
|
130
|
+
const body = await rpc.call('machine.get', { id: machineId }, { timeoutMs: 30_000, signal })
|
|
131
|
+
if (body?.machine?.status === 'Running') return body.machine
|
|
132
|
+
await new Promise((resolve) => setTimeout(resolve, 1000))
|
|
133
|
+
}
|
|
134
|
+
throw updateError('The new cloud computer did not reach Running; the old computer was restored.')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function update({ machine: machineRef, confirmed } = {}) {
|
|
138
|
+
if (running) throw updateError('A computer update is already running; wait for it to finish.')
|
|
139
|
+
if (confirmed !== true) throw updateError('Updating the computer requires explicit confirmation.')
|
|
140
|
+
|
|
141
|
+
running = true
|
|
142
|
+
const stamp = Date.now().toString(36)
|
|
143
|
+
let old = null
|
|
144
|
+
let original = ''
|
|
145
|
+
let originalStatus = ''
|
|
146
|
+
let backup = ''
|
|
147
|
+
let renamed = false
|
|
148
|
+
let created = null
|
|
149
|
+
let localDir = null
|
|
150
|
+
const tarPath = `.dsh/rayrun-update-${stamp}.tgz`
|
|
151
|
+
try {
|
|
152
|
+
const { body, machine } = await findMachine(machineRef)
|
|
153
|
+
old = machine
|
|
154
|
+
original = machineName(machine)
|
|
155
|
+
originalStatus = machine.status
|
|
156
|
+
backup = backupName(original, stamp)
|
|
157
|
+
if (machine.status !== 'Running' && machine.status !== 'Paused' && machine.status !== 'Stopped') {
|
|
158
|
+
throw updateError(`The cloud computer is ${machine.status}; no update was attempted.`)
|
|
159
|
+
}
|
|
160
|
+
const agents = Array.isArray(body?.agents) ? body.agents : []
|
|
161
|
+
if (agents.length > 0 && !agents.some((agent) => agent?.ref === image)) {
|
|
162
|
+
throw updateError(`The required image ${image} is not available in this Rayrun account.`)
|
|
163
|
+
}
|
|
164
|
+
const credentials = await rpc.call('credentials.list', {}, { timeoutMs: 30_000 })
|
|
165
|
+
const list = Array.isArray(credentials?.credentials) ? credentials.credentials : []
|
|
166
|
+
const credentialName = pickCredential(list, machine)
|
|
167
|
+
if (!credentialName) {
|
|
168
|
+
throw updateError('No DeepSeek credential is available in this Rayrun account; add one before updating the computer.')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const tools = getTools()
|
|
172
|
+
const exec = toolOf(tools, 'rayrun_exec')
|
|
173
|
+
const files = toolOf(tools, 'rayrun_files')
|
|
174
|
+
const signal = AbortSignal.timeout(TIMEOUT_MS)
|
|
175
|
+
localDir = mkdtempSync(path.join(tmpdir(), 'rayrun-bots-update-'))
|
|
176
|
+
const localTar = path.join(localDir, 'workspace.tgz')
|
|
177
|
+
|
|
178
|
+
const rename = async (id, name) => rpc.call('machine.action', { id, verb: 'rename', name }, { timeoutMs: 120_000, signal })
|
|
179
|
+
const stop = async (id) => rpc.call('machine.action', { id, verb: 'stop' }, { timeoutMs: 120_000, signal })
|
|
180
|
+
|
|
181
|
+
await rename(old.id, backup)
|
|
182
|
+
renamed = true
|
|
183
|
+
const create = await rpc.call('machine.create', {
|
|
184
|
+
name: original,
|
|
185
|
+
agent: image,
|
|
186
|
+
cpu_cores: Number(old.cpu_cores) || 2,
|
|
187
|
+
memory_mb: Math.max(2048, Number(old.memory_mb) || 2048),
|
|
188
|
+
...(Number(old.workspace_mb) > 0 ? { workspace_mb: Number(old.workspace_mb) } : {}),
|
|
189
|
+
remote_desktop: old.remote_desktop === true,
|
|
190
|
+
credentials: [credentialName],
|
|
191
|
+
egress_allow: ['api.deepseek.com'],
|
|
192
|
+
...(Number(old.max_lifetime_seconds) > 0 ? { lifetime_seconds: Number(old.max_lifetime_seconds) } : {}),
|
|
193
|
+
}, { timeoutMs: 240_000, signal })
|
|
194
|
+
created = create?.machine
|
|
195
|
+
if (!created?.id) throw updateError('Rayrun created no replacement computer; the old computer was restored.')
|
|
196
|
+
const runningMachine = created.status === 'Running' ? created : await waitRunning(created.id, signal)
|
|
197
|
+
|
|
198
|
+
shellFailure(await exec.execute({
|
|
199
|
+
sandbox: old.id,
|
|
200
|
+
command: [
|
|
201
|
+
'set -e',
|
|
202
|
+
'paths=""',
|
|
203
|
+
...PRESERVE.map((entry) => `[ -e "/${entry}" ] && paths="$paths ${entry}"`),
|
|
204
|
+
'[ -n "$paths" ]',
|
|
205
|
+
'mkdir -p /workspace/.dsh',
|
|
206
|
+
`tar -czf /workspace/${tarPath} --exclude=workspace/${tarPath} -C / $paths`,
|
|
207
|
+
].join('\n'),
|
|
208
|
+
timeout_seconds: 1800,
|
|
209
|
+
}, { signal }), 'Packing the old computer')
|
|
210
|
+
|
|
211
|
+
await files.execute({
|
|
212
|
+
action: 'download',
|
|
213
|
+
sandbox: old.id,
|
|
214
|
+
path: tarPath,
|
|
215
|
+
local_path: localTar,
|
|
216
|
+
}, { signal })
|
|
217
|
+
const size = statSync(localTar).size
|
|
218
|
+
if (size <= 0) throw updateError('The workspace archive is empty; the old computer was restored.')
|
|
219
|
+
shellFailure(await exec.execute({
|
|
220
|
+
sandbox: runningMachine.id,
|
|
221
|
+
command: 'mkdir -p /workspace/.dsh',
|
|
222
|
+
timeout_seconds: 60,
|
|
223
|
+
}, { signal }), 'Preparing the new computer')
|
|
224
|
+
await files.execute({
|
|
225
|
+
action: 'upload',
|
|
226
|
+
sandbox: runningMachine.name || runningMachine.id,
|
|
227
|
+
path: tarPath,
|
|
228
|
+
local_path: localTar,
|
|
229
|
+
}, { signal })
|
|
230
|
+
shellFailure(await exec.execute({
|
|
231
|
+
sandbox: runningMachine.id,
|
|
232
|
+
command: `test -s /workspace/${tarPath}`,
|
|
233
|
+
timeout_seconds: 60,
|
|
234
|
+
}, { signal }), 'Checking the uploaded archive')
|
|
235
|
+
|
|
236
|
+
shellFailure(await exec.execute({
|
|
237
|
+
sandbox: runningMachine.id,
|
|
238
|
+
command: `set -e\ntar -xzf /workspace/${tarPath} -C /\nrm -f /workspace/${tarPath}`,
|
|
239
|
+
timeout_seconds: 1800,
|
|
240
|
+
}, { signal }), 'Restoring the new computer')
|
|
241
|
+
shellFailure(await exec.execute({
|
|
242
|
+
sandbox: runningMachine.id,
|
|
243
|
+
command: 'test -d /workspace',
|
|
244
|
+
timeout_seconds: 60,
|
|
245
|
+
}, { signal }), 'Checking the new computer')
|
|
246
|
+
await exec.execute({
|
|
247
|
+
sandbox: old.id,
|
|
248
|
+
command: `rm -f /workspace/${tarPath}`,
|
|
249
|
+
timeout_seconds: 60,
|
|
250
|
+
}, { signal }).catch(() => {})
|
|
251
|
+
|
|
252
|
+
let destroyed = false
|
|
253
|
+
try {
|
|
254
|
+
await rpc.call('machine.action', { id: old.id, verb: 'destroy' }, { timeoutMs: 120_000, signal })
|
|
255
|
+
destroyed = true
|
|
256
|
+
} catch (error) {
|
|
257
|
+
// The new computer is already verified. Do not roll back a successful
|
|
258
|
+
// migration because cleanup failed; stop the old computer and report it.
|
|
259
|
+
try { await stop(old.id) } catch { /* best effort */ }
|
|
260
|
+
try {
|
|
261
|
+
logger?.warn?.(`dsh-rayrun-bots: computer update could not destroy the old computer: ${String(error?.message ?? error).slice(0, 200)}`)
|
|
262
|
+
} catch {
|
|
263
|
+
// Logging must not change the update result.
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
updated: true,
|
|
268
|
+
machine: { id: runningMachine.id, name: runningMachine.name || original, image },
|
|
269
|
+
previous: { id: old.id, name: backup, status: destroyed ? 'Destroyed' : 'Stopped', destroyed },
|
|
270
|
+
credential: credentialName,
|
|
271
|
+
}
|
|
272
|
+
} catch (error) {
|
|
273
|
+
let restored = true
|
|
274
|
+
if (old !== null) {
|
|
275
|
+
if (created?.id) {
|
|
276
|
+
try {
|
|
277
|
+
await rpc.call('machine.action', { id: created.id, verb: 'rename', name: failedName(original, stamp) }, { timeoutMs: 120_000 })
|
|
278
|
+
} catch { restored = false }
|
|
279
|
+
try {
|
|
280
|
+
await rpc.call('machine.action', { id: created.id, verb: 'stop' }, { timeoutMs: 120_000 })
|
|
281
|
+
} catch { restored = false }
|
|
282
|
+
}
|
|
283
|
+
if (renamed) {
|
|
284
|
+
try {
|
|
285
|
+
await rpc.call('machine.action', { id: old.id, verb: 'rename', name: original }, { timeoutMs: 120_000 })
|
|
286
|
+
} catch { restored = false }
|
|
287
|
+
if (originalStatus !== 'Running') {
|
|
288
|
+
try {
|
|
289
|
+
const current = await rpc.call('machine.get', { id: old.id }, { timeoutMs: 30_000 })
|
|
290
|
+
if (current?.machine?.status === 'Running') {
|
|
291
|
+
await rpc.call('machine.action', { id: old.id, verb: 'stop' }, { timeoutMs: 120_000 })
|
|
292
|
+
}
|
|
293
|
+
} catch { /* best effort: the old machine may already be stopped */ }
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
logger?.warn?.(`dsh-rayrun-bots: computer update failed: ${String(error?.message ?? error).slice(0, 200)}`)
|
|
299
|
+
} catch {
|
|
300
|
+
// Logging must not change the failure.
|
|
301
|
+
}
|
|
302
|
+
const replacement = created?.id ? ` The stopped replacement is ${failedName(original, stamp)}.` : ''
|
|
303
|
+
if (!restored) {
|
|
304
|
+
throw updateError(`Computer update failed and automatic rollback could not restore "${original}"; check the old and new computers before retrying.${replacement} ${String(error?.message ?? error).slice(0, 300)}`)
|
|
305
|
+
}
|
|
306
|
+
if (error?.code === ERROR_CODES.computerUpdate) {
|
|
307
|
+
if (!replacement) throw error
|
|
308
|
+
throw updateError(`${error.message}${replacement}`)
|
|
309
|
+
}
|
|
310
|
+
throw updateError(`Computer update failed; the old computer was restored.${replacement} ${String(error?.message ?? error).slice(0, 300)}`)
|
|
311
|
+
} finally {
|
|
312
|
+
running = false
|
|
313
|
+
if (localDir !== null) {
|
|
314
|
+
try { rmSync(localDir, { recursive: true, force: true }) } catch { /* temp cleanup is best effort */ }
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return { update }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export { BOT_IMAGE, CLOUD_HOST_IMAGE, PRESERVE }
|