pi-better-subagents 0.35.0 → 0.37.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.
Files changed (97) hide show
  1. package/README.md +13 -11
  2. package/assignment-outcomes.ts +9 -6
  3. package/assignment-report.ts +103 -19
  4. package/batch.mjs +14 -5
  5. package/bin/recover-workspace.mjs +19 -0
  6. package/catalog-host-admission.ts +19 -3
  7. package/catalog-preferences.ts +1 -1
  8. package/catalog-resolver.ts +35 -1
  9. package/catalog-store.ts +27 -20
  10. package/child-apply-patch.ts +13 -0
  11. package/child-dependencies.mjs +25 -12
  12. package/child-operations.ts +80 -1
  13. package/child-preflight.mjs +8 -2
  14. package/child-process-list.ts +8 -0
  15. package/cleanup.ts +10 -2
  16. package/config.ts +53 -3
  17. package/continuation-authority.ts +3 -1
  18. package/continuation-runtime.ts +88 -0
  19. package/continuation.ts +4 -2
  20. package/docs/usage.md +92 -81
  21. package/extensions.mjs +11 -13
  22. package/failures.ts +10 -2
  23. package/finalization.ts +21 -1
  24. package/goal-provider.ts +44 -2
  25. package/health-observation.ts +43 -48
  26. package/index.ts +417 -155
  27. package/isolated-workspace.ts +557 -0
  28. package/launch-context.ts +23 -0
  29. package/launch-digest.mjs +6 -0
  30. package/list.mjs +2 -2
  31. package/log-cursor.ts +91 -15
  32. package/managed-launch-bootstrap.mjs +2 -2
  33. package/managed-launch-client.ts +28 -8
  34. package/managed-launch-host.ts +168 -15
  35. package/managed-launch-journal.mjs +1 -5
  36. package/managed-launch-port.ts +4 -0
  37. package/operation-bridge-types.ts +27 -2
  38. package/output-payload.ts +26 -12
  39. package/owned-exit.ts +12 -0
  40. package/package.json +4 -2
  41. package/parse.ts +57 -10
  42. package/permission-policy.ts +41 -8
  43. package/process-identity.d.mts +1 -0
  44. package/process-identity.mjs +29 -0
  45. package/registry.ts +77 -38
  46. package/retained-result.ts +65 -0
  47. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  48. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  49. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  50. package/runtime-client/artifacts/darwin-x64.json +1 -1
  51. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  52. package/runtime-client/artifacts/linux-arm64.json +1 -1
  53. package/runtime-client/artifacts/linux-x64.gz +0 -0
  54. package/runtime-client/artifacts/linux-x64.json +1 -1
  55. package/runtime-client/src/runtime/client.mjs +30 -3
  56. package/runtime-client/src/runtime/root.mjs +5 -2
  57. package/runtime-client/src/runtime/work-client.mjs +150 -7
  58. package/session-selection.ts +2 -1
  59. package/session-store.ts +9 -0
  60. package/settings-page.ts +147 -108
  61. package/shared-callback-batcher.ts +11 -2
  62. package/shared-catalog.ts +29 -21
  63. package/shared-navigator-panels.ts +26 -4
  64. package/shared-navigator.ts +244 -40
  65. package/shared-operation-coordinator/assignment-inbox.mjs +118 -0
  66. package/shared-operation-coordinator/assignment-observation.mjs +43 -35
  67. package/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  68. package/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  69. package/shared-operation-coordinator/src/background-requests.ts +14 -3
  70. package/shared-operation-coordinator/src/discovery.ts +5 -3
  71. package/shared-operation-coordinator/src/operations.ts +50 -2
  72. package/shared-operation-coordinator/src/outbox.ts +9 -0
  73. package/shared-operation-coordinator/src/result-supervision.ts +12 -0
  74. package/shared-operation-coordinator/src/rows.ts +2 -0
  75. package/shared-operation-coordinator/src/schema.ts +40 -24
  76. package/shared-operation-coordinator/src/store.ts +40 -8
  77. package/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  78. package/shared-operation-coordinator/src/types.ts +5 -1
  79. package/shared-sandbox-core.ts +1 -1
  80. package/shared-task-exec.ts +12 -1
  81. package/shared-task-process-identity.ts +126 -0
  82. package/shared-task-process-list.ts +8 -2
  83. package/shared-task-sandbox.ts +5 -3
  84. package/shared-task-tools.ts +8 -5
  85. package/shared-work-client.d.mts +10 -0
  86. package/shared-work-client.mjs +150 -7
  87. package/subagent-tools.ts +28 -34
  88. package/task-guard.ts +13 -1
  89. package/task-policy.ts +8 -2
  90. package/timing.ts +10 -1
  91. package/tools.ts +4 -7
  92. package/work-observation.ts +91 -17
  93. package/worker-operations-host.ts +12 -4
  94. package/worker-waits.ts +93 -34
  95. package/workspace-files.ts +114 -0
  96. package/workspace-scope.ts +6 -0
  97. package/worktree-feedback.ts +77 -0
package/catalog-store.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Filesystem catalog: project, personal, and bundled sources.
3
3
  *
4
- * Discovery is deterministic and reads the disk on every call. There is no
5
- * launch cache. Callers that launch a batch must retain the returned snapshot
4
+ * Discovery is deterministic. Direct callers read disk on every call; the server
5
+ * can supply bounded source reuse after admission. Callers launching a batch retain the snapshot
6
6
  * and reuse that object for every job.
7
7
  *
8
8
  * Project files are read only when `projectTrusted` is true. Pass Pi's
@@ -51,6 +51,13 @@ export const DEFAULT_PROJECT_CONFIG_DIR_NAME = ".pi";
51
51
  export const SOURCE_PRECEDENCE = ["project", "user", "bundled"] as const;
52
52
 
53
53
  export interface LoadCatalogInput {
54
+ /** Server-owned, bounded source reuse. Admission and discovery still run first. */
55
+ sources?: {
56
+ read(path: string): string;
57
+ parse(raw: string, path: string): ParseResult;
58
+ entry?(entry: CatalogEntry): CatalogEntry;
59
+ preferences?(root: string): ReturnType<typeof readCatalogPreferences>;
60
+ };
54
61
  cwd: string;
55
62
  /** Host trust decision. Untrusted projects do not contribute definitions. */
56
63
  projectTrusted: boolean;
@@ -195,13 +202,13 @@ export function listScopedAgents(input: LoadCatalogInput, scope: "user" | "proje
195
202
  if (!isSafeConfigDirName(config)) throw new Error("Unsafe project config directory");
196
203
  const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
197
204
  const occurrences = new Map<string, Occurrence[]>();
198
- collectDirectory(directory, scope, "agent", occurrences, diagnostics);
205
+ collectDirectory(directory, scope, "agent", occurrences, diagnostics, input.sources);
199
206
  const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
200
207
  ? [{ path: item.path, definition: item.parse.definition }] : []);
201
208
  return { agents, diagnostics };
202
209
  }
203
210
 
204
- /** Read every source again. Identical bytes produce the same digest and a new object. */
211
+ /** Discover authorized sources. Identical bytes produce the same content digest. */
205
212
  export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
206
213
  const loadedAt = new Date().toISOString();
207
214
  const diagnostics: Diagnostic[] = [];
@@ -219,8 +226,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
219
226
 
220
227
  if (input.projectTrusted) {
221
228
  const project = projectCatalogPaths(input.cwd, configDirName);
222
- collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics);
223
- collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics);
229
+ collectDirectory(project.roles, "project", "role", groups.get("project")!, diagnostics, input.sources);
230
+ collectDirectory(project.agents, "project", "agent", groups.get("project")!, diagnostics, input.sources);
224
231
  } else {
225
232
  const project = projectCatalogPaths(input.cwd, configDirName);
226
233
  if (pathExists(project.roles) || pathExists(project.agents) || pathExists(project.root)) {
@@ -233,8 +240,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
233
240
  }
234
241
 
235
242
  const user = userCatalogPaths(input.userRoot);
236
- collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics);
237
- collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics);
243
+ collectDirectory(user.roles, "user", "role", groups.get("user")!, diagnostics, input.sources);
244
+ collectDirectory(user.agents, "user", "agent", groups.get("user")!, diagnostics, input.sources);
238
245
 
239
246
  const bundledRoles = input.bundledRoot ?? bundledRolesRoot();
240
247
  if (!existsSync(bundledRoles)) {
@@ -246,24 +253,22 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
246
253
  severity: "warning",
247
254
  }));
248
255
  } else {
249
- collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics);
256
+ collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled")!, diagnostics, input.sources);
250
257
  }
251
258
  if (input.bundledAgentsRoot) {
252
- collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics);
259
+ collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled")!, diagnostics, input.sources);
253
260
  }
254
261
 
255
262
  const { entries, blocked } = selectIdentities(groups, diagnostics);
256
263
  const savedSettings: Record<string, { model?: string | null; effort?: ThinkingLevel | null }> = {};
257
264
  const preferenceSources: Record<string, Partial<Record<"model" | "effort", { scope: "user" | "project"; path: string; bundled?: boolean }>>> = {};
258
- const preferenceDigests: string[] = [];
259
265
  const scopes = [
260
266
  { scope: "user" as const, root: user.root },
261
267
  ...(input.projectTrusted ? [{ scope: "project" as const, root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
262
268
  ];
263
269
  for (const { scope, root } of scopes) {
264
270
  try {
265
- const preferences = readCatalogPreferences(root);
266
- preferenceDigests.push(preferences.digest);
271
+ const preferences = input.sources?.preferences?.(root) ?? readCatalogPreferences(root);
267
272
  for (const entry of entries) {
268
273
  if (scope === "user" && entry.scope === "project") continue;
269
274
  const own = preferences.settings[entry.id];
@@ -272,8 +277,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
272
277
  if (own.bundled) {
273
278
  const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
274
279
  const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
275
- const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
276
- const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback!.path);
280
+ const raw = fallback ? (input.sources?.read(fallback.path) ?? readFileSync(fallback.path, "utf8")) : undefined;
281
+ const parsed = raw === undefined ? undefined : (input.sources?.parse(raw, fallback!.path) ?? parseDefinition(raw, fallback!.path));
277
282
  if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
278
283
  || contentDigest(raw!) !== fallback.contentDigest) {
279
284
  const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
@@ -309,8 +314,8 @@ export function loadCatalog(input: LoadCatalogInput): CatalogSnapshot {
309
314
  }
310
315
  }
311
316
  }
312
- const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
313
- const digest = contentDigest(JSON.stringify([snapshot.digest, preferenceDigests, savedSettings, preferenceSources]));
317
+ const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt, input.sources);
318
+ const digest = contentDigest(JSON.stringify([snapshot.digest, savedSettings, preferenceSources]));
314
319
  return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
315
320
  }
316
321
 
@@ -526,6 +531,7 @@ function collectDirectory(
526
531
  directoryKind: CatalogKind,
527
532
  into: Map<string, Occurrence[]>,
528
533
  diagnostics: Diagnostic[],
534
+ sources?: LoadCatalogInput["sources"],
529
535
  ): void {
530
536
  let stats;
531
537
  try {
@@ -602,7 +608,7 @@ function collectDirectory(
602
608
  if (!fileStats.isFile()) continue;
603
609
  let raw: string;
604
610
  try {
605
- raw = readFileSync(path, "utf8");
611
+ raw = sources?.read(path) ?? readFileSync(path, "utf8");
606
612
  } catch (error) {
607
613
  diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${path}: ${(error as Error).message}`, {
608
614
  scope,
@@ -614,7 +620,7 @@ function collectDirectory(
614
620
  }
615
621
  let parse: ParseResult;
616
622
  try {
617
- parse = parseDefinition(raw, path);
623
+ parse = sources?.parse(raw, path) ?? parseDefinition(raw, path);
618
624
  } catch (error) {
619
625
  const detail = error instanceof Error ? error.message : String(error);
620
626
  diagnostics.push(diagnostic(
@@ -765,11 +771,12 @@ function finishSnapshot(
765
771
  blocked: CatalogEntry[],
766
772
  diagnostics: Diagnostic[],
767
773
  loadedAt: string,
774
+ sources?: LoadCatalogInput["sources"],
768
775
  ): CatalogSnapshot {
769
776
  const roleEntries: Array<readonly [string, CatalogEntry]> = [];
770
777
  const agentEntries: Array<readonly [string, CatalogEntry]> = [];
771
778
  for (const entry of entries) {
772
- const frozen = deepFreeze(cloneEntry(entry));
779
+ const frozen = sources?.entry?.(entry) ?? deepFreeze(cloneEntry(entry));
773
780
  if (frozen.kind === "role") roleEntries.push([frozen.id, frozen]);
774
781
  else agentEntries.push([frozen.id, frozen]);
775
782
  }
@@ -0,0 +1,13 @@
1
+ import { withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { createApplyPatchToolDefinition } from "./shared-task-apply-patch.ts";
3
+ import { createTaskFileOperations } from "./shared-task-files.ts";
4
+
5
+ /** Ordinary worker implementation. Confined workers install their own guarded definition. */
6
+ export default function childApplyPatch(pi: ExtensionAPI): void {
7
+ const files = createTaskFileOperations({ requireLaunchPlan: () => ({ confined: false }) });
8
+ const tool = createApplyPatchToolDefinition(process.cwd(), {
9
+ readFile: files.read.readFile, writeFile: files.write.writeFile, mkdir: files.write.mkdir,
10
+ remove: files.remove.remove, checkWrite: files.check.write, checkRemove: files.check.remove,
11
+ }, withFileMutationQueue);
12
+ pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
13
+ }
@@ -70,28 +70,33 @@ export async function resolveChildClosure({ resolution, model, virtual = false,
70
70
  load = loadContract, configPaths = [] }) {
71
71
  const result = { ...resolution, specs: [], reasons: { ...resolution.reasons }, paths: {}, declarations: [],
72
72
  providers: [], modelGroups: [], fingerprints: configPaths.map(path => ({ path, hash: fingerprint(path) })) };
73
+ function requiredPath(spec, from) {
74
+ const path = resolvePath(spec, from);
75
+ if (path) return path;
76
+ const reason = (resolution.reasons[spec] ?? []).join(', ');
77
+ throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.${reason ? ` Selected for ${reason}.` : ''}`);
78
+ }
73
79
  if (resolution.mode !== 'isolated') {
74
80
  if (virtual) throw new Error(`Virtual model ${model} requires isolated mode with a declared supplier; ${resolution.mode} mode is unsupported.`);
75
- return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => {
76
- const path = resolvePath(spec);
77
- if (!path) throw new Error(`Child dependency ${spec} is not installed.`);
78
- return [spec, path];
79
- })) };
81
+ return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => [spec, requiredPath(spec)])) };
80
82
  }
81
83
  const providerMap = { ...BUILTIN_PROVIDER_EXTENSIONS, ...(config.providerExtensions ?? {}) };
82
- const active = [], done = new Set();
84
+ const active = [], done = new Set(), entrypoints = new Set();
83
85
  let ownsVirtual = false;
84
86
  const visit = async (spec, from) => {
85
- const path = resolvePath(spec, from);
86
- if (!path) throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.`);
87
+ const path = requiredPath(spec, from);
87
88
  const root = packageRoot(path);
88
89
  const identity = root ?? realpathSync(path);
89
90
  if (active.includes(identity)) throw new Error(`Child dependency cycle: ${[...active, identity].join(' -> ')}`);
90
- if (done.has(identity)) return;
91
- active.push(identity);
91
+ // Different tool entrypoints can share a package and its dependency manifest.
92
+ const entrypoint = realpathSync(path);
93
+ if (entrypoints.has(entrypoint)) return;
94
+ entrypoints.add(entrypoint);
92
95
  // Two packages may declare the same relative spec against different roots.
93
96
  const key = result.paths[spec] && result.paths[spec] !== path ? path : spec;
94
97
  result.specs.push(key); result.paths[key] = path;
98
+ if (done.has(identity)) return;
99
+ active.push(identity);
95
100
  if (root) {
96
101
  const manifestPath = join(root, 'package.json');
97
102
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
@@ -137,7 +142,7 @@ export async function resolveChildLaunch(options, trustedPaths = []) {
137
142
  }
138
143
 
139
144
  /** Validate actual child registration, never the parent's catalog. Groups require one physical candidate. */
140
- export async function checkChildPreflight(plan, { registry, tools, model }, load = loadContract) {
145
+ export async function checkChildPreflight(plan, { registry, tools, registeredTools = [], model }, load = loadContract) {
141
146
  if (plan.configSnapshot && JSON.stringify(configSnapshot(plan.configSnapshot.map(item => item.dir))) !== JSON.stringify(plan.configSnapshot))
142
147
  throw new Error('Child configuration drift: agent or project JSON configuration changed. Launch again.');
143
148
  for (const item of plan.fingerprints) if (fingerprint(item.path) !== item.hash)
@@ -157,5 +162,13 @@ export async function checkChildPreflight(plan, { registry, tools, model }, load
157
162
  for (const group of plan.modelGroups) if (!available.some(m => m.provider === group.provider && m.api !== 'pi-virtual' &&
158
163
  (group.ids.includes(m.id) || (group.prefix && m.id.startsWith(group.prefix)))))
159
164
  throw new Error(`Child has no available candidate for ${group.provider}: ${group.ids.join(', ')}${group.prefix ? ` (prefix ${group.prefix})` : ''}. Check extension, models and credentials.`);
160
- for (const tool of plan.tools) if (!tools.includes(tool)) throw new Error(`Child requested tool ${tool} is unavailable.`);
165
+ const inactive = [];
166
+ for (const tool of plan.tools) {
167
+ if (tools.includes(tool)) continue;
168
+ if (!plan.optionalTrustedTools?.includes(tool) || !registeredTools.includes(tool)) {
169
+ throw new Error(`Child requested tool ${tool} is unavailable.`);
170
+ }
171
+ inactive.push(tool);
172
+ }
173
+ return inactive;
161
174
  }
@@ -20,6 +20,7 @@ import { connect, type Socket } from "node:net";
20
20
  import * as piSdk from "@earendil-works/pi-coding-agent";
21
21
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
22
22
  import { captureParkCheckpoint, type ParkCheckpoint } from "./park-checkpoint.ts";
23
+ import { supportsPromptSections } from "./shared-execution-policy.ts";
23
24
  import {
24
25
  ACKNOWLEDGE_OPERATION_TOOL,
25
26
  OPERATION_BRIDGE_ENV_KEYS,
@@ -28,12 +29,14 @@ import {
28
29
  OPERATIONS_ATTEMPT_ID_ENV,
29
30
  OPERATIONS_CHILD_ID_ENV,
30
31
  OPERATIONS_CONVERSATION_ID_ENV,
32
+ OPERATIONS_DEADLINE_AT_ENV,
31
33
  OPERATIONS_ENABLED_ENV,
32
34
  OPERATIONS_ENDPOINT_ENV,
33
35
  OPERATIONS_RUN_ID_ENV,
34
36
  OPERATIONS_TOKEN_ENV,
35
37
  OPERATIONS_WRITER_LEASE_ID_ENV,
36
38
  WAIT_OPERATIONS_TOOL,
39
+ assertWaitToolDependencies,
37
40
  OperationBridgeError,
38
41
  OperationToolError,
39
42
  type JsonRecord,
@@ -54,6 +57,7 @@ import {
54
57
  requiresParkCheckpoint,
55
58
  parseBridgeEndpoint,
56
59
  validateJsonSchemaSupport,
60
+ validateJsonSchema,
57
61
  redactSecret,
58
62
  } from "./operation-bridge-types.ts";
59
63
 
@@ -67,6 +71,7 @@ export interface ChildOperationBridgeConfig {
67
71
  attemptId?: string;
68
72
  writerLeaseId?: string;
69
73
  childId?: string;
74
+ deadlineAt?: number | null;
70
75
  requestTimeoutMs?: number;
71
76
  }
72
77
 
@@ -120,6 +125,10 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
120
125
  const token = env[OPERATIONS_TOKEN_ENV]!;
121
126
  const runId = env[OPERATIONS_RUN_ID_ENV]!;
122
127
  const conversationId = env[OPERATIONS_CONVERSATION_ID_ENV]!;
128
+ const deadline = env[OPERATIONS_DEADLINE_AT_ENV];
129
+ if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)))) {
130
+ return { status: "invalid", reason: "operation bridge assignment deadline is invalid" };
131
+ }
123
132
  try {
124
133
  parseBridgeEndpoint(endpoint);
125
134
  } catch {
@@ -138,6 +147,7 @@ export function readChildOperationBridgeConfig(env: NodeJS.ProcessEnv = process.
138
147
  token,
139
148
  runId,
140
149
  conversationId,
150
+ ...(deadline !== undefined ? { deadlineAt: Number(deadline) || null } : {}),
141
151
  ...(env[OPERATIONS_ATTEMPT_ID_ENV] ? { attemptId: env[OPERATIONS_ATTEMPT_ID_ENV]! } : {}),
142
152
  ...(env[OPERATIONS_WRITER_LEASE_ID_ENV] ? { writerLeaseId: env[OPERATIONS_WRITER_LEASE_ID_ENV]! } : {}),
143
153
  ...(env[OPERATIONS_CHILD_ID_ENV] ? { childId: env[OPERATIONS_CHILD_ID_ENV]! } : {}),
@@ -488,6 +498,7 @@ export function verifyDescriptor(value: unknown, config: Pick<ChildOperationBrid
488
498
  }));
489
499
  }
490
500
  const capabilities = validateCapabilities(record.capabilities);
501
+ assertWaitToolDependencies(capabilities, [...seen]);
491
502
  if (seen.has(WAIT_OPERATIONS_TOOL) && !(capabilities.wait && capabilities.parking)) {
492
503
  throw new OperationBridgeError("invalid-request", "parent exposed wait_for_operations without a parking capability");
493
504
  }
@@ -809,7 +820,19 @@ export function installChildOperationBridge(
809
820
  let installed = false;
810
821
  let starting: Promise<void> | undefined;
811
822
  let completingPark = false;
823
+ let completion = { correctionUsed: false, reported: false };
824
+ let reportError: string | undefined;
825
+ let bridgeConfig: ChildOperationBridgeConfig | undefined;
812
826
  const env = options.env ?? process.env;
827
+ const completionEntryType = "pi-subagent-completion";
828
+
829
+ const canCorrectCompletion = (signal?: AbortSignal): boolean => state.status === "ready"
830
+ && !completion.correctionUsed && !completion.reported && !signal?.aborted
831
+ && (bridgeConfig?.deadlineAt == null || Date.now() < bridgeConfig.deadlineAt);
832
+
833
+ function saveCompletion(): void {
834
+ pi.appendEntry(completionEntryType, { attemptId: bridgeConfig?.attemptId ?? bridgeConfig?.runId, ...completion });
835
+ }
813
836
 
814
837
  const handle: ChildOperationBridgeHandle = {
815
838
  getState: () => ({ ...state, ...(state.descriptor ? { descriptor: state.descriptor } : {}) }),
@@ -843,7 +866,7 @@ export function installChildOperationBridge(
843
866
  if (activeToolExecutions === 0) restoreBridgeEnvironment();
844
867
  });
845
868
 
846
- pi.on("session_start", async (_event, _ctx) => {
869
+ pi.on("session_start", async (_event, ctx) => {
847
870
  if (installed || starting) return starting;
848
871
  starting = (async () => {
849
872
  const read = options.config
@@ -856,6 +879,7 @@ export function installChildOperationBridge(
856
879
  return;
857
880
  }
858
881
  state.status = "connecting";
882
+ bridgeConfig = read.config;
859
883
  options.onDiagnostic?.({ event: "connecting" });
860
884
  const active = (options.clientFactory ?? ((config) => createOperationBridgeClient(config, {
861
885
  requestTimeoutMs: options.requestTimeoutMs,
@@ -872,6 +896,17 @@ export function installChildOperationBridge(
872
896
  }
873
897
  client = active;
874
898
  state.descriptor = descriptor;
899
+ if (descriptor.capabilities.reportAssignment) {
900
+ const entries = ctx.sessionManager.getEntries();
901
+ for (let index = entries.length - 1; index >= 0; index--) {
902
+ const entry = entries[index]!;
903
+ if (entry.type !== "custom" || entry.customType !== completionEntryType) continue;
904
+ const data = entry.data as { attemptId?: string; correctionUsed?: boolean; reported?: boolean } | undefined;
905
+ if (data?.attemptId !== (read.config.attemptId ?? read.config.runId)) continue;
906
+ completion = { correctionUsed: data.correctionUsed === true, reported: data.reported === true };
907
+ break;
908
+ }
909
+ }
875
910
  try {
876
911
  registerTools(descriptor, state.parkingSupported === true);
877
912
  } catch (error) {
@@ -889,6 +924,31 @@ export function installChildOperationBridge(
889
924
  return starting;
890
925
  });
891
926
 
927
+ pi.on("before_agent_start", (event, ctx) => {
928
+ if (!state.descriptor?.capabilities.reportAssignment) return;
929
+ const instruction = `Assignment completion: call report_assignment_result before returning. Evidence sources must resolve inside this assigned workspace: ${JSON.stringify(ctx.cwd)}. A sibling output directory is outside that boundary; use an existing workspace file or place the reportable artifact inside the workspace. Use offset and max_bytes for evidence larger than 65536 bytes. Continue remaining local work within the existing deadline, or report a concrete blocker; do not infer a tool-call budget from the number of calls you have made.`;
930
+ if (!supportsPromptSections(event.systemPromptOptions)) return { systemPrompt: `${event.systemPrompt}\n\n${instruction}` };
931
+ const prompt = event.systemPromptOptions as { sections?: Record<string, string> };
932
+ (prompt.sections ??= {}).assignment_completion = instruction;
933
+ });
934
+
935
+ pi.on("agent_end", (event, ctx) => {
936
+ if (!state.descriptor?.capabilities.reportAssignment || !canCorrectCompletion(ctx.signal)) return;
937
+ let last;
938
+ for (let index = event.messages.length - 1; index >= 0; index--) {
939
+ const message = event.messages[index]!;
940
+ if (message.role !== "assistant") continue;
941
+ last = message;
942
+ break;
943
+ }
944
+ if (last?.stopReason !== "stop") return;
945
+ completion.correctionUsed = true;
946
+ saveCompletion();
947
+ pi.sendMessage({ customType: "assignment-completion-correction", display: false,
948
+ content: `The assignment has no accepted report. ${reportError ? `The latest report was refused: ${reportError}. ` : ""}This is the one completion correction for this execution attempt, within its original authority and deadline. Finish available remaining work, inspect and acknowledge any outstanding operation evidence, then call report_assignment_result with workspace evidence. If progress is blocked or work remains, report incomplete with remaining_work and the concrete blocker. Do not claim completion from process exit or final prose.` },
949
+ { deliverAs: "followUp", triggerTurn: true });
950
+ });
951
+
892
952
  pi.on("message_end", (event) => {
893
953
  const message = event.message as { role?: string; content?: unknown };
894
954
  if (message.role !== "assistant" || !Array.isArray(message.content)) return;
@@ -963,6 +1023,7 @@ export function installChildOperationBridge(
963
1023
  try {
964
1024
  return await invokeTool(tool, toolCallId, params, signal);
965
1025
  } catch (error) {
1026
+ if (tool.name === "report_assignment_result") reportError = redactSecret(error instanceof Error ? error.message : String(error)).slice(0, 2048);
966
1027
  return toolErrorResult(error);
967
1028
  }
968
1029
  },
@@ -981,6 +1042,13 @@ export function installChildOperationBridge(
981
1042
  throw new OperationToolError("tool parameters must be an object");
982
1043
  }
983
1044
  const params = rawParams as JsonRecord;
1045
+ if (tool.name === "report_assignment_result" && params.status === "incomplete" && !params.blocker
1046
+ && Array.isArray(params.remaining_work) && params.remaining_work.length > 0
1047
+ && validateJsonSchema(tool.parameters, params).ok && canCorrectCompletion(signal)) {
1048
+ completion.correctionUsed = true;
1049
+ saveCompletion();
1050
+ throw new OperationToolError("The incomplete report has not been accepted. Use the one completion correction to continue the listed remaining local work within the original authority and deadline, then report the result. If blocked or still incomplete, report that explicitly; no further automatic correction will be requested.");
1051
+ }
984
1052
  if (isLaunchTool(tool.name, params)) {
985
1053
  const bridgeEnvironmentField = findBridgeEnvironmentKey(params);
986
1054
  if (bridgeEnvironmentField) {
@@ -991,6 +1059,17 @@ export function installChildOperationBridge(
991
1059
  }
992
1060
  }
993
1061
  const raw = await client.request(tool.name, params, { signal });
1062
+ if (tool.name === "report_assignment_result" && raw && typeof raw === "object"
1063
+ && ["complete", "incomplete"].includes(String((raw as JsonRecord).status))) {
1064
+ completion.reported = true;
1065
+ reportError = undefined;
1066
+ saveCompletion();
1067
+ }
1068
+ if (tool.name === ACKNOWLEDGE_OPERATION_TOOL && params.disposition === "assignment-complete"
1069
+ && raw && typeof raw === "object" && (raw as JsonRecord).phase === "consumed") {
1070
+ completion.reported = true;
1071
+ saveCompletion();
1072
+ }
994
1073
  if (tool.name === WAIT_OPERATIONS_TOOL) {
995
1074
  return waitToolResult(toolCallId, raw);
996
1075
  }
@@ -9,12 +9,18 @@ export default function childPreflight(pi) {
9
9
  };
10
10
  let plan;
11
11
  try { plan = JSON.parse(readFileSync(process.env[PREFLIGHT_ENV], 'utf8')); } catch (error) { fail(error); }
12
+ const reported = new Set();
12
13
  // The task guard activates its adapters on session_start. Check after every
13
14
  // startup handler has finished, before the first request (and subsequent runs).
14
15
  const check = async (ctx, tools) => {
15
16
  try {
16
- await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
17
- tools: pi.getActiveTools(), model: ctx.model });
17
+ const inactive = await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
18
+ tools: pi.getActiveTools(), registeredTools: pi.getAllTools?.().map(tool => tool.name), model: ctx.model });
19
+ const newlyInactive = inactive.filter(tool => !reported.has(tool));
20
+ if (newlyInactive.length) {
21
+ for (const tool of newlyInactive) reported.add(tool);
22
+ process.stderr.write(`Subagent child preflight: inherited trusted tools are inactive in this child: ${newlyInactive.join(', ')}. Continuing without them.\n`);
23
+ }
18
24
  } catch (error) { fail(error); }
19
25
  };
20
26
  pi.on('session_start', async (_event, ctx) => check(ctx, []));
@@ -0,0 +1,8 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { createProcessListToolDefinition } from "./shared-task-process-list.ts";
3
+
4
+ /** Keep the fixed, bounded inventory contract when no task sandbox is active. */
5
+ export default function childProcessList(pi: ExtensionAPI): void {
6
+ const tool = createProcessListToolDefinition(process.cwd(), { requireLaunchPlan: () => ({ confined: false }) }, () => "read");
7
+ pi.registerTool(tool as Parameters<ExtensionAPI["registerTool"]>[0]);
8
+ }
package/cleanup.ts CHANGED
@@ -615,7 +615,7 @@ function removeAgedRunArtifacts(
615
615
  if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return false;
616
616
  const fresh = readMeta(meta.id) ?? meta;
617
617
  if (!ageSweepEligible(fresh, cutoff, retained, scope)) return false;
618
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return true;
618
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return true;
619
619
  errors.push(`${runDir(meta.id)}: could not remove run artifacts`);
620
620
  return false;
621
621
  }, () => false);
@@ -867,6 +867,7 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
867
867
  return [];
868
868
  }
869
869
  const entries: SizeCapEntry[] = [];
870
+ const workspaces = new Map<string, { root: string; started: number; entry: SizeCapEntry }>();
870
871
  for (const id of ids) {
871
872
  const dir = runDir(id);
872
873
  const meta = readMeta(id);
@@ -877,7 +878,14 @@ export function collectSizeCapEntries(): SizeCapEntry[] {
877
878
  dirMtimeMs: safeStatMtime(dir) ?? 0,
878
879
  bytes: dirBytes(dir),
879
880
  });
881
+ const workspace = meta?.recipe?.workspace;
882
+ if (workspace && meta && meta.startedAt >= (workspaces.get(workspace.owner)?.started ?? 0)) {
883
+ workspaces.set(workspace.owner, { root: workspace.root, started: meta.startedAt, entry: entries[entries.length - 1]! });
884
+ }
880
885
  }
886
+ // A restored conversation may have outlived its first attempt. Charge its
887
+ // one shared checkout to the most recent writer still in the registry.
888
+ for (const { root, entry } of workspaces.values()) entry.bytes += dirBytes(root);
881
889
  return entries;
882
890
  }
883
891
 
@@ -999,7 +1007,7 @@ function removeSizeCappedRun(
999
1007
  if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
1000
1008
  if (outcomeProtected(fresh)) return "retained";
1001
1009
  if (scope.occupancy.runIds.has(fresh.id)) return "retained";
1002
- if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
1010
+ if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId), errors })) return "removed";
1003
1011
  errors.push(`${runDir(id)}: could not remove run artifacts`);
1004
1012
  return "failed";
1005
1013
  }, () => "retained");
package/config.ts CHANGED
@@ -9,12 +9,14 @@
9
9
  * `defaultSkills` absent → the child discovers the user-level skills catalog.
10
10
  */
11
11
 
12
- import { existsSync, readFileSync, statSync } from "node:fs";
12
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { dirname, isAbsolute, join } from "node:path";
15
15
  import { homedir } from "node:os";
16
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
+ import { toolPackage, supportsChildProvider } from "./shared-task-tools.ts";
16
18
  import { SELF_SPEC } from "./extensions.ts";
17
- import { installedPackage } from "./child-dependencies.mjs";
19
+ import { installedPackage, packageRoot } from "./child-dependencies.mjs";
18
20
  import { isDelegationMode, type DelegationMode } from "./delegation.ts";
19
21
  import { normalizeSkillExposure } from "./skills.ts";
20
22
  import { validatedTimingMinutes, type TimingSettings } from "./timing.ts";
@@ -23,6 +25,7 @@ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from ".
23
25
  export interface SubagentConfig extends TimingSettings {
24
26
  /** Foreground delegation policy; /subagents mode overrides this for the current session. */
25
27
  delegationMode?: DelegationMode | null;
28
+ gitWorkspace?: "clone" | "worktree";
26
29
  defaultModel?: string | null;
27
30
  defaultTools?: string | null;
28
31
  /**
@@ -195,6 +198,7 @@ export function writeSubagentSettings(
195
198
  settings: {
196
199
  delegationMode: DelegationMode;
197
200
  maxConcurrent: number;
201
+ gitWorkspace?: "clone" | "worktree";
198
202
  maxMinutes?: number;
199
203
  /** Omit to preserve the saved value; `null` explicitly records discovery. */
200
204
  defaultSkills?: string[] | null;
@@ -209,11 +213,15 @@ export function writeSubagentSettings(
209
213
  if (!isConcurrencyCap(settings.maxConcurrent)) throw new Error("Concurrent subagents must be a positive whole number.");
210
214
  const next: {
211
215
  delegationMode: DelegationMode; maxConcurrent: number; maxMinutes?: number; defaultSkills?: string[] | null;
212
- toolWaitMinutes?: number; stuckMinutes?: number;
216
+ toolWaitMinutes?: number; stuckMinutes?: number; gitWorkspace?: "clone" | "worktree";
213
217
  } = {
214
218
  delegationMode: settings.delegationMode,
215
219
  maxConcurrent: settings.maxConcurrent,
216
220
  };
221
+ if (settings.gitWorkspace !== undefined) {
222
+ if (settings.gitWorkspace !== "clone" && settings.gitWorkspace !== "worktree") throw new Error("Unknown Git workspace mode.");
223
+ next.gitWorkspace = settings.gitWorkspace;
224
+ }
217
225
  if (settings.maxMinutes !== undefined) {
218
226
  next.maxMinutes = validatedTimingMinutes(settings.maxMinutes, "maxMinutes");
219
227
  }
@@ -251,6 +259,48 @@ export function normalizeTools(list: string): string {
251
259
  return list.split(",").map((t) => t.trim()).filter(Boolean).join(",");
252
260
  }
253
261
 
262
+ export const ORDINARY_TOOL_PROVIDERS: Readonly<Record<string, string>> = {
263
+ apply_patch: join(selfDir(), "child-apply-patch.ts"),
264
+ process_list: join(selfDir(), "child-process-list.ts"),
265
+ };
266
+
267
+ /** Check the owning package even when a mapping points directly to one of its files. */
268
+ export function supportedChildEntrypoint(name: string, pkg: string, path: string): boolean {
269
+ return supportsChildProvider(name, pkg, packageRoot(path) ?? path);
270
+ }
271
+
272
+ /** Capture exact user-installed entrypoints already active in the foreground. */
273
+ export function activeChildProviders(pi: Pick<ExtensionAPI, "getActiveTools" | "getAllTools">): Record<string, string> {
274
+ const active = new Set(pi.getActiveTools?.() ?? []);
275
+ const paths = new Map<string, string>();
276
+ const seen = new Set<string>();
277
+ for (const tool of pi.getAllTools?.() ?? []) {
278
+ if (!active.has(tool.name)) continue;
279
+ // The SDK reports active names. Conflicting registrations have no unique owner.
280
+ if (seen.has(tool.name)) { paths.delete(tool.name); continue; }
281
+ seen.add(tool.name);
282
+ if (tool.sourceInfo?.scope !== "user") continue;
283
+ const owner = toolPackage(tool);
284
+ if (!owner || !supportsChildProvider(tool.name, owner.package, owner.root)) continue;
285
+ try {
286
+ const path = realpathSync(tool.sourceInfo.path);
287
+ if (!statSync(path).isFile() || !supportedChildEntrypoint(tool.name, owner.package, path)) continue;
288
+ paths.set(tool.name, path);
289
+ } catch { /* An unavailable entrypoint cannot supply a new worker. */ }
290
+ }
291
+ return Object.fromEntries(paths);
292
+ }
293
+
294
+ export function ordinaryChildConfig(config: SubagentConfig, activeProviders: Record<string, string> = {}): SubagentConfig {
295
+ const packaged = config.toolExtensions === null ? undefined : bundledConfig().toolExtensions;
296
+ return { ...config, toolExtensions: { ...activeProviders, ...ORDINARY_TOOL_PROVIDERS, ...packaged, ...config.toolExtensions } };
297
+ }
298
+
299
+ export function addEditablePatch(names: string[], excluded: ReadonlySet<string>): void {
300
+ const editable = names.some(name => (name === "edit" || name === "write") && !excluded.has(name));
301
+ if (editable && !excluded.has("apply_patch") && !names.includes("apply_patch")) names.push("apply_patch");
302
+ }
303
+
254
304
  /** This package's own root — the extension dir, which is also `self`. */
255
305
  export function selfDir(): string {
256
306
  return dirname(fileURLToPath(import.meta.url));
@@ -10,8 +10,10 @@ export function intersectContinuationPermissions(captured: any, current: any): a
10
10
  .sort((a, b) => a.name.localeCompare(b.name) || a.package.localeCompare(b.package)) };
11
11
  const intersect = (old: any, fresh: any) => {
12
12
  if (!old || !fresh) throw new Error("Continuation permission profile unavailable");
13
+ if (!fresh.enabled) return old.enabled ? { ...old } : { ...fresh };
14
+ if (!old.enabled) return { ...fresh };
13
15
  const access = ["off", "read", "write", "read-write"];
14
- const value = { ...fresh, enabled: old.enabled || fresh.enabled };
16
+ const value = { ...fresh };
15
17
  for (const key of ["projectFiles", "outsideProject", "storedCredentials"]) {
16
18
  if (!access.includes(old[key]) || !access.includes(fresh[key])) throw new Error("Invalid continuation permission profile");
17
19
  value[key] = access[Math.min(access.indexOf(old[key]), access.indexOf(fresh[key]))];