@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.6

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,230 @@
1
+ /**
2
+ * worktree.ts — Git worktree isolation for agents.
3
+ *
4
+ * Creates a temporary git worktree so the agent works on an isolated copy of the repo.
5
+ * On completion, if no changes were made, the worktree is cleaned up.
6
+ * If changes exist, a branch is created and returned in the result.
7
+ *
8
+ * Every git call goes through `pi.exec` (async) rather than `execFileSync`: a
9
+ * worktree copy can take seconds, and a session that spawns several isolated
10
+ * agents at once would otherwise serialize them all on the TUI's event loop.
11
+ */
12
+
13
+ import { randomUUID } from "node:crypto";
14
+ import { existsSync, realpathSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join, relative } from "node:path";
17
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+
19
+ export interface WorktreeInfo {
20
+ /** Absolute path to the worktree directory (the copied repo's root). */
21
+ path: string;
22
+ /** Branch name created for this worktree (if changes exist). */
23
+ branch: string;
24
+ /** Commit SHA that the worktree was created from. */
25
+ baseSha: string;
26
+ /** Resolved toplevel of the repo the worktree was created from; the result branch lands here. */
27
+ repoRoot: string;
28
+ /**
29
+ * Where the agent should work inside the worktree: the equivalent of the
30
+ * cwd the worktree was created from. Equals `path` when that cwd was the
31
+ * repo root; points at the copied subdirectory when it was deeper (e.g. a
32
+ * monorepo package), so the requested scoping survives isolation.
33
+ */
34
+ workPath: string;
35
+ }
36
+
37
+ /**
38
+ * Project-wide switch for worktree isolation (`worktreeIsolation` in
39
+ * subagents.json). Default `true` — unchanged behaviour.
40
+ *
41
+ * The `"off"` isolation value gives a model a legal way to decline a worktree,
42
+ * but it still depends on the model choosing it. This is the deterministic half
43
+ * of the same fix: on a large repo where every worktree costs real time and
44
+ * disk (#184), turning it off means no caller can create one, whatever it
45
+ * passes.
46
+ */
47
+ let worktreeIsolationEnabled = true;
48
+
49
+ export function setWorktreeIsolationEnabled(enabled: boolean): void {
50
+ worktreeIsolationEnabled = enabled;
51
+ }
52
+
53
+ export function isWorktreeIsolationEnabled(): boolean {
54
+ return worktreeIsolationEnabled;
55
+ }
56
+
57
+ export interface WorktreeCleanupResult {
58
+ /** Whether changes were found in the worktree. */
59
+ hasChanges: boolean;
60
+ /** Branch name if changes were committed. */
61
+ branch?: string;
62
+ /** Worktree path if it was kept. */
63
+ path?: string;
64
+ }
65
+
66
+ /**
67
+ * Run git and return its trimmed stdout, throwing on failure so callers keep
68
+ * the try/catch control flow `execFileSync` gave them.
69
+ *
70
+ * `pi.exec` never rejects — it reports failure in the result — and a command
71
+ * killed by its timeout comes back as `killed` with an exit code of 0, so both
72
+ * have to be checked to reproduce `execFileSync`'s "throws on anything but a
73
+ * clean exit".
74
+ */
75
+ async function git(pi: ExtensionAPI, cwd: string, args: string[], timeout: number): Promise<string> {
76
+ const result = await pi.exec("git", args, { cwd, timeout });
77
+ if (result.killed) throw new GitTimeoutError(`\`git ${args.join(" ")}\` timed out after ${timeout}ms in ${cwd}`);
78
+ if (result.code !== 0) {
79
+ throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed (exit ${result.code})`);
80
+ }
81
+ return result.stdout.trim();
82
+ }
83
+
84
+ /** A git call killed by its timeout — reported as-is, never as a repo-state cause. */
85
+ class GitTimeoutError extends Error {}
86
+
87
+ /**
88
+ * Why `createWorktree` could not isolate an agent. The message names the
89
+ * directory it tried and the specific cause, so a caller can tell "wrong
90
+ * directory" from "repo with no commits" from a git failure.
91
+ */
92
+ export class WorktreeError extends Error {}
93
+
94
+ /** Run one git step, rethrowing a failure as a `WorktreeError` whose message is `cause(detail)`. */
95
+ async function step(run: Promise<string>, cause: (detail: string) => string): Promise<string> {
96
+ try {
97
+ return await run;
98
+ } catch (err) {
99
+ const detail = err instanceof Error ? err.message : String(err);
100
+ throw new WorktreeError(err instanceof GitTimeoutError ? detail : cause(detail));
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Create a temporary git worktree for an agent, from the repo containing `cwd`
106
+ * (which may be any directory inside it, not just the toplevel).
107
+ *
108
+ * @throws WorktreeError — `cwd` is not inside a git work tree, the repo has no
109
+ * commits yet, `git worktree add` failed, or a git call timed out.
110
+ */
111
+ export async function createWorktree(pi: ExtensionAPI, cwd: string, agentId: string): Promise<WorktreeInfo> {
112
+ const inside = await step(
113
+ git(pi, cwd, ["rev-parse", "--is-inside-work-tree"], 5000),
114
+ detail => `${cwd} is not inside a git repository (${detail})`,
115
+ );
116
+ // "false" with a clean exit: inside a `.git` dir or a bare repo.
117
+ if (inside !== "true") throw new WorktreeError(`${cwd} is inside a git directory but not a work tree`);
118
+ // realpath both sides — git emits resolved paths while cwd may arrive
119
+ // through a symlink (macOS /tmp).
120
+ const repoRoot = realpathSync(await step(
121
+ git(pi, cwd, ["rev-parse", "--show-toplevel"], 5000),
122
+ detail => `${cwd} has no git work tree toplevel (${detail})`,
123
+ ));
124
+ const baseSha = await step(
125
+ git(pi, cwd, ["rev-parse", "--verify", "HEAD"], 5000),
126
+ () => `${repoRoot} has no commits yet; commit at least once`,
127
+ );
128
+ // Where cwd sits inside the repo ("" at the root): the agent must work at
129
+ // the same subdirectory inside the copy, or a monorepo-package cwd would
130
+ // silently widen to the whole repo.
131
+ const subdir = relative(repoRoot, realpathSync(cwd));
132
+
133
+ const branch = `pi-agent-${agentId}`;
134
+ const suffix = randomUUID().slice(0, 8);
135
+ const worktreePath = join(tmpdir(), `pi-agent-${agentId}-${suffix}`);
136
+
137
+ // Create detached worktree at HEAD
138
+ await step(
139
+ git(pi, cwd, ["worktree", "add", "--detach", worktreePath, "HEAD"], 30000),
140
+ detail => `\`git worktree add\` failed in ${repoRoot}: ${detail}`,
141
+ );
142
+ return { path: worktreePath, branch, baseSha, repoRoot, workPath: subdir ? join(worktreePath, subdir) : worktreePath };
143
+ }
144
+
145
+ /**
146
+ * Clean up a worktree after agent completion.
147
+ * - If no changes: remove worktree entirely.
148
+ * - If changes exist: create a branch, commit changes, return branch info.
149
+ */
150
+ export async function cleanupWorktree(
151
+ pi: ExtensionAPI,
152
+ cwd: string,
153
+ worktree: WorktreeInfo,
154
+ agentDescription: string,
155
+ ): Promise<WorktreeCleanupResult> {
156
+ if (!existsSync(worktree.path)) {
157
+ return { hasChanges: false };
158
+ }
159
+
160
+ try {
161
+ // Check for uncommitted changes in the worktree
162
+ const status = await git(pi, worktree.path, ["status", "--porcelain"], 10000);
163
+
164
+ if (status) {
165
+ // Changes exist — stage, commit, and create a branch
166
+ await git(pi, worktree.path, ["add", "-A"], 10000);
167
+ // Truncate description for commit message (no shell sanitization needed — pi.exec uses argv)
168
+ const safeDesc = agentDescription.slice(0, 200);
169
+ const commitMsg = `pi-agent: ${safeDesc}`;
170
+ await git(pi, worktree.path, ["commit", "--no-verify", "-m", commitMsg], 10000);
171
+ } else {
172
+ const currentSha = await git(pi, worktree.path, ["rev-parse", "HEAD"], 5000);
173
+
174
+ if (currentSha === worktree.baseSha) {
175
+ // No changes — remove worktree
176
+ await removeWorktree(pi, cwd, worktree.path);
177
+ return { hasChanges: false };
178
+ }
179
+ }
180
+
181
+ // Create a branch pointing to the worktree's HEAD.
182
+ // If the branch already exists, append a suffix to avoid overwriting previous work.
183
+ let branchName = worktree.branch;
184
+ try {
185
+ await git(pi, worktree.path, ["branch", branchName], 5000);
186
+ } catch {
187
+ // Branch already exists — use a unique suffix
188
+ branchName = `${worktree.branch}-${Date.now()}`;
189
+ await git(pi, worktree.path, ["branch", branchName], 5000);
190
+ }
191
+ // Update branch name in worktree info for the caller
192
+ worktree.branch = branchName;
193
+
194
+ // Remove the worktree (branch persists in main repo)
195
+ await removeWorktree(pi, cwd, worktree.path);
196
+
197
+ return {
198
+ hasChanges: true,
199
+ branch: worktree.branch,
200
+ path: worktree.path,
201
+ };
202
+ } catch {
203
+ // Best effort cleanup on error
204
+ try { await removeWorktree(pi, cwd, worktree.path); } catch { /* ignore */ }
205
+ return { hasChanges: false };
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Force-remove a worktree.
211
+ */
212
+ async function removeWorktree(pi: ExtensionAPI, cwd: string, worktreePath: string): Promise<void> {
213
+ try {
214
+ await git(pi, cwd, ["worktree", "remove", "--force", worktreePath], 10000);
215
+ } catch {
216
+ // If git worktree remove fails, try pruning
217
+ try {
218
+ await git(pi, cwd, ["worktree", "prune"], 5000);
219
+ } catch { /* ignore */ }
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Prune any orphaned worktrees (crash recovery).
225
+ */
226
+ export async function pruneWorktrees(pi: ExtensionAPI, cwd: string): Promise<void> {
227
+ try {
228
+ await git(pi, cwd, ["worktree", "prune"], 5000);
229
+ } catch { /* ignore */ }
230
+ }
package/src/xml.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * xml.ts — escaping for the `<task-notification>` payloads.
3
+ *
4
+ * A module of its own because both notification builders need it and they sit
5
+ * on opposite sides of a dependency edge: the agent one lives in `index.ts`,
6
+ * which imports `workflow/task.ts`, so the workflow one cannot reach back for
7
+ * it without a cycle.
8
+ */
9
+
10
+ /** Escape XML special characters to prevent injection in structured notifications. */
11
+ export function escapeXml(s: string): string {
12
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
13
+ }