@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.2

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 (83) hide show
  1. package/dist/agent/channel-runner.d.ts +3 -0
  2. package/dist/agent/channel-runner.js +9 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/job-manager.d.ts +11 -3
  6. package/dist/agent/job-manager.js +63 -6
  7. package/dist/agent/prompt/sections.js +46 -7
  8. package/dist/agent/prompt/types.d.ts +9 -0
  9. package/dist/agent/session-events.js +7 -42
  10. package/dist/agent/types.d.ts +4 -0
  11. package/dist/playbooks/agent-delegation.md +46 -21
  12. package/dist/playbooks/runtime-orientation.md +2 -2
  13. package/dist/runtime/bootstrap.d.ts +38 -0
  14. package/dist/runtime/bootstrap.js +167 -14
  15. package/dist/runtime/dingtalk.d.ts +9 -0
  16. package/dist/runtime/dingtalk.js +3 -0
  17. package/dist/runtime/durable-dispatch.d.ts +4 -0
  18. package/dist/runtime/durable-dispatch.js +16 -0
  19. package/dist/runtime/store.d.ts +7 -0
  20. package/dist/runtime/subagent-commands.d.ts +15 -0
  21. package/dist/runtime/subagent-commands.js +122 -0
  22. package/dist/runtime/task-commands.js +5 -1
  23. package/dist/security/logger.js +10 -1
  24. package/dist/security/types.d.ts +17 -1
  25. package/dist/shared/host-process.d.ts +21 -0
  26. package/dist/shared/host-process.js +44 -0
  27. package/dist/shared/jsonl-appender.d.ts +2 -0
  28. package/dist/shared/jsonl-appender.js +25 -13
  29. package/dist/shared/shell-words.d.ts +9 -0
  30. package/dist/shared/shell-words.js +52 -0
  31. package/dist/subagents/discovery.d.ts +42 -1
  32. package/dist/subagents/discovery.js +302 -69
  33. package/dist/subagents/external/claude-code.d.ts +2 -0
  34. package/dist/subagents/external/claude-code.js +152 -0
  35. package/dist/subagents/external/codex-cli.d.ts +2 -0
  36. package/dist/subagents/external/codex-cli.js +133 -0
  37. package/dist/subagents/external/exec.d.ts +2 -0
  38. package/dist/subagents/external/exec.js +38 -0
  39. package/dist/subagents/external/harness.d.ts +102 -0
  40. package/dist/subagents/external/harness.js +76 -0
  41. package/dist/subagents/external/registry.d.ts +2 -0
  42. package/dist/subagents/external/registry.js +11 -0
  43. package/dist/subagents/external/run.d.ts +49 -0
  44. package/dist/subagents/external/run.js +266 -0
  45. package/dist/subagents/runs.d.ts +230 -0
  46. package/dist/subagents/runs.js +615 -0
  47. package/dist/subagents/tool.d.ts +26 -0
  48. package/dist/subagents/tool.js +464 -182
  49. package/dist/subagents/workspace-lease.d.ts +36 -0
  50. package/dist/subagents/workspace-lease.js +48 -0
  51. package/dist/tasks/artifact-subject.js +50 -2
  52. package/dist/tasks/control.d.ts +12 -0
  53. package/dist/tasks/control.js +20 -0
  54. package/dist/tasks/store.d.ts +21 -0
  55. package/dist/tasks/store.js +80 -0
  56. package/dist/tasks/verification.d.ts +8 -0
  57. package/dist/tasks/verification.js +10 -2
  58. package/dist/tools/index.d.ts +1 -1
  59. package/dist/tools/index.js +12 -1
  60. package/dist/tools/registry.js +1 -0
  61. package/dist/tools/subagent-manage.d.ts +23 -0
  62. package/dist/tools/subagent-manage.js +154 -0
  63. package/dist/tools/tool-details.d.ts +1 -1
  64. package/dist/tui/app.js +2 -0
  65. package/dist/tui/commands.d.ts +1 -0
  66. package/dist/tui/commands.js +2 -0
  67. package/dist/tui/turn-controller.d.ts +1 -0
  68. package/dist/tui/turn-controller.js +1 -0
  69. package/dist/usage/ledger.d.ts +13 -0
  70. package/dist/usage/ledger.js +15 -2
  71. package/dist/usage/render.js +22 -0
  72. package/examples/sub-agents/README.md +61 -12
  73. package/examples/sub-agents/builder-hard.md +45 -0
  74. package/examples/sub-agents/builder.md +41 -0
  75. package/examples/sub-agents/documenter.md +53 -0
  76. package/examples/sub-agents/log-sifter.md +43 -0
  77. package/examples/sub-agents/planner.md +42 -0
  78. package/examples/sub-agents/reviewer.md +38 -38
  79. package/examples/sub-agents/scout.md +31 -0
  80. package/examples/sub-agents/verifier.md +32 -36
  81. package/examples/sub-agents/worker.md +36 -0
  82. package/package.json +1 -1
  83. package/examples/sub-agents/researcher.md +0 -41
@@ -1,10 +1,11 @@
1
1
  import { existsSync, statSync } from "node:fs";
2
- import { mkdir, writeFile } from "node:fs/promises";
2
+ import { mkdir } from "node:fs/promises";
3
3
  import { isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
5
5
  import { 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 * as log from "../log.js";
8
9
  import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
9
10
  import { recallRelevantMemory } from "../memory/recall.js";
10
11
  import { formatModelReference } from "../models/utils.js";
@@ -12,12 +13,15 @@ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
12
13
  import { formatLocalTime } from "../shared/local-time.js";
13
14
  import { splitH1Sections } from "../shared/markdown-sections.js";
14
15
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
15
- import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
16
+ import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
16
17
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
17
18
  import { readStoredTask } from "../tasks/store.js";
18
19
  import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
19
20
  import { buildToolSet } from "../tools/registry.js";
20
- import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
21
+ import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
22
+ import { launchExternalRun } from "./external/run.js";
23
+ import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
24
+ import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
21
25
  const subagentSchema = Type.Object({
22
26
  label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
23
27
  agent: Type.Optional(Type.String({ description: "Name of a configured sub-agent from workspaceDir/sub-agents/" })),
@@ -198,13 +202,14 @@ function parseArtifactMarker(output) {
198
202
  * whether it fits the reply budget. What comes back to the parent is capped at
199
203
  * MAX_SUBAGENT_RESULT_UNITS; a reply over budget is truncated with a pointer to the file
200
204
  * a chatty sub-agent can no longer blow out the parent's context.
205
+ *
206
+ * The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
207
+ * runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
208
+ * This function only needs the path, to point at it.
201
209
  */
202
- async function finalizeSubAgentOutput(runContext, finalText, returns) {
210
+ function finalizeSubAgentOutput(runContext, finalText, returns) {
203
211
  const trimmed = finalText.trim();
204
212
  const outputPath = join(runContext.artifactDir, "output.md");
205
- if (trimmed) {
206
- await writeFile(outputPath, finalText, "utf-8");
207
- }
208
213
  let artifactPath;
209
214
  if (returns === "artifact" && trimmed) {
210
215
  const filename = parseArtifactMarker(trimmed);
@@ -234,19 +239,22 @@ async function finalizeSubAgentOutput(runContext, finalText, returns) {
234
239
  * received — a stray write/edit here would race the shared memory serial queue
235
240
  * (channel-maintenance-queue) and silently corrupt durable memory.
236
241
  */
237
- function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
242
+ function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
238
243
  const protectedPaths = [
239
244
  getChannelMemoryPath(channelDir),
240
245
  getChannelHistoryPath(channelDir),
241
246
  getChannelSessionPath(channelDir),
242
247
  ];
243
- return {
248
+ // The role directory gets the same structural denial (spec 040, D8.1): a sub-agent's write/edit
249
+ // tools are exactly as capable of writing a self-authorizing `runtime: external` role file as
250
+ // the main agent's are.
251
+ return withSubAgentsDirWriteDeny({
244
252
  ...securityConfig,
245
253
  pathGuard: {
246
254
  ...securityConfig.pathGuard,
247
255
  writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
248
256
  },
249
- };
257
+ }, workspaceDir);
250
258
  }
251
259
  /**
252
260
  * Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
@@ -254,7 +262,7 @@ function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
254
262
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
255
263
  */
256
264
  function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
257
- const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir);
265
+ const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
258
266
  return buildToolSet({
259
267
  executor,
260
268
  securityConfig,
@@ -401,17 +409,17 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
401
409
  resultTruncated: extras?.resultTruncated ?? false,
402
410
  };
403
411
  }
404
- function linkAbortSignals(parentSignal, childController) {
405
- if (!parentSignal) {
406
- return () => { };
407
- }
408
- const abortChild = () => childController.abort(parentSignal.reason);
409
- if (parentSignal.aborted) {
410
- abortChild();
411
- return () => { };
412
- }
413
- parentSignal.addEventListener("abort", abortChild, { once: true });
414
- return () => parentSignal.removeEventListener("abort", abortChild);
412
+ /**
413
+ * A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
414
+ * `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
415
+ * jobs. Stopping a run is now an explicit decision (`subagent_manage op=cancel`), not a side
416
+ * effect of stopping something else.
417
+ */
418
+ function sleep(ms) {
419
+ return new Promise((resolve) => {
420
+ const timer = setTimeout(resolve, ms);
421
+ timer.unref?.();
422
+ });
415
423
  }
416
424
  export function createSubAgentTool(options) {
417
425
  return {
@@ -420,6 +428,9 @@ export function createSubAgentTool(options) {
420
428
  description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no configured agent is required. You may instead name a configured sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Execution budgets come from `effort` presets and context injection from `context`; both have safe defaults, so state the task well and leave them alone unless you have a reason. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
421
429
  parameters: subagentSchema,
422
430
  execute: async (_toolCallId, params, signal, onUpdate) => {
431
+ if (signal?.aborted) {
432
+ throw new Error("Sub-agent aborted");
433
+ }
423
434
  const availableModels = options.getAvailableModels();
424
435
  const discovery = options.getSubAgentDiscovery?.() ?? {
425
436
  directory: `${options.workspaceDir}/sub-agents`,
@@ -438,17 +449,155 @@ export function createSubAgentTool(options) {
438
449
  const config = invocation.config;
439
450
  const returns = params.returns ?? "text";
440
451
  const runContext = await prepareRunContext(_toolCallId, params, options);
452
+ // D9: an independent verifier checks against a target that isn't moving under it. It
453
+ // never takes a lease itself, but a target with an active write lease is refused up
454
+ // front — cheaper than explaining afterward why the attestation is worthless.
455
+ if (runContext.purpose === "verify") {
456
+ // A role that admits it writes cannot also be the checker, and `exec` has no protocol
457
+ // terminal to prove it even ran to completion — both are hard "no"s, not advisories.
458
+ if (config.mutates === "write") {
459
+ throw new Error(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
460
+ }
461
+ if (config.runtime === "external" && config.harness === "exec") {
462
+ throw new Error(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
463
+ }
464
+ const holder = findWorkspaceLeaseHolder(runContext.workingDirectory);
465
+ if (holder) {
466
+ throw new Error(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
467
+ }
468
+ }
469
+ // Admission: a write-mutating run takes an exclusive workspace lease before it is even
470
+ // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
471
+ // Read runs and purpose=verify never take one. Shared by both runtimes.
472
+ let leaseKey;
473
+ if (config.mutates === "write" && runContext.purpose !== "verify") {
474
+ const lease = acquireWorkspaceLease({
475
+ runId: runContext.runId,
476
+ channelId: options.runtimeContext.channelId,
477
+ workingDirectory: runContext.workingDirectory,
478
+ });
479
+ if (!lease.ok) {
480
+ throw new Error(formatWorkspaceLeaseConflict(lease.heldBy));
481
+ }
482
+ leaseKey = lease.leaseKey;
483
+ }
484
+ if (config.runtime === "external") {
485
+ if (!config.harness) {
486
+ releaseWorkspaceLease(leaseKey);
487
+ throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
488
+ }
489
+ try {
490
+ await launchExternalRun({
491
+ runId: runContext.runId,
492
+ channelId: options.runtimeContext.channelId,
493
+ channelDir: options.channelDir,
494
+ label: params.label,
495
+ agent: config.name,
496
+ source: config.source,
497
+ harness: config.harness,
498
+ command: config.command ?? "",
499
+ shell: config.shell,
500
+ env: config.env,
501
+ externalModelRef: config.externalModelRef,
502
+ thinkingLevel: config.thinkingLevel,
503
+ maxWallTimeSec: config.maxWallTimeSec,
504
+ systemPrompt: config.systemPrompt,
505
+ task: params.task,
506
+ workingDirectory: runContext.workingDirectory,
507
+ artifactDir: runContext.artifactDir,
508
+ purpose: runContext.purpose,
509
+ taskId: runContext.taskId,
510
+ leaseKey,
511
+ mutates: config.mutates,
512
+ workspaceDir: options.workspaceDir,
513
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
514
+ });
515
+ }
516
+ catch (error) {
517
+ releaseWorkspaceLease(leaseKey);
518
+ throw error;
519
+ }
520
+ // D2: external's sync grace window is always 0 — always the dispatched placeholder,
521
+ // never an inline wait. The run keeps going in the background and wakes the channel.
522
+ return {
523
+ content: [
524
+ {
525
+ type: "text",
526
+ text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
527
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
528
+ "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
529
+ },
530
+ ],
531
+ details: {
532
+ kind: "subagent",
533
+ agent: config.name,
534
+ source: config.source,
535
+ model: config.externalModelRef ?? "unknown",
536
+ tools: [],
537
+ turns: 0,
538
+ toolCalls: 0,
539
+ durationMs: 0,
540
+ failed: false,
541
+ usage: createEmptyUsageTotals(),
542
+ runId: runContext.runId,
543
+ purpose: runContext.purpose,
544
+ taskId: runContext.taskId,
545
+ artifactDir: runContext.artifactDir,
546
+ resultTruncated: false,
547
+ dispatched: true,
548
+ },
549
+ };
550
+ }
441
551
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
442
- const apiKey = await options.resolveApiKey(config.model);
552
+ let apiKey;
553
+ try {
554
+ apiKey = await options.resolveApiKey(config.model);
555
+ }
556
+ catch (error) {
557
+ releaseWorkspaceLease(leaseKey);
558
+ throw error;
559
+ }
443
560
  const startedAt = Date.now();
444
561
  const usage = createEmptyUsageTotals();
445
562
  let assistantTurns = 0;
446
563
  let toolCalls = 0;
447
564
  let failureReason;
448
- /** Set alongside failureReason only for the three self-inflicted budget aborts, never for a parent-driven stop. */
565
+ /** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
449
566
  let budgetExceeded = false;
567
+ /** Set only by the `subagent_manage op=cancel` handle registered below — a real stop, unlike a budget abort. */
568
+ let externallyCancelled = false;
569
+ /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
570
+ let detached = false;
450
571
  let lastUpdateText = "";
572
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
573
+ try {
574
+ await runManager.register({
575
+ runId: runContext.runId,
576
+ channelId: options.runtimeContext.channelId,
577
+ runtime: "internal",
578
+ agent: config.name,
579
+ label: params.label,
580
+ source: config.source,
581
+ tools: [...config.tools],
582
+ model: formatModelReference(config.model),
583
+ purpose: runContext.purpose,
584
+ taskId: runContext.taskId,
585
+ workingDirectory: runContext.workingDirectory,
586
+ artifactDir: runContext.artifactDir,
587
+ leaseKey,
588
+ });
589
+ }
590
+ catch (error) {
591
+ // Until the durable running record exists, setup still owns the lease. A channel/host
592
+ // admission rejection or required persist failure must leave no invisible writer lock.
593
+ releaseWorkspaceLease(leaseKey);
594
+ throw error;
595
+ }
451
596
  const emitUpdate = (text) => {
597
+ // Once detached, execute() has already returned to the SDK; nothing is listening
598
+ // for further progress on this (from its view, finished) tool call.
599
+ if (detached)
600
+ return;
452
601
  const nextText = text.trim();
453
602
  if (!nextText || nextText === lastUpdateText) {
454
603
  return;
@@ -459,187 +608,320 @@ export function createSubAgentTool(options) {
459
608
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
460
609
  });
461
610
  };
462
- const availableTools = buildSubagentTools(scopedExecutor, config.bashTimeoutSec, options, runContext);
463
- const verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
464
- const verifierSubjectBefore = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
465
- const worker = options.createWorker?.({
466
- subAgent: config,
467
- apiKey,
468
- tools: filterToolsByName(availableTools, config.tools),
469
- }) ??
470
- new Agent({
471
- initialState: {
472
- systemPrompt: config.systemPrompt,
473
- model: config.model,
474
- thinkingLevel: config.thinkingLevel,
611
+ let worker;
612
+ let wallClockTimer;
613
+ let unsubscribe;
614
+ let verifierGitStateBefore;
615
+ let verifierSubjectBefore;
616
+ try {
617
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
618
+ verifierGitStateBefore =
619
+ runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
620
+ verifierSubjectBefore =
621
+ runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
622
+ worker =
623
+ options.createWorker?.({
624
+ subAgent: config,
625
+ apiKey,
475
626
  tools: filterToolsByName(availableTools, config.tools),
476
- },
477
- convertToLlm,
478
- getApiKey: async () => apiKey,
479
- streamFn: streamSimple,
627
+ }) ??
628
+ new Agent({
629
+ initialState: {
630
+ systemPrompt: config.systemPrompt,
631
+ model: config.model,
632
+ thinkingLevel: config.thinkingLevel,
633
+ tools: filterToolsByName(availableTools, config.tools),
634
+ },
635
+ convertToLlm,
636
+ getApiKey: async () => apiKey,
637
+ streamFn: streamSimple,
638
+ });
639
+ runManager.registerCancelHandle(runContext.runId, () => {
640
+ externallyCancelled = true;
641
+ worker?.abort();
480
642
  });
481
- const childController = new AbortController();
482
- const unlinkAbortSignals = linkAbortSignals(signal, childController);
483
- const wallClockTimer = setTimeout(() => {
484
- failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
485
- budgetExceeded = true;
486
- worker.abort();
487
- }, config.maxWallTimeSec * 1000);
488
- const unsubscribe = worker.subscribe((event) => {
489
- if (event.type === "message_end" && isAssistantMessage(event.message)) {
490
- assistantTurns++;
491
- const messageUsage = event.message.usage;
492
- usage.input += messageUsage.input;
493
- usage.output += messageUsage.output;
494
- usage.cacheRead += messageUsage.cacheRead;
495
- usage.cacheWrite += messageUsage.cacheWrite;
496
- usage.total += messageUsage.totalTokens;
497
- usage.cost.input += messageUsage.cost.input;
498
- usage.cost.output += messageUsage.cost.output;
499
- usage.cost.cacheRead += messageUsage.cost.cacheRead;
500
- usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
501
- usage.cost.total += messageUsage.cost.total;
502
- }
503
- if (event.type === "tool_execution_start") {
504
- toolCalls++;
505
- const label = extractLabelFromArgs(event.args) || event.toolName;
506
- emitUpdate(formatStatus(config.name, label));
507
- if (toolCalls > config.maxToolCalls) {
508
- failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
643
+ wallClockTimer = setTimeout(() => {
644
+ failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
645
+ budgetExceeded = true;
646
+ worker?.abort();
647
+ }, config.maxWallTimeSec * 1000);
648
+ unsubscribe = worker.subscribe((event) => {
649
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
650
+ assistantTurns++;
651
+ const messageUsage = event.message.usage;
652
+ usage.input += messageUsage.input;
653
+ usage.output += messageUsage.output;
654
+ usage.cacheRead += messageUsage.cacheRead;
655
+ usage.cacheWrite += messageUsage.cacheWrite;
656
+ usage.total += messageUsage.totalTokens;
657
+ usage.cost.input += messageUsage.cost.input;
658
+ usage.cost.output += messageUsage.cost.output;
659
+ usage.cost.cacheRead += messageUsage.cost.cacheRead;
660
+ usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
661
+ usage.cost.total += messageUsage.cost.total;
662
+ }
663
+ if (event.type === "tool_execution_start") {
664
+ toolCalls++;
665
+ const label = extractLabelFromArgs(event.args) || event.toolName;
666
+ emitUpdate(formatStatus(config.name, label));
667
+ if (toolCalls > config.maxToolCalls) {
668
+ failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
669
+ budgetExceeded = true;
670
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
671
+ worker?.abort();
672
+ }
673
+ }
674
+ if (event.type === "turn_end" &&
675
+ isAssistantMessage(event.message) &&
676
+ event.toolResults.length > 0 &&
677
+ assistantTurns >= config.maxTurns) {
678
+ failureReason = `Turn budget exceeded (${config.maxTurns})`;
509
679
  budgetExceeded = true;
510
- emitUpdate(formatStatus(config.name, "tool budget reached"));
511
- worker.abort();
680
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
681
+ worker?.abort();
512
682
  }
683
+ });
684
+ emitUpdate(formatStatus(config.name, "started"));
685
+ }
686
+ catch (error) {
687
+ unsubscribe?.();
688
+ if (wallClockTimer)
689
+ clearTimeout(wallClockTimer);
690
+ runManager.clearCancelHandle(runContext.runId);
691
+ try {
692
+ worker?.abort();
513
693
  }
514
- if (event.type === "turn_end" &&
515
- isAssistantMessage(event.message) &&
516
- event.toolResults.length > 0 &&
517
- assistantTurns >= config.maxTurns) {
518
- failureReason = `Turn budget exceeded (${config.maxTurns})`;
519
- budgetExceeded = true;
520
- emitUpdate(formatStatus(config.name, "turn budget reached"));
521
- worker.abort();
522
- }
523
- });
524
- emitUpdate(formatStatus(config.name, "started"));
525
- try {
526
- if (childController.signal.aborted) {
527
- throw new Error("Sub-agent aborted");
694
+ catch {
695
+ // Preserve the setup error; settlement below is the lifecycle authority.
528
696
  }
529
- const abortWorker = () => worker.abort();
530
- childController.signal.addEventListener("abort", abortWorker, { once: true });
697
+ const setupError = error instanceof Error ? error : new Error(String(error));
698
+ await runManager.settle(runContext.runId, {
699
+ status: "failed",
700
+ failureReason: setupError.message,
701
+ usage,
702
+ usageKnown: true,
703
+ costKnown: true,
704
+ turns: assistantTurns,
705
+ toolCalls,
706
+ durationMs: Date.now() - startedAt,
707
+ outputText: "",
708
+ }, { announce: false });
709
+ throw setupError;
710
+ }
711
+ const activeWorker = worker;
712
+ const activeUnsubscribe = unsubscribe;
713
+ const activeWallClockTimer = wallClockTimer;
714
+ /**
715
+ * Runs the worker to completion, including the D6 convergence turn, and returns the
716
+ * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
717
+ * fatal case (no assistant message at all) — every other outcome, including a budget
718
+ * abort or explicit cancel, is a normal (if failed) result.
719
+ */
720
+ async function runToCompletion() {
531
721
  try {
532
722
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
533
- await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
534
- await worker.waitForIdle();
723
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
724
+ await activeWorker.waitForIdle();
725
+ // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
726
+ // conclusion instead of discarding the work outright. An explicit cancel skips
727
+ // this — the model asked this run to stop now, not to wrap up.
728
+ if (budgetExceeded && !externallyCancelled) {
729
+ clearTimeout(activeWallClockTimer);
730
+ emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
731
+ const preConvergenceMessageCount = activeWorker.state.messages.length;
732
+ activeWorker.state.tools = [];
733
+ let convergenceTimedOut = false;
734
+ const convergenceTimer = setTimeout(() => {
735
+ convergenceTimedOut = true;
736
+ activeWorker.abort();
737
+ }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
738
+ try {
739
+ await activeWorker.prompt(CONVERGENCE_PROMPT);
740
+ await activeWorker.waitForIdle();
741
+ }
742
+ catch {
743
+ // Best effort: fall through to whatever worker.state.messages holds.
744
+ }
745
+ finally {
746
+ clearTimeout(convergenceTimer);
747
+ }
748
+ if (convergenceTimedOut) {
749
+ // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
750
+ // convergence turn and fall back to whatever came before it.
751
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
752
+ }
753
+ }
535
754
  }
536
755
  finally {
537
- childController.signal.removeEventListener("abort", abortWorker);
756
+ activeUnsubscribe();
757
+ clearTimeout(activeWallClockTimer);
538
758
  }
539
- // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
540
- // conclusion instead of discarding the work outright. A parent-driven /stop
541
- // (childController already aborted) skips this — the user asked to stop now.
542
- if (budgetExceeded && !childController.signal.aborted) {
543
- clearTimeout(wallClockTimer);
544
- emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
545
- const preConvergenceMessageCount = worker.state.messages.length;
546
- worker.state.tools = [];
547
- let convergenceTimedOut = false;
548
- const convergenceTimer = setTimeout(() => {
549
- convergenceTimedOut = true;
550
- worker.abort();
551
- }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
552
- childController.signal.addEventListener("abort", abortWorker, { once: true });
553
- try {
554
- await worker.prompt(CONVERGENCE_PROMPT);
555
- await worker.waitForIdle();
556
- }
557
- catch {
558
- // Best effort: fall through to whatever worker.state.messages holds.
559
- }
560
- finally {
561
- childController.signal.removeEventListener("abort", abortWorker);
562
- clearTimeout(convergenceTimer);
563
- }
564
- if (convergenceTimedOut) {
565
- // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
566
- // convergence turn and fall back to whatever came before it.
567
- worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
759
+ const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
760
+ const durationMs = Date.now() - startedAt;
761
+ if (!lastAssistantMessage) {
762
+ failureReason = failureReason || "Sub-agent returned no assistant message";
763
+ emitUpdate(formatStatus(config.name, "failed"));
764
+ throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
765
+ }
766
+ const finalText = extractAssistantText(lastAssistantMessage);
767
+ const effectiveFailureReason = failureReason ||
768
+ (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
769
+ ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
770
+ : undefined);
771
+ const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
772
+ const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
773
+ const workspaceChanged = runContext.purpose === "verify" &&
774
+ (verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
775
+ ? verifierSubjectBefore !== verifierSubjectAfter
776
+ : verifierGitStateBefore !== undefined &&
777
+ verifierGitStateAfter !== undefined &&
778
+ verifierGitStateBefore !== verifierGitStateAfter);
779
+ const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
780
+ const verificationVerdict = runContext.purpose === "verify"
781
+ ? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
782
+ ? "pass"
783
+ : "fail"
784
+ : undefined;
785
+ if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
786
+ const evidence = workspaceChanged
787
+ ? "Verifier changed tracked workspace files; the attestation is invalid."
788
+ : !declaredVerdict
789
+ ? "Verifier did not emit the required final VERDICT marker."
790
+ : finalText.trim().slice(0, 8_000);
791
+ await writeVerificationAttestation(options.channelDir, {
792
+ runId: runContext.runId,
793
+ taskId: runContext.taskId,
794
+ verdict: verificationVerdict,
795
+ checkedAt: formatLocalTime(),
796
+ evidence,
797
+ workspaceChanged: Boolean(workspaceChanged),
798
+ subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
799
+ subjectDir: runContext.workingDirectory,
800
+ // Internal verify always keeps write/edit structurally removed from the
801
+ // verifier's tool set (buildSubagentTools above) — a real, enforced gate.
802
+ verificationStrength: "enforced",
803
+ });
804
+ }
805
+ // Internal runs always report full usage; cost is "unknown" only for the shape a
806
+ // free/local model produces (tokens spent, nothing billed) — external harnesses
807
+ // override both explicitly once they land (D4/D9).
808
+ const costKnown = usage.cost.total > 0 || usage.total === 0;
809
+ const baseSettleInput = {
810
+ usage,
811
+ usageKnown: true,
812
+ costKnown,
813
+ turns: assistantTurns,
814
+ toolCalls,
815
+ durationMs,
816
+ verificationVerdict,
817
+ verificationStrength: runContext.purpose === "verify" ? "enforced" : undefined,
818
+ };
819
+ if (effectiveFailureReason) {
820
+ if (!finalText.trim()) {
821
+ emitUpdate(formatStatus(config.name, "failed"));
822
+ throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
568
823
  }
824
+ emitUpdate(formatStatus(config.name, "stopped"));
825
+ const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
826
+ return {
827
+ toolResult: {
828
+ content: [
829
+ { type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) },
830
+ ],
831
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
832
+ },
833
+ settleInput: {
834
+ ...baseSettleInput,
835
+ status: "failed",
836
+ failureReason: effectiveFailureReason,
837
+ outputText: finalText,
838
+ },
839
+ };
569
840
  }
841
+ const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
842
+ return {
843
+ toolResult: {
844
+ content: [
845
+ {
846
+ type: "text",
847
+ text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
848
+ },
849
+ ],
850
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
851
+ },
852
+ settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
853
+ };
570
854
  }
571
- finally {
572
- unsubscribe();
573
- unlinkAbortSignals();
574
- clearTimeout(wallClockTimer);
575
- }
576
- if (signal?.aborted) {
577
- throw new Error("Sub-agent aborted");
578
- }
579
- const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
580
- const durationMs = Date.now() - startedAt;
581
- if (!lastAssistantMessage) {
582
- failureReason = failureReason || "Sub-agent returned no assistant message";
583
- emitUpdate(formatStatus(config.name, "failed"));
584
- throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
585
- }
586
- const finalText = extractAssistantText(lastAssistantMessage);
587
- const effectiveFailureReason = failureReason ||
588
- (lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
589
- ? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
590
- : undefined);
591
- const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
592
- const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
593
- const workspaceChanged = runContext.purpose === "verify" &&
594
- (verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
595
- ? verifierSubjectBefore !== verifierSubjectAfter
596
- : verifierGitStateBefore !== undefined &&
597
- verifierGitStateAfter !== undefined &&
598
- verifierGitStateBefore !== verifierGitStateAfter);
599
- const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
600
- const verificationVerdict = runContext.purpose === "verify"
601
- ? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
602
- ? "pass"
603
- : "fail"
604
- : undefined;
605
- if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
606
- const evidence = workspaceChanged
607
- ? "Verifier changed tracked workspace files; the attestation is invalid."
608
- : !declaredVerdict
609
- ? "Verifier did not emit the required final VERDICT marker."
610
- : finalText.trim().slice(0, 8_000);
611
- await writeVerificationAttestation(options.channelDir, {
612
- runId: runContext.runId,
613
- taskId: runContext.taskId,
614
- verdict: verificationVerdict,
615
- checkedAt: formatLocalTime(),
616
- evidence,
617
- workspaceChanged: Boolean(workspaceChanged),
618
- subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
619
- subjectDir: runContext.workingDirectory,
620
- });
621
- }
622
- if (effectiveFailureReason) {
623
- if (!finalText.trim()) {
624
- emitUpdate(formatStatus(config.name, "failed"));
625
- throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
626
- }
627
- emitUpdate(formatStatus(config.name, "stopped"));
628
- const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
855
+ /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
856
+ function fatalSettleInput(error) {
629
857
  return {
630
- content: [{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) }],
631
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
858
+ status: "failed",
859
+ failureReason: failureReason || error.message,
860
+ usage,
861
+ usageKnown: true,
862
+ costKnown: usage.cost.total > 0 || usage.total === 0,
863
+ turns: assistantTurns,
864
+ toolCalls,
865
+ durationMs: Date.now() - startedAt,
866
+ outputText: "",
632
867
  };
633
868
  }
634
- const finalized = await finalizeSubAgentOutput(runContext, finalText, returns);
869
+ // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
870
+ // clock budget) before degrading to a "still running" placeholder. The run itself keeps
871
+ // executing either way — only the *return* differs.
872
+ const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
873
+ const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
874
+ ok: false,
875
+ error: error instanceof Error ? error : new Error(String(error)),
876
+ }));
877
+ const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
878
+ if (raceResult !== "timed-out") {
879
+ runManager.clearCancelHandle(runContext.runId);
880
+ if (!raceResult.ok) {
881
+ await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
882
+ throw raceResult.error;
883
+ }
884
+ await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
885
+ return raceResult.value.toolResult;
886
+ }
887
+ // Grace window elapsed: hand back a placeholder now and let the run keep going in the
888
+ // background. It settles and, this time, announces itself with a completion wake (D2/D7)
889
+ // — the same "runtime guarantees completion" contract background jobs already keep.
890
+ detached = true;
891
+ void outcomePromise.then(async (outcome) => {
892
+ runManager.clearCancelHandle(runContext.runId);
893
+ const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
894
+ await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
895
+ log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
896
+ });
897
+ });
635
898
  return {
636
899
  content: [
637
900
  {
638
901
  type: "text",
639
- text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
902
+ text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
903
+ "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
904
+ "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
640
905
  },
641
906
  ],
642
- details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
907
+ details: {
908
+ kind: "subagent",
909
+ agent: config.name,
910
+ source: config.source,
911
+ model: formatModelReference(config.model),
912
+ tools: [...config.tools],
913
+ turns: assistantTurns,
914
+ toolCalls,
915
+ durationMs: Date.now() - startedAt,
916
+ failed: false,
917
+ usage: { ...usage, cost: { ...usage.cost } },
918
+ runId: runContext.runId,
919
+ purpose: runContext.purpose,
920
+ taskId: runContext.taskId,
921
+ artifactDir: runContext.artifactDir,
922
+ resultTruncated: false,
923
+ dispatched: true,
924
+ },
643
925
  };
644
926
  },
645
927
  };