@oyasmi/pipiclaw 0.9.0-beta.7 → 0.9.0-beta.9

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 (77) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +21 -2
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/agent/job-manager.d.ts +3 -3
  6. package/dist/agent/job-manager.js +0 -1
  7. package/dist/agent/runner-factory.d.ts +16 -4
  8. package/dist/agent/runner-factory.js +9 -23
  9. package/dist/agent/types.d.ts +9 -1
  10. package/dist/agent/types.js +3 -16
  11. package/dist/memory/review-log.js +0 -0
  12. package/dist/memory/scheduler.d.ts +1 -0
  13. package/dist/memory/scheduler.js +64 -6
  14. package/dist/playbooks/agent-delegation.md +2 -2
  15. package/dist/runtime/bootstrap.d.ts +10 -2
  16. package/dist/runtime/bootstrap.js +83 -55
  17. package/dist/runtime/channel-event.d.ts +41 -0
  18. package/dist/runtime/channel-event.js +1 -0
  19. package/dist/runtime/delivery.d.ts +3 -2
  20. package/dist/runtime/dingtalk.d.ts +9 -31
  21. package/dist/runtime/durable-dispatch.d.ts +4 -2
  22. package/dist/runtime/durable-dispatch.js +36 -25
  23. package/dist/runtime/events.d.ts +3 -2
  24. package/dist/runtime/events.js +2 -3
  25. package/dist/runtime/subagent-commands.js +48 -10
  26. package/dist/runtime/task-commands.js +2 -2
  27. package/dist/runtime/task-driver.d.ts +7 -7
  28. package/dist/runtime/task-driver.js +1 -4
  29. package/dist/runtime/task-migration.js +1 -1
  30. package/dist/runtime/task-wake.d.ts +4 -4
  31. package/dist/settings.d.ts +0 -106
  32. package/dist/settings.js +0 -224
  33. package/dist/shared/host-process.d.ts +25 -9
  34. package/dist/shared/host-process.js +59 -10
  35. package/dist/shared/types.d.ts +1 -0
  36. package/dist/shared/types.js +10 -1
  37. package/dist/subagents/discovery.d.ts +24 -0
  38. package/dist/subagents/discovery.js +103 -17
  39. package/dist/subagents/external/claude-code.js +10 -3
  40. package/dist/subagents/external/codex-cli.js +9 -3
  41. package/dist/subagents/external/exec.js +1 -0
  42. package/dist/subagents/external/harness.d.ts +22 -0
  43. package/dist/subagents/external/harness.js +22 -4
  44. package/dist/subagents/external/run.d.ts +23 -3
  45. package/dist/subagents/external/run.js +112 -131
  46. package/dist/subagents/external/settlement.d.ts +50 -0
  47. package/dist/subagents/external/settlement.js +123 -0
  48. package/dist/subagents/format.d.ts +4 -0
  49. package/dist/subagents/format.js +7 -0
  50. package/dist/subagents/runs.d.ts +73 -16
  51. package/dist/subagents/runs.js +197 -120
  52. package/dist/subagents/tool.d.ts +38 -6
  53. package/dist/subagents/tool.js +93 -61
  54. package/dist/subagents/verification-outcome.d.ts +26 -0
  55. package/dist/subagents/verification-outcome.js +16 -0
  56. package/dist/subagents/workspace-lease.d.ts +10 -1
  57. package/dist/subagents/workspace-lease.js +15 -2
  58. package/dist/tasks/ledger.js +1 -1
  59. package/dist/{shared → tasks}/task-schedule.js +1 -1
  60. package/dist/tools/bash.js +1 -1
  61. package/dist/tools/event-manage.js +1 -4
  62. package/dist/tools/grep.js +2 -3
  63. package/dist/tools/index.js +6 -0
  64. package/dist/tools/job.js +5 -5
  65. package/dist/tools/memory-manage.js +3 -6
  66. package/dist/tools/session-search.js +0 -1
  67. package/dist/tools/skill-manage.js +3 -3
  68. package/dist/tools/subagent-manage.d.ts +20 -6
  69. package/dist/tools/subagent-manage.js +88 -18
  70. package/dist/tools/task-manage/shared.js +2 -2
  71. package/dist/tools/task-manage.js +1 -4
  72. package/dist/tools/web-fetch.js +0 -1
  73. package/dist/tui/app.js +4 -4
  74. package/package.json +1 -1
  75. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  76. /package/dist/{shared → tasks}/task-events.js +0 -0
  77. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -15,13 +15,15 @@ import { splitH1Sections } from "../shared/markdown-sections.js";
15
15
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
16
16
  import { RecoverableToolError } from "../shared/recoverable-error.js";
17
17
  import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
18
+ import { createEmptyUsageTotals } from "../shared/types.js";
18
19
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
19
20
  import { readStoredTask } from "../tasks/store.js";
20
- import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
21
+ import { writeVerificationAttestation } from "../tasks/verification.js";
21
22
  import { buildToolSet } from "../tools/registry.js";
22
- import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
23
+ import { externalRoleFingerprint, formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
23
24
  import { launchExternalRun } from "./external/run.js";
24
25
  import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
26
+ import { resolveVerificationOutcome } from "./verification-outcome.js";
25
27
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
26
28
  const subagentSchema = Type.Object({
27
29
  label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
@@ -156,16 +158,6 @@ async function gitWorkspaceState(executor) {
156
158
  const result = await executor.exec("git status --porcelain=v1 --untracked-files=all", { timeout: 30 });
157
159
  return result.code === 0 ? result.stdout : undefined;
158
160
  }
159
- function createEmptyUsageTotals() {
160
- return {
161
- input: 0,
162
- output: 0,
163
- cacheRead: 0,
164
- cacheWrite: 0,
165
- total: 0,
166
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
167
- };
168
- }
169
161
  function isAssistantMessage(message) {
170
162
  return typeof message === "object" && message !== null && "role" in message && message.role === "assistant";
171
163
  }
@@ -290,7 +282,36 @@ export function buildVerificationProtocol(taskPath) {
290
282
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
291
283
  ].join("\n");
292
284
  }
293
- function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
285
+ /**
286
+ * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
287
+ * protocol terminal to prove it even ran to completion, and a target with an active write lease
288
+ * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
289
+ * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
290
+ * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
291
+ * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
292
+ */
293
+ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
294
+ if (purpose !== "verify")
295
+ return;
296
+ if (config.mutates === "write") {
297
+ throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
298
+ }
299
+ if (config.runtime === "external" && config.harness === "exec") {
300
+ throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
301
+ }
302
+ const holder = findWorkspaceLeaseHolder(workingDirectory);
303
+ if (holder) {
304
+ throw new RecoverableToolError(`Cannot verify "${workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
305
+ }
306
+ }
307
+ /**
308
+ * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
309
+ * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
310
+ * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
311
+ * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
312
+ * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
313
+ */
314
+ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
294
315
  const taskText = task.trim();
295
316
  const lines = [
296
317
  `Runtime context:`,
@@ -345,7 +366,7 @@ function stripRuntimeContextWrapper(renderedText) {
345
366
  .replace(/\s*<\/runtime_context>$/i, "")
346
367
  .trim();
347
368
  }
348
- async function buildContextualBlocks(task, config, options, currentModel) {
369
+ export async function buildContextualBlocks(task, config, options, currentModel) {
349
370
  if (config.contextMode !== "contextual") {
350
371
  return [];
351
372
  }
@@ -398,7 +419,6 @@ function filterToolsByName(allTools, names) {
398
419
  }
399
420
  function createDetails(config, runContext, usage, turns, toolCalls, durationMs, failed, failureReason, verificationVerdict, extras) {
400
421
  return {
401
- kind: "subagent",
402
422
  agent: config.name,
403
423
  source: config.source,
404
424
  model: formatModelReference(config.model),
@@ -460,27 +480,24 @@ export function createSubAgentTool(options) {
460
480
  }
461
481
  const config = invocation.config;
462
482
  const returns = params.returns ?? "text";
483
+ // Spec 042 D3: `returns: "artifact"` has no external equivalent — the marker protocol
484
+ // scopes a produced file to `artifactDir`, but an external agent's real output lives in
485
+ // its working directory. Implementing it would build a same-named, different-meaning
486
+ // protocol; rejecting it is honest about the mismatch. An external run's full output
487
+ // always lands in `output.md` regardless (spec 032 D4), so this loses nothing — a caller
488
+ // that needs a specific artifact location says so in the task text.
489
+ if (config.runtime === "external" && returns === "artifact") {
490
+ throw new RecoverableToolError(`Sub-agent "${config.name}" is external; returns: "artifact" has no effect on external roles ` +
491
+ "(their full output always lands in output.md). State the desired output file in the task text instead.");
492
+ }
463
493
  const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
464
494
  // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
465
495
  // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
466
496
  const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
467
- // D9: an independent verifier checks against a target that isn't moving under it. It
468
- // never takes a lease itself, but a target with an active write lease is refused up
469
- // front — cheaper than explaining afterward why the attestation is worthless.
470
- if (runContext.purpose === "verify") {
471
- // A role that admits it writes cannot also be the checker, and `exec` has no protocol
472
- // terminal to prove it even ran to completion — both are hard "no"s, not advisories.
473
- if (config.mutates === "write") {
474
- throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
475
- }
476
- if (config.runtime === "external" && config.harness === "exec") {
477
- throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
478
- }
479
- const holder = findWorkspaceLeaseHolder(runContext.workingDirectory);
480
- if (holder) {
481
- throw new RecoverableToolError(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
482
- }
483
- }
497
+ // D9: an independent verifier checks against a target that isn't moving under it — shared
498
+ // with `subagent_manage op=follow_up` (spec 042 D7) so a verify run's admission rules
499
+ // cannot drift between the two dispatch paths.
500
+ assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
484
501
  // Admission: a write-mutating run takes an exclusive workspace lease before it is even
485
502
  // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
486
503
  // Read runs and purpose=verify never take one. Shared by both runtimes.
@@ -498,16 +515,21 @@ export function createSubAgentTool(options) {
498
515
  }
499
516
  if (config.runtime === "external") {
500
517
  if (!config.harness) {
501
- releaseWorkspaceLease(leaseKey);
518
+ releaseWorkspaceLease(leaseKey, runContext.runId);
502
519
  throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
503
520
  }
521
+ let launchResult;
504
522
  try {
505
523
  // D9/T5: external roles get the same task envelope internal workers do — runtime
506
524
  // paths, injected context blocks, and (for purpose=verify) the verification
507
525
  // protocol — rather than the raw task text (spec 040 gap closed post-review).
526
+ // Spec 042 D3: `returns: "artifact"` is rejected for external above, so this is
527
+ // always "text" here — passed literally rather than the `returns` variable so the
528
+ // ARTIFACT marker protocol is never injected into an external envelope, which no
529
+ // external result parser has ever read.
508
530
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
509
- const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns);
510
- await launchExternalRun({
531
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, "text");
532
+ launchResult = await launchExternalRun({
511
533
  runId: runContext.runId,
512
534
  channelId: options.runtimeContext.channelId,
513
535
  channelDir: options.channelDir,
@@ -529,14 +551,27 @@ export function createSubAgentTool(options) {
529
551
  taskId: runContext.taskId,
530
552
  leaseKey,
531
553
  mutates: config.mutates,
554
+ roleFingerprint: externalRoleFingerprint(config),
532
555
  workspaceDir: options.workspaceDir,
533
556
  securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
534
557
  });
535
558
  }
536
559
  catch (error) {
537
- releaseWorkspaceLease(leaseKey);
560
+ // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
561
+ // every failure past that point settles the run itself and already released this
562
+ // lease (spec 042 D2/D5), so this catch must not release it a second time.
563
+ releaseWorkspaceLease(leaseKey, runContext.runId);
538
564
  throw error;
539
565
  }
566
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
567
+ // "[Dispatched]" placeholder the model would wait on forever — two of the three
568
+ // failure kinds never used to announce at all. `settle()` already released the lease.
569
+ if (!launchResult.ok) {
570
+ if (launchResult.kind === "missing-binary") {
571
+ throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
572
+ }
573
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
574
+ }
540
575
  // D2: external's sync grace window is always 0 — always the dispatched placeholder,
541
576
  // never an inline wait. The run keeps going in the background and wakes the channel.
542
577
  return {
@@ -549,7 +584,6 @@ export function createSubAgentTool(options) {
549
584
  },
550
585
  ],
551
586
  details: {
552
- kind: "subagent",
553
587
  agent: config.name,
554
588
  source: config.source,
555
589
  model: config.externalModelRef ?? "unknown",
@@ -574,7 +608,7 @@ export function createSubAgentTool(options) {
574
608
  apiKey = await options.resolveApiKey(config.model);
575
609
  }
576
610
  catch (error) {
577
- releaseWorkspaceLease(leaseKey);
611
+ releaseWorkspaceLease(leaseKey, runContext.runId);
578
612
  throw error;
579
613
  }
580
614
  const startedAt = Date.now();
@@ -609,7 +643,7 @@ export function createSubAgentTool(options) {
609
643
  catch (error) {
610
644
  // Until the durable running record exists, setup still owns the lease. A channel/host
611
645
  // admission rejection or required persist failure must leave no invisible writer lock.
612
- releaseWorkspaceLease(leaseKey);
646
+ releaseWorkspaceLease(leaseKey, runContext.runId);
613
647
  throw error;
614
648
  }
615
649
  const emitUpdate = (text) => {
@@ -789,32 +823,31 @@ export function createSubAgentTool(options) {
789
823
  : undefined);
790
824
  const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
791
825
  const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
792
- const workspaceChanged = runContext.purpose === "verify" &&
793
- (verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
794
- ? verifierSubjectBefore !== verifierSubjectAfter
795
- : verifierGitStateBefore !== undefined &&
796
- verifierGitStateAfter !== undefined &&
797
- verifierGitStateBefore !== verifierGitStateAfter);
798
- const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
799
- const verificationVerdict = runContext.purpose === "verify"
800
- ? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
801
- ? "pass"
802
- : "fail"
826
+ // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
827
+ // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
828
+ // run's own output does and does not prove. Only the attestation write (and its
829
+ // "enforced" strength) stays here, since only the internal path structurally removes
830
+ // write/edit from the verifier's tool set.
831
+ const verification = runContext.purpose === "verify"
832
+ ? resolveVerificationOutcome({
833
+ subjectBefore: verifierSubjectBefore,
834
+ subjectAfter: verifierSubjectAfter,
835
+ gitStateBefore: verifierGitStateBefore,
836
+ gitStateAfter: verifierGitStateAfter,
837
+ finalText,
838
+ runFailed: Boolean(effectiveFailureReason),
839
+ })
803
840
  : undefined;
804
- if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
805
- const evidence = workspaceChanged
806
- ? "Verifier changed tracked workspace files; the attestation is invalid."
807
- : !declaredVerdict
808
- ? "Verifier did not emit the required final VERDICT marker."
809
- : finalText.trim().slice(0, 8_000);
841
+ const verificationVerdict = verification?.verdict;
842
+ if (runContext.purpose === "verify" && runContext.taskId && verification) {
810
843
  await writeVerificationAttestation(options.channelDir, {
811
844
  runId: runContext.runId,
812
845
  taskId: runContext.taskId,
813
- verdict: verificationVerdict,
846
+ verdict: verification.verdict,
814
847
  checkedAt: formatLocalTime(),
815
- evidence,
816
- workspaceChanged: Boolean(workspaceChanged),
817
- subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
848
+ evidence: verification.evidence,
849
+ workspaceChanged: verification.workspaceChanged,
850
+ subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
818
851
  subjectDir: runContext.workingDirectory,
819
852
  // Internal verify always keeps write/edit structurally removed from the
820
853
  // verifier's tool set (buildSubagentTools above) — a real, enforced gate.
@@ -926,7 +959,6 @@ export function createSubAgentTool(options) {
926
959
  },
927
960
  ],
928
961
  details: {
929
- kind: "subagent",
930
962
  agent: config.name,
931
963
  source: config.source,
932
964
  model: formatModelReference(config.model),
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The `purpose=verify` judgment rule, shared by the internal verifier path (`tool.ts`) and the
3
+ * external one (`external/settlement.ts`) — spec 042 D1. Internal and external verify differ in
4
+ * how "did the workspace change" is observed (subject hash vs. a git-status fallback for
5
+ * internal; subject hash only for external, since it has no `Executor` to run `git status`
6
+ * through), which is why both inputs are accepted here rather than picking one. This function
7
+ * does no I/O; writing the attestation itself stays with each caller because `verificationStrength`
8
+ * ("enforced" internal vs. "advisory" external) is a fact only the caller knows.
9
+ */
10
+ export interface ResolveVerificationOutcomeInput {
11
+ subjectBefore?: string;
12
+ subjectAfter?: string;
13
+ /** Internal-only fallback, used when a subject hash could not be computed on either side. */
14
+ gitStateBefore?: string;
15
+ gitStateAfter?: string;
16
+ finalText: string;
17
+ /** Whether the underlying run itself failed or aborted — a verifier that never finished cleanly
18
+ * cannot produce a trustworthy PASS regardless of what it printed. */
19
+ runFailed: boolean;
20
+ }
21
+ export interface VerificationOutcome {
22
+ verdict: "pass" | "fail";
23
+ workspaceChanged: boolean;
24
+ evidence: string;
25
+ }
26
+ export declare function resolveVerificationOutcome(input: ResolveVerificationOutcomeInput): VerificationOutcome;
@@ -0,0 +1,16 @@
1
+ import { parseVerificationVerdict } from "../tasks/verification.js";
2
+ export function resolveVerificationOutcome(input) {
3
+ const workspaceChanged = input.subjectBefore !== undefined && input.subjectAfter !== undefined
4
+ ? input.subjectBefore !== input.subjectAfter
5
+ : input.gitStateBefore !== undefined &&
6
+ input.gitStateAfter !== undefined &&
7
+ input.gitStateBefore !== input.gitStateAfter;
8
+ const declaredVerdict = parseVerificationVerdict(input.finalText);
9
+ const verdict = declaredVerdict === "pass" && !input.runFailed && !workspaceChanged ? "pass" : "fail";
10
+ const evidence = workspaceChanged
11
+ ? "Verifier changed tracked workspace files; the attestation is invalid."
12
+ : !declaredVerdict
13
+ ? "Verifier did not emit the required final VERDICT marker."
14
+ : input.finalText.trim().slice(0, 8_000);
15
+ return { verdict, workspaceChanged, evidence };
16
+ }
@@ -30,7 +30,16 @@ export type AcquireWorkspaceLeaseResult = {
30
30
  heldBy: WorkspaceLeaseHolder;
31
31
  };
32
32
  export declare function acquireWorkspaceLease(holder: WorkspaceLeaseHolder): AcquireWorkspaceLeaseResult;
33
- export declare function releaseWorkspaceLease(leaseKey: string | undefined): void;
33
+ /**
34
+ * Spec 042 D5: release only the caller's own lease. A blind `leases.delete(key)` let a restore
35
+ * whose lease-rebuild failed (a real path — `realpath` can drift under a symlink swap) still
36
+ * `settle()` and delete the *new* holder's lease for the same key, and a caller could otherwise
37
+ * double-release harmlessly-in-appearance but incorrectly-in-general. `runId` must match the
38
+ * current holder for the delete to happen; anything else (already released, held by someone else)
39
+ * is a no-op rather than an assertion failure — callers already treat "did I ever hold it" as
40
+ * something they cannot always know for certain (e.g. a settle() racing a lease rebuild).
41
+ */
42
+ export declare function releaseWorkspaceLease(leaseKey: string | undefined, runId: string): void;
34
43
  /** Read-only check for a pre-flight gate (e.g. `purpose=verify`, D9) that must not itself take a lease. */
35
44
  export declare function findWorkspaceLeaseHolder(workingDirectory: string): WorkspaceLeaseHolder | undefined;
36
45
  export declare function formatWorkspaceLeaseConflict(heldBy: WorkspaceLeaseHolder): string;
@@ -33,9 +33,22 @@ export function acquireWorkspaceLease(holder) {
33
33
  leases.set(leaseKey, holder);
34
34
  return { ok: true, leaseKey };
35
35
  }
36
- export function releaseWorkspaceLease(leaseKey) {
37
- if (leaseKey)
36
+ /**
37
+ * Spec 042 D5: release only the caller's own lease. A blind `leases.delete(key)` let a restore
38
+ * whose lease-rebuild failed (a real path — `realpath` can drift under a symlink swap) still
39
+ * `settle()` and delete the *new* holder's lease for the same key, and a caller could otherwise
40
+ * double-release harmlessly-in-appearance but incorrectly-in-general. `runId` must match the
41
+ * current holder for the delete to happen; anything else (already released, held by someone else)
42
+ * is a no-op rather than an assertion failure — callers already treat "did I ever hold it" as
43
+ * something they cannot always know for certain (e.g. a settle() racing a lease rebuild).
44
+ */
45
+ export function releaseWorkspaceLease(leaseKey, runId) {
46
+ if (!leaseKey)
47
+ return;
48
+ const holder = leases.get(leaseKey);
49
+ if (holder && holder.runId === runId) {
38
50
  leases.delete(leaseKey);
51
+ }
39
52
  }
40
53
  /** Read-only check for a pre-flight gate (e.g. `purpose=verify`, D9) that must not itself take a lease. */
41
54
  export function findWorkspaceLeaseHolder(workingDirectory) {
@@ -2,8 +2,8 @@ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
4
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
5
- import { nextTaskWake } from "../shared/task-schedule.js";
6
5
  import { createDefaultTaskControl, parseTaskControl, taskPriorityRank } from "./control.js";
6
+ import { nextTaskWake } from "./task-schedule.js";
7
7
  import { normalizeStoredStatus, wasLegacyEscalated } from "./transitions.js";
8
8
  const FRONTMATTER_FIELDS = [
9
9
  "status",
@@ -1,5 +1,5 @@
1
1
  import { Cron } from "croner";
2
- import { errorMessage } from "./text-utils.js";
2
+ import { errorMessage } from "../shared/text-utils.js";
3
3
  /**
4
4
  * The cron cadence of a recurring task lives in its `schedule` frontmatter key.
5
5
  * Cron is always interpreted in the host timezone — tasks (and events) follow the
@@ -152,7 +152,7 @@ export function createBashTool(executor, options = {}) {
152
152
  : "It runs off-turn and will NOT wake you when it finishes; check it with the job tool (op:poll/list)."),
153
153
  },
154
154
  ],
155
- details: { kind: "bash", async: { state: "running", jobId: job.id } },
155
+ details: { async: { state: "running", jobId: job.id } },
156
156
  };
157
157
  }
158
158
  const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
@@ -170,10 +170,7 @@ export function createEventManageTool(options) {
170
170
  });
171
171
  return {
172
172
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
173
- details: {
174
- kind: "event_manage",
175
- ...result,
176
- },
173
+ details: { ...result },
177
174
  };
178
175
  },
179
176
  };
@@ -203,7 +203,7 @@ export function createGrepTool(executor, options = {}) {
203
203
  text: `No matches found in ${scope}. Try a broader pattern, drop the glob, or widen the path.`,
204
204
  },
205
205
  ],
206
- details: { kind: "grep", matchCount: 0, fileCount: 0 },
206
+ details: { matchCount: 0, fileCount: 0 },
207
207
  };
208
208
  }
209
209
  files.sort((a, b) => a[0].localeCompare(b[0]));
@@ -219,7 +219,7 @@ export function createGrepTool(executor, options = {}) {
219
219
  text: `No more matching files (skip=${startOffset} is past the last of ${files.length}).`,
220
220
  },
221
221
  ],
222
- details: { kind: "grep", matchCount: 0, fileCount: files.length },
222
+ details: { matchCount: 0, fileCount: files.length },
223
223
  };
224
224
  }
225
225
  const blocks = [];
@@ -249,7 +249,6 @@ export function createGrepTool(executor, options = {}) {
249
249
  return {
250
250
  content: [{ type: "text", text: outputText }],
251
251
  details: {
252
- kind: "grep",
253
252
  matchCount: shownMatchCount,
254
253
  fileCount: files.length,
255
254
  shownFileCount: page.length,
@@ -68,6 +68,12 @@ export function createPipiclawTools(options) {
68
68
  getSubAgentDiscovery: options.getSubAgentDiscovery,
69
69
  workspaceDir: options.workspaceDir,
70
70
  securityConfig,
71
+ // Spec 042 D7: follow_up builds its envelope through the same buildContextualBlocks
72
+ // the initial dispatch uses, which needs these to resolve a memory: relevant recall.
73
+ getCurrentModel: options.getCurrentModel,
74
+ resolveApiKey: options.resolveApiKey,
75
+ getMemoryRecallSettings: options.getMemoryRecallSettings,
76
+ memoryCandidateStore: options.memoryCandidateStore,
71
77
  }), "subagent_manage"),
72
78
  ];
73
79
  }
package/dist/tools/job.js CHANGED
@@ -49,7 +49,7 @@ export function createJobTool(options) {
49
49
  const text = outcomes.map((outcome) => `- [${outcome.id}] ${outcome.status}`).join("\n");
50
50
  return {
51
51
  content: [{ type: "text", text: `Cancel results:\n${text}` }],
52
- details: { kind: "job", op: "cancel", outcomes },
52
+ details: { op: "cancel", outcomes },
53
53
  };
54
54
  }
55
55
  if (op === "list") {
@@ -57,12 +57,12 @@ export function createJobTool(options) {
57
57
  if (jobs.length === 0) {
58
58
  return {
59
59
  content: [{ type: "text", text: "No background jobs." }],
60
- details: { kind: "job", op: "list", jobs },
60
+ details: { op: "list", jobs },
61
61
  };
62
62
  }
63
63
  return {
64
64
  content: [{ type: "text", text: jobs.map(formatJobLine).join("\n") }],
65
- details: { kind: "job", op: "list", jobs },
65
+ details: { op: "list", jobs },
66
66
  };
67
67
  }
68
68
  // poll
@@ -70,7 +70,7 @@ export function createJobTool(options) {
70
70
  if (jobs.length === 0) {
71
71
  return {
72
72
  content: [{ type: "text", text: "No matching running jobs to wait for." }],
73
- details: { kind: "job", op: "poll", jobs },
73
+ details: { op: "poll", jobs },
74
74
  };
75
75
  }
76
76
  const finished = jobs.filter((job) => job.status !== "running");
@@ -85,7 +85,7 @@ export function createJobTool(options) {
85
85
  }
86
86
  return {
87
87
  content: [{ type: "text", text: parts.join("\n\n") }],
88
- details: { kind: "job", op: "poll", jobs },
88
+ details: { op: "poll", jobs },
89
89
  };
90
90
  },
91
91
  };
@@ -83,7 +83,7 @@ export function createMemoryManageTool(options) {
83
83
  rejectMissingArgument("save", "content", args);
84
84
  }
85
85
  if (containsSecret(trimmed)) {
86
- return textResult("This content looks like a credential or secret, so it was not saved. Store the secret in an approved secret manager and remember only its location.", { kind: "memory_manage", op: "save", saved: false, blockedReason: "secret" });
86
+ return textResult("This content looks like a credential or secret, so it was not saved. Store the secret in an approved secret manager and remember only its location.", { op: "save", saved: false, blockedReason: "secret" });
87
87
  }
88
88
  // Serialize through the shared channel memory queue so this never races with background
89
89
  // consolidation/maintenance on the same channel's files.
@@ -105,7 +105,6 @@ export function createMemoryManageTool(options) {
105
105
  ? `Saved to channel memory${kind ? ` (${kind})` : ""}.`
106
106
  : "That memory is already present; no duplicate was added.";
107
107
  return textResult(message, {
108
- kind: "memory_manage",
109
108
  op: "save",
110
109
  saved: result.added > 0 || result.skippedDuplicate > 0,
111
110
  });
@@ -134,13 +133,12 @@ export function createMemoryManageTool(options) {
134
133
  candidateStore: options.memoryCandidateStore,
135
134
  });
136
135
  if (items.length === 0) {
137
- return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, { kind: "memory_manage", op: "search", resultCount: 0 });
136
+ return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, { op: "search", resultCount: 0 });
138
137
  }
139
138
  const rendered = items
140
139
  .map((item, index) => `${index + 1}. [${item.source}/${item.title}] ${item.content}`)
141
140
  .join("\n");
142
141
  return textResult(`Found ${items.length} stored memory entr${items.length === 1 ? "y" : "ies"}:\n\n${rendered}`, {
143
- kind: "memory_manage",
144
142
  op: "search",
145
143
  resultCount: items.length,
146
144
  });
@@ -157,7 +155,6 @@ export function createMemoryManageTool(options) {
157
155
  const matches = entries.filter((entry) => entry.content === trimmed || entry.content.toLowerCase().includes(needle));
158
156
  if (matches.length === 0) {
159
157
  return textResult(`No stored memory entry matched "${trimmed}"; nothing was removed.`, {
160
- kind: "memory_manage",
161
158
  op: "forget",
162
159
  forgotten: false,
163
160
  });
@@ -180,7 +177,7 @@ export function createMemoryManageTool(options) {
180
177
  }).catch((error) => {
181
178
  log.logWarning(`Failed to append memory review log for channel ${options.channelId}`, errorMessage(error));
182
179
  });
183
- return textResult("Removed the entry from active channel memory. Its exact content and source transcript window are tombstoned against automatic replay; if the fact is stated again later, it may be learned as new. Original session history and retention backups are unchanged.", { kind: "memory_manage", op: "forget", forgotten: true, entryId: removed.id });
180
+ return textResult("Removed the entry from active channel memory. Its exact content and source transcript window are tombstoned against automatic replay; if the fact is stated again later, it may be learned as new. Original session history and retention backups are unchanged.", { op: "forget", forgotten: true, entryId: removed.id });
184
181
  }
185
182
  return {
186
183
  name: "memory_manage",
@@ -54,7 +54,6 @@ export function createSessionSearchTool(options) {
54
54
  },
55
55
  ],
56
56
  details: {
57
- kind: "session_search",
58
57
  resultCount: response.results.length,
59
58
  searchedDocuments: response.searchedDocuments,
60
59
  },
@@ -190,7 +190,7 @@ async function viewWorkspaceSkill(options, name, filePath) {
190
190
  }
191
191
  return {
192
192
  content: [{ type: "text", text: `Skill: ${name}\nPath: ${targetPath}\n\n${body}` }],
193
- details: { kind: "skill_manage", action: "view", name, path: targetPath, truncated: truncation.truncated },
193
+ details: { action: "view", name, path: targetPath, truncated: truncation.truncated },
194
194
  };
195
195
  }
196
196
  export function createSkillManageTool(options) {
@@ -205,7 +205,7 @@ export function createSkillManageTool(options) {
205
205
  const skills = await listWorkspaceSkills(options);
206
206
  return {
207
207
  content: [{ type: "text", text: JSON.stringify({ skills }) }],
208
- details: { kind: "skill_manage", action: "list", count: skills.length },
208
+ details: { action: "list", count: skills.length },
209
209
  };
210
210
  }
211
211
  if (!args.name) {
@@ -224,7 +224,7 @@ export function createSkillManageTool(options) {
224
224
  });
225
225
  return {
226
226
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
227
- details: { kind: "skill_manage", ...result },
227
+ details: { ...result },
228
228
  };
229
229
  },
230
230
  };
@@ -1,7 +1,10 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
3
  import { Type } from "typebox";
4
+ import type { MemoryCandidateStore } from "../memory/candidates.js";
3
5
  import type { SecurityConfig } from "../security/types.js";
4
- import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
6
+ import type { PipiclawMemoryRecallSettings } from "../settings.js";
7
+ import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
5
8
  declare const subagentManageSchema: Type.TObject<{
6
9
  label: Type.TString;
7
10
  op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"cancel">, Type.TLiteral<"follow_up">]>;
@@ -10,14 +13,25 @@ declare const subagentManageSchema: Type.TObject<{
10
13
  }>;
11
14
  export interface SubAgentManageToolOptions {
12
15
  channelId: string;
13
- /** Needed only for `follow_up` on a `purpose=verify` run: where the attestation is written. */
14
- channelDir?: string;
16
+ /**
17
+ * Spec 042 D7: required, not defaulted. `follow_up` dispatches a new external process through
18
+ * the same envelope and audit path the initial dispatch uses (D9's verify task path, D8.1's
19
+ * audit log, D7's `buildSubAgentTask`) — all of which need the real value. The previous
20
+ * `options.workspaceDir ?? ""` silently pointed the audit log at the daemon's own cwd and
21
+ * malformed the verify task path; production has always supplied both, so making them required
22
+ * only tightens what was already true rather than changing production behavior.
23
+ */
24
+ workspaceDir: string;
25
+ channelDir: string;
15
26
  /** Needed only for `follow_up`: re-resolves the role's current config by name. */
16
27
  getSubAgentDiscovery?: () => SubAgentDiscoveryResult;
17
- /** Needed only for `follow_up`, which dispatches a new external process and must audit it
18
- * exactly like the initial dispatch (D8.1/T5). */
19
- workspaceDir?: string;
20
28
  securityConfig?: SecurityConfig;
29
+ /** Spec 042 D7: `follow_up` builds its envelope through the same `buildContextualBlocks` the
30
+ * initial dispatch uses — these three are what that function needs beyond `channelDir`/`workspaceDir`. */
31
+ getCurrentModel?: () => Model<Api>;
32
+ resolveApiKey?: (model: Model<Api>) => Promise<string>;
33
+ getMemoryRecallSettings?: () => PipiclawMemoryRecallSettings;
34
+ memoryCandidateStore?: MemoryCandidateStore;
21
35
  }
22
36
  export declare function createSubAgentManageTool(options: SubAgentManageToolOptions): AgentTool<typeof subagentManageSchema>;
23
37
  export {};