dsh-baton-host 0.6.15 → 0.6.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.js +100 -18
  2. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -19,11 +19,15 @@ export const inject = ['sessionController', 'workspaceRegistry']
19
19
 
20
20
  const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
21
21
  const MAX_EVENTS = 200
22
+ const admitWaitMs = () => Number(process.env.DSH_BATON_ADMIT_WAIT_MS) || 10_000
22
23
  const MAX_RUNS = 100
23
24
  const QUIET_CONFIRM_MS = 2000
24
25
  const CANCEL_ATTEMPTS = 3
25
26
  const CANCEL_SETTLE_MS = 6000
26
27
  const ACTIVITY_MAX_ERRORS = 10
28
+ // A run taken up after a plugin reload whose message Harness had not admitted yet.
29
+ const TAKE_UP_RETRY_MS = 3000
30
+ const takeUpAdmitMs = () => Number(process.env.DSH_BATON_TAKE_UP_ADMIT_MS) || 5 * 60_000
27
31
  const MAX_REQUEST_BYTES = 4 * 1024 * 1024
28
32
  const MAX_WAIT_S = 24 * 3600
29
33
  const MAX_HUMAN_INPUTS = 10
@@ -333,8 +337,10 @@ export function apply(ctx) {
333
337
  if (again.size) store.timer = setTimeout(guard('persist runs', flushRuns), PERSIST_DELAY_MS)
334
338
  }
335
339
 
336
- // Load earlier records. A run that was active when Harness went away cannot
337
- // finish any more (Harness ends the turn on restart), so it is marked interrupted.
340
+ // Load earlier records. A run that was active when the plugin went away is taken up again
341
+ // when its session is still at work: the plugin was reloaded (switched off and on, or
342
+ // updated) while Harness kept running. Otherwise it cannot finish any more (Harness ends the
343
+ // turn on restart), so it is marked interrupted.
338
344
  function enableStore() {
339
345
  fs.mkdirSync(store.dir, { recursive: true, mode: 0o700 })
340
346
  if (!IS_WIN) fs.chmodSync(store.dir, 0o700)
@@ -350,15 +356,53 @@ export function apply(ctx) {
350
356
  loaded.sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)))
351
357
  for (const old of loaded.splice(0, Math.max(0, loaded.length - MAX_RUNS))) fs.rmSync(path.join(store.dir, `${old.id}.json`), { force: true })
352
358
  store.enabled = true
359
+ const resumable = []
353
360
  for (const run of loaded) {
354
361
  if (runs.has(run.id)) continue
355
362
  run.events ??= []
356
363
  runs.set(run.id, run)
357
- if (isActive(run)) {
358
- Object.assign(run, { state: 'interrupted', endedAt: new Date().toISOString(), error: 'Harness restarted while this run was active; its turn was stopped.' })
359
- persist(run)
364
+ if (isActive(run)) resumable.push(run)
365
+ }
366
+ for (const run of resumable) guard('take up runs', takeUp)(run)
367
+ }
368
+ async function takeUp(run, tries = 0) {
369
+ const items = run.sessionId ? await sessionActivity(run.sessionId).catch(() => null) : []
370
+ if (!isActive(run)) return
371
+ // A message that reached the conversation while no plugin listened: the run is in it.
372
+ if (!run.sawPrompt && run.sessionId) {
373
+ const log = await sessionLog(run.sessionId).catch(() => null)
374
+ // Ended meanwhile (a late refusal of the prompt, a cancel): left as it is.
375
+ if (!isActive(run)) return
376
+ if (Array.isArray(log?.events) && log.events.some((e) => e.type === 'user/message' && e.data?.source?.rpcId === run.requestId)) {
377
+ Object.assign(run, { sawPrompt: true, state: 'running', admitted: true })
360
378
  }
361
379
  }
380
+ // Unknown is not idle (Harness may not answer yet right after the reload): look again a few
381
+ // times. A message Harness had not taken in yet may still arrive: a cold start took 2 min 35 s
382
+ // to admit one (Mac, 2026-11-18), so that is looked for up to takeUpAdmitMs().
383
+ const notYetIn = !run.admitted && !run.sawPrompt
384
+ const again = items === null ? tries < ACTIVITY_MAX_ERRORS : notYetIn && !items?.length && (tries + 1) * TAKE_UP_RETRY_MS < takeUpAdmitMs()
385
+ if (again) {
386
+ setTimeout(guard('take up runs', () => takeUp(run, tries + 1)), TAKE_UP_RETRY_MS)
387
+ return
388
+ }
389
+ if (Array.isArray(items) && items.length) {
390
+ // Its turn may have ended while no plugin listened: with no turn left, only background
391
+ // work (sub-agents, jobs), the run ends once that is done, as after a seen turn end.
392
+ if (run.sawPrompt && !items.some((g) => g.kind === 'turn')) run.idleSeen = true
393
+ // A question asked through the plugin that went away cannot be answered from here any more
394
+ // (its request belonged to the old plugin): the wait says to answer it in the Harness window.
395
+ if (run.question && !questions.has(run.sessionId)) {
396
+ delete run.question
397
+ if (run.state === 'waiting') run.waitNoticed = false
398
+ }
399
+ pushEvent(run, { type: 'plugin_reloaded' })
400
+ persist(run)
401
+ scheduleQuietCheck(run.sessionId, 1000)
402
+ return
403
+ }
404
+ // settle, so a wait that began since the reload wakes now.
405
+ settle(run, 'interrupted', { error: notYetIn ? 'The plugin reloaded before Harness took the message in, and it never arrived; send it again if it is still wanted.' : 'Harness restarted while this run was active; its turn was stopped.' })
362
406
  }
363
407
 
364
408
  // Per-session turn state: whether the current turn has produced assistant
@@ -745,11 +789,11 @@ export function apply(ctx) {
745
789
  const run = run_id ? getRun(run_id) : null
746
790
  const entry = questions.get(run?.sessionId ?? session_id)
747
791
  if (run && (!isActive(run) || !entry || run.question?.question_id !== entry.id)) {
748
- if (run.state === 'waiting') throw new Error(`Run ${run.id} is waiting for something in the Harness UI (an approval, for example) that cannot be answered from here; tell the user.`)
792
+ if (run.state === 'waiting') throw new Error(`Run ${run.id} is waiting for something in the Harness UI (an approval, or a question left open when the plugin reloaded) that cannot be answered from here; tell the user to answer it in the Harness window.`)
749
793
  throw new Error(`Run ${run.id} is ${run.state} and has no open question to answer.`)
750
794
  }
751
795
  if (!entry) {
752
- if (waitingSessions.has(session_id)) throw new Error(`Session ${session_id} is waiting for something in the Harness UI (an approval, for example) that cannot be answered from here; tell the user.`)
796
+ if (waitingSessions.has(session_id)) throw new Error(`Session ${session_id} is waiting for something in the Harness UI (an approval, or a question left open when the plugin reloaded) that cannot be answered from here; tell the user to answer it in the Harness window.`)
753
797
  throw new Error(`Session ${session_id} has no open question to answer.`)
754
798
  }
755
799
  const shown = run ? publicRun(run, 0) : { session_id }
@@ -761,7 +805,13 @@ export function apply(ctx) {
761
805
  const options = q.options ?? []
762
806
  const chosen = (a.choose ?? []).map((c) => {
763
807
  const byNumber = typeof c === 'number' || /^\d+$/.test(String(c)) ? options[Number(c) - 1] : undefined
764
- const option = byNumber ?? options.find((o) => o.label === c) ?? options.find((o) => o.label.toLowerCase().replace(RECOMMENDED, '').trim() === String(c).toLowerCase().replace(RECOMMENDED, '').trim())
808
+ // Labels compared on letters and digits, the asker's mark left out: "Markdown(.md,推荐)" and "Markdown (.md)" are one option.
809
+ const bareLabel = (v) => String(v).toLowerCase().replace(/\(recommended\)|recommended|推荐/g, '').replace(/[^\p{L}\p{N}]+/gu, '')
810
+ const option = byNumber ?? options.find((o) => o.label === c) ?? options.find((o) => o.label.toLowerCase().replace(RECOMMENDED, '').trim() === String(c).toLowerCase().replace(RECOMMENDED, '').trim()) ?? (bareLabel(c) ? options.find((o) => bareLabel(o.label) === bareLabel(c)) : undefined) ?? (() => {
811
+ // The label's head: "md" for "md (Markdown)", when only one option starts that way.
812
+ const heads = bareLabel(c) ? options.filter((o) => bareLabel(String(o.label).split(/[((]/)[0]) === bareLabel(c)) : []
813
+ return heads.length === 1 ? heads[0] : undefined
814
+ })()
765
815
  if (!option) throw new Error(`Question ${q.id} has no option ${JSON.stringify(c)}; options: ${options.map((o, i) => `${i + 1}. ${o.label}`).join('; ')}`)
766
816
  return option.label
767
817
  })
@@ -864,25 +914,46 @@ export function apply(ctx) {
864
914
  // A session's whole event log and its folder. Harness up to 0.2.1 has sessionController.inspect;
865
915
  // 0.2.2 replaced it with paged history (events): the newest page first, beforeSeq walks back,
866
916
  // throughSeq pins every page to the same cut. The folder then comes from the session list.
917
+ // A log read before (the last few sessions) is kept, so a later read walks back only to the
918
+ // last event it has instead of reading the whole log again (a follow reads it each round). A
919
+ // log that no longer holds that event, or has fewer events, is read whole.
920
+ const logCache = new Map()
867
921
  async function sessionLog(sessionId) {
868
922
  if (typeof controller.inspect === 'function') return controller.inspect(sessionId, signal())
869
923
  if (typeof controller.events !== 'function') throw new Error('This DeepSeek Harness version cannot read a session log.')
924
+ const events = await pagedLog(sessionId, logCache.get(sessionId))
925
+ const { items } = await controller.list({}, signal())
926
+ return { meta: { cwd: items.find((it) => it.sessionId === sessionId)?.cwd ?? null }, events }
927
+ }
928
+ async function pagedLog(sessionId, known) {
870
929
  const address = { kind: 'session', sessionId }
871
930
  const pages = []
872
931
  let throughSeq
873
932
  let beforeSeq
933
+ let joined = false
874
934
  for (;;) {
875
935
  const page = await controller.events({ address, maxMessages: 500, ...(throughSeq === undefined ? {} : { throughSeq }), ...(beforeSeq === undefined ? {} : { beforeSeq }) }, signal())
876
936
  throughSeq ??= page.cursor
877
937
  const events = (page.records ?? []).filter((r) => r?.type === 'event' && r.event).map((r) => r.event)
878
938
  pages.unshift(events)
939
+ if (known && events.length && events[0].seq <= known.lastSeq) { joined = true; break }
879
940
  if (!page.hasMore || !events.length || events[0].seq === beforeSeq) break
880
941
  beforeSeq = events[0].seq
881
942
  }
882
943
  const seen = new Set()
883
- const events = pages.flat().filter((e) => (seen.has(e.seq) ? false : (seen.add(e.seq), true)))
884
- const { items } = await controller.list({}, signal())
885
- return { meta: { cwd: items.find((it) => it.sessionId === sessionId)?.cwd ?? null }, events }
944
+ let events = pages.flat().filter((e) => (seen.has(e.seq) ? false : (seen.add(e.seq), true)))
945
+ if (joined) {
946
+ if (!events.some((e) => e.seq === known.lastSeq)) return pagedLog(sessionId, null)
947
+ events = [...known.events, ...events.filter((e) => e.seq > known.lastSeq)]
948
+ }
949
+ const lastSeq = events.at(-1)?.seq
950
+ logCache.delete(sessionId)
951
+ // Read-only for callers; a very long log is not kept (memory).
952
+ if (Number.isFinite(lastSeq) && events.length <= 50_000 && events.every((e, i) => i === 0 || e.seq > events[i - 1].seq)) {
953
+ logCache.set(sessionId, { events, lastSeq })
954
+ if (logCache.size > 8) logCache.delete(logCache.keys().next().value)
955
+ }
956
+ return events
886
957
  }
887
958
 
888
959
  async function readSession({ session_id, last = 10 }) {
@@ -1665,14 +1736,25 @@ export function apply(ctx) {
1665
1736
  ...(chosen.model ? { model: chosen.model } : {}),
1666
1737
  }
1667
1738
  remember(run)
1668
- try {
1669
- await controller.prompt({ sessionId, requestId: run.requestId, content: [{ type: 'text', text: message }], mode }, signal())
1670
- run.admitted = true // in Harness's queue (or conversation) now
1671
- if (drift) rememberDefault(drift.now)
1672
- } catch (error) {
1673
- settle(run, 'failed', { error: String(error?.message ?? error) })
1674
- }
1739
+ // Harness answers the prompt once it has taken the message in; on a cold start (the first
1740
+ // session after a restart) that took 2 min 35 s, and the client sat in dsh_send all along
1741
+ // (Mac, 2026-11-18). So the reply waits at most admitWaitMs() (10 s); Harness's answer still settles
1742
+ // the run when it comes (a refusal fails it, and dsh_wait says so).
1743
+ const admitted = controller.prompt({ sessionId, requestId: run.requestId, content: [{ type: 'text', text: message }], mode }, signal())
1744
+ .then(() => {
1745
+ run.admitted = true // in Harness's queue (or conversation) now
1746
+ if (drift) rememberDefault(drift.now)
1747
+ return true
1748
+ }, (error) => {
1749
+ settle(run, 'failed', { error: String(error?.message ?? error) })
1750
+ return true
1751
+ })
1752
+ let timer
1753
+ const answered = await Promise.race([admitted, new Promise((r) => { timer = setTimeout(() => r(false), admitWaitMs()) })])
1754
+ clearTimeout(timer)
1755
+ if (!answered) pushEvent(run, { type: 'admission_pending' })
1675
1756
  return {
1757
+ ...(answered ? {} : { admission_pending: true }),
1676
1758
  ...publicRun(run),
1677
1759
  mode,
1678
1760
  mode_source: modeSource,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-baton-host",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
4
4
  "description": "Hand coding tasks from Claude Code, Codex or Antigravity to DeepSeek Harness: they run live in the Harness window and come back with the changed files and test results. 让 Claude Code、Codex 和 Antigravity 把编码任务交给 DeepSeek Harness:在 Harness 窗口里实时跑,做完带着改动文件和测试结果交回。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -24,7 +24,7 @@
24
24
  "docs"
25
25
  ],
26
26
  "dependencies": {
27
- "dsh-baton-mcp": "0.6.15"
27
+ "dsh-baton-mcp": "0.6.17"
28
28
  },
29
29
  "license": "MIT",
30
30
  "dsh": {