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/lib/dependency.js CHANGED
@@ -19,6 +19,9 @@ export const DETACHED_MIN_VERSION = '1.1.0'
19
19
  /** `runtime.*` arrived in the 1.2 line. */
20
20
  export const RUNTIME_RPC_MIN_VERSION = '1.2.0'
21
21
 
22
+ /** Machine-bound credential names arrived in 1.2.2. */
23
+ export const MACHINE_CREDENTIALS_MIN_VERSION = '1.2.2'
24
+
22
25
  /**
23
26
  * Whether an installed 1.x dependency exposes the host-callable detached RPC.
24
27
  * 1.0.x uses the single-turn `rayrun_agent` tool instead.
@@ -48,6 +51,22 @@ export function supportsRuntimeRpc(version) {
48
51
  return minor > 2 || (minor === 2 && patch >= 0)
49
52
  }
50
53
 
54
+ /**
55
+ * Whether the installed dependency returns machine-bound credential names in
56
+ * `overview.machines[]` / `machine.get`. Default cloudHost relies on this to
57
+ * carry the machine credential into the runtime spec; 1.2.0 and 1.2.1 do not.
58
+ * @param {string | null | undefined} version
59
+ * @returns {boolean}
60
+ */
61
+ export function supportsMachineCredentials(version) {
62
+ if (typeof version !== 'string') return false
63
+ const match = /^1\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.-]+)?$/.exec(version)
64
+ if (!match) return false
65
+ const minor = Number(match[1])
66
+ const patch = Number(match[2])
67
+ return minor > 2 || (minor === 2 && patch >= 2)
68
+ }
69
+
51
70
  /** Read the installed package manifest, distinguishing a missing package from a broken one. */
52
71
  function readInstalled(profileDir) {
53
72
  const filename = path.join(profileDir, 'node_modules', DEPENDENCY_NAME, 'package.json')
package/lib/errors.js CHANGED
@@ -30,6 +30,9 @@ export const ERROR_CODES = Object.freeze({
30
30
  runtimeNotFound: 'E_RUNTIME_NOT_FOUND',
31
31
  runtimesUnavailable: 'E_RUNTIMES_UNAVAILABLE',
32
32
  guestdOutdated: 'E_GUESTD_OUTDATED',
33
+ imageUnsupported: 'E_IMAGE_UNSUPPORTED',
34
+ workerNoReply: 'E_WORKER_NO_REPLY',
35
+ computerUpdate: 'E_COMPUTER_UPDATE',
33
36
  balanceLow: 'E_BALANCE_LOW',
34
37
  internal: 'E_INTERNAL',
35
38
  })
@@ -22,17 +22,128 @@ import { RUNTIME_CONTRACT_VERSION } from './runtime.js'
22
22
 
23
23
  const TASK_TIMEOUT_SECONDS = 900
24
24
  const REPLY_MAX_BYTES = 64 * 1024
25
+ const IMAGE_MAX = 128
26
+ const DETACHED_IMAGE = 'deepseek-harness@1'
27
+ const SHELL_ONESHOT_IMAGES = new Set(['dsh-bot@1', 'dsh-bot-devcheck@1'])
28
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/
29
+
30
+ /** The image name on a computer-plugin machine, or '' when it cannot be read. */
31
+ function imageOf(machine) {
32
+ const image = typeof machine?.agent === 'string' ? machine.agent.trim() : ''
33
+ if (!image || image.length > IMAGE_MAX || CONTROL.test(image)) return ''
34
+ return image
35
+ }
36
+
37
+ function imageFailure(image, message, sandbox) {
38
+ const error = rayrunFailure(ERROR_CODES.imageUnsupported, message)
39
+ if (image) error.image = image
40
+ if (sandbox) error.computer = sandbox
41
+ return error
42
+ }
43
+
44
+ /**
45
+ * Refuse a detached turn that cannot be shown to run a DSH worker.
46
+ * An empty image is refused too: the previous precheck treated that as
47
+ * "unknown" and still called `dsh.start`, which is how a shell-oneshot
48
+ * machine created a task and then failed with no `reply.md`.
49
+ */
50
+ function assertImageSupported(image, sandbox) {
51
+ if (!image) {
52
+ throw imageFailure(
53
+ '',
54
+ `The cloud computer image could not be read, so no detached task was started. A shell-oneshot image (for example dsh-bot@1) does not start a DSH worker; use an image such as ${DETACHED_IMAGE}.`,
55
+ sandbox,
56
+ )
57
+ }
58
+ if (!SHELL_ONESHOT_IMAGES.has(image)) return
59
+ throw imageFailure(
60
+ image,
61
+ `The cloud computer image "${image}" runs a shell oneshot, not a DSH worker; detached turns cannot run. Recreate the computer with an image such as ${DETACHED_IMAGE}.`,
62
+ sandbox,
63
+ )
64
+ }
65
+
66
+ /**
67
+ * Read the image from overview, then from `machine.get` when overview omits it.
68
+ * A previously stored image for this same computer is the last resort, so a
69
+ * later blank overview can still reject a known oneshot without creating a task.
70
+ */
71
+ async function resolveImage(rpc, machine, remembered) {
72
+ const sandbox = String(machine?.name || machine?.id || '')
73
+ let image = imageOf(machine)
74
+ if (image) {
75
+ assertImageSupported(image, sandbox)
76
+ return image
77
+ }
78
+ if (typeof machine?.id === 'string' && machine.id.trim() !== '') {
79
+ try {
80
+ const detail = await rpc.call('machine.get', { id: machine.id })
81
+ image = imageOf(detail?.machine)
82
+ } catch {
83
+ // Overview already proved the computer plugin is reachable. A failed
84
+ // detail read still means the image is unknown, so the turn stops below.
85
+ image = ''
86
+ }
87
+ if (image) {
88
+ assertImageSupported(image, sandbox)
89
+ return image
90
+ }
91
+ }
92
+ const rememberedImage = typeof remembered?.image === 'string' ? remembered.image : ''
93
+ const rememberedComputer = typeof remembered?.computer === 'string' ? remembered.computer : ''
94
+ if (rememberedImage && rememberedComputer && rememberedComputer === sandbox) {
95
+ image = imageOf({ agent: rememberedImage })
96
+ }
97
+ assertImageSupported(image, sandbox)
98
+ return image
99
+ }
25
100
 
26
101
  function resultNames(body) {
27
102
  return Array.isArray(body?.files) && body.files.length ? body.files.join(', ') : 'none'
28
103
  }
29
104
 
105
+ function redactProviderError(value) {
106
+ return String(value ?? '')
107
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+|(sk-)[A-Za-z0-9_-]{16,}/gi, (match, bearer, sk) => (
108
+ bearer ? `${bearer}[redacted]` : `${sk}[redacted]`
109
+ ))
110
+ .slice(0, 500)
111
+ }
112
+
113
+ /**
114
+ * Best-effort read of the worker's DSH session log after a missing reply.md.
115
+ * The provider error is written by the worker session, not by this host; the
116
+ * dependency's exec tool reads it on the machine. Any failure is silent: the
117
+ * original worker-no-reply error remains actionable on its own.
118
+ */
119
+ async function providerErrorHint(getTools, detached) {
120
+ let tool
121
+ try {
122
+ tool = getTools?.()?.get?.('rayrun_exec')
123
+ } catch {
124
+ return ''
125
+ }
126
+ if (typeof tool?.execute !== 'function') return ''
127
+ try {
128
+ const result = await tool.execute({
129
+ sandbox: detached.sandbox,
130
+ command: "grep -R -h -E 'Authentication Fails|MISSING_CREDENTIAL|invalid.*api key|401' /workspace/.rayrun/dsh/sessions 2>/dev/null | tail -n 3",
131
+ timeout_seconds: 30,
132
+ })
133
+ const text = [result?.stdout, result?.stderr].filter(Boolean).join('\n').trim()
134
+ return text ? ` Provider error: ${redactProviderError(text)}` : ''
135
+ } catch {
136
+ return ''
137
+ }
138
+ }
139
+
30
140
  /**
31
141
  * Create the detached adapter. `getOrigin` is lazy because it is only available
32
- * after the DSH web server is injected.
33
- * @param {{ getOrigin?: () => string | undefined, fetchImpl?: Function }} options
142
+ * after the DSH web server is injected. `getTools` is optional and used only to
143
+ * read the worker's provider error after a missing reply.md.
144
+ * @param {{ getOrigin?: () => string | undefined, getTools?: () => object, fetchImpl?: Function }} options
34
145
  */
35
- export function createRayrunDetachedRuntime({ getOrigin, fetchImpl = globalThis.fetch } = {}) {
146
+ export function createRayrunDetachedRuntime({ getOrigin, getTools, fetchImpl = globalThis.fetch } = {}) {
36
147
  const rpc = createRayrunRpc({ getOrigin, fetchImpl })
37
148
 
38
149
  return {
@@ -42,8 +153,15 @@ export function createRayrunDetachedRuntime({ getOrigin, fetchImpl = globalThis.
42
153
  get available() {
43
154
  return Boolean(getOrigin?.())
44
155
  },
45
- async start({ bot, text, history = [], messageSeq, botId, stateRoot } = {}) {
156
+ async start({
157
+ bot, text, history = [], messageSeq, botId, stateRoot,
158
+ rememberedImage, rememberedComputer,
159
+ } = {}) {
46
160
  const machine = await rpc.resolveMachine()
161
+ const image = await resolveImage(rpc, machine, {
162
+ image: rememberedImage,
163
+ computer: rememberedComputer,
164
+ })
47
165
  const localDir = ensureBotWorkspace(stateRoot, botId, { name: bot?.name })
48
166
  const objective = [
49
167
  buildPrompt({ bot, text, history, messageSeq }),
@@ -72,6 +190,7 @@ export function createRayrunDetachedRuntime({ getOrigin, fetchImpl = globalThis.
72
190
  localDir,
73
191
  timeoutSeconds: TASK_TIMEOUT_SECONDS,
74
192
  startedAt: typeof body.started_at === 'string' ? body.started_at : new Date().toISOString(),
193
+ image,
75
194
  }
76
195
  },
77
196
  async status({ detached } = {}) {
@@ -109,9 +228,12 @@ export function createRayrunDetachedRuntime({ getOrigin, fetchImpl = globalThis.
109
228
  try {
110
229
  info = statSync(replyPath)
111
230
  } catch {
231
+ const known = imageOf({ agent: detached?.image })
232
+ const named = known ? ` This computer image is "${known}".` : ''
233
+ const provider = await providerErrorHint(getTools, detached)
112
234
  throw rayrunFailure(
113
- ERROR_CODES.internal,
114
- `The cloud worker did not write reply.md (files: ${resultNames(body)}).`,
235
+ ERROR_CODES.workerNoReply,
236
+ `The cloud worker ended without writing reply.md (files: ${resultNames(body)}).${named} Check the worker session under .rayrun/dsh/sessions/ for the provider error. A missing or invalid DeepSeek credential (MISSING_CREDENTIAL or provider Authentication Fails) prevents the worker from replying; add a valid model credential or recreate the computer with one.${provider}`,
115
237
  )
116
238
  }
117
239
  if (!info.isFile() || info.size > REPLY_MAX_BYTES) {
package/lib/sessions.js CHANGED
@@ -37,6 +37,7 @@ export const SESSION_ORIGINS = Object.freeze(['chat', 'routine'])
37
37
  const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/
38
38
  const DETACHED_TASK = /^[A-Za-z0-9._-]{1,80}$/
39
39
  const DETACHED_TIMEOUT_MAX = 3600
40
+ const IMAGE_MAX = 128
40
41
  /** Credential shapes that must never enter the transcript through an error line. */
41
42
  const SECRET = /(Bearer\s+)[A-Za-z0-9._~+/=-]+|(sk-)[A-Za-z0-9_-]{16,}|((?:RAYRUN_TOKEN|DEEPSEEK_API_KEY|DEEPSEEK_KEY)\s*[=:]\s*)\S+/gi
42
43
 
@@ -88,6 +89,12 @@ function textOf(value, field = 'text') {
88
89
  return result
89
90
  }
90
91
 
92
+ function imageValue(value, field) {
93
+ const image = textOf(value, field)
94
+ if ([...image].length > IMAGE_MAX) fail(`${field} is too long.`, { field })
95
+ return image
96
+ }
97
+
91
98
  function originOf(value, field) {
92
99
  if (value === undefined || value === 'chat') return undefined
93
100
  if (!SESSION_ORIGINS.includes(value)) fail(`${field} is invalid.`, { field })
@@ -139,12 +146,14 @@ function validateDetached(value) {
139
146
  if (!Number.isInteger(value.timeoutSeconds) || value.timeoutSeconds < 1 || value.timeoutSeconds > DETACHED_TIMEOUT_MAX) {
140
147
  fail(`detached.timeoutSeconds must be an integer from 1 through ${DETACHED_TIMEOUT_MAX}.`, { field: 'detached.timeoutSeconds' })
141
148
  }
149
+ const image = value.image === undefined ? undefined : imageValue(value.image, 'detached.image')
142
150
  return {
143
151
  taskId: value.taskId,
144
152
  sandbox,
145
153
  localDir,
146
154
  startedAt: isoOf(value.startedAt, 'detached.startedAt'),
147
155
  timeoutSeconds: value.timeoutSeconds,
156
+ ...(image === undefined ? {} : { image }),
148
157
  }
149
158
  }
150
159
 
@@ -173,6 +182,8 @@ function validateSession(value, botId) {
173
182
  if (typeof value.error.message !== 'string') fail('Session error message is invalid.')
174
183
  }
175
184
  const detached = value.detached === undefined ? undefined : validateDetached(value.detached)
185
+ const computer = value.computer === undefined ? undefined : textOf(value.computer, 'computer')
186
+ const image = value.image === undefined ? undefined : imageValue(value.image, 'image')
176
187
  return {
177
188
  schema: SESSION_SCHEMA_VERSION,
178
189
  botId,
@@ -182,6 +193,8 @@ function validateSession(value, botId) {
182
193
  queue,
183
194
  createdAt,
184
195
  updatedAt,
196
+ ...(computer === undefined ? {} : { computer }),
197
+ ...(image === undefined ? {} : { image }),
185
198
  ...(detached === undefined ? {} : { detached }),
186
199
  ...(value.error === undefined ? {} : { error: { code: value.error.code, message: value.error.message } }),
187
200
  }
@@ -197,6 +210,8 @@ function publicSession(session) {
197
210
  pending: session.queue.length,
198
211
  createdAt: session.createdAt,
199
212
  updatedAt: session.updatedAt,
213
+ ...(session.computer === undefined ? {} : { computer: session.computer }),
214
+ ...(session.image === undefined ? {} : { image: session.image }),
200
215
  ...(session.detached === undefined ? {} : {
201
216
  detached: { taskId: session.detached.taskId, startedAt: session.detached.startedAt },
202
217
  }),
@@ -204,6 +219,34 @@ function publicSession(session) {
204
219
  }
205
220
  }
206
221
 
222
+ function computerField(session) {
223
+ return session.computer === undefined ? {} : { computer: session.computer }
224
+ }
225
+
226
+ function imageField(session) {
227
+ return session.image === undefined ? {} : { image: session.image }
228
+ }
229
+
230
+ /** An image annotation on a failure, or undefined when it is absent or unusable. */
231
+ function notedImage(error) {
232
+ if (typeof error?.image !== 'string') return undefined
233
+ try {
234
+ return imageValue(error.image, 'image')
235
+ } catch {
236
+ return undefined
237
+ }
238
+ }
239
+
240
+ /** A computer name annotation on a failure, or undefined when it is absent or unusable. */
241
+ function notedComputer(error) {
242
+ if (typeof error?.computer !== 'string') return undefined
243
+ try {
244
+ return textOf(error.computer, 'computer')
245
+ } catch {
246
+ return undefined
247
+ }
248
+ }
249
+
207
250
  function readSession(stateRoot, botId) {
208
251
  const file = path.join(stateRoot, 'bots', botId, 'session.json')
209
252
  let text
@@ -392,6 +435,8 @@ export function openSessionStore(stateRoot) {
392
435
  ],
393
436
  createdAt: session.createdAt,
394
437
  updatedAt: at,
438
+ ...computerField(session),
439
+ ...imageField(session),
395
440
  ...(session.detached === undefined ? {} : { detached: session.detached }),
396
441
  }
397
442
  writeSession(root, next)
@@ -413,6 +458,8 @@ export function openSessionStore(stateRoot) {
413
458
  queue: session.queue.slice(1),
414
459
  createdAt: session.createdAt,
415
460
  updatedAt: at,
461
+ ...computerField(session),
462
+ ...imageField(session),
416
463
  }
417
464
  writeSession(root, next)
418
465
  return { session: publicSession(next), item }
@@ -434,6 +481,8 @@ export function openSessionStore(stateRoot) {
434
481
  queue: session.queue,
435
482
  createdAt: session.createdAt,
436
483
  updatedAt: at,
484
+ ...computerField(session),
485
+ ...imageField(session),
437
486
  }
438
487
  writeSession(root, next)
439
488
  return { session: publicSession(next), message }
@@ -448,6 +497,8 @@ export function openSessionStore(stateRoot) {
448
497
  ? error.code
449
498
  : ERROR_CODES.internal
450
499
  const detail = redact(error?.message ?? error) || 'The turn failed.'
500
+ const noted = notedImage(error)
501
+ const computer = notedComputer(error)
451
502
  const message = { seq: session.lastSeq + 1, at, role: 'system', code, text: detail }
452
503
  appendMessage(root, botId, message)
453
504
  const next = {
@@ -459,6 +510,8 @@ export function openSessionStore(stateRoot) {
459
510
  queue: session.queue,
460
511
  createdAt: session.createdAt,
461
512
  updatedAt: at,
513
+ ...(computer === undefined ? computerField(session) : { computer }),
514
+ ...(noted === undefined ? imageField(session) : { image: noted }),
462
515
  error: { code, message: detail },
463
516
  }
464
517
  writeSession(root, next)
@@ -474,6 +527,7 @@ export function openSessionStore(stateRoot) {
474
527
  fail(`session for ${botId} is not running; cannot attach a detached task.`)
475
528
  }
476
529
  const at = isoNow(now)
530
+ const record = validateDetached({ ...detached, startedAt: detached?.startedAt ?? at })
477
531
  const next = {
478
532
  schema: SESSION_SCHEMA_VERSION,
479
533
  botId,
@@ -483,7 +537,9 @@ export function openSessionStore(stateRoot) {
483
537
  queue: session.queue,
484
538
  createdAt: session.createdAt,
485
539
  updatedAt: at,
486
- detached: validateDetached({ ...detached, startedAt: detached?.startedAt ?? at }),
540
+ computer: record.sandbox,
541
+ ...(record.image === undefined ? imageField(session) : { image: record.image }),
542
+ detached: record,
487
543
  }
488
544
  writeSession(root, next)
489
545
  return publicSession(next)
@@ -495,6 +551,16 @@ export function openSessionStore(stateRoot) {
495
551
  return session?.detached ?? null
496
552
  }
497
553
 
554
+ /** The last machine this bot ran on, if known. */
555
+ function computer(id) {
556
+ return load(id)?.computer ?? null
557
+ }
558
+
559
+ /** The last known image for this bot's computer, if one was recorded. */
560
+ function image(id) {
561
+ return load(id)?.image ?? null
562
+ }
563
+
498
564
  /** Sessions whose cloud task must be resumed by this host process. */
499
565
  function detachedSessions() {
500
566
  const botsRoot = path.join(root, 'bots')
@@ -570,6 +636,8 @@ export function openSessionStore(stateRoot) {
570
636
  queue: session.queue,
571
637
  createdAt: session.createdAt,
572
638
  updatedAt: at,
639
+ ...computerField(session),
640
+ ...imageField(session),
573
641
  error: { code: ERROR_CODES.hostDown, message: detail },
574
642
  })
575
643
  } else if (session.state === 'queued' && session.queue.length === 0) {
@@ -582,6 +650,8 @@ export function openSessionStore(stateRoot) {
582
650
  queue: [],
583
651
  createdAt: session.createdAt,
584
652
  updatedAt: new Date().toISOString(),
653
+ ...computerField(session),
654
+ ...imageField(session),
585
655
  })
586
656
  }
587
657
  }
@@ -589,7 +659,7 @@ export function openSessionStore(stateRoot) {
589
659
 
590
660
  return {
591
661
  status, history, enqueue, shift, complete, failTurn, recover,
592
- attach, detached, detachedSessions, finishDetached, failDetached,
662
+ attach, detached, detachedSessions, finishDetached, failDetached, computer, image,
593
663
  }
594
664
  }
595
665
 
@@ -600,15 +670,18 @@ export function openSessionStore(stateRoot) {
600
670
  * runtime fails the send before anything is queued, so the page never gets a
601
671
  * fake reply. A failure after queueing becomes a `failed` session with a
602
672
  * redacted system line; the next send resumes the remaining queue.
603
- * @param {{ stateRoot: string, runtime: object, getBot: (id: string) => object, logger?: object }} options
673
+ * @param {{ stateRoot: string, runtime: object, getBot: (id: string) => object, logger?: object, detachedPollMs?: number }} options
604
674
  */
605
- export function openSessionRunner({ stateRoot, runtime, getBot, logger, detachedPollMs = 3000 } = {}) {
675
+ export const DEFAULT_DETACHED_POLL_MS = 1000
676
+
677
+ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detachedPollMs = DEFAULT_DETACHED_POLL_MS } = {}) {
606
678
  if (typeof getBot !== 'function') throw new TypeError('getBot is required.')
607
679
  const store = openSessionStore(stateRoot)
608
680
  store.recover()
609
681
  const active = new Map()
610
682
  const detachedPolls = new Map()
611
- const pollDelay = Number.isInteger(detachedPollMs) && detachedPollMs > 0 ? detachedPollMs : 3000
683
+ const acceptances = new Map()
684
+ const pollDelay = Number.isInteger(detachedPollMs) && detachedPollMs > 0 ? detachedPollMs : DEFAULT_DETACHED_POLL_MS
612
685
 
613
686
  function detachedCapable() {
614
687
  return runtime.available === true
@@ -618,6 +691,25 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
618
691
  && typeof runtime.collect === 'function'
619
692
  }
620
693
 
694
+ /** Resolve the sender's acceptance promise after the runtime attaches or fails. */
695
+ function settleAcceptance(botId, seq, error) {
696
+ const key = `${botId}:${seq}`
697
+ const pending = acceptances.get(key)
698
+ if (pending) {
699
+ acceptances.delete(key)
700
+ if (error) pending.reject(error)
701
+ else pending.resolve(store.status(botId))
702
+ }
703
+ if (!error) return
704
+ // A failed turn leaves the rest queued, not accepted. Do not leave callers
705
+ // waiting for a later kick that may never come.
706
+ for (const [pendingKey, waiter] of acceptances) {
707
+ if (!pendingKey.startsWith(`${botId}:`)) continue
708
+ acceptances.delete(pendingKey)
709
+ waiter.reject(error)
710
+ }
711
+ }
712
+
621
713
  function kick(botId) {
622
714
  if (detachedPolls.has(botId)) return undefined
623
715
  if (active.has(botId)) return active.get(botId)
@@ -650,6 +742,8 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
650
742
  origin: next.item.origin,
651
743
  botId,
652
744
  stateRoot,
745
+ rememberedImage: store.image(botId),
746
+ rememberedComputer: store.computer(botId),
653
747
  })
654
748
  if (typeof started?.taskId !== 'string' || started.taskId.trim() === ''
655
749
  || typeof started?.sandbox !== 'string' || started.sandbox.trim() === ''
@@ -661,6 +755,7 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
661
755
  }
662
756
  store.attach(botId, started)
663
757
  startDetachedPoll(botId, started.taskId)
758
+ settleAcceptance(botId, next.item.seq, null)
664
759
  return
665
760
  }
666
761
  const reply = await runtime.run({
@@ -678,7 +773,11 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
678
773
  }
679
774
  store.complete(botId, reply.text)
680
775
  } catch (error) {
681
- store.failTurn(botId, error)
776
+ try {
777
+ store.failTurn(botId, error)
778
+ } finally {
779
+ settleAcceptance(botId, next.item.seq, error)
780
+ }
682
781
  return
683
782
  }
684
783
  }
@@ -749,6 +848,8 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
749
848
  record.failures += 1
750
849
  if (error?.code === ERROR_CODES.machineStopped
751
850
  || error?.code === ERROR_CODES.tokenRequired
851
+ || error?.code === ERROR_CODES.imageUnsupported
852
+ || error?.code === ERROR_CODES.workerNoReply
752
853
  || record.failures >= 3) {
753
854
  store.failDetached(botId, taskId, error)
754
855
  stop()
@@ -774,15 +875,50 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
774
875
  for (const item of pending) startDetachedPoll(item.botId, item.detached.taskId)
775
876
  }
776
877
 
777
- function send(botId, text, options = {}) {
878
+ function enqueueTurn(botId, text, options, waitForAcceptance) {
778
879
  if (runtime.available !== true) {
779
880
  const error = new Error('The cloud bot runtime is not wired in this build; no turn was sent.')
780
881
  error.code = ERROR_CODES.runtimeUnavailable
781
882
  throw error
782
883
  }
884
+ const before = store.status(botId)
885
+ const idle = !active.has(botId)
886
+ && !detachedPolls.has(botId)
887
+ && (before === null || (
888
+ before.pending === 0
889
+ && (before.state === 'idle' || before.state === 'failed' || before.state === 'interrupted')
890
+ ))
783
891
  const result = store.enqueue(botId, text, options)
784
- kick(botId)
785
- return result
892
+ let accepted
893
+ if (waitForAcceptance && detachedCapable() && idle) {
894
+ accepted = new Promise((resolve, reject) => {
895
+ acceptances.set(`${botId}:${result.message.seq}`, { resolve, reject })
896
+ })
897
+ }
898
+ try {
899
+ kick(botId)
900
+ } catch (error) {
901
+ settleAcceptance(botId, result.message.seq, error)
902
+ throw error
903
+ }
904
+ return { result, accepted }
905
+ }
906
+
907
+ /** Queue one turn without waiting; used by routines and the scheduler. */
908
+ function send(botId, text, options = {}) {
909
+ return enqueueTurn(botId, text, options, false).result
910
+ }
911
+
912
+ /**
913
+ * Queue one turn and, when the bot is idle, resolve only after a detached
914
+ * runtime has attached the cloud task. Callers can treat that as the point
915
+ * after which closing the page/laptop no longer loses the turn.
916
+ */
917
+ async function sendAccepted(botId, text, options = {}) {
918
+ const { result, accepted } = enqueueTurn(botId, text, options, true)
919
+ if (accepted === undefined) return result
920
+ const session = await accepted
921
+ return { session, message: result.message }
786
922
  }
787
923
 
788
924
  async function settled(botId) {
@@ -814,8 +950,10 @@ export function openSessionRunner({ stateRoot, runtime, getBot, logger, detached
814
950
 
815
951
  return {
816
952
  send,
953
+ sendAccepted,
817
954
  status: (botId) => store.status(botId),
818
955
  history: (botId, options) => store.history(botId, options),
956
+ computer: (botId) => store.computer(botId),
819
957
  settled,
820
958
  close,
821
959
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Read-only update check used by the Settings page.
3
+ *
4
+ * This module only reads the public npm dist-tags document for this package.
5
+ * It does not download, install, modify the profile or touch a credential. The
6
+ * page calls it explicitly through the same-origin host RPC; no background
7
+ * polling and no telemetry.
8
+ */
9
+ import { Buffer } from 'node:buffer'
10
+
11
+ export const UPDATE_PACKAGE = 'dsh-rayrun-bots'
12
+ export const UPDATE_REGISTRY = 'https://registry.npmjs.org'
13
+ const MAX_RESPONSE_BYTES = 64 * 1024
14
+ const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
15
+
16
+ const parseVersion = (value) => {
17
+ const match = VERSION.exec(String(value ?? ''))
18
+ if (!match) return null
19
+ return {
20
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
21
+ pre: match[4] === undefined ? [] : match[4].split('.'),
22
+ }
23
+ }
24
+
25
+ function comparePre(left, right) {
26
+ if (left.length === 0 && right.length === 0) return 0
27
+ if (left.length === 0) return 1
28
+ if (right.length === 0) return -1
29
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
30
+ if (index >= left.length) return -1
31
+ if (index >= right.length) return 1
32
+ const a = left[index]
33
+ const b = right[index]
34
+ const aNumeric = /^\d+$/.test(a)
35
+ const bNumeric = /^\d+$/.test(b)
36
+ if (aNumeric && bNumeric) {
37
+ const diff = Number(a) - Number(b)
38
+ if (diff !== 0) return diff < 0 ? -1 : 1
39
+ } else if (aNumeric) {
40
+ return -1
41
+ } else if (bNumeric) {
42
+ return 1
43
+ } else if (a !== b) {
44
+ return a < b ? -1 : 1
45
+ }
46
+ }
47
+ return 0
48
+ }
49
+
50
+ /** Compare two semver strings; returns -1, 0 or 1. */
51
+ export function compareVersions(left, right) {
52
+ const a = parseVersion(left)
53
+ const b = parseVersion(right)
54
+ if (a === null || b === null) throw new Error('compareVersions needs two semver strings.')
55
+ for (let index = 0; index < 3; index += 1) {
56
+ if (a.core[index] !== b.core[index]) return a.core[index] < b.core[index] ? -1 : 1
57
+ }
58
+ return comparePre(a.pre, b.pre)
59
+ }
60
+
61
+ /** Build the copyable update command. It is never executed by the plugin. */
62
+ export function updateCommand({ latest } = {}) {
63
+ if (parseVersion(latest) === null) throw new Error('A valid update version is required.')
64
+ return `npm_config_registry=${UPDATE_REGISTRY} dsh plugin --profile web add ${UPDATE_PACKAGE}@${latest}`
65
+ }
66
+
67
+ /**
68
+ * Read npm dist-tags and compare the channel that matches this build.
69
+ *
70
+ * @param {{ current: string, fetchImpl?: typeof fetch, registry?: string, timeoutMs?: number }} options
71
+ */
72
+ export async function checkForUpdate({
73
+ current,
74
+ fetchImpl = globalThis.fetch,
75
+ registry = UPDATE_REGISTRY,
76
+ timeoutMs = 8000,
77
+ } = {}) {
78
+ if (typeof current !== 'string' || parseVersion(current) === null) {
79
+ throw new Error('The current version is not valid semver.')
80
+ }
81
+ if (typeof fetchImpl !== 'function') throw new Error('No fetch implementation is available.')
82
+ const channel = current.includes('-') ? 'alpha' : 'latest'
83
+ const url = `${registry}/-/package/${encodeURIComponent(UPDATE_PACKAGE)}/dist-tags`
84
+ const response = await fetchImpl(url, {
85
+ headers: { accept: 'application/json' },
86
+ redirect: 'error',
87
+ signal: AbortSignal.timeout(timeoutMs),
88
+ })
89
+ if (!response?.ok) {
90
+ throw new Error(`npm returned HTTP ${Number(response?.status) || 0}.`)
91
+ }
92
+ const text = await response.text()
93
+ if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) {
94
+ throw new Error('npm returned an oversized dist-tags response.')
95
+ }
96
+ let tags
97
+ try {
98
+ tags = JSON.parse(text)
99
+ } catch {
100
+ throw new Error('npm returned invalid JSON.')
101
+ }
102
+ if (typeof tags !== 'object' || tags === null || Array.isArray(tags)) {
103
+ throw new Error('npm returned an invalid dist-tags document.')
104
+ }
105
+ const tagged = tags[channel]
106
+ if (parseVersion(tagged) === null) {
107
+ return { current, channel, latest: null, updateAvailable: false }
108
+ }
109
+ return {
110
+ current,
111
+ channel,
112
+ latest: tagged,
113
+ updateAvailable: compareVersions(tagged, current) > 0,
114
+ }
115
+ }
116
+
117
+ export { parseVersion }