@xiangyixie/dsh-superagent 0.14.1 → 0.14.3

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/console.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * @module dsh-superagent/console
11
11
  */
12
12
  import { randomBytes } from 'node:crypto'
13
+ import { readFileSync } from 'node:fs'
13
14
  import fsp from 'node:fs/promises'
14
15
  import { createServer } from 'node:http'
15
16
  import path from 'node:path'
@@ -24,6 +25,10 @@ import {
24
25
  } from './workbench.js'
25
26
 
26
27
  const DISCOVERY_FILE = 'console.json'
28
+ // The conversation the page was last showing is the only thing the console has
29
+ // to remember across a host restart: messages and runs are both durable on the
30
+ // host side, but neither can be found again without this id.
31
+ const TIMELINE_FILE = 'console-timeline.json'
27
32
  const MAX_CLIENTS = 16
28
33
  const MAX_TEXT = 20_000
29
34
  const MAX_FRAME_BYTES = 512 * 1024
@@ -32,8 +37,49 @@ const MAX_RECORDS = 400
32
37
  const MAX_RECORD_BYTES = 1024 * 1024
33
38
  const HEARTBEAT_MS = 15_000
34
39
  const RUN_POLL_MS = 1_200
40
+ // A short delay keeps a streamed turn from rewriting the timeline per token.
41
+ const TIMELINE_SAVE_MS = 400
42
+ // The remembered transcript is a lean window on disk, not a second log: keep the
43
+ // most recent turns only, and let the host's runs and artifacts carry the rest.
44
+ const TIMELINE_MAX_RECORDS = 120
45
+ const TIMELINE_MAX_BYTES = 160 * 1024
35
46
  const REQUEST_TIMEOUT_MS = 30_000
47
+ const APPROVAL_TIMEOUT_MS = 10 * 60 * 1000
36
48
  const ROUTE_HINT = 'GET / serves the console; the JSON API is under /api/console.'
49
+ const MAX_ARTIFACT_BYTES = 2 * 1024 * 1024
50
+
51
+ /** Types the console may preview inline; anything else is refused, not sniffed. */
52
+ const ARTIFACT_TYPES = new Map([
53
+ ['.html', 'text/html; charset=utf-8'],
54
+ ['.htm', 'text/html; charset=utf-8'],
55
+ ['.md', 'text/markdown; charset=utf-8'],
56
+ ['.txt', 'text/plain; charset=utf-8'],
57
+ ['.log', 'text/plain; charset=utf-8'],
58
+ ['.csv', 'text/plain; charset=utf-8'],
59
+ ['.tsv', 'text/plain; charset=utf-8'],
60
+ ['.json', 'application/json; charset=utf-8'],
61
+ ['.yml', 'text/plain; charset=utf-8'],
62
+ ['.yaml', 'text/plain; charset=utf-8'],
63
+ ['.py', 'text/plain; charset=utf-8'],
64
+ ['.js', 'text/plain; charset=utf-8'],
65
+ ['.mjs', 'text/plain; charset=utf-8'],
66
+ ['.css', 'text/plain; charset=utf-8'],
67
+ ['.svg', 'image/svg+xml'],
68
+ ['.png', 'image/png'],
69
+ ['.jpg', 'image/jpeg'],
70
+ ['.jpeg', 'image/jpeg'],
71
+ ['.gif', 'image/gif'],
72
+ ['.webp', 'image/webp'],
73
+ ['.pdf', 'application/pdf'],
74
+ ])
75
+
76
+ /**
77
+ * An artifact page runs with an opaque origin so its scripts cannot reach the
78
+ * console's token or storage, while still rendering its own styles and CDNs.
79
+ */
80
+ const ARTIFACT_PAGE_CSP = "sandbox allow-scripts allow-popups allow-forms; default-src 'none'; "
81
+ + "script-src 'unsafe-inline' 'unsafe-eval' https:; style-src 'unsafe-inline' https:; "
82
+ + "img-src data: https:; font-src data: https:; connect-src https:; media-src https: data:"
37
83
 
38
84
  /** @param {unknown} value @returns {string} */
39
85
  function messageOf(value) {
@@ -107,15 +153,25 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
107
153
  const token = randomBytes(32).toString('base64url')
108
154
  const instanceId = randomBytes(6).toString('hex')
109
155
  const discoveryPath = path.join(stateRoot, DISCOVERY_FILE)
156
+ const timelinePath = path.join(stateRoot, TIMELINE_FILE)
110
157
  const startedAt = new Date().toISOString()
111
158
  const clients = new Set()
159
+ // Approval questions raised inside this conversation wait here until the open
160
+ // page answers them. Nothing resolves on its own: a page that never answers
161
+ // fails closed to `cancelled`, and no path grants a call without a decision.
162
+ const approvals = new Map()
112
163
  let boundPort = null
113
164
  let server = null
114
165
  let page = null
115
166
  let starting = null
116
167
  let closing = null
117
168
  let stopRequested = false
118
- let currentSessionId = null
169
+ const timeline = readTimeline()
170
+ let currentSessionId = timeline.sessionId
171
+ // Only a remembered conversation is forgotten on failure: a fresh one that
172
+ // cannot stream should stay, so the next message resumes it instead of
173
+ // silently starting another.
174
+ let rememberedSessionId = currentSessionId
119
175
  let unsubscribe = null
120
176
  let runTimer = null
121
177
  let lastRuns = null
@@ -135,6 +191,21 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
135
191
  bytes: 0,
136
192
  seen: new Set(),
137
193
  }
194
+ let timelineTimer = null
195
+ let timelineOversized = false
196
+ if (currentSessionId) {
197
+ // Seeding before any client attaches is what makes the first opening after
198
+ // a restart carry the same words the last one did. The store belongs to the
199
+ // remembered conversation even when it had no transcript yet.
200
+ store.sessionId = currentSessionId
201
+ if (timeline.records.length > 0) mergeRecords(timeline.records)
202
+ // A file written by an older build can exceed the bound this one enforces.
203
+ // Rewrite it once at startup so the "bounded timeline" claim holds on disk,
204
+ // not only for writes that follow a new turn.
205
+ timelineOversized = store.dropped > 0
206
+ || timeline.records.length > TIMELINE_MAX_RECORDS
207
+ || timeline.records.reduce((sum, record) => sum + Buffer.byteLength(JSON.stringify(record)), 0) > TIMELINE_MAX_BYTES
208
+ }
138
209
 
139
210
  const url = () => `http://127.0.0.1:${boundPort}`
140
211
  const allowedHosts = () => new Set([
@@ -156,6 +227,93 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
156
227
  }
157
228
  }
158
229
 
230
+ /**
231
+ * The conversation the page last showed, read back after a restart so the
232
+ * console reopens the same conversation instead of an empty one. The host
233
+ * keeps runs and messages durable, but its follow opening does not replay the
234
+ * messages after a restart, so the transcript window travels here too. A
235
+ * missing or damaged file is simply "nothing remembered" — history is never
236
+ * invented.
237
+ *
238
+ * @returns {{sessionId: string|null, records: Array<object>}} what to reopen.
239
+ */
240
+ function readTimeline() {
241
+ try {
242
+ const parsed = JSON.parse(readFileSync(timelinePath, 'utf8'))
243
+ const sessionId = typeof parsed?.sessionId === 'string' && parsed.sessionId ? parsed.sessionId : null
244
+ const records = Array.isArray(parsed?.records) ? parsed.records : []
245
+ return { sessionId, records: sessionId ? records : [] }
246
+ } catch (error) {
247
+ if (error?.code !== 'ENOENT') log(`console: cannot read ${timelinePath}: ${messageOf(error)}`)
248
+ return { sessionId: null, records: [] }
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Remember the session the page shows and the transcript it shows there. The
254
+ * write is debounced and bounded; a failure is logged, never fatal.
255
+ *
256
+ * @param {boolean} [immediate] - write now instead of on the next tick.
257
+ * @returns {Promise<void>|undefined} the write when immediate, so a stop can wait.
258
+ */
259
+ function saveTimeline(immediate = false) {
260
+ if (timelineTimer && immediate) {
261
+ clearTimeout(timelineTimer)
262
+ timelineTimer = null
263
+ }
264
+ if (!immediate) {
265
+ if (timelineTimer) return
266
+ timelineTimer = setTimeout(() => {
267
+ timelineTimer = null
268
+ saveTimeline(true)
269
+ }, TIMELINE_SAVE_MS)
270
+ timelineTimer.unref?.()
271
+ return
272
+ }
273
+ const tidied = []
274
+ let bytes = 0
275
+ const owned = !store.sessionId || store.sessionId === currentSessionId
276
+ for (let index = owned ? store.entries.length - 1 : -1; index >= 0; index -= 1) {
277
+ const record = store.entries[index].record
278
+ const size = Buffer.byteLength(JSON.stringify(record))
279
+ if (tidied.length >= TIMELINE_MAX_RECORDS || bytes + size > TIMELINE_MAX_BYTES) break
280
+ tidied.unshift(record)
281
+ bytes += size
282
+ }
283
+ const body = `${JSON.stringify({
284
+ version: 1,
285
+ sessionId: currentSessionId,
286
+ savedAt: new Date().toISOString(),
287
+ records: tidied,
288
+ })}\n`
289
+ const tmp = `${timelinePath}.${process.pid}.tmp`
290
+ return fsp.writeFile(tmp, body, 'utf8')
291
+ .then(() => replaceTimeline(tmp))
292
+ .catch(error => log(`console: cannot save ${timelinePath}: ${messageOf(error)}`))
293
+ }
294
+
295
+ /**
296
+ * Swap the finished timeline file into place. Windows refuses the rename
297
+ * while another handle still holds the target open, so a plain rename turns
298
+ * an ordinary concurrent read into a lost-history write. Retrying briefly is
299
+ * the whole fix; a real filesystem error still surfaces to the caller.
300
+ *
301
+ * @param {string} tmp - fully written temporary file beside the target.
302
+ * @returns {Promise<void>} resolves once the target holds the new bytes.
303
+ */
304
+ async function replaceTimeline(tmp) {
305
+ for (let attempt = 0; ; attempt += 1) {
306
+ try {
307
+ await fsp.rename(tmp, timelinePath)
308
+ return
309
+ } catch (error) {
310
+ const transient = error?.code === 'EPERM' || error?.code === 'EACCES' || error?.code === 'EBUSY'
311
+ if (!transient || attempt >= 4) throw error
312
+ await new Promise(resolve => setTimeout(resolve, 20 * (attempt + 1)))
313
+ }
314
+ }
315
+ }
316
+
159
317
  function authorize(req, { allowQuery = false } = {}) {
160
318
  if (!boundPort) {
161
319
  throw new WorkbenchError(503, 'the console is not listening yet', { id: 'not-ready' })
@@ -216,6 +374,56 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
216
374
  return withSeq
217
375
  }
218
376
 
377
+ /**
378
+ * Put one host approval question to the open page and wait for its answer.
379
+ * No client, a closed stream, or a timeout all fail closed to `cancelled`, so
380
+ * a blocked call is never granted without a person deciding it here.
381
+ *
382
+ * @param {object} request - approval question projected for display.
383
+ * @param {string} [request.toolName] - the tool asking for the decision.
384
+ * @param {string|null} [request.callId] - the exact tool call, when known.
385
+ * @param {string|null} [request.reason] - the asker's own explanation.
386
+ * @param {object|null} [request.displayReason] - localized copy of it.
387
+ * @param {string|null} [request.agentId] - agent that asked, for mapping to a lane.
388
+ * @param {string|null} [request.source] - short human label for that agent.
389
+ * @param {string|null} [request.callArguments] - the blocked call's raw arguments, so the page can name the path.
390
+ * @returns {Promise<'allowed-once'|'rejected'|'cancelled'>} the decision.
391
+ */
392
+ function askApproval(request = {}) {
393
+ if (clients.size === 0) return Promise.resolve('cancelled')
394
+ const id = `ap_${randomBytes(6).toString('hex')}`
395
+ const payload = {
396
+ id,
397
+ toolName: typeof request.toolName === 'string' && request.toolName ? request.toolName : 'tool',
398
+ callId: request.callId ?? null,
399
+ callArguments: typeof request.callArguments === 'string' ? request.callArguments.slice(0, 4000) : null,
400
+ reason: typeof request.reason === 'string' ? request.reason : null,
401
+ displayReason: request.displayReason && typeof request.displayReason === 'object'
402
+ ? request.displayReason
403
+ : null,
404
+ agentId: request.agentId ?? null,
405
+ source: request.source ?? null,
406
+ askedAt: new Date().toISOString(),
407
+ }
408
+ return new Promise(resolve => {
409
+ const settle = outcome => {
410
+ const pending = approvals.get(id)
411
+ if (!pending) return
412
+ approvals.delete(id)
413
+ if (pending.timer) clearTimeout(pending.timer)
414
+ resolve(outcome)
415
+ }
416
+ const timer = setTimeout(() => {
417
+ if (!approvals.has(id)) return
418
+ settle('cancelled')
419
+ broadcast({ type: 'approval', action: 'expired', id })
420
+ }, APPROVAL_TIMEOUT_MS)
421
+ timer.unref?.()
422
+ approvals.set(id, { payload, timer, settle })
423
+ broadcast({ type: 'approval', action: 'asked', approval: payload })
424
+ })
425
+ }
426
+
219
427
  function resetStore(sessionId = null) {
220
428
  store.sessionId = sessionId
221
429
  store.header = null
@@ -321,6 +529,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
321
529
  if (frame.type === 'stream.snapshot') {
322
530
  if (frame.header) store.header = frame.header
323
531
  const added = mergeRecords(frame.records)
532
+ if (added > 0) saveTimeline()
324
533
  // Forward the opening only when it carried records we did not hold.
325
534
  // Replaying the host's post-turn snapshot (usually just the setup
326
535
  // records) would make the page clear the history it already has.
@@ -331,12 +540,18 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
331
540
  return
332
541
  }
333
542
  if (frame.type === 'session.event' && frame.event) {
334
- mergeRecords([{ type: 'event', event: frame.event }])
543
+ if (mergeRecords([{ type: 'event', event: frame.event }]) > 0) saveTimeline()
335
544
  }
336
545
  broadcast(frame)
337
546
  })
338
547
  } catch (error) {
339
548
  log(`console: cannot subscribe to conversation ${sessionId}: ${messageOf(error)}`)
549
+ if (rememberedSessionId && rememberedSessionId === sessionId) {
550
+ rememberedSessionId = null
551
+ currentSessionId = null
552
+ resetStore(null)
553
+ saveTimeline(true)
554
+ }
340
555
  broadcast({
341
556
  type: 'error',
342
557
  code: 'stream-unavailable',
@@ -374,6 +589,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
374
589
  detach()
375
590
  currentSessionId = sessionId
376
591
  resetStore(sessionId)
592
+ saveTimeline(true)
377
593
  // The follow stream opens with a snapshot, so it starts when the first
378
594
  // browser subscribes rather than when the session is created. Otherwise
379
595
  // the snapshot is written to nobody.
@@ -397,6 +613,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
397
613
  capabilities: caps,
398
614
  sessionId: currentSessionId,
399
615
  runs: currentSessionId ? lastRuns ?? [] : [],
616
+ approvals: [...approvals.values()].map(entry => entry.payload),
400
617
  }
401
618
  }
402
619
 
@@ -466,6 +683,63 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
466
683
  res.on('error', cleanup)
467
684
  }
468
685
 
686
+ /**
687
+ * Serve one file that a run report names. The report is the allowlist: a
688
+ * token holder cannot read an arbitrary path unless the agent already wrote
689
+ * that path into a report for this conversation.
690
+ *
691
+ * @param {object} parsed - request URL.
692
+ * @param {import('node:http').ServerResponse} res - response sink.
693
+ */
694
+ async function serveArtifact(parsed, res) {
695
+ const sessionId = currentSessionId
696
+ if (!sessionId) throw new WorkbenchError(409, 'there is no conversation yet', { id: 'no-session' })
697
+ const raw = (parsed.searchParams.get('path') || '').trim()
698
+ if (!raw) throw new WorkbenchError(400, 'path is required', { id: 'missing-path' })
699
+ const target = path.resolve(raw)
700
+ const runId = (parsed.searchParams.get('runId') || '').trim()
701
+ let reports = []
702
+ if (runId && typeof host.readRun === 'function') {
703
+ const run = await host.readRun(sessionId, runId)
704
+ reports = typeof run?.report === 'string' ? [run.report] : []
705
+ } else if (typeof host.listRuns === 'function') {
706
+ const rows = await host.listRuns(sessionId)
707
+ reports = (Array.isArray(rows) ? rows : [])
708
+ .map(run => run?.report)
709
+ .filter(report => typeof report === 'string')
710
+ }
711
+ const variants = [raw, target, target.replace(/\\/g, '/'), target.replace(/\//g, '\\')]
712
+ const listed = reports.some(report => variants.some(value => value && report.includes(value)))
713
+ if (!listed) {
714
+ throw new WorkbenchError(403, 'this path is not named in any run report', {
715
+ id: 'artifact-not-listed',
716
+ hint: 'only files a run reported can be previewed here; copy the path and open it in your editor instead.',
717
+ })
718
+ }
719
+ const type = ARTIFACT_TYPES.get(path.extname(target).toLowerCase())
720
+ if (!type) {
721
+ throw new WorkbenchError(415, 'this file type is not previewable in the console', { id: 'artifact-type' })
722
+ }
723
+ let stat
724
+ try {
725
+ stat = await fsp.stat(target)
726
+ } catch {
727
+ throw new WorkbenchError(404, 'the run named this file but it is no longer on disk', { id: 'artifact-missing' })
728
+ }
729
+ if (!stat.isFile()) throw new WorkbenchError(404, 'that path is not a file', { id: 'artifact-not-file' })
730
+ if (stat.size > MAX_ARTIFACT_BYTES) {
731
+ throw new WorkbenchError(413, `the file is above the ${MAX_ARTIFACT_BYTES}-byte preview limit`, {
732
+ id: 'artifact-too-large',
733
+ })
734
+ }
735
+ const body = await fsp.readFile(target)
736
+ const headers = {
737
+ 'content-disposition': `inline; filename="${path.basename(target).replace(/["\\]/g, '_')}"`,
738
+ }
739
+ if (type.startsWith('text/html')) headers['content-security-policy'] = ARTIFACT_PAGE_CSP
740
+ sendText(res, 200, body, type, headers)
741
+ }
742
+
469
743
  async function handle(req, res) {
470
744
  try {
471
745
  const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
@@ -475,13 +749,25 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
475
749
  if (pathname === '/' || pathname === '/console' || pathname === '/index.html') {
476
750
  if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
477
751
  authorize(req, { allowQuery: true })
752
+ // The host seats this page in the "超级智能体" main panel, so framing is
753
+ // allowed from loopback origins only — the token still gates the page.
478
754
  sendText(res, 200, page, 'text/html; charset=utf-8', {
479
755
  'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
480
- + "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
756
+ + "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; "
757
+ + "frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:*",
481
758
  })
482
759
  return
483
760
  }
484
761
 
762
+ // A preview opens in its own tab, which cannot carry an Authorization
763
+ // header, so this one route also accepts the console token in the query.
764
+ if (pathname === '/api/console/artifact') {
765
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
766
+ authorize(req, { allowQuery: true })
767
+ await serveArtifact(parsed, res)
768
+ return
769
+ }
770
+
485
771
  authorize(req)
486
772
  const parts = pathname.split('/').filter(Boolean)
487
773
  if (parts[0] !== 'api' || parts[1] !== 'console') {
@@ -582,6 +868,30 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
582
868
  return
583
869
  }
584
870
 
871
+ if (leaf === 'approval' && parts.length === 3) {
872
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
873
+ const body = await readJson(req)
874
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
875
+ const decision = body?.decision === 'allow'
876
+ ? 'allowed-once'
877
+ : body?.decision === 'reject' ? 'rejected' : null
878
+ if (!id) throw new WorkbenchError(400, 'id is required', { id: 'missing-approval-id' })
879
+ if (!decision) {
880
+ throw new WorkbenchError(400, 'decision must be allow or reject', { id: 'bad-approval-decision' })
881
+ }
882
+ const pending = approvals.get(id)
883
+ if (!pending) {
884
+ throw new WorkbenchError(409, 'this approval is no longer waiting for you', {
885
+ id: 'approval-gone',
886
+ hint: 'reload the page: the question expired, or another window already answered it.',
887
+ })
888
+ }
889
+ pending.settle(decision)
890
+ broadcast({ type: 'approval', action: 'decided', id, outcome: decision })
891
+ send(res, 200, { ok: true, data: { id, outcome: decision } })
892
+ return
893
+ }
894
+
585
895
  if (leaf === 'answer' && parts.length === 3) {
586
896
  if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
587
897
  const body = await readJson(req)
@@ -607,6 +917,53 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
607
917
  return
608
918
  }
609
919
 
920
+ if (leaf === 'wizard' && parts.length <= 4) {
921
+ const action = parts[3] ?? 'status'
922
+ const requireHost = name => {
923
+ if (typeof host[name] !== 'function') {
924
+ throw new WorkbenchError(501, `this host does not implement ${name}`, {
925
+ id: 'wizard-unavailable',
926
+ hint: 'update the plugin or open the console from a host that provides the wizard hooks.',
927
+ })
928
+ }
929
+ }
930
+ if (action === 'status') {
931
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
932
+ requireHost('wizardStatus')
933
+ const probe = ['1', 'true'].includes(parsed.searchParams.get('probe') ?? '')
934
+ send(res, 200, {
935
+ ok: true,
936
+ data: await host.wizardStatus({ sessionId: currentSessionId, probe }),
937
+ })
938
+ return
939
+ }
940
+ if (!['preview', 'save', 'rollback', 'trial'].includes(action)) {
941
+ throw new WorkbenchError(404, `no route for ${method} ${pathname}`, { id: 'not-found', hint: ROUTE_HINT })
942
+ }
943
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
944
+ const body = await readJson(req)
945
+ if (action === 'preview') {
946
+ requireHost('wizardPreview')
947
+ send(res, 200, { ok: true, data: await host.wizardPreview(body ?? {}) })
948
+ return
949
+ }
950
+ if (action === 'save') {
951
+ requireHost('wizardSave')
952
+ send(res, 200, { ok: true, data: await host.wizardSave(body ?? {}) })
953
+ return
954
+ }
955
+ if (action === 'rollback') {
956
+ requireHost('wizardRollback')
957
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
958
+ if (!id) throw new WorkbenchError(400, 'id is required', { id: 'missing-backup-id' })
959
+ send(res, 200, { ok: true, data: await host.wizardRollback(id) })
960
+ return
961
+ }
962
+ requireHost('wizardTrial')
963
+ send(res, 200, { ok: true, data: await host.wizardTrial() })
964
+ return
965
+ }
966
+
610
967
  if (leaf === 'runs' && parts.length <= 4) {
611
968
  if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
612
969
  if (!currentSessionId) {
@@ -685,6 +1042,11 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
685
1042
 
686
1043
  return {
687
1044
  discoveryPath,
1045
+ askApproval,
1046
+ /** The conversation this page currently shows; null before one is created. */
1047
+ get sessionId() {
1048
+ return currentSessionId
1049
+ },
688
1050
  get token() {
689
1051
  return token
690
1052
  },
@@ -724,6 +1086,12 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
724
1086
  boundPort = address.port
725
1087
  server = instance
726
1088
  await writeDiscovery()
1089
+ // Warm the run list for a remembered conversation. The host keeps runs
1090
+ // durable, so this is a read; without it `/state` and the first
1091
+ // bootstrap report "no runs" until some page has attached, which reads
1092
+ // as lost history even though the runs are on disk.
1093
+ if (currentSessionId) refreshRuns().catch(() => {})
1094
+ if (timelineOversized) saveTimeline(true)
727
1095
  return { port: boundPort, url: url() }
728
1096
  })()
729
1097
  starting = run
@@ -740,6 +1108,10 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
740
1108
  stopRequested = true
741
1109
  closing = (async () => {
742
1110
  detach()
1111
+ // Flush before forgetting the id: a graceful stop must leave the next
1112
+ // start able to reopen this conversation, not erase it. Await it so a
1113
+ // restart that follows immediately cannot read a half-written file.
1114
+ await saveTimeline(true)
743
1115
  currentSessionId = null
744
1116
  for (const res of clients) {
745
1117
  try {
package/lib/entry.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Package entry point.
3
+ *
4
+ * A plugin is loaded as one module graph. If any file that graph imports is
5
+ * missing, the import throws before `apply` exists, and the host can only say
6
+ * "this plugin did not load" — in the desktop UI that looks like every tool of
7
+ * the plugin vanishing at once, with no reason given.
8
+ *
9
+ * The commonest cause is an incomplete installation: `lib/index.js` was copied
10
+ * but a sibling it imports (`wizard.js`, `board.js`, ...) was not. This file is
11
+ * the only static import of the package, so it can catch that failure and name
12
+ * the file that is missing plus the command that fixes it.
13
+ */
14
+ import path from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+
17
+ const libDir = path.dirname(fileURLToPath(import.meta.url))
18
+
19
+ /**
20
+ * Turn a failed import into the sentence a user needs.
21
+ *
22
+ * @param {unknown} error - thrown by the failed import.
23
+ * @param {string} [dir] - this package's lib directory, for the fix suggestion.
24
+ * @returns {string} one readable explanation.
25
+ */
26
+ export function explainLoadError(error, dir = libDir) {
27
+ const raw = error?.message ?? String(error)
28
+ const match = /Cannot find (module|package) '([^']+)'/.exec(raw)
29
+ if (!match) {
30
+ return `dsh-superagent failed to load: ${raw}. `
31
+ + 'The session keeps its other tools; no dsh-superagent tool exists until this is fixed.'
32
+ }
33
+ const [, kind, specifier] = match
34
+ if (kind === 'package') {
35
+ return `dsh-superagent failed to load because a package it imports is missing: ${specifier}. `
36
+ + `Fix: run npm install in ${path.dirname(dir)}, then restart the host.`
37
+ }
38
+ // Node prints a resolved absolute path for a relative import, but an older
39
+ // runtime may keep the bare specifier; show whichever it gave.
40
+ const file = path.isAbsolute(specifier) || specifier.includes('://')
41
+ ? specifier
42
+ : path.resolve(dir, specifier)
43
+ return `dsh-superagent failed to load because a file it imports is missing: ${file}. `
44
+ + 'This installation is incomplete — usually only lib/index.js was copied. '
45
+ + `Fix: copy every file of the package's lib directory into ${dir} `
46
+ + '(Copy-Item lib\\* -Force on Windows) or reinstall the package, then restart the host. '
47
+ + 'Until then the plugin is skipped and none of its tools appear in any session.'
48
+ }
49
+
50
+ let loaded
51
+ try {
52
+ loaded = await import('./index.js')
53
+ } catch (error) {
54
+ const explanation = explainLoadError(error)
55
+ // The host logs what it catches; the console line is for the terminal that
56
+ // started it. Both carry the same sentence.
57
+ console.error(`[dsh-superagent] ${explanation}`)
58
+ const failure = new Error(explanation, { cause: error })
59
+ failure.code = error?.code
60
+ throw failure
61
+ }
62
+
63
+ export const name = loaded.name
64
+ export const inject = loaded.inject
65
+ export const apply = loaded.apply