@henryqw/pi-subagent 27.15.1 → 27.16.0

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.
@@ -0,0 +1,85 @@
1
+ # Checked workspace tasks
2
+
3
+ Use one worker to change several explicitly selected Git repositories in a non-Git workspace. The worker receives an absolute worktree map. It does not need sibling-relative paths.
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ S[Explicit repository set] --> W[One worker, separate owned worktrees]
8
+ W --> C[Check the complete candidate set]
9
+ C --> I[Stage and check the complete integration set]
10
+ I --> P[Preflight every Main target]
11
+ P --> R[Promote serially and save each receipt]
12
+ R --> X[Reconcile a partial result explicitly]
13
+ ```
14
+
15
+ ## Request
16
+
17
+ ```json
18
+ {
19
+ "mode": "isolated",
20
+ "id": "change-contract",
21
+ "goal": "Change the service and client together.",
22
+ "repositories": { "service": "/work/app/service", "client": "/work/app/client" },
23
+ "tasks": [{
24
+ "id": "change", "kind": "changeset", "role": "implementer", "modelClass": "balanced",
25
+ "requirements": "Change and test both sides of the contract.",
26
+ "deliverable": "Clean committed candidates in both selected worktrees.",
27
+ "dependsOn": [], "contextFrom": [],
28
+ "inputs": { "contract": "/work/app/contract.txt" },
29
+ "checks": [
30
+ { "repository": "service", "command": "pnpm", "args": ["test"] },
31
+ { "repository": "client", "command": "pnpm", "args": ["test"] }
32
+ ]
33
+ }],
34
+ "finalChecks": [
35
+ { "repository": "service", "command": "pnpm", "args": ["test"] },
36
+ { "repository": "client", "command": "pnpm", "args": ["test"] }
37
+ ]
38
+ }
39
+ ```
40
+
41
+ Call from `/work/app`. Each repository must be a canonical direct child with its own `.git` directory. Select 1 to 8 repositories. Aliases, linked worktrees, nested repositories, Git environment overrides, and repositories with Git submodules are not supported.
42
+
43
+ Workspace mode supports exactly one changeset task. It rejects text tasks, dependencies, task judgment, and final judgment. It has no automatic correction, retry, refresh, or restaging. The existing single-repository graph remains unchanged when `repositories` is absent.
44
+
45
+ Every selected repository needs task checks and final checks. Select commands that test that repository. The complete final command list must contain at most 32 entries. Checks must leave the tracked and untracked state clean. If the committed root `package.json` has a test script, that script is pinned from the exact Main base commit. Dirty Main files do not change the pinned script. All task and final checks reject a changed pinned script, regardless of the command name, path, or arguments. Repositories without a root manifest or test script can use their native check commands.
46
+
47
+ `PI_SUBAGENT_REPOSITORIES` contains the absolute repository-to-worktree map as JSON, which is a structured text format. `PI_SUBAGENT_INPUTS` contains the input-name-to-copy map. Check commands receive both environment variables. Task checks use worker worktrees; final checks use integration worktrees. The complete repository set is checked before and after commands, including unchanged members.
48
+
49
+ ## Root inputs
50
+
51
+ `inputs` selects up to 8 canonical regular files inside the workspace but outside every Git repository. Each file can contain at most 64 KiB. Directories and symlinks are rejected. Each request stores separate private read-only copies. A later request can select different inputs or new contents.
52
+
53
+ The worker gets copy paths, not permission to edit original inputs. Their content identities are checked with every complete-set inspection. A changed source or copy blocks validation and promotion. Inputs never become Git candidates and are never promoted or restored. This is not a sandbox: an authorized tool can bypass file permissions. A detected input change requires manual inspection.
54
+
55
+ ## Integration and recovery
56
+
57
+ Use `subagent_workspace` from the workspace root. Workspace records use their own state version; they do not change existing single-repository records. `/subagent` does not list workspace requests. Existing prune checks protect their retained repository resources.
58
+
59
+ | Action | Required fields | Result |
60
+ | --- | --- | --- |
61
+ | `status` | `id` | Read saved state without mutations. |
62
+ | `stage` | `id`, `expected` | Select the complete checked candidate map from `candidates`. Create an integration worktree in every repository. |
63
+ | `validate` | `id`, `expected` | Check the complete integration map from `tips`. |
64
+ | `promote` | `id`, `expected` | Preflight every target, then promote the exact passing `tips` serially. |
65
+ | `reconcile` | `id` | Inspect interrupted stage or promotion intents without replay. |
66
+ | `abort` | `id` | Stop the exact task-wide worker and retain all Git work. |
67
+ | `cleanup` | `id` | Remove only fully promoted, clean, exactly owned resources. |
68
+
69
+ `expected` must include every repository and its exact branch, commit, index tree, and committed tree. Partial maps are rejected. Status retains per-repository candidates, stages, intents, and promotion receipts.
70
+
71
+ Dirty Main files are preserved. Worker execution can start from the committed Main identities while Main is dirty. Staging and promotion require all Main targets to be clean and unchanged. Each promotion receipt is saved before the next repository can move. All targets are checked again between promotions.
72
+
73
+ **Promotion is not atomic.** A later repository can fail after an earlier repository moved. No rollback is attempted. After an interrupted promotion, call `reconcile`. It compares each uncertain target with its saved endpoints. A target at the promoted endpoint gets a receipt; a target still at its base becomes pending. Then explicitly call `promote` with the complete `tips` to continue. No proven promotion is repeated. Any other Main state requires manual reconciliation.
74
+
75
+ A crash during allocation does not grant ownership. Uncertain allocations and worker prompts are retained and are never adopted or replayed automatically. A completed exact merge can be reconciled after manual conflict resolution. An unstarted merge or incomplete allocation needs manual inspection and a new request. Failed and aborted work is retained; automatic discard is not available.
76
+
77
+ Worker observation uses the request's saved `childMaxMs` maximum runtime and `childIdleMs` idle limit. Only complete Pi session messages renew the idle limit; the maximum runtime does not renew. When a limit expires, the runner saves prompt failure evidence and attempts exact worker termination with a separate safety budget. Unproved termination stays visible for recovery. Every repository worktree is retained, and uncertain prompts are not replayed. These are worker limits, not a deadline for the complete request.
78
+
79
+ An active `abort` can first report a busy lifecycle lock while cancellation settles. Inspect status and repeat `abort` after the active operation ends. Session replacement cancels local observation and suppresses stale delivery, but preserves saved recovery identities.
80
+
81
+ ## Direct work
82
+
83
+ Direct requests can also supply the top-level `repositories` map. Each task uses the same selected set. A write request reserves the workspace and every selected checkout together until all exact owned workers are proved stopped. A conflict in one member refuses the whole reservation. The result labels each repository's change report or stale-read warning.
84
+
85
+ Direct selection rejects `paths` and `continueFrom`. Scope comes from the task packet. Root-file writes are not authorized by repository selection. Direct work has no checked integration, rollback, or sandbox. Other sessions and external processes are outside process-local admission.
@@ -131,6 +131,7 @@ const CHECKOUT_HEADING = "Checkout (report only, not enforced; changes by other
131
131
  function checkoutLines(note: CheckoutNote): string[] {
132
132
  const safe = (value: string) => value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
133
133
  switch (note.kind) {
134
+ case "repositories": return Object.entries(note.notes).flatMap(([name, item]) => item ? [`Repository ${safe(name)}:`, ...checkoutLines(item).map((line) => ` ${line}`)] : []);
134
135
  case "stale": return [STALE_READ_NOTICE];
135
136
  case "unavailable": return [`${note.check} unavailable: ${safe(note.reason)}`];
136
137
  case "changes": {
@@ -8,6 +8,8 @@ import { resolveExecutionPolicy } from "./config.ts";
8
8
  import { captureFallbackWarning } from "./task-model-fallback.ts";
9
9
  import { registerCheckoutAdmission } from "./admission.ts";
10
10
  import { registerIsolatedExtension } from "./isolated.ts";
11
+ import { registerWorkspaceExtension } from "./workspace.ts";
12
+ import { resolveWorkspaceScope } from "../dist/workspace-scope.js";
11
13
  import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask } from "./subagent-command.ts";
12
14
  import { MODEL_CLASS_GUIDANCE } from "./model-class-policy.ts";
13
15
  import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowResult, workerOutputForMain, type BackgroundWorkflowTransportDetails, type WorkflowTransportEntry } from "./result-transport.ts";
@@ -233,7 +235,14 @@ export default function subagentExtension(pi: ExtensionAPI): void {
233
235
  return true;
234
236
  }
235
237
  };
236
- const holdAdmission = registerCheckoutAdmission(pi, canWrite);
238
+ const holdAdmission = registerCheckoutAdmission(pi, canWrite, async (input, ctx) => {
239
+ if (!input || typeof input !== "object" || !Object.hasOwn(input, "repositories")) return [];
240
+ const parsed = parseDelegateTask(input);
241
+ if (parsed.mode !== "direct" || !parsed.workflow.repositories) return [];
242
+ const scope = await resolveWorkspaceScope(ctx.cwd, parsed.workflow.repositories);
243
+ return Object.values(scope.repositories).map(({ root }) => root);
244
+ });
245
+ const workspaceSurface = registerWorkspaceExtension(pi, currentPolicy);
237
246
  /** Resolve a Role's package resources and route for a direct Herdr launch. */
238
247
  const prepareDirectLaunch = async (role: Role, context: ExtensionContext, options: { modelClass?: ProfileName; model?: string }) => {
239
248
  const resources = await resolveRolePackageResources(role, context);
@@ -336,7 +345,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
336
345
  if (!data || typeof data !== "object" || !("sessionId" in data) || typeof data.sessionId !== "string"
337
346
  || !("pending" in data) || typeof data.pending !== "boolean") return;
338
347
  const { sessionId } = data;
339
- if ([...directTasks.values()].some((task) => task.pendingResult?.(sessionId)) || isolatedSurface.hasPendingResult(sessionId)) {
348
+ if ([...directTasks.values()].some((task) => task.pendingResult?.(sessionId)) || isolatedSurface.hasPendingResult(sessionId) || workspaceSurface.hasPendingResult(sessionId)) {
340
349
  data.pending = true;
341
350
  }
342
351
  });
@@ -777,11 +786,12 @@ export default function subagentExtension(pi: ExtensionAPI): void {
777
786
  try {
778
787
  const parsed = parseDelegateTask(args);
779
788
  const dryRun = parsed.dryRun ? { dryRun: true } : {};
780
- if (parsed.mode === "isolated") return { ...parsed.request, ...dryRun };
789
+ if (parsed.mode === "isolated" || parsed.mode === "workspace") return { ...parsed.request, ...dryRun };
781
790
  const workflow = parsed.workflow;
782
- if (workflow.mode === "single") return { mode: "direct" as const, ...workflow.delegations[0], ...dryRun };
783
- if (workflow.mode === "parallel") return { mode: "direct" as const, tasks: workflow.delegations, ...dryRun };
784
- return { mode: "direct" as const, chain: workflow.delegations, ...dryRun };
791
+ const selection = workflow.repositories ? { repositories: workflow.repositories } : {};
792
+ if (workflow.mode === "single") return { mode: "direct" as const, ...workflow.delegations[0], ...selection, ...dryRun };
793
+ if (workflow.mode === "parallel") return { mode: "direct" as const, tasks: workflow.delegations, ...selection, ...dryRun };
794
+ return { mode: "direct" as const, chain: workflow.delegations, ...selection, ...dryRun };
785
795
  } catch (error) { throw boundedError(error); }
786
796
  },
787
797
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
@@ -789,10 +799,12 @@ export default function subagentExtension(pi: ExtensionAPI): void {
789
799
  // Isolated requests read the policy in the runner; report it here with the tool's context.
790
800
  reportConfig(ctx);
791
801
  const parsed = parseDelegateTask(params);
802
+ if (parsed.mode === "workspace") return parsed.dryRun ? await workspaceSurface.plan(parsed.request, signal, ctx) : await workspaceSurface.execute(parsed.request, signal, ctx);
792
803
  if (parsed.mode === "isolated") {
793
804
  return parsed.dryRun ? await isolatedSurface.plan(parsed.request, signal, ctx) : await isolatedSurface.execute(parsed.request, signal, ctx);
794
805
  }
795
806
  const workflow = parsed.workflow;
807
+ const selected = workflow.repositories ? await resolveWorkspaceScope(ctx.cwd, workflow.repositories, signal) : undefined;
796
808
  const catalog = loadRoleCatalog();
797
809
  for (const delegation of workflow.delegations) {
798
810
  try { findRole(catalog, delegation.role); } catch (error) { throw boundedError(error); }
@@ -830,7 +842,12 @@ export default function subagentExtension(pi: ExtensionAPI): void {
830
842
  const startedAt = new Map<string, number>();
831
843
  // Launch snapshots: write requests report changes; read requests detect a stale checkout.
832
844
  const snapshots = new Map<string, CheckoutSnapshot | Error | undefined>();
845
+ const selectedSnapshots = new Map<string, Map<string, CheckoutSnapshot | Error | undefined>>();
833
846
  const checkout = async ({ id, delegation }: WorkflowEntry) => {
847
+ if (selected && selectedSnapshots.has(id)) {
848
+ const notes = await Promise.all(Object.entries(selected.repositories).map(async ([name, repo]) => [name, await checkoutNote(repo.root, selectedSnapshots.get(id)!.get(name), writes)] as const));
849
+ return { checkout: { kind: "repositories" as const, notes: Object.fromEntries(notes.filter((entry) => entry[1] !== undefined)) } };
850
+ }
834
851
  if (!snapshots.has(id)) return {};
835
852
  const note = await checkoutNote(ctx.cwd, snapshots.get(id), writes, delegation.paths);
836
853
  return note ? { checkout: note } : {};
@@ -916,12 +933,16 @@ export default function subagentExtension(pi: ExtensionAPI): void {
916
933
  startWidgetItem(entry.id, taskId, display, prepared.model.id, prepared.thinkingLevel, ctx);
917
934
  const transient = await materializeTransientLaunch({ launch: prepared, prompt: prepared.systemPrompt,
918
935
  promptArgIndex: prepared.promptArgIndex }, activeSignal);
919
- snapshots.set(entry.id, await snapshotCheckout(ctx.cwd).catch((error: unknown) => error instanceof Error ? error : new Error(String(error))));
936
+ if (selected) {
937
+ await resolveWorkspaceScope(ctx.cwd, workflow.repositories!, activeSignal);
938
+ selectedSnapshots.set(entry.id, new Map(await Promise.all(Object.entries(selected.repositories).map(async ([name, repo]) => [name,
939
+ await snapshotCheckout(repo.root).catch((error: unknown) => error instanceof Error ? error : new Error(String(error)))] as const))));
940
+ } else snapshots.set(entry.id, await snapshotCheckout(ctx.cwd).catch((error: unknown) => error instanceof Error ? error : new Error(String(error))));
920
941
  let handle: DirectHandle;
921
942
  try {
922
943
  handle = await herdr.start({ ...prepared, args: [...transient.launch.args] },
923
944
  `d-${randomUUID().replaceAll("-", "").slice(0, 24)}`, `${directRef(display)} ${display.title}`,
924
- `${entry.delegation.access === "read" ? `${entry.delegation.task}\n\n${READ_ACCESS_NOTICE}` : entry.delegation.task}\n\nFinal answer budget: ${answerBytes} bytes, conclusions first. Main sees only that much inline; a longer answer is saved to a file.`, activeSignal, (tab) => {
945
+ `${entry.delegation.access === "read" ? `${entry.delegation.task}\n\n${READ_ACCESS_NOTICE}` : entry.delegation.task}${selected ? `\n\nExplicit selected repository map: ${JSON.stringify(workflow.repositories)}. Do not modify other repositories or workspace-root files. Selection and admission are not a sandbox.` : ""}\n\nFinal answer budget: ${answerBytes} bytes, conclusions first. Main sees only that much inline; a longer answer is saved to a file.`, activeSignal, (tab) => {
925
946
  const record = { taskId, entryId: entry.id, display, ...tab };
926
947
  // Persist before agent start, or let the new session carry the exact identity after settlement.
927
948
  if (recordEpoch === directRecordEpoch) pi.appendEntry(DIRECT_TAB_TYPE, record);
@@ -9,6 +9,8 @@ import { Type, type Static } from "typebox";
9
9
  import { Check, Errors } from "typebox/value";
10
10
  import { runGit } from "../dist/git-process.js";
11
11
  import { ExecuteRequestSchema, parseExecuteRequest, type ExecuteRequest } from "../dist/schema.js";
12
+ import { WorkspaceRequestSchema, parseWorkspaceRequest, type WorkspaceRequest } from "../dist/workspace-schema.js";
13
+ import { RepositorySelectionSchema, parseRepositorySelection, type RepositorySelection } from "../dist/workspace-scope.js";
12
14
 
13
15
  export const MAX_WORKFLOW_ENTRIES = 8;
14
16
 
@@ -53,6 +55,7 @@ export const DelegationSchema = Type.Object({
53
55
 
54
56
  export const DirectWorkflowSchema = Type.Object({
55
57
  mode: Type.Literal("direct"),
58
+ repositories: Type.Optional(RepositorySelectionSchema),
56
59
  role: Type.Optional(RoleSchema),
57
60
  name: Type.Optional(TaskNameSchema),
58
61
  task: Type.Optional(TaskSchema),
@@ -75,19 +78,20 @@ export const DelegateTaskParameters = Type.Object({
75
78
  tasks: Type.Optional(Type.Union([
76
79
  Type.Array(DelegationSchema, { minItems: 1, maxItems: MAX_WORKFLOW_ENTRIES }),
77
80
  ExecuteRequestSchema.properties.tasks,
81
+ WorkspaceRequestSchema.properties.tasks,
78
82
  ])),
79
- finalChecks: ExecuteRequestSchema.properties.finalChecks,
83
+ finalChecks: Type.Optional(Type.Union([ExecuteRequestSchema.properties.finalChecks, WorkspaceRequestSchema.properties.finalChecks])),
80
84
  finalJudgment: ExecuteRequestSchema.properties.finalJudgment,
81
85
  dryRun: Type.Optional(DryRunSchema),
82
86
  }, { additionalProperties: false });
83
87
 
84
88
  export type Delegation = Static<typeof DelegationSchema> & { kind: "text" };
85
89
  export type WorkflowMode = "single" | "parallel" | "chain";
86
- export type ParsedWorkflow =
90
+ export type ParsedWorkflow = (
87
91
  | { mode: "single"; delegations: [Delegation] }
88
92
  | { mode: "parallel"; delegations: Delegation[] }
89
- | { mode: "chain"; delegations: Delegation[] };
90
- export type ParsedDelegateTask = ({ mode: "direct"; workflow: ParsedWorkflow } | { mode: "isolated"; request: ExecuteRequest }) & { dryRun: boolean };
93
+ | { mode: "chain"; delegations: Delegation[] }) & { repositories?: RepositorySelection };
94
+ export type ParsedDelegateTask = ({ mode: "direct"; workflow: ParsedWorkflow } | { mode: "isolated"; request: ExecuteRequest } | { mode: "workspace"; request: WorkspaceRequest }) & { dryRun: boolean };
91
95
 
92
96
  type DirectInput = Static<typeof DirectWorkflowSchema>;
93
97
  const DELEGATION_KEYS = ["role", "name", "task", "access", "paths", "continueFrom", "kind", "model", "modelClass"] as const;
@@ -167,6 +171,10 @@ export function parseWorkflow(value: unknown): ParsedWorkflow {
167
171
  const workflow: ParsedWorkflow = mode === "single" ? { mode, delegations: [normalizeDelegation(input as Static<typeof DelegationSchema>, "workflow")] }
168
172
  : mode === "parallel" ? { mode, delegations: input.tasks!.map((item, index) => normalizeDelegation(item, `tasks[${index}]`)) }
169
173
  : { mode, delegations: input.chain!.map((item, index) => normalizeDelegation(item, `chain[${index}]`)) };
174
+ if (input.repositories) {
175
+ workflow.repositories = parseRepositorySelection(input.repositories);
176
+ if (workflow.delegations.some((task) => task.continueFrom || task.paths)) throw new Error("Selected direct repositories do not support continueFrom or paths; use the repository-labelled change report and explicit task scope.");
177
+ }
170
178
  const continued = workflow.delegations.flatMap(({ continueFrom }) => continueFrom === undefined ? [] : [continueFrom]);
171
179
  if (new Set(continued).size !== continued.length) throw new Error("A direct request may continue each worker at most once.");
172
180
  return workflow;
@@ -185,6 +193,7 @@ export function parseDelegateTask(value: unknown): ParsedDelegateTask {
185
193
  value = rest;
186
194
  }
187
195
  if (value && typeof value === "object" && !Array.isArray(value) && (value as { mode?: unknown }).mode === "isolated") {
196
+ if (Object.hasOwn(value, "repositories")) return { mode: "workspace", request: parseWorkspaceRequest(value), dryRun };
188
197
  return { mode: "isolated", request: parseExecuteRequest(value), dryRun };
189
198
  }
190
199
  return { mode: "direct", workflow: parseWorkflow(value), dryRun };
@@ -203,6 +212,7 @@ export type ChangeReport = {
203
212
  };
204
213
 
205
214
  export type CheckoutNote =
215
+ | { kind: "repositories"; notes: Record<string, CheckoutNote | undefined> }
206
216
  | { kind: "changes"; report: ChangeReport }
207
217
  | { kind: "stale" }
208
218
  | { kind: "unavailable"; check: "change report" | "stale-read check"; reason: string };
@@ -0,0 +1,83 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { createCanonicalGitRootResolver } from "../dist/composition.js";
3
+ import { CheckedGitRuntime } from "../dist/git-runtime.js";
4
+ import { HerdrHostRuntime } from "../dist/herdr-runtime.js";
5
+ import { RoleLaunchRuntime } from "../dist/launch-runtime.js";
6
+ import { WorkspaceRunner } from "../dist/workspace.js";
7
+ import { WorkspaceActionSchema, type WorkspaceRequest, type WorkspaceState } from "../dist/workspace-schema.js";
8
+ import type { ExecutionPolicySnapshot } from "../dist/schema.js";
9
+ import { workerOutputForMain } from "./result-transport.ts";
10
+ import { captureFallbackWarning } from "./task-model-fallback.ts";
11
+
12
+ /** Workspace requests keep their own versioned set state; scalar requests retain their existing contract. */
13
+ export function registerWorkspaceExtension(pi: ExtensionAPI, policy: () => ExecutionPolicySnapshot) {
14
+ let current: ExtensionContext | undefined, epoch = 0;
15
+ const jobs = new Map<AbortController, { session: string; epoch: number; accepted: boolean }>();
16
+ const git = new CheckedGitRuntime();
17
+ const host = (saved: ExecutionPolicySnapshot) => new HerdrHostRuntime({
18
+ inspectInFlightTaskCandidate: git.inspectInFlightTaskCandidate.bind(git),
19
+ executionBudget: () => ({ maxTurns: saved.maxTurns, maxMs: saved.childMaxMs, ...(saved.maxTokens === undefined ? {} : { maxTokens: saved.maxTokens }) }),
20
+ });
21
+ const coordinator = new RoleLaunchRuntime({ pi, context: () => {
22
+ policy();
23
+ if (!current) throw new Error("Workspace Role launch has no current Pi context.");
24
+ return current;
25
+ }, captureFallbackWarning: (signal) => {
26
+ if (!current) throw new Error("Workspace Role launch has no current Pi context.");
27
+ const ctx = current, capturedEpoch = epoch, sessionId = ctx.sessionManager.getSessionId();
28
+ return captureFallbackWarning(pi, ctx, () => epoch === capturedEpoch && current?.sessionManager.getSessionId() === sessionId, signal);
29
+ }, resolveRoot: createCanonicalGitRootResolver(), inspectMainBase: git.inspectMainBase.bind(git) });
30
+ const runner = new WorkspaceRunner({ coordinator, git, policy, host,
31
+ preflightHost: async (root, operation) => await host(policy()).preflightHost({ root, nonGitWorkspace: true }, operation) });
32
+ const stop = () => { epoch++; for (const controller of jobs.keys()) controller.abort(); };
33
+ pi.on("session_start", (_event, ctx) => { stop(); current = ctx; });
34
+ pi.on("session_shutdown", () => { stop(); current = undefined; });
35
+ pi.on("model_select", (event, ctx) => { current = { ...ctx, model: event.model }; });
36
+ const result = (state: WorkspaceState) => {
37
+ // Keep identities complete. Check output stays in the private state, not in a large inline dump.
38
+ const evidence = (value: WorkspaceState["final"]) => value && { ...value, results: value.results.map(({ stdout: _stdout, stderr: _stderr, ...item }) => item) };
39
+ const details = { ...state, preliminary: evidence(state.preliminary), final: evidence(state.final) };
40
+ return { content: [{ type: "text" as const, text: `Workspace ${state.request.id}: ${state.status}. ${state.failure ?? ""}\n${JSON.stringify(details)}` }], details };
41
+ };
42
+ pi.registerTool({ name: "subagent_workspace", label: "Subagent workspace", exposure: "model-only",
43
+ description: "Inspect or act on one explicit multi-repository request. stage takes the complete candidate set as expected; validate and promote take the complete integration tip set. Promotion is serial, not atomic. After any interrupted or partial promotion, reconcile first, then explicitly promote remaining targets. abort retains work; cleanup removes only fully promoted, clean, exactly owned resources. No rollback or automatic replay.",
44
+ parameters: WorkspaceActionSchema,
45
+ async execute(_id, params, signal, _update, ctx) { current = ctx; return result(await runner.action(params, ctx.cwd, signal)); },
46
+ });
47
+ return {
48
+ hasPendingResult: (session: string) => [...jobs].some(([controller, job]) => job.session === session && job.epoch === epoch && job.accepted && !controller.signal.aborted),
49
+ async plan(request: WorkspaceRequest, signal: AbortSignal | undefined, ctx: ExtensionContext) {
50
+ current = ctx;
51
+ const plan = await runner.plan(request, ctx.cwd, signal);
52
+ return { content: [{ type: "text" as const, text: `Workspace dry run passed. No resources created. Not checked: Herdr host, admission, worker, or checks.\n${JSON.stringify(plan)}` }], details: { dryRun: true, ...plan } };
53
+ },
54
+ async execute(request: WorkspaceRequest, signal: AbortSignal | undefined, ctx: ExtensionContext) {
55
+ current = ctx;
56
+ const controller = new AbortController(), job = { session: ctx.sessionManager.getSessionId(), epoch, accepted: false };
57
+ jobs.set(controller, job);
58
+ const abort = () => controller.abort(signal?.reason);
59
+ if (signal?.aborted) abort(); else signal?.addEventListener("abort", abort, { once: true });
60
+ let accept!: (state: WorkspaceState) => void, reject!: (error: unknown) => void;
61
+ const accepted = new Promise<WorkspaceState>((resolve, fail) => { accept = resolve; reject = fail; });
62
+ const deliverable = () => epoch === job.epoch && current?.sessionManager.getSessionId() === job.session && ctx.sessionManager.getSessionId() === job.session;
63
+ void runner.execute(request, ctx.cwd, controller.signal, (state) => {
64
+ job.accepted = true; signal?.removeEventListener("abort", abort); accept(state);
65
+ }).then((state) => {
66
+ jobs.delete(controller);
67
+ if (!deliverable()) return;
68
+ try { pi.sendMessage({ customType: "pi-subagent-workspace-result", content: workerOutputForMain(result(state).content[0]!.text), display: true }, { triggerTurn: true, deliverAs: "followUp" }); }
69
+ catch { console.error("Workspace result delivery failed; inspect subagent_workspace status. Saved resources are retained."); }
70
+ }, (error: unknown) => {
71
+ jobs.delete(controller); signal?.removeEventListener("abort", abort);
72
+ if (!job.accepted) { reject(error); return; }
73
+ if (deliverable()) {
74
+ try { pi.sendMessage({ customType: "pi-subagent-workspace-result", content: `Workspace ${request.id} stopped. Inspect subagent_workspace status before recovery.`, display: true }, { triggerTurn: true, deliverAs: "followUp" }); }
75
+ catch { console.error("Workspace failure delivery failed; saved resources are retained."); }
76
+ }
77
+ });
78
+ const state = await accepted;
79
+ if (!deliverable()) throw new Error("Workspace request was saved, but its launching session changed. Inspect subagent_workspace status.");
80
+ return { content: [{ type: "text" as const, text: `Workspace ${state.request.id} saved; one worker will receive the complete selected worktree map. Use subagent_workspace status. No repository is promoted automatically.` }], details: { id: state.request.id, root: state.root } };
81
+ },
82
+ };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.15.1",
3
+ "version": "27.16.0",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -71,7 +71,7 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@henryqw/pi-config-store": "^4.0.0",
74
- "@henryqw/pi-herdr": "^0.6.0",
74
+ "@henryqw/pi-herdr": "^0.6.1",
75
75
  "@henryqw/pi-multi-codex": "^3.0.0",
76
76
  "@henryqw/pi-process": "^0.2.0",
77
77
  "@henryqw/pi-task-models": "^9.2.0",