@henryqw/pi-subagent 27.15.1 → 27.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTEXT.md CHANGED
@@ -36,6 +36,15 @@ An isolated-graph task whose result is bounded text rather than a changeset. Com
36
36
  **Changeset task**:
37
37
  An isolated-graph task that produces a committed change in its own worker worktree.
38
38
 
39
+ **Repository set**:
40
+ The explicitly selected independent Git repositories that one workspace task reads, checks, and changes. An unchanged member remains part of the exact input set.
41
+
42
+ **Workspace input**:
43
+ An explicitly selected non-Git file copied for read-only task use. It is never a Git candidate or a promotion target.
44
+
45
+ **Promotion receipt**:
46
+ The durable record of one repository's proved movement to its checked integration tip. A receipt does not imply that other repositories moved.
47
+
39
48
  ### Checked integration
40
49
 
41
50
  **Candidate**:
package/README.md CHANGED
@@ -105,6 +105,14 @@ Text after the target adds a review focus, for example `/review #42 cache invali
105
105
 
106
106
  The verdict is **Ship** only if each reviewer task succeeded and answered exactly `PASS`. Otherwise, the verdict is **Do not ship**, with the findings in priority order. If the checkout changed during a review task, the verdict is also **Do not ship**, and you must run the review again. Main does not fix findings. If another `/review` prompt template loads first, Pi keeps that template and reports a name collision.
107
107
 
108
+ ### Several repositories in one workspace
109
+
110
+ Add an explicit `repositories` map to `delegate_task` to select independent Git repositories in a non-Git workspace. One isolated worker can change the complete set. Use `subagent_workspace` for status, checks, serial promotion, and recovery.
111
+
112
+ Workspace mode supports one changeset task with repository-specific checks and optional read-only root inputs. It rejects dependencies and judgment. Saved worker idle and maximum limits apply. Each committed root test script stays pinned, regardless of the check command; repositories without that script can use native checks. Promotion is not atomic and never rolls back. See [Checked workspace tasks](./docs/workspace.md) for the request, limits, and partial-promotion procedure.
113
+
114
+ Direct requests can select the same repository set for admission and labelled change reports. This does not provide a sandbox.
115
+
108
116
  ### Isolated workflow
109
117
 
110
118
  ![Isolated workers commit checked candidates; Main stages ready work while siblings run, advances dependents, validates the combined tip, and explicitly promotes](./docs/orchestration-architecture.svg)
@@ -24,6 +24,9 @@ export interface HerdrHostRuntimeOptions {
24
24
  lsofCommand?: string;
25
25
  executionBudget?: () => Omit<EphemeralSubagentExecutionBudget, "startedAt">;
26
26
  }
27
+ type WorkerObservationContext = OperationContext & {
28
+ observe?: () => Promise<void>;
29
+ };
27
30
  export declare function workspaceLabel(attempt: TaskAttempt): string;
28
31
  export declare class HerdrHostRuntime implements HostRuntime {
29
32
  private readonly inspectInFlightCandidate;
@@ -41,6 +44,7 @@ export declare class HerdrHostRuntime implements HostRuntime {
41
44
  /** Fail-closed Herdr caller/capability gate. This method creates no state or host resource. */
42
45
  preflightHost(input: {
43
46
  root: string;
47
+ nonGitWorkspace?: boolean;
44
48
  }, context: OperationContext): Promise<void>;
45
49
  planHostAllocation(input: {
46
50
  readonly requestId: ExecuteRequest["id"];
@@ -70,9 +74,11 @@ export declare class HerdrHostRuntime implements HostRuntime {
70
74
  workerId: string;
71
75
  kind: "initial" | "correction" | "followup";
72
76
  preCandidate: WorkspaceIdentity;
77
+ workspacePaths?: Readonly<Record<string, string>>;
78
+ idleMs?: number;
73
79
  failure?: string;
74
80
  instruction?: string;
75
- }, context: OperationContext): Promise<WorkerResult>;
81
+ }, context: WorkerObservationContext): Promise<WorkerResult>;
76
82
  terminateWorker(input: {
77
83
  task: TaskRequest;
78
84
  attempt: TaskAttempt;
@@ -113,6 +119,8 @@ export declare class HerdrHostRuntime implements HostRuntime {
113
119
  private allocateWorkspace;
114
120
  private allocateWorkerTab;
115
121
  private allocateAgent;
122
+ /** Reuse exact lifecycle polling; only complete Pi messages renew the idle deadline. */
123
+ private observeWorker;
116
124
  private reconcileDeliveredPrompt;
117
125
  private candidateResult;
118
126
  private isExpectedCandidate;
@@ -148,3 +156,4 @@ export declare class HerdrHostRuntime implements HostRuntime {
148
156
  private callTimeout;
149
157
  private contextInterrupted;
150
158
  }
159
+ export {};
@@ -306,6 +306,16 @@ export class HerdrHostRuntime {
306
306
  const workspaceId = exactString(pane.workspace_id, "Herdr current workspace_id");
307
307
  const workspaceResponse = await this.herdr.json(["workspace", "get", workspaceId], this.processOptions(root, context, HERDR_OPERATION_CAP_MS));
308
308
  const workspace = parseWorkspaceInfo(workspaceResponse, workspaceId);
309
+ if (input.nonGitWorkspace) {
310
+ if (workspace.worktree !== undefined && workspace.worktree !== null)
311
+ throw new Error("Selected repositories require a non-Git Herdr workspace.");
312
+ if (await realpath(exactString(pane.cwd, "Herdr current pane cwd")) !== root)
313
+ throw new Error("Herdr pane does not identify the selected non-Git workspace.");
314
+ const probe = await this.execute("git", ["rev-parse", "--show-toplevel"], this.processOptions(root, context, GIT_INSPECTION_CAP_MS));
315
+ if (probe.code === 0 || probe.killed || !/not a git repository/i.test(probe.stderr))
316
+ throw new Error("Herdr non-Git workspace scope is uncertain.");
317
+ return;
318
+ }
309
319
  const worktree = record(workspace.worktree, "Herdr current workspace worktree");
310
320
  const checkout = await realpath(exactString(worktree.checkout_path, "Herdr current checkout_path"));
311
321
  if (checkout !== root)
@@ -491,6 +501,7 @@ export class HerdrHostRuntime {
491
501
  task: input.task,
492
502
  kind: input.kind,
493
503
  worktreeCwd: allocation.worktreeCwd,
504
+ ...(input.workspacePaths ? { workspacePaths: input.workspacePaths } : {}),
494
505
  ...(input.failure ? { failure: input.failure } : {}),
495
506
  ...(input.instruction ? { instruction: input.instruction } : {}),
496
507
  })}\n\nTurn identity: ${input.attempt.correlationToken}:${input.attempt.prompts.length}`;
@@ -500,6 +511,8 @@ export class HerdrHostRuntime {
500
511
  catch (error) {
501
512
  return { outcome: "not_prompted", diagnostic: `Worker assignment was not submitted: ${safeText(error)}` };
502
513
  }
514
+ if (input.idleMs !== undefined)
515
+ context = await this.observeWorker(allocation, input.idleMs, context);
503
516
  let ready;
504
517
  try {
505
518
  ready = await this.waitForSettledAgent(allocation, context);
@@ -890,8 +903,40 @@ export class HerdrHostRuntime {
890
903
  return { kind: "agent", outcome: "owned" };
891
904
  });
892
905
  }
906
+ /** Reuse exact lifecycle polling; only complete Pi messages renew the idle deadline. */
907
+ async observeWorker(allocation, idleMs, outer) {
908
+ const path = this.workerSessionFile(allocation.leasePath, allocation.token);
909
+ await this.assertPrivateLeaseDirectories(allocation.leasePath, false);
910
+ let offset = (await this.privateSessionFile(path))?.length ?? 0;
911
+ let idleDeadline = this.now() + idleMs;
912
+ return {
913
+ ...outer,
914
+ get deadline() { return Math.min(outer.deadline ?? Infinity, idleDeadline); },
915
+ observe: async () => {
916
+ outer.signal.throwIfAborted();
917
+ if (outer.deadline !== undefined && this.now() >= outer.deadline)
918
+ throw new Error("Worker maximum runtime is exhausted.");
919
+ const session = await this.privateSessionFile(path) ?? "";
920
+ if (session.length < offset)
921
+ throw new Error("Worker session shrank during observation.");
922
+ let end;
923
+ while ((end = session.indexOf("\n", offset)) >= 0) {
924
+ const line = session.slice(offset, end);
925
+ offset = end + 1;
926
+ if (!line.trim())
927
+ continue;
928
+ const entry = JSON.parse(line);
929
+ if (entry?.type === "message" && ["user", "assistant", "toolResult"].includes(entry.message?.role))
930
+ idleDeadline = this.now() + idleMs;
931
+ }
932
+ if (this.now() >= idleDeadline)
933
+ throw new Error(`Worker made no progress for ${idleMs}ms; its exact session is retained.`);
934
+ },
935
+ };
936
+ }
893
937
  async reconcileDeliveredPrompt(input, allocation, context, prompt, promptMayBeInFlight = true) {
894
938
  for (;;) {
939
+ await context.observe?.();
895
940
  let lifecycle;
896
941
  try {
897
942
  lifecycle = await this.waitForAgentLifecycle(allocation, context, true);
@@ -933,7 +978,8 @@ export class HerdrHostRuntime {
933
978
  if (SETTLED_AGENT_STATES.has(lifecycle.status)
934
979
  && inspection.valid
935
980
  && inspection.clean
936
- && this.isExpectedCandidate(input, inspection.candidate)) {
981
+ && this.isExpectedCandidate(input, inspection.candidate)
982
+ && (!input.workspacePaths || await this.workerTurnFinished(allocation, prompt))) {
937
983
  return {
938
984
  outcome: "candidate",
939
985
  candidate: inspection.candidate,
@@ -970,6 +1016,7 @@ export class HerdrHostRuntime {
970
1016
  }
971
1017
  }
972
1018
  async candidateResult(input, allocation, context, prompt) {
1019
+ await context.observe?.();
973
1020
  let inspection;
974
1021
  try {
975
1022
  inspection = await this.inspectInFlightCandidate({ root: allocation.worktreeCwd, task: input.task, attempt: input.attempt }, this.childContext(context, GIT_INSPECTION_CAP_MS));
@@ -977,7 +1024,8 @@ export class HerdrHostRuntime {
977
1024
  catch (error) {
978
1025
  return { outcome: "unknown", diagnostic: `Settled worker candidate inspection failed: ${safeText(error)}` };
979
1026
  }
980
- if (!inspection.valid || !inspection.clean || !this.isExpectedCandidate(input, inspection.candidate)) {
1027
+ if (!inspection.valid || !inspection.clean || !this.isExpectedCandidate(input, inspection.candidate)
1028
+ || input.workspacePaths && !await this.workerTurnFinished(allocation, prompt)) {
981
1029
  return await this.reconcileDeliveredPrompt(input, allocation, context, prompt, false);
982
1030
  }
983
1031
  return {
@@ -988,7 +1036,7 @@ export class HerdrHostRuntime {
988
1036
  }
989
1037
  isExpectedCandidate(input, candidate) {
990
1038
  const expectedBranch = `refs/heads/${worktreeIntent(input.attempt).branch}`;
991
- return isCleanCommitted(candidate) && candidate.branch === expectedBranch && candidate.head !== input.preCandidate.head;
1039
+ return isCleanCommitted(candidate) && candidate.branch === expectedBranch && (input.workspacePaths !== undefined || candidate.head !== input.preCandidate.head);
992
1040
  }
993
1041
  async waitForSettledAgent(allocation, context) {
994
1042
  return await this.waitForAgentLifecycle(allocation, context, false);
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export declare function roleToolPolicyFromArgv(args: readonly string[]): string[
19
19
  * `codemode` or `deferred` exposure. Loading `builtin:codemode` alone registers the tool inactive.
20
20
  */
21
21
  export declare function roleActivatesCodemode(tools: readonly string[]): boolean;
22
- export declare const CHILD_EXCLUDED_TOOL_NAMES: readonly ["delegate_task", "ask_question", "subagent_status", "subagent_resume", "subagent_stage", "subagent_abort"];
22
+ export declare const CHILD_EXCLUDED_TOOL_NAMES: readonly ["delegate_task", "ask_question", "subagent_status", "subagent_resume", "subagent_stage", "subagent_abort", "subagent_workspace"];
23
23
  export declare const DELEGATE_TASK: {
24
24
  readonly id: "pi-subagent/delegateTask";
25
25
  readonly label: "Subagent delegation";
package/dist/index.js CHANGED
@@ -66,6 +66,7 @@ export const CHILD_EXCLUDED_TOOL_NAMES = [
66
66
  "subagent_resume",
67
67
  "subagent_stage",
68
68
  "subagent_abort",
69
+ "subagent_workspace",
69
70
  ];
70
71
  const SYSTEM_PROMPT_FLAG = "--append-system-prompt";
71
72
  const CHILD_IDENTITY_POLICY = "You are a delegated Pi Subagent, not Main. Execute the assigned Role and task directly. Main-only delegation rules do not apply. Recursive delegation is unavailable; do not seek or invoke delegation tools.";
package/dist/process.d.ts CHANGED
@@ -3,6 +3,7 @@ type ProcessOptions = {
3
3
  signal?: AbortSignal;
4
4
  timeoutMs?: number;
5
5
  stdin?: string;
6
+ env?: Readonly<Record<string, string>>;
6
7
  };
7
8
  /** Infrastructure errors reject; only ordinary command exits return a result. */
8
9
  export declare const runProcess: (command: string, args: string[], options: ProcessOptions) => Promise<import("@henryqw/pi-process").ExecResult>;
package/dist/process.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawnBounded } from "@henryqw/pi-process";
2
2
  const OUTPUT_LIMIT_BYTES = 1024 * 1024;
3
3
  /** Infrastructure errors reject; only ordinary command exits return a result. */
4
- export const runProcess = async (command, args, options) => await spawnBounded(command, args, {
4
+ export const runProcess = async (command, args, options) => await spawnBounded(options.env ? "/usr/bin/env" : command, options.env ? [...Object.entries(options.env).map(([key, value]) => `${key}=${value}`), command, ...args] : args, {
5
5
  cwd: options.cwd,
6
6
  signal: options.signal,
7
7
  timeoutMs: options.timeoutMs ?? null,
package/dist/runner.d.ts CHANGED
@@ -164,6 +164,10 @@ export interface HostRuntime {
164
164
  workerId: string;
165
165
  kind: "initial" | "correction" | "followup";
166
166
  preCandidate: WorkspaceIdentity;
167
+ /** Explicit complete repository worktree map; the caller validates every member. */
168
+ workspacePaths?: Readonly<Record<string, string>>;
169
+ /** Optional idle bound for exact worker session observation. */
170
+ idleMs?: number;
167
171
  failure?: string;
168
172
  instruction?: string;
169
173
  }, context: OperationContext): Promise<WorkerResult>;
@@ -284,6 +288,22 @@ export interface RunResponse {
284
288
  main?: MainStatus;
285
289
  continuation?: ResumeRequest;
286
290
  }
291
+ interface RuntimeScope {
292
+ readonly signal: AbortSignal;
293
+ call<T>(operation: (context: OperationContext) => Promise<T>): Promise<T>;
294
+ }
295
+ export declare class DeadlineScope implements RuntimeScope {
296
+ readonly deadline: number;
297
+ readonly signal: AbortSignal;
298
+ private readonly now;
299
+ private readonly controller;
300
+ private readonly timer;
301
+ constructor(deadline: number, now: () => number, outerSignal?: AbortSignal);
302
+ call<T>(operation: (context: OperationContext) => Promise<T>): Promise<T>;
303
+ close(): void;
304
+ private remaining;
305
+ private throwIfExpired;
306
+ }
287
307
  export type TextTaskContext = {
288
308
  taskId: string;
289
309
  text: string;
@@ -295,6 +315,7 @@ export declare function buildChangesetTaskPrompt(input: {
295
315
  task: ChangesetTaskRequest;
296
316
  kind: "initial" | "correction" | "followup";
297
317
  worktreeCwd: string;
318
+ workspacePaths?: Readonly<Record<string, string>>;
298
319
  failure?: string;
299
320
  instruction?: string;
300
321
  }): string;
package/dist/runner.js CHANGED
@@ -86,7 +86,7 @@ class ProductiveScope {
86
86
  return result;
87
87
  }
88
88
  }
89
- class DeadlineScope {
89
+ export class DeadlineScope {
90
90
  deadline;
91
91
  signal;
92
92
  now;
@@ -450,6 +450,9 @@ export function buildChangesetTaskPrompt(input) {
450
450
  || input.instruction.includes("\0") || input.instruction.length > 32_000)) {
451
451
  throw new Error(`${input.kind === "followup" ? "follow-up" : "correction"} instruction must be non-empty exact text of at most 32000 characters.`);
452
452
  }
453
+ const scope = input.workspacePaths
454
+ ? `Work only in these selected worktrees: ${JSON.stringify(input.workspacePaths)}. Commit the complete result and leave every selected worktree clean. Read each selected repository's agent instructions and domain context before changes. Do not modify workspace-root input files or other repositories.`
455
+ : "Work only in the exact worktree above. Commit the complete result and leave that worktree clean.";
453
456
  const checks = input.task.checks.map((check) => JSON.stringify({ command: check.command, args: check.args })).join("\n");
454
457
  const upstreamTaskData = input.contexts.length
455
458
  ? ["", "Upstream task data:", formatTextTaskContexts(input.contexts, CHANGESET_TASK_PROMPT_MAX_BYTES)]
@@ -484,7 +487,7 @@ export function buildChangesetTaskPrompt(input) {
484
487
  ...(input.kind === "correction" ? ["", "Correction failure:", input.failure] : []),
485
488
  ...(input.kind === "correction" && input.instruction ? ["", "Main's instruction:", input.instruction] : []),
486
489
  "",
487
- "Work only in the exact worktree above. Commit the complete result and leave that worktree clean.",
490
+ scope,
488
491
  ].join("\n");
489
492
  if (Buffer.byteLength(text, "utf8") > CHANGESET_TASK_PROMPT_MAX_BYTES) {
490
493
  throw new Error(`Worker assignment exceeds ${CHANGESET_TASK_PROMPT_MAX_BYTES} bytes.`);
@@ -732,7 +735,8 @@ export class IsolatedRunner {
732
735
  * A non-terminal state owns every resource name its saved text mentions; an unreadable state owns every
733
736
  * name its raw text mentions, or every name when unreadable. */
734
737
  async pruneOwnership(checkouts) {
735
- const owners = [];
738
+ const { workspacePruneOwners } = await import("./workspace.js");
739
+ const owners = await workspacePruneOwners(checkouts, this.store.agentDir);
736
740
  let lease;
737
741
  const request = ({ state, path }, orphaned) => ({ id: state.request.id, name: state.request.goal,
738
742
  status: inventoryStatus(state, orphaned), directory: dirname(path), root: state.root, orphaned });
package/dist/schema.d.ts CHANGED
@@ -154,7 +154,7 @@ export type ExecuteRequest = Omit<ExecuteRequestInput, "finalChecks"> & {
154
154
  export type ExecutionPolicySnapshot = Static<typeof ExecutionPolicySnapshotSchema>;
155
155
  export type ResumeRequest = Static<typeof ResumeRequestSchema>;
156
156
  export type WorkspaceIdentity = Static<typeof WorkspaceSchema>;
157
- declare const WorktreeRecordSchema: Type.TObject<{
157
+ export declare const WorktreeRecordSchema: Type.TObject<{
158
158
  path: Type.TString;
159
159
  cwd: Type.TString;
160
160
  branch: Type.TString;
@@ -309,7 +309,7 @@ export type TextTaskState = Static<typeof TextTaskStateSchema>;
309
309
  export type TaskState = Static<typeof TaskStateSchema>;
310
310
  export type WaveState = Static<typeof WaveStateSchema>;
311
311
  export type RunState = Static<typeof RunStateSchema>;
312
- declare const WorkspaceSchema: Type.TObject<{
312
+ export declare const WorkspaceSchema: Type.TObject<{
313
313
  branch: Type.TString;
314
314
  head: Type.TString;
315
315
  index: Type.TString;
@@ -511,7 +511,7 @@ declare const CleanupStepSchema: Type.TObject<{
511
511
  status: Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"running">, Type.TLiteral<"completed">]>;
512
512
  failure: Type.TOptional<Type.TString>;
513
513
  }>;
514
- declare const TaskAttemptSchema: Type.TObject<{
514
+ export declare const TaskAttemptSchema: Type.TObject<{
515
515
  number: Type.TInteger;
516
516
  waveNumber: Type.TInteger;
517
517
  waveBase: Type.TObject<{
@@ -1205,7 +1205,7 @@ declare const WaveStateSchema: Type.TObject<{
1205
1205
  taskIds: Type.TArray<Type.TString>;
1206
1206
  status: Type.TUnion<[Type.TLiteral<"dispatching">, Type.TLiteral<"integrating">, Type.TLiteral<"completed">, Type.TLiteral<"needs_attention">]>;
1207
1207
  }>;
1208
- declare const ExecutionPolicySnapshotSchema: Type.TObject<{
1208
+ export declare const ExecutionPolicySnapshotSchema: Type.TObject<{
1209
1209
  maxSubagents: Type.TInteger;
1210
1210
  maxTurns: Type.TInteger;
1211
1211
  maxTokens: Type.TOptional<Type.TInteger>;
package/dist/schema.js CHANGED
@@ -90,7 +90,7 @@ const AllocationLifecycleFields = {
90
90
  possibleResources: Type.Optional(Type.Array(RuntimeTextSchema, { maxItems: MAX_POSSIBLE_RESOURCES })),
91
91
  failure: OptionalRuntimeTextSchema,
92
92
  };
93
- const WorktreeRecordSchema = Type.Object({
93
+ export const WorktreeRecordSchema = Type.Object({
94
94
  path: RuntimeTextSchema,
95
95
  cwd: RuntimeTextSchema,
96
96
  branch: RuntimeTextSchema,
@@ -143,7 +143,7 @@ export const AllocationIntentSchema = Type.Union([
143
143
  AgentAllocationIntentSchema,
144
144
  ]);
145
145
  export const CLEANUP_KINDS = ["worker_tab", "workspace", "worktree", "branch"];
146
- const WorkspaceSchema = Type.Object({
146
+ export const WorkspaceSchema = Type.Object({
147
147
  branch: RuntimeTextSchema,
148
148
  head: Type.String({ pattern: OID_PATTERN }),
149
149
  index: Type.String({ pattern: OID_PATTERN }),
@@ -267,7 +267,7 @@ const CleanupStepSchema = Type.Object({
267
267
  status: Type.Union([Type.Literal("pending"), Type.Literal("running"), Type.Literal("completed")]),
268
268
  failure: OptionalRuntimeTextSchema,
269
269
  }, { additionalProperties: false });
270
- const TaskAttemptSchema = Type.Object({
270
+ export const TaskAttemptSchema = Type.Object({
271
271
  number: Type.Integer({ minimum: 1, maximum: 2 }),
272
272
  waveNumber: Type.Integer({ minimum: 1 }),
273
273
  waveBase: WorkspaceSchema,
@@ -340,7 +340,7 @@ const FinalGateSchema = Type.Object({
340
340
  review: Type.Optional(ReviewEvidenceSchema),
341
341
  failure: OptionalRuntimeTextSchema,
342
342
  }, { additionalProperties: false });
343
- const ExecutionPolicySnapshotSchema = Type.Object({
343
+ export const ExecutionPolicySnapshotSchema = Type.Object({
344
344
  maxSubagents: Type.Integer({ minimum: 1 }),
345
345
  maxTurns: Type.Integer({ minimum: 1 }),
346
346
  maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),
package/dist/store.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare class RunStateHandle {
27
27
  save(): Promise<void>;
28
28
  }
29
29
  export declare class FileRunStore {
30
- private readonly agentDir?;
30
+ readonly agentDir?: string;
31
31
  private readonly onStateSaved?;
32
32
  private readonly productiveRunLeases;
33
33
  constructor(agentDir?: string, onStateSaved?: (state: RunState) => void);