dsh-taskbridge 1.4.2 → 1.5.1

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 (44) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/README.md +10 -8
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +180 -16
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +11 -13
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  13. package/docs/releases/1.5.0.zh.md +51 -0
  14. package/docs/releases/1.5.1.zh.md +70 -0
  15. package/docs/runtime-compatibility.md +4 -4
  16. package/docs/silent-wait.md +157 -3
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +298 -103
  20. package/package.json +9 -3
  21. package/src/client/api.js +315 -34
  22. package/src/client/index.jsx +151 -67
  23. package/src/codex/installer.js +251 -11
  24. package/src/config/redact.js +72 -11
  25. package/src/http/execution-plane.js +124 -10
  26. package/src/index.d.ts +347 -0
  27. package/src/index.js +88 -5
  28. package/src/jobs/activity.js +102 -9
  29. package/src/jobs/continuation-identity.js +283 -0
  30. package/src/jobs/engine.js +491 -55
  31. package/src/jobs/history.js +96 -0
  32. package/src/mcp/continuation.js +317 -0
  33. package/src/mcp/metrics.js +366 -0
  34. package/src/mcp/server.js +1203 -53
  35. package/src/mcp/wait.js +338 -73
  36. package/src/review/prompts.js +145 -126
  37. package/src/runtime/agent-runner.js +330 -0
  38. package/src/runtime/permissions.js +192 -2
  39. package/src/runtime/question-call.js +162 -0
  40. package/src/runtime/questions.js +909 -0
  41. package/src/runtime/sandbox.js +363 -358
  42. package/src/runtime/session-placement.js +1207 -1121
  43. package/src/version.js +121 -0
  44. package/src/workspace/worktrees.js +70 -4
@@ -350,6 +350,76 @@ export const KNOWN_AGENT_TEMPLATES = [
350
350
  // Exact published 1.4.1 companion, including its LF and CRLF forms.
351
351
  { version: '1.4.1', sha256: '8b6211918ce867ecfdac3495973813a70b7290bdd40221b439d98638f82ac3d4' },
352
352
  { version: '1.4.1', sha256: 'e2a8dc4cac897266e198b98be8fbf91d4159ab9a799704f200224457d292b5be' },
353
+ // Exact 1.4.2 bytes, taken from that RELEASE's own `codex/dsh-taskbridge.toml` in the
354
+ // repository's HEAD (the file as it was published, before later edits), in the LF form it
355
+ // was committed in (`38234033…`, 26388 bytes) and the CRLF form a Windows install rewrites
356
+ // it to (`b62426ab…`, 26740 bytes). Both were computed from the committed blob, never from
357
+ // the current working-tree template: deriving them from the NEW text would make every
358
+ // untouched 1.4.2 install hash to an unknown value, be reported `modified` and never be
359
+ // refreshed. An operator-edited file still hashes to something unknown and stays untouched.
360
+ { version: '1.4.2', sha256: '38234033103190c0523fbf5223c848186fbd03d86b109e89940d1623e430bfb7' },
361
+ { version: '1.4.2', sha256: 'b62426abad77e06b054941cc71fb3d821a9e0d695b1196f62e2170c47c6d17a7' },
362
+ // Exact local test.1 template, read from its installed package (LF and CRLF).
363
+ { version: '1.4.3-test.1', sha256: 'a42fa6da6f028f7ea489ee4b97af7a734958d0cf5ee9affe4361fd534b233882' },
364
+ { version: '1.4.3-test.1', sha256: 'd9fcf481dd7cd61a019dfd753f9dc29c6ad34e6a6aeb4e31e08de7117ff1deaf' },
365
+ // Exact installed test.2 package verified by the coordinator before 1.5.0.
366
+ { version: '1.4.3-test.2', sha256: 'a761461a769b8f297be0e4b7bb68de591918d5afa74a8348e9d475c87011a967' },
367
+ { version: '1.4.3-test.2', sha256: '75ee69400e040d8e18542121a0a49467539368cc0205cc120785b62b6692e16d' },
368
+ // Exact published 1.5.0 template — the file an existing 1.5.0 installation holds when
369
+ // the build that teaches the repeated-failure acknowledgment starts. The instruction
370
+ // body changed in this working tree (the `failure` block gained its `eventId`, the
371
+ // redelivery rule and the `ackFailureEventId` acknowledgment), so 1.5.0's bytes are a
372
+ // DISTINCT published build that has to be enumerated: without them every untouched
373
+ // 1.5.0 install would be reported `modified` ("somebody else's file") and never
374
+ // refreshed. Both byte forms are enumerated, exactly like every other release:
375
+ //
376
+ // * `4af78cd2…` — the LF form as the release committed it (`git show
377
+ // 6d1eef9:codex/dsh-taskbridge.toml`, 32100 bytes, version = "1.5.0").
378
+ // * `253a6958…` — the same text with every `\n` turned into `\r\n` (32521 bytes), the
379
+ // uniform CRLF form a Windows install writes.
380
+ //
381
+ // Both are exact content identities computed from the committed blob, never derived
382
+ // from the NEW template: an operator-edited file still hashes to something unknown and
383
+ // is left alone.
384
+ { version: '1.5.0', sha256: '4af78cd2afb3d739d2f73ad8c21893b7e6434d0d06508b19fe36e9ba8012667b' },
385
+ { version: '1.5.0', sha256: '253a695842e9634e28e86030c7ffb10d21b338f09451a8c13849cfce1d9d9364' },
386
+ // The INSTALLED local test build `1.5.1-test.1`. Its identity is not a guess: the bytes
387
+ // are the template that build's own product package shipped, rendered by the SAME
388
+ // renderer this module uses, and they were compared byte-for-byte with the file actually
389
+ // installed on the operator's machine.
390
+ //
391
+ // * `1995032a…` — the LF form (40220 bytes, `version = "1.5.1-test.1"`).
392
+ // * `287be66f…` — the same text with every `\n` turned into `\r\n` (40266 bytes), which
393
+ // is exactly what is installed on Windows.
394
+ //
395
+ // Without these two, an untouched test.1 install hashes to "unknown content" and is
396
+ // reported `modified`, which is what made the upgrade to test.2 impossible. Only these
397
+ // exact bytes qualify: a single edited character still hashes to something unknown and
398
+ // stays the operator's file.
399
+ { version: '1.5.1-test.1', sha256: '1995032ab0794404d243f34d97478021c435fda1d584254cb1b70fcbe5432970' },
400
+ { version: '1.5.1-test.1', sha256: '287be66fb4e9d4623d4384545a990c267bf5f5aeede68acc9965c1b442d38ceb' },
401
+ // A LOCAL artifact of this operator's machine, NOT a published release identity.
402
+ //
403
+ // What it is: when this machine's plugin was upgraded to `1.5.1-test.2`, the running
404
+ // module still answered the CACHED old version, so the integration was written with the
405
+ // CURRENT template body but `version = "1.5.0"` stamped in it. The reference is that
406
+ // product template rendered by this module's own renderer with that stale version, and
407
+ // it was compared byte-for-byte with the file actually installed here.
408
+ //
409
+ // Why it must be enumerated: the next start reads the REAL manifest, so without these
410
+ // bytes the operator's freshly written file would be classified `modified` — a
411
+ // self-inflicted false conflict after every update. The version line is the ONLY thing
412
+ // that makes it distinct from a real 1.5.0 build, which is exactly why it is matched by
413
+ // exact content and nothing else: any edit (or any other template) still hashes to an
414
+ // unknown value and stays the operator's file.
415
+ //
416
+ // * `da2f428f…` — LF form (39,743 bytes).
417
+ // * `f55893e7…` — the installed CRLF form (40,259 bytes).
418
+ { version: '1.5.0', sha256: 'da2f428f726ae64b6895941d5238516346af91b63b038b1d57787be327fb28ee' },
419
+ { version: '1.5.0', sha256: 'f55893e7605627c6f0c9a4c55f58a5a1956d4c11b8c03c99569dca241842d8bb' },
420
+ // Exact locally installed test.3 product template, verified before preparing 1.5.1.
421
+ { version: '1.5.1-test.3', sha256: 'dc1c17f3bdfe171d3c1e7f943d569b12ffe12d6b25190fffe1c8c9550446f29d' },
422
+ { version: '1.5.1-test.3', sha256: '06e13895f6df3ec9fbf48b1b40af42940f3ddf2b3afad356751dbd11e1205ff4' },
353
423
  ];
354
424
 
355
425
  /** The `version = "…"` line of an agent file, at column 0. */
@@ -467,6 +537,123 @@ export function requireCodexHome(codexHome) {
467
537
  return resolve(codexHome);
468
538
  }
469
539
 
540
+ /**
541
+ * Resolve the SELECTED Codex home to the REAL directory it names, pinning it once.
542
+ *
543
+ * Why this exists: a migrated machine commonly keeps `~/.codex` as a junction (Windows) or
544
+ * symlink pointing at the real store (for example `E:\Codex\Data\.codex`). That root link
545
+ * is the operator's own layout, not a hostile indirection: refusing it made every update
546
+ * report a false conflict and forced a manual fix. So the ROOT may be a link — it is
547
+ * resolved ONCE here and every later read, classification, write, repair, refresh and
548
+ * removal uses the resolved target, which means an alias retargeted mid-operation can
549
+ * never redirect a write to a new place.
550
+ *
551
+ * What is NOT relaxed:
552
+ * * `<home>/agents`, the agent file and `config.toml` are still inspected and refused
553
+ * when THEY are links (see {@link inspectCodexBoundary});
554
+ * * a target that is missing, not a directory, or unreadable is refused with a clear
555
+ * reason rather than created or followed further;
556
+ * * the root link itself is never deleted, moved or rewritten.
557
+ * @param {string} selected - the selected home (already absolute; may be a link).
558
+ * @returns {Promise<{ selected: string, real: string, linked: boolean, linkTarget: string | null,
559
+ * error: null | { code: string, reason: string, message: string } }>} pinned home facts.
560
+ */
561
+ async function pinCodexHome(selected) {
562
+ const selectedPath = selected;
563
+ const linkedInfo = await inspectDirectory(selectedPath).catch(() => ({ kind: 'unknown' }));
564
+ // A missing root is the ordinary first-install case: it is created by the writer, and
565
+ // its parent is what must be a real directory.
566
+ if (linkedInfo.kind === 'missing') {
567
+ return { selected: selectedPath, real: selectedPath, linked: false, linkTarget: null, error: null };
568
+ }
569
+ if (linkedInfo.kind === 'unknown') {
570
+ // The platform could not classify the root. That is NOT "unusable": it is the
571
+ // existing `boundary-unverified` diagnosis, which the boundary inspection below owns.
572
+ // Pinning leaves the path alone and lets that check report the refusal.
573
+ return { selected: selectedPath, real: selectedPath, linked: false, linkTarget: null, error: null };
574
+ }
575
+ if (linkedInfo.kind !== 'link') {
576
+ // A real directory (including a junction that `lstat`/attributes prove is one is
577
+ // handled by the link branch below): nothing to resolve.
578
+ if (linkedInfo.kind === 'directory') {
579
+ return { selected: selectedPath, real: selectedPath, linked: false, linkTarget: null, error: null };
580
+ }
581
+ // A DANGLING Windows junction is the awkward case: `lstat` reports an ordinary
582
+ // directory (the target is never reached), so it lands here as `directory`-less and
583
+ // `realpath` fails. Resolve it as a link attempt: if `realpath` cannot answer, the
584
+ // selected root exists but does not lead to a usable directory, and nothing may be
585
+ // created at the alias.
586
+ let dangling = null;
587
+ try {
588
+ dangling = await realpath(selectedPath);
589
+ } catch {
590
+ dangling = null;
591
+ }
592
+ if (dangling === null) {
593
+ return {
594
+ selected: selectedPath,
595
+ real: selectedPath,
596
+ linked: false,
597
+ linkTarget: null,
598
+ error: {
599
+ code: 'CODEX_HOME_UNUSABLE',
600
+ reason: 'codex-home-link-unresolvable',
601
+ message: 'the Codex home cannot be resolved to a real directory (its target is missing)',
602
+ },
603
+ };
604
+ }
605
+ return {
606
+ selected: selectedPath,
607
+ real: selectedPath,
608
+ linked: false,
609
+ linkTarget: null,
610
+ error: {
611
+ code: 'CODEX_HOME_UNUSABLE',
612
+ reason: 'codex-home-not-a-directory',
613
+ message: 'the Codex home exists but is not a directory, so nothing was read or written',
614
+ },
615
+ };
616
+ }
617
+ // The ROOT is a link/junction: resolve it once and classify what it really names.
618
+ let resolved;
619
+ try {
620
+ resolved = await realpath(selectedPath);
621
+ } catch {
622
+ return {
623
+ selected: selectedPath,
624
+ real: selectedPath,
625
+ linked: true,
626
+ linkTarget: null,
627
+ error: {
628
+ code: 'CODEX_HOME_UNUSABLE',
629
+ reason: 'codex-home-link-unresolvable',
630
+ message: 'the Codex home is a link whose target cannot be resolved (missing or dangling)',
631
+ },
632
+ };
633
+ }
634
+ const realInfo = await inspectDirectory(resolved).catch(() => ({ kind: 'unknown' }));
635
+ if (realInfo.kind !== 'directory') {
636
+ return {
637
+ selected: selectedPath,
638
+ real: resolved,
639
+ linked: true,
640
+ linkTarget: linkedInfo.target ?? null,
641
+ error: {
642
+ code: 'CODEX_HOME_UNUSABLE',
643
+ reason: 'codex-home-target-not-a-directory',
644
+ message: 'the Codex home link does not point at a real directory, so nothing was read or written',
645
+ },
646
+ };
647
+ }
648
+ return {
649
+ selected: selectedPath,
650
+ real: resolved,
651
+ linked: true,
652
+ linkTarget: linkedInfo.target ?? null,
653
+ error: null,
654
+ };
655
+ }
656
+
470
657
  /**
471
658
  * Read the shipped agent template.
472
659
  * @returns {Promise<string>} template text exactly as published.
@@ -975,8 +1162,11 @@ export async function inspectCodexBoundary(home) {
975
1162
  const agentsPath = join(home, 'agents');
976
1163
  const homeInfo = await inspectDirectory(home);
977
1164
  if (homeInfo.kind === 'link') {
978
- // The agents path is resolved through the link; do not inspect it further, and
979
- // do not report whether anything below it exists.
1165
+ // Reached only when the caller did NOT pin the root first (a direct caller of this
1166
+ // public helper). The installer's own entries resolve a selected root link through
1167
+ // {@link pinCodexHome} and then inspect the REAL directory, so this branch keeps the
1168
+ // conservative answer for an unpinned call: below an unresolved link nothing is
1169
+ // written and nothing below it is even inspected.
980
1170
  return { blocked: true, link: 'codex-home', unknown: false, home: homeInfo, agents: { kind: 'unchecked' } };
981
1171
  }
982
1172
  const agentsInfo = homeInfo.kind === 'directory'
@@ -2054,21 +2244,33 @@ export async function readCodexStatus({
2054
2244
  version = null,
2055
2245
  hostNode = null,
2056
2246
  } = {}) {
2057
- const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2247
+ const selected = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2248
+ // A link/JUNCTION at the ROOT is the operator's own layout and is allowed: it is pinned
2249
+ // to its real directory ONCE here, and everything below reads, classifies and writes
2250
+ // against that real path.
2251
+ const pinned = await pinCodexHome(selected);
2252
+ const home = pinned.real;
2058
2253
  const agentPath = join(home, 'agents', AGENT_FILENAME);
2059
2254
  const configPath = join(home, 'config.toml');
2060
2255
  const packageVersionValue = version ?? await readPackageVersion();
2061
2256
  const template = renderAgentFile(await readAgentTemplate(), packageVersionValue);
2062
2257
  // The boundary first: a link at the Codex home or at `agents` means the agent path
2063
2258
  // does not name a file this plugin may touch, whatever `lstat` would say about it.
2064
- const boundary = await inspectCodexBoundary(home);
2259
+ const boundary = pinned.error === null
2260
+ ? await inspectCodexBoundary(home)
2261
+ // A root that could not be pinned is refused WITHOUT inspecting anything below it:
2262
+ // the alias does not lead to a usable directory, so there is nothing to classify and
2263
+ // nothing may be created through it.
2264
+ : { blocked: true, link: null, unknown: false, home: { kind: 'link' }, agents: { kind: 'unchecked' } };
2065
2265
  const agent = boundary.blocked
2066
2266
  ? {
2067
2267
  state: AGENT_STATES.conflict,
2068
2268
  present: false,
2069
2269
  reason: boundary.unknown === true
2070
2270
  ? 'boundary-unverified'
2071
- : boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link',
2271
+ // A selected ROOT that could not be pinned reports WHY (missing target, not a
2272
+ // directory) instead of the generic "is a link".
2273
+ : (pinned.error?.reason ?? (boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link')),
2072
2274
  contents: null,
2073
2275
  }
2074
2276
  : await readAgentState(agentPath, template);
@@ -2153,7 +2355,13 @@ export async function readCodexStatus({
2153
2355
  }
2154
2356
 
2155
2357
  return buildStatus({
2358
+ // The REAL directory every action uses, plus the selected spelling so an operator who
2359
+ // configured a junction can recognise it. `codexHome` is always the path actually
2360
+ // read and written.
2156
2361
  codexHome: home,
2362
+ codexHomeSelected: pinned.selected,
2363
+ codexHomeLinked: pinned.linked,
2364
+ codexHomeLinkTarget: pinned.linkTarget,
2157
2365
  agentPath,
2158
2366
  configPath,
2159
2367
  packageVersionValue,
@@ -2189,6 +2397,9 @@ function defaultDiscoveryPath(env) {
2189
2397
  */
2190
2398
  function buildStatus({
2191
2399
  codexHome,
2400
+ codexHomeSelected = null,
2401
+ codexHomeLinked = false,
2402
+ codexHomeLinkTarget = null,
2192
2403
  agentPath,
2193
2404
  configPath,
2194
2405
  packageVersionValue,
@@ -2208,6 +2419,11 @@ function buildStatus({
2208
2419
  const mcpOk = mcp.state === MCP_STATES.configured;
2209
2420
  return {
2210
2421
  codexHome,
2422
+ // The selected spelling and whether it was a root link, kept beside the REAL path so
2423
+ // an operator who configured a junction recognises the answer without guessing.
2424
+ codexHomeSelected: codexHomeSelected ?? codexHome,
2425
+ codexHomeLinked: codexHomeLinked === true,
2426
+ codexHomeLinkTarget,
2211
2427
  packageVersion: packageVersionValue,
2212
2428
  // Whether the two directories that bound every write are real directories. A link
2213
2429
  // at either one is a stable diagnosis, not an installation state: install, repair
@@ -2389,10 +2605,28 @@ export async function runCodexAction(action, {
2389
2605
  if (codexHome !== null && (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome))) {
2390
2606
  throw new CodexInstallError('CODEX_HOME_INVALID', 'the Codex home must be an absolute path');
2391
2607
  }
2392
- const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2608
+ const selected = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2609
+ // Pin the selected root ONCE, so install, repair and remove all act on the same real
2610
+ // directory even if the alias is retargeted while this action runs.
2611
+ const pinned = await pinCodexHome(selected);
2612
+ const home = pinned.real;
2613
+ /**
2614
+ * Attach the SELECTED spelling to a status document read from the pinned real path.
2615
+ *
2616
+ * `readCodexStatus` was handed the real directory, so its own "selected" is that
2617
+ * directory; the operator's spelling comes from here.
2618
+ * @param {object} status - status read against `home`.
2619
+ * @returns {object} the same status, annotated.
2620
+ */
2621
+ const annotated = (status) => ({
2622
+ ...status,
2623
+ codexHomeSelected: pinned.selected,
2624
+ codexHomeLinked: pinned.linked,
2625
+ codexHomeLinkTarget: pinned.linkTarget,
2626
+ });
2393
2627
  if (action === 'status') {
2394
2628
  const status = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2395
- return { action, changed: [], refused: [], status };
2629
+ return { action, changed: [], refused: [], status: annotated(status) };
2396
2630
  }
2397
2631
 
2398
2632
  const before = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
@@ -2409,7 +2643,7 @@ export async function runCodexAction(action, {
2409
2643
  : null;
2410
2644
  if (linked !== null) {
2411
2645
  refused.push(linked);
2412
- return { action, changed, refused, status: before };
2646
+ return { action, changed, refused, status: annotated(before) };
2413
2647
  }
2414
2648
 
2415
2649
  if (action === 'remove') {
@@ -2425,7 +2659,7 @@ export async function runCodexAction(action, {
2425
2659
  }
2426
2660
 
2427
2661
  const status = await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2428
- return { action, changed, refused, status };
2662
+ return { action, changed, refused, status: annotated(status) };
2429
2663
  }
2430
2664
 
2431
2665
  /**
@@ -2486,8 +2720,14 @@ export async function refreshKnownAgentTemplate(options = {}) {
2486
2720
  if (codexHome !== null && (typeof codexHome !== 'string' || codexHome.trim() === '' || !isAbsolute(codexHome))) {
2487
2721
  throw new CodexInstallError('CODEX_HOME_INVALID', 'the Codex home must be an absolute path');
2488
2722
  }
2489
- const home = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2490
- const before = plan ?? await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode });
2723
+ // A selected ROOT link is allowed and pinned here too, so a startup refresh migrates the
2724
+ // same real directory the settings page installs into (and a `plan` captured by the
2725
+ // caller was itself read through the same pin).
2726
+ const selectedRoot = codexHome === null ? resolveCodexHome({ env }) : requireCodexHome(codexHome);
2727
+ const home = (await pinCodexHome(selectedRoot)).real;
2728
+ const before = (plan === undefined || plan === null)
2729
+ ? await readCodexStatus({ codexHome: home, env, discoveryFile, version, hostNode })
2730
+ : plan;
2491
2731
  const changed = [];
2492
2732
  const refused = [];
2493
2733
 
@@ -12,16 +12,72 @@ const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
12
12
  const KEYLIKE_PATTERN = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
13
13
  const ASSIGNMENT_PATTERN = /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
14
14
  /**
15
- * A profile key embedded in a *directory* name, the shape this repository's own
16
- * workspace has (`…/Local/Temp/dsh-SoexNz/…`, which held the local user id). It is
17
- * masked because it identifies an account; only a path-shaped key is matched, so
18
- * an ordinary hyphenated word in prose is untouched.
15
+ * A per-user profile directory under the OPERATING SYSTEM'S temporary root.
16
+ *
17
+ * The observed shape is `%TEMP%\dsh-VG1MVl\dsh-delegate-test-…` (and on some hosts
18
+ * `~/.cache/dsh-SoexNz/…`): the platform points `TEMP` at a per-profile directory
19
+ * whose six-character suffix is the account key. That suffix is exactly what is
20
+ * masked, and the marker is `dsh-`/`profile-` plus six characters plus digits —
21
+ * nothing more.
22
+ *
23
+ * Two earlier versions were wrong in opposite directions, so the rule is stated
24
+ * around what is PROVABLE instead of around what looks unusual:
25
+ *
26
+ * * the first masked every `dsh-`/`profile-` segment with six alphanumerics, so an
27
+ * ordinary repository or package name — this product's own `dsh-delegate` and its
28
+ * installed `dsh-taskbridge` — was rewritten in every published path;
29
+ * * the second tried to tell a profile key from a word by case and digit shape. That
30
+ * is a guess: a repository may be `v2-tools`, a package `dsh-Bridge2`. A masked
31
+ * path proves nothing, so a guess that fires wrongly disables continuation.
32
+ *
33
+ * A profile key is only recognised where it actually lives: directly under a
34
+ * temporary root ({@link TEMPORARY_ROOT}), or anywhere in such a path. An ordinary
35
+ * segment elsewhere, whatever its case or digits, keeps its readable path.
19
36
  *
20
37
  * The preceding separator is captured and re-emitted so a Windows path keeps its
21
- * backslash. A single combined character class would normalise `\` to `/` and
22
- * change a path an operator is trying to recognise.
38
+ * backslash; a combined character class would normalise `\` to `/`.
39
+ */
40
+ const PROFILE_SEGMENT = String.raw`(?:dsh|profile)-[A-Za-z0-9]{6}(?![A-Za-z0-9])`;
41
+
42
+ /**
43
+ * The directory names the platform's temporary root is reached through.
44
+ *
45
+ * `temp` is the Windows/POSIX temporary root; `tmp` and `.cache` cover the POSIX and
46
+ * per-user-cache spellings. They are matched as complete, case-insensitive segment
47
+ * names, so they anchor WHERE a profile key may appear rather than being redacted.
23
48
  */
24
- const PATH_KEY_PATTERN = /([\\/])(?:dsh|profile)-[A-Za-z0-9]{6,}(?=[\\/]|$)/g;
49
+ const TEMPORARY_ROOT = String.raw`(?:temp|tmp|\.cache)`;
50
+
51
+ /**
52
+ * Mask a profile key only where it is provably one: as a segment directly under a
53
+ * temporary root. Both the separator and the temp-root segment are kept; only the key
54
+ * is replaced, so `…\Temp\dsh-VG1MVl\work` becomes `…\Temp\<mask>\work` and the
55
+ * platform's own separator survives (`/home/u/.cache/<mask>/x`).
56
+ *
57
+ * Two anchored forms, because a stored path may start at the root or continue through
58
+ * it:
59
+ *
60
+ * 1. `…<sep><temp><sep><key>…` — separators are captured and re-emitted verbatim;
61
+ * 2. `^<temp><sep><key>…` — the path begins with the root, e.g. `temp\dsh-abc123\x`.
62
+ */
63
+ const PATH_KEY_PATTERN = new RegExp(
64
+ [
65
+ String.raw`([\\/])`,
66
+ `(${TEMPORARY_ROOT})`,
67
+ String.raw`([\\/])`,
68
+ // The placeholder itself is never rewritten again, so redaction is idempotent.
69
+ String.raw`(?!(?:dsh|profile)-mask)`,
70
+ PROFILE_SEGMENT,
71
+ String.raw`(?=[\\/]|$)`,
72
+ ].join(''),
73
+ 'gi',
74
+ );
75
+
76
+ /** The same rule for a path that STARTS with the temporary root (`temp\dsh-abc123\x`). */
77
+ const LEADING_TEMP_KEY_PATTERN = new RegExp(
78
+ [`^(${TEMPORARY_ROOT})`, String.raw`([\\/])`, PROFILE_SEGMENT, String.raw`(?=[\\/]|$)`].join(''),
79
+ 'i',
80
+ );
25
81
 
26
82
  /** What {@link PATH_KEY_PATTERN} replaces the identifying segment with. */
27
83
  const PATH_KEY_SEGMENT = 'masks-user-profile-segment';
@@ -100,10 +156,15 @@ export function redactText(text) {
100
156
  .replace(BEARER_PATTERN, `Bearer ${MASK}`)
101
157
  .replace(KEYLIKE_PATTERN, MASK)
102
158
  .replace(ASSIGNMENT_PATTERN, (_match, name) => `${name}=${MASK}`)
103
- // Last, and path-anchored: a workspace path reported by a preflight is shown
104
- // so an operator can recognise the repository, but the per-profile segment of
105
- // the platform temp path is not theirs to see.
106
- .replace(PATH_KEY_PATTERN, (_match, separator) => `${separator}${PATH_KEY_SEGMENT}`);
159
+ // Last, and path-anchored: an ordinary workspace path is shown so an operator can
160
+ // recognise the repository; only a profile key under a temporary root is masked.
161
+ // The leading-root form runs first. Each pass re-emits every separator and the
162
+ // temp-root segment it matched, so a POSIX `.cache` path keeps its `/`.
163
+ .replace(LEADING_TEMP_KEY_PATTERN, (_match, root, separator) => `${root}${separator}${PATH_KEY_SEGMENT}`)
164
+ .replace(
165
+ PATH_KEY_PATTERN,
166
+ (_match, before, root, separator) => `${before}${root}${separator}${PATH_KEY_SEGMENT}`,
167
+ );
107
168
  }
108
169
 
109
170
  /**
@@ -36,8 +36,16 @@ export const EXECUTION_PREFIX = '/dsh-delegate/x';
36
36
  */
37
37
  export const MAX_OBSERVE_WAIT_MS = 25_000;
38
38
 
39
- /** Body fields `POST /tasks/observe` accepts. Everything else is refused. */
40
- const OBSERVE_FIELDS = Object.freeze(['taskId', 'waitMs']);
39
+ /**
40
+ * Body fields `POST /tasks/observe` accepts. Everything else is refused.
41
+ *
42
+ * `ackFailureEventId` acknowledges one delivered repeated-failure reminder by its
43
+ * exact `eventId`; the acknowledgment result is echoed back as `failureAck`. It is
44
+ * OPTIONAL and was added after 1.5.0: a caller that does not send it gets exactly
45
+ * the old body shape and the old answer shape (no `failureAck` field), and its
46
+ * absence never acknowledges anything.
47
+ */
48
+ const OBSERVE_FIELDS = Object.freeze(['taskId', 'waitMs', 'ackFailureEventId']);
41
49
 
42
50
  /**
43
51
  * Build a node-style handler for the execution plane.
@@ -66,6 +74,9 @@ export function createExecutionHandler(deps) {
66
74
  // The switch gate below applies to it exactly as it does to a submission,
67
75
  // because a decision is an authorization exercise like any other.
68
76
  ['POST /tasks/permission', decidePermission],
77
+ // The ordinary-question answer. Registered beside the permission route because it is
78
+ // the other way a paused native tool call resumes.
79
+ ['POST /tasks/question', answerQuestion],
69
80
  // The commander's DELIVERY REVIEW of one finished task. It is the only write that
70
81
  // records `hostAcceptance`, and it is narrow on purpose: it decides no permission,
71
82
  // changes no switch/provider/model/isolation/credential, merges no file and creates
@@ -118,12 +129,13 @@ export function createExecutionHandler(deps) {
118
129
 
119
130
  let connection;
120
131
  if (deps.engine.authorizationMode === 'switch') {
121
- // Only the two AUTHORIZING verbs need the switch: a submission creates work and a
122
- // decision releases a paused call. A delivery REVIEW is not one of them: it records
123
- // a conclusion about an already-finished result, so it stays answerable with the
132
+ // Only the AUTHORIZING verbs need the switch: a submission creates work, and a
133
+ // decision (a permission decision or a question answer) releases a paused call
134
+ // whose work already exists. A delivery REVIEW is not one of them: it records a
135
+ // conclusion about an already-finished result, so it stays answerable with the
124
136
  // switch off, exactly like reading or cancelling a task. Reads, cancel and
125
137
  // preflight are equally unaffected.
126
- const gated = key === 'POST /tasks' || key === 'POST /tasks/permission';
138
+ const gated = key === 'POST /tasks' || key === 'POST /tasks/permission' || key === 'POST /tasks/question';
127
139
  if (gated && deps.engine.posture().authorized !== true) {
128
140
  sendJson(res, 403, {
129
141
  ok: false,
@@ -217,13 +229,22 @@ async function submitTask({ req, res, connection, deps }) {
217
229
  const continueFromTaskId = body.continueFromTaskId === undefined || body.continueFromTaskId === null
218
230
  ? undefined
219
231
  : body.continueFromTaskId;
232
+ // The Agent Teams decision travels as the commander's own field and is folded into the
233
+ // existing overrides channel (the engine's per-task choice path). A non-boolean is
234
+ // refused here rather than reaching the engine's sanitiser as a coercible value.
235
+ if (body.agentTeams !== undefined && typeof body.agentTeams !== 'boolean') {
236
+ throw new HttpError(400, 'AGENT_TEAMS_INVALID', 'agentTeams must be a boolean');
237
+ }
238
+ const overrides = body.agentTeams === undefined
239
+ ? body.overrides
240
+ : { ...(body.overrides ?? {}), agentTeams: body.agentTeams };
220
241
  if (deps.engine.authorizationMode === 'switch') {
221
242
  const task = await deps.engine.start({
222
243
  connectionId: connection.connectionId,
223
244
  workspacePath: body.workspacePath,
224
245
  prompt: body.prompt,
225
246
  ...(body.title === undefined ? {} : { title: body.title }),
226
- overrides: body.overrides,
247
+ overrides,
227
248
  ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
228
249
  });
229
250
  sendJson(res, 202, { ok: true, task });
@@ -241,7 +262,7 @@ async function submitTask({ req, res, connection, deps }) {
241
262
  workspacePath: body.workspacePath,
242
263
  prompt: body.prompt,
243
264
  ...(body.title === undefined ? {} : { title: body.title }),
244
- overrides: body.overrides,
265
+ overrides,
245
266
  ...(continueFromTaskId === undefined ? {} : { continueFromTaskId }),
246
267
  });
247
268
  sendJson(res, 202, { ok: true, task });
@@ -339,7 +360,74 @@ async function decidePermission({ req, res, connection, deps }) {
339
360
  sendJson(res, 200, { ok: true, ...result });
340
361
  }
341
362
 
342
- /** Body fields `POST /tasks/review` accepts. Everything else is refused. */
363
+ /**
364
+ * Answer one pending QUESTION for one owned task.
365
+ *
366
+ * Shaped like the permission route and for the same reasons: the connection identity is
367
+ * the authenticated one (never the body's), so a caller can only answer its OWN task, and
368
+ * the body is validated here because any local caller can reach this route. The answer
369
+ * batch itself is validated by the bridge against the questions the worker actually
370
+ * asked — this route only checks the shape, so a malformed batch is refused early.
371
+ *
372
+ * Nothing here can grant access: the engine settles a paused native question, and any
373
+ * widening still needs `POST /tasks/permission`.
374
+ * @param {object} context - `req`, `res`, `connection`, `deps`.
375
+ * @returns {Promise<void>} resolves after the answer is sent.
376
+ */
377
+ async function answerQuestion({ req, res, connection, deps }) {
378
+ const body = await readJsonBody(req);
379
+ // A closed top-level field set: an unknown field (including a transport CONTROL field
380
+ // such as `waitAfterAnswer`, which the MCP server strips and the route must not accept)
381
+ // is refused rather than silently dropped, so a caller never believes it changed
382
+ // something here.
383
+ for (const key of Object.keys(body)) {
384
+ if (!['taskId', 'requestId', 'answers'].includes(key)) {
385
+ throw new HttpError(400, 'QUESTION_FIELD_UNKNOWN', `unknown field ${JSON.stringify(key)}`);
386
+ }
387
+ }
388
+ if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
389
+ throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
390
+ }
391
+ if (typeof body.requestId !== 'string' || body.requestId.trim() === '') {
392
+ throw new HttpError(400, 'QUESTION_REQUEST_ID_REQUIRED', 'requestId is required');
393
+ }
394
+ if (!Array.isArray(body.answers)) {
395
+ throw new HttpError(400, 'QUESTION_ANSWERS_REQUIRED', 'answers must be an array');
396
+ }
397
+ for (const answer of body.answers) {
398
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
399
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'each answer must be an object');
400
+ }
401
+ // Each answer is a closed shape too: an unknown field is refused, not ignored.
402
+ const allowed = ['id', 'selected', 'custom'];
403
+ for (const key of Object.keys(answer)) {
404
+ if (!allowed.includes(key)) {
405
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', `unknown answer field ${JSON.stringify(key)}`);
406
+ }
407
+ }
408
+ if (typeof answer.id !== 'string' || answer.id === '') {
409
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'each answer needs a question id');
410
+ }
411
+ if (answer.selected !== undefined && (!Array.isArray(answer.selected)
412
+ || answer.selected.some((label) => typeof label !== 'string'))) {
413
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'selected must be an array of labels');
414
+ }
415
+ if (answer.custom !== undefined && answer.custom !== null && typeof answer.custom !== 'string') {
416
+ throw new HttpError(400, 'QUESTION_ANSWER_INVALID', 'custom must be a string when present');
417
+ }
418
+ }
419
+ const result = await deps.engine.decideQuestion({
420
+ connectionId: connection.connectionId,
421
+ taskId: body.taskId,
422
+ requestId: body.requestId,
423
+ answers: body.answers.map((answer) => ({
424
+ id: answer.id,
425
+ selected: Array.isArray(answer.selected) ? [...answer.selected] : [],
426
+ ...(typeof answer.custom === 'string' ? { custom: answer.custom } : {}),
427
+ })),
428
+ });
429
+ sendJson(res, 200, { ok: true, ...result });
430
+ }
343
431
  const REVIEW_FIELDS = Object.freeze(['taskId', 'decision', 'note']);
344
432
 
345
433
  /**
@@ -448,6 +536,19 @@ async function observeTask({ req, res, connection, deps }) {
448
536
  if (typeof body.taskId !== 'string' || body.taskId.trim() === '') {
449
537
  throw new HttpError(400, 'TASK_ID_REQUIRED', 'taskId is required');
450
538
  }
539
+ // An ack is optional; when the field is present it must be a NON-EMPTY bounded
540
+ // string so a caller cannot smuggle an unbounded or meaningless value into the
541
+ // engine. A wrong type, an empty string, or an overlong value is REFUSED — the
542
+ // same policy the MCP schema enforces (`minLength: 1`) — never silently treated
543
+ // as absent. A `null` ack is read as "the field was not supplied" (the JSON way
544
+ // to omit an optional value), which keeps old callers unaffected.
545
+ let ackFailureEventId;
546
+ if (body.ackFailureEventId !== undefined && body.ackFailureEventId !== null) {
547
+ if (typeof body.ackFailureEventId !== 'string' || body.ackFailureEventId === '' || body.ackFailureEventId.length > 64) {
548
+ throw new HttpError(400, 'OBSERVE_ACK_INVALID', 'ackFailureEventId must be a non-empty string of at most 64 characters');
549
+ }
550
+ ackFailureEventId = body.ackFailureEventId;
551
+ }
451
552
  let waitMs = MAX_OBSERVE_WAIT_MS;
452
553
  if (body.waitMs !== undefined && body.waitMs !== null) {
453
554
  if (!Number.isInteger(body.waitMs) || body.waitMs < 0) {
@@ -463,6 +564,9 @@ async function observeTask({ req, res, connection, deps }) {
463
564
  connectionId: connection.connectionId,
464
565
  waitMs,
465
566
  signal: abandonment.signal,
567
+ // The exact event the caller observed and now acknowledges. Ownership is
568
+ // proven by the connection above; the eventId binding is the engine's.
569
+ ...(ackFailureEventId === undefined ? {} : { ackFailureEventId }),
466
570
  });
467
571
  // The reader left while the engine was settling: there is nothing to answer,
468
572
  // and writing to a closed response would only throw into the refusal path.
@@ -475,7 +579,17 @@ async function observeTask({ req, res, connection, deps }) {
475
579
  // request can never be decided, so this must not enter a wait loop.
476
580
  const observation = await historyObservation(deps, body.taskId, connection);
477
581
  if (abandonment.abandoned() || !isWritable(res)) return;
478
- sendJson(res, 200, { ok: true, wait: { waitMs, waitedMs: 0, activitySinceWait: false }, ...observation });
582
+ // A settled stored task has no live reminder to acknowledge; an ack against one
583
+ // is answered honestly as not-acknowledged instead of pretending success.
584
+ const failureAck = ackFailureEventId === undefined
585
+ ? undefined
586
+ : { acknowledged: false, eventId: ackFailureEventId, reason: 'no-pending' };
587
+ sendJson(res, 200, {
588
+ ok: true,
589
+ wait: { waitMs, waitedMs: 0, activitySinceWait: false },
590
+ ...observation,
591
+ ...(failureAck === undefined ? {} : { failureAck }),
592
+ });
479
593
  } finally {
480
594
  abandonment.dispose();
481
595
  }