@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
@@ -0,0 +1,60 @@
1
+ /**
2
+ * gated-fix.js — verify by running a command, not by asking a second opinion.
3
+ *
4
+ * Demonstrates: `gate` (a shell command that must pass, or the agent is failed
5
+ * and its call returns null), and `resume` to hand the failure back to the same
6
+ * child instead of re-paying for the context it already built.
7
+ *
8
+ * Two constraints this example is shaped around, both worth knowing:
9
+ *
10
+ * 1. `gate` cannot be combined with `resume`. A resumed child keeps the agent
11
+ * type, model, tree and tools it was started with, so the corrective pass
12
+ * is NOT itself gated — re-verification needs its own gated call.
13
+ * 2. `isolation: "worktree"` is deliberately not used here. An isolated child's
14
+ * worktree is committed to a branch and removed when it settles, so a later
15
+ * agent would verify the main tree and could pass while the fix it was
16
+ * checking lives somewhere else. Isolation is for parallel writers that
17
+ * would collide; a serial fix-then-verify chain wants one shared tree.
18
+ *
19
+ * args: { task?: string, test?: string }
20
+ *
21
+ * Run: ask the model — "run the workflow at examples/workflows/gated-fix.js
22
+ * with the test command npm test". Needs a real test command to be useful.
23
+ */
24
+ export const meta = {
25
+ name: "gated-fix",
26
+ description: "Fix a failing test, then prove it passes by running the suite",
27
+ phases: [{ title: "Fix" }, { title: "Verify" }],
28
+ }
29
+
30
+ const task = args?.task ?? "Find and fix the failing test."
31
+ const testCommand = args?.test ?? "npm test"
32
+
33
+ phase("Fix")
34
+
35
+ // The gate runs after the agent finishes. A non-zero exit fails the agent and
36
+ // folds the command's output into its error, so `fixed` is null exactly when
37
+ // the suite did not pass — no need to ask a model whether the fix worked.
38
+ let fixed = await agent(task, { label: "fix", gate: testCommand })
39
+
40
+ if (fixed === null) {
41
+ log(`${testCommand} failed — handing the output back to the same child`)
42
+
43
+ // Resume, not a fresh spawn: the child still has everything it learned on the
44
+ // first pass, so it is told what broke rather than rediscovering it.
45
+ fixed = await agent(
46
+ `\`${testCommand}\` is still failing. Read the failure above, fix the cause, and stop.`,
47
+ { label: "fix", resume: "fix" },
48
+ )
49
+
50
+ // The resume could not carry the gate, so verify separately. This child works
51
+ // in the same tree, which is what makes the check meaningful.
52
+ phase("Verify")
53
+ const verified = await agent(
54
+ `Run \`${testCommand}\` and report the result. Change nothing.`,
55
+ { label: "verify", gate: testCommand, effort: "low" },
56
+ )
57
+ return { passed: verified !== null, summary: fixed }
58
+ }
59
+
60
+ return { passed: true, summary: fixed }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * lib/count-child.js — a nested workflow, invoked by compose.js.
3
+ *
4
+ * A child is an ordinary workflow: it needs its own `export const meta =`
5
+ * declaration, which is exactly what marks a file in a workflows directory as
6
+ * runnable rather than as some unrelated script that happens to live there.
7
+ *
8
+ * args: { root?: string }
9
+ */
10
+ export const meta = {
11
+ name: "count-child",
12
+ description: "Count the source files under a directory",
13
+ }
14
+
15
+ const root = args?.root ?? "src/"
16
+
17
+ const found = await agent(
18
+ `List every source file under ${root}. One path per line, nothing else.`,
19
+ {
20
+ label: "scan",
21
+ schema: {
22
+ type: "object",
23
+ properties: { files: { type: "array", items: { type: "string" } } },
24
+ required: ["files"],
25
+ },
26
+ },
27
+ )
28
+
29
+ // A schema call can still return null if the child never complied.
30
+ return found === null ? 0 : found.files.length
@@ -0,0 +1,68 @@
1
+ /**
2
+ * review-panel.js — the case where a barrier is actually earned.
3
+ *
4
+ * Demonstrates: `parallel` used correctly, `effort` tiering (cheap reviewers,
5
+ * an expensive judge), and a `model` override.
6
+ *
7
+ * Most of the time `pipeline` beats `parallel`, because a barrier idles every
8
+ * fast agent until the slowest finishes. This is the exception: the synthesis
9
+ * prompt interpolates ALL of the reviews, so it genuinely cannot start until
10
+ * every one of them is in. That — a prompt that compares results against each
11
+ * other — is what justifies a barrier.
12
+ *
13
+ * args: { target?: string, lenses?: string[] }
14
+ *
15
+ * Run: ask the model — "run the workflow at examples/workflows/review-panel.js
16
+ * against src/auth.ts".
17
+ */
18
+ export const meta = {
19
+ name: "review-panel",
20
+ description:
21
+ "Review one thing from several angles, then reconcile the verdicts",
22
+ phases: [{ title: "Review" }, { title: "Synthesize" }],
23
+ }
24
+
25
+ const target = args?.target ?? "the changed files"
26
+ const lenses = args?.lenses ?? ["correctness", "security", "performance"]
27
+
28
+ phase("Review")
29
+
30
+ // Perspective diversity, not redundancy: three reviewers with DIFFERENT briefs
31
+ // catch failure modes that three identical ones cannot.
32
+ const reviews = await parallel(
33
+ lenses.map(
34
+ (lens) => () =>
35
+ agent(
36
+ `Review ${target} through the lens of ${lens} alone. Be specific and brief.`,
37
+ {
38
+ label: `review:${lens}`,
39
+ // Cheap for the survey work; the judge below gets the depth.
40
+ effort: "low",
41
+ },
42
+ ),
43
+ ),
44
+ )
45
+
46
+ // A thunk that throws becomes null without taking its siblings down.
47
+ const usable = reviews
48
+ .map((text, i) => ({ lens: lenses[i], text }))
49
+ .filter((r) => r.text !== null)
50
+
51
+ if (usable.length === 0) {
52
+ log("every reviewer failed — nothing to synthesize")
53
+ return { reviewed: 0, verdict: null }
54
+ }
55
+
56
+ phase("Synthesize")
57
+
58
+ // This is the barrier's payoff: one prompt that sees all of them at once and can
59
+ // weigh them against each other.
60
+ const verdict = await agent(
61
+ [
62
+ `Reconcile these reviews of ${target}. Where they disagree, say which is right and why.`,
63
+ ...usable.map((r) => `\n## ${r.lens}\n${r.text}`),
64
+ ].join("\n"),
65
+ { label: "synthesize", effort: "high", agentType: "Plan" },
66
+ )
67
+
68
+ return { reviewed: usable.length, verdict }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * structured-findings.js — get objects back, not prose.
3
+ *
4
+ * Demonstrates: `schema` on every agent call, so the script manipulates
5
+ * validated objects instead of parsing text it hopes is well-formed.
6
+ *
7
+ * Reach for this whenever the script has to *do* something with the results —
8
+ * sort, count, filter, compare — rather than hand them straight to you.
9
+ *
10
+ * args: { dimensions?: string[] } — review angles, default bugs + perf
11
+ *
12
+ * Run: ask the model — "run the workflow at
13
+ * examples/workflows/structured-findings.js".
14
+ */
15
+ export const meta = {
16
+ name: "structured-findings",
17
+ description: "Review changed files across dimensions and verify each finding",
18
+ phases: [{ title: "Review" }, { title: "Verify" }],
19
+ }
20
+
21
+ const FINDINGS = {
22
+ type: "object",
23
+ properties: {
24
+ findings: {
25
+ type: "array",
26
+ items: {
27
+ type: "object",
28
+ properties: {
29
+ title: { type: "string" },
30
+ file: { type: "string" },
31
+ severity: { type: "string" },
32
+ },
33
+ required: ["title", "file"],
34
+ },
35
+ },
36
+ },
37
+ required: ["findings"],
38
+ }
39
+
40
+ const VERDICT = {
41
+ type: "object",
42
+ properties: { isReal: { type: "boolean" }, why: { type: "string" } },
43
+ required: ["isReal"],
44
+ }
45
+
46
+ const dimensions = args?.dimensions ?? ["bugs", "performance"]
47
+
48
+ const reviewed = await pipeline(
49
+ dimensions,
50
+ (dim) =>
51
+ agent(`Review the changed files for ${dim}. Report every finding.`, {
52
+ label: `review:${dim}`,
53
+ phase: "Review",
54
+ // With a schema the call resolves to the validated object, so `.findings`
55
+ // below is a real array rather than something scraped out of prose.
56
+ schema: FINDINGS,
57
+ }),
58
+ // A barrier is earned here only per-dimension: each dimension's findings are
59
+ // verified concurrently, but dimensions never wait for each other.
60
+ (review) =>
61
+ parallel(
62
+ review.findings.map(
63
+ (f) => () =>
64
+ agent(`Try to REFUTE this finding: ${f.title} (${f.file})`, {
65
+ label: `verify:${f.file}`,
66
+ phase: "Verify",
67
+ schema: VERDICT,
68
+ }).then((verdict) => ({ ...f, verdict })),
69
+ ),
70
+ ),
71
+ )
72
+
73
+ // filter(Boolean) twice: once for a whole dimension that failed, once for an
74
+ // individual verification that did. A schema call can still return null.
75
+ const confirmed = reviewed
76
+ .filter(Boolean)
77
+ .flat()
78
+ .filter(Boolean)
79
+ .filter((f) => f.verdict?.isReal)
80
+
81
+ return { confirmed: confirmed.length, findings: confirmed }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-subagents",
3
- "version": "0.17.1",
4
- "description": "Claude Code-style autonomous subagents for Pi, with HerbertGao-maintained UI extensions.",
3
+ "version": "0.18.0",
4
+ "description": "Claude Code-style autonomous subagents and workflow orchestration for Pi, with HerbertGao-maintained UI extensions.",
5
5
  "keywords": [
6
6
  "agent",
7
7
  "autonomous",
@@ -26,7 +26,8 @@
26
26
  },
27
27
  "files": [
28
28
  "src/**/*.ts",
29
- "examples/**/*.md",
29
+ "examples/**/*",
30
+ "docs/**/*.md",
30
31
  "README.md",
31
32
  "CHANGELOG.md",
32
33
  "SECURITY.md",
@@ -46,15 +47,16 @@
46
47
  "dependencies": {
47
48
  "@sinclair/typebox": "^0.34.49",
48
49
  "croner": "^10.0.1",
49
- "nanoid": "^5.1.16"
50
+ "nanoid": "^5.1.16",
51
+ "typebox": "^1.3.7"
50
52
  },
51
53
  "devDependencies": {
52
54
  "@vitest/coverage-istanbul": "^4.1.10"
53
55
  },
54
56
  "peerDependencies": {
55
- "@earendil-works/pi-ai": ">=0.81.0",
56
- "@earendil-works/pi-coding-agent": ">=0.81.0",
57
- "@earendil-works/pi-tui": ">=0.81.0"
57
+ "@earendil-works/pi-ai": ">=0.84.0",
58
+ "@earendil-works/pi-coding-agent": ">=0.84.0",
59
+ "@earendil-works/pi-tui": ">=0.84.0"
58
60
  },
59
61
  "engines": {
60
62
  "node": ">=22.19.0"
@@ -68,9 +70,9 @@
68
70
  },
69
71
  "x-upstream": {
70
72
  "package": "@tintinweb/pi-subagents",
71
- "version": "0.18.2",
73
+ "version": "0.19.0",
72
74
  "reviewedVersion": "0.19.0",
73
75
  "repository": "https://github.com/tintinweb/pi-subagents",
74
- "commit": "ad81024825b315577692b785831262874e66be95"
76
+ "commit": "95d10867f391636e6563e3885e972618083f306b"
75
77
  }
76
78
  }
@@ -20,14 +20,13 @@
20
20
  * discarding their comments, key order, and quoting. So the edits are line-wise
21
21
  * and preserve everything they don't touch.
22
22
  *
23
- * That leaves removal best-effort: it recognizes the parser's case-insensitive
24
- * bare `false` spellings and trailing comments, and reports `changed: false`
25
- * for values it cannot rewrite, so the caller refuses honestly rather than
26
- * announcing a change it did not make.
23
+ * That leaves removal best-effort: it recognizes a lowercase bare `false`, and
24
+ * reports `changed: false` for the spellings it cannot rewrite, so the caller
25
+ * refuses honestly rather than announcing a change it did not make.
27
26
  */
28
27
 
29
28
  import { existsSync } from "node:fs"
30
- import { join } from "node:path"
29
+ import { join, sep } from "node:path"
31
30
  import { getAgentDir } from "@earendil-works/pi-coding-agent"
32
31
  import { parseAgentFrontmatter } from "./custom-agents.js"
33
32
  import type { AgentConfig } from "./types.js"
@@ -61,20 +60,60 @@ export function findAgentFile(
61
60
  return undefined
62
61
  }
63
62
 
63
+ /**
64
+ * Find the file behind a *loaded* agent, preferring the path the loader
65
+ * actually read (`AgentConfig.sourcePath`) over the `<type>.md` guess.
66
+ *
67
+ * An agent's type comes from its frontmatter `name:` now, so the two can
68
+ * disagree: `reviewer.md` declaring `name: code-reviewer` is loaded as
69
+ * `code-reviewer`, and probing for `code-reviewer.md` finds nothing. That is
70
+ * not a harmless miss — `/agents → Disable` would then take the no-file branch
71
+ * and write a NEW `code-reviewer.md` stub, which loses to `reviewer.md` on
72
+ * load, leaving the agent enabled while reporting success.
73
+ *
74
+ * The probe stays as the fallback: a built-in that was never ejected has no
75
+ * `sourcePath`, and a path can go stale between a load and this call.
76
+ */
77
+ export function locateAgentFile(
78
+ name: string,
79
+ sourcePath: string | undefined,
80
+ cwd: string = process.cwd(),
81
+ ): { path: string; location: AgentFileLocation } | undefined {
82
+ if (sourcePath && existsSync(sourcePath)) {
83
+ return { path: sourcePath, location: classifyAgentDir(sourcePath, cwd) }
84
+ }
85
+ return findAgentFile(name, cwd)
86
+ }
87
+
88
+ /**
89
+ * Which discovery location a loaded agent's file came from. Only ever names
90
+ * a directory in a confirmation prompt, so an unrecognized parent — which
91
+ * loadCustomAgents cannot currently produce — reports as personal rather than
92
+ * widening the type for a case that has no better answer.
93
+ */
94
+ function classifyAgentDir(path: string, cwd: string): AgentFileLocation {
95
+ if (path.startsWith(projectAgentsDir(cwd) + sep)) return "project"
96
+ if (path.startsWith(workspaceAgentsDir(cwd) + sep)) return "workspace"
97
+ return "personal"
98
+ }
99
+
64
100
  export type DisableOutcome = "disabled" | "already-disabled" | "no-frontmatter"
65
101
 
66
- /** A line that sets `enabled: false`, accepting YAML case and comments. */
67
- const ENABLED_FALSE = /^[ \t]*enabled:[ \t]*false[ \t]*(?:#[^\r\n]*)?$/i
102
+ /** A line that sets `enabled: false`, ignoring trailing whitespace / CR. */
103
+ const ENABLED_FALSE = /^enabled:[ \t]*false[ \t]*$/
68
104
  /** An opening or closing `---` fence line. */
69
105
  const FENCE = /^---[ \t]*$/
70
106
 
71
107
  /**
72
108
  * Split a file into its frontmatter lines and everything else, agreeing with
73
- * what `parseAgentFrontmatter` (the load side) considers a frontmatter block.
109
+ * what `parseAgentFrontmatter` (the load side) considers a frontmatter block —
110
+ * including its BOM normalisation, which is why the fence test looks past one.
111
+ * The BOM itself stays in `lines[0]`: it belongs to the file's encoding, not to
112
+ * the block, and an edit must not strip it from the user's file.
74
113
  *
75
114
  * Lines keep their terminators, so an edit preserves the file's existing line
76
115
  * endings instead of rewriting CRLF to LF. Returns undefined when there is no
77
- * usable block. A leading BOM stays byte-for-byte in the file.
116
+ * usable block.
78
117
  */
79
118
  function splitFrontmatter(
80
119
  content: string,
@@ -83,9 +122,10 @@ function splitFrontmatter(
83
122
  | undefined {
84
123
  const lines = content.split(/(?<=\n)/)
85
124
  if (lines.length === 0) return undefined
86
- const first = (
87
- content.startsWith("\uFEFF") ? lines[0].slice(1) : lines[0]
88
- ).replace(/\r?\n$/, "")
125
+ // The BOM stays where it is — it belongs to the file, not the block — so the
126
+ // fence test looks past it and every index below is unaffected.
127
+ const bom = content.startsWith("\uFEFF")
128
+ const first = (bom ? lines[0].slice(1) : lines[0]).replace(/\r?\n$/, "")
89
129
  if (!FENCE.test(first)) return undefined
90
130
  const closeIdx = lines.findIndex(
91
131
  (l, i) => i > 0 && FENCE.test(l.replace(/\r?\n$/, "")),