@herbertgao/pi-subagents 0.17.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +427 -120
  3. package/docs/rpc.md +184 -0
  4. package/docs/workflows.md +466 -0
  5. package/examples/agent-tool-description.md +6 -6
  6. package/examples/workflows/compose.js +52 -0
  7. package/examples/workflows/fan-out-audit.js +56 -0
  8. package/examples/workflows/gated-fix.js +60 -0
  9. package/examples/workflows/lib/count-child.js +30 -0
  10. package/examples/workflows/review-panel.js +68 -0
  11. package/examples/workflows/structured-findings.js +81 -0
  12. package/package.json +11 -9
  13. package/src/agent-file-toggle.ts +52 -12
  14. package/src/agent-manager.ts +837 -146
  15. package/src/agent-runner.ts +213 -39
  16. package/src/cross-extension-rpc.ts +73 -14
  17. package/src/custom-agents.ts +101 -47
  18. package/src/index.ts +2249 -914
  19. package/src/invocation-config.ts +13 -0
  20. package/src/mention-clone.ts +215 -0
  21. package/src/mention.ts +147 -0
  22. package/src/model-resolver.ts +9 -1
  23. package/src/nested-tools.ts +40 -26
  24. package/src/output-file.ts +18 -8
  25. package/src/prompts.ts +46 -9
  26. package/src/schedule.ts +21 -16
  27. package/src/settings.ts +137 -7
  28. package/src/structured-output.ts +136 -0
  29. package/src/types.ts +126 -8
  30. package/src/ui/agent-mention.ts +274 -0
  31. package/src/ui/agent-widget.ts +20 -5
  32. package/src/ui/conversation-viewer.ts +10 -4
  33. package/src/ui/fleet-list.ts +167 -22
  34. package/src/ui/workflow-card.ts +555 -0
  35. package/src/ui/workflow-dialog.ts +1304 -0
  36. package/src/ui/workflow-menu.ts +226 -0
  37. package/src/workflow/collisions.ts +122 -0
  38. package/src/workflow/entry.ts +47 -0
  39. package/src/workflow/host.ts +463 -0
  40. package/src/workflow/journal.ts +164 -0
  41. package/src/workflow/json-schema.ts +142 -0
  42. package/src/workflow/meta.ts +401 -0
  43. package/src/workflow/progress.ts +622 -0
  44. package/src/workflow/runtime.ts +1399 -0
  45. package/src/workflow/saved.ts +230 -0
  46. package/src/workflow/task.ts +333 -0
  47. package/src/workflow/tool-description.ts +200 -0
  48. package/src/workflow/worker-source.ts +781 -0
  49. package/src/worktree.ts +97 -95
  50. package/src/xml.ts +13 -0
package/src/worktree.ts CHANGED
@@ -4,13 +4,17 @@
4
4
  * Creates a temporary git worktree so the agent works on an isolated copy of the repo.
5
5
  * On completion, if no changes were made, the worktree is cleaned up.
6
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.
7
11
  */
8
12
 
9
- import { execFileSync } from "node:child_process"
10
13
  import { randomUUID } from "node:crypto"
11
14
  import { existsSync, realpathSync } from "node:fs"
12
15
  import { tmpdir } from "node:os"
13
16
  import { join, relative } from "node:path"
17
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
14
18
 
15
19
  export interface WorktreeInfo {
16
20
  /** Absolute path to the worktree directory (the copied repo's root). */
@@ -49,49 +53,61 @@ export function isWorktreeIsolationEnabled(): boolean {
49
53
  }
50
54
 
51
55
  export interface WorktreeCleanupResult {
52
- /** Whether changes were found in the worktree. */
56
+ /** Whether changes were found or may remain after a cleanup failure. */
53
57
  hasChanges: boolean
54
58
  /** Branch name if changes were committed. */
55
59
  branch?: string
56
- /** Worktree path if it was kept. */
60
+ /** Worktree path. On error, the agent's changes remain here for recovery. */
57
61
  path?: string
62
+ /** Cleanup failure. When present, the worktree is deliberately preserved. */
63
+ error?: 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(
76
+ pi: ExtensionAPI,
77
+ cwd: string,
78
+ args: string[],
79
+ timeout: number,
80
+ ): Promise<string> {
81
+ const result = await pi.exec("git", args, { cwd, timeout })
82
+ if (result.killed || result.code !== 0) {
83
+ throw new Error(
84
+ result.stderr.trim() ||
85
+ `git ${args.join(" ")} failed (exit ${result.code})`,
86
+ )
87
+ }
88
+ return result.stdout.trim()
58
89
  }
59
90
 
60
91
  /**
61
92
  * Create a temporary git worktree for an agent.
62
93
  * Returns the worktree path, or undefined if not in a git repo.
63
94
  */
64
- export function createWorktree(
95
+ export async function createWorktree(
96
+ pi: ExtensionAPI,
65
97
  cwd: string,
66
98
  agentId: string,
67
- ): WorktreeInfo | undefined {
99
+ ): Promise<WorktreeInfo | undefined> {
68
100
  // Verify we're in a git repo with at least one commit (HEAD must exist)
69
101
  let baseSha: string
70
102
  let subdir: string
71
103
  try {
72
- execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
73
- cwd,
74
- stdio: "pipe",
75
- timeout: 5000,
76
- })
77
- baseSha = execFileSync("git", ["rev-parse", "HEAD"], {
78
- cwd,
79
- stdio: "pipe",
80
- timeout: 5000,
81
- })
82
- .toString()
83
- .trim()
104
+ await git(pi, cwd, ["rev-parse", "--is-inside-work-tree"], 5000)
105
+ baseSha = await git(pi, cwd, ["rev-parse", "HEAD"], 5000)
84
106
  // Where cwd sits inside the repo ("" at the root): the agent must work at
85
107
  // the same subdirectory inside the copy, or a monorepo-package cwd would
86
108
  // silently widen to the whole repo. realpath both sides — git emits
87
109
  // resolved paths while cwd may arrive through a symlink (macOS /tmp).
88
- const topLevel = execFileSync("git", ["rev-parse", "--show-toplevel"], {
89
- cwd,
90
- stdio: "pipe",
91
- timeout: 5000,
92
- })
93
- .toString()
94
- .trim()
110
+ const topLevel = await git(pi, cwd, ["rev-parse", "--show-toplevel"], 5000)
95
111
  subdir = relative(realpathSync(topLevel), realpathSync(cwd))
96
112
  } catch {
97
113
  return undefined
@@ -103,11 +119,12 @@ export function createWorktree(
103
119
 
104
120
  try {
105
121
  // Create detached worktree at HEAD
106
- execFileSync("git", ["worktree", "add", "--detach", worktreePath, "HEAD"], {
122
+ await git(
123
+ pi,
107
124
  cwd,
108
- stdio: "pipe",
109
- timeout: 30000,
110
- })
125
+ ["worktree", "add", "--detach", worktreePath, "HEAD"],
126
+ 30000,
127
+ )
111
128
  return {
112
129
  path: worktreePath,
113
130
  branch,
@@ -125,56 +142,49 @@ export function createWorktree(
125
142
  * - If no changes: remove worktree entirely.
126
143
  * - If changes exist: create a branch, commit changes, return branch info.
127
144
  */
128
- export function cleanupWorktree(
145
+ export async function cleanupWorktree(
146
+ pi: ExtensionAPI,
129
147
  cwd: string,
130
148
  worktree: WorktreeInfo,
131
149
  agentDescription: string,
132
- ): WorktreeCleanupResult {
150
+ ): Promise<WorktreeCleanupResult> {
133
151
  if (!existsSync(worktree.path)) {
134
152
  return { hasChanges: false }
135
153
  }
136
154
 
155
+ let preservedBranch: string | undefined
137
156
  try {
138
157
  // Check for uncommitted changes in the worktree
139
- const status = execFileSync("git", ["status", "--porcelain"], {
140
- cwd: worktree.path,
141
- stdio: "pipe",
142
- timeout: 30000,
143
- })
144
- .toString()
145
- .trim()
158
+ const status = await git(
159
+ pi,
160
+ worktree.path,
161
+ ["status", "--porcelain"],
162
+ 10000,
163
+ )
146
164
 
147
165
  if (status) {
148
166
  // Changes exist — stage, commit, and create a branch
149
- execFileSync("git", ["add", "-A"], {
150
- cwd: worktree.path,
151
- stdio: "pipe",
152
- timeout: 10000,
153
- })
154
- // Truncate description for commit message (no shell sanitization needed — execFileSync uses argv)
167
+ await git(pi, worktree.path, ["add", "-A"], 10000)
168
+ // Truncate description for commit message (no shell sanitization needed — pi.exec uses argv)
155
169
  const safeDesc = agentDescription.slice(0, 200)
156
170
  const commitMsg = `pi-agent: ${safeDesc}`
157
- execFileSync(
158
- "git",
171
+ await git(
172
+ pi,
173
+ worktree.path,
159
174
  ["commit", "--no-verify", "--no-gpg-sign", "-m", commitMsg],
160
- {
161
- cwd: worktree.path,
162
- stdio: "pipe",
163
- timeout: 10000,
164
- },
175
+ 10000,
165
176
  )
166
177
  } else {
167
- const currentSha = execFileSync("git", ["rev-parse", "HEAD"], {
168
- cwd: worktree.path,
169
- stdio: "pipe",
170
- timeout: 5000,
171
- })
172
- .toString()
173
- .trim()
178
+ const currentSha = await git(
179
+ pi,
180
+ worktree.path,
181
+ ["rev-parse", "HEAD"],
182
+ 5000,
183
+ )
174
184
 
175
185
  if (currentSha === worktree.baseSha) {
176
186
  // No changes — remove worktree
177
- removeWorktree(cwd, worktree.path)
187
+ await removeWorktree(pi, cwd, worktree.path)
178
188
  return { hasChanges: false }
179
189
  }
180
190
  }
@@ -183,76 +193,68 @@ export function cleanupWorktree(
183
193
  // If the branch already exists, append a suffix to avoid overwriting previous work.
184
194
  let branchName = worktree.branch
185
195
  try {
186
- execFileSync("git", ["branch", branchName], {
187
- cwd: worktree.path,
188
- stdio: "pipe",
189
- timeout: 5000,
190
- })
196
+ await git(pi, worktree.path, ["branch", branchName], 5000)
191
197
  } catch {
192
198
  // Branch already exists — use a unique suffix
193
199
  branchName = `${worktree.branch}-${Date.now()}`
194
- execFileSync("git", ["branch", branchName], {
195
- cwd: worktree.path,
196
- stdio: "pipe",
197
- timeout: 5000,
198
- })
200
+ await git(pi, worktree.path, ["branch", branchName], 5000)
199
201
  }
200
202
  // Update branch name in worktree info for the caller
201
203
  worktree.branch = branchName
204
+ preservedBranch = branchName
202
205
 
203
206
  // Remove the worktree (branch persists in main repo)
204
- removeWorktree(cwd, worktree.path)
207
+ await removeWorktree(pi, cwd, worktree.path)
205
208
 
206
209
  return {
207
210
  hasChanges: true,
208
211
  branch: worktree.branch,
209
212
  path: worktree.path,
210
213
  }
211
- } catch {
212
- // Best effort cleanup on error
213
- try {
214
- removeWorktree(cwd, worktree.path)
215
- } catch {
216
- /* ignore */
214
+ } catch (error) {
215
+ // This may be the only copy of the agent's work. Keep it recoverable and
216
+ // report the path instead of turning a preservation failure into "no changes".
217
+ return {
218
+ hasChanges: true,
219
+ ...(preservedBranch ? { branch: preservedBranch } : {}),
220
+ path: worktree.path,
221
+ error: error instanceof Error ? error.message : String(error),
217
222
  }
218
- return { hasChanges: false }
219
223
  }
220
224
  }
221
225
 
222
226
  /**
223
227
  * Force-remove a worktree.
224
228
  */
225
- function removeWorktree(cwd: string, worktreePath: string): void {
229
+ async function removeWorktree(
230
+ pi: ExtensionAPI,
231
+ cwd: string,
232
+ worktreePath: string,
233
+ ): Promise<void> {
226
234
  try {
227
- execFileSync("git", ["worktree", "remove", "--force", worktreePath], {
228
- cwd,
229
- stdio: "pipe",
230
- timeout: 10000,
231
- })
232
- } catch {
233
- // If git worktree remove fails, try pruning
235
+ await git(pi, cwd, ["worktree", "remove", "--force", worktreePath], 10000)
236
+ } catch (removeError) {
237
+ // A concurrent remover may have deleted the directory while Git still
238
+ // returned an error. Prune stale metadata, but report failure if the copy
239
+ // still exists — callers must not mistake a leaked worktree for success.
234
240
  try {
235
- execFileSync("git", ["worktree", "prune"], {
236
- cwd,
237
- stdio: "pipe",
238
- timeout: 5000,
239
- })
241
+ await git(pi, cwd, ["worktree", "prune"], 5000)
240
242
  } catch {
241
243
  /* ignore */
242
244
  }
245
+ if (existsSync(worktreePath)) throw removeError
243
246
  }
244
247
  }
245
248
 
246
249
  /**
247
250
  * Prune any orphaned worktrees (crash recovery).
248
251
  */
249
- export function pruneWorktrees(cwd: string): void {
252
+ export async function pruneWorktrees(
253
+ pi: ExtensionAPI,
254
+ cwd: string,
255
+ ): Promise<void> {
250
256
  try {
251
- execFileSync("git", ["worktree", "prune"], {
252
- cwd,
253
- stdio: "pipe",
254
- timeout: 5000,
255
- })
257
+ await git(pi, cwd, ["worktree", "prune"], 5000)
256
258
  } catch {
257
259
  /* ignore */
258
260
  }
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
+ }