@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
@@ -2,6 +2,7 @@ import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { ChannelStore } from "../channel/store.js";
3
3
  import { type UsageTotals } from "../shared/types.js";
4
4
  import type { UsageLedger } from "../usage/ledger.js";
5
+ import type { WorkspaceBaseline } from "./workspace-summary.js";
5
6
  /**
6
7
  * The run: one abstraction level for delegation, whether it executes as an in-process sub-agent
7
8
  * or (from spec 040 phase 2 onward) a short-lived external CLI process. See
@@ -87,6 +88,9 @@ export interface RunRecord extends RunUsage {
87
88
  /** P2-2: `git status --porcelain` taken right after a `mutates: "write"` run finished, so the
88
89
  * wake's reader does not have to spend its own first tool call finding out what changed. */
89
90
  workspaceSummary?: string;
91
+ /** A write run's dirty-path snapshot at dispatch, so the post-run summary reports only what this
92
+ * run changed (see `workspace-summary.ts`). Persisted so restart reconciliation can use it too. */
93
+ workspaceBaseline?: WorkspaceBaseline;
90
94
  /** Set once settlement (write output, free resources) has happened; guards against replay. */
91
95
  settledAt?: number;
92
96
  /**
@@ -169,6 +173,7 @@ export interface RegisterRunInput {
169
173
  /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
170
174
  leaseKey?: string;
171
175
  mutates?: RunMutates;
176
+ workspaceBaseline?: WorkspaceBaseline;
172
177
  }
173
178
  interface PendingSettlement {
174
179
  status: SettleInput["status"];
@@ -183,6 +188,7 @@ interface PendingSettlement {
183
188
  verificationVerdict?: "pass" | "fail";
184
189
  workspaceSummary?: string;
185
190
  sessionId?: string;
191
+ model?: string;
186
192
  finishedAt: number;
187
193
  announce: boolean;
188
194
  }
@@ -205,6 +211,9 @@ export interface SettleInput {
205
211
  workspaceSummary?: string;
206
212
  /** The harness's own session/thread id, captured even on failure so a later resume can still use it. */
207
213
  sessionId?: string;
214
+ /** The model that actually produced the result, when it differs from the one registered (an
215
+ * internal run that switched to the backup model). Usage is billed against this one. */
216
+ model?: string;
208
217
  }
209
218
  /**
210
219
  * A best-effort, out-of-band notice about a run — distinct from the completion wake (`dispatch`).
@@ -213,7 +222,7 @@ export interface SettleInput {
213
222
  * run itself takes to settle, not the wake turn's latency on top of that.
214
223
  */
215
224
  export interface RunNotice {
216
- kind: "settled" | "progress";
225
+ kind: "settled" | "progress" | "stalled";
217
226
  runId: string;
218
227
  agent: string;
219
228
  /** Only set for `kind: "settled"`. */
@@ -221,6 +230,8 @@ export interface RunNotice {
221
230
  durationMs: number;
222
231
  /** Only set for `kind: "progress"`: the harness's most recently observed step, already short. */
223
232
  step?: string;
233
+ /** Only set for `kind: "stalled"`: how long the run has written no output. */
234
+ silentMs?: number;
224
235
  }
225
236
  export type RunNotifier = (channelId: string, notice: RunNotice) => void | Promise<void>;
226
237
  export interface RunManagerOptions {
@@ -263,6 +274,9 @@ export declare class SubAgentRunManager {
263
274
  * restart reconciliation already reads once from the finished process's own output. */
264
275
  private stopped;
265
276
  private readonly externalProgressTails;
277
+ /** Internal runs that went async report their steps in-process; this paces them exactly like the
278
+ * external tail does. Created on first report, dropped at settlement. */
279
+ private readonly internalProgressPacers;
266
280
  private readonly queue;
267
281
  constructor(channelId: string, options: RunManagerOptions);
268
282
  /** Release observation timers without cancelling dispatched work or its settlement. */
@@ -283,6 +297,12 @@ export declare class SubAgentRunManager {
283
297
  /** Start tailing a just-launched external run's artifact file for a human-readable step label
284
298
  * (P1a). Best-effort only — see `progress-tail.ts` for the polling/pacing contract. */
285
299
  private startExternalProgressTail;
300
+ /**
301
+ * A step label from an internal run that has outlived its sync grace window: nobody is watching
302
+ * the tool call any more, so without this the run would be silent until it settles. Paced by the
303
+ * same rules as an external run's tail; a no-op once the run is no longer running.
304
+ */
305
+ noteProgress(runId: string, step: string): void;
286
306
  private stopExternalProgressTail;
287
307
  private forget;
288
308
  get(runId: string): RunRecord | undefined;
@@ -12,7 +12,7 @@ import { isRecord } from "../shared/type-guards.js";
12
12
  import { createEmptyUsageTotals } from "../shared/types.js";
13
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
14
14
  import { logTaskDispatch, logTaskSettlement } from "../tasks/work-log.js";
15
- import { startExternalProgressTail } from "./external/progress-tail.js";
15
+ import { createProgressPacer, startExternalProgressTail } from "./external/progress-tail.js";
16
16
  import { finalizeExternalRun } from "./external/settlement.js";
17
17
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
18
18
  /**
@@ -98,6 +98,7 @@ function createPendingSettlement(input, finishedAt, announce) {
98
98
  verificationVerdict: input.verificationVerdict,
99
99
  workspaceSummary: input.workspaceSummary,
100
100
  sessionId: input.sessionId,
101
+ model: input.model,
101
102
  finishedAt,
102
103
  announce,
103
104
  };
@@ -116,6 +117,8 @@ function applyPendingSettlement(record, pending) {
116
117
  record.workspaceSummary = pending.workspaceSummary;
117
118
  if (pending.sessionId)
118
119
  record.sessionId = pending.sessionId;
120
+ if (pending.model)
121
+ record.model = pending.model;
119
122
  record.finishedAt = pending.finishedAt;
120
123
  record.settledAt = pending.finishedAt;
121
124
  record.settlementPending = undefined;
@@ -161,6 +164,9 @@ export class SubAgentRunManager {
161
164
  * restart reconciliation already reads once from the finished process's own output. */
162
165
  this.stopped = false;
163
166
  this.externalProgressTails = new Map();
167
+ /** Internal runs that went async report their steps in-process; this paces them exactly like the
168
+ * external tail does. Created on first report, dropped at settlement. */
169
+ this.internalProgressPacers = new Map();
164
170
  this.queue = createSerialQueue();
165
171
  }
166
172
  /** Release observation timers without cancelling dispatched work or its settlement. */
@@ -191,7 +197,10 @@ export class SubAgentRunManager {
191
197
  catch (error) {
192
198
  if (required)
193
199
  throw error;
194
- log.logWarning(`Failed to persist sub-agent run ${record.runId}`, errorMessage(error));
200
+ log.logWarn("subagent.persist.failed", "Run persist failed", {
201
+ reason: errorMessage(error),
202
+ fields: { runId: record.runId },
203
+ });
195
204
  }
196
205
  }
197
206
  /**
@@ -209,7 +218,10 @@ export class SubAgentRunManager {
209
218
  return true;
210
219
  }
211
220
  catch (error) {
212
- log.logWarning(`Failed to write output.md for sub-agent run ${record.runId}`, errorMessage(error));
221
+ log.logWarn("subagent.output.write_failed", "Run output.md write failed", {
222
+ reason: errorMessage(error),
223
+ fields: { runId: record.runId },
224
+ });
213
225
  return false;
214
226
  }
215
227
  }
@@ -220,7 +232,10 @@ export class SubAgentRunManager {
220
232
  return;
221
233
  void Promise.resolve()
222
234
  .then(() => notify(this.channelId, notice))
223
- .catch((error) => log.logWarning(`Failed to emit run notice for ${notice.runId}`, errorMessage(error)));
235
+ .catch((error) => log.logWarn("subagent.notice.failed", "Run notice failed", {
236
+ reason: errorMessage(error),
237
+ fields: { runId: notice.runId },
238
+ }));
224
239
  }
225
240
  /** Start tailing a just-launched external run's artifact file for a human-readable step label
226
241
  * (P1a). Best-effort only — see `progress-tail.ts` for the polling/pacing contract. */
@@ -243,9 +258,42 @@ export class SubAgentRunManager {
243
258
  step,
244
259
  });
245
260
  },
261
+ onStall: (silentMs) => {
262
+ this.emitNotice({
263
+ kind: "stalled",
264
+ runId: record.runId,
265
+ agent: record.agent,
266
+ durationMs: Date.now() - (record.processStartedAt ?? record.startedAt),
267
+ silentMs,
268
+ });
269
+ },
246
270
  });
247
271
  this.externalProgressTails.set(record.runId, tail);
248
272
  }
273
+ /**
274
+ * A step label from an internal run that has outlived its sync grace window: nobody is watching
275
+ * the tool call any more, so without this the run would be silent until it settles. Paced by the
276
+ * same rules as an external run's tail; a no-op once the run is no longer running.
277
+ */
278
+ noteProgress(runId, step) {
279
+ if (this.stopped)
280
+ return;
281
+ const record = this.runs.get(runId);
282
+ if (!record || record.status !== "running" || record.settlementPending)
283
+ return;
284
+ let pacer = this.internalProgressPacers.get(runId);
285
+ if (!pacer) {
286
+ pacer = createProgressPacer(record.startedAt, (label) => this.emitNotice({
287
+ kind: "progress",
288
+ runId,
289
+ agent: record.agent,
290
+ durationMs: Date.now() - record.startedAt,
291
+ step: label,
292
+ }));
293
+ this.internalProgressPacers.set(runId, pacer);
294
+ }
295
+ pacer.offer(step);
296
+ }
249
297
  stopExternalProgressTail(runId) {
250
298
  const tail = this.externalProgressTails.get(runId);
251
299
  if (!tail)
@@ -268,6 +316,7 @@ export class SubAgentRunManager {
268
316
  this.runs.delete(record.runId);
269
317
  this.cancelHandles.delete(record.runId);
270
318
  this.externalLaunches.delete(record.runId);
319
+ this.internalProgressPacers.delete(record.runId);
271
320
  this.clearExternalRecoveryTimer(record.runId);
272
321
  }
273
322
  get(runId) {
@@ -361,7 +410,10 @@ export class SubAgentRunManager {
361
410
  purpose: record.purpose,
362
411
  label: record.label,
363
412
  }).catch((error) => {
364
- log.logWarning(`Failed to log dispatch of ${record.runId} to task ${record.taskId}`, errorMessage(error));
413
+ log.logWarn("subagent.task_dispatch.log_failed", "Task dispatch record failed", {
414
+ reason: errorMessage(error),
415
+ fields: { runId: record.runId, taskId: record.taskId },
416
+ });
365
417
  });
366
418
  }
367
419
  return record;
@@ -479,7 +531,10 @@ export class SubAgentRunManager {
479
531
  return;
480
532
  record.terminationReason = reason;
481
533
  await this.persist(record).catch((error) => {
482
- log.logWarning(`Failed to persist termination reason for run ${runId}`, errorMessage(error));
534
+ log.logWarn("subagent.persist.failed", "Termination reason persist failed", {
535
+ reason: errorMessage(error),
536
+ fields: { runId },
537
+ });
483
538
  });
484
539
  });
485
540
  }
@@ -527,6 +582,7 @@ export class SubAgentRunManager {
527
582
  this.externalLaunches.delete(runId);
528
583
  this.clearExternalRecoveryTimer(runId);
529
584
  this.stopExternalProgressTail(runId);
585
+ this.internalProgressPacers.delete(runId);
530
586
  if (!record.usageRecorded) {
531
587
  record.usageRecorded = true;
532
588
  this.options.ledger?.record({
@@ -574,7 +630,10 @@ export class SubAgentRunManager {
574
630
  artifactDir: record.artifactDir,
575
631
  })
576
632
  .catch((error) => {
577
- log.logWarning(`Failed to archive sub-agent run ${record.runId}`, errorMessage(error));
633
+ log.logWarn("subagent.archive.failed", "Run archive failed", {
634
+ reason: errorMessage(error),
635
+ fields: { runId: record.runId },
636
+ });
578
637
  });
579
638
  await this.persist(record);
580
639
  }
@@ -585,7 +644,10 @@ export class SubAgentRunManager {
585
644
  if (!record.taskAccounted && record.taskId && record.channelDir) {
586
645
  record.taskAccounted = true;
587
646
  await this.creditOwningTask(record, input, outputSaved).catch((error) => {
588
- log.logWarning(`Failed to credit task ${record.taskId} for run ${record.runId}`, errorMessage(error));
647
+ log.logWarn("subagent.task_settle.log_failed", "Task credit for run failed", {
648
+ reason: errorMessage(error),
649
+ fields: { runId: record.runId, taskId: record.taskId },
650
+ });
589
651
  });
590
652
  await this.persist(record);
591
653
  }
@@ -654,12 +716,13 @@ export class SubAgentRunManager {
654
716
  // K parallel fan-out runs otherwise produce K wake turns, each re-asking "is this the only
655
717
  // one?" via a fresh subagent_list call — this answers it inline (review 2026-08-23
656
718
  // §3.3), so the model can reliably reply [SILENT] to every wake but the last.
657
- const siblingCount = record.taskId
658
- ? Array.from(this.runs.values()).filter((other) => other.taskId === record.taskId && other.status === "running" && other.runId !== record.runId).length
659
- : 0;
660
- const belongsTo = record.taskId
661
- ? ` It belongs to task ${record.taskId}.${siblingCount > 0 ? ` ${siblingCount} other run(s) for this task are still running.` : ""}`
719
+ // A chat-level run's siblings are the other chat-level runs on this channel: the same "was this
720
+ // the last one?" question, without a task to scope it.
721
+ const siblingCount = Array.from(this.runs.values()).filter((other) => other.taskId === record.taskId && other.status === "running" && other.runId !== record.runId).length;
722
+ const siblingNote = siblingCount > 0
723
+ ? ` ${siblingCount} other run(s) ${record.taskId ? "for this task" : "on this channel"} are still running.`
662
724
  : "";
725
+ const belongsTo = record.taskId ? ` It belongs to task ${record.taskId}.${siblingNote}` : siblingNote;
663
726
  const verdictLine = record.verificationVerdict !== undefined
664
727
  ? `\nVerdict: ${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}`
665
728
  : "";
@@ -710,7 +773,10 @@ export class SubAgentRunManager {
710
773
  await this.options.dispatch(event);
711
774
  }
712
775
  catch (error) {
713
- log.logWarning(`Failed to dispatch completion wake for run ${record.runId}`, errorMessage(error));
776
+ log.logWarn("subagent.wake.dispatch_failed", "Completion wake dispatch failed", {
777
+ reason: errorMessage(error),
778
+ fields: { runId: record.runId },
779
+ });
714
780
  return;
715
781
  }
716
782
  record.wakeEnqueued = true;
@@ -774,7 +840,10 @@ export class SubAgentRunManager {
774
840
  return status;
775
841
  this.clearExternalRecoveryTimer(runId);
776
842
  await this.reconcileExternalRun(adoptedRecord).catch((error) => {
777
- log.logWarning(`Failed to reconcile cancelled adopted run ${runId}`, errorMessage(error));
843
+ log.logWarn("subagent.reconcile.failed", "Cancelled adopted run reconcile failed", {
844
+ reason: errorMessage(error),
845
+ fields: { runId },
846
+ });
778
847
  });
779
848
  return this.runs.get(runId)?.status ?? status;
780
849
  }
@@ -810,7 +879,10 @@ export class SubAgentRunManager {
810
879
  raw = await readFile(path, "utf-8");
811
880
  }
812
881
  catch (error) {
813
- log.logWarning(`Skipping unreadable sub-agent run record ${filename} (left on disk)`, errorMessage(error));
882
+ log.logWarn("subagent.record.unreadable", "Unreadable run record skipped (left on disk)", {
883
+ reason: errorMessage(error),
884
+ fields: { file: filename },
885
+ });
814
886
  continue;
815
887
  }
816
888
  let record;
@@ -824,7 +896,9 @@ export class SubAgentRunManager {
824
896
  // Genuinely corrupt content (bad JSON or shape) — quarantine rather than delete, so
825
897
  // the evidence survives for a manual look; `.corrupt` files never match the `.json`
826
898
  // filter above, so this cannot loop.
827
- log.logWarning(`Quarantining corrupt sub-agent run record: ${filename}`);
899
+ log.logWarn("subagent.record.quarantined", "Corrupt run record quarantined", {
900
+ fields: { file: filename },
901
+ });
828
902
  await rename(path, `${path}.corrupt`).catch(() => undefined);
829
903
  continue;
830
904
  }
@@ -853,7 +927,10 @@ export class SubAgentRunManager {
853
927
  workspaceSummary: pending.workspaceSummary,
854
928
  sessionId: pending.sessionId,
855
929
  }, { announce: pending.announce }).catch((error) => {
856
- log.logWarning(`Failed to finish pending sub-agent settlement ${record?.runId}`, errorMessage(error));
930
+ log.logWarn("subagent.settle.failed", "Pending settlement could not be finished", {
931
+ reason: errorMessage(error),
932
+ fields: { runId: record?.runId },
933
+ });
857
934
  });
858
935
  continue;
859
936
  }
@@ -869,7 +946,10 @@ export class SubAgentRunManager {
869
946
  durationMs: Date.now() - record.startedAt,
870
947
  outputText: "",
871
948
  }, { announce: true }).catch((error) => {
872
- log.logWarning(`Failed to reconcile sub-agent run ${record?.runId}`, errorMessage(error));
949
+ log.logWarn("subagent.reconcile.failed", "Run reconcile failed", {
950
+ reason: errorMessage(error),
951
+ fields: { runId: record?.runId },
952
+ });
873
953
  });
874
954
  }
875
955
  if (record.runtime === "external" && record.status === "running") {
@@ -888,11 +968,17 @@ export class SubAgentRunManager {
888
968
  // realpath drift between restarts.
889
969
  record.leaseKey = rebuilt.leaseKey;
890
970
  await this.persist(record).catch((error) => {
891
- log.logWarning(`Failed to persist rebuilt lease for run ${record.runId}`, errorMessage(error));
971
+ log.logWarn("subagent.lease.persist_failed", "Rebuilt lease persist failed", {
972
+ reason: errorMessage(error),
973
+ fields: { runId: record.runId },
974
+ });
892
975
  });
893
976
  }
894
977
  else {
895
- log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
978
+ log.logWarn("subagent.lease.rebuild_failed", "Workspace lease for adopted run could not be rebuilt", {
979
+ reason: formatWorkspaceLeaseConflict(rebuilt.heldBy),
980
+ fields: { runId: record.runId },
981
+ });
896
982
  // This run cannot safely continue without its lease: it could write concurrently
897
983
  // with the holder that won the restart race. Kill the adopted process only after
898
984
  // confirming its persisted pid identity; a reused pid must never receive a signal.
@@ -916,7 +1002,10 @@ export class SubAgentRunManager {
916
1002
  // Clear the stale key first so settlement cannot delete the other run's lease.
917
1003
  record.leaseKey = undefined;
918
1004
  await this.persist(record).catch((error) => {
919
- log.logWarning(`Failed to persist cleared lease for run ${record.runId}`, errorMessage(error));
1005
+ log.logWarn("subagent.lease.persist_failed", "Cleared lease persist failed", {
1006
+ reason: errorMessage(error),
1007
+ fields: { runId: record.runId },
1008
+ });
920
1009
  });
921
1010
  await this.settle(record.runId, {
922
1011
  status: "lost",
@@ -931,13 +1020,19 @@ export class SubAgentRunManager {
931
1020
  durationEstimated: true,
932
1021
  outputText: "",
933
1022
  }, { announce: true }).catch((error) => {
934
- log.logWarning(`Failed to settle lease-conflicted run ${record?.runId}`, errorMessage(error));
1023
+ log.logWarn("subagent.settle.failed", "Lease-conflicted run settlement failed", {
1024
+ reason: errorMessage(error),
1025
+ fields: { runId: record?.runId },
1026
+ });
935
1027
  });
936
1028
  continue;
937
1029
  }
938
1030
  }
939
1031
  await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
940
- log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
1032
+ log.logWarn("subagent.reconcile.failed", "External run reconcile failed", {
1033
+ reason: errorMessage(error),
1034
+ fields: { runId: record?.runId },
1035
+ });
941
1036
  });
942
1037
  if (record.status === "running")
943
1038
  this.scheduleExternalRecovery(record);
@@ -950,7 +1045,10 @@ export class SubAgentRunManager {
950
1045
  if (!record.wakeEnqueued) {
951
1046
  const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => "");
952
1047
  await this.announce(record, outputText, Boolean(outputText.trim())).catch((error) => {
953
- log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
1048
+ log.logWarn("subagent.wake.reannounce_failed", "Run re-announce failed", {
1049
+ reason: errorMessage(error),
1050
+ fields: { runId: record?.runId },
1051
+ });
954
1052
  });
955
1053
  }
956
1054
  }
@@ -1052,6 +1150,7 @@ export class SubAgentRunManager {
1052
1150
  terminationReason: record.terminationReason,
1053
1151
  maxWallTimeSec,
1054
1152
  mutates: record.mutates,
1153
+ workspaceBaseline: record.workspaceBaseline,
1055
1154
  }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
1056
1155
  }
1057
1156
  /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
@@ -1088,7 +1187,10 @@ export class SubAgentRunManager {
1088
1187
  if (!current || current.status !== "running")
1089
1188
  return;
1090
1189
  void this.reconcileExternalRunAtDeadline(current).catch((error) => {
1091
- log.logWarning(`Failed to reconcile adopted external run ${current.runId}`, errorMessage(error));
1190
+ log.logWarn("subagent.reconcile.failed", "Adopted external run reconcile failed", {
1191
+ reason: errorMessage(error),
1192
+ fields: { runId: current.runId },
1193
+ });
1092
1194
  });
1093
1195
  }, Math.max(0, record.deadlineAt - Date.now()));
1094
1196
  timer.unref?.();
@@ -1111,7 +1213,10 @@ export class SubAgentRunManager {
1111
1213
  if (!isTerminal(record.status))
1112
1214
  continue;
1113
1215
  await this.collectGarbageIfExpired(record, now).catch((error) => {
1114
- log.logWarning(`Failed to garbage-collect sub-agent run ${record.runId}`, errorMessage(error));
1216
+ log.logWarn("subagent.gc.failed", "Run garbage collection failed", {
1217
+ reason: errorMessage(error),
1218
+ fields: { runId: record.runId },
1219
+ });
1115
1220
  });
1116
1221
  }
1117
1222
  }
@@ -1166,9 +1271,9 @@ export function createSubAgentRuntime(options = {}) {
1166
1271
  collectingGarbage = true;
1167
1272
  try {
1168
1273
  for (const manager of managers.values()) {
1169
- await manager
1170
- .collectGarbage()
1171
- .catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
1274
+ await manager.collectGarbage().catch((error) => log.logWarn("subagent.gc.failed", "Run garbage collection pass failed", {
1275
+ reason: errorMessage(error),
1276
+ }));
1172
1277
  }
1173
1278
  }
1174
1279
  finally {
@@ -1219,7 +1324,7 @@ export function createSubAgentRuntime(options = {}) {
1219
1324
  channelIds = await listRecordChannelIds(stateDir);
1220
1325
  }
1221
1326
  catch (error) {
1222
- log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
1327
+ log.logWarn("subagent.scan.failed", "Persisted run scan failed", { reason: errorMessage(error) });
1223
1328
  return 0;
1224
1329
  }
1225
1330
  let restored = 0;
@@ -1229,7 +1334,7 @@ export function createSubAgentRuntime(options = {}) {
1229
1334
  // Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
1230
1335
  await collectGarbageAllChannels();
1231
1336
  if (restored > 0) {
1232
- log.logInfo(`Restored ${restored} sub-agent run record(s)`);
1337
+ log.logInfoEvent("subagent.restore.done", "Sub-agent run records restored", { fields: { count: restored } });
1233
1338
  }
1234
1339
  return restored;
1235
1340
  }
@@ -1,4 +1,4 @@
1
- import { type AgentEvent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
1
+ import { type AgentEvent, type AgentMessage, type AgentState, type AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { Type } from "typebox";
4
4
  import type { Executor } from "../executor.js";
@@ -106,6 +106,14 @@ export interface SubAgentToolOptions {
106
106
  convergenceWallClockMs?: number;
107
107
  /** Test-only override for the D2 sync grace window; defaults to SYNC_GRACE_MS. */
108
108
  syncGraceMs?: number;
109
+ /** Test-only override for the transient-error retry backoff base; defaults to RETRY_BASE_DELAY_MS. */
110
+ retryBaseDelayMs?: number;
111
+ /**
112
+ * `settings.fallbackModel`, resolved the way the main agent resolves it (spec 017): `null` when
113
+ * unset, unresolvable or missing a key. An internal run that still fails after its transient
114
+ * retries switches to it once, like the main turn does.
115
+ */
116
+ resolveFallbackModel?: () => Promise<Model<Api> | null>;
109
117
  /** Channel manager owned by the application; also a seam for admission failures. */
110
118
  getRunManager: (channelId: string) => SubAgentRunManager;
111
119
  /** Present only inside a task session: every delegation is bound to this task automatically (spec 052, D4). */
@@ -123,10 +131,15 @@ interface SubAgentWorker {
123
131
  state: {
124
132
  messages: AgentMessage[];
125
133
  tools: AgentTool<any>[];
134
+ model?: Model<Api>;
135
+ thinkingLevel?: AgentState["thinkingLevel"];
126
136
  };
127
137
  subscribe(listener: (event: AgentEvent) => void): () => void;
128
138
  abort(): void;
129
139
  prompt(input: string): Promise<void>;
140
+ /** Resume from the current transcript (last message a user or tool result). Without it a
141
+ * provider error cannot be retried in place, so the run fails as before. */
142
+ continue?(): Promise<void>;
130
143
  waitForIdle(): Promise<void>;
131
144
  }
132
145
  /**
@@ -183,24 +196,18 @@ export declare function buildVerificationProtocol(taskPath: string | undefined,
183
196
  */
184
197
  export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
185
198
  /**
186
- * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
187
- * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
188
- * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
189
- * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
190
- * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
199
+ * The task envelope both runtimes' first dispatch sends (a follow-up sends `buildFollowUpTask`
200
+ * instead). `config` is narrowed to `{ name }` — the only field this function reads.
191
201
  */
192
202
  export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext): string;
193
- /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
194
- * D7) so `subagent_run op=follow_up` only needs to wire these three fields, not the full tool
195
- * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
196
- export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "runtimeContext" | "workspaceDir">;
197
203
  /**
198
- * Spec 050, D12: `memory: index` injects the same three sections the main agent's first-turn
199
- * bootstrap does — workspace MEMORY.md, the channel index, today's journal tail — at half the
200
- * main agent's budget. No per-call LLM recall: a sub-agent task is short-lived, so there is no
201
- * "first turn" to bootstrap once and reuse; it gets the same snapshot every dispatch.
204
+ * The envelope for `subagent_run op=follow_up`. A resumed session already holds the first
205
+ * dispatch's whole envelope — runtime paths, injected memory/context blocks, the role — so sending
206
+ * it again only re-bills that context and buries the new instruction. Only what is new goes: the
207
+ * artifact directory (fresh per run) and the instruction itself, plus the checker protocol again
208
+ * for a verify run, since its final VERDICT line is what settlement reads.
202
209
  */
203
- export declare function buildContextualBlocks(config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory">, options: ContextualBlocksOptions): Promise<string[]>;
210
+ export declare function buildFollowUpTask(task: string, runtimeContext: SubAgentToolOptions["runtimeContext"], runContext: SubAgentRunContext): string;
204
211
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolFields>;
205
212
  export declare function createSubAgentInlineTool(options: SubAgentToolOptions): AgentTool<typeof subagentInlineSchema, SubAgentToolFields>;
206
213
  export {};