oira666_pi-subagent 0.5.9 → 0.5.10

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/docs/sessions.md CHANGED
@@ -30,7 +30,7 @@ The ledger uses immutable files and atomic hard links beside saved worker sessio
30
30
  }
31
31
  ```
32
32
 
33
- The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap.
33
+ The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap. Provider-generated `null` for this optional field also keeps the cap; explicit `0` still replaces it with zero.
34
34
 
35
35
  - Increases reserve only additional capacity from the original launcher's allowance.
36
36
  - Decreases cannot remove slots already spent or assigned. They do not refund the parent. Raising a cap to a previously funded value needs no new reservation.
@@ -47,7 +47,9 @@ The shared name registry and ownership identity are recorded in session metadata
47
47
 
48
48
  The agent that launched a worker owns its original session. A child may receive an ancestor's worker name in its task. Resuming that name creates a private session fork, leaving the owner's context untouched. Each caller reuses one fork per name, including across restarts. Forks retain the same budget.
49
49
 
50
- Concurrent resumes of the same session are rejected using both in-process checks and crash-tolerant registry markers. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context.
50
+ Concurrent resumes of the same session are rejected using both in-process checks and crash-tolerant registry markers. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context. Resumes open the saved transcript explicitly, preserving its original working directory even when the caller's directory differs. They do not use Pi's cwd-filtered `--continue` discovery. The runner selects that transcript once before extension discovery and uses its working directory for discovery and process startup. Caller approval applies only when that directory matches the caller's project; otherwise the saved project is explicitly unapproved, including when extension exclusions are disabled.
51
+
52
+ Relative `--skill`, `--prompt-template`, and theme file/directory arguments keep the parent's startup directory as their base, even when a resumed worker runs in another project. Named theme selections and non-filesystem references are forwarded unchanged.
51
53
 
52
54
  ## Crash recovery
53
55
 
@@ -1,4 +1,4 @@
1
- import { Assert } from "@sinclair/typebox/value";
1
+ import { Value } from "@sinclair/typebox/value";
2
2
  import type { Static, TSchema, TLiteral } from "@sinclair/typebox";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { isBranchBudgetAmount, SubagentBudgetError } from "../budget.js";
@@ -58,7 +58,8 @@ export const ResumeItem = Type.Object(
58
58
 
59
59
  export const ResumeSubagentsParams = Type.Object(
60
60
  {
61
- resumes: Type.Union([Type.Array(ResumeItem, { minItems: 1 }), ResumeItem], {
61
+ resumes: Type.Array(ResumeItem, {
62
+ minItems: 1,
62
63
  description: "Array of {subagent, task} objects. Each named subagent is resumed in parallel with its new task.",
63
64
  }),
64
65
  },
@@ -188,6 +189,15 @@ export function prepareRecoveryArguments(
188
189
 
189
190
  /** SDK argument preparation must return a schema-validated value. */
190
191
  export function validatePreparedArguments<T extends TSchema>(schema: T, value: unknown): Static<T> {
191
- Assert(schema, value);
192
- return value;
192
+ if (Value.Check(schema, value)) return value;
193
+ // Pi aliases TypeBox imports to its installed version. Newer Assert errors say only "Assert".
194
+ // Read validation issues directly so both TypeBox versions report useful paths without echoing input.
195
+ const issues = Array.from(Value.Errors(schema, value), (error) => {
196
+ const at = "instancePath" in error && typeof error.instancePath === "string" ? error.instancePath : error.path;
197
+ const params = "params" in error && isRecord(error.params) ? error.params : {};
198
+ const keys = params.additionalProperties ?? params.requiredProperties;
199
+ const properties = Array.isArray(keys) ? ` (${keys.filter((key) => typeof key === "string").join(", ")})` : "";
200
+ return `${at || "root"}: ${error.message}${properties}`;
201
+ });
202
+ throw new Error(`Invalid tool arguments:\n${issues.join("\n")}`);
193
203
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-subagent",
3
- "version": "0.5.9",
3
+ "version": "0.5.10",
4
4
  "description": "Subagent extension for Pi coding agent. Delegate tasks to specialized agents.",
5
5
  "type": "module",
6
6
  "main": "index.ts",
@@ -3,8 +3,10 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { AgentConfig } from "../agents.js";
5
5
  import type { SubagentModelSettings } from "../storage/name-records.js";
6
+ import { latestSessionFile } from "../storage/session-fork.js";
6
7
  import { SUBAGENT_FALLBACK_MODEL_ENV } from "./constants.js";
7
8
  import { childExtensionArgs, excludedExtensions } from "./extension-policy.js";
9
+ import { resolveInheritedResource } from "./resource-paths.js";
8
10
  function resolveExtensionArg(value: string): string {
9
11
  if (!value) return value;
10
12
  if (value.startsWith("npm:") || value.startsWith("git:")) return value;
@@ -18,7 +20,7 @@ function resolveExtensionArg(value: string): string {
18
20
  interface InheritedCliArgs {
19
21
  /** --extension/-e and --no-extensions/-ne args (with path resolution) */
20
22
  extensionArgs: string[];
21
- /** All other non-blocked flags to forward verbatim to every child */
23
+ /** Other non-blocked flags, with filesystem resources anchored to the startup cwd. */
22
24
  alwaysProxy: string[];
23
25
  /** Explicit CLI provider associated with a forwarded --api-key. */
24
26
  explicitProvider: string | undefined;
@@ -45,7 +47,7 @@ interface InheritedCliArgs {
45
47
  * Unknown flags use a heuristic: if the next token doesn't start with "-",
46
48
  * it is treated as the flag's value.
47
49
  */
48
- function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
50
+ function parseInheritedCliArgs(argv: string[], startupCwd = process.cwd()): InheritedCliArgs {
49
51
  const extensionArgs: string[] = [];
50
52
  const alwaysProxy: string[] = [];
51
53
  let explicitProvider: string | undefined;
@@ -149,7 +151,10 @@ function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
149
151
  ) {
150
152
  const [value, skip] = getVal();
151
153
  if (value !== undefined) {
152
- alwaysProxy.push(flagName, value);
154
+ const forwarded = ["--skill", "--prompt-template", "--theme"].includes(flagName)
155
+ ? resolveInheritedResource(flagName, value, startupCwd)
156
+ : value;
157
+ alwaysProxy.push(flagName, forwarded);
153
158
  if (flagName === "--provider") explicitProvider = value;
154
159
  }
155
160
  i += skip;
@@ -218,9 +223,16 @@ function parseInheritedCliArgs(argv: string[]): InheritedCliArgs {
218
223
  /** Cached once — process.argv is immutable at runtime */
219
224
  const _inheritedCliArgs = parseInheritedCliArgs(process.argv);
220
225
 
221
- export async function resolveChildExtensionArgs(cwd: string, projectTrusted?: boolean): Promise<string[] | undefined> {
226
+ export async function resolveChildExtensionArgs(
227
+ cwd: string,
228
+ projectTrusted?: boolean,
229
+ forceTrustDecision = false,
230
+ ): Promise<string[] | undefined> {
222
231
  const excludes = excludedExtensions();
223
- if (excludes.length === 0) return undefined;
232
+ if (excludes.length === 0)
233
+ return forceTrustDecision
234
+ ? [..._inheritedCliArgs.extensionArgs, projectTrusted ? "--approve" : "--no-approve"]
235
+ : undefined;
224
236
  return childExtensionArgs(_inheritedCliArgs.extensionArgs, cwd, projectTrusted, excludes);
225
237
  }
226
238
 
@@ -255,6 +267,7 @@ export function buildPiArgs(
255
267
  selection?: { provider: string; model: string; thinking: string },
256
268
  extensionArgsOverride?: string[],
257
269
  resumeSettings?: SubagentModelSettings,
270
+ savedSessionFile?: string | null,
258
271
  ): { args: string[]; prompt: string } {
259
272
  const provider = resumeSettings?.model?.includes("/") ? resumeSettings.model.split("/", 1)[0] : selection?.provider;
260
273
  // Named resumes can reuse CLI-only auth, but only for the explicitly matching provider.
@@ -277,10 +290,18 @@ export function buildPiArgs(
277
290
  if (extensionArgsOverride) args.push(...extensionArgsOverride);
278
291
 
279
292
  if (sessionDir) args.push("--session-dir", sessionDir);
280
- if (resumeSession) args.push("--continue");
293
+ if (resumeSession || resumeSettings) {
294
+ // The runner pins this before resource discovery. Only standalone callers select here.
295
+ const savedFile =
296
+ savedSessionFile === undefined ? (sessionDir ? latestSessionFile(sessionDir) : undefined) : savedSessionFile;
297
+ if (savedFile) args.push("--session", savedFile);
298
+ else if (resumeSettings)
299
+ throw new Error(`Cannot resume named subagent: no saved session file in ${sessionDir ?? "(missing directory)"}.`);
300
+ else args.push("--continue"); // Legacy recovery without a saved transcript can start from its task.
301
+ }
281
302
 
282
303
  // Named resumes bypass today's parent, agent definition, CLI defaults, and presets.
283
- // Missing legacy settings are left to --continue rather than replaced with current defaults.
304
+ // Missing legacy settings are left to the saved session rather than replaced with current defaults.
284
305
  const model = resumeSettings
285
306
  ? resumeSettings.model
286
307
  : (selection?.model ?? resolveSubagentModel(agent.model, fallbackModelOverride));
package/runner/options.ts CHANGED
@@ -15,7 +15,7 @@ export interface RunningSubagentHandle {
15
15
  export type RunningSubagentStartedCallback = (handle: RunningSubagentHandle) => void;
16
16
 
17
17
  export interface RunAgentOptions {
18
- /** Working directory inherited by every subagent process. */
18
+ /** Caller working directory; saved-session resumes run in the saved project's cwd. */
19
19
  cwd: string;
20
20
  /** Effective trust for this cwd; absent SDK callers fail closed. */
21
21
  projectTrusted?: boolean;
@@ -56,7 +56,7 @@ export interface RunAgentOptions {
56
56
  * self-set env var would then masquerade as "inherited from a parent".
57
57
  */
58
58
  namesFile?: string;
59
- /** Continue the most recent session in sessionDir instead of creating a new one. */
59
+ /** Select and pin the most recent saved session in sessionDir instead of creating a new one. */
60
60
  resumeSession?: boolean;
61
61
  /** Previously captured state for this same subagent, used to render resumed nested trees. */
62
62
  initialResult?: SingleResult;
@@ -0,0 +1,25 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ /** Pin explicit filesystem resources before a resume switches the child to another project. */
7
+ export function resolveInheritedResource(flag: string, value: string, startupCwd: string): string {
8
+ if (path.isAbsolute(value)) return value;
9
+ if (value.startsWith("file://")) return fileURLToPath(value);
10
+ // Keep package/URL/builtin references, but do not mistake Windows drive paths for URI schemes.
11
+ if (!/^[a-z]:/i.test(value) && (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith("git@"))) return value;
12
+ if (value === "~") return os.homedir();
13
+ if (value.startsWith("~/") || (process.platform === "win32" && value.startsWith("~\\")))
14
+ return path.join(os.homedir(), value.slice(2));
15
+ // Bare theme identifiers stay names; explicit paths and existing local theme resources are pinned.
16
+ if (
17
+ flag === "--theme" &&
18
+ !/[\\/]/.test(value) &&
19
+ !value.endsWith(".json") &&
20
+ !fs.existsSync(path.resolve(startupCwd, value))
21
+ )
22
+ return value;
23
+ // Resolve even missing files so a same-named file in the saved project cannot replace them.
24
+ return path.resolve(startupCwd, value);
25
+ }
@@ -0,0 +1,58 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { latestSessionFile } from "../storage/session-fork.js";
4
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
5
+ import { isRecord } from "../storage/values.js";
6
+
7
+ export interface SessionTarget {
8
+ cwd: string;
9
+ sessionDir: string | undefined;
10
+ /** null pins the absence of a transcript, so argument building must not rediscover one. */
11
+ sessionFile: string | null;
12
+ }
13
+
14
+ /** Select once, before asynchronous resource discovery, and use this target throughout the launch. */
15
+ export function resolveSessionTarget(
16
+ callerCwd: string,
17
+ sessionDir: string | undefined,
18
+ resumeSession: boolean,
19
+ namedResume = false,
20
+ ): SessionTarget {
21
+ const target: SessionTarget = {
22
+ cwd: path.resolve(callerCwd),
23
+ sessionDir: sessionDir ? path.resolve(callerCwd, sessionDir) : undefined,
24
+ sessionFile: null,
25
+ };
26
+ if (!resumeSession && !namedResume) return target;
27
+ target.sessionFile = target.sessionDir ? (latestSessionFile(target.sessionDir) ?? null) : null;
28
+ if (!target.sessionFile) {
29
+ if (namedResume)
30
+ throw new Error(`Cannot resume named subagent: no saved session file in ${sessionDir ?? "(missing directory)"}.`);
31
+ return target;
32
+ }
33
+ // Like Pi's header scan, skip blank/malformed lines but require the first parsed entry to be a header.
34
+ let header: unknown;
35
+ for (const line of fs.readFileSync(target.sessionFile, "utf8").split("\n")) {
36
+ try {
37
+ header = JSON.parse(line);
38
+ } catch {
39
+ continue;
40
+ }
41
+ if (header) break;
42
+ }
43
+ if (!isRecord(header) || header.type !== "session" || typeof header.id !== "string")
44
+ throw new Error(`Cannot resume subagent: invalid saved session header in ${target.sessionFile}.`);
45
+ if (header.cwd !== undefined && typeof header.cwd !== "string")
46
+ throw new Error(`Cannot resume subagent: invalid saved working directory in ${target.sessionFile}.`);
47
+ // Pi-created headers store native absolute paths. Reject ambiguous manually edited paths rather
48
+ // than approving one cwd while Pi interprets another. Legacy headers without cwd inherit the caller.
49
+ if (typeof header.cwd === "string" && header.cwd) {
50
+ if (!path.isAbsolute(header.cwd))
51
+ throw new Error(`Cannot resume subagent: saved working directory must be absolute in ${target.sessionFile}.`);
52
+ // Reuse Pi's normalization, including Windows shell paths; this does not open or mutate a session.
53
+ target.cwd = SessionManager.inMemory(header.cwd).getCwd();
54
+ }
55
+ if (!fs.statSync(target.cwd).isDirectory())
56
+ throw new Error(`Cannot resume subagent: saved working directory is not a directory: ${target.cwd}.`);
57
+ return target;
58
+ }
package/runner/single.ts CHANGED
@@ -14,6 +14,8 @@ import { writePromptToTempFile, cleanupTempDir, sessionDirExists } from "./files
14
14
  import { appendBoundedStderr, priorDescendantUsage, endedWithSyntheticResumeFailure } from "./result.js";
15
15
  import { runAttempt } from "./attempt.js";
16
16
  import { selectIntelligence } from "../intelligence.js";
17
+ import * as path from "node:path";
18
+ import { resolveSessionTarget } from "./session-target.js";
17
19
  export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleResult> {
18
20
  const {
19
21
  agents,
@@ -114,7 +116,18 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
114
116
  }
115
117
 
116
118
  try {
117
- const extensionArgs = await resolveChildExtensionArgs(opts.cwd, opts.projectTrusted);
119
+ if (opts.signal?.aborted) {
120
+ result.exitCode = 130;
121
+ result.stopReason = "aborted";
122
+ result.errorMessage = "Subagent was aborted.";
123
+ emitUpdate();
124
+ return result;
125
+ }
126
+ const target = resolveSessionTarget(opts.cwd, sessionDir, shouldContinueSession, !!opts.resumeSettings);
127
+ // Approval is scoped to the caller's project, never transferable to a saved project's cwd.
128
+ const projectTrusted = target.cwd === path.resolve(opts.cwd) ? opts.projectTrusted : false;
129
+ const childOpts = { ...opts, cwd: target.cwd, sessionDir: target.sessionDir, projectTrusted };
130
+ const extensionArgs = await resolveChildExtensionArgs(target.cwd, projectTrusted, !!target.sessionFile);
118
131
  if (opts.signal?.aborted) {
119
132
  result.exitCode = 130;
120
133
  result.stopReason = "aborted";
@@ -132,13 +145,14 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
132
145
  agent,
133
146
  promptTmpPath,
134
147
  task,
135
- sessionDir,
148
+ target.sessionDir,
136
149
  shouldContinueSession,
137
150
  fallbackModel,
138
151
  opts.rawPrompt === true,
139
152
  selection,
140
153
  extensionArgs,
141
154
  opts.resumeSettings,
155
+ target.sessionFile,
142
156
  );
143
157
  const prompt =
144
158
  result.budget && readBudget(result.budget).limit > 0
@@ -152,7 +166,7 @@ export async function runAgentSubprocess(opts: RunAgentOptions): Promise<SingleR
152
166
  for (let attempt = 0; ; attempt++) {
153
167
  startupTimedOut = false;
154
168
  const outcome = await runAttempt(
155
- opts.resumeSettings ? { ...opts, fallbackModel: settings.model } : opts,
169
+ opts.resumeSettings ? { ...childOpts, fallbackModel: settings.model } : childOpts,
156
170
  result,
157
171
  piArgs,
158
172
  prompt,
@@ -3,7 +3,8 @@ import * as path from "node:path";
3
3
  import { SUBAGENT_NAMES_CUSTOM_TYPE } from "./names-identity.js";
4
4
  import { isRecord } from "./values.js";
5
5
 
6
- function latestSessionFile(sessionDir: string): string | undefined {
6
+ /** Select the saved file directly; Pi's --continue filters custom session dirs by cwd. */
7
+ export function latestSessionFile(sessionDir: string): string | undefined {
7
8
  try {
8
9
  const entries = fs
9
10
  .readdirSync(sessionDir)
package/types/outcomes.ts CHANGED
@@ -18,26 +18,26 @@ export function subagentDetailsHaveErrors(value: unknown): boolean {
18
18
  return isSubagentDetails(value) && value.results.some((result) => isResultError(result));
19
19
  }
20
20
 
21
- /** Normalize common legacy/model-generated resume argument shorthands. */
21
+ /** Normalize resume shorthands and strict-provider nulls before schema validation.
22
+ * Only the optional budget accepts null as omission; required fields and intelligence remain invalid. */
22
23
  export function prepareResumeArguments(args: unknown): unknown {
23
24
  if (!args || typeof args !== "object" || Array.isArray(args)) return args;
24
25
  const record = args as Record<string, unknown>;
26
+ const omitNullBudget = (item: unknown): unknown => {
27
+ if (!item || typeof item !== "object" || Array.isArray(item)) return item;
28
+ const resume = item as Record<string, unknown>;
29
+ if (resume.max_subagents_allowed !== null) return item;
30
+ const { max_subagents_allowed: _budget, ...rest } = resume;
31
+ return rest;
32
+ };
25
33
  if (record.resumes === undefined && typeof record.subagent === "string" && typeof record.task === "string") {
26
- return {
27
- resumes: [
28
- {
29
- subagent: record.subagent,
30
- task: record.task,
31
- ...(record.intelligence !== undefined ? { intelligence: record.intelligence } : {}),
32
- ...(record.max_subagents_allowed !== undefined
33
- ? { max_subagents_allowed: record.max_subagents_allowed }
34
- : {}),
35
- },
36
- ],
37
- };
34
+ // Preserve unknown fields so validation still rejects intelligence and misspelled arguments.
35
+ const { resumes: _resumes, ...item } = record;
36
+ return { resumes: [omitNullBudget(item)] };
38
37
  }
39
- if (record.resumes && typeof record.resumes === "object" && !Array.isArray(record.resumes)) {
40
- return { ...record, resumes: [record.resumes] };
38
+ if (Array.isArray(record.resumes)) return { ...record, resumes: record.resumes.map(omitNullBudget) };
39
+ if (record.resumes && typeof record.resumes === "object") {
40
+ return { ...record, resumes: [omitNullBudget(record.resumes)] };
41
41
  }
42
42
  return args;
43
43
  }