@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -1,10 +1,11 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
2
  import { mkdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
- import { Agent } from "@earendil-works/pi-agent-core";
5
- import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
4
+ import { Agent, } from "@earendil-works/pi-agent-core";
5
+ import { clampThinkingLevel, isRetryableAssistantError, 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 { shouldFallback } from "../agent/model-fallback.js";
8
9
  import { getChannelDir } from "../channel/channel-paths.js";
9
10
  import * as log from "../log.js";
10
11
  import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, JOURNAL_TAIL_MAX_UNITS, WORKSPACE_MEMORY_MAX_UNITS, } from "../memory/index-budget.js";
@@ -28,6 +29,7 @@ import { launchExternalRun } from "./external/run.js";
28
29
  import { resolveSyncGraceMs } from "./runs.js";
29
30
  import { resolveVerificationVerdict } from "./verification-outcome.js";
30
31
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
32
+ import { changedPathsSummary, snapshotWorkspace } from "./workspace-summary.js";
31
33
  /** Shared by both invocation surfaces (spec 046, D2.1). */
32
34
  const workingDirectoryField = Type.Optional(Type.String({
33
35
  description: "Optional existing directory to run the sub-agent in (its shell cwd and relative-path root). Use it to work on another checkout — e.g. a `git worktree add`ed one. Defaults to this runtime's own working directory.",
@@ -110,6 +112,49 @@ const RESULT_TRUNCATION_HEAD_RATIO = 1;
110
112
  * This is a hard stop on that convergence turn itself, independent of maxWallTimeSec.
111
113
  */
112
114
  const CONVERGENCE_WALL_CLOCK_MS = 60_000;
115
+ /**
116
+ * A provider error (429, overloaded, 5xx, dropped stream) used to fail an internal run outright —
117
+ * the main session retries those, a bare `Agent` does not. Retried in place with exponential
118
+ * backoff (2s, 4s, 8s) before falling back to the backup model; the wall-time budget still bounds
119
+ * the whole thing.
120
+ */
121
+ const MAX_TRANSIENT_RETRIES = 3;
122
+ const RETRY_BASE_DELAY_MS = 2_000;
123
+ /**
124
+ * D2's grace window is per turn, not per call. The SDK runs a whole tool batch sequentially as
125
+ * soon as one call in it is sequential (`bash`, `edit`, `write`), so "a worktree, then three
126
+ * delegations" in one message used to block the channel for three back-to-back grace windows.
127
+ * Every call in one agent run shares that run's AbortSignal, which is what keys the deadline:
128
+ * the first delegation of a turn starts the clock, later ones get only what is left of it.
129
+ */
130
+ const turnGraceDeadlines = new WeakMap();
131
+ function graceDeadlineFor(signal, graceMs, now) {
132
+ if (!signal)
133
+ return now + graceMs;
134
+ let deadline = turnGraceDeadlines.get(signal);
135
+ if (deadline === undefined) {
136
+ deadline = now + graceMs;
137
+ turnGraceDeadlines.set(signal, deadline);
138
+ }
139
+ return deadline;
140
+ }
141
+ /** Resolves once `signal` aborts (never rejects; pending forever without one). `dispose` drops
142
+ * the listener, since a turn's signal outlives every call that raced against it. */
143
+ function watchAbort(signal) {
144
+ let dispose = () => { };
145
+ const aborted = new Promise((resolve) => {
146
+ if (!signal)
147
+ return;
148
+ if (signal.aborted) {
149
+ resolve("aborted");
150
+ return;
151
+ }
152
+ const onAbort = () => resolve("aborted");
153
+ signal.addEventListener("abort", onAbort, { once: true });
154
+ dispose = () => signal.removeEventListener("abort", onAbort);
155
+ });
156
+ return { aborted, dispose };
157
+ }
113
158
  const CONVERGENCE_PROMPT = "Your turn/tool-call/wall-time budget for this task is exhausted. Based only on the work you have already completed, respond now with your conclusions: confirmed facts, what remains unfinished, and suggested next steps. Do not call any more tools.";
114
159
  /**
115
160
  * Pins every command a run issues to the run's working directory. It sets the child's real `cwd`
@@ -261,7 +306,10 @@ function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
261
306
  */
262
307
  async function resolveContextualBlocks(config, options) {
263
308
  return buildContextualBlocks(config, options).catch((error) => {
264
- log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
309
+ log.logWarn("subagent.context.inject_failed", "Sub-agent context injection failed; continuing without it", {
310
+ channelId: options.runtimeContext.channelId,
311
+ reason: errorMessage(error),
312
+ });
265
313
  return [];
266
314
  });
267
315
  }
@@ -397,11 +445,8 @@ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
397
445
  }
398
446
  }
399
447
  /**
400
- * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
401
- * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
402
- * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
403
- * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
404
- * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
448
+ * The task envelope both runtimes' first dispatch sends (a follow-up sends `buildFollowUpTask`
449
+ * instead). `config` is narrowed to `{ name }` — the only field this function reads.
405
450
  */
406
451
  export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext) {
407
452
  const taskText = task.trim();
@@ -422,10 +467,33 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
422
467
  }
423
468
  lines.push("", `Task:`, taskText);
424
469
  if (runContext.purpose === "verify") {
425
- const taskPath = runContext.taskId
426
- ? join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`)
427
- : undefined;
428
- lines.push("", buildVerificationProtocol(taskPath, runContext.item));
470
+ lines.push("", buildVerificationProtocol(verificationTaskPath(runtimeContext, runContext), runContext.item));
471
+ }
472
+ return lines.join("\n");
473
+ }
474
+ function verificationTaskPath(runtimeContext, runContext) {
475
+ return runContext.taskId
476
+ ? join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`)
477
+ : undefined;
478
+ }
479
+ /**
480
+ * The envelope for `subagent_run op=follow_up`. A resumed session already holds the first
481
+ * dispatch's whole envelope — runtime paths, injected memory/context blocks, the role — so sending
482
+ * it again only re-bills that context and buries the new instruction. Only what is new goes: the
483
+ * artifact directory (fresh per run) and the instruction itself, plus the checker protocol again
484
+ * for a verify run, since its final VERDICT line is what settlement reads.
485
+ */
486
+ export function buildFollowUpTask(task, runtimeContext, runContext) {
487
+ const lines = [
488
+ "Follow-up in the same session. Your earlier instructions and context still apply unless this changes them.",
489
+ `- Working directory: ${runContext.workingDirectory}`,
490
+ `- Artifact directory for this follow-up: ${runContext.artifactDir}`,
491
+ "",
492
+ "Follow-up instruction:",
493
+ task.trim(),
494
+ ];
495
+ if (runContext.purpose === "verify") {
496
+ lines.push("", buildVerificationProtocol(verificationTaskPath(runtimeContext, runContext), runContext.item));
429
497
  }
430
498
  return lines.join("\n");
431
499
  }
@@ -435,7 +503,7 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
435
503
  * main agent's budget. No per-call LLM recall: a sub-agent task is short-lived, so there is no
436
504
  * "first turn" to bootstrap once and reuse; it gets the same snapshot every dispatch.
437
505
  */
438
- export async function buildContextualBlocks(config, options) {
506
+ async function buildContextualBlocks(config, options) {
439
507
  if (config.contextMode !== "contextual") {
440
508
  return [];
441
509
  }
@@ -518,7 +586,7 @@ function createDetails(input) {
518
586
  * the sync-grace/detached-placeholder split — is identical regardless of which schema the model
519
587
  * called through.
520
588
  */
521
- async function dispatchSubAgentRun(options, currentModel, config, warning, params, onUpdate) {
589
+ async function dispatchSubAgentRun(options, currentModel, config, warning, params, signal, onUpdate) {
522
590
  // Derived rather than model-supplied (spec 045): `${agent}: ${task's first line}`, the
523
591
  // same shape `subagent_run op=follow_up` already builds by hand.
524
592
  const runLabel = `${config.name}: ${params.task.split("\n")[0]?.slice(0, 80) ?? ""}`;
@@ -548,8 +616,20 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
548
616
  }
549
617
  leaseKey = lease.leaseKey;
550
618
  }
619
+ // Taken under the lease, before the run can write: what "already dirty" means for this run.
620
+ const workspaceBaseline = config.mutates === "write" ? await snapshotWorkspace(runContext.workingDirectory) : undefined;
551
621
  if (config.runtime === "external") {
552
- return dispatchExternalRun({ options, currentModel, config, runLabel, runContext, leaseKey, params, runManager });
622
+ return dispatchExternalRun({
623
+ options,
624
+ currentModel,
625
+ config,
626
+ runLabel,
627
+ runContext,
628
+ leaseKey,
629
+ params,
630
+ runManager,
631
+ workspaceBaseline,
632
+ });
553
633
  }
554
634
  return dispatchInternalRun({
555
635
  options,
@@ -560,8 +640,10 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
560
640
  runContext,
561
641
  leaseKey,
562
642
  params,
643
+ signal,
563
644
  onUpdate,
564
645
  runManager,
646
+ workspaceBaseline,
565
647
  });
566
648
  }
567
649
  /**
@@ -602,6 +684,7 @@ async function dispatchExternalRun(input) {
602
684
  item: runContext.item,
603
685
  leaseKey,
604
686
  mutates: config.mutates,
687
+ workspaceBaseline: input.workspaceBaseline,
605
688
  roleFingerprint: externalRoleFingerprint(config),
606
689
  workspaceDir: options.workspaceDir,
607
690
  securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
@@ -652,7 +735,7 @@ async function dispatchExternalRun(input) {
652
735
  * placeholder while the run keeps going in the background.
653
736
  */
654
737
  async function dispatchInternalRun(input) {
655
- const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, onUpdate, runManager } = input;
738
+ const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, signal, onUpdate, runManager } = input;
656
739
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
657
740
  let apiKey;
658
741
  try {
@@ -674,6 +757,12 @@ async function dispatchInternalRun(input) {
674
757
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
675
758
  let detached = false;
676
759
  let lastUpdateText = "";
760
+ /** The model actually answering; differs from `config.model` once a backup-model switch happened. */
761
+ let activeModel = config.model;
762
+ /** Set when the run switched to the backup model, for the reply and the record. */
763
+ let fallbackNote;
764
+ /** Wakes a retry backoff early when the run is cancelled or out of wall time. */
765
+ const retryBackoff = new AbortController();
677
766
  let worker;
678
767
  try {
679
768
  await runManager.register({
@@ -693,6 +782,7 @@ async function dispatchInternalRun(input) {
693
782
  channelDir: options.channelDir,
694
783
  leaseKey,
695
784
  mutates: config.mutates,
785
+ workspaceBaseline: input.workspaceBaseline,
696
786
  });
697
787
  }
698
788
  catch (error) {
@@ -707,6 +797,7 @@ async function dispatchInternalRun(input) {
707
797
  // start writing after the supposed cancellation (especially dangerous for a write verifier).
708
798
  runManager.registerCancelHandle(runContext.runId, () => {
709
799
  externallyCancelled = true;
800
+ retryBackoff.abort();
710
801
  worker?.abort();
711
802
  });
712
803
  const emitUpdate = (text) => {
@@ -730,6 +821,7 @@ async function dispatchInternalRun(input) {
730
821
  durationMs: Date.now() - startedAt,
731
822
  failed: Boolean(failureReason),
732
823
  failureReason,
824
+ modelOverride: fallbackNote ? formatModelReference(activeModel) : undefined,
733
825
  }),
734
826
  });
735
827
  };
@@ -756,12 +848,14 @@ async function dispatchInternalRun(input) {
756
848
  tools: filterToolsByName(availableTools, config.tools),
757
849
  },
758
850
  convertToLlm,
851
+ // Read on every request, so a backup-model switch only has to replace the key.
759
852
  getApiKey: async () => apiKey,
760
853
  streamFn: streamSimple,
761
854
  });
762
855
  wallClockTimer = setTimeout(() => {
763
856
  failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
764
857
  budgetExceeded = true;
858
+ retryBackoff.abort();
765
859
  worker?.abort();
766
860
  }, config.maxWallTimeSec * 1000);
767
861
  unsubscribe = worker.subscribe((event) => {
@@ -773,6 +867,10 @@ async function dispatchInternalRun(input) {
773
867
  toolCalls++;
774
868
  const label = describeToolCall(event.toolName, event.args);
775
869
  emitUpdate(formatStatus(config.name, label));
870
+ // After detaching, the step goes out as a paced run notice instead, like an external
871
+ // run's progress tail — otherwise an async internal run is silent until it settles.
872
+ if (detached)
873
+ runManager.noteProgress(runContext.runId, label);
776
874
  if (toolCalls > config.maxToolCalls) {
777
875
  failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
778
876
  budgetExceeded = true;
@@ -820,6 +918,64 @@ async function dispatchInternalRun(input) {
820
918
  const activeWorker = worker;
821
919
  const activeUnsubscribe = unsubscribe;
822
920
  const activeWallClockTimer = wallClockTimer;
921
+ /**
922
+ * A transcript ending in a provider error is retried in place (the error message removed, the
923
+ * loop continued from the last user/tool message): transient errors up to
924
+ * MAX_TRANSIENT_RETRIES times with backoff, then — for anything but a context overflow — one
925
+ * switch to the backup model, the same rule the main turn follows (`shouldFallback`). Budget
926
+ * aborts and explicit cancels are never retried.
927
+ */
928
+ async function recoverFromProviderErrors() {
929
+ const resume = activeWorker.continue?.bind(activeWorker);
930
+ if (!resume)
931
+ return;
932
+ let retries = 0;
933
+ let switched = false;
934
+ for (;;) {
935
+ if (budgetExceeded || externallyCancelled)
936
+ return;
937
+ const last = activeWorker.state.messages.at(-1);
938
+ if (!last || !isAssistantMessage(last) || last.stopReason !== "error")
939
+ return;
940
+ // `shouldFallback` is false only for a context overflow, which no retry or model switch fixes.
941
+ if (!shouldFallback(last.errorMessage))
942
+ return;
943
+ if (retries < MAX_TRANSIENT_RETRIES && isRetryableAssistantError(last)) {
944
+ retries++;
945
+ emitUpdate(formatStatus(config.name, `provider error, retrying (${retries}/${MAX_TRANSIENT_RETRIES})`));
946
+ const delayMs = (options.retryBaseDelayMs ?? RETRY_BASE_DELAY_MS) * 2 ** (retries - 1);
947
+ await sleepUnref(delayMs, retryBackoff.signal);
948
+ if (budgetExceeded || externallyCancelled)
949
+ return;
950
+ }
951
+ else {
952
+ if (switched || !options.resolveFallbackModel)
953
+ return;
954
+ const candidate = await options.resolveFallbackModel().catch(() => null);
955
+ if (!candidate || formatModelReference(candidate) === formatModelReference(activeModel))
956
+ return;
957
+ let candidateKey;
958
+ try {
959
+ candidateKey = await options.resolveApiKey(candidate);
960
+ }
961
+ catch {
962
+ return;
963
+ }
964
+ switched = true;
965
+ retries = 0;
966
+ const fromRef = formatModelReference(activeModel);
967
+ activeModel = candidate;
968
+ apiKey = candidateKey;
969
+ activeWorker.state.model = candidate;
970
+ activeWorker.state.thinkingLevel = clampThinkingLevel(candidate, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL);
971
+ fallbackNote = `switched from ${fromRef} to backup model ${formatModelReference(candidate)} after: ${last.errorMessage?.split("\n")[0]?.slice(0, 200) ?? "unknown error"}`;
972
+ emitUpdate(formatStatus(config.name, `switching to backup model ${formatModelReference(candidate)}`));
973
+ }
974
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, -1);
975
+ await resume();
976
+ await activeWorker.waitForIdle();
977
+ }
978
+ }
823
979
  /**
824
980
  * Runs the worker to completion, including the D6 convergence turn, and returns the
825
981
  * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
@@ -835,6 +991,7 @@ async function dispatchInternalRun(input) {
835
991
  else {
836
992
  await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext));
837
993
  await activeWorker.waitForIdle();
994
+ await recoverFromProviderErrors();
838
995
  }
839
996
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
840
997
  // conclusion instead of discarding the work outright. An explicit cancel skips
@@ -872,6 +1029,8 @@ async function dispatchInternalRun(input) {
872
1029
  }
873
1030
  const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
874
1031
  const durationMs = Date.now() - startedAt;
1032
+ const modelRef = fallbackNote ? formatModelReference(activeModel) : undefined;
1033
+ const fallbackLine = fallbackNote ? `Note: this run ${fallbackNote}.\n\n` : "";
875
1034
  if (!lastAssistantMessage) {
876
1035
  failureReason = failureReason || "Sub-agent returned no assistant message";
877
1036
  emitUpdate(formatStatus(config.name, "failed"));
@@ -900,11 +1059,17 @@ async function dispatchInternalRun(input) {
900
1059
  toolCalls,
901
1060
  durationMs,
902
1061
  verificationVerdict,
1062
+ model: modelRef,
903
1063
  };
904
1064
  if (effectiveFailureReason) {
905
1065
  if (!finalText.trim()) {
906
1066
  emitUpdate(formatStatus(config.name, "failed"));
907
- throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
1067
+ // Settlement records the reason itself, not the next-step advice wrapped around it below.
1068
+ failureReason = effectiveFailureReason;
1069
+ // The delegating model can act on this alone — re-dispatch, narrow the task, or do the
1070
+ // work itself — so it is not a user-facing error bubble.
1071
+ throw new RecoverableToolError(`${fallbackLine}${buildFailureText(config, effectiveFailureReason, finalText)}\n` +
1072
+ `Retry the delegation (narrower if it hit a budget), or do the work directly; subagent_run op=show runId=${runContext.runId} has the details.`);
908
1073
  }
909
1074
  emitUpdate(formatStatus(config.name, "stopped"));
910
1075
  const finalized = finalizeSubAgentOutput(runContext, finalText);
@@ -913,7 +1078,9 @@ async function dispatchInternalRun(input) {
913
1078
  content: [
914
1079
  {
915
1080
  type: "text",
916
- text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
1081
+ text: mutatesNote +
1082
+ fallbackLine +
1083
+ buildStoppedText(config, effectiveFailureReason, finalized.replyText),
917
1084
  },
918
1085
  ],
919
1086
  details: createDetails({
@@ -927,6 +1094,7 @@ async function dispatchInternalRun(input) {
927
1094
  failureReason: effectiveFailureReason,
928
1095
  verificationVerdict,
929
1096
  resultTruncated: finalized.truncated,
1097
+ modelOverride: modelRef,
930
1098
  }),
931
1099
  },
932
1100
  settleInput: {
@@ -939,13 +1107,24 @@ async function dispatchInternalRun(input) {
939
1107
  },
940
1108
  };
941
1109
  }
1110
+ // P2-2, same as an external write run: what this run changed, so the reader does not spend
1111
+ // its first tool call finding out. Only a cleanly completed write run pays for it.
1112
+ const workspaceSummary = config.mutates === "write"
1113
+ ? await changedPathsSummary(runContext.workingDirectory, input.workspaceBaseline).catch(() => undefined)
1114
+ : undefined;
1115
+ const workspaceLine = workspaceSummary
1116
+ ? `\n\nWorkspace after the run (git status --porcelain): ${workspaceSummary}`
1117
+ : "";
942
1118
  const finalized = finalizeSubAgentOutput(runContext, finalText);
943
1119
  return {
944
1120
  toolResult: {
945
1121
  content: [
946
1122
  {
947
1123
  type: "text",
948
- text: mutatesNote + (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
1124
+ text: mutatesNote +
1125
+ fallbackLine +
1126
+ (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`) +
1127
+ workspaceLine,
949
1128
  },
950
1129
  ],
951
1130
  details: createDetails({
@@ -957,9 +1136,10 @@ async function dispatchInternalRun(input) {
957
1136
  durationMs,
958
1137
  verificationVerdict,
959
1138
  resultTruncated: finalized.truncated,
1139
+ modelOverride: modelRef,
960
1140
  }),
961
1141
  },
962
- settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
1142
+ settleInput: { ...baseSettleInput, status: "completed", outputText: finalText, workspaceSummary },
963
1143
  };
964
1144
  }
965
1145
  /** Best-effort settle input for the one fatal path that rejects instead of resolving. */
@@ -974,18 +1154,29 @@ async function dispatchInternalRun(input) {
974
1154
  toolCalls,
975
1155
  durationMs: Date.now() - startedAt,
976
1156
  outputText: "",
1157
+ model: fallbackNote ? formatModelReference(activeModel) : undefined,
977
1158
  };
978
1159
  }
979
- // D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
980
- // clock budget) before degrading to a "still running" placeholder. The run itself keeps
981
- // executing either way — only the *return* differs.
982
- const graceMs = Math.min(config.maxWallTimeSec * 1000, resolveSyncGraceMs(options.syncGraceMs));
1160
+ // D2: the tool call waits at most until this turn's shared grace deadline (never longer than
1161
+ // the run's own wall clock budget) before degrading to a "still running" placeholder. It also
1162
+ // stops waiting the moment the turn is aborted (`/stop`): the SDK awaits this call, so ignoring
1163
+ // the signal held `/stop` until its force-end fallback — and a result that then arrived inside
1164
+ // the grace window settled `announce: false` into a turn that no longer existed, so nobody
1165
+ // ever saw it. The run itself keeps executing either way — only the *return* differs.
1166
+ const now = Date.now();
1167
+ const deadline = Math.min(graceDeadlineFor(signal, resolveSyncGraceMs(options.syncGraceMs), now), now + config.maxWallTimeSec * 1000);
983
1168
  const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
984
1169
  ok: false,
985
1170
  error: error instanceof Error ? error : new Error(String(error)),
986
1171
  }));
987
- const raceResult = await Promise.race([outcomePromise, sleepUnref(graceMs).then(() => "timed-out")]);
988
- if (raceResult !== "timed-out") {
1172
+ const abortWatch = watchAbort(signal);
1173
+ const raceResult = await Promise.race([
1174
+ outcomePromise,
1175
+ sleepUnref(Math.max(0, deadline - now)).then(() => "timed-out"),
1176
+ abortWatch.aborted,
1177
+ ]);
1178
+ abortWatch.dispose();
1179
+ if (raceResult !== "timed-out" && raceResult !== "aborted") {
989
1180
  runManager.clearCancelHandle(runContext.runId);
990
1181
  if (!raceResult.ok) {
991
1182
  await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
@@ -994,15 +1185,18 @@ async function dispatchInternalRun(input) {
994
1185
  await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
995
1186
  return raceResult.value.toolResult;
996
1187
  }
997
- // Grace window elapsed: hand back a placeholder now and let the run keep going in the
998
- // background. It settles and, this time, announces itself with a completion wake (D2/D7)
999
- // — the same "runtime guarantees completion" contract background jobs already keep.
1188
+ // Grace window elapsed (or the turn was stopped): hand back a placeholder now and let the run
1189
+ // keep going in the background. It settles and, this time, announces itself with a completion
1190
+ // wake (D2/D7) — the same "runtime guarantees completion" contract background jobs already keep.
1000
1191
  detached = true;
1001
1192
  void outcomePromise.then(async (outcome) => {
1002
1193
  runManager.clearCancelHandle(runContext.runId);
1003
1194
  const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
1004
1195
  await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
1005
- log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
1196
+ log.logWarn("subagent.settle.failed", "Detached run settlement failed", {
1197
+ reason: errorMessage(error),
1198
+ fields: { runId: runContext.runId },
1199
+ });
1006
1200
  });
1007
1201
  });
1008
1202
  return {
@@ -1049,7 +1243,7 @@ export function createSubAgentTool(options) {
1049
1243
  if (!invocation.config) {
1050
1244
  throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
1051
1245
  }
1052
- return dispatchSubAgentRun(options, currentModel, invocation.config, undefined, params, onUpdate);
1246
+ return dispatchSubAgentRun(options, currentModel, invocation.config, undefined, params, signal, onUpdate);
1053
1247
  },
1054
1248
  };
1055
1249
  }
@@ -1082,7 +1276,7 @@ export function createSubAgentInlineTool(options) {
1082
1276
  if (!invocation.config) {
1083
1277
  throw new RecoverableToolError(invocation.error ?? "Unable to resolve inline sub-agent.");
1084
1278
  }
1085
- return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, onUpdate);
1279
+ return dispatchSubAgentRun(options, currentModel, invocation.config, invocation.warning, params, signal, onUpdate);
1086
1280
  },
1087
1281
  };
1088
1282
  }
@@ -1,8 +1,20 @@
1
1
  /**
2
2
  * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
3
3
  * does not have to spend its own first tool call finding out. `git status --porcelain` only — a
4
- * convenience for the reader, not evidence of anything. Returns `undefined` on any failure (not a
5
- * git repo, `git` unavailable) or when nothing changed; a caller with nothing to show should
6
- * simply omit the line.
4
+ * convenience for the reader, not evidence of anything.
5
+ *
6
+ * A checkout is often already dirty when a write run starts (the leader's own edits, an earlier
7
+ * run's output). Reporting the raw status would credit all of that to this run, so a write run
8
+ * takes a cheap baseline at dispatch — each dirty path's status plus size/mtime — and the summary
9
+ * leaves out every path whose signature is unchanged. A pre-dirty file the run touched again gets
10
+ * a new mtime and so still shows up.
7
11
  */
8
- export declare function changedPathsSummary(workingDirectory: string, limit?: number): Promise<string | undefined>;
12
+ /** Dirty path → `<XY status>|<size>|<mtimeMs>` at dispatch time. */
13
+ export type WorkspaceBaseline = Record<string, string>;
14
+ /** `undefined` when the directory is not a git checkout or is too dirty to baseline. */
15
+ export declare function snapshotWorkspace(workingDirectory: string): Promise<WorkspaceBaseline | undefined>;
16
+ /**
17
+ * Returns `undefined` on any failure (not a git repo, `git` unavailable) or when nothing changed;
18
+ * a caller with nothing to show should simply omit the line.
19
+ */
20
+ export declare function changedPathsSummary(workingDirectory: string, baseline?: WorkspaceBaseline, limit?: number): Promise<string | undefined>;
@@ -1,29 +1,85 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { stat } from "node:fs/promises";
3
+ import { join } from "node:path";
2
4
  import { promisify } from "node:util";
3
5
  const execFileAsync = promisify(execFile);
4
- /**
5
- * P2-2: a plain-language "what changed" line for a completion wake, so the agent that reads it
6
- * does not have to spend its own first tool call finding out. `git status --porcelain` only — a
7
- * convenience for the reader, not evidence of anything. Returns `undefined` on any failure (not a
8
- * git repo, `git` unavailable) or when nothing changed; a caller with nothing to show should
9
- * simply omit the line.
10
- */
11
- export async function changedPathsSummary(workingDirectory, limit = 20) {
12
- let statusOutput;
6
+ /** Past this many dirty paths a baseline is not worth persisting on every run record; the summary
7
+ * then falls back to the raw status and says so. */
8
+ const BASELINE_MAX_ENTRIES = 500;
9
+ async function readPorcelain(workingDirectory) {
13
10
  try {
14
11
  const args = ["-C", workingDirectory, "status", "--porcelain=v1", "--untracked-files=all"];
15
- statusOutput = (await execFileAsync("git", args, { maxBuffer: 4 * 1024 * 1024 })).stdout;
12
+ const { stdout } = await execFileAsync("git", args, { maxBuffer: 4 * 1024 * 1024 });
13
+ return stdout
14
+ .split("\n")
15
+ .map((line) => line.trimEnd())
16
+ .filter((line) => line.length > 3);
16
17
  }
17
18
  catch {
18
19
  return undefined;
19
20
  }
20
- const lines = statusOutput
21
- .split("\n")
22
- .map((line) => line.trim())
23
- .filter(Boolean);
24
- if (lines.length === 0)
21
+ }
22
+ /** `XY path` or `XY orig -> path`; the path is what a later status line will be keyed by. */
23
+ function porcelainPath(line) {
24
+ const rest = line.slice(3);
25
+ const arrow = rest.indexOf(" -> ");
26
+ return arrow >= 0 ? rest.slice(arrow + 4) : rest;
27
+ }
28
+ async function pathSignature(workingDirectory, line) {
29
+ const status = line.slice(0, 2);
30
+ const path = porcelainPath(line);
31
+ // A quoted path (special characters) is not worth unquoting for a convenience line: its status
32
+ // alone still tells "unchanged since dispatch" apart from most real edits.
33
+ if (path.startsWith('"'))
34
+ return status;
35
+ try {
36
+ const info = await stat(join(workingDirectory, path));
37
+ return `${status}|${info.size}|${info.mtimeMs}`;
38
+ }
39
+ catch {
40
+ return `${status}|missing`;
41
+ }
42
+ }
43
+ /** `undefined` when the directory is not a git checkout or is too dirty to baseline. */
44
+ export async function snapshotWorkspace(workingDirectory) {
45
+ const lines = await readPorcelain(workingDirectory);
46
+ if (!lines || lines.length > BASELINE_MAX_ENTRIES)
47
+ return undefined;
48
+ const baseline = {};
49
+ await Promise.all(lines.map(async (line) => {
50
+ baseline[porcelainPath(line)] = await pathSignature(workingDirectory, line);
51
+ }));
52
+ return baseline;
53
+ }
54
+ /**
55
+ * Returns `undefined` on any failure (not a git repo, `git` unavailable) or when nothing changed;
56
+ * a caller with nothing to show should simply omit the line.
57
+ */
58
+ export async function changedPathsSummary(workingDirectory, baseline, limit = 20) {
59
+ const lines = await readPorcelain(workingDirectory);
60
+ if (!lines)
61
+ return undefined;
62
+ let changed = lines;
63
+ let unchangedCount = 0;
64
+ if (baseline) {
65
+ const flags = await Promise.all(lines.map(async (line) => {
66
+ const before = baseline[porcelainPath(line)];
67
+ return before !== undefined && before === (await pathSignature(workingDirectory, line));
68
+ }));
69
+ changed = lines.filter((_, index) => !flags[index]);
70
+ unchangedCount = lines.length - changed.length;
71
+ }
72
+ if (changed.length === 0)
25
73
  return undefined;
26
- const shown = lines.slice(0, limit).join(", ");
27
- const overflow = lines.length > limit ? ` (+${lines.length - limit} more)` : "";
28
- return `${shown}${overflow}`;
74
+ const shown = changed
75
+ .slice(0, limit)
76
+ .map((line) => line.trim())
77
+ .join(", ");
78
+ const overflow = changed.length > limit ? ` (+${changed.length - limit} more)` : "";
79
+ const note = baseline
80
+ ? unchangedCount > 0
81
+ ? ` (${unchangedCount} path(s) already dirty before the run and untouched are omitted)`
82
+ : ""
83
+ : " (no pre-run baseline: may include changes that predate this run)";
84
+ return `${shown}${overflow}${note}`;
29
85
  }
@@ -32,8 +32,15 @@ export interface TaskBoard {
32
32
  /** Ref lines the board renders before folding old, already-seen results away. */
33
33
  export declare const BOARD_REF_LINE_BUDGET = 12;
34
34
  export declare function buildTaskBoard(channelDir: string, taskId: string, body: string): Promise<TaskBoard | undefined>;
35
- /** Render the `<task_board>` block body. */
35
+ /** Render the `<task_board>` block body (model-facing; `/tasks show` uses `renderTaskBoardForUser`). */
36
36
  export declare function renderTaskBoard(board: TaskBoard, nowMs?: number): string;
37
+ /**
38
+ * The board as `/tasks show` presents it (spec 053, D2): flat bullets only — DingTalk drops
39
+ * indentation, so the brief's `↳` continuation lines would read as orphans — with every ref a
40
+ * work item has folded into its one line. No "seen / new" split (that is the leader's
41
+ * de-duplication aid) and no pointer at a model tool.
42
+ */
43
+ export declare function renderTaskBoardForUser(board: TaskBoard, taskId: string, nowMs?: number): string;
37
44
  /**
38
45
  * The `<task_results>` block body: what came back since the previous step, as the completion wake
39
46
  * showed it — the output's tail and, for a run, what it left changed. A task step's brief replaces