@oyasmi/pipiclaw 0.9.1 → 0.9.2-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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -2,6 +2,7 @@ import { mkdir, readdir, readFile, rmdir, stat, unlink } from "node:fs/promises"
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { formatDuration } from "../shared/duration.js";
5
6
  import { isProcessAlive, killProcessGroup, readProcessStartTime } from "../shared/host-process.js";
6
7
  import { RecoverableToolError } from "../shared/recoverable-error.js";
7
8
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -67,6 +68,42 @@ async function unlinkIfPresent(path) {
67
68
  function isTerminal(status) {
68
69
  return status !== "running";
69
70
  }
71
+ function createPendingSettlement(input, finishedAt, announce) {
72
+ return {
73
+ status: input.status,
74
+ failureReason: input.failureReason,
75
+ usage: input.usage,
76
+ usageKnown: input.usageKnown,
77
+ costKnown: input.costKnown,
78
+ turns: input.turns,
79
+ toolCalls: input.toolCalls,
80
+ durationMs: input.durationMs,
81
+ durationEstimated: input.durationEstimated,
82
+ verificationVerdict: input.verificationVerdict,
83
+ verificationStrength: input.verificationStrength,
84
+ sessionId: input.sessionId,
85
+ finishedAt,
86
+ announce,
87
+ };
88
+ }
89
+ function applyPendingSettlement(record, pending) {
90
+ record.status = pending.status;
91
+ record.failureReason = pending.failureReason;
92
+ record.usage = pending.usage;
93
+ record.usageKnown = pending.usageKnown;
94
+ record.costKnown = pending.costKnown;
95
+ record.turns = pending.turns;
96
+ record.toolCalls = pending.toolCalls;
97
+ record.durationMs = pending.durationMs;
98
+ record.durationEstimated = pending.durationEstimated;
99
+ record.verificationVerdict = pending.verificationVerdict;
100
+ record.verificationStrength = pending.verificationStrength;
101
+ if (pending.sessionId)
102
+ record.sessionId = pending.sessionId;
103
+ record.finishedAt = pending.finishedAt;
104
+ record.settledAt = pending.finishedAt;
105
+ record.settlementPending = undefined;
106
+ }
70
107
  function parseRunRecord(raw) {
71
108
  const value = JSON.parse(raw);
72
109
  if (!isRecord(value) ||
@@ -82,12 +119,6 @@ function parseRunRecord(raw) {
82
119
  }
83
120
  return value;
84
121
  }
85
- function formatDuration(ms) {
86
- const seconds = Math.round(ms / 1000);
87
- if (seconds < 60)
88
- return `${seconds}s`;
89
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
90
- }
91
122
  /**
92
123
  * Per-channel manager for delegation runs — the single settlement/usage/wake authority for both
93
124
  * internal sub-agents and (once wired) external harnesses (D7). Modeled directly on
@@ -99,9 +130,9 @@ export class SubAgentRunManager {
99
130
  this.channelId = channelId;
100
131
  this.options = options;
101
132
  this.runs = new Map();
102
- /** In-memory cancel handles for runs alive in *this* process (internal runs; external process
103
- * kill goes through pid, not this map, once phase 2/3 lands). Never persisted: a restart loses
104
- * the only thing that could reach an in-process worker anyway (D10.3). */
133
+ /** In-memory cancel handles for runs alive in *this* process (internal worker abort or live
134
+ * external process-group kill). Never persisted: a restart cannot reach an in-process worker,
135
+ * while adopted external runs are cancelled through their persisted pid (D10.3). */
105
136
  this.cancelHandles = new Map();
106
137
  /** External launch intents exist before a safe live child handle does. A cancel in that window
107
138
  * is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
@@ -218,7 +249,7 @@ export class SubAgentRunManager {
218
249
  // non-goals). Checked before anything is persisted, so a rejected run costs nothing.
219
250
  if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
220
251
  throw new RecoverableToolError(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
221
- "Wait for one to finish, or cancel one with subagent_manage first.");
252
+ "Wait for one to finish, or cancel one with subagent_run op=cancel first.");
222
253
  }
223
254
  if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
224
255
  throw new RecoverableToolError(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
@@ -272,26 +303,44 @@ export class SubAgentRunManager {
272
303
  * that restore treats as `lost` rather than guessing (D1/D10.3).
273
304
  */
274
305
  async setLaunched(runId, info) {
275
- const record = this.runs.get(runId);
276
- if (!record)
277
- return;
278
- record.pid = info.pid;
279
- record.pidStartedAt = info.pidStartedAt;
280
- record.argv = info.argv;
281
- record.deadlineAt = info.deadlineAt;
282
- // claude-code pre-assigns its session id before running (D4); persisting it here, not just
283
- // at settle(), means a run that crashes before any output is still resumable.
284
- if (info.sessionId)
285
- record.sessionId = info.sessionId;
286
- record.verifySubjectBefore = info.verifySubjectBefore;
287
- record.maxWallTimeSec = info.maxWallTimeSec;
288
- record.processStartedAt = info.processStartedAt;
289
- record.channelDir = info.channelDir;
290
- record.invocationWarnings = info.invocationWarnings;
291
- record.roleFingerprint = info.roleFingerprint;
292
- record.parserVersion = info.parserVersion;
293
- record.cliVersion = info.cliVersion;
294
- await this.persist(record, true);
306
+ await this.queue.run(runId, async () => {
307
+ const record = this.runs.get(runId);
308
+ if (!record || record.status !== "running")
309
+ return;
310
+ record.pid = info.pid;
311
+ record.pidStartedAt = info.pidStartedAt;
312
+ record.argv = info.argv;
313
+ record.deadlineAt = info.deadlineAt;
314
+ // claude-code pre-assigns its session id before running (D4); persisting it here, not just
315
+ // at settle(), means a run that crashes before any output is still resumable.
316
+ if (info.sessionId)
317
+ record.sessionId = info.sessionId;
318
+ record.verifySubjectBefore = info.verifySubjectBefore;
319
+ record.verifyBaseCommit = info.verifyBaseCommit;
320
+ record.verifyBaselineUntrackedPaths = info.verifyBaselineUntrackedPaths;
321
+ record.maxWallTimeSec = info.maxWallTimeSec;
322
+ record.processStartedAt = info.processStartedAt;
323
+ record.channelDir = info.channelDir;
324
+ record.invocationWarnings = info.invocationWarnings;
325
+ record.roleFingerprint = info.roleFingerprint;
326
+ record.parserVersion = info.parserVersion;
327
+ record.cliVersion = info.cliVersion;
328
+ await this.persist(record, true);
329
+ });
330
+ }
331
+ /** Persist best-effort probe results after the pid/launch recovery record is already durable.
332
+ * A slow or unavailable `ps`/`--version` probe must never reopen the post-spawn recovery window. */
333
+ async updateLaunchMetadata(runId, info) {
334
+ await this.queue.run(runId, async () => {
335
+ const record = this.runs.get(runId);
336
+ if (!record || record.status !== "running" || !record.pid)
337
+ return;
338
+ if (info.pidStartedAt !== undefined)
339
+ record.pidStartedAt = info.pidStartedAt;
340
+ if (info.cliVersion !== undefined)
341
+ record.cliVersion = info.cliVersion;
342
+ await this.persist(record);
343
+ });
295
344
  }
296
345
  /** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
297
346
  * interrupted activation, while copied text or a different dispatch id can never claim it. */
@@ -361,39 +410,35 @@ export class SubAgentRunManager {
361
410
  const record = this.runs.get(runId);
362
411
  if (!record || record.settledAt)
363
412
  return; // Idempotent: already settled, never replay.
364
- // The terminal fields are persisted, required, before any side effect runs (P0-2): a
365
- // failed persist here rolls the record back to `running` so a restart replays settlement
366
- // from scratch instead of applying side effects the disk never recorded.
413
+ // Keep the externally visible record `running` while the settlement intent is made durable.
414
+ // This preserves restart recovery without publishing a terminal status before its lease is
415
+ // released: the caller reaches settle() only after its worker/process has finished.
367
416
  const snapshot = { ...record };
368
- record.status = input.status;
369
- record.failureReason = input.failureReason;
370
- record.usage = input.usage;
371
- record.usageKnown = input.usageKnown;
372
- record.costKnown = input.costKnown;
373
- record.turns = input.turns;
374
- record.toolCalls = input.toolCalls;
375
- record.durationMs = input.durationMs;
376
- record.durationEstimated = input.durationEstimated;
377
- record.verificationVerdict = input.verificationVerdict;
378
- record.verificationStrength = input.verificationStrength;
379
- if (input.sessionId)
380
- record.sessionId = input.sessionId;
381
- record.finishedAt = Date.now();
382
- record.settledAt = record.finishedAt;
383
- try {
384
- await this.persist(record, true);
385
- }
386
- catch (error) {
387
- Object.assign(record, snapshot);
388
- throw error;
417
+ const pending = record.settlementPending ?? createPendingSettlement(input, Date.now(), options.announce);
418
+ if (!record.settlementPending) {
419
+ record.settlementPending = pending;
420
+ try {
421
+ await this.persist(record, true);
422
+ }
423
+ catch (error) {
424
+ Object.assign(record, snapshot);
425
+ throw error;
426
+ }
389
427
  }
390
428
  const outputSaved = await this.writeOutputFile(record, input.outputText);
429
+ // This is the commit point for the observable state transition. Both operations are
430
+ // synchronous and adjacent: no observer can see a terminal record while this run still
431
+ // owns the lease. The durable intent above covers a crash before this point.
391
432
  releaseWorkspaceLease(record.leaseKey, record.runId);
392
- record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
433
+ record.leaseKey = undefined;
434
+ applyPendingSettlement(record, pending);
435
+ // Terminal records never display as "lease held" (P1-4). The terminal write is best-effort:
436
+ // the durable intent above remains available for restart recovery if this publish fails,
437
+ // and the lease must not be reacquired after the process has finished.
438
+ await this.persist(record);
393
439
  this.cancelHandles.delete(runId);
394
440
  this.externalLaunches.delete(runId);
395
441
  this.clearExternalRecoveryTimer(runId);
396
- await this.persist(record);
397
442
  if (!record.usageRecorded) {
398
443
  record.usageRecorded = true;
399
444
  this.options.ledger?.record({
@@ -436,7 +481,7 @@ export class SubAgentRunManager {
436
481
  runId: record.runId,
437
482
  runtime: record.runtime,
438
483
  harness: record.harness,
439
- status: record.status,
484
+ status: pending.status,
440
485
  taskId: record.taskId,
441
486
  artifactDir: record.artifactDir,
442
487
  })
@@ -467,7 +512,7 @@ export class SubAgentRunManager {
467
512
  const tail = outputText.slice(-WAKE_OUTPUT_TAIL_CHARS).trim();
468
513
  const harnessLabel = record.harness ? `${record.runtime}/${record.harness}` : record.runtime;
469
514
  // K parallel fan-out runs otherwise produce K wake turns, each re-asking "is this the only
470
- // one?" via a fresh subagent_manage op=list call — this answers it inline (review 2026-08-23
515
+ // one?" via a fresh subagent_list call — this answers it inline (review 2026-08-23
471
516
  // §3.3), so the model can reliably reply [SILENT] to every wake but the last.
472
517
  const siblingCount = record.taskId
473
518
  ? Array.from(this.runs.values()).filter((other) => other.taskId === record.taskId && other.status === "running" && other.runId !== record.runId).length
@@ -528,7 +573,7 @@ export class SubAgentRunManager {
528
573
  record.wakeEnqueued = true;
529
574
  await this.persist(record);
530
575
  }
531
- /** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
576
+ /** Explicit cancel (`subagent_run op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
532
577
  async cancel(runId) {
533
578
  let adoptedRecord;
534
579
  const status = await this.queue.run(runId, async () => {
@@ -538,8 +583,10 @@ export class SubAgentRunManager {
538
583
  if (record.status !== "running")
539
584
  return record.status;
540
585
  const cancelHandle = this.cancelHandles.get(runId);
541
- this.cancelHandles.delete(runId);
542
586
  if (cancelHandle) {
587
+ // Keep the handle until settle() owns terminal cleanup. A worker may need an async turn to
588
+ // observe abort(); deleting it here would let a second cancel mark an active writer lost,
589
+ // release its lease, and admit another writer while the first worker can still run.
543
590
  // External: mark the reason before the handle kills the process, so whichever code
544
591
  // path settles this run reports "cancelled" instead of guessing from whatever the
545
592
  // process happened to print before it died (P1-1). This also covers
@@ -592,7 +639,9 @@ export class SubAgentRunManager {
592
639
  * Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
593
640
  * construction (D10.3): the worker lived in the process that just disappeared, so any record
594
641
  * still `running` is settled as `lost` and the channel is woken to say so. External runs are
595
- * left alone here — the harness-specific probe (spec 040 phase 2/3) reconciles those.
642
+ * left for the harness-specific probe (spec 040 phase 2/3), except an adopted write run whose
643
+ * lease cannot be rebuilt: it is killed and settled as `lost` rather than allowed to continue
644
+ * without mutual exclusion.
596
645
  */
597
646
  async restore() {
598
647
  const stateDir = this.options.stateDir;
@@ -623,6 +672,33 @@ export class SubAgentRunManager {
623
672
  }
624
673
  this.runs.set(record.runId, record);
625
674
  restored++;
675
+ if (record.settlementPending && !record.settledAt) {
676
+ // A previous process reached the settlement intent after its worker/process had
677
+ // finished, but crashed before publishing the terminal record. The old lease key is
678
+ // process-local and cannot be trusted after restart; clear it before retrying so this
679
+ // recovery cannot release a different run's lease.
680
+ const pending = record.settlementPending;
681
+ record.leaseKey = undefined;
682
+ const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => "");
683
+ await this.settle(record.runId, {
684
+ status: pending.status,
685
+ failureReason: pending.failureReason,
686
+ usage: pending.usage,
687
+ usageKnown: pending.usageKnown,
688
+ costKnown: pending.costKnown,
689
+ turns: pending.turns,
690
+ toolCalls: pending.toolCalls,
691
+ durationMs: pending.durationMs,
692
+ durationEstimated: pending.durationEstimated,
693
+ outputText,
694
+ verificationVerdict: pending.verificationVerdict,
695
+ verificationStrength: pending.verificationStrength,
696
+ sessionId: pending.sessionId,
697
+ }, { announce: pending.announce }).catch((error) => {
698
+ log.logWarning(`Failed to finish pending sub-agent settlement ${record?.runId}`, errorMessage(error));
699
+ });
700
+ continue;
701
+ }
626
702
  if (record.runtime === "internal" && record.status === "running") {
627
703
  await this.settle(record.runId, {
628
704
  status: "lost",
@@ -659,13 +735,47 @@ export class SubAgentRunManager {
659
735
  }
660
736
  else {
661
737
  log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
662
- // This run does not actually hold a lease anymore — record that honestly
663
- // (spec 042 D5) so a later settle() cannot delete a different holder's lease
664
- // for the same key, and so displays stop claiming this run still holds it.
738
+ // This run cannot safely continue without its lease: it could write concurrently
739
+ // with the holder that won the restart race. Kill the adopted process only after
740
+ // confirming its persisted pid identity; a reused pid must never receive a signal.
741
+ // Either an identity mismatch or an unavailable probe is settled as lost with the
742
+ // uncertainty recorded, instead of silently degrading to an unprotected writer
743
+ // (D10.1/D10.3).
744
+ const processIdentity = record.pid ? await this.processIdentity(record) : "unknown";
745
+ let processSafetyNote;
746
+ if (processIdentity === "same") {
747
+ await killProcessGroup(record.pid).catch(() => undefined);
748
+ processSafetyNote = " The adopted process identity matched and its process group was signalled.";
749
+ }
750
+ else if (processIdentity === "different") {
751
+ processSafetyNote =
752
+ " The persisted pid identity did not match the current process; no signal was sent.";
753
+ }
754
+ else {
755
+ processSafetyNote =
756
+ " The adopted process identity could not be confirmed; no signal was sent, so its result remains unknown.";
757
+ }
758
+ // Clear the stale key first so settlement cannot delete the other run's lease.
665
759
  record.leaseKey = undefined;
666
760
  await this.persist(record).catch((error) => {
667
761
  log.logWarning(`Failed to persist cleared lease for run ${record.runId}`, errorMessage(error));
668
762
  });
763
+ await this.settle(record.runId, {
764
+ status: "lost",
765
+ failureReason: "The daemon restarted while this write delegation's workspace lease was held by another run; its result is unknown." +
766
+ processSafetyNote,
767
+ usage: record.usage,
768
+ usageKnown: record.usageKnown,
769
+ costKnown: record.costKnown,
770
+ turns: record.turns ?? 0,
771
+ toolCalls: record.toolCalls ?? 0,
772
+ durationMs: Date.now() - (record.processStartedAt ?? record.startedAt),
773
+ durationEstimated: true,
774
+ outputText: "",
775
+ }, { announce: true }).catch((error) => {
776
+ log.logWarning(`Failed to settle lease-conflicted run ${record?.runId}`, errorMessage(error));
777
+ });
778
+ continue;
669
779
  }
670
780
  }
671
781
  await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
@@ -701,6 +811,14 @@ export class SubAgentRunManager {
701
811
  const current = await readProcessStartTime(record.pid);
702
812
  return current === record.pidStartedAt;
703
813
  }
814
+ async processIdentity(record) {
815
+ if (!record.pid || !record.pidStartedAt)
816
+ return "unknown";
817
+ const current = await readProcessStartTime(record.pid);
818
+ if (!current)
819
+ return "unknown";
820
+ return current === record.pidStartedAt ? "same" : "different";
821
+ }
704
822
  /**
705
823
  * Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
706
824
  * judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
@@ -780,6 +898,8 @@ export class SubAgentRunManager {
780
898
  terminationReason: record.terminationReason,
781
899
  maxWallTimeSec,
782
900
  verifySubjectBefore: record.verifySubjectBefore,
901
+ verifyBaseCommit: record.verifyBaseCommit,
902
+ verifyBaselineUntrackedPaths: record.verifyBaselineUntrackedPaths,
783
903
  }, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
784
904
  }
785
905
  /** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
@@ -2,6 +2,7 @@ import { type AgentEvent, type AgentMessage, type AgentTool } from "@earendil-wo
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";
5
+ import type { FileStore } from "../file-store.js";
5
6
  import type { MemoryCandidateStore } from "../memory/candidates.js";
6
7
  import type { SecurityConfig } from "../security/types.js";
7
8
  import type { PipiclawMemoryRecallSettings } from "../settings.js";
@@ -9,23 +10,34 @@ import { type UsageTotals } from "../shared/types.js";
9
10
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
10
11
  import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
11
12
  import { getSubAgentRunManager } from "./runs.js";
13
+ /**
14
+ * Role-based delegation (spec 046, D2.1): the common path. No override fields beyond routing
15
+ * ones — tools, model, effort, context, thinkingLevel and mutates all live in the role file, so
16
+ * a call naming an external role cannot pass any of them (there is nowhere for it to put them).
17
+ */
12
18
  declare const subagentSchema: Type.TObject<{
13
- label: Type.TString;
14
- agent: Type.TOptional<Type.TString>;
15
- name: Type.TOptional<Type.TString>;
19
+ agent: Type.TString;
16
20
  task: Type.TString;
17
- systemPrompt: Type.TOptional<Type.TString>;
21
+ workingDirectory: Type.TOptional<Type.TString>;
22
+ purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
23
+ taskId: Type.TOptional<Type.TString>;
24
+ }>;
25
+ /**
26
+ * Inline delegation (spec 046, D2.1): a one-off executor for when no configured role fits.
27
+ * Carries every field a role file would otherwise supply.
28
+ */
29
+ declare const subagentInlineSchema: Type.TObject<{
30
+ task: Type.TString;
31
+ systemPrompt: Type.TString;
18
32
  tools: Type.TOptional<Type.TArray<Type.TString>>;
19
33
  model: Type.TOptional<Type.TString>;
20
34
  effort: Type.TOptional<Type.TUnion<[Type.TLiteral<"quick">, Type.TLiteral<"standard">, Type.TLiteral<"deep">]>>;
21
35
  context: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
22
- paths: Type.TOptional<Type.TArray<Type.TString>>;
36
+ thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
37
+ mutates: Type.TOptional<Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"write">]>>;
23
38
  workingDirectory: Type.TOptional<Type.TString>;
24
39
  purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
25
40
  taskId: Type.TOptional<Type.TString>;
26
- returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
27
- thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
28
- mutates: Type.TOptional<Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"write">]>>;
29
41
  }>;
30
42
  /**
31
43
  * Fields the `subagent` tool itself constructs. `kind` is not among them: `withToolDetails`
@@ -46,10 +58,8 @@ export interface SubAgentToolFields {
46
58
  purpose: "work" | "verify";
47
59
  taskId?: string;
48
60
  verificationVerdict?: "pass" | "fail";
49
- /** Always populated (spec 032 D4): the full output is saved to `${artifactDir}/output.md` regardless of `returns`. */
61
+ /** Always populated (spec 032 D4): the full output is saved to `${artifactDir}/output.md`. */
50
62
  artifactDir: string;
51
- /** Set only when `returns: "artifact"` and the sub-agent emitted a valid ARTIFACT: marker. */
52
- artifactPath?: string;
53
63
  /** True when the reply text was truncated against MAX_SUBAGENT_RESULT_UNITS; the full text is still on disk. */
54
64
  resultTruncated: boolean;
55
65
  /**
@@ -61,10 +71,11 @@ export interface SubAgentToolFields {
61
71
  }
62
72
  /** The shape consumers read post-wrap, once `withToolDetails` has stamped `kind`. */
63
73
  export type SubAgentToolDetails = SubAgentToolFields & {
64
- kind: "subagent";
74
+ kind: "subagent" | "subagent_inline";
65
75
  };
66
76
  export interface SubAgentToolOptions {
67
77
  executor: Executor;
78
+ fileStore: FileStore;
68
79
  /** Host checkout used as the sub-agent's cwd. Defaults to process.cwd(). */
69
80
  workingDirectory?: string;
70
81
  /** Mirrors the parent channel's ProjectScope.boundary onto the sub-agent's own tool set (spec 043, D6.2). */
@@ -117,7 +128,7 @@ interface SubAgentWorker {
117
128
  * only caps what gets echoed into the parent's context.
118
129
  */
119
130
  export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
120
- /** Exported for `subagent_manage op=follow_up` (spec 042 D7), which constructs one of these for
131
+ /** Exported for `subagent_run op=follow_up` (spec 042 D7), which constructs one of these for
121
132
  * its own new run rather than a hand-rolled envelope. */
122
133
  export interface SubAgentRunContext {
123
134
  runId: string;
@@ -142,30 +153,30 @@ export declare function assertWithinProjectBoundary(target: string, base: string
142
153
  * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
143
154
  */
144
155
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
145
- /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
156
+ /** Shared by both runtimes' task envelopes and `subagent_run`'s verify follow-up (spec 040, D9). */
146
157
  export declare function buildVerificationProtocol(taskPath: string): string;
147
158
  /**
148
- * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
149
- * protocol terminal to prove it even ran to completion, and a target with an active write lease
150
- * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
151
- * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
152
- * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
153
- * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
159
+ * D9 verify admission — `exec` has no protocol terminal to prove it even ran to completion, and a
160
+ * target with an active write lease is refused up front. A write-capable verifier is allowed: it
161
+ * takes the same exclusive lease as a work writer and receives an advisory attestation.
162
+ * Spec 042 D7: exported so `subagent_run op=follow_up` runs the exact same checks the initial
163
+ * dispatch does, including the remaining `exec` restriction.
154
164
  */
155
165
  export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
156
166
  /**
157
- * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
167
+ * Exported for `subagent_run op=follow_up` (spec 042 D7), which builds a follow-up run's task
158
168
  * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
159
169
  * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
160
170
  * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
161
171
  * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
162
172
  */
163
- export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext, returns: "text" | "artifact"): string;
164
- /** Exported for `subagent_manage op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
173
+ export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext): string;
174
+ /** Exported for `subagent_run op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
165
175
  /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
166
- * D7) so `subagent_manage op=follow_up` only needs to wire these six fields, not the full tool
176
+ * D7) so `subagent_run op=follow_up` only needs to wire these six fields, not the full tool
167
177
  * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
168
178
  export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "getMemoryRecallSettings" | "runtimeContext" | "workspaceDir" | "resolveApiKey" | "memoryCandidateStore">;
169
179
  export declare function buildContextualBlocks(task: string, config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory" | "description">, options: ContextualBlocksOptions, currentModel: Model<Api>): Promise<string[]>;
170
180
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolFields>;
181
+ export declare function createSubAgentInlineTool(options: SubAgentToolOptions): AgentTool<typeof subagentInlineSchema, SubAgentToolFields>;
171
182
  export {};