@oyasmi/pipiclaw 0.9.0-beta.6 → 0.9.0-beta.8

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 (82) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +154 -132
  3. package/dist/agent/commands.d.ts +6 -0
  4. package/dist/agent/job-manager.js +6 -10
  5. package/dist/agent/progress-formatter.js +3 -3
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.js +2 -1
  8. package/dist/main.js +2 -1
  9. package/dist/memory/extraction.js +0 -1
  10. package/dist/memory/maintenance-gates.d.ts +1 -1
  11. package/dist/memory/maintenance-jobs.js +2 -3
  12. package/dist/memory/metadata.d.ts +0 -15
  13. package/dist/memory/metadata.js +0 -7
  14. package/dist/memory/probation.d.ts +1 -5
  15. package/dist/memory/probation.js +2 -6
  16. package/dist/memory/review-log.js +0 -0
  17. package/dist/memory/scheduler.d.ts +1 -0
  18. package/dist/memory/scheduler.js +64 -6
  19. package/dist/models/auth-cli.d.ts +1 -1
  20. package/dist/models/auth-cli.js +3 -2
  21. package/dist/paths.d.ts +0 -6
  22. package/dist/paths.js +0 -6
  23. package/dist/playbooks/agent-delegation.md +2 -2
  24. package/dist/runtime/app-home.d.ts +32 -0
  25. package/dist/runtime/app-home.js +319 -0
  26. package/dist/runtime/bootstrap.d.ts +1 -67
  27. package/dist/runtime/bootstrap.js +114 -512
  28. package/dist/runtime/delivery.js +1 -1
  29. package/dist/runtime/dingtalk.d.ts +7 -6
  30. package/dist/runtime/dingtalk.js +5 -13
  31. package/dist/runtime/durable-dispatch.d.ts +1 -0
  32. package/dist/runtime/durable-dispatch.js +36 -25
  33. package/dist/runtime/subagent-commands.js +48 -10
  34. package/dist/runtime/task-wake.d.ts +54 -0
  35. package/dist/runtime/task-wake.js +99 -0
  36. package/dist/shared/host-process.d.ts +25 -9
  37. package/dist/shared/host-process.js +59 -10
  38. package/dist/shared/wake-claim.d.ts +23 -0
  39. package/dist/shared/wake-claim.js +26 -0
  40. package/dist/subagents/discovery.d.ts +25 -1
  41. package/dist/subagents/discovery.js +108 -17
  42. package/dist/subagents/external/claude-code.js +13 -5
  43. package/dist/subagents/external/codex-cli.js +9 -3
  44. package/dist/subagents/external/exec.js +1 -0
  45. package/dist/subagents/external/harness.d.ts +22 -0
  46. package/dist/subagents/external/harness.js +40 -7
  47. package/dist/subagents/external/run.d.ts +23 -3
  48. package/dist/subagents/external/run.js +113 -123
  49. package/dist/subagents/external/settlement.d.ts +50 -0
  50. package/dist/subagents/external/settlement.js +123 -0
  51. package/dist/subagents/format.d.ts +4 -0
  52. package/dist/subagents/format.js +7 -0
  53. package/dist/subagents/runs.d.ts +70 -13
  54. package/dist/subagents/runs.js +202 -118
  55. package/dist/subagents/tool.d.ts +27 -2
  56. package/dist/subagents/tool.js +92 -48
  57. package/dist/subagents/verification-outcome.d.ts +26 -0
  58. package/dist/subagents/verification-outcome.js +16 -0
  59. package/dist/subagents/workspace-lease.d.ts +10 -1
  60. package/dist/subagents/workspace-lease.js +15 -2
  61. package/dist/tools/index.js +6 -0
  62. package/dist/tools/memory-manage.js +0 -1
  63. package/dist/tools/subagent-manage.d.ts +20 -6
  64. package/dist/tools/subagent-manage.js +86 -16
  65. package/dist/tui/app.d.ts +1 -1
  66. package/dist/tui/app.js +3 -2
  67. package/dist/tui/cli.d.ts +1 -1
  68. package/dist/tui/cli.js +1 -1
  69. package/dist/tui/terminal-media-sender.d.ts +1 -1
  70. package/examples/sub-agents/README.md +15 -14
  71. package/examples/sub-agents/builder-hard.md +9 -8
  72. package/examples/sub-agents/builder.md +12 -11
  73. package/examples/sub-agents/documenter.md +11 -12
  74. package/examples/sub-agents/explorer.md +16 -13
  75. package/examples/sub-agents/git-committer.md +17 -16
  76. package/examples/sub-agents/log-sifter.md +19 -16
  77. package/examples/sub-agents/planner.md +17 -17
  78. package/examples/sub-agents/reviewer.md +13 -21
  79. package/examples/sub-agents/scout.md +5 -4
  80. package/examples/sub-agents/verifier.md +8 -12
  81. package/examples/sub-agents/worker.md +7 -6
  82. package/package.json +1 -1
@@ -7,7 +7,7 @@ import type { SecurityConfig } from "../security/types.js";
7
7
  import type { PipiclawMemoryRecallSettings } from "../settings.js";
8
8
  import type { UsageTotals } from "../shared/types.js";
9
9
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
10
- import { type ResolvedSubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
10
+ import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
11
11
  import { getSubAgentRunManager } from "./runs.js";
12
12
  declare const subagentSchema: Type.TObject<{
13
13
  label: Type.TString;
@@ -107,7 +107,9 @@ interface SubAgentWorker {
107
107
  * only caps what gets echoed into the parent's context.
108
108
  */
109
109
  export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
110
- interface SubAgentRunContext {
110
+ /** Exported for `subagent_manage op=follow_up` (spec 042 D7), which constructs one of these for
111
+ * its own new run rather than a hand-rolled envelope. */
112
+ export interface SubAgentRunContext {
111
113
  runId: string;
112
114
  purpose: "work" | "verify";
113
115
  taskId?: string;
@@ -122,5 +124,28 @@ interface SubAgentRunContext {
122
124
  declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
123
125
  /** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
124
126
  export declare function buildVerificationProtocol(taskPath: string): string;
127
+ /**
128
+ * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
129
+ * protocol terminal to prove it even ran to completion, and a target with an active write lease
130
+ * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
131
+ * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
132
+ * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
133
+ * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
134
+ */
135
+ export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
136
+ /**
137
+ * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
138
+ * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
139
+ * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
140
+ * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
141
+ * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
142
+ */
143
+ export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext, returns: "text" | "artifact"): string;
144
+ /** Exported for `subagent_manage op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
145
+ /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
146
+ * D7) so `subagent_manage op=follow_up` only needs to wire these six fields, not the full tool
147
+ * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
148
+ export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "getMemoryRecallSettings" | "runtimeContext" | "workspaceDir" | "resolveApiKey" | "memoryCandidateStore">;
149
+ export declare function buildContextualBlocks(task: string, config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory" | "description">, options: ContextualBlocksOptions, currentModel: Model<Api>): Promise<string[]>;
125
150
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolDetails>;
126
151
  export {};
@@ -17,11 +17,12 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
17
17
  import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
18
18
  import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
19
19
  import { readStoredTask } from "../tasks/store.js";
20
- import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
20
+ import { writeVerificationAttestation } from "../tasks/verification.js";
21
21
  import { buildToolSet } from "../tools/registry.js";
22
- import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
22
+ import { externalRoleFingerprint, formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
23
23
  import { launchExternalRun } from "./external/run.js";
24
24
  import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
25
+ import { resolveVerificationOutcome } from "./verification-outcome.js";
25
26
  import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
26
27
  const subagentSchema = Type.Object({
27
28
  label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
@@ -290,7 +291,36 @@ export function buildVerificationProtocol(taskPath) {
290
291
  "- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
291
292
  ].join("\n");
292
293
  }
293
- function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
294
+ /**
295
+ * D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
296
+ * protocol terminal to prove it even ran to completion, and a target with an active write lease
297
+ * is refused up front (cheaper than explaining afterward why the attestation would be worthless).
298
+ * Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
299
+ * dispatch does — before this function existed, follow_up on a role that had since been hot-edited
300
+ * to `mutates: write` would silently take the write lease and dispatch instead of refusing.
301
+ */
302
+ export function assertVerifyAdmissible(config, purpose, workingDirectory) {
303
+ if (purpose !== "verify")
304
+ return;
305
+ if (config.mutates === "write") {
306
+ throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
307
+ }
308
+ if (config.runtime === "external" && config.harness === "exec") {
309
+ throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
310
+ }
311
+ const holder = findWorkspaceLeaseHolder(workingDirectory);
312
+ if (holder) {
313
+ throw new RecoverableToolError(`Cannot verify "${workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
314
+ }
315
+ }
316
+ /**
317
+ * Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
318
+ * envelope the same way the initial dispatch does rather than a hand-rolled approximation.
319
+ * `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
320
+ * caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
321
+ * `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
322
+ */
323
+ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
294
324
  const taskText = task.trim();
295
325
  const lines = [
296
326
  `Runtime context:`,
@@ -345,7 +375,7 @@ function stripRuntimeContextWrapper(renderedText) {
345
375
  .replace(/\s*<\/runtime_context>$/i, "")
346
376
  .trim();
347
377
  }
348
- async function buildContextualBlocks(task, config, options, currentModel) {
378
+ export async function buildContextualBlocks(task, config, options, currentModel) {
349
379
  if (config.contextMode !== "contextual") {
350
380
  return [];
351
381
  }
@@ -460,27 +490,24 @@ export function createSubAgentTool(options) {
460
490
  }
461
491
  const config = invocation.config;
462
492
  const returns = params.returns ?? "text";
493
+ // Spec 042 D3: `returns: "artifact"` has no external equivalent — the marker protocol
494
+ // scopes a produced file to `artifactDir`, but an external agent's real output lives in
495
+ // its working directory. Implementing it would build a same-named, different-meaning
496
+ // protocol; rejecting it is honest about the mismatch. An external run's full output
497
+ // always lands in `output.md` regardless (spec 032 D4), so this loses nothing — a caller
498
+ // that needs a specific artifact location says so in the task text.
499
+ if (config.runtime === "external" && returns === "artifact") {
500
+ throw new RecoverableToolError(`Sub-agent "${config.name}" is external; returns: "artifact" has no effect on external roles ` +
501
+ "(their full output always lands in output.md). State the desired output file in the task text instead.");
502
+ }
463
503
  const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
464
504
  // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
465
505
  // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
466
506
  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
- }
507
+ // D9: an independent verifier checks against a target that isn't moving under it — shared
508
+ // with `subagent_manage op=follow_up` (spec 042 D7) so a verify run's admission rules
509
+ // cannot drift between the two dispatch paths.
510
+ assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
484
511
  // Admission: a write-mutating run takes an exclusive workspace lease before it is even
485
512
  // registered (spec 040, D10.1) — a rejected delegation should never count as "started".
486
513
  // Read runs and purpose=verify never take one. Shared by both runtimes.
@@ -498,16 +525,21 @@ export function createSubAgentTool(options) {
498
525
  }
499
526
  if (config.runtime === "external") {
500
527
  if (!config.harness) {
501
- releaseWorkspaceLease(leaseKey);
528
+ releaseWorkspaceLease(leaseKey, runContext.runId);
502
529
  throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
503
530
  }
531
+ let launchResult;
504
532
  try {
505
533
  // D9/T5: external roles get the same task envelope internal workers do — runtime
506
534
  // paths, injected context blocks, and (for purpose=verify) the verification
507
535
  // protocol — rather than the raw task text (spec 040 gap closed post-review).
536
+ // Spec 042 D3: `returns: "artifact"` is rejected for external above, so this is
537
+ // always "text" here — passed literally rather than the `returns` variable so the
538
+ // ARTIFACT marker protocol is never injected into an external envelope, which no
539
+ // external result parser has ever read.
508
540
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
509
- const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns);
510
- await launchExternalRun({
541
+ const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, "text");
542
+ launchResult = await launchExternalRun({
511
543
  runId: runContext.runId,
512
544
  channelId: options.runtimeContext.channelId,
513
545
  channelDir: options.channelDir,
@@ -529,14 +561,27 @@ export function createSubAgentTool(options) {
529
561
  taskId: runContext.taskId,
530
562
  leaseKey,
531
563
  mutates: config.mutates,
564
+ roleFingerprint: externalRoleFingerprint(config),
532
565
  workspaceDir: options.workspaceDir,
533
566
  securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
534
567
  });
535
568
  }
536
569
  catch (error) {
537
- releaseWorkspaceLease(leaseKey);
570
+ // Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
571
+ // every failure past that point settles the run itself and already released this
572
+ // lease (spec 042 D2/D5), so this catch must not release it a second time.
573
+ releaseWorkspaceLease(leaseKey, runContext.runId);
538
574
  throw error;
539
575
  }
576
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
577
+ // "[Dispatched]" placeholder the model would wait on forever — two of the three
578
+ // failure kinds never used to announce at all. `settle()` already released the lease.
579
+ if (!launchResult.ok) {
580
+ if (launchResult.kind === "missing-binary") {
581
+ 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.`);
582
+ }
583
+ throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
584
+ }
540
585
  // D2: external's sync grace window is always 0 — always the dispatched placeholder,
541
586
  // never an inline wait. The run keeps going in the background and wakes the channel.
542
587
  return {
@@ -574,7 +619,7 @@ export function createSubAgentTool(options) {
574
619
  apiKey = await options.resolveApiKey(config.model);
575
620
  }
576
621
  catch (error) {
577
- releaseWorkspaceLease(leaseKey);
622
+ releaseWorkspaceLease(leaseKey, runContext.runId);
578
623
  throw error;
579
624
  }
580
625
  const startedAt = Date.now();
@@ -609,7 +654,7 @@ export function createSubAgentTool(options) {
609
654
  catch (error) {
610
655
  // Until the durable running record exists, setup still owns the lease. A channel/host
611
656
  // admission rejection or required persist failure must leave no invisible writer lock.
612
- releaseWorkspaceLease(leaseKey);
657
+ releaseWorkspaceLease(leaseKey, runContext.runId);
613
658
  throw error;
614
659
  }
615
660
  const emitUpdate = (text) => {
@@ -789,32 +834,31 @@ export function createSubAgentTool(options) {
789
834
  : undefined);
790
835
  const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
791
836
  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"
837
+ // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
838
+ // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
839
+ // run's own output does and does not prove. Only the attestation write (and its
840
+ // "enforced" strength) stays here, since only the internal path structurally removes
841
+ // write/edit from the verifier's tool set.
842
+ const verification = runContext.purpose === "verify"
843
+ ? resolveVerificationOutcome({
844
+ subjectBefore: verifierSubjectBefore,
845
+ subjectAfter: verifierSubjectAfter,
846
+ gitStateBefore: verifierGitStateBefore,
847
+ gitStateAfter: verifierGitStateAfter,
848
+ finalText,
849
+ runFailed: Boolean(effectiveFailureReason),
850
+ })
803
851
  : 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);
852
+ const verificationVerdict = verification?.verdict;
853
+ if (runContext.purpose === "verify" && runContext.taskId && verification) {
810
854
  await writeVerificationAttestation(options.channelDir, {
811
855
  runId: runContext.runId,
812
856
  taskId: runContext.taskId,
813
- verdict: verificationVerdict,
857
+ verdict: verification.verdict,
814
858
  checkedAt: formatLocalTime(),
815
- evidence,
816
- workspaceChanged: Boolean(workspaceChanged),
817
- subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
859
+ evidence: verification.evidence,
860
+ workspaceChanged: verification.workspaceChanged,
861
+ subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
818
862
  subjectDir: runContext.workingDirectory,
819
863
  // Internal verify always keeps write/edit structurally removed from the
820
864
  // verifier's tool set (buildSubagentTools above) — a real, enforced gate.
@@ -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) {
@@ -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
  }
@@ -96,7 +96,6 @@ export function createMemoryManageTool(options) {
96
96
  metadata: {
97
97
  kind: normalizeMemoryKind(kind),
98
98
  sourceType: "user",
99
- trust: "explicit",
100
99
  probationUntil: null,
101
100
  },
102
101
  },
@@ -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 {};
@@ -1,11 +1,12 @@
1
- import { join } from "node:path";
1
+ import { dirname, join } from "node:path";
2
2
  import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
5
+ import { externalRoleFingerprint } from "../subagents/discovery.js";
5
6
  import { launchExternalRun } from "../subagents/external/run.js";
6
- import { elapsedMs, formatCost, formatDuration, harnessLabel } from "../subagents/format.js";
7
+ import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
7
8
  import { getSubAgentRunManager } from "../subagents/runs.js";
8
- import { buildVerificationProtocol } from "../subagents/tool.js";
9
+ import { assertVerifyAdmissible, buildContextualBlocks, buildSubAgentTask, } from "../subagents/tool.js";
9
10
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "../subagents/workspace-lease.js";
10
11
  const subagentManageSchema = Type.Object({
11
12
  label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
@@ -16,12 +17,14 @@ const subagentManageSchema = Type.Object({
16
17
  runId: Type.Optional(Type.String({ description: "Required for cancel and follow_up." })),
17
18
  task: Type.Optional(Type.String({ description: "Follow-up instruction. Required for op=follow_up." })),
18
19
  });
20
+ /** Spec 042 D9: cap on `op=list`'s output — see the call site for why running runs are exempt. */
21
+ const LIST_CAP = 50;
19
22
  function formatRunLine(record) {
20
23
  const task = record.taskId ? `, task ${record.taskId}` : "";
21
24
  const lease = record.leaseKey ? ", lease held" : "";
22
25
  const cost = formatCost(record);
23
26
  const costPart = cost ? `, ${cost}` : "";
24
- const header = `- [${record.runId}] ${record.agent} (${harnessLabel(record)}) — "${record.label}" — ${record.status} (${formatDuration(elapsedMs(record))}${task}${lease}${costPart})`;
27
+ const header = `- [${record.runId}] ${record.agent} (${harnessLabel(record)}) — "${record.label}" — ${record.status} (${formatRunDuration(record)}${task}${lease}${costPart})`;
25
28
  if (record.status === "failed" && record.failureReason) {
26
29
  return `${header}\n failed: ${record.failureReason}`;
27
30
  }
@@ -47,9 +50,25 @@ export function createSubAgentManageTool(options) {
47
50
  parameters: subagentManageSchema,
48
51
  execute: async (_toolCallId, { op, runId, task }) => {
49
52
  if (op === "list") {
50
- const runs = manager().list();
51
- const text = runs.length === 0 ? "No delegation runs." : runs.map(formatRunLine).join("\n");
52
- return { content: [{ type: "text", text }], details: { kind: "subagent_manage", op, runs } };
53
+ // Spec 042 D9: this used to return every run on the channel, unbounded, in both the
54
+ // text and `details.runs` — a long-lived channel could dump thousands of historical
55
+ // records into a single tool result. Running runs (the ones a decision might depend
56
+ // on) are never dropped; only the terminal tail is capped, newest first.
57
+ const allRuns = manager().list();
58
+ const running = allRuns.filter((record) => record.status === "running");
59
+ const terminal = allRuns
60
+ .filter((record) => record.status !== "running")
61
+ .sort((a, b) => (b.finishedAt ?? b.startedAt) - (a.finishedAt ?? a.startedAt));
62
+ const shownTerminal = terminal.slice(0, Math.max(0, LIST_CAP - running.length));
63
+ const runs = [...running, ...shownTerminal];
64
+ const lines = runs.length === 0 ? ["No delegation runs."] : runs.map(formatRunLine);
65
+ if (runs.length < allRuns.length) {
66
+ lines.push(`… showing ${runs.length} of ${allRuns.length} runs (all running + most recently finished). Ask about a specific runId if you need an older one not shown here.`);
67
+ }
68
+ return {
69
+ content: [{ type: "text", text: lines.join("\n") }],
70
+ details: { kind: "subagent_manage", op, runs },
71
+ };
53
72
  }
54
73
  if (!runId) {
55
74
  throw new RecoverableToolError(`${op} requires runId.`);
@@ -106,6 +125,19 @@ export function createSubAgentManageTool(options) {
106
125
  if (role.shell) {
107
126
  throw new RecoverableToolError(`Role "${record.agent}" runs its command through a shell, which has no way to carry a resume session id. Delegate a new run instead, carrying forward whatever context it needs.`);
108
127
  }
128
+ // Spec 042 D7: verify admission is re-checked against the *current* role config, shared
129
+ // with the initial dispatch — a role hot-edited to mutates: write since the original run
130
+ // must not silently take the write lease and dispatch just because it once was read-only.
131
+ assertVerifyAdmissible(role, record.purpose, record.workingDirectory);
132
+ // Spec 042 D7: a role hot-edited since the original dispatch (different command, model,
133
+ // or shell mode) would resume the old session under a harness invocation it never wrote.
134
+ // Only enforced when the original run actually recorded a fingerprint — an older record
135
+ // predating this field cannot be checked, so it is let through rather than made
136
+ // permanently unresumable.
137
+ const currentFingerprint = externalRoleFingerprint(role);
138
+ if (record.roleFingerprint !== undefined && record.roleFingerprint !== currentFingerprint) {
139
+ throw new RecoverableToolError(`Role "${record.agent}" has changed (command, model, or shell mode) since run "${resolvedRunId}" was dispatched; resuming under the new config could reinterpret the old session incorrectly. Delegate a new run instead.`);
140
+ }
109
141
  // A short, human-typeable id (spec 041) — the follow-up gets a fresh identity, not the
110
142
  // dispatching tool call's own id.
111
143
  const newRunId = manager().mintRunId();
@@ -121,13 +153,42 @@ export function createSubAgentManageTool(options) {
121
153
  }
122
154
  leaseKey = lease.leaseKey;
123
155
  }
124
- // The initial dispatch envelopes verify runs with the protocol (tool.ts); a follow-up
125
- // on a verify run must carry the same protocol, not just the bare instruction (D9).
126
- const envelopedTask = record.purpose === "verify" && record.taskId
127
- ? `${task.trim()}\n\n${buildVerificationProtocol(join(options.workspaceDir ?? "", options.channelId, "tasks", `${record.taskId}.md`))}`
128
- : task;
156
+ // Spec 042 D7: the same `<subagent-artifacts>/<runId>` layout the initial dispatch uses,
157
+ // computed with a real path join rather than a regex substitution that assumed the old
158
+ // runId was the last path segment with no separators of its own.
159
+ const artifactDir = join(dirname(record.artifactDir), newRunId);
160
+ const runContext = {
161
+ runId: newRunId,
162
+ purpose: record.purpose,
163
+ taskId: record.taskId,
164
+ workingDirectory: record.workingDirectory,
165
+ artifactDir,
166
+ };
167
+ // Spec 042 D7: the same envelope construction the initial dispatch uses — runtime context
168
+ // (including this run's own artifact directory), paths/session/memory context blocks, and
169
+ // (for a verify run) the verification protocol — not a hand-rolled "task + maybe verify
170
+ // protocol" that left the external agent unaware of its own working/artifact directories.
171
+ // `getCurrentModel`/`resolveApiKey` are only needed for the `memory: relevant` recall path
172
+ // inside `buildContextualBlocks` — optional here so a caller that only ever exercises
173
+ // list/cancel is not forced to wire an LLM-backed dependency it will never use. Absent
174
+ // either, context blocks degrade to none rather than guessing at a model or key.
175
+ const contextualBlocks = options.getCurrentModel && options.resolveApiKey
176
+ ? await buildContextualBlocks(task, role, {
177
+ channelDir: options.channelDir,
178
+ workspaceDir: options.workspaceDir,
179
+ runtimeContext: { workspaceDir: options.workspaceDir, channelId: options.channelId },
180
+ getMemoryRecallSettings: options.getMemoryRecallSettings,
181
+ resolveApiKey: options.resolveApiKey,
182
+ memoryCandidateStore: options.memoryCandidateStore,
183
+ }, options.getCurrentModel())
184
+ : [];
185
+ const envelopedTask = buildSubAgentTask(task, role, { workspaceDir: options.workspaceDir, channelId: options.channelId }, contextualBlocks, runContext,
186
+ // returns: "artifact" has no external equivalent (spec 042 D3) and follow_up never
187
+ // requests it — always "text", matching the initial external dispatch.
188
+ "text");
189
+ let launchResult;
129
190
  try {
130
- await launchExternalRun({
191
+ launchResult = await launchExternalRun({
131
192
  runId: newRunId,
132
193
  channelId: options.channelId,
133
194
  channelDir: options.channelDir,
@@ -144,13 +205,14 @@ export function createSubAgentManageTool(options) {
144
205
  systemPrompt: role.systemPrompt,
145
206
  task: envelopedTask,
146
207
  workingDirectory: record.workingDirectory,
147
- artifactDir: record.artifactDir.replace(/[^/\\]+$/, newRunId),
208
+ artifactDir,
148
209
  purpose: record.purpose,
149
210
  taskId: record.taskId,
150
211
  leaseKey,
151
212
  resumeSessionId: record.sessionId,
152
213
  mutates: role.mutates,
153
- workspaceDir: options.workspaceDir ?? "",
214
+ roleFingerprint: currentFingerprint,
215
+ workspaceDir: options.workspaceDir,
154
216
  securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
155
217
  });
156
218
  }
@@ -158,9 +220,17 @@ export function createSubAgentManageTool(options) {
158
220
  // Until launchExternalRun has durably registered the run, no settlement authority owns
159
221
  // this lease. Releasing here mirrors the initial subagent dispatch path and covers prompt,
160
222
  // artifact, audit, invocation, and pre-spawn failures in follow_up.
161
- releaseWorkspaceLease(leaseKey);
223
+ releaseWorkspaceLease(leaseKey, newRunId);
162
224
  throw error;
163
225
  }
226
+ // Spec 042 D2: a pre-spawn failure is reported in this same turn — settle() already
227
+ // released the lease, so there is nothing left to clean up here.
228
+ if (!launchResult.ok) {
229
+ if (launchResult.kind === "missing-binary") {
230
+ throw new Error(`Follow-up on run "${resolvedRunId}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the follow-up was not dispatched.`);
231
+ }
232
+ throw new RecoverableToolError(`Follow-up on run "${resolvedRunId}" failed to launch: ${launchResult.reason} The follow-up was not dispatched.`);
233
+ }
164
234
  return {
165
235
  content: [
166
236
  {
package/dist/tui/app.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
2
2
  export interface TuiAppOptions {
3
3
  channel?: string;
4
4
  /** One-shot, non-interactive run: process a single prompt then exit. */