@oyasmi/pipiclaw 0.9.2-beta.4 → 0.9.2-beta.6

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 (76) hide show
  1. package/dist/agent/channel-runner.d.ts +32 -1
  2. package/dist/agent/channel-runner.js +112 -12
  3. package/dist/agent/context-budget.d.ts +9 -1
  4. package/dist/agent/context-budget.js +11 -5
  5. package/dist/agent/job-manager.d.ts +2 -0
  6. package/dist/agent/job-manager.js +1 -0
  7. package/dist/agent/session-events.js +2 -22
  8. package/dist/agent/types.d.ts +2 -1
  9. package/dist/channel/channel-context.d.ts +4 -0
  10. package/dist/channel/channel-event.d.ts +39 -0
  11. package/dist/channel/channel-event.js +11 -1
  12. package/dist/channel/project-scope-store.js +6 -11
  13. package/dist/channel/store.d.ts +7 -0
  14. package/dist/commands/catalog.d.ts +1 -1
  15. package/dist/memory/bootstrap.js +3 -5
  16. package/dist/memory/candidates.js +2 -4
  17. package/dist/memory/files.d.ts +0 -1
  18. package/dist/memory/files.js +6 -9
  19. package/dist/memory/maintenance-state.js +4 -0
  20. package/dist/runtime/bootstrap.d.ts +12 -6
  21. package/dist/runtime/bootstrap.js +144 -75
  22. package/dist/runtime/delivery.js +1 -0
  23. package/dist/runtime/dingtalk.d.ts +59 -3
  24. package/dist/runtime/dingtalk.js +192 -83
  25. package/dist/runtime/inbound-media.d.ts +60 -0
  26. package/dist/runtime/inbound-media.js +95 -0
  27. package/dist/runtime/task-driver.d.ts +7 -0
  28. package/dist/runtime/task-driver.js +23 -44
  29. package/dist/runtime/task-migration.d.ts +11 -0
  30. package/dist/runtime/task-migration.js +11 -0
  31. package/dist/security/command-guard.js +1 -3
  32. package/dist/security/config.d.ts +1 -1
  33. package/dist/security/config.js +8 -32
  34. package/dist/security/path-guard.js +1 -6
  35. package/dist/security/project-scope.js +1 -3
  36. package/dist/settings.d.ts +2 -2
  37. package/dist/settings.js +13 -20
  38. package/dist/shared/atomic-file.d.ts +2 -3
  39. package/dist/shared/atomic-file.js +8 -9
  40. package/dist/shared/config-diagnostic.d.ts +21 -0
  41. package/dist/shared/config-diagnostic.js +32 -0
  42. package/dist/shared/numeric.d.ts +7 -0
  43. package/dist/shared/numeric.js +19 -0
  44. package/dist/shared/text-utils.d.ts +10 -0
  45. package/dist/shared/text-utils.js +16 -0
  46. package/dist/shared/types.d.ts +23 -0
  47. package/dist/shared/types.js +12 -0
  48. package/dist/shared/with-timeout.d.ts +3 -0
  49. package/dist/shared/with-timeout.js +8 -0
  50. package/dist/subagents/discovery.d.ts +7 -7
  51. package/dist/subagents/discovery.js +27 -59
  52. package/dist/subagents/runs.d.ts +6 -0
  53. package/dist/subagents/runs.js +11 -0
  54. package/dist/subagents/tool.js +195 -128
  55. package/dist/subagents/workspace-lease.js +1 -3
  56. package/dist/tasks/control.d.ts +2 -0
  57. package/dist/tasks/control.js +2 -0
  58. package/dist/tasks/ledger.d.ts +0 -9
  59. package/dist/tasks/ledger.js +92 -158
  60. package/dist/tools/config.d.ts +1 -1
  61. package/dist/tools/config.js +9 -46
  62. package/dist/tools/skill.js +1 -3
  63. package/dist/tools/truncate.js +24 -28
  64. package/dist/tui/app.js +1 -1
  65. package/dist/web/config.js +3 -15
  66. package/examples/sub-agents/builder.md +1 -1
  67. package/examples/sub-agents/documenter.md +1 -1
  68. package/examples/sub-agents/explorer.md +4 -4
  69. package/examples/sub-agents/git-committer.md +4 -4
  70. package/examples/sub-agents/log-sifter.md +3 -3
  71. package/examples/sub-agents/planner.md +1 -1
  72. package/examples/sub-agents/reviewer.md +1 -1
  73. package/examples/sub-agents/worker.md +1 -1
  74. package/package.json +3 -2
  75. package/dist/agent/index.d.ts +0 -2
  76. package/dist/agent/index.js +0 -1
@@ -24,6 +24,12 @@ export type RunMutates = "read" | "write";
24
24
  * rule for numeric thresholds.
25
25
  */
26
26
  export declare const SYNC_GRACE_MS = 120000;
27
+ /**
28
+ * Effective sync grace window. A test-only env override (`PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS`)
29
+ * lets the deterministic e2e layer exercise the detached-settlement + completion-wake path
30
+ * (spec 048 A14/A15/A16) without a multi-minute wait; production always uses `SYNC_GRACE_MS`.
31
+ */
32
+ export declare function resolveSyncGraceMs(override?: number): number;
27
33
  /** D10.2: per-channel cap on concurrently running delegation runs. */
28
34
  export declare const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
29
35
  /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
@@ -20,6 +20,17 @@ import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLe
20
20
  * rule for numeric thresholds.
21
21
  */
22
22
  export const SYNC_GRACE_MS = 120_000;
23
+ /**
24
+ * Effective sync grace window. A test-only env override (`PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS`)
25
+ * lets the deterministic e2e layer exercise the detached-settlement + completion-wake path
26
+ * (spec 048 A14/A15/A16) without a multi-minute wait; production always uses `SYNC_GRACE_MS`.
27
+ */
28
+ export function resolveSyncGraceMs(override) {
29
+ if (override !== undefined)
30
+ return override;
31
+ const env = Number(process.env.PIPICLAW_TEST_SUBAGENT_SYNC_GRACE_MS);
32
+ return Number.isFinite(env) && env > 0 ? env : SYNC_GRACE_MS;
33
+ }
23
34
  /** D10.2: per-channel cap on concurrently running delegation runs. */
24
35
  export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
25
36
  /** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
@@ -16,7 +16,8 @@ import { splitH1Sections } from "../shared/markdown-sections.js";
16
16
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
17
17
  import { RecoverableToolError } from "../shared/recoverable-error.js";
18
18
  import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
19
- import { createEmptyUsageTotals } from "../shared/types.js";
19
+ import { addUsage, createEmptyUsageTotals } from "../shared/types.js";
20
+ import { sleepUnref } from "../shared/with-timeout.js";
20
21
  import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
21
22
  import { readStoredTask } from "../tasks/store.js";
22
23
  import { writeVerificationAttestation } from "../tasks/verification.js";
@@ -24,7 +25,7 @@ import { describeToolCall } from "../tools/presentation.js";
24
25
  import { buildToolSet } from "../tools/registry.js";
25
26
  import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
26
27
  import { launchExternalRun } from "./external/run.js";
27
- import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
28
+ import { getSubAgentRunManager, resolveSyncGraceMs } from "./runs.js";
28
29
  import { resolveVerificationOutcome } from "./verification-outcome.js";
29
30
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
30
31
  /** Shared by both invocation surfaces (spec 046, D2.1). */
@@ -224,6 +225,29 @@ function getLastAssistantMessage(messages) {
224
225
  function formatStatus(agentName, text) {
225
226
  return `Subagent ${agentName}: ${text}`;
226
227
  }
228
+ /**
229
+ * The "still running, don't wait or re-dispatch" reply shared by every dispatch path that hands
230
+ * back a placeholder instead of the run's own result: external always takes this path (D2); an
231
+ * internal run takes it once the sync grace window elapses (D2/D7). Only the runtime label
232
+ * (`external, <harness>` vs `internal, async`) differs between the two.
233
+ */
234
+ function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
235
+ return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
236
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
237
+ "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.");
238
+ }
239
+ /**
240
+ * `buildContextualBlocks` shared by the external dispatch path and `runToCompletion`'s internal
241
+ * one (spec 040 gap closed post-review): context injection is an enhancement, not a
242
+ * precondition, so a failure here degrades to no context blocks rather than failing a dispatch
243
+ * that would otherwise have run fine.
244
+ */
245
+ async function resolveContextualBlocks(task, config, options, currentModel) {
246
+ return buildContextualBlocks(task, config, options, currentModel).catch((error) => {
247
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
248
+ return [];
249
+ });
250
+ }
227
251
  function buildFailureText(config, reason, lastAssistantText) {
228
252
  const trimmedLastText = lastAssistantText.trim();
229
253
  if (!trimmedLastText) {
@@ -456,28 +480,28 @@ function filterToolsByName(allTools, names) {
456
480
  const allowed = new Set(names);
457
481
  return allTools.filter((tool) => allowed.has(tool.name));
458
482
  }
459
- function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict, extras) {
483
+ function createDetails(input) {
460
484
  return {
461
- agent: config.name,
462
- source: config.source,
463
- model: extras?.modelOverride ?? formatModelReference(config.model),
464
- tools: extras?.toolsOverride ?? [...config.tools],
465
- turns,
466
- toolCalls,
467
- durationMs,
468
- failed,
469
- failureReason,
485
+ agent: input.config.name,
486
+ source: input.config.source,
487
+ model: input.modelOverride ?? formatModelReference(input.config.model),
488
+ tools: input.toolsOverride ?? [...input.config.tools],
489
+ turns: input.turns,
490
+ toolCalls: input.toolCalls,
491
+ durationMs: input.durationMs,
492
+ failed: input.failed ?? false,
493
+ failureReason: input.failureReason,
470
494
  usage: {
471
- ...usage,
472
- cost: { ...usage.cost },
495
+ ...input.usage,
496
+ cost: { ...input.usage.cost },
473
497
  },
474
- runId: runContext.runId,
475
- purpose: runContext.purpose,
476
- taskId: runContext.taskId,
477
- verificationVerdict,
478
- artifactDir: runContext.artifactDir,
479
- resultTruncated: extras?.resultTruncated ?? false,
480
- dispatched: extras?.dispatched,
498
+ runId: input.runContext.runId,
499
+ purpose: input.runContext.purpose,
500
+ taskId: input.runContext.taskId,
501
+ verificationVerdict: input.verificationVerdict,
502
+ artifactDir: input.runContext.artifactDir,
503
+ resultTruncated: input.resultTruncated ?? false,
504
+ dispatched: input.dispatched,
481
505
  };
482
506
  }
483
507
  /**
@@ -486,12 +510,6 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
486
510
  * jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
487
511
  * effect of stopping something else.
488
512
  */
489
- function sleep(ms) {
490
- return new Promise((resolve) => {
491
- const timer = setTimeout(resolve, ms);
492
- timer.unref?.();
493
- });
494
- }
495
513
  /**
496
514
  * Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
497
515
  * after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
@@ -530,83 +548,112 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
530
548
  leaseKey = lease.leaseKey;
531
549
  }
532
550
  if (config.runtime === "external") {
533
- if (!config.harness) {
534
- releaseWorkspaceLease(leaseKey, runContext.runId);
535
- throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
536
- }
537
- let launchResult;
538
- try {
539
- // D9/T5: external roles get the same task envelope internal workers do — runtime
540
- // paths, injected context blocks, and (for purpose=verify) the verification
541
- // protocol — rather than the raw task text (spec 040 gap closed post-review).
542
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
543
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
544
- // beats failing a dispatch that would otherwise have run fine.
545
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
546
- return [];
547
- });
548
- const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
549
- launchResult = await launchExternalRun({
550
- runId: runContext.runId,
551
- channelId: options.runtimeContext.channelId,
552
- channelDir: options.channelDir,
553
- label: runLabel,
554
- agent: config.name,
555
- source: config.source,
556
- harness: config.harness,
557
- command: config.command ?? "",
558
- shell: config.shell,
559
- env: config.env,
560
- externalModelRef: config.externalModelRef,
561
- thinkingLevel: config.thinkingLevel,
562
- maxWallTimeSec: config.maxWallTimeSec,
563
- systemPrompt: config.systemPrompt,
564
- task: envelopedTask,
565
- workingDirectory: runContext.workingDirectory,
566
- artifactDir: runContext.artifactDir,
567
- purpose: runContext.purpose,
568
- taskId: runContext.taskId,
569
- leaseKey,
570
- mutates: config.mutates,
571
- roleFingerprint: externalRoleFingerprint(config),
572
- workspaceDir: options.workspaceDir,
573
- securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
574
- });
575
- }
576
- catch (error) {
577
- // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
578
- // every failure past that point settles the run itself and already released this
579
- // lease (spec 042 D2/D5), so this catch must not release it a second time.
580
- releaseWorkspaceLease(leaseKey, runContext.runId);
581
- throw error;
582
- }
583
- // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
584
- // "[Dispatched]" placeholder the model would wait on forever — two of the three
585
- // failure kinds never used to announce at all. `settle()` already released the lease.
586
- if (!launchResult.ok) {
587
- if (launchResult.kind === "missing-binary") {
588
- throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
589
- }
590
- throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
551
+ return dispatchExternalRun({ options, currentModel, config, runLabel, runContext, leaseKey, params });
552
+ }
553
+ return dispatchInternalRun({
554
+ options,
555
+ currentModel,
556
+ config,
557
+ runLabel,
558
+ mutatesNote,
559
+ runContext,
560
+ leaseKey,
561
+ params,
562
+ onUpdate,
563
+ runManager,
564
+ });
565
+ }
566
+ /**
567
+ * The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
568
+ * process and always returns the "[Dispatched]" placeholder — external's sync grace window is
569
+ * always 0, so there is no inline-wait branch to share with the internal path.
570
+ */
571
+ async function dispatchExternalRun(input) {
572
+ const { options, currentModel, config, runLabel, runContext, leaseKey, params } = input;
573
+ if (!config.harness) {
574
+ releaseWorkspaceLease(leaseKey, runContext.runId);
575
+ throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
576
+ }
577
+ let launchResult;
578
+ try {
579
+ // D9/T5: external roles get the same task envelope internal workers do — runtime
580
+ // paths, injected context blocks, and (for purpose=verify) the verification
581
+ // protocol — rather than the raw task text (spec 040 gap closed post-review).
582
+ const contextualBlocks = await resolveContextualBlocks(params.task, config, options, currentModel);
583
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
584
+ launchResult = await launchExternalRun({
585
+ runId: runContext.runId,
586
+ channelId: options.runtimeContext.channelId,
587
+ channelDir: options.channelDir,
588
+ label: runLabel,
589
+ agent: config.name,
590
+ source: config.source,
591
+ harness: config.harness,
592
+ command: config.command ?? "",
593
+ shell: config.shell,
594
+ env: config.env,
595
+ externalModelRef: config.externalModelRef,
596
+ thinkingLevel: config.thinkingLevel,
597
+ maxWallTimeSec: config.maxWallTimeSec,
598
+ systemPrompt: config.systemPrompt,
599
+ task: envelopedTask,
600
+ workingDirectory: runContext.workingDirectory,
601
+ artifactDir: runContext.artifactDir,
602
+ purpose: runContext.purpose,
603
+ taskId: runContext.taskId,
604
+ leaseKey,
605
+ mutates: config.mutates,
606
+ roleFingerprint: externalRoleFingerprint(config),
607
+ workspaceDir: options.workspaceDir,
608
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
609
+ });
610
+ }
611
+ catch (error) {
612
+ // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
613
+ // every failure past that point settles the run itself and already released this
614
+ // lease (spec 042 D2/D5), so this catch must not release it a second time.
615
+ releaseWorkspaceLease(leaseKey, runContext.runId);
616
+ throw error;
617
+ }
618
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
619
+ // "[Dispatched]" placeholder the model would wait on forever — two of the three
620
+ // failure kinds never used to announce at all. `settle()` already released the lease.
621
+ if (!launchResult.ok) {
622
+ if (launchResult.kind === "missing-binary") {
623
+ throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
591
624
  }
592
- // D2: external's sync grace window is always 0 — always the dispatched placeholder,
593
- // never an inline wait. The run keeps going in the background and wakes the channel.
594
- return {
595
- content: [
596
- {
597
- type: "text",
598
- text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
599
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
600
- "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.",
601
- },
602
- ],
603
- details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
604
- dispatched: true,
605
- modelOverride: config.externalModelRef ?? "unknown",
606
- toolsOverride: [],
607
- }),
608
- };
625
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
609
626
  }
627
+ // D2: external's sync grace window is always 0 — always the dispatched placeholder,
628
+ // never an inline wait. The run keeps going in the background and wakes the channel.
629
+ return {
630
+ content: [
631
+ {
632
+ type: "text",
633
+ text: buildDispatchedText(runContext.runId, config.name, `external, ${config.harness}`, runContext.workingDirectory),
634
+ },
635
+ ],
636
+ details: createDetails({
637
+ config,
638
+ runContext,
639
+ usage: createEmptyUsageTotals(),
640
+ turns: 0,
641
+ toolCalls: 0,
642
+ durationMs: 0,
643
+ dispatched: true,
644
+ modelOverride: config.externalModelRef ?? "unknown",
645
+ toolsOverride: [],
646
+ }),
647
+ };
648
+ }
649
+ /**
650
+ * The `runtime: internal` half of `dispatchSubAgentRun` (spec 046, D2.5): registers the durable
651
+ * run record, runs the worker (with budget enforcement and the D6 convergence turn), settles it,
652
+ * and returns either its real result or — once the sync grace window elapses — a "[Dispatched]"
653
+ * placeholder while the run keeps going in the background.
654
+ */
655
+ async function dispatchInternalRun(input) {
656
+ const { options, currentModel, config, runLabel, mutatesNote, runContext, leaseKey, params, onUpdate, runManager } = input;
610
657
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
611
658
  let apiKey;
612
659
  try {
@@ -673,7 +720,16 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
673
720
  lastUpdateText = nextText;
674
721
  onUpdate?.({
675
722
  content: [{ type: "text", text: nextText }],
676
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
723
+ details: createDetails({
724
+ config,
725
+ runContext,
726
+ usage,
727
+ turns: assistantTurns,
728
+ toolCalls,
729
+ durationMs: Date.now() - startedAt,
730
+ failed: Boolean(failureReason),
731
+ failureReason,
732
+ }),
677
733
  });
678
734
  };
679
735
  let wallClockTimer;
@@ -721,17 +777,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
721
777
  unsubscribe = worker.subscribe((event) => {
722
778
  if (event.type === "message_end" && isAssistantMessage(event.message)) {
723
779
  assistantTurns++;
724
- const messageUsage = event.message.usage;
725
- usage.input += messageUsage.input;
726
- usage.output += messageUsage.output;
727
- usage.cacheRead += messageUsage.cacheRead;
728
- usage.cacheWrite += messageUsage.cacheWrite;
729
- usage.total += messageUsage.totalTokens;
730
- usage.cost.input += messageUsage.cost.input;
731
- usage.cost.output += messageUsage.cost.output;
732
- usage.cost.cacheRead += messageUsage.cost.cacheRead;
733
- usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
734
- usage.cost.total += messageUsage.cost.total;
780
+ addUsage(usage, event.message.usage);
735
781
  }
736
782
  if (event.type === "tool_execution_start") {
737
783
  toolCalls++;
@@ -792,12 +838,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
792
838
  */
793
839
  async function runToCompletion() {
794
840
  try {
795
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
796
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
797
- // beats failing a dispatch that would otherwise have run fine.
798
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
799
- return [];
800
- });
841
+ const contextualBlocks = await resolveContextualBlocks(params.task, config, options, currentModel);
801
842
  if (externallyCancelled) {
802
843
  failureReason = failureReason || "Cancelled by request.";
803
844
  }
@@ -930,7 +971,18 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
930
971
  text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
931
972
  },
932
973
  ],
933
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { resultTruncated: finalized.truncated }),
974
+ details: createDetails({
975
+ config,
976
+ runContext,
977
+ usage,
978
+ turns: assistantTurns,
979
+ toolCalls,
980
+ durationMs,
981
+ failed: true,
982
+ failureReason: effectiveFailureReason,
983
+ verificationVerdict,
984
+ resultTruncated: finalized.truncated,
985
+ }),
934
986
  },
935
987
  settleInput: {
936
988
  ...baseSettleInput,
@@ -951,7 +1003,16 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
951
1003
  text: mutatesNote + (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
952
1004
  },
953
1005
  ],
954
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { resultTruncated: finalized.truncated }),
1006
+ details: createDetails({
1007
+ config,
1008
+ runContext,
1009
+ usage,
1010
+ turns: assistantTurns,
1011
+ toolCalls,
1012
+ durationMs,
1013
+ verificationVerdict,
1014
+ resultTruncated: finalized.truncated,
1015
+ }),
955
1016
  },
956
1017
  settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
957
1018
  };
@@ -973,12 +1034,12 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
973
1034
  // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
974
1035
  // clock budget) before degrading to a "still running" placeholder. The run itself keeps
975
1036
  // executing either way — only the *return* differs.
976
- const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
1037
+ const graceMs = Math.min(config.maxWallTimeSec * 1000, resolveSyncGraceMs(options.syncGraceMs));
977
1038
  const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
978
1039
  ok: false,
979
1040
  error: error instanceof Error ? error : new Error(String(error)),
980
1041
  }));
981
- const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
1042
+ const raceResult = await Promise.race([outcomePromise, sleepUnref(graceMs).then(() => "timed-out")]);
982
1043
  if (raceResult !== "timed-out") {
983
1044
  runManager.clearCancelHandle(runContext.runId);
984
1045
  if (!raceResult.ok) {
@@ -1004,12 +1065,18 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
1004
1065
  {
1005
1066
  type: "text",
1006
1067
  text: mutatesNote +
1007
- `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
1008
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
1009
- "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.",
1068
+ buildDispatchedText(runContext.runId, config.name, "internal, async", runContext.workingDirectory),
1010
1069
  },
1011
1070
  ],
1012
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, false, undefined, undefined, { dispatched: true }),
1071
+ details: createDetails({
1072
+ config,
1073
+ runContext,
1074
+ usage,
1075
+ turns: assistantTurns,
1076
+ toolCalls,
1077
+ durationMs: Date.now() - startedAt,
1078
+ dispatched: true,
1079
+ }),
1013
1080
  };
1014
1081
  }
1015
1082
  export function createSubAgentTool(options) {
@@ -1,8 +1,6 @@
1
1
  import { realpathSync } from "node:fs";
2
+ import { withTrailingSlash } from "../shared/text-utils.js";
2
3
  const leases = new Map();
3
- function withTrailingSlash(path) {
4
- return path.endsWith("/") ? path : `${path}/`;
5
- }
6
4
  function pathsConflict(a, b) {
7
5
  return (a === b ||
8
6
  withTrailingSlash(a).startsWith(withTrailingSlash(b)) ||
@@ -41,6 +41,8 @@ export declare function parseTaskControl(raw: string): TaskControl;
41
41
  * Migration-only reader for v1/v2 control blocks. `parseTaskControl` no longer accepts them —
42
42
  * this exists so `migrateLegacyTaskState` (spec 029, D6's window, closed here) can durably
43
43
  * upgrade an old file the one time it is encountered. Nothing else may call this.
44
+ *
45
+ * RETIRE AT v0.9.3 — see the header comment in `../runtime/task-migration.js`.
44
46
  */
45
47
  export declare function parseLegacyTaskControl(raw: string): TaskControl;
46
48
  /** Reset state that is meaningful only within one recurring task cycle. */
@@ -72,6 +72,8 @@ export function parseTaskControl(raw) {
72
72
  * Migration-only reader for v1/v2 control blocks. `parseTaskControl` no longer accepts them —
73
73
  * this exists so `migrateLegacyTaskState` (spec 029, D6's window, closed here) can durably
74
74
  * upgrade an old file the one time it is encountered. Nothing else may call this.
75
+ *
76
+ * RETIRE AT v0.9.3 — see the header comment in `../runtime/task-migration.js`.
75
77
  */
76
78
  export function parseLegacyTaskControl(raw) {
77
79
  let value;
@@ -176,15 +176,6 @@ export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: numb
176
176
  export declare function extractTaskTitle(content: string, fallbackId: string): string;
177
177
  export declare function hasTaskHeading(content: string, names: readonly string[]): boolean;
178
178
  export declare function missingStandardTaskSections(content: string): string[];
179
- /**
180
- * Unchecked Markdown acceptance boxes under the DoD section, plus a synthetic
181
- * entry when DoD has content but no checkbox syntax at all.
182
- *
183
- * Without the "no checklist items" case, a DoD written as prose or a numbered
184
- * list (no `- [ ]` anywhere) makes this function return an empty array —
185
- * indistinguishable from "everything is checked" — which would silently let
186
- * `task_close outcome=complete` through with nothing ever actually verified.
187
- */
188
179
  export declare function uncheckedTaskAcceptanceItems(content: string): string[];
189
180
  /**
190
181
  * Count of checkbox items (checked or not) under the DoD heading, for cross-referencing a Plan