import { homedir } from "node:os"; import { resolve } from "node:path"; import { Type } from "typebox"; import type { AgentConfig, IsolationMode, ThinkingLevel } from "./types.js"; /** * The model-facing `isolation` parameter, shared by the `Agent` tool and the * nested delegation tool so the two cannot drift. * * Shape matters more than wording here. As a single-value optional literal, * models that fill every optional parameter — the transcript on #231 shows one * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it — * had only `"worktree"` available to fill it with, and kept spawning worktrees * across three turns while their own reasoning said to omit the field. Every * other optional parameter has an inert filler; this one did not. `"off"` is * listed first and described as the default so the harmless value is the * obvious one to reach for. * * The wording tracks Claude Code's own `isolation` parameter, whose phrasing * models have the most exposure to: one description on the union rather than * per-value ones, opening "Isolation mode.", then a sentence per value in * schema order, each with its caveats in a trailing parenthetical. Two clauses * are ours, because our shape is not theirs — `"off"` has no counterpart there * (their enum is `worktree | remote`, so both of their values do something), * and neither does the uncommitted-work warning, which is the specific trap * #231 fell into. Deliberately absent is any "only use a worktree when…" * restriction: Claude Code's `Agent` tool states the capability and stops, and * a second legal value is what lets a model decline one, not being told to. */ const isolationParamShape = { isolation: Type.Optional( Type.Union([Type.Literal("off"), Type.Literal("worktree")], { description: 'Isolation mode. Default "off". "off" runs the agent in the current checkout, the same as omitting the field. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo (a copy cannot see uncommitted or staged changes in the main checkout).', }), ), }; /** * Build the `isolation` parameter for a tool schema, or nothing when the * project disabled worktrees (`worktreeIsolation: false`). * * Dropping the field beats accepting it and quietly downgrading. The setting is * for a project whose model passes `"worktree"` on *every* call, so a * per-result "isolation was disabled" note would be noise on every result and * would keep raising the salience of a capability that isn't there. With no * field there is nothing to pass, nothing to drop, and nothing to explain — the * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context * cost. The resolver gate and the `agent-manager` check still cover the paths a * schema can't reach: agent files, the scheduler, and cross-extension RPC. * * Like `scheduleParam`, this is read once at tool registration — flipping the * setting needs a new pi session for the schema to change. */ export function isolationParam(enabled: boolean): Partial { return enabled ? isolationParamShape : {}; } /** * The model-facing `cwd` parameter of the `Agent` tool. * * Exists because the worktree is made from the repo containing the agent's * working directory, which used to always be the session cwd: a session started * in `~` had no way to isolate an agent in `~/code/some-repo`. */ export const cwdParam = { cwd: Type.Optional( Type.String({ description: 'Working directory for the agent: absolute, "~/"-prefixed, or relative to the session cwd. Default: the session cwd. With isolation: "worktree", the worktree is created from the git repo containing this directory, the agent runs at the same subdirectory inside the copy, and the result branch lands in that repo. Pass it whenever the target repo is not the session cwd. Project config (.pi extensions, skills, settings) still loads from the session cwd.', }), ), }; /** * Resolve the `Agent` tool's `cwd` against the session cwd: `~` and `~/` * expand to the home directory, a relative path resolves against `sessionCwd`. * Blank means unset: models that fill every optional parameter send `""`. * Existence is checked later by the manager, which re-checks at start time. */ export function resolveCwdParam(cwd: string | undefined, sessionCwd: string, homeDir = homedir()): string | undefined { const trimmed = cwd?.trim(); if (!trimmed) return undefined; if (trimmed === "~") return homeDir; if (trimmed.startsWith("~/")) return resolve(homeDir, trimmed.slice(2)); return resolve(sessionCwd, trimmed); } interface AgentInvocationParams { model?: string; thinking?: string; max_turns?: number; run_in_background?: boolean; inherit_context?: boolean; isolated?: boolean; /** * Untyped on purpose. Both tool schemas now build this field conditionally * and spread it, which erases TypeBox's literal inference to `unknown` (the * `schedule` param has the same shape). The resolver below narrows by * comparison rather than trusting the declaration, which also makes it safe * for the cross-extension RPC path, where options arrive unvalidated. */ isolation?: unknown; } interface ResolveOptions { /** * Whether worktree isolation is permitted at all. False when the project set * `worktreeIsolation: false`, which drops a requested worktree rather than * failing the call: the fail-loud precedent covers spawns that *cannot* work, * while this one is the user opting out, and throwing would break exactly the * calls the `"off"` value exists to tolerate. Defaults to allowed. */ worktreeAllowed?: boolean; /** * What an unqualified spawn means — neither the call nor the agent file said. * * Top-level callers pass the `backgroundByDefault` setting (default `true`, * following Claude Code). Nested callers pass `false` unconditionally: a * detached child is killed by `abortOwnedChildren` when its parent settles * and has no notification path of its own, so backgrounding one loses its * work. Both call sites pass it explicitly; the `false` fallback only covers * a caller that supplies no options at all, which in-tree means tests. */ defaultRunInBackground?: boolean; } export function resolveAgentInvocationConfig( agentConfig: AgentConfig | undefined, params: AgentInvocationParams, opts?: ResolveOptions, ): { thinking?: ThinkingLevel; maxTurns?: number; inheritContext: boolean; runInBackground: boolean; isolated: boolean; isolation?: IsolationMode; } { // Precedence first, collapse second — reversing these loses the veto, since // an agent file's "off" only outranks a caller's "worktree" while it is still // a value. Everything downstream then sees "worktree" or nothing at all. const requested = agentConfig?.isolation ?? params.isolation; const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined; return { // A specialist's frontmatter is a reusable default, not a policy boundary: // an explicit dispatch chooses the effort for this run. Pi still clamps the // selected level to the resolved model, and agent-manager records that // requested-versus-effective difference after the session starts. thinking: (params.thinking ?? agentConfig?.thinking) as ThinkingLevel | undefined, maxTurns: agentConfig?.maxTurns ?? params.max_turns, inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false, runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false, isolated: agentConfig?.isolated ?? params.isolated ?? false, isolation, }; }