@oyasmi/pipiclaw 0.9.2-beta.3 → 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 (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -5,6 +5,7 @@ import { Agent } from "@earendil-works/pi-agent-core";
5
5
  import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
6
6
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
7
7
  import { Type } from "typebox";
8
+ import { getChannelDir } from "../channel/channel-paths.js";
8
9
  import * as log from "../log.js";
9
10
  import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
10
11
  import { recallRelevantMemory } from "../memory/recall.js";
@@ -15,7 +16,8 @@ import { splitH1Sections } from "../shared/markdown-sections.js";
15
16
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
16
17
  import { RecoverableToolError } from "../shared/recoverable-error.js";
17
18
  import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
18
- import { createEmptyUsageTotals } from "../shared/types.js";
19
+ import { addUsage, createEmptyUsageTotals } from "../shared/types.js";
20
+ import { sleepUnref } from "../shared/with-timeout.js";
19
21
  import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
20
22
  import { readStoredTask } from "../tasks/store.js";
21
23
  import { writeVerificationAttestation } from "../tasks/verification.js";
@@ -23,7 +25,7 @@ import { describeToolCall } from "../tools/presentation.js";
23
25
  import { buildToolSet } from "../tools/registry.js";
24
26
  import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
25
27
  import { launchExternalRun } from "./external/run.js";
26
- import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
28
+ import { getSubAgentRunManager, resolveSyncGraceMs } from "./runs.js";
27
29
  import { resolveVerificationOutcome } from "./verification-outcome.js";
28
30
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
29
31
  /** Shared by both invocation surfaces (spec 046, D2.1). */
@@ -223,6 +225,29 @@ function getLastAssistantMessage(messages) {
223
225
  function formatStatus(agentName, text) {
224
226
  return `Subagent ${agentName}: ${text}`;
225
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
+ }
226
251
  function buildFailureText(config, reason, lastAssistantText) {
227
252
  const trimmedLastText = lastAssistantText.trim();
228
253
  if (!trimmedLastText) {
@@ -358,7 +383,7 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
358
383
  `Runtime context:`,
359
384
  `- Workspace root: ${runtimeContext.workspaceDir}`,
360
385
  `- Channel id: ${runtimeContext.channelId}`,
361
- `- Channel directory: ${runtimeContext.workspaceDir}/${runtimeContext.channelId}`,
386
+ `- Channel directory: ${getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId)}`,
362
387
  `- Working directory: ${runContext.workingDirectory}`,
363
388
  `- Artifact directory: ${runContext.artifactDir}`,
364
389
  `- Your configured role: ${config.name}`,
@@ -371,7 +396,7 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
371
396
  }
372
397
  lines.push("", `Task:`, taskText);
373
398
  if (runContext.purpose === "verify") {
374
- const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
399
+ const taskPath = join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`);
375
400
  lines.push("", buildVerificationProtocol(taskPath));
376
401
  }
377
402
  return lines.join("\n");
@@ -455,28 +480,28 @@ function filterToolsByName(allTools, names) {
455
480
  const allowed = new Set(names);
456
481
  return allTools.filter((tool) => allowed.has(tool.name));
457
482
  }
458
- function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict, extras) {
483
+ function createDetails(input) {
459
484
  return {
460
- agent: config.name,
461
- source: config.source,
462
- model: extras?.modelOverride ?? formatModelReference(config.model),
463
- tools: extras?.toolsOverride ?? [...config.tools],
464
- turns,
465
- toolCalls,
466
- durationMs,
467
- failed,
468
- 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,
469
494
  usage: {
470
- ...usage,
471
- cost: { ...usage.cost },
495
+ ...input.usage,
496
+ cost: { ...input.usage.cost },
472
497
  },
473
- runId: runContext.runId,
474
- purpose: runContext.purpose,
475
- taskId: runContext.taskId,
476
- verificationVerdict,
477
- artifactDir: runContext.artifactDir,
478
- resultTruncated: extras?.resultTruncated ?? false,
479
- 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,
480
505
  };
481
506
  }
482
507
  /**
@@ -485,12 +510,6 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
485
510
  * jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
486
511
  * effect of stopping something else.
487
512
  */
488
- function sleep(ms) {
489
- return new Promise((resolve) => {
490
- const timer = setTimeout(resolve, ms);
491
- timer.unref?.();
492
- });
493
- }
494
513
  /**
495
514
  * Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
496
515
  * after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
@@ -529,83 +548,112 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
529
548
  leaseKey = lease.leaseKey;
530
549
  }
531
550
  if (config.runtime === "external") {
532
- if (!config.harness) {
533
- releaseWorkspaceLease(leaseKey, runContext.runId);
534
- throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
535
- }
536
- let launchResult;
537
- try {
538
- // D9/T5: external roles get the same task envelope internal workers do — runtime
539
- // paths, injected context blocks, and (for purpose=verify) the verification
540
- // protocol — rather than the raw task text (spec 040 gap closed post-review).
541
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
542
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
543
- // beats failing a dispatch that would otherwise have run fine.
544
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
545
- return [];
546
- });
547
- const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
548
- launchResult = await launchExternalRun({
549
- runId: runContext.runId,
550
- channelId: options.runtimeContext.channelId,
551
- channelDir: options.channelDir,
552
- label: runLabel,
553
- agent: config.name,
554
- source: config.source,
555
- harness: config.harness,
556
- command: config.command ?? "",
557
- shell: config.shell,
558
- env: config.env,
559
- externalModelRef: config.externalModelRef,
560
- thinkingLevel: config.thinkingLevel,
561
- maxWallTimeSec: config.maxWallTimeSec,
562
- systemPrompt: config.systemPrompt,
563
- task: envelopedTask,
564
- workingDirectory: runContext.workingDirectory,
565
- artifactDir: runContext.artifactDir,
566
- purpose: runContext.purpose,
567
- taskId: runContext.taskId,
568
- leaseKey,
569
- mutates: config.mutates,
570
- roleFingerprint: externalRoleFingerprint(config),
571
- workspaceDir: options.workspaceDir,
572
- securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
573
- });
574
- }
575
- catch (error) {
576
- // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
577
- // every failure past that point settles the run itself and already released this
578
- // lease (spec 042 D2/D5), so this catch must not release it a second time.
579
- releaseWorkspaceLease(leaseKey, runContext.runId);
580
- throw error;
581
- }
582
- // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
583
- // "[Dispatched]" placeholder the model would wait on forever — two of the three
584
- // failure kinds never used to announce at all. `settle()` already released the lease.
585
- if (!launchResult.ok) {
586
- if (launchResult.kind === "missing-binary") {
587
- 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.`);
588
- }
589
- 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.`);
590
624
  }
591
- // D2: external's sync grace window is always 0 — always the dispatched placeholder,
592
- // never an inline wait. The run keeps going in the background and wakes the channel.
593
- return {
594
- content: [
595
- {
596
- type: "text",
597
- text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
598
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
599
- "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.",
600
- },
601
- ],
602
- details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
603
- dispatched: true,
604
- modelOverride: config.externalModelRef ?? "unknown",
605
- toolsOverride: [],
606
- }),
607
- };
625
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
608
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;
609
657
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
610
658
  let apiKey;
611
659
  try {
@@ -672,7 +720,16 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
672
720
  lastUpdateText = nextText;
673
721
  onUpdate?.({
674
722
  content: [{ type: "text", text: nextText }],
675
- 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
+ }),
676
733
  });
677
734
  };
678
735
  let wallClockTimer;
@@ -720,17 +777,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
720
777
  unsubscribe = worker.subscribe((event) => {
721
778
  if (event.type === "message_end" && isAssistantMessage(event.message)) {
722
779
  assistantTurns++;
723
- const messageUsage = event.message.usage;
724
- usage.input += messageUsage.input;
725
- usage.output += messageUsage.output;
726
- usage.cacheRead += messageUsage.cacheRead;
727
- usage.cacheWrite += messageUsage.cacheWrite;
728
- usage.total += messageUsage.totalTokens;
729
- usage.cost.input += messageUsage.cost.input;
730
- usage.cost.output += messageUsage.cost.output;
731
- usage.cost.cacheRead += messageUsage.cost.cacheRead;
732
- usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
733
- usage.cost.total += messageUsage.cost.total;
780
+ addUsage(usage, event.message.usage);
734
781
  }
735
782
  if (event.type === "tool_execution_start") {
736
783
  toolCalls++;
@@ -791,12 +838,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
791
838
  */
792
839
  async function runToCompletion() {
793
840
  try {
794
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
795
- // Context injection is an enhancement, not a precondition -- degrading to no context blocks
796
- // beats failing a dispatch that would otherwise have run fine.
797
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
798
- return [];
799
- });
841
+ const contextualBlocks = await resolveContextualBlocks(params.task, config, options, currentModel);
800
842
  if (externallyCancelled) {
801
843
  failureReason = failureReason || "Cancelled by request.";
802
844
  }
@@ -929,7 +971,18 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
929
971
  text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
930
972
  },
931
973
  ],
932
- 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
+ }),
933
986
  },
934
987
  settleInput: {
935
988
  ...baseSettleInput,
@@ -950,7 +1003,16 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
950
1003
  text: mutatesNote + (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
951
1004
  },
952
1005
  ],
953
- 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
+ }),
954
1016
  },
955
1017
  settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
956
1018
  };
@@ -972,12 +1034,12 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
972
1034
  // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
973
1035
  // clock budget) before degrading to a "still running" placeholder. The run itself keeps
974
1036
  // executing either way — only the *return* differs.
975
- const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
1037
+ const graceMs = Math.min(config.maxWallTimeSec * 1000, resolveSyncGraceMs(options.syncGraceMs));
976
1038
  const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
977
1039
  ok: false,
978
1040
  error: error instanceof Error ? error : new Error(String(error)),
979
1041
  }));
980
- const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
1042
+ const raceResult = await Promise.race([outcomePromise, sleepUnref(graceMs).then(() => "timed-out")]);
981
1043
  if (raceResult !== "timed-out") {
982
1044
  runManager.clearCancelHandle(runContext.runId);
983
1045
  if (!raceResult.ok) {
@@ -1003,12 +1065,18 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
1003
1065
  {
1004
1066
  type: "text",
1005
1067
  text: mutatesNote +
1006
- `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
1007
- "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
1008
- "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),
1009
1069
  },
1010
1070
  ],
1011
- 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
+ }),
1012
1080
  };
1013
1081
  }
1014
1082
  export function createSubAgentTool(options) {
@@ -1044,7 +1112,7 @@ export function createSubAgentInlineTool(options) {
1044
1112
  return {
1045
1113
  name: "subagent_inline",
1046
1114
  label: "subagent_inline",
1047
- description: "Delegate a task to a one-off inline sub-agent when no configured role fits — define its systemPrompt (plus optional tools/model) here instead of a role file. Prefer `subagent` with a configured `agent` when one already covers this work. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
1115
+ description: "Advanced fallback only, not the default: use `subagent` first whenever any configured role in the workspace `sub-agents/` can do the work. `subagent` is the normal role-based path: pass its `agent` and complete `task`; the role file supplies the tools, model, budget and context policy. Use `subagent_inline` only when no configured role is suitable. It is a raw one-shot meta-executor, not a shorthand for `subagent`: there is no role file to supply those settings. Build a complete valid inline call yourself — `task` and `systemPrompt` are required; choose valid values for any needed `tools`, `model`, `effort`, `context`, `thinkingLevel`, `mutates`, `workingDirectory`, `purpose` and `taskId` fields. Do not send a partial role-style payload or choose this tool just because it is available. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
1048
1116
  parameters: subagentInlineSchema,
1049
1117
  execute: async (_toolCallId, params, signal, onUpdate) => {
1050
1118
  if (signal?.aborted) {
@@ -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