@hcflabs/pi-subagent 28.3.4 → 28.6.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.
- package/README.md +11 -3
- package/dist/index.d.ts +5 -0
- package/dist/index.js +24 -6
- package/dist/mcp-role.js +1 -1
- package/dist/prune.d.ts +2 -0
- package/docs/orchestration.md +5 -3
- package/extensions/git-read.ts +35 -6
- package/extensions/isolated.ts +134 -30
- package/extensions/repos.ts +3 -3
- package/extensions/subagent-command.ts +8 -5
- package/extensions/workflow.ts +5 -1
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -35,13 +35,13 @@ Commands, prompts, and UI are for you. Tools and the packaged skill are for Main
|
|
|
35
35
|
| `/review [target] [focus]` | prompt | Tell Main to review a change with parallel `reviewer` tasks and give one ship verdict. See [Review a change](#review-a-change). |
|
|
36
36
|
| `/subagent recover` | command | Classify interrupted isolated work in the canonical repository. Send Main request IDs, blockers, and next actions. Requires no UI or Herdr pane. |
|
|
37
37
|
| `delegate_task` | tool | Start authorized shared-checkout work or a durable isolated checked graph. With `dryRun: true`, check the request and show the resolved plan without a launch. |
|
|
38
|
-
| `subagent_repos` | tool | List the child Git repositories below the Pi working directory and the `repo` selector of each. Read-only. |
|
|
38
|
+
| `subagent_repos` | tool | List the child Git repositories below the Pi working directory and the `repo` selector of each. Mark linked worktrees and submodules. Read-only. |
|
|
39
39
|
| `subagent_status` | tool | Read saved isolated state, exact identities, failed review verdicts, and allowed continuation. Does not replay work. Supports structured output for `codemode`. |
|
|
40
40
|
| `subagent_resume` | tool | Perform the reported `retry`, `verify`, or `finalize` continuation, not staging or integration. Same-worker correction retries accept optional `instruction` text. `verify` can also adopt a later clean committed candidate from the same settled worker. That candidate must pass its normal checks and judgment. |
|
|
41
41
|
| `subagent_stage` | tool | Stage, resolve, reject, or revise an exact candidate. Rejecting a staged candidate freezes its generation. |
|
|
42
42
|
| `subagent_integrate` | tool | Advance dependents, refresh, validate, correct, promote, reconcile, clean up promotion, or release rejected and superseded resources. |
|
|
43
43
|
| `subagent_abort` | tool | Terminate an isolated request without discarding retained work. Retained candidates and integration work require release or proof of absence. |
|
|
44
|
-
| `git_read` | tool | Let Role-declared children inspect bounded local Git evidence without Bash, tests, network access, or writes. Not available to Main. |
|
|
44
|
+
| `git_read` | tool | Let Role-declared children inspect bounded local Git evidence without Bash, tests, network access, or writes. In a parent directory that is not a Git repository, the optional `repo` parameter selects a child repository. Not available to Main. |
|
|
45
45
|
| `pi-subagent` | skill | Guide Main through authorization, delegation, checks, integration, and recovery. |
|
|
46
46
|
| Direct status widget (`D`) | ui | Show direct workflows as a tree under `Main` with references, names, Role badges, status, routes, elapsed time, measured task tokens, cost, and tool activity. In fullscreen mode, a click on a working or finished worker row focuses that worker's verified Herdr pane. |
|
|
47
47
|
| Isolated status widget (`I`) | ui | Show recorded task state, Role/model-class badges, and retained workspaces in the TUI. Readiness does not mean promotion. |
|
|
@@ -108,13 +108,19 @@ When Pi runs in a parent directory that holds many repositories, set `repo` to s
|
|
|
108
108
|
|
|
109
109
|
The worker opens in the current Herdr workspace with the Repository target as its working directory. Change reports and stale-read checks use that checkout, and each result names its `repo`. A write request reserves the checkout of each target at one time, so writers in different repositories can run together. When Pi runs in a parent directory that is not a Git repository, each Main call that can write covers the whole parent. Such a call waits while a direct writer owns the checkout of any Repository target in it. Main can still read files and use `subagent_repos`.
|
|
110
110
|
|
|
111
|
+
A worker that uses `repo` starts in the Repository target, so `git_read` needs no `repo`. A worker that starts in a parent directory that is not a Git repository must pass `repo` to `git_read`, with the same selector rules. Without `repo`, `git_read` fails with a message that names `repo`.
|
|
112
|
+
|
|
111
113
|
A `herdr_command` job with write access blocks direct writers in its checkout until `stop` proves that the job ended.
|
|
112
114
|
|
|
113
115
|
An isolated request accepts one `repo` for the whole graph. Tasks cannot select another repository. The request then uses the Repository target as its checkout. State, worker worktrees, validation, and promotion belong to that repository. The Pi working directory does not change.
|
|
114
116
|
|
|
115
117
|
Your Herdr workspace can belong to another checkout or to none. Herdr opens the primary workspace of the target when it opens the first worker worktree, and it does not close that workspace later. Pass the same `repo` to `subagent_status`, `subagent_resume`, `subagent_stage`, `subagent_integrate`, and `subagent_abort`.
|
|
116
118
|
|
|
117
|
-
Run `/subagent` in a parent directory that is not a Git repository. It lists the isolated requests of each Repository target below it, with their `repo`. `/subagent recover` recovers each Repository target that has saved requests. `/subagent prune`
|
|
119
|
+
Run `/subagent` in a parent directory that is not a Git repository. It lists the isolated requests of each Repository target below it, with their `repo`. `/subagent recover` recovers each Repository target that has saved requests. `/subagent prune` reviews the leftovers of each Repository target and prefixes each item with its `repo`.
|
|
120
|
+
|
|
121
|
+
The same commands work in a plain subdirectory of a Git repository. They then read the repository that contains the directory, and also each Repository target below the directory. Items of the outer repository have no `repo`. At the top level of a repository, the commands read only that repository.
|
|
122
|
+
|
|
123
|
+
Discovery searches 3 directory levels. It also lists repositories inside repositories, such as submodules. When a directory at the depth limit has child directories, or another limit stops the search, `subagent_repos` and these commands show a warning. A warning means that some repositories were not examined.
|
|
118
124
|
|
|
119
125
|
To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`. This opens a new tab with the saved conversation and a new reference. Continue the newest reference from the original checkout and workspace. For a worker that ran with `repo`, select the same `repo`. For eligibility and stop behavior, see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker).
|
|
120
126
|
|
|
@@ -269,6 +275,8 @@ Role Markdown files in `~/.pi/agent/config/pi-subagent/` require frontmatter and
|
|
|
269
275
|
| `mcps` | Optional exact global server names from `~/.pi/agent/mcp.json`, using native `mcpServers` format. Omitted or `[]` denies access to `mcp.json` servers. Servers that Role extensions register always connect. |
|
|
270
276
|
| body | Required system instructions |
|
|
271
277
|
|
|
278
|
+
A Role's `modelClass` selects a Task Profile. When the profile has a primary and a fallback that resolve in Main, the worker selects the Task Profile Model `task/<profile>`. A retryable error on the primary then moves the worker to the fallback. The launch record names the primary route. A designated `model` uses no fallback.
|
|
279
|
+
|
|
272
280
|
The package ships `implementer`, `reviewer`, and `scout`; same-name user Roles override built-ins. Roles define capabilities, not access or isolation. Unknown frontmatter keys invalidate that file and report its path and key. Other valid Roles load; duplicate names become unavailable. Delegation to an invalid file's claimed Role fails with that file's error. Inspect `/subagent roles`.
|
|
273
281
|
|
|
274
282
|
The built-in reviewer answers exactly `PASS` when it finds no actionable correctness risk. Otherwise, each finding starts with a priority and a confidence (`high`, `medium`, or `low`), for example `[P1] confidence: high`. Then it gives file and line evidence, the trigger, the impact, and the smallest fix. Each finding blocks approval.
|
package/dist/index.d.ts
CHANGED
|
@@ -73,6 +73,11 @@ export interface PreparedRoleLaunch extends ResolvedRoleLaunch {
|
|
|
73
73
|
export interface CreateRoleLaunchInput {
|
|
74
74
|
role: Role;
|
|
75
75
|
route: ResolvedTaskRoute;
|
|
76
|
+
/**
|
|
77
|
+
* Task Profile of the route. When set, the child selects the Task Profile Model `task/<profile>`,
|
|
78
|
+
* so a retryable error on the primary route moves the child to the fallback route.
|
|
79
|
+
*/
|
|
80
|
+
failoverProfile?: ProfileName;
|
|
76
81
|
extensions?: readonly string[];
|
|
77
82
|
tools?: readonly string[];
|
|
78
83
|
env?: Readonly<Record<string, string>>;
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { createConfigStore, extensionConfigDir, field, formatConfigIssues, parse
|
|
|
6
6
|
import { hasDisplayControlCharacters } from "./display-text.js";
|
|
7
7
|
import { DEFAULT_MAX_TURNS } from "./ephemeral.js";
|
|
8
8
|
import { loadRoleMcpConfig, parseRoleMcpAllowlist } from "./mcp-role.js";
|
|
9
|
-
import { loadTaskModelsConfig, modelReference, orderedProfileRoutes, PROFILE_NAMES, resolveConfiguredTaskRoute, resolveTaskModelRoute, } from "@hcflabs/pi-task-models";
|
|
9
|
+
import { loadTaskModelsConfig, modelReference, orderedProfileRoutes, PROFILE_NAMES, resolveConfiguredTaskRoute, resolveTaskModelRoute, TASK_PROFILE_MODELS_EXTENSION, taskProfileModelReference, } from "@hcflabs/pi-task-models";
|
|
10
10
|
export { DISPLAY_TEXT_CONTRACT, hasDisplayControlCharacters } from "./display-text.js";
|
|
11
11
|
export { loadRoleMcpConfig, parseRoleMcpAllowlist } from "./mcp-role.js";
|
|
12
12
|
export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, DEFAULT_MAX_TURNS, EphemeralSubagentError, EXECUTION_BUDGET_ENV, formatDuration, } from "./ephemeral.js";
|
|
@@ -450,6 +450,14 @@ function resolveConfiguredRoute(ctx, profileName, profile) {
|
|
|
450
450
|
}
|
|
451
451
|
throw new Error(`No usable ${profileName} task model route. Run /task-models.`);
|
|
452
452
|
}
|
|
453
|
+
/** Return the profile when it has a primary and a fallback route that resolve in this session, so failover can help. */
|
|
454
|
+
function failoverProfile(ctx, profileName, agentDir = getAgentDir()) {
|
|
455
|
+
const profile = loadTaskModelsConfig(agentDir).value.profiles[profileName];
|
|
456
|
+
if (!profile)
|
|
457
|
+
return undefined;
|
|
458
|
+
const usable = orderedProfileRoutes(profile).filter((route) => resolveTaskModelRoute(ctx, route) !== undefined);
|
|
459
|
+
return usable.length > 1 ? profileName : undefined;
|
|
460
|
+
}
|
|
453
461
|
export function resolveRoleSkills(pi, role) {
|
|
454
462
|
const skills = new Map(pi.getCommands()
|
|
455
463
|
.filter((command) => command.source === "skill")
|
|
@@ -512,6 +520,8 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
|
|
|
512
520
|
ROLE_MCP_EXTENSION,
|
|
513
521
|
...(role.tools.includes("git_read") ? [GIT_READ_EXTENSION] : []),
|
|
514
522
|
ROLE_TOOLS_EXTENSION,
|
|
523
|
+
// The child runs with --no-extensions, so it loads the Task Profile Models only from this path.
|
|
524
|
+
...(input.failoverProfile ? [TASK_PROFILE_MODELS_EXTENSION] : []),
|
|
515
525
|
];
|
|
516
526
|
const env = Object.fromEntries(Object.entries(input.env ?? {}).map(([key, value]) => {
|
|
517
527
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
|
|
@@ -527,7 +537,7 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
|
|
|
527
537
|
for (const skill of skills.paths)
|
|
528
538
|
args.push("--skill", skill);
|
|
529
539
|
args.push(`--${ROLE_TOOL_POLICY_FLAG}`, JSON.stringify(tools));
|
|
530
|
-
args.push("--model", modelReference(input.route.model));
|
|
540
|
+
args.push("--model", input.failoverProfile ? taskProfileModelReference(input.failoverProfile) : modelReference(input.route.model));
|
|
531
541
|
if (input.route.thinkingLevel)
|
|
532
542
|
args.push("--thinking", input.route.thinkingLevel);
|
|
533
543
|
args.push(ctx.isProjectTrusted() ? "--approve" : "--no-approve");
|
|
@@ -546,11 +556,16 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
|
|
|
546
556
|
function prepareResolvedRoleLaunch(pi, ctx, input) {
|
|
547
557
|
const { task, modelClass, agentDir, ...launchInput } = input;
|
|
548
558
|
const selectedClass = modelClass ?? input.role.modelClass;
|
|
559
|
+
const route = selectedClass === undefined
|
|
560
|
+
? resolveConfiguredTaskRoute(ctx, task, agentDir)
|
|
561
|
+
: resolveTaskRoute(ctx, selectedClass, agentDir);
|
|
562
|
+
// The route resolved, so the config loads. A task without a class uses its assigned or declared profile.
|
|
563
|
+
const profileName = selectedClass ?? loadTaskModelsConfig(agentDir).value.tasks[task.id] ?? task.defaultProfile;
|
|
564
|
+
const failover = failoverProfile(ctx, profileName, agentDir);
|
|
549
565
|
return prepareRoleLaunchFromSkills(ctx, {
|
|
550
566
|
...launchInput,
|
|
551
|
-
route
|
|
552
|
-
|
|
553
|
-
: resolveTaskRoute(ctx, selectedClass, agentDir),
|
|
567
|
+
route,
|
|
568
|
+
...(failover ? { failoverProfile: failover } : {}),
|
|
554
569
|
}, resolveRoleSkills(pi, input.role));
|
|
555
570
|
}
|
|
556
571
|
export function resolveRoleLaunch(pi, ctx, input) {
|
|
@@ -589,9 +604,12 @@ export async function resolveConfiguredRoleLaunch(pi, ctx, input) {
|
|
|
589
604
|
...namedSkills,
|
|
590
605
|
paths: [...new Set([...namedSkills.paths, ...resources.skills])],
|
|
591
606
|
};
|
|
607
|
+
const route = resolveTaskRoute(ctx, input.modelClass);
|
|
608
|
+
const failover = failoverProfile(ctx, input.modelClass);
|
|
592
609
|
const prepared = prepareRoleLaunchFromSkills(ctx, {
|
|
593
610
|
role: effectiveRole,
|
|
594
|
-
route
|
|
611
|
+
route,
|
|
612
|
+
...(failover ? { failoverProfile: failover } : {}),
|
|
595
613
|
}, skills);
|
|
596
614
|
assertNoMissingRoleSkills(effectiveRole, prepared);
|
|
597
615
|
const args = [
|
package/dist/mcp-role.js
CHANGED
|
@@ -62,7 +62,7 @@ const HTTP_CHECKS = {
|
|
|
62
62
|
}, "an http URL on localhost, 127.0.0.1, or [::1] without query or fragment, on the \"oauth.callbackPort\" port"],
|
|
63
63
|
"oauth.scope": [isString, "a string"],
|
|
64
64
|
"oauth.clientName": [(value) => typeof value === "string" && value.trim() !== "", "a non-empty string"],
|
|
65
|
-
"oauth.clientRegistration": [(value) => value === "dcr" || value === "cimd", '"dcr" or "cimd"'],
|
|
65
|
+
"oauth.clientRegistration": [(value) => value === "auto" || value === "dcr" || value === "cimd", '"auto", "dcr", or "cimd"'],
|
|
66
66
|
"oauth.authServerMetadataUrl": [(value) => isHttpsOrLoopback(parseUrl(value)), "an https URL, or http on localhost, 127.0.0.1, or [::1]"],
|
|
67
67
|
auth: [(value) => isRecord(value) && typeof value.provider === "string" && value.provider !== "", "an object with a non-empty \"provider\" string"],
|
|
68
68
|
};
|
package/dist/prune.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export interface PruneRequest {
|
|
|
17
17
|
}
|
|
18
18
|
/** One reviewed pi-subagent branch, with its registered checkout when one exists. */
|
|
19
19
|
export interface PruneItem {
|
|
20
|
+
/** The Repository target selector, when /subagent prune runs in a parent directory of repositories. */
|
|
21
|
+
repo?: string;
|
|
20
22
|
branch: string;
|
|
21
23
|
tip: string;
|
|
22
24
|
path?: string;
|
package/docs/orchestration.md
CHANGED
|
@@ -444,7 +444,7 @@ The report lists removed, skipped, and failed resources. After complete cleanup,
|
|
|
444
444
|
|
|
445
445
|
### Prune leftover worktrees
|
|
446
446
|
|
|
447
|
-
Run `/subagent prune` to clean up leftover worker and integration checkouts under `.worktrees/`. Their branches have the name `pi-subagent/subagent-<name>-<24hex>`, or the saved legacy name `pi-subagent/subagent-<24hex>`. The command also cleans up such branches that have no checkout. The review starts with the number of removable and blocked items. It groups the items by the exact reason that the command can remove them, or by their exact blockers, and shows each reason once. Under each reason, it shows the readable name, if present, and the first 8 characters of the identity suffix. The command can remove an item only when all of these conditions are true:
|
|
447
|
+
Run `/subagent prune` to clean up leftover worker and integration checkouts under `.worktrees/`. Their branches have the name `pi-subagent/subagent-<name>-<24hex>`, or the saved legacy name `pi-subagent/subagent-<24hex>`. The command also cleans up such branches that have no checkout. The review starts with the number of removable and blocked items. It groups the items by the exact reason that the command can remove them, or by their exact blockers, and shows each reason once. Under each reason, it shows the readable name, if present, and the first 8 characters of the identity suffix. In a parent directory that is not a Git repository, the command reviews each Repository target below it. In a plain subdirectory of a Git repository, it reviews the outer repository and each Repository target below the subdirectory. Each item of a Repository target then starts with its `repo`, and Main HEAD is the HEAD of that repository. The review shows a warning when discovery did not examine all directories. The command can remove an item only when all of these conditions are true:
|
|
448
448
|
|
|
449
449
|
- Its branch tip is already in Main's HEAD or in the local `origin` default-branch ref. The command does not fetch.
|
|
450
450
|
- Its checkout has no tracked or untracked changes. No merge, rebase, cherry-pick, revert, or bisect is in progress.
|
|
@@ -518,7 +518,7 @@ Before launch, the extension checks each selected entry against Pi's documented
|
|
|
518
518
|
- `auth.provider` uses plain HTTP outside `localhost`, `127.0.0.1`, or `[::1]`.
|
|
519
519
|
- `oauth.authServerMetadataUrl` does not use HTTPS outside those hosts.
|
|
520
520
|
|
|
521
|
-
The extension never modifies the file. Fix the entry or choose another server. The extension passes valid `auth`, `oauth`, and `description` fields through, so Pi's native provider auth and OAuth apply. `oauth.clientRegistration` must be `dcr
|
|
521
|
+
The extension never modifies the file. Fix the entry or choose another server. The extension passes valid `auth`, `oauth`, and `description` fields through, so Pi's native provider auth and OAuth apply. `oauth.clientRegistration` must be `auto`, `dcr`, or `cimd`. A `cimd` entry cannot use `clientId` or `clientName`. Any `callbackUrl` must use localhost or 127.0.0.1 with path `/callback`.
|
|
522
522
|
|
|
523
523
|
The extension still ignores project MCP overrides. A project cannot change the global server allowlist or exposure of the Role. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work starts. The extension excludes Main-only delegation, integration, and recovery tools, `herdr_handoff`, `herdr_command`, and `ask_question` from children.
|
|
524
524
|
|
|
@@ -537,7 +537,9 @@ Isolated Herdr Role launches receive the same turn, token, and child-runtime bud
|
|
|
537
537
|
| `blame` | Required `path`, optional `revision` and paired `startLine`/`endLine` |
|
|
538
538
|
| `rev-parse` | Optional `revision`; resolves one commit ID |
|
|
539
539
|
|
|
540
|
-
|
|
540
|
+
Every operation accepts the optional `repo` parameter. Use it when the assigned cwd is a parent directory that is not a Git repository. `repo` is a child Git repository as a path relative to the assigned cwd, such as `team/service`. It follows the same rules as the `delegate_task` `repo` parameter: the path must stay inside cwd after symlink resolution and must be a Git top-level directory. If `repo` is omitted and cwd is not a Git repository, the call fails with a message that names `repo`. Main lists the targets with `subagent_repos`.
|
|
541
|
+
|
|
542
|
+
Revisions accept commit IDs or named refs with optional `~N`/`^N` ancestry, not ranges or reflog expressions. Paths are literal. They are relative to the selected `repo`, or to the assigned cwd if `repo` is omitted. The tool rejects absolute paths, traversal, `.git` components, and paths that look like options.
|
|
541
543
|
|
|
542
544
|
Use named candidate refs. Do not assume that Main's checkout contains an isolated candidate. In isolated judgment, the supplied exact patch stays authoritative. Git inspection supplies only referenced context, not a replacement diff. Reviewers still cannot run tests, write, commit, or push. They approve only with exact `PASS`.
|
|
543
545
|
|
package/extensions/git-read.ts
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
2
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
2
|
import { spawnBounded } from "@hcflabs/pi-process";
|
|
3
|
+
import { gitTopLevel, resolveRepoTarget } from "@hcflabs/pi-repo";
|
|
4
4
|
import { ROLE_TOOL_POLICY_FLAG, roleToolPolicyFromArgv } from "@hcflabs/pi-subagent";
|
|
5
5
|
import { Type, type Static } from "typebox";
|
|
6
6
|
import { Check } from "typebox/value";
|
|
7
7
|
|
|
8
|
+
// pi-ai StringEnum returns a pi-schema type, so TypeBox Static cannot infer it.
|
|
9
|
+
function StringEnum<const T extends readonly string[]>(values: T, options: { description?: string } = {}) {
|
|
10
|
+
return Type.Unsafe<T[number]>({ type: "string", enum: [...values], ...options });
|
|
11
|
+
}
|
|
12
|
+
|
|
8
13
|
const OUTPUT_BYTES = 32 * 1024;
|
|
9
14
|
const TIMEOUT_MS = 30_000;
|
|
10
15
|
const Parameters = Type.Object({
|
|
11
16
|
operation: StringEnum(["status", "diff", "show", "log", "blame", "rev-parse"]),
|
|
12
17
|
mode: Type.Optional(StringEnum(["working", "staged", "committed"], { description: "Diff only; defaults to working (unstaged). Committed requires base and tip." })),
|
|
18
|
+
repo: Type.Optional(Type.String({ minLength: 1, description: "Child Git repository as a path relative to the assigned cwd, such as team/service. Required when cwd is not a Git repository. Same rules as the delegate_task repo. Omit it to use cwd." })),
|
|
13
19
|
base: Type.Optional(Type.String()),
|
|
14
20
|
tip: Type.Optional(Type.String()),
|
|
15
21
|
revision: Type.Optional(Type.String({ description: "Commit ID or named ref with optional ~N/^N ancestry; defaults to HEAD. No ranges or reflog expressions." })),
|
|
16
|
-
path: Type.Optional(Type.String({ description: "One literal path relative to the assigned cwd; no absolute paths, traversal, or .git paths." })),
|
|
22
|
+
path: Type.Optional(Type.String({ description: "One literal path relative to the selected repo, or to the assigned cwd if repo is omitted; no absolute paths, traversal, or .git paths." })),
|
|
17
23
|
maxCount: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Log only; defaults to 20." })),
|
|
18
24
|
startLine: Type.Optional(Type.Integer({ minimum: 1, maximum: 1_000_000, description: "Blame only; supply both line bounds." })),
|
|
19
25
|
endLine: Type.Optional(Type.Integer({ minimum: 1, maximum: 1_000_000 })),
|
|
@@ -24,8 +30,8 @@ const Result = Type.Object({ output: Type.String(), stderr: Type.String(), trunc
|
|
|
24
30
|
function parse(input: unknown): Params {
|
|
25
31
|
if (!Check(Parameters, input)) throw new Error("git_read requires a supported operation and valid structured parameters; arbitrary Git options are not accepted.");
|
|
26
32
|
const allowed: Record<Params["operation"], string[]> = {
|
|
27
|
-
status: ["path"], diff: ["mode", "base", "tip", "path"], show: ["revision", "path"],
|
|
28
|
-
log: ["revision", "path", "maxCount"], blame: ["revision", "path", "startLine", "endLine"], "rev-parse": ["revision"],
|
|
33
|
+
status: ["repo", "path"], diff: ["repo", "mode", "base", "tip", "path"], show: ["repo", "revision", "path"],
|
|
34
|
+
log: ["repo", "revision", "path", "maxCount"], blame: ["repo", "revision", "path", "startLine", "endLine"], "rev-parse": ["repo", "revision"],
|
|
29
35
|
};
|
|
30
36
|
for (const key of Object.keys(input)) {
|
|
31
37
|
if (key !== "operation" && !allowed[input.operation].includes(key)) throw new Error(`git_read ${input.operation} does not accept ${key}.`);
|
|
@@ -107,16 +113,39 @@ async function inspect(params: Params, cwd: string, signal?: AbortSignal): Promi
|
|
|
107
113
|
return { output: result.stdout, stderr: result.stderr, truncated: result.stdoutTruncated === true };
|
|
108
114
|
}
|
|
109
115
|
|
|
116
|
+
/** Run the operation in the selected repository root. Without repo, run in cwd and name repo if cwd is not a repository. */
|
|
117
|
+
async function inspectIn(params: Params, cwd: string, signal?: AbortSignal): Promise<Static<typeof Result>> {
|
|
118
|
+
if (params.repo !== undefined) {
|
|
119
|
+
let root: string;
|
|
120
|
+
try {
|
|
121
|
+
root = (await resolveRepoTarget(cwd, params.repo, signal ? { signal } : {})).root;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw new Error(`git_read ${params.operation} repo ${params.repo}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
124
|
+
}
|
|
125
|
+
return await inspect(params, root, signal);
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
return await inspect(params, cwd, signal);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
// Git exit 128 is not specific to a missing repository. Ask pi-repo, which does not read Git messages.
|
|
131
|
+
const outside = signal?.aborted ? false : await gitTopLevel(cwd, signal ? { signal } : {}).then((root) => root === undefined, () => false);
|
|
132
|
+
if (outside) {
|
|
133
|
+
throw new Error(`git_read ${params.operation}: ${cwd} is not a Git repository. Set the repo parameter to a child Git repository, as a path relative to cwd, such as team/service.`, { cause: error });
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
110
139
|
export default function gitRead(pi: ExtensionAPI): void {
|
|
111
140
|
// Like the MCP adapter, inspect argv because Pi binds extension flags after factories load.
|
|
112
141
|
if (!process.argv.includes(`--${ROLE_TOOL_POLICY_FLAG}`) || !roleToolPolicyFromArgv(process.argv).includes("git_read")) return;
|
|
113
142
|
pi.registerTool({
|
|
114
143
|
name: "git_read", label: "Git read",
|
|
115
|
-
description: "
|
|
144
|
+
description: "Read bounded local Git evidence: status, working or staged diff, base-to-tip diff, show of a commit or file, log, blame, and rev-parse of a commit. The operations are fixed and read-only. The tool accepts no shell, no options, no network, no tests, and no changes. If cwd is not a Git repository, set repo to a child Git repository, as a path relative to cwd. Paths are relative to the selected repo, or to cwd if repo is omitted. The tool keeps at most the last 32 KiB of output. If the output is truncated, narrow the path, ref, or line scope. Each call has a 30-second timeout.",
|
|
116
145
|
parameters: Parameters,
|
|
117
146
|
outputSchema: Result,
|
|
118
147
|
async execute(_id, input, signal, _update, ctx) {
|
|
119
|
-
const result = await
|
|
148
|
+
const result = await inspectIn(parse(input), ctx.cwd, signal);
|
|
120
149
|
return {
|
|
121
150
|
content: [{ type: "text", text: `${result.truncated ? "[TRUNCATED: only the last 32768 bytes follow; narrow the request.]\n" : ""}${result.output}${result.stderr ? `\nGit diagnostic: ${result.stderr}` : ""}` }],
|
|
122
151
|
structuredContent: result, details: result,
|
package/extensions/isolated.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { lstat } from "node:fs/promises";
|
|
1
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
2
2
|
import { basename, relative, sep } from "node:path";
|
|
3
3
|
import type { JsonValue } from "@earendil-works/pi-ai";
|
|
4
4
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -905,13 +905,27 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
905
905
|
};
|
|
906
906
|
/** Report lines for discovery issues and truncation, because an incomplete search cannot prove absence. */
|
|
907
907
|
const discoveryWarnings = (found: RepoDiscovery): string[] => [
|
|
908
|
-
...(found.truncated ? [`Repository discovery below ${found.base} stopped at a limit; some repositories were not examined.`] : []),
|
|
908
|
+
...(found.truncated ? [`Repository discovery below ${found.base} stopped at a limit (depth, directory count, repository count, or time); some repositories were not examined.`] : []),
|
|
909
909
|
...found.issues.slice(0, 20).map(({ path, reason }) => `Repository discovery could not examine ${path}: ${boundedPublicText(reason)}`),
|
|
910
910
|
...(found.issues.length > 20 ? [`${found.issues.length - 20} more repository discovery issues omitted.`] : []),
|
|
911
911
|
];
|
|
912
|
-
/**
|
|
913
|
-
|
|
914
|
-
|
|
912
|
+
/**
|
|
913
|
+
* Repository targets below `cwd`, when `cwd` is a plain directory inside an outer repository.
|
|
914
|
+
* At the top level of a repository, discovery does not run. A failure becomes a warning and does not stop the outer repository.
|
|
915
|
+
*/
|
|
916
|
+
const nestedDiscovery = async (cwd: string): Promise<{ found?: RepoDiscovery; warnings: string[] }> => {
|
|
917
|
+
try {
|
|
918
|
+
const top = await gitTopLevel(cwd);
|
|
919
|
+
if (top === undefined || top === await realpath(cwd)) return { warnings: [] };
|
|
920
|
+
return { found: await discoverRepos(cwd), warnings: [] };
|
|
921
|
+
} catch (error) {
|
|
922
|
+
// A missing directory has nothing to discover.
|
|
923
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ENOTDIR") return { warnings: [] };
|
|
924
|
+
return { warnings: [`Repository discovery below ${cwd} failed: ${boundedPublicText(error instanceof Error ? error.message : String(error))}`] };
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
/** Read-only inventory of the discovered Repository targets. Each request names its repo and a live checkout. */
|
|
928
|
+
const childRequests = async (found: RepoDiscovery, current: () => boolean): Promise<{ requests: IsolatedRequest[]; invalidIds: string[]; warnings: string[] }> => {
|
|
915
929
|
const requests: IsolatedRequest[] = [];
|
|
916
930
|
const invalidIds: string[] = [];
|
|
917
931
|
const selectorOf = (root: string) => found.repos.find((item) => item.root === root)?.repo
|
|
@@ -940,9 +954,41 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
940
954
|
requests.push({ ...request, repo: selectorOf(primary), leaseLive: false, checkout: primary });
|
|
941
955
|
}
|
|
942
956
|
invalidIds.push(...orphans.invalidIds);
|
|
957
|
+
return { requests, invalidIds, warnings };
|
|
958
|
+
};
|
|
959
|
+
/** Read-only inventory across the Repository targets below a parent directory that is not a Git repository. */
|
|
960
|
+
const childInventory = async (cwd: string, current: () => boolean = () => true): Promise<IsolatedInventory> => {
|
|
961
|
+
const found = await discoverRepos(cwd);
|
|
962
|
+
const { requests, invalidIds, warnings } = await childRequests(found, current);
|
|
943
963
|
return { root: found.base, leaseLive: requests.some((request) => request.leaseLive), requests,
|
|
944
964
|
invalidIds: [...new Set(invalidIds)], warnings };
|
|
945
965
|
};
|
|
966
|
+
/** Recovery lines for each discovered Repository target that has saved requests. */
|
|
967
|
+
const childRecoveryLines = async (found: RepoDiscovery): Promise<string[]> => {
|
|
968
|
+
const lines: string[] = [];
|
|
969
|
+
for (const { repo, root: child } of found.repos) {
|
|
970
|
+
const listed = await getComponents().runner.listRequests(child).catch(async (error: unknown) => {
|
|
971
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT" && await lstat(child).then(() => false, () => true)) return { requests: [], invalidIds: [] };
|
|
972
|
+
throw error;
|
|
973
|
+
});
|
|
974
|
+
if (!listed.requests.length && !listed.invalidIds.length) continue;
|
|
975
|
+
lines.push(`repo ${repo}:`, ...await recoveryLines(child));
|
|
976
|
+
}
|
|
977
|
+
return lines;
|
|
978
|
+
};
|
|
979
|
+
/** Review items of each discovered Repository target. One unreadable repository adds a warning and does not stop the others. */
|
|
980
|
+
const childPruneItems = async (found: RepoDiscovery): Promise<{ items: PruneItem[]; warnings: string[] }> => {
|
|
981
|
+
const items: PruneItem[] = [];
|
|
982
|
+
const warnings = discoveryWarnings(found);
|
|
983
|
+
for (const { repo, root: child } of found.repos) {
|
|
984
|
+
try {
|
|
985
|
+
for (const item of await inspectPruneCandidates(child, child, pruneGuards(child))) items.push({ ...item, repo });
|
|
986
|
+
} catch (failure) {
|
|
987
|
+
warnings.push(`Prune review could not read repo ${repo}: ${boundedPublicText(failure instanceof Error ? failure.message : String(failure))}`);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return { items, warnings };
|
|
991
|
+
};
|
|
946
992
|
return {
|
|
947
993
|
async inventory(cwd, current) {
|
|
948
994
|
let root: string;
|
|
@@ -967,7 +1013,28 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
967
1013
|
}
|
|
968
1014
|
const orphans = await getComponents().runner.listOrphanRequests(root);
|
|
969
1015
|
const leaseLive = await getComponents().runner.hasProductiveRunLease(root);
|
|
970
|
-
|
|
1016
|
+
const own = { root, leaseLive, requests: [...requests, ...orphans.requests], invalidIds: [...new Set([...invalidIds, ...orphans.invalidIds])] };
|
|
1017
|
+
// In a plain directory inside an outer repository, also list the Repository targets below cwd.
|
|
1018
|
+
const { found, warnings } = await nestedDiscovery(cwd);
|
|
1019
|
+
if (!found && !warnings.length) return own;
|
|
1020
|
+
let children: Awaited<ReturnType<typeof childRequests>> | undefined;
|
|
1021
|
+
if (found) {
|
|
1022
|
+
try {
|
|
1023
|
+
children = await childRequests(found, current ?? (() => true));
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
if (current?.() === false) throw error;
|
|
1026
|
+
warnings.push(`Isolated inventory could not read the repositories below ${found.base}: ${boundedPublicText(error instanceof Error ? error.message : String(error))}`);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return {
|
|
1030
|
+
root,
|
|
1031
|
+
leaseLive: leaseLive || (children?.requests.some((request) => request.leaseLive) ?? false),
|
|
1032
|
+
// The inventory has several roots, so each request keeps the lease state of its own root.
|
|
1033
|
+
requests: [...own.requests.map((request) => ({ ...request, leaseLive })), ...children?.requests ?? []],
|
|
1034
|
+
invalidIds: [...new Set([...own.invalidIds, ...children?.invalidIds ?? []])],
|
|
1035
|
+
// The child warnings already hold the discovery warnings. A failed child read keeps them here.
|
|
1036
|
+
warnings: [...warnings, ...children?.warnings ?? (found ? discoveryWarnings(found) : [])],
|
|
1037
|
+
};
|
|
971
1038
|
},
|
|
972
1039
|
async recover(cwd) {
|
|
973
1040
|
let root: string;
|
|
@@ -977,15 +1044,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
977
1044
|
if (await gitTopLevel(cwd).then((top) => top !== undefined, () => true)) throw error;
|
|
978
1045
|
// Outside a Git repository, recover each Repository target that has saved requests.
|
|
979
1046
|
const found = await discoverRepos(cwd);
|
|
980
|
-
const lines
|
|
981
|
-
for (const { repo, root: child } of found.repos) {
|
|
982
|
-
const listed = await getComponents().runner.listRequests(child).catch(async (error: unknown) => {
|
|
983
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT" && await lstat(child).then(() => false, () => true)) return { requests: [], invalidIds: [] };
|
|
984
|
-
throw error;
|
|
985
|
-
});
|
|
986
|
-
if (!listed.requests.length && !listed.invalidIds.length) continue;
|
|
987
|
-
lines.push(`repo ${repo}:`, ...await recoveryLines(child));
|
|
988
|
-
}
|
|
1047
|
+
const lines = await childRecoveryLines(found);
|
|
989
1048
|
const warnings = discoveryWarnings(found);
|
|
990
1049
|
// An incomplete discovery is not proof that no request exists.
|
|
991
1050
|
if (!lines.length) lines.push(warnings.length ? `No isolated requests in the ${found.repos.length} repositories that discovery examined below ${found.base}.`
|
|
@@ -993,7 +1052,18 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
993
1052
|
lines.push(...warnings);
|
|
994
1053
|
return boundedReport(lines, "recovery report lines omitted; use subagent_status for exact request evidence.");
|
|
995
1054
|
}
|
|
996
|
-
|
|
1055
|
+
const lines = await recoveryLines(root);
|
|
1056
|
+
// In a plain directory inside an outer repository, also recover the Repository targets below cwd.
|
|
1057
|
+
const { found, warnings } = await nestedDiscovery(cwd);
|
|
1058
|
+
if (found) {
|
|
1059
|
+
try {
|
|
1060
|
+
lines.push(...await childRecoveryLines(found));
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
warnings.push(`Recovery could not read the repositories below ${found.base}: ${boundedPublicText(error instanceof Error ? error.message : String(error))}`);
|
|
1063
|
+
}
|
|
1064
|
+
warnings.push(...discoveryWarnings(found));
|
|
1065
|
+
}
|
|
1066
|
+
return boundedReport([...lines, ...warnings], "recovery report lines omitted; use subagent_status for exact request evidence.");
|
|
997
1067
|
},
|
|
998
1068
|
async discardPlan(cwd, request) {
|
|
999
1069
|
// A request listed from a parent directory runs Git in a live checkout of its own repository.
|
|
@@ -1019,23 +1089,57 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
1019
1089
|
], "removal report lines omitted; reopen /subagent to inspect retained resources.") };
|
|
1020
1090
|
},
|
|
1021
1091
|
async prunePlan(cwd) {
|
|
1022
|
-
|
|
1023
|
-
|
|
1092
|
+
let root: string;
|
|
1093
|
+
try {
|
|
1094
|
+
root = await lookupRoot(cwd);
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
// Outside a Git repository, review each Repository target below cwd. Any other failure stays a failure.
|
|
1097
|
+
if (await gitTopLevel(cwd).then((top) => top !== undefined, () => true)) throw error;
|
|
1098
|
+
const found = await discoverRepos(cwd);
|
|
1099
|
+
return { root: found.base, ...await childPruneItems(found) };
|
|
1100
|
+
}
|
|
1101
|
+
const items = await inspectPruneCandidates(root, cwd, pruneGuards(root));
|
|
1102
|
+
// In a plain directory inside an outer repository, also review the Repository targets below cwd.
|
|
1103
|
+
const { found, warnings } = await nestedDiscovery(cwd);
|
|
1104
|
+
if (!found) return warnings.length ? { root, items, warnings } : { root, items };
|
|
1105
|
+
const children = await childPruneItems(found);
|
|
1106
|
+
return { root, items: [...items, ...children.items], warnings: [...warnings, ...children.warnings] };
|
|
1024
1107
|
},
|
|
1025
1108
|
async prune(cwd, items, allowIgnored, force, current) {
|
|
1026
1109
|
requireCurrent(current);
|
|
1027
|
-
|
|
1028
|
-
const
|
|
1029
|
-
|
|
1030
|
-
const
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
const
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1110
|
+
// Items reviewed in a parent directory carry their Repository target. Group them so each repository is checked again.
|
|
1111
|
+
const groups = new Map<string | undefined, PruneItem[]>();
|
|
1112
|
+
for (const item of items) groups.set(item.repo, [...groups.get(item.repo) ?? [], item]);
|
|
1113
|
+
const lines: string[] = [];
|
|
1114
|
+
let failed = 0;
|
|
1115
|
+
let skipped = 0;
|
|
1116
|
+
for (const [repo, group] of groups) {
|
|
1117
|
+
requireCurrent(current);
|
|
1118
|
+
let root: string;
|
|
1119
|
+
try {
|
|
1120
|
+
root = await lookupRoot(cwd, undefined, repo);
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
// One unreadable Repository target keeps its items and does not stop the other targets.
|
|
1123
|
+
failed += group.length;
|
|
1124
|
+
lines.push(`failed: repo ${repo}: ${group.length} item(s) kept: ${boundedPublicText(error instanceof Error ? error.message : String(error))}`);
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
const mainCwd = repo === undefined ? cwd : root;
|
|
1128
|
+
const { removals, checkouts } = await removePruneCandidates(root, mainCwd, group, allowIgnored, force,
|
|
1129
|
+
{ ...pruneGuards(root), current: () => current() && !sessionClosed });
|
|
1130
|
+
const removed = removals.filter(({ outcome }) => outcome === "removed");
|
|
1131
|
+
const reconciled = removed.length
|
|
1132
|
+
? await getComponents().runner.reconcilePrunedAborts(checkouts, removed.map(({ item }) => basename(item.branch))) : [];
|
|
1133
|
+
const count = (outcome: string) => removals.filter((item) => item.outcome === outcome).length;
|
|
1134
|
+
failed += count("failed");
|
|
1135
|
+
skipped += count("skipped");
|
|
1136
|
+
lines.push(
|
|
1137
|
+
`Pi Subagent prune in ${root}: ${removed.length} removed, ${count("skipped")} skipped, ${count("failed")} failed.`,
|
|
1138
|
+
...removals.map(({ outcome, item, reason }) => `${outcome}: ${item.path ?? "(no checkout)"} · ${item.branch} · ${reason}`),
|
|
1139
|
+
...reconciled,
|
|
1140
|
+
);
|
|
1141
|
+
}
|
|
1142
|
+
return { failed, skipped, text: boundedReport(lines.length ? lines : ["Pi Subagent prune: nothing selected."], "prune report lines omitted.") };
|
|
1039
1143
|
},
|
|
1040
1144
|
async inspect(root, requestId) {
|
|
1041
1145
|
const response = await getComponents().runner.status(requestId, root);
|
package/extensions/repos.ts
CHANGED
|
@@ -15,7 +15,7 @@ export function registerRepoDiscovery(pi: ExtensionAPI): void {
|
|
|
15
15
|
pi.registerTool({
|
|
16
16
|
name: "subagent_repos",
|
|
17
17
|
label: "Subagent Repos",
|
|
18
|
-
description: "List the child Git repositories below the Pi working directory, with the repo selector that delegate_task accepts. The tool changes no files and no Git state. It does not follow symlinks and
|
|
18
|
+
description: "List the child Git repositories below the Pi working directory, with the repo selector that delegate_task accepts. The tool changes no files and no Git state. It does not follow symlinks. It lists repositories inside repositories, such as submodules, and marks linked worktrees and submodules.",
|
|
19
19
|
promptSnippet: "List child Git repositories and their repo selectors for delegate_task",
|
|
20
20
|
promptGuidelines: [
|
|
21
21
|
"When the Pi working directory holds several repositories, use subagent_repos to find the repo selector, then set repo on delegate_task. Never guess a selector, and never select a repository the user did not name or authorize.",
|
|
@@ -29,8 +29,8 @@ export function registerRepoDiscovery(pi: ExtensionAPI): void {
|
|
|
29
29
|
...(signal ? { signal } : {}),
|
|
30
30
|
});
|
|
31
31
|
const lines = [
|
|
32
|
-
`${found.repos.length} repositories below ${found.base}${found.truncated ? " (truncated: a limit stopped the search)" : ""}.`,
|
|
33
|
-
...found.repos.map(({ repo, linkedWorktree }) => `${repo}${linkedWorktree ? " (linked worktree)" : ""}`),
|
|
32
|
+
`${found.repos.length} repositories below ${found.base}${found.truncated ? " (truncated: a depth, directory, repository, or time limit stopped the search, so some directories were not examined)" : ""}.`,
|
|
33
|
+
...found.repos.map(({ repo, linkedWorktree, submodule }) => `${repo}${linkedWorktree ? " (linked worktree)" : submodule ? " (submodule)" : ""}`),
|
|
34
34
|
...(found.issues.length ? ["Issues:", ...found.issues.slice(0, 20).map(({ path, reason }) => `${path}: ${reason}`)] : []),
|
|
35
35
|
...(found.issues.length > 20 ? [`${found.issues.length - 20} more issues omitted.`] : []),
|
|
36
36
|
];
|
|
@@ -75,6 +75,8 @@ export type { PruneItem };
|
|
|
75
75
|
export interface PrunePlan {
|
|
76
76
|
root: string;
|
|
77
77
|
items: readonly PruneItem[];
|
|
78
|
+
/** Incomplete review evidence, such as discovery issues or repositories that could not be read. */
|
|
79
|
+
warnings?: readonly string[];
|
|
78
80
|
}
|
|
79
81
|
|
|
80
82
|
/** Mutation adapters MUST check current() synchronously alongside their live ownership
|
|
@@ -211,7 +213,7 @@ const glyph = (status: string) => TONES[statusTone(status)].glyph;
|
|
|
211
213
|
const cleanupReport = ({ text, failed, skipped }: CleanupReport): Report => textReport(failed ? "error" : skipped ? "warning" : "success", text);
|
|
212
214
|
|
|
213
215
|
const PRUNE_IGNORED_CONFIRM_CODE_POINTS = 4_000;
|
|
214
|
-
const shortId = ({ branch }: PruneItem) => branch.replace(/^pi-subagent\/subagent-/, "").replace(/([0-9a-f]{8})[0-9a-f]{16}$/, "$1")
|
|
216
|
+
const shortId = ({ branch, repo }: PruneItem) => `${repo ? `${repo}:` : ""}${branch.replace(/^pi-subagent\/subagent-/, "").replace(/([0-9a-f]{8})[0-9a-f]{16}$/, "$1")}`;
|
|
215
217
|
const NOT_SHOWN = "they are not removed in this run; run /subagent prune again after this run.";
|
|
216
218
|
|
|
217
219
|
/** Fit whole item lines within `max` code points; never cut silently, and report exactly which items were shown. */
|
|
@@ -237,8 +239,9 @@ function fitItems<T>(header: string, items: readonly T[], line: (item: T) => str
|
|
|
237
239
|
|
|
238
240
|
/** Groups items by exact reason, prunable groups first, in lines of 10 IDs so a long list is cut at whole lines.
|
|
239
241
|
* Only shown items may be removed. IDs are display-only; removal uses the reviewed items. */
|
|
240
|
-
function pruneReview({ root, items }: PrunePlan): { report: Report; shown: PruneItem[] } {
|
|
241
|
-
|
|
242
|
+
function pruneReview({ root, items, warnings = [] }: PrunePlan): { report: Report; shown: PruneItem[] } {
|
|
243
|
+
const warningSection: Section[] = warnings.length ? [{ heading: `Warnings (${warnings.length})`, tone: "warning", rows: warnings.map((text) => ({ text })) }] : [];
|
|
244
|
+
if (!items.length) return { report: { tone: warnings.length ? "warning" : "info", title: `No pi-subagent worktrees or branches in ${root}.`, sections: warningSection }, shown: [] };
|
|
242
245
|
const groups = new Map<string, PruneItem[]>();
|
|
243
246
|
for (const item of [...items.filter((item) => item.prunable), ...items.filter((item) => !item.prunable)]) {
|
|
244
247
|
const title = item.prunable ? `Prunable: ${item.reason}` : `Blocked: ${item.path ? item.reason : `${item.reason}; no checkout`}`;
|
|
@@ -262,7 +265,7 @@ function pruneReview({ root, items }: PrunePlan): { report: Report; shown: Prune
|
|
|
262
265
|
ROLES_REPORT_CODE_POINTS, NOT_SHOWN, (row) => row.items.length);
|
|
263
266
|
const sections = [...new Set(reviewed.shown.map(({ section }) => section))]
|
|
264
267
|
.map((section) => ({ ...section, rows: reviewed.shown.filter((row) => row.section === section).map(({ row }) => row) }));
|
|
265
|
-
return { report: { ...head, sections: [...head.sections, ...sections, ...moreSection(reviewed.more)] }, shown: reviewed.shown.flatMap((row) => row.items) };
|
|
268
|
+
return { report: { ...head, sections: [...head.sections, ...warningSection, ...sections, ...moreSection(reviewed.more)] }, shown: reviewed.shown.flatMap((row) => row.items) };
|
|
266
269
|
}
|
|
267
270
|
|
|
268
271
|
function discardReview(plan: DiscardPlan): { report: Report; shown: DiscardPlan["items"] } {
|
|
@@ -373,7 +376,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
|
|
|
373
376
|
handleInput(data) { list.handleInput(data); tui.requestRender(); },
|
|
374
377
|
invalidate() { list.invalidate(); },
|
|
375
378
|
};
|
|
376
|
-
}, { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 } });
|
|
379
|
+
}, { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 }, blocked: { kind: "question", message: title } });
|
|
377
380
|
}
|
|
378
381
|
|
|
379
382
|
/** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
|
package/extensions/workflow.ts
CHANGED
|
@@ -2,11 +2,15 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { createReadStream } from "node:fs";
|
|
3
3
|
import { lstat, readlink } from "node:fs/promises";
|
|
4
4
|
import { posix } from "node:path";
|
|
5
|
-
import { StringEnum } from "@earendil-works/pi-ai";
|
|
6
5
|
import { DISPLAY_TEXT_CONTRACT } from "@hcflabs/pi-subagent";
|
|
7
6
|
import { PROFILE_NAMES } from "@hcflabs/pi-task-models";
|
|
8
7
|
import { Type, type Static } from "typebox";
|
|
9
8
|
import { Check, Errors } from "typebox/value";
|
|
9
|
+
|
|
10
|
+
// pi-ai StringEnum returns a pi-schema type, so TypeBox Static cannot infer it.
|
|
11
|
+
function StringEnum<const T extends readonly string[]>(values: T, options: { description?: string } = {}) {
|
|
12
|
+
return Type.Unsafe<T[number]>({ type: "string", enum: [...values], ...options });
|
|
13
|
+
}
|
|
10
14
|
import { runGit } from "../dist/git-process.js";
|
|
11
15
|
import { ExecuteRequestSchema, parseExecuteRequest, type ExecuteRequest } from "../dist/schema.js";
|
|
12
16
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hcflabs/pi-subagent",
|
|
3
|
-
"version": "28.
|
|
3
|
+
"version": "28.6.0",
|
|
4
4
|
"description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -41,9 +41,9 @@
|
|
|
41
41
|
"pack:check": "npm pack --dry-run"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
|
-
"@earendil-works/pi-ai": "^1.
|
|
45
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
46
|
-
"@earendil-works/pi-tui": "^1.
|
|
44
|
+
"@earendil-works/pi-ai": "^1.6.0",
|
|
45
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
46
|
+
"@earendil-works/pi-tui": "^1.6.0",
|
|
47
47
|
"typebox": "^1.3.15"
|
|
48
48
|
},
|
|
49
49
|
"repository": {
|
|
@@ -73,14 +73,14 @@
|
|
|
73
73
|
"@hcflabs/pi-config-store": "^4.0.0",
|
|
74
74
|
"@hcflabs/pi-herdr": "^0.7.0",
|
|
75
75
|
"@hcflabs/pi-process": "^0.3.0",
|
|
76
|
-
"@hcflabs/pi-repo": "^0.1.
|
|
77
|
-
"@hcflabs/pi-task-models": "^9.
|
|
76
|
+
"@hcflabs/pi-repo": "^0.1.4",
|
|
77
|
+
"@hcflabs/pi-task-models": "^9.3.0",
|
|
78
78
|
"proper-lockfile": "^4.1.2"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@earendil-works/pi-ai": "1.
|
|
82
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
83
|
-
"@earendil-works/pi-tui": "1.
|
|
81
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
82
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
83
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
84
84
|
"@types/proper-lockfile": "^4.1.4"
|
|
85
85
|
}
|
|
86
86
|
}
|