dsh-baton-host 0.6.13 → 0.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -56,6 +56,57 @@ function normalizePath(p) {
56
56
  try { return fs.realpathSync.native(abs) } catch { return abs }
57
57
  }
58
58
 
59
+ // Where a new session goes. Harness keeps every session of a workspace in the workspace's own
60
+ // folder, so a hand-over to a folder that is not a workspace would get a workspace of its own,
61
+ // one more in the sidebar for each subfolder or throw-away folder. Instead it joins:
62
+ // - the conversation's own folder (base), when the target is inside it: a Claude Code chat in
63
+ // Coding handing over Coding/app joins the Coding workspace;
64
+ // - for folders clients make per conversation, one shared folder: Codex chats without a project
65
+ // (Documents/Codex/<date>/<chat>), Claude scratch folders (…/scratch-workspaces/…), Claude
66
+ // worktrees (<project>/.claude/worktrees/<name>, joined to the project) and Codex worktrees
67
+ // (~/.codex/worktrees/…).
68
+ // The session then starts in that folder and the message names the target folder.
69
+ const CASELESS = process.platform === 'win32' || process.platform === 'darwin'
70
+ const same = (a, b) => (CASELESS ? a.toLowerCase() === b.toLowerCase() : a === b)
71
+ function isInside(dir, parent) {
72
+ const r = path.relative(CASELESS ? parent.toLowerCase() : parent, CASELESS ? dir.toLowerCase() : dir)
73
+ return r !== '' && !r.startsWith('..') && !path.isAbsolute(r)
74
+ }
75
+ const DAY = /^\d{4}-\d{2}-\d{2}$/
76
+ function sharedFolder(dir) {
77
+ const parts = dir.split(path.sep)
78
+ const upto = (i) => parts.slice(0, i).join(path.sep) || path.sep
79
+ for (let i = parts.length - 2; i >= 1; i--) {
80
+ const at = parts[i]
81
+ // Claude Code worktrees share the folder that holds them, never the project's main checkout.
82
+ if (same(at, 'worktrees') && i >= 2 && same(parts[i - 1], '.claude')) return { path: upto(i + 1), title: 'Claude worktrees' }
83
+ if (same(at, 'worktrees') && same(parts[i - 1], '.codex')) return { path: upto(i + 1), title: 'Codex worktrees' }
84
+ if (same(at, 'scratch-workspaces')) return { path: upto(i + 1), title: 'Claude scratch' }
85
+ if (same(at, 'Codex') && same(parts[i - 1], 'Documents') && DAY.test(parts[i + 1] ?? '')) return { path: upto(i + 1), title: 'Codex chats' }
86
+ }
87
+ return null
88
+ }
89
+ // A Git worktree (its .git is a file pointing into another repository's worktrees): a checkout
90
+ // of its own, so a session for it must not open in the folder around it, which may be the main checkout.
91
+ function isLinkedWorktree(dir) {
92
+ try {
93
+ const text = fs.readFileSync(path.join(dir, '.git'), 'utf8')
94
+ return text.startsWith('gitdir:') && /[\\/]worktrees[\\/]/.test(text)
95
+ } catch { return false }
96
+ }
97
+ function sessionHome(target, base) {
98
+ const usable = (dir) => dir && !same(dir, os.homedir()) && dir !== path.parse(dir).root && isDirectory(dir)
99
+ if (base && !isLinkedWorktree(target)) {
100
+ let b = normalizePath(base)
101
+ const shared = sharedFolder(b)
102
+ if (shared && isDirectory(shared.path)) b = shared.path
103
+ if (usable(b) && isInside(target, b)) return { path: b, ...(shared && same(b, shared.path) && shared.title ? { title: shared.title } : {}) }
104
+ }
105
+ const shared = sharedFolder(target)
106
+ if (shared && usable(shared.path)) return shared
107
+ return { path: target }
108
+ }
109
+
59
110
  // Prepare the socket path without touching anything that is not ours: only our
60
111
  // own directory gets 0700, only a stale socket is removed, and a live host that
61
112
  // already answers there is left alone.
@@ -180,6 +231,7 @@ export function apply(ctx) {
180
231
  ...(run.waitingOn ? { waiting_on: run.waitingOn } : {}),
181
232
  ...(run.supersededBy ? { superseded_by: run.supersededBy } : {}),
182
233
  ...(run.humanInputs?.length ? { human_interjections: run.humanInputs } : {}),
234
+ ...(run.approvalsAllowed?.length ? { approvals_allowed: run.approvalsAllowed } : {}),
183
235
  ...(run.question ? { question: run.question } : {}),
184
236
  ...(tail ? { recent_events: run.events.slice(-tail) } : {}),
185
237
  })
@@ -258,17 +310,27 @@ export function apply(ctx) {
258
310
  fs.renameSync(tmp, file)
259
311
  }
260
312
 
313
+ // A write refused for a moment (Windows: an antivirus holding the file) is tried again a few
314
+ // times: a record left saying "running" would come back as interrupted after a restart.
315
+ const writeTries = new Map()
261
316
  function flushRuns() {
262
317
  clearTimeout(store.timer)
263
318
  store.timer = null
319
+ const again = new Set()
264
320
  for (const id of store.dirty) {
265
321
  const run = runs.get(id)
266
322
  try {
267
323
  if (run) writeRunFile(run)
268
324
  else fs.rmSync(path.join(store.dir, `${id}.json`), { force: true })
269
- } catch (error) { logError('persist run', error) }
325
+ writeTries.delete(id)
326
+ } catch (error) {
327
+ logError('persist run', error)
328
+ const tries = (writeTries.get(id) ?? 0) + 1
329
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) && tries < 5) { writeTries.set(id, tries); again.add(id) } else writeTries.delete(id)
330
+ }
270
331
  }
271
- store.dirty.clear()
332
+ store.dirty = again
333
+ if (again.size) store.timer = setTimeout(guard('persist runs', flushRuns), PERSIST_DELAY_MS)
272
334
  }
273
335
 
274
336
  // Load earlier records. A run that was active when Harness went away cannot
@@ -304,9 +366,45 @@ export function apply(ctx) {
304
366
  // followup, or someone typing in the Harness UI); one after it is a steer.
305
367
  const turns = new Map() // sessionId -> { hasOutput }
306
368
 
369
+ // An approval asked inside a tool call (the run_code of Harness's PTC mode, for one) leaves the
370
+ // agent "running", so its status never says "waiting". The session log's approval/asked and
371
+ // approval/decided pair does: the run waits for the Harness UI from the first open approval
372
+ // to the last decision.
373
+ const openApprovals = new Map() // sessionId -> Map(approval id -> whether it waits for a person)
374
+ let approvalSeq = 0
375
+ const personApproval = (sessionId) => [...(openApprovals.get(sessionId)?.values() ?? [])].some(Boolean)
376
+ // What Harness's Auto review puts in the approval it asks for after turning a call down.
377
+ const AUTO_REVIEW_DENIAL = /^Auto review denied tool/
378
+ function onApproval(sessionId, type, data) {
379
+ const open = openApprovals.get(sessionId) ?? new Map()
380
+ if (type === 'approval/asked') {
381
+ // One this plugin answers itself (onApprovalRequest) is decided at once: no person to wait for.
382
+ const forPerson = !(approvalsMode() === 'allow' && outputReceiversFor(sessionId).length && !AUTO_REVIEW_DENIAL.test(String(data.reason ?? '')))
383
+ open.set(data.id ?? `asked-${++approvalSeq}`, forPerson)
384
+ } else if (data.id) open.delete(data.id)
385
+ else { const oldest = open.keys().next(); if (!oldest.done) open.delete(oldest.value) } // no id: the oldest one
386
+ if (open.size) openApprovals.set(sessionId, open)
387
+ else openApprovals.delete(sessionId)
388
+ // Any open approval that waits for a person, whatever else is open, puts the run in waiting.
389
+ if (personApproval(sessionId)) {
390
+ if (!waitingSessions.has(sessionId)) { uiEpisodes.set(sessionId, (uiEpisodes.get(sessionId) ?? 0) + 1); waitingSince.set(sessionId, Date.now()) }
391
+ waitingSessions.add(sessionId)
392
+ for (const run of outputReceiversFor(sessionId)) if (run.state !== 'waiting') needsPerson(run, 500)
393
+ } else if (type === 'approval/decided') {
394
+ waitingSessions.delete(sessionId)
395
+ waitingSince.delete(sessionId)
396
+ for (const run of outputReceiversFor(sessionId)) if (run.state === 'waiting' && !questions.has(sessionId)) { run.state = 'running'; persist(run) }
397
+ }
398
+ wakeFollowers(sessionId)
399
+ }
400
+
307
401
  ctx.on('session/event', guard('session/event', (session, event) => {
308
402
  const data = event.data ?? {}
309
403
  if (FOLLOW_EVENTS.has(event.type)) wakeFollowers(session.id)
404
+ if (event.type === 'approval/asked' || event.type === 'approval/decided') onApproval(session.id, event.type, data)
405
+ // Harness asks for approvals only inside a turn, so none is open after it: one whose
406
+ // decision never came is not left to hold the session's waiting state.
407
+ if (event.type === 'turn/end' && openApprovals.has(session.id)) { openApprovals.delete(session.id); onApproval(session.id, 'approval/decided', { id: null }) }
310
408
  // Turn state is kept only for a turn in progress and dropped at its end.
311
409
  if (event.type === 'turn/start') turns.set(session.id, { hasOutput: false })
312
410
  else if (event.type === 'assistant/message' && turns.has(session.id)) turns.get(session.id).hasOutput = true
@@ -461,13 +559,15 @@ export function apply(ctx) {
461
559
 
462
560
  ctx.on('agent/status', guard('agent/status', ({ agent, status }) => {
463
561
  if (!agent) return
562
+ // An approval asked inside a tool call keeps the run waiting though the agent says "running".
563
+ const approvalOpen = personApproval(agent.id)
464
564
  if (status === 'waiting') { if (!waitingSessions.has(agent.id)) { uiEpisodes.set(agent.id, (uiEpisodes.get(agent.id) ?? 0) + 1); waitingSince.set(agent.id, Date.now()) } waitingSessions.add(agent.id) }
465
- else { waitingSessions.delete(agent.id); waitingSince.delete(agent.id) }
565
+ else if (!approvalOpen) { waitingSessions.delete(agent.id); waitingSince.delete(agent.id) }
466
566
  wakeFollowers(agent.id)
467
567
  const receivers = receiversFor(agent.id)
468
568
  if (status === 'running' && receivers.length) lastRunningAt.set(agent.id, Date.now())
469
569
  for (const run of outputReceiversFor(agent.id)) {
470
- if (status === 'running') run.state = 'running'
570
+ if (status === 'running') { if (!approvalOpen) run.state = 'running' }
471
571
  // Needs a person: a question (see user-questions/request) or an approval in the
472
572
  // Harness UI. Waiters wake a moment later, so a question that comes with it is on the run.
473
573
  else if (status === 'waiting') { if (run.state !== 'waiting') needsPerson(run, 500) }
@@ -684,6 +784,28 @@ export function apply(ctx) {
684
784
 
685
785
  ctx.on('user-questions/request', guardWaterfall(onQuestion), { global: true, prepend: true })
686
786
 
787
+ // Approvals in a hand-over run: allowed once here unless the plugin page says to leave them
788
+ // to the Harness UI (the user's choice, 2026-11-17: a hand-over must not stall on one). Only
789
+ // sessions with a run of this plugin in progress; every other approval goes on to Harness.
790
+ // Each one is listed on the run (approvals_allowed), so the client sees what was let through.
791
+ const MAX_ALLOWED = 20
792
+ function onApprovalRequest(request, next) {
793
+ const sessionId = request?.agent?.id
794
+ const runs = sessionId ? outputReceiversFor(sessionId) : []
795
+ if (!runs.length || approvalsMode() !== 'allow' || request?.signal?.aborted) return next()
796
+ // A call Harness's own Auto review model turned down (it never lets a high-risk one, such as
797
+ // sending secrets out, through) stays with the user: allowing it here would undo that review.
798
+ if (AUTO_REVIEW_DENIAL.test(String(request.reason ?? ''))) return next()
799
+ const entry = { time: new Date().toISOString(), tool: String(request.toolName ?? 'tool'), ...(request.reason ? { reason: String(request.reason).slice(0, 300) } : {}) }
800
+ for (const run of runs) {
801
+ run.approvalsAllowed = [...(run.approvalsAllowed ?? []), entry].slice(-MAX_ALLOWED)
802
+ pushEvent(run, { type: 'approval_allowed', tool: entry.tool })
803
+ persist(run)
804
+ }
805
+ return 'allowed-once'
806
+ }
807
+ ctx.on('approval/request', guardWaterfall(onApprovalRequest), { global: true, prepend: true })
808
+
687
809
  // Harness's own "busy send" setting (Settings → sending while busy: queue or steer),
688
810
  // as a dsh-baton mode, or null when this Harness has no such setting to read.
689
811
  function harnessBusyMode() {
@@ -1062,13 +1184,17 @@ export function apply(ctx) {
1062
1184
 
1063
1185
  // One model, or an error naming what is there: never a near miss in its place.
1064
1186
  // "provider/model" picks between providers that offer the same model.
1065
- function matchModel(c, asked) {
1187
+ function modelHits(c, asked) {
1066
1188
  const slash = String(asked).lastIndexOf('/')
1067
1189
  const provider = slash > 0 ? modelKey(String(asked).slice(0, slash)) : null
1068
1190
  const want = modelKey(slash > 0 ? String(asked).slice(slash + 1) : asked)
1069
- const hits = c.groups.flatMap((g) => (provider && modelKey(g.id) !== provider ? [] : g.models
1191
+ const hits = want ? c.groups.flatMap((g) => (provider && modelKey(g.id) !== provider ? [] : g.models
1070
1192
  .filter((m) => modelKey(m.id) === want || modelKey(m.name) === want)
1071
- .map((m) => ({ provider: g.id, entry: m }))))
1193
+ .map((m) => ({ provider: g.id, entry: m })))) : []
1194
+ return { want, hits }
1195
+ }
1196
+ function matchModel(c, asked) {
1197
+ const { want, hits } = modelHits(c, asked)
1072
1198
  if (!want || !hits.length) throw new Error(`No model in Harness matches ${JSON.stringify(asked)}. Available: ${listed(c)}.`)
1073
1199
  if (hits.length > 1) throw new Error(`${JSON.stringify(asked)} matches several models: ${hits.map((h) => `${h.provider}/${h.entry.id}`).join(', ')}. Pass one of them as provider/model.`)
1074
1200
  return hits[0]
@@ -1117,15 +1243,40 @@ export function apply(ctx) {
1117
1243
 
1118
1244
  // Work out the model a send asks for before anything is created, so a name that
1119
1245
  // matches nothing (or several) fails the send with the list of what is there.
1120
- async function planModel(sessionId, { model, reasoning_effort }) {
1121
- if (model == null && reasoning_effort == null) return null
1246
+ // `hit` is a catalog entry already found exactly (a hand-over default): it is used as it
1247
+ // is, never matched again by name.
1248
+ async function planModel(sessionId, { model, reasoning_effort, hit: exact }) {
1249
+ if (model == null && reasoning_effort == null && !exact) return null
1122
1250
  if (!canSelect()) throw new Error(MODELS_UNSUPPORTED)
1123
1251
  const c = await catalog()
1124
1252
  let hit
1125
- if (model != null) hit = matchModel(c, model)
1126
- else {
1127
- // Effort alone: the model the session runs with now (a new one: Harness's default).
1128
- const current = (sessionId && (await sessionModel(sessionId))) || c.default
1253
+ if (exact) hit = exact
1254
+ else if (model != null) {
1255
+ hit = exactModel(c, String(model))
1256
+ if (!hit) {
1257
+ // A name several providers share: the hand-over default on the plugin page decides
1258
+ // when it is one of them (issue #1, "DeepSeek-V4.1-Flash" from three providers).
1259
+ const { hits } = modelHits(c, model)
1260
+ const pin = hits.length > 1 ? handoverDefaults() : null
1261
+ const pinned = pin?.model && !pin.unreadable ? exactModel(c, pin.model) : null
1262
+ const chosen = pinned && hits.find((h) => h.provider === pinned.provider && h.entry.id === pinned.entry.id)
1263
+ if (chosen) {
1264
+ const plan = { provider: chosen.provider, model: chosen.entry.id, ...(reasoning_effort != null ? { reasoningEffort: matchEffort(chosen, reasoning_effort) } : {}) }
1265
+ return { ...plan, note: `${JSON.stringify(model)} matches several models (${hits.map((h) => `${h.provider}/${h.entry.id}`).join(', ')}); it ran on ${chosen.provider}/${chosen.entry.id}, the hand-over default set on ${PAGE}.` }
1266
+ }
1267
+ hit = matchModel(c, model)
1268
+ }
1269
+ } else if (!sessionId) {
1270
+ // Effort alone on a new session: Harness's default model, read inside the pick queue
1271
+ // (applyModel), so a pick running for another send cannot stand in for it. Checked
1272
+ // here against the default as it is now, so a wrong effort fails before anything is made.
1273
+ const entry = defaultHit(c)
1274
+ if (!entry) throw new Error(`The model ${c.default?.provider}/${c.default?.model} is not in Harness's catalog now; pass model too. Available: ${listed(c)}.`)
1275
+ matchEffort({ provider: c.default.provider, entry }, reasoning_effort)
1276
+ return { followDefault: true, reasoningEffort: reasoning_effort, catalog: c }
1277
+ } else {
1278
+ // Effort alone: the model the session runs with now.
1279
+ const current = (await sessionModel(sessionId)) || c.default
1129
1280
  const entry = c.groups.find((g) => g.id === current?.provider)?.models.find((m) => m.id === current?.model)
1130
1281
  if (!entry) throw new Error(`The model ${current?.provider}/${current?.model} is not in Harness's catalog now; pass model too. Available: ${listed(c)}.`)
1131
1282
  hit = { provider: current.provider, entry }
@@ -1133,13 +1284,209 @@ export function apply(ctx) {
1133
1284
  return { provider: hit.provider, model: hit.entry.id, ...(reasoning_effort != null ? { reasoningEffort: matchEffort(hit, reasoning_effort) } : {}) }
1134
1285
  }
1135
1286
 
1287
+ // --- hand-over defaults (Plugins page) ------------------------------------------
1288
+ // The model and reasoning effort a new hand-over session starts on when the send names
1289
+ // none, chosen on the plugin's page. Unset, a new session follows Harness's default model,
1290
+ // and that default moves whenever a model is picked in Harness's model menu. Kept in
1291
+ // settings.json in the dsh-baton home, with the last Harness default a hand-over followed,
1292
+ // so a change of that default is said in the reply instead of passing unnoticed.
1293
+ // A setting never fails a send: one that cannot be used is skipped and said in model_note.
1294
+ const SETTINGS_FILE = path.join(batonHome(), 'settings.json')
1295
+ const pause = (ms) => { try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } catch { /* no wait */ } }
1296
+ // { data } or { data: {}, error, corrupt? }. A missing file is no settings; a file another
1297
+ // process holds (Windows antivirus or indexer) is read again once; one that is not JSON
1298
+ // is reported, never taken for "nothing set".
1299
+ function loadSettings() {
1300
+ let text
1301
+ for (let attempt = 0; ; attempt++) {
1302
+ try { text = fs.readFileSync(SETTINGS_FILE, 'utf8'); break } catch (error) {
1303
+ if (error?.code === 'ENOENT') return { data: {} }
1304
+ if (attempt >= 1) return { data: {}, error: error?.code ?? String(error?.message ?? error) }
1305
+ pause(50)
1306
+ }
1307
+ }
1308
+ try {
1309
+ const s = JSON.parse(text.replace(/^/, ''))
1310
+ if (s && typeof s === 'object' && !Array.isArray(s)) return { data: s }
1311
+ } catch { /* below */ }
1312
+ return { data: {}, error: 'not valid JSON', corrupt: true }
1313
+ }
1314
+ // Merge a change into the file. An unreadable file is never overwritten from scratch:
1315
+ // only a save from the page replaces a broken one, after keeping it as settings.json.bad-<time>.
1316
+ function writeSettings(change, { replaceBroken = false } = {}) {
1317
+ const now = loadSettings()
1318
+ if (now.error && !(replaceBroken && now.corrupt)) throw new Error(`${SETTINGS_FILE} could not be read (${now.error}), so it was left as it is`)
1319
+ if (now.corrupt) fs.renameSync(SETTINGS_FILE, `${SETTINGS_FILE}.bad-${Date.now()}`)
1320
+ const next = { ...now.data, ...change }
1321
+ const body = JSON.stringify(next, null, 2) + '\n'
1322
+ fs.mkdirSync(path.dirname(SETTINGS_FILE), { recursive: true })
1323
+ const tmp = `${SETTINGS_FILE}.${process.pid}.tmp`
1324
+ fs.writeFileSync(tmp, body)
1325
+ // Windows refuses the rename while another process has the file open: try again shortly.
1326
+ for (let attempt = 0; ; attempt++) {
1327
+ try { fs.renameSync(tmp, SETTINGS_FILE); return next } catch (error) {
1328
+ if (attempt >= 5) { fs.rmSync(tmp, { force: true }); throw error }
1329
+ pause(40)
1330
+ }
1331
+ }
1332
+ }
1333
+ const filled = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null)
1334
+ // How approvals in a hand-over run are answered: 'allow' (the default) or 'ask' (the Harness UI).
1335
+ // Fails closed: a settings file that cannot be read, or a value other than the two, is 'ask'.
1336
+ function approvalsMode() {
1337
+ const { data, error } = loadSettings()
1338
+ if (error) return 'ask'
1339
+ return data.approvals == null || data.approvals === 'allow' ? 'allow' : 'ask'
1340
+ }
1341
+ function handoverDefaults() {
1342
+ const { data, error } = loadSettings()
1343
+ const h = data.handover && typeof data.handover === 'object' ? data.handover : {}
1344
+ return { model: filled(h.model), reasoning_effort: filled(h.reasoning_effort), ...(error ? { unreadable: error } : {}) }
1345
+ }
1346
+ // A saved "provider/model" names one catalog entry exactly; nothing else stands in for it.
1347
+ // Model ids may hold slashes themselves (openrouter/deepseek/deepseek-v4-pro).
1348
+ function exactModel(c, saved) {
1349
+ for (const g of c.groups) {
1350
+ if (!saved.startsWith(`${g.id}/`)) continue
1351
+ const entry = g.models.find((m) => m.id === saved.slice(g.id.length + 1))
1352
+ if (entry) return { provider: g.id, entry }
1353
+ }
1354
+ return null
1355
+ }
1356
+ const efforts = (hit) => (hit?.entry.reasoning?.efforts ?? []).map((e) => e.id)
1357
+ const hasEffort = (hit, asked) => { try { matchEffort(hit, asked); return true } catch { return false } }
1358
+ const defaultHit = (c) => c.groups.find((g) => g.id === c.default?.provider)?.models.find((m) => m.id === c.default?.model)
1359
+ // Choosing a model for a session needs Harness's default-model service as well, to put
1360
+ // the default back after the pick (keepingDefault).
1361
+ const canKeepDefault = () => {
1362
+ const dm = defaultModel()
1363
+ return typeof dm?.currentSelection === 'function' && typeof dm?.saveSelection === 'function'
1364
+ }
1365
+ const PAGE = 'the dsh-baton plugin page in Harness'
1366
+
1367
+ // What a new session's send asks for once the hand-over defaults fill in what it left out.
1368
+ async function withHandoverDefaults({ model, reasoning_effort }) {
1369
+ const out = { model, reasoning_effort, hit: null, used: { model: false, reasoning_effort: false }, notes: [] }
1370
+ const pin = handoverDefaults()
1371
+ if (pin.unreadable) {
1372
+ out.notes.push(`The hand-over defaults on ${PAGE} could not be read (${pin.unreadable}), so they were not used. Choose them on that page again if this goes on.`)
1373
+ return out
1374
+ }
1375
+ const wantModel = model == null && pin.model
1376
+ const wantEffort = reasoning_effort == null && pin.reasoning_effort
1377
+ if (!wantModel && !wantEffort) return out
1378
+ if (!canSelect() || !canKeepDefault()) {
1379
+ out.notes.push(`The hand-over defaults on ${PAGE} were not used: this DeepSeek Harness cannot choose a model per session.`)
1380
+ return out
1381
+ }
1382
+ let c
1383
+ try { c = await catalog() } catch (error) {
1384
+ out.notes.push(`Harness's model list could not be read (${error?.message ?? error}), so the hand-over defaults on ${PAGE} were not used.`)
1385
+ return out
1386
+ }
1387
+ let target = null
1388
+ if (wantModel) {
1389
+ const hit = exactModel(c, pin.model)
1390
+ if (!hit) out.notes.push(`The hand-over default model ${pin.model} (set on ${PAGE}) is not in Harness's model list now, so this session uses Harness's default model instead.`)
1391
+ else if (reasoning_effort != null && !hasEffort(hit, reasoning_effort)) out.notes.push(`The hand-over default model ${pin.model} (set on ${PAGE}) has no reasoning effort ${reasoning_effort}, so this session uses Harness's default model with that effort.`)
1392
+ else { out.hit = hit; out.used.model = true; target = hit }
1393
+ }
1394
+ if (wantEffort) {
1395
+ if (!target && model != null) { try { target = exactModel(c, String(model)) ?? matchModel(c, model) } catch { target = null } }
1396
+ if (!target && model == null) { const entry = defaultHit(c); target = entry ? { provider: c.default.provider, entry } : null }
1397
+ if (target && efforts(target).includes(pin.reasoning_effort)) { out.reasoning_effort = pin.reasoning_effort; out.used.reasoning_effort = true }
1398
+ else if (target) out.notes.push(`${target.provider}/${target.entry.id} has no reasoning effort ${pin.reasoning_effort} (the hand-over default on ${PAGE}), so it runs with its own default effort.`)
1399
+ }
1400
+ return out
1401
+ }
1402
+
1403
+ // A new session that followed Harness's default: if that default is not the one the last
1404
+ // such hand-over ran on, say so, since nothing else shows it moved. The new default is
1405
+ // recorded only once the message is in (rememberDefault), so a refused send does not use
1406
+ // up the note.
1407
+ function defaultDrift(selected) {
1408
+ const now = selected ? `${selected.provider}/${selected.model}` : null
1409
+ if (!now) return null
1410
+ const saved = loadSettings()
1411
+ if (saved.error) return null
1412
+ const before = filled(saved.data.lastDefaultModel)
1413
+ if (before === now) return null
1414
+ return { now, note: before ? `Harness's default model changed since the last new hand-over (${before} then, ${now} now), so this session runs on ${now}. Picking a model in Harness's model menu changes that default. To keep new hand-overs on one model, choose a hand-over default model on ${PAGE}.` : null }
1415
+ }
1416
+ function rememberDefault(now) {
1417
+ try { writeSettings({ lastDefaultModel: now }) } catch (error) { logError('save last default model', error) }
1418
+ }
1419
+
1420
+ // The plugin page reads and saves the defaults through these.
1421
+ async function handoverView() {
1422
+ const pin = handoverDefaults()
1423
+ const view = { model: pin.model, reasoning_effort: pin.reasoning_effort, approvals: approvalsMode(), ...(pin.unreadable ? { unreadable: pin.unreadable } : {}) }
1424
+ if (!canSelect() || !canKeepDefault()) return { ...view, supported: false }
1425
+ const c = await catalog()
1426
+ return {
1427
+ ...view,
1428
+ supported: true,
1429
+ default: shownModel(c.default),
1430
+ models: c.groups.flatMap((g) => g.models.map((m) => ({
1431
+ provider: g.id, provider_name: g.name ?? g.id, model: m.id, name: m.name ?? m.id,
1432
+ reasoning_efforts: (m.reasoning?.efforts ?? []).map((e) => ({ id: e.id, name: e.name ?? e.id })),
1433
+ }))),
1434
+ ...(pin.model && !exactModel(c, pin.model) ? { missing: true } : {}),
1435
+ }
1436
+ }
1437
+ // A field left out of the body keeps its saved value; null clears it. A saved model that
1438
+ // left Harness's list may be kept as it is (the provider may come back), but not chosen anew.
1439
+ async function saveHandover(body) {
1440
+ if ('approvals' in body && !['allow', 'ask'].includes(body.approvals)) throw new Error(`approvals is "allow" or "ask", not ${JSON.stringify(body.approvals)}.`)
1441
+ const touchesModel = 'model' in body || 'reasoning_effort' in body
1442
+ let model = null
1443
+ let reasoning_effort = null
1444
+ if (touchesModel) {
1445
+ const pin = handoverDefaults()
1446
+ model = 'model' in body ? filled(body.model) : pin.model
1447
+ reasoning_effort = 'reasoning_effort' in body ? filled(body.reasoning_effort) : pin.reasoning_effort
1448
+ if (model != null || reasoning_effort != null) {
1449
+ if (!canSelect() || !canKeepDefault()) throw new Error(MODELS_UNSUPPORTED)
1450
+ const c = await catalog()
1451
+ const hit = model != null ? exactModel(c, model) : null
1452
+ if (model != null && !hit && model !== pin.model) throw new Error(`No model ${model} in Harness's model list.`)
1453
+ const allowed = hit ? efforts(hit) : [...new Set(c.groups.flatMap((g) => g.models.flatMap((m) => efforts({ entry: m }))))]
1454
+ if (reasoning_effort != null && !allowed.includes(reasoning_effort)) throw new Error(`No reasoning effort ${reasoning_effort}${hit ? ` for ${model}` : ''}; there is ${allowed.join(', ') || 'none'}.`)
1455
+ }
1456
+ }
1457
+ // Only what this save names is written. A field it left out is read again now, after the
1458
+ // catalogue wait, so a save from another page in the meantime is not undone.
1459
+ const change = {}
1460
+ if (touchesModel) {
1461
+ const latest = handoverDefaults()
1462
+ change.handover = { model: 'model' in body ? model : latest.model, reasoning_effort: 'reasoning_effort' in body ? reasoning_effort : latest.reasoning_effort }
1463
+ }
1464
+ if ('approvals' in body) change.approvals = body.approvals
1465
+ // A broken file that is replaced: the approvals choice in it is unknown, so the safe one.
1466
+ else if (loadSettings().corrupt) change.approvals = 'ask'
1467
+ writeSettings(change, { replaceBroken: true })
1468
+ return handoverView()
1469
+ }
1470
+
1136
1471
  // Put the session on its model before the prompt goes in. Without a plan, a new session
1137
1472
  // is pinned to the default as it stands, so a pick running for another send cannot leak
1138
1473
  // into it (Harness reads the default only when the first request is built); an existing
1139
1474
  // one keeps its own. The pin is best effort: if it fails, the session just uses the default.
1140
1475
  async function applyModel(sessionId, plan, isNew) {
1476
+ if (plan?.followDefault) {
1477
+ // Effort alone on a new session: the default as it stands inside the queue, with that effort if it has it.
1478
+ let dropped = null
1479
+ const { selected } = await keepingDefault((kept) => {
1480
+ const entry = plan.catalog.groups.find((g) => g.id === kept?.provider)?.models.find((m) => m.id === kept?.model)
1481
+ const effort = entry && hasEffort({ provider: kept.provider, entry }, plan.reasoningEffort) ? matchEffort({ provider: kept.provider, entry }, plan.reasoningEffort) : null
1482
+ if (!effort) dropped = plan.reasoningEffort
1483
+ return controller.selectModel({ sessionId, ...kept, ...(effort ? { reasoningEffort: effort } : {}) })
1484
+ })
1485
+ return { model: shownModel(selected), source: 'requested', ...(dropped ? { droppedEffort: dropped } : {}) }
1486
+ }
1141
1487
  if (plan) {
1142
- const { selected } = await keepingDefault(() => controller.selectModel({ sessionId, ...plan }))
1488
+ const { note: _note, ...pick } = plan // the note is for the reply, not for Harness
1489
+ const { selected } = await keepingDefault(() => controller.selectModel({ sessionId, ...pick }))
1143
1490
  return { model: shownModel(selected), source: 'requested' }
1144
1491
  }
1145
1492
  if (isNew && canSelect() && defaultModel()) {
@@ -1195,7 +1542,7 @@ export function apply(ctx) {
1195
1542
  await teamsService.setEnabled(agent, enabled)
1196
1543
  }
1197
1544
 
1198
- async function send({ message, session_id, cwd, workspace_id, mode: asked, sender, model, reasoning_effort, team }) {
1545
+ async function send({ message, session_id, cwd, workspace_id, conversation_folder, mode: asked, sender, model, reasoning_effort, team }) {
1199
1546
  if (!message || !message.trim()) throw new Error('message is required')
1200
1547
  if (asked != null && asked !== 'followup' && asked !== 'steer') throw new Error('mode must be followup or steer')
1201
1548
  if (team != null && typeof team !== 'boolean') throw new Error('team must be true or false')
@@ -1208,6 +1555,7 @@ export function apply(ctx) {
1208
1555
  if (sender != null && !SENDER_RE.test(sender)) throw new Error('sender must be 1-32 characters of a-z, 0-9 or -')
1209
1556
  let sessionId = session_id
1210
1557
  let workspace = null
1558
+ let workFolder = null
1211
1559
  // Harness never runs a prompt sent to an archived session: the run would stay queued forever.
1212
1560
  if (sessionId && isArchived(sessionId)) {
1213
1561
  throw new Error(`Session ${sessionId} is archived. Unarchive it in Harness, or start a new session with cwd or workspace_id.`)
@@ -1222,23 +1570,75 @@ export function apply(ctx) {
1222
1570
  throw new Error(`The folder ${dir}${workspace_id ? ` (workspace ${workspace_id})` : ''} does not exist, so no session was started and nothing was sent. Check the path (a project on an external drive needs that drive connected), or create the folder first.`)
1223
1571
  }
1224
1572
  }
1225
- const plan = await planModel(sessionId, { model, reasoning_effort })
1573
+ // Agent Teams belong to the whole session: changed while a turn runs (for a message that
1574
+ // waits behind it, or one steered into it), they would change that turn too.
1575
+ if (team != null && sessionId) {
1576
+ const busy = activeRunsFor(sessionId).length > 0 || (await sessionActivity(sessionId).catch(() => [])).length > 0
1577
+ if (busy) throw new Error(`No message was sent: the session is busy, and Agent Teams apply to the whole session, so turning them ${team ? 'on' : 'off'} now would change the running turn too. Send it again once the session is idle, or without team.`)
1578
+ }
1226
1579
  const isNew = !sessionId
1580
+ // A new session takes the plugin page's hand-over defaults for what the send leaves out;
1581
+ // a session that exists keeps its own model.
1582
+ const want = isNew ? await withHandoverDefaults({ model, reasoning_effort }) : { model, reasoning_effort, hit: null, used: {}, notes: [] }
1583
+ const fromPage = () => want.used.model || want.used.reasoning_effort
1584
+ // A send fails only over what it asked for itself: if the plan fails because of a
1585
+ // hand-over default, the send is planned again without the defaults.
1586
+ const dropDefaults = (error, what) => {
1587
+ want.notes.push(`The hand-over defaults on ${PAGE} could not be used (${what}: ${error?.message ?? error}), so this session uses ${model != null ? 'the model asked for' : "Harness's default model"}.`)
1588
+ want.used = { model: false, reasoning_effort: false }
1589
+ want.hit = null
1590
+ }
1591
+ let plan
1592
+ try { plan = await planModel(sessionId, want) } catch (error) {
1593
+ if (!fromPage()) throw error
1594
+ dropDefaults(error, 'planning')
1595
+ plan = await planModel(sessionId, { model, reasoning_effort })
1596
+ }
1227
1597
  if (isNew) {
1228
1598
  // A folder that is not a workspace yet is registered first, so the new session shows in the sidebar.
1229
- workspace = workspace_id ? { id: workspace_id } : await createWorkspace({ path: cwd, create_dir: false })
1599
+ if (workspace_id) workspace = { id: workspace_id }
1600
+ else {
1601
+ const target = normalizePath(cwd)
1602
+ // A folder that is a workspace already (sessions from before 0.6.15) keeps it.
1603
+ const own = await registry.resolveByPath(target).catch(() => undefined)
1604
+ const home = own ? { path: target } : sessionHome(target, conversation_folder)
1605
+ workspace = await createWorkspace({ path: home.path, title: home.title, create_dir: false })
1606
+ if (!same(home.path, target)) {
1607
+ workFolder = target
1608
+ // First, not last: a message saying "the current directory" otherwise ran in the parent
1609
+ // (Windows, 2 of 3 runs). A leading /command (/goal) stays first.
1610
+ const note = `(Working folder for this task: ${target}. Run every command there: set each shell command's working directory to ${target}, or cd into it first. "The current directory", "here" and relative paths below all mean ${target}; this session opened in ${home.path}, a folder that contains it.)`
1611
+ // A command such as /goal, not a path such as /Users/me/app/x.js.
1612
+ const slash = /^(\/[A-Za-z][\w-]*)(\s+|$)/.exec(message)
1613
+ message = slash ? `${slash[1]} ${note}\n\n${message.slice(slash[0].length)}` : `${note}\n\n${message}`
1614
+ }
1615
+ }
1230
1616
  sessionId = (await controller.create({ workspaceId: workspace.id })).sessionId
1231
1617
  }
1232
1618
  // A model that cannot be set fails the send before the prompt goes in.
1233
- const chosen = await applyModel(sessionId, plan, isNew).catch((error) => {
1234
- throw new Error(`${isNew ? `Session ${sessionId} was created, but no message was sent: ` : 'No message was sent: '}the model could not be set (${error?.message ?? error})`)
1235
- })
1236
- // Team mode goes on (or off) before the prompt, so the first step already has the Team tools.
1237
- if (team != null) {
1238
- await setTeam(sessionId, team).catch((error) => {
1239
- throw new Error(`${isNew ? `Session ${sessionId} was created, but no message was sent: ` : 'No message was sent: '}Agent Teams could not be turned ${team ? 'on' : 'off'} (${error?.message ?? error})`)
1240
- })
1619
+ const notSet = (error) => new Error(`${isNew ? `Session ${sessionId} was created, but no message was sent: ` : 'No message was sent: '}the model could not be set (${error?.message ?? error})`)
1620
+ let chosen
1621
+ try { chosen = await applyModel(sessionId, plan, isNew) } catch (error) {
1622
+ if (!fromPage()) throw notSet(error)
1623
+ // A default Harness would not take (a provider signed out since): the send's own request instead.
1624
+ logError('apply hand-over default', error)
1625
+ dropDefaults(error, 'setting the model')
1626
+ try { chosen = await applyModel(sessionId, await planModel(sessionId, { model, reasoning_effort }), isNew) } catch (again) { throw notSet(again) }
1241
1627
  }
1628
+ let modelSource = chosen.source
1629
+ if (want.used.model) modelSource = 'handover_default'
1630
+ else if (want.used.reasoning_effort && model == null) modelSource = 'default' // Harness's default model, the effort set on the page
1631
+ const modelNotes = [...want.notes]
1632
+ if (plan?.note) modelNotes.push(plan.note)
1633
+ if (chosen.droppedEffort) modelNotes.push(`${chosen.model?.provider}/${chosen.model?.model} has no reasoning effort ${chosen.droppedEffort}, so it runs with its own default effort.`)
1634
+ let drift = null
1635
+ if (isNew && modelSource === 'default') {
1636
+ let followed = chosen.model
1637
+ if (!followed) try { followed = shownModel(defaultModel()?.currentSelection?.()) } catch { /* unknown */ }
1638
+ drift = defaultDrift(followed)
1639
+ if (drift?.note) modelNotes.push(drift.note)
1640
+ }
1641
+ const pagePart = [...(want.used.model ? ['model'] : []), ...(want.used.reasoning_effort ? ['reasoning_effort'] : [])]
1242
1642
  // A session that never picked a model runs on Harness's default.
1243
1643
  let provider = chosen.model?.provider
1244
1644
  if (!provider) try { provider = defaultModel()?.currentSelection?.()?.provider } catch { /* unknown: no check */ }
@@ -1246,7 +1646,17 @@ export function apply(ctx) {
1246
1646
  const empty = await emptyBalance()
1247
1647
  if (empty) throw new Error(`${isNew ? `Session ${sessionId} was created, but no message was sent` : 'No message was sent'}: the DeepSeek account has no balance left (${empty}), so the run would fail at once. Do not send again until the user has topped up (Harness → Settings → Account, or platform.deepseek.com).`)
1248
1648
  }
1649
+ // Team mode goes on (or off) before the prompt, so the first step already has the Team tools,
1650
+ // and after the checks that can refuse the send, so a refused send leaves it as it was.
1651
+ if (team != null) {
1652
+ await setTeam(sessionId, team).catch((error) => {
1653
+ throw new Error(`${isNew ? `Session ${sessionId} was created, but no message was sent: ` : 'No message was sent: '}Agent Teams could not be turned ${team ? 'on' : 'off'} (${error?.message ?? error})`)
1654
+ })
1655
+ }
1249
1656
  const ahead = activeRunsFor(sessionId).map((r) => r.id)
1657
+ // A followup into a busy session waits in its queue, behind our runs or a turn the user
1658
+ // typed in Harness: said back, so the client knows it can still change it.
1659
+ const queuedBehind = !isNew && mode === 'followup' && (ahead.length > 0 || (await sessionActivity(sessionId).catch(() => [])).length > 0)
1250
1660
  const run = {
1251
1661
  id: `hrun-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
1252
1662
  sessionId, requestId: requestIdFor(sender), ...(sender ? { sender } : {}), mode, state: 'queued', sawPrompt: false,
@@ -1258,6 +1668,7 @@ export function apply(ctx) {
1258
1668
  try {
1259
1669
  await controller.prompt({ sessionId, requestId: run.requestId, content: [{ type: 'text', text: message }], mode }, signal())
1260
1670
  run.admitted = true // in Harness's queue (or conversation) now
1671
+ if (drift) rememberDefault(drift.now)
1261
1672
  } catch (error) {
1262
1673
  settle(run, 'failed', { error: String(error?.message ?? error) })
1263
1674
  }
@@ -1266,10 +1677,14 @@ export function apply(ctx) {
1266
1677
  mode,
1267
1678
  mode_source: modeSource,
1268
1679
  model: chosen.model,
1269
- model_source: chosen.source,
1680
+ model_source: modelSource,
1681
+ ...(pagePart.length ? { handover_default: pagePart } : {}),
1682
+ ...(modelNotes.length ? { model_note: modelNotes.join(' ') } : {}),
1270
1683
  ...(team != null ? { team } : {}),
1271
1684
  ...(ahead.length ? { other_active_runs: ahead } : {}),
1685
+ ...(queuedBehind ? { queued_behind: true } : {}),
1272
1686
  ...(workspace ? { workspace } : {}),
1687
+ ...(workFolder ? { work_folder: workFolder } : {}),
1273
1688
  }
1274
1689
  }
1275
1690
 
@@ -1458,8 +1873,67 @@ export function apply(ctx) {
1458
1873
  }
1459
1874
 
1460
1875
 
1876
+ // --- hand-over defaults route -----------------------------------------------
1877
+ // GET /dsh-baton/handover: the saved defaults and Harness's model list, for the plugin page.
1878
+ // POST (JSON): save new ones. Only the plugin page itself may save. Its request carries the
1879
+ // header x-dsh-baton: handover and a JSON body, which a page on another site can only send
1880
+ // after a CORS preflight that this route never answers. The Host must be an address or a
1881
+ // localhost name, never another name, so a site that rebinds its own name to this machine
1882
+ // is refused too. The desktop app's window (dsh-app://app) reaches the web server through a
1883
+ // proxy that drops Origin, so a missing Origin is allowed; one that is there must be the
1884
+ // app's own or match the Host (dsh web in a browser).
1885
+ function localHost(hostname) {
1886
+ const bare = hostname.replace(/^\[|\]$/g, '')
1887
+ return bare === 'localhost' || bare.endsWith('.localhost') || net.isIP(bare) !== 0
1888
+ }
1889
+ // The peer of the connection: on this computer only, whatever the Host says (a Harness web
1890
+ // server bound to the network would otherwise take a save from another machine).
1891
+ const LOOPBACK = /^(?:127\.\d+\.\d+\.\d+|::1|::ffff:127\.\d+\.\d+\.\d+)$/
1892
+ function fromHarnessPage(request) {
1893
+ const headers = request.headers ?? {}
1894
+ const peer = request.socket?.remoteAddress
1895
+ if (peer != null && !LOOPBACK.test(peer)) return false
1896
+ if (headers['x-dsh-baton'] !== 'handover') return false
1897
+ if (!String(headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) return false
1898
+ let host
1899
+ try { host = new URL(`http://${headers.host}`) } catch { return false }
1900
+ if (!localHost(host.hostname)) return false
1901
+ if (headers.origin == null) return true
1902
+ let origin
1903
+ try { origin = new URL(headers.origin) } catch { return false }
1904
+ return origin.protocol === 'dsh-app:' || origin.host === host.host
1905
+ }
1906
+ function readBody(request, limit = 16 * 1024) {
1907
+ return new Promise((resolve, reject) => {
1908
+ const chunks = []
1909
+ let size = 0
1910
+ request.on('data', (chunk) => {
1911
+ size += chunk.length
1912
+ if (size > limit) { reject(new Error('request body too large')); request.destroy() } else chunks.push(chunk)
1913
+ })
1914
+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1915
+ request.on('error', reject)
1916
+ })
1917
+ }
1918
+ function replyJson(response, code, body) {
1919
+ response.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' })
1920
+ response.end(JSON.stringify(body))
1921
+ }
1922
+ async function serveHandover(request, response) {
1923
+ try {
1924
+ if (request.method === 'GET') return replyJson(response, 200, await handoverView())
1925
+ if (request.method !== 'POST') return replyJson(response, 405, { error: 'GET or POST only' })
1926
+ if (!fromHarnessPage(request)) return replyJson(response, 403, { error: 'These settings can only be saved from the Harness window on this computer.' })
1927
+ const raw = await readBody(request)
1928
+ const body = raw.trim() ? JSON.parse(raw) : {}
1929
+ replyJson(response, 200, await saveHandover(body && typeof body === 'object' && !Array.isArray(body) ? body : {}))
1930
+ } catch (error) {
1931
+ replyJson(response, 400, { error: String(error?.message ?? error) })
1932
+ }
1933
+ }
1934
+
1461
1935
  // --- MCP registration -----------------------------------------------------
1462
- // Switching the plugin on registers the dsh-baton MCP server for Claude Code and Codex,
1936
+ // Switching the plugin on registers the dsh-baton MCP server for Claude Code, Codex and Antigravity,
1463
1937
  // the same entries `dsh-baton setup` writes, so adding the plugin is the whole install.
1464
1938
  // It runs again on every Harness start: a plugin update brings the server along, and an
1465
1939
  // entry that is already right is left untouched. The Plugins page reads the outcome from
@@ -1512,9 +1986,18 @@ export function apply(ctx) {
1512
1986
  handler: (request, response) => {
1513
1987
  const { state, ok, error, version, runtime, clients = [] } = registration
1514
1988
  response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
1515
- response.end(JSON.stringify({ version: VERSION, registration: { state, ok, error, version, runtime, clients: clients.map(({ id, label, state }) => ({ id, label, state })) } }))
1989
+ response.end(JSON.stringify({ version: VERSION, registration: { state, ok, error, version, runtime, clients: clients.map(({ id, label, state, error, file }) => ({ id, label, state, ...(error === 'bad-json' ? { error, file } : {}) })) } }))
1516
1990
  },
1517
1991
  }), 'dsh-baton-host status route')
1992
+ web.effect(() => web.webServer.register({
1993
+ kind: 'exact',
1994
+ path: '/dsh-baton/handover',
1995
+ // The promise goes back to the web server, and nothing in the last resort can throw.
1996
+ handler: (request, response) => serveHandover(request, response).catch((error) => {
1997
+ logError('hand-over route', error)
1998
+ try { replyJson(response, 500, { error: String(error?.message ?? error) }) } catch { try { response.destroy() } catch { /* gone */ } }
1999
+ }),
2000
+ }), 'dsh-baton-host hand-over route')
1518
2001
  })
1519
2002
  }
1520
2003