pi-agent-flow 1.8.1 → 1.8.3

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 (154) hide show
  1. package/README.md +4 -30
  2. package/agents/audit.md +1 -2
  3. package/agents/build.md +1 -0
  4. package/agents/craft.md +12 -8
  5. package/agents/debug.md +2 -2
  6. package/agents/ideas.md +1 -0
  7. package/agents/scout.md +1 -0
  8. package/dist/agents.d.ts +41 -0
  9. package/dist/agents.d.ts.map +1 -0
  10. package/dist/agents.js +283 -0
  11. package/dist/agents.js.map +1 -0
  12. package/dist/batch/batch-bash.d.ts +87 -0
  13. package/dist/batch/batch-bash.d.ts.map +1 -0
  14. package/dist/batch/batch-bash.js +369 -0
  15. package/dist/batch/batch-bash.js.map +1 -0
  16. package/dist/batch/constants.d.ts +100 -0
  17. package/dist/batch/constants.d.ts.map +1 -0
  18. package/dist/batch/constants.js +15 -0
  19. package/dist/batch/constants.js.map +1 -0
  20. package/dist/batch/execute.d.ts +21 -0
  21. package/dist/batch/execute.d.ts.map +1 -0
  22. package/dist/batch/execute.js +440 -0
  23. package/dist/batch/execute.js.map +1 -0
  24. package/dist/batch/fuzzy-edit.d.ts +29 -0
  25. package/dist/batch/fuzzy-edit.d.ts.map +1 -0
  26. package/dist/batch/fuzzy-edit.js +257 -0
  27. package/dist/batch/fuzzy-edit.js.map +1 -0
  28. package/dist/batch/index.d.ts +85 -0
  29. package/dist/batch/index.d.ts.map +1 -0
  30. package/dist/batch/index.js +422 -0
  31. package/dist/batch/index.js.map +1 -0
  32. package/dist/batch/render.d.ts +14 -0
  33. package/dist/batch/render.d.ts.map +1 -0
  34. package/dist/batch/render.js +74 -0
  35. package/dist/batch/render.js.map +1 -0
  36. package/dist/batch/symbols.d.ts +9 -0
  37. package/dist/batch/symbols.d.ts.map +1 -0
  38. package/dist/batch/symbols.js +310 -0
  39. package/dist/batch/symbols.js.map +1 -0
  40. package/dist/batch.d.ts +12 -0
  41. package/dist/batch.d.ts.map +1 -0
  42. package/dist/batch.js +11 -0
  43. package/dist/batch.js.map +1 -0
  44. package/dist/cli-args.d.ts +27 -0
  45. package/dist/cli-args.d.ts.map +1 -0
  46. package/dist/cli-args.js +265 -0
  47. package/dist/cli-args.js.map +1 -0
  48. package/dist/config.d.ts +58 -0
  49. package/dist/config.d.ts.map +1 -0
  50. package/dist/config.js +296 -0
  51. package/dist/config.js.map +1 -0
  52. package/dist/depth.d.ts +25 -0
  53. package/dist/depth.d.ts.map +1 -0
  54. package/dist/depth.js +160 -0
  55. package/dist/depth.js.map +1 -0
  56. package/dist/executor.d.ts +87 -0
  57. package/dist/executor.d.ts.map +1 -0
  58. package/dist/executor.js +295 -0
  59. package/dist/executor.js.map +1 -0
  60. package/dist/flow-prompt.d.ts +23 -0
  61. package/dist/flow-prompt.d.ts.map +1 -0
  62. package/dist/flow-prompt.js +99 -0
  63. package/dist/flow-prompt.js.map +1 -0
  64. package/dist/flow.d.ts +76 -0
  65. package/dist/flow.d.ts.map +1 -0
  66. package/dist/flow.js +704 -0
  67. package/dist/flow.js.map +1 -0
  68. package/dist/index.d.ts +10 -0
  69. package/dist/index.d.ts.map +1 -0
  70. package/dist/index.js +327 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/reasoning-strip.d.ts +26 -0
  73. package/dist/reasoning-strip.d.ts.map +1 -0
  74. package/dist/reasoning-strip.js +58 -0
  75. package/dist/reasoning-strip.js.map +1 -0
  76. package/dist/render-utils.d.ts +42 -0
  77. package/dist/render-utils.d.ts.map +1 -0
  78. package/dist/render-utils.js +182 -0
  79. package/dist/render-utils.js.map +1 -0
  80. package/dist/render.d.ts +24 -0
  81. package/dist/render.d.ts.map +1 -0
  82. package/dist/render.js +409 -0
  83. package/dist/render.js.map +1 -0
  84. package/dist/runner-events.d.ts +59 -0
  85. package/dist/runner-events.d.ts.map +1 -0
  86. package/dist/runner-events.js +539 -0
  87. package/dist/runner-events.js.map +1 -0
  88. package/dist/session-mode.d.ts +10 -0
  89. package/dist/session-mode.d.ts.map +1 -0
  90. package/dist/session-mode.js +25 -0
  91. package/dist/session-mode.js.map +1 -0
  92. package/dist/settings-resolver.d.ts +28 -0
  93. package/dist/settings-resolver.d.ts.map +1 -0
  94. package/dist/settings-resolver.js +148 -0
  95. package/dist/settings-resolver.js.map +1 -0
  96. package/dist/sliding-prompt.d.ts +40 -0
  97. package/dist/sliding-prompt.d.ts.map +1 -0
  98. package/dist/sliding-prompt.js +121 -0
  99. package/dist/sliding-prompt.js.map +1 -0
  100. package/dist/snapshot.d.ts +29 -0
  101. package/dist/snapshot.d.ts.map +1 -0
  102. package/dist/snapshot.js +199 -0
  103. package/dist/snapshot.js.map +1 -0
  104. package/dist/structured-output.d.ts +36 -0
  105. package/dist/structured-output.d.ts.map +1 -0
  106. package/dist/structured-output.js +244 -0
  107. package/dist/structured-output.js.map +1 -0
  108. package/dist/timed-bash.d.ts +45 -0
  109. package/dist/timed-bash.d.ts.map +1 -0
  110. package/dist/timed-bash.js +219 -0
  111. package/dist/timed-bash.js.map +1 -0
  112. package/dist/tool-utils.d.ts +20 -0
  113. package/dist/tool-utils.d.ts.map +1 -0
  114. package/dist/tool-utils.js +38 -0
  115. package/dist/tool-utils.js.map +1 -0
  116. package/dist/transitions.d.ts +39 -0
  117. package/dist/transitions.d.ts.map +1 -0
  118. package/dist/transitions.js +59 -0
  119. package/dist/transitions.js.map +1 -0
  120. package/dist/types.d.ts +207 -0
  121. package/dist/types.d.ts.map +1 -0
  122. package/dist/types.js +143 -0
  123. package/dist/types.js.map +1 -0
  124. package/dist/web-tool.d.ts +35 -0
  125. package/dist/web-tool.d.ts.map +1 -0
  126. package/dist/web-tool.js +545 -0
  127. package/dist/web-tool.js.map +1 -0
  128. package/package.json +7 -5
  129. package/src/agents.ts +0 -299
  130. package/src/ambient.d.ts +0 -107
  131. package/src/batch/batch-bash.ts +0 -443
  132. package/src/batch/constants.ts +0 -128
  133. package/src/batch/execute.ts +0 -551
  134. package/src/batch/fuzzy-edit.ts +0 -323
  135. package/src/batch/index.ts +0 -494
  136. package/src/batch/render.ts +0 -81
  137. package/src/batch/symbols.ts +0 -341
  138. package/src/batch.ts +0 -28
  139. package/src/cli-args.ts +0 -315
  140. package/src/config.ts +0 -391
  141. package/src/executor.ts +0 -445
  142. package/src/flow.ts +0 -834
  143. package/src/hooks.ts +0 -294
  144. package/src/index.ts +0 -1132
  145. package/src/render-utils.ts +0 -205
  146. package/src/render.ts +0 -524
  147. package/src/runner-events.ts +0 -692
  148. package/src/session-mode.ts +0 -33
  149. package/src/sliding-prompt.ts +0 -144
  150. package/src/structured-output.ts +0 -195
  151. package/src/timed-bash.ts +0 -270
  152. package/src/transitions.ts +0 -86
  153. package/src/types.ts +0 -386
  154. package/src/web-tool.ts +0 -663
package/README.md CHANGED
@@ -45,7 +45,7 @@ pi install .
45
45
  - **Flow-state delegation** — six bundled specialist flows (`scout`, `debug`, `build`, `craft`, `audit`, `ideas`) plus custom flows via Markdown front-matter
46
46
  - **Isolated forked context** — each flow runs as an isolated `pi` child process with a session snapshot (or clean slate when configured)
47
47
  - **Parallel execution** — batch independent flows into one call with bounded concurrency
48
- - **Structured reports** — every flow returns `[Summary]`, `[Done]`, `[Not Done]`, `[Next Steps]`; optional JSON schema with files, actions, commands, and reasoning
48
+ - **Structured reports** — every flow returns structured output with `summary`, `files`, `actions`, `commands`, `notDone`, `nextSteps`, `reasoning`, and `notes`; optional JSON schema for machine-readable results
49
49
  - **Mechanically enriched commands** — bash commands in structured output are replaced with exact verbatim tool-call strings and annotated with `executionTime`
50
50
  - **Depth guards** — configurable max delegation depth (default: `3`)
51
51
  - **Session timeout modes** — child flows use controlled budgets: `fast` (300s), `default` (600s), `long` (900s), or `extreme_long` (1200s)
@@ -55,14 +55,12 @@ pi install .
55
55
  - **Model tiering & failover** — flows map to `lite` / `flash` / `full` tiers with primary + failover model chains
56
56
  - **Persistent flow mode** — switch global model strategies with `--flow-mode`; written to `settings.json` and remembered across sessions
57
57
  - **Flow-mode notification** — concise (`mode: name | lite: model · flash: model · full: model`) or verbose (with per-tier flow-name labels) startup message
58
- - **Auto-transition** — opt-in automatic queuing of follow-up flows based on the declarative transition matrix
59
58
  - **Unified batch tools** — `batch` (read/write/edit/delete) and `batch_read` replace separate file tools for cross-cutting work
60
59
  - **Web tool** — built-in `web` search (Brave + DuckDuckGo) and page fetch with HTML→Markdown conversion
61
60
  - **Sliding system prompt** — lightweight routing reminder injected before each user message, stripped from child snapshots to avoid duplication
62
61
  - **Session snapshot sanitization** — removes sliding prompts, reasoning/thinking artifacts, and non-inheritable content before forking; compresses prior flow results into compact context maps
63
62
  - **Shared context inheritance** — child flows receive the parent's sanitized session automatically; write forward-looking intents and let the child pick up context from its inherited snapshot
64
63
  - **Project flow confirmation** — prompts before running project-local flows from `.pi/agents/` for security
65
- - **Post-flow hooks** — automatic advisory messages suggesting follow-up flows (e.g., `build → audit`)
66
64
  - **Rich TUI rendering** — collapsed activity-panel view with per-flow stats, live countdowns, and expanded view with full reports and tool traces
67
65
  - **Smooth streaming metrics** — token counters and smoothed TPS increment tick-by-tick during active streaming
68
66
 
@@ -76,7 +74,7 @@ This approach delivers four concrete benefits:
76
74
 
77
75
  1. **Avoid duplicate tool calls** — every sub-agent launch no longer re-runs the same `read`, `grep`, or `bash` probes that the parent already performed.
78
76
  2. **Prevent context bloat** — long transcripts with repeated file listings and command outputs are kept out of the main conversation thread.
79
- 3. **Eliminate unnecessary noise** — the parent agent sees only structured results (`[Summary]`, `[Done]`, `[Not Done]`, `[Next Steps]`) instead of pages of intermediate reasoning.
77
+ 3. **Eliminate unnecessary noise** — the parent agent sees only structured results (`summary`, `notDone`, `nextSteps`, etc.) instead of pages of intermediate reasoning.
80
78
  4. **Preserve focus** — each flow stays locked on its intent because it isn't distracted by unrelated earlier messages.
81
79
 
82
80
  The result is faster, cheaper, and cleaner delegation: the main agent remains uncluttered while specialized flows do the heavy lifting in isolated contexts.
@@ -254,7 +252,7 @@ Only include fields that have data. Omit empty arrays; missing array fields are
254
252
 
255
253
  ---
256
254
 
257
- ## Post-Flow Hooks & Auto-Transitions
255
+ ## Post-Flow Advisory Messages
258
256
 
259
257
  When certain flows complete, the system injects advisory messages suggesting follow-up flows. This keeps the agent on the optimal path without requiring the user to manually chain flows.
260
258
 
@@ -273,28 +271,7 @@ When certain flows complete, the system injects advisory messages suggesting fol
273
271
  | `craft` | `build` | success | Plan ready. Consider running a [build] flow to implement the design. |
274
272
  | `ideas` | `craft` | success | Ideas explored. Consider running a [craft] flow to design the approach, or [build] to implement directly. |
275
273
 
276
- Hooks are smart: if the agent already included the suggested flow in the same batch, the advisory is suppressed to avoid redundancy.
277
-
278
- ### Auto-transition
279
-
280
- Enable `autoTransition: true` in `flowSettings` (or `--auto-transition`) to automatically queue follow-up flows without manual intervention. The system checks that the target flow exists, was not already requested, and would not create a cycle before queuing it.
281
-
282
- ### Extending hooks
283
-
284
- Hooks are registered via `registerHook()` in `hooks.ts`. Each hook defines a trigger (flow type + success requirement) and an action that returns advisory text.
285
-
286
- Example — a custom `scout → craft` hook:
287
-
288
- ```ts
289
- registerHook({
290
- name: "my/scout-to-craft",
291
- trigger: { flowTypes: ["scout"], onlyOnSuccess: true },
292
- action: (ctx) => ({
293
- content: "Consider running a [craft] flow to design a solution.",
294
- priority: 10,
295
- }),
296
- });
297
- ```
274
+ Advisories are smart: if the agent already included the suggested flow in the same batch, the advisory is suppressed to avoid redundancy.
298
275
 
299
276
  ---
300
277
 
@@ -429,7 +406,6 @@ You can also set flow runtime defaults under `flowSettings`:
429
406
  "maxConcurrency": 4,
430
407
  "toolOptimize": true,
431
408
  "structuredOutput": true,
432
- "autoTransition": false
433
409
  }
434
410
  }
435
411
  ```
@@ -440,7 +416,6 @@ You can also set flow runtime defaults under `flowSettings`:
440
416
  | `maxConcurrency` | `4` | Maximum parallel flows (capped to CPU count) |
441
417
  | `toolOptimize` | `true` | Use unified `batch`/`batch_read` instead of separate read/write/edit |
442
418
  | `structuredOutput` | `true` | Inject JSON structured-output instructions into flow prompts |
443
- | `autoTransition` | `false` | Automatically queue follow-up flows based on the transition matrix |
444
419
 
445
420
  Session mode precedence is:
446
421
 
@@ -464,7 +439,6 @@ per-flow sessionMode > --flow-session-mode > PI_FLOW_SESSION_MODE > flowSettings
464
439
  | `--flow-max-concurrency [n]` | Maximum parallel flows | `4` |
465
440
  | `--tool-optimize` | Use unified `batch`/`batch_read` | `true` |
466
441
  | `--no-tool-optimize` | Disable tool optimization; use legacy read/write/edit | — |
467
- | `--auto-transition` | Automatically queue follow-up flows | `false` |
468
442
  | `--structured-output` | Inject structured JSON output instructions | `true` |
469
443
  | `--no-structured-output` | Disable structured output injection | — |
470
444
 
package/agents/audit.md CHANGED
@@ -3,6 +3,7 @@ name: audit
3
3
  description: Audit security, quality, correctness, and apply fixes
4
4
  tools: batch, bash, find, grep, ls
5
5
  maxDepth: 0
6
+ tier: flash
6
7
  ---
7
8
 
8
9
  ## Mission
@@ -27,5 +28,3 @@ During this audit flow — your mission is to verify and remediate quality, secu
27
28
  - If a fix requires broader redesign, recommend [craft] in [Next Steps].
28
29
  - If root cause is unclear, recommend [debug] rather than guessing.
29
30
 
30
- ## Note
31
- Treat this as a clean-slate system rewrite, unless explicitly mentioned in the requirements. Perform a comprehensive migration with zero requirements for backwards compatibility. You must ensure that all residual code, variable names, test suites, and documentation are fully refactored and perfectly aligned with the new architecture.
package/agents/build.md CHANGED
@@ -3,6 +3,7 @@ name: build
3
3
  description: Implement features, fix bugs, write tests, deploy, and ship
4
4
  tools: batch, bash, find, grep, ls
5
5
  maxDepth: 0
6
+ tier: flash
6
7
  ---
7
8
 
8
9
  ## Mission
package/agents/craft.md CHANGED
@@ -3,27 +3,31 @@ name: craft
3
3
  description: Plan structure, break down requirements, design solutions
4
4
  tools: batch, bash, find, grep, ls
5
5
  maxDepth: 0
6
+ tier: full
6
7
  ---
7
8
 
8
9
  ## Mission
9
10
 
10
- During this craft flow — your mission is to design a clear plan. Be conservative: prefer existing patterns and proven conventions over novelty, and treat the conversation history above as background reference only.
11
+ During this craft flow — your mission is to design a clear, well-structured plan for implementation. Think architecturally: evaluate the full landscape, design for clean migration, and treat the conversation history above as background reference only.
11
12
 
12
13
  ## Workflow
13
14
 
14
15
  1. Understand — define the problem, constraints, existing behavior, and success criteria.
15
- 2. Explore — map relevant patterns and dependencies. Use `batch` with `o: "read"`, `s: <offset>`, and `l: <limit>` for targeted file reading instead of bash `sed`/`head`/`tail`.
16
- 3. Designchoose the simplest solution that works and fits existing patterns.
17
- 4. Plan — produce concrete ordered tasks and identify parallel vs sequential work.
18
- 5. Review — check risks, edge cases, test strategy, and handoff path before build.
16
+ 2. Explore — map relevant patterns, dependencies, and existing architecture. Use `batch` with `o: "read"`, `s: <offset>`, and `l: <limit>` for targeted file reading instead of bash `sed`/`head`/`tail`.
17
+ 3. Evaluateassess whether the change fits existing patterns or requires a clean migration. Prefer incremental improvement when safe; endorse full-cut redesign when the architecture demands it.
18
+ 4. Design — produce a concrete plan with ordered tasks, data flow, module boundaries, and interface contracts.
19
+ 5. Review — check risks, edge cases, test strategy, migration path, and handoff to build.
19
20
 
20
21
  ## Rules
21
22
 
22
23
  - Follow SOLID, DRY, and KISS.
23
24
  - Design for 10x, build for 1x.
24
- - Avoid tech debt; choose a maintainable approach or explain the trade-off.
25
- - Prefer explicit assumptions and constraints over hidden decisions.
25
+ - Prefer explicit assumptions and constraints over hidden decisions state what you assume and why.
26
+ - When redesigning, preserve data integrity and migration paths; never orphan existing consumers.
27
+ - Favor clean migration: if a redesign is warranted, cut fully rather than leaving half-measures.
28
+ - Document trade-offs explicitly when the optimal path is unclear.
26
29
  - Do not implement changes from this flow unless explicitly requested.
27
30
 
28
31
  ## Note
29
- Treat this as a clean-slate system rewrite, unless explicitly mentioned in the requirements. Perform a comprehensive migration with zero requirements for backwards compatibility. You must ensure that all residual code, variable names, test suites, and documentation are fully refactored and perfectly aligned with the new architecture.
32
+
33
+ This flow operates in design mode — produce plans and specifications, not implementations. When a clean-slate redesign is warranted by the requirements, embrace it fully: define the target architecture, migration steps, and rollback strategy. When incremental change suffices, prefer it. The key principle is intentional design over accidental complexity.
package/agents/debug.md CHANGED
@@ -3,6 +3,7 @@ name: debug
3
3
  description: Investigate logs, errors, stack traces, root causes
4
4
  tools: batch, bash, find, grep, ls
5
5
  maxDepth: 0
6
+ tier: lite
6
7
  ---
7
8
 
8
9
  ## Mission
@@ -28,5 +29,4 @@ During this debug flow — your mission is to investigate root cause. Be forensi
28
29
  - Documentation-only updates are required after finishing the work when relevant and safe; if no docs changed, explain why in the final report.
29
30
  - Do not implement product-code changes from this flow unless explicitly requested.
30
31
 
31
- ## Note
32
- Treat this as a clean-slate system rewrite, unless explicitly mentioned in the requirements. Perform a comprehensive migration with zero requirements for backwards compatibility. You must ensure that all residual code, variable names, test suites, and documentation are fully refactored and perfectly aligned with the new architecture.
32
+
package/agents/ideas.md CHANGED
@@ -3,6 +3,7 @@ name: ideas
3
3
  description: Generate ideas, explore possibilities, and think creatively using inherited context as background
4
4
  tools: batch, bash
5
5
  maxDepth: 0
6
+ tier: full
6
7
  ---
7
8
 
8
9
  ## Mission
package/agents/scout.md CHANGED
@@ -3,6 +3,7 @@ name: scout
3
3
  description: Discover files, trace code paths, map architecture
4
4
  tools: batch, bash, find, grep, ls
5
5
  maxDepth: 0
6
+ tier: lite
6
7
  ---
7
8
 
8
9
  ## Mission
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Flow discovery and configuration.
3
+ *
4
+ * Flows are Markdown files with YAML frontmatter that define name, description,
5
+ * optional model/tools, and a system prompt body.
6
+ *
7
+ * Lookup locations:
8
+ * - User flows: ~/.pi/agent/agents/*.md by default, or
9
+ * $PI_CODING_AGENT_DIR/agents/*.md when the env var is set
10
+ * - Project flows: .pi/agents/*.md (walks up from cwd)
11
+ */
12
+ export type FlowScope = "user" | "project" | "both" | "bundled" | "all";
13
+ export type FlowTier = "lite" | "flash" | "full";
14
+ export interface FlowConfig {
15
+ name: string;
16
+ description: string;
17
+ tools?: string[];
18
+ model?: string;
19
+ thinking?: string;
20
+ maxDepth?: number;
21
+ inheritContext?: boolean;
22
+ tier?: FlowTier;
23
+ systemPrompt: string;
24
+ source: "user" | "project" | "bundled";
25
+ filePath: string;
26
+ }
27
+ export interface FlowDiscoveryResult {
28
+ flows: FlowConfig[];
29
+ projectFlowsDir: string | null;
30
+ }
31
+ /** Determine the model tier for a given flow name. */
32
+ export declare function getFlowTier(flowName: string): FlowTier;
33
+ /** Return the bundled flow names associated with a given tier. */
34
+ export declare function getTierFlowNames(tier: FlowTier): string[];
35
+ /**
36
+ * Discover all available flows according to the requested scope.
37
+ *
38
+ * Precedence is: bundled < user < project.
39
+ */
40
+ export declare function discoverFlows(cwd: string, scope: FlowScope): FlowDiscoveryResult;
41
+ //# sourceMappingURL=agents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,CAAC;AAExE,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEjD,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAAC;IACvC,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,sDAAsD;AACtD,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAetD;AAED,kEAAkE;AAClE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,QAAQ,GAAG,MAAM,EAAE,CASzD;AA2MD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,mBAAmB,CAsBhF"}
package/dist/agents.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Flow discovery and configuration.
3
+ *
4
+ * Flows are Markdown files with YAML frontmatter that define name, description,
5
+ * optional model/tools, and a system prompt body.
6
+ *
7
+ * Lookup locations:
8
+ * - User flows: ~/.pi/agent/agents/*.md by default, or
9
+ * $PI_CODING_AGENT_DIR/agents/*.md when the env var is set
10
+ * - Project flows: .pi/agents/*.md (walks up from cwd)
11
+ */
12
+ import { parseFrontmatter } from "@mariozechner/pi-coding-agent";
13
+ import * as fs from "node:fs";
14
+ import * as os from "node:os";
15
+ import * as path from "node:path";
16
+ /** Determine the model tier for a given flow name. */
17
+ export function getFlowTier(flowName) {
18
+ const normalized = flowName.toLowerCase().trim();
19
+ switch (normalized) {
20
+ case "scout":
21
+ case "debug":
22
+ return "lite";
23
+ case "build":
24
+ case "audit":
25
+ return "flash";
26
+ case "ideas":
27
+ case "craft":
28
+ return "full";
29
+ default:
30
+ return "flash";
31
+ }
32
+ }
33
+ /** Return the bundled flow names associated with a given tier. */
34
+ export function getTierFlowNames(tier) {
35
+ switch (tier) {
36
+ case "lite":
37
+ return ["scout", "debug"];
38
+ case "flash":
39
+ return ["build", "audit"];
40
+ case "full":
41
+ return ["ideas", "craft"];
42
+ }
43
+ }
44
+ // ---------------------------------------------------------------------------
45
+ // Internal helpers
46
+ // ---------------------------------------------------------------------------
47
+ function isDirectory(p) {
48
+ try {
49
+ return fs.statSync(p).isDirectory();
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
55
+ function getUserFlowsDir() {
56
+ const configDir = process.env["PI_CODING_AGENT_DIR"]?.trim() || path.join(os.homedir(), ".pi", "agent");
57
+ return path.join(configDir, "agents");
58
+ }
59
+ /** Get the bundled flows directory from the plugin's location. */
60
+ function getBundledFlowsDir() {
61
+ // Method 1: import.meta.url (ESM)
62
+ // When source lives in src/, agents/ is one level up at the package root.
63
+ try {
64
+ if (import.meta.url) {
65
+ const pluginDir = path.dirname(new URL(import.meta.url).pathname);
66
+ // Check same directory first, then parent (for src/ layout)
67
+ for (const base of [pluginDir, path.dirname(pluginDir)]) {
68
+ const dir = path.join(base, "agents");
69
+ if (fs.existsSync(dir))
70
+ return dir;
71
+ }
72
+ }
73
+ }
74
+ catch { }
75
+ // Method 2: __dirname (CommonJS / jiti)
76
+ try {
77
+ if (typeof __dirname !== "undefined") {
78
+ for (const base of [__dirname, path.dirname(__dirname)]) {
79
+ const dir = path.join(base, "agents");
80
+ if (fs.existsSync(dir))
81
+ return dir;
82
+ }
83
+ }
84
+ }
85
+ catch { }
86
+ // Method 3: Find from require.resolve
87
+ try {
88
+ const resolved = require.resolve("pi-agent-flow/package.json");
89
+ const dir = path.join(path.dirname(resolved), "agents");
90
+ if (fs.existsSync(dir))
91
+ return dir;
92
+ }
93
+ catch { }
94
+ // Fallback: cwd
95
+ return path.join(process.cwd(), "agents");
96
+ }
97
+ /** Walk up from `cwd` looking for a `.pi/agents` directory. */
98
+ function findNearestProjectFlowsDir(cwd) {
99
+ let dir = cwd;
100
+ while (true) {
101
+ const candidate = path.join(dir, ".pi", "agents");
102
+ if (isDirectory(candidate))
103
+ return candidate;
104
+ const parent = path.dirname(dir);
105
+ if (parent === dir)
106
+ return null;
107
+ dir = parent;
108
+ }
109
+ }
110
+ /** Parse a single flow markdown file into a FlowConfig. Returns null on skip. */
111
+ function parseFlowFile(filePath, source) {
112
+ let content;
113
+ try {
114
+ content = fs.readFileSync(filePath, "utf-8");
115
+ }
116
+ catch {
117
+ return null;
118
+ }
119
+ let parsed;
120
+ try {
121
+ parsed = parseFrontmatter(content);
122
+ }
123
+ catch (err) {
124
+ const message = err instanceof Error ? err.message : String(err);
125
+ console.warn(`[pi-agent-flow] Skipping invalid flow file "${filePath}": ${message}`);
126
+ return null;
127
+ }
128
+ const frontmatter = parsed.frontmatter ?? {};
129
+ const body = parsed.body ?? "";
130
+ const name = typeof frontmatter.name === "string" ? frontmatter.name.trim().toLowerCase() : "";
131
+ const description = typeof frontmatter.description === "string" ? frontmatter.description.trim() : "";
132
+ if (!name || !description) {
133
+ if (!name)
134
+ console.warn(`[pi-agent-flow] Skipping flow file "${filePath}": missing or empty 'name' field.`);
135
+ if (!description)
136
+ console.warn(`[pi-agent-flow] Skipping flow file "${filePath}": missing or empty 'description' field.`);
137
+ return null;
138
+ }
139
+ // Warn about unknown frontmatter keys
140
+ const knownKeys = new Set([
141
+ "name", "description", "tools", "model", "thinking",
142
+ "maxDepth", "inheritContext", "tier",
143
+ ]);
144
+ for (const key of Object.keys(frontmatter)) {
145
+ if (!knownKeys.has(key)) {
146
+ console.warn(`[pi-agent-flow] Unknown frontmatter key "${key}" in "${filePath}". This field will be ignored.`);
147
+ }
148
+ }
149
+ let tools;
150
+ if (typeof frontmatter.tools === "string") {
151
+ const parsedTools = frontmatter.tools
152
+ .split(",")
153
+ .map((t) => t.trim())
154
+ .filter(Boolean);
155
+ if (parsedTools.length > 0)
156
+ tools = parsedTools;
157
+ }
158
+ else if (Array.isArray(frontmatter.tools)) {
159
+ const parsedTools = frontmatter.tools
160
+ .filter((t) => typeof t === "string")
161
+ .map((t) => t.trim())
162
+ .filter(Boolean);
163
+ if (parsedTools.length > 0)
164
+ tools = parsedTools;
165
+ }
166
+ else if (frontmatter.tools !== undefined) {
167
+ console.warn(`[pi-agent-flow] Ignoring invalid tools field in "${filePath}". Expected a comma-separated string or string array.`);
168
+ }
169
+ let maxDepth;
170
+ if (typeof frontmatter.maxDepth === "number") {
171
+ maxDepth = frontmatter.maxDepth;
172
+ }
173
+ else if (typeof frontmatter.maxDepth === "string") {
174
+ const parsed = Number(frontmatter.maxDepth);
175
+ if (Number.isFinite(parsed) && parsed >= 0)
176
+ maxDepth = parsed;
177
+ }
178
+ let inheritContext;
179
+ if (typeof frontmatter.inheritContext === "boolean") {
180
+ inheritContext = frontmatter.inheritContext;
181
+ }
182
+ else if (typeof frontmatter.inheritContext === "string") {
183
+ const normalized = frontmatter.inheritContext.trim().toLowerCase();
184
+ if (normalized === "true" || normalized === "yes" || normalized === "1") {
185
+ inheritContext = true;
186
+ }
187
+ else if (normalized === "false" || normalized === "no" || normalized === "0") {
188
+ inheritContext = false;
189
+ }
190
+ else {
191
+ console.warn(`[pi-agent-flow] Ignoring invalid inheritContext value "${frontmatter.inheritContext}" in "${filePath}". Expected true/false.`);
192
+ }
193
+ }
194
+ else if (frontmatter.inheritContext !== undefined) {
195
+ console.warn(`[pi-agent-flow] Ignoring invalid inheritContext field in "${filePath}". Expected boolean or string.`);
196
+ }
197
+ // Tier: prefer explicit frontmatter, fall back to name-based inference
198
+ let tier;
199
+ if (typeof frontmatter.tier === "string") {
200
+ const normalized = frontmatter.tier.trim().toLowerCase();
201
+ if (normalized === "lite" || normalized === "flash" || normalized === "full") {
202
+ tier = normalized;
203
+ }
204
+ else {
205
+ console.warn(`[pi-agent-flow] Ignoring invalid tier "${frontmatter.tier}" in "${filePath}". Expected lite, flash, or full.`);
206
+ }
207
+ }
208
+ return {
209
+ name,
210
+ description,
211
+ tools,
212
+ model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
213
+ thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
214
+ maxDepth,
215
+ inheritContext,
216
+ tier: tier ?? getFlowTier(name),
217
+ systemPrompt: body,
218
+ source,
219
+ filePath,
220
+ };
221
+ }
222
+ /** Load all flow definitions from a directory. */
223
+ function loadFlowsFromDir(dir, source) {
224
+ if (!fs.existsSync(dir))
225
+ return [];
226
+ let entries;
227
+ try {
228
+ entries = fs.readdirSync(dir, { withFileTypes: true });
229
+ }
230
+ catch {
231
+ return [];
232
+ }
233
+ entries.sort((a, b) => a.name.localeCompare(b.name));
234
+ const flows = [];
235
+ for (const entry of entries) {
236
+ if (!entry.name.endsWith(".md"))
237
+ continue;
238
+ if (!entry.isFile() && !entry.isSymbolicLink())
239
+ continue;
240
+ const flow = parseFlowFile(path.join(dir, entry.name), source);
241
+ if (flow)
242
+ flows.push(flow);
243
+ }
244
+ return flows;
245
+ }
246
+ function mergeFlows(...groups) {
247
+ const flowMap = new Map();
248
+ for (const group of groups) {
249
+ for (const flow of group)
250
+ flowMap.set(flow.name.toLowerCase(), flow);
251
+ }
252
+ return Array.from(flowMap.values());
253
+ }
254
+ // ---------------------------------------------------------------------------
255
+ // Public API
256
+ // ---------------------------------------------------------------------------
257
+ /**
258
+ * Discover all available flows according to the requested scope.
259
+ *
260
+ * Precedence is: bundled < user < project.
261
+ */
262
+ export function discoverFlows(cwd, scope) {
263
+ const bundledFlowsDir = getBundledFlowsDir();
264
+ const userFlowsDir = getUserFlowsDir();
265
+ const projectFlowsDir = findNearestProjectFlowsDir(cwd);
266
+ const bundledFlows = scope === "user" || scope === "project" ? [] : loadFlowsFromDir(bundledFlowsDir, "bundled");
267
+ const userFlows = scope === "project" || scope === "bundled" ? [] : loadFlowsFromDir(userFlowsDir, "user");
268
+ const projectFlows = scope === "user" || scope === "bundled" || !projectFlowsDir ? [] : loadFlowsFromDir(projectFlowsDir, "project");
269
+ if (scope === "bundled") {
270
+ return { flows: bundledFlows, projectFlowsDir };
271
+ }
272
+ if (scope === "user") {
273
+ return { flows: mergeFlows(bundledFlows, userFlows), projectFlowsDir };
274
+ }
275
+ if (scope === "project") {
276
+ return { flows: mergeFlows(projectFlows), projectFlowsDir };
277
+ }
278
+ return {
279
+ flows: mergeFlows(bundledFlows, userFlows, projectFlows),
280
+ projectFlowsDir,
281
+ };
282
+ }
283
+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AS,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IAC3G,MAAM,YAAY,GAAG,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;IAErI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,CAAC;IACjD,CAAC;IACD,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACtB,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,YAAY,EAAE,SAAS,CAAC,EAAE,eAAe,EAAE,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,YAAY,CAAC,EAAE,eAAe,EAAE,CAAC;IAC7D,CAAC;IACD,OAAO;QACN,KAAK,EAAE,UAAU,CAAC,YAAY,EAAE,SAAS,EAAE,YAAY,CAAC;QACxD,eAAe;KACf,CAAC;AACH,CAAC"}
@@ -0,0 +1,87 @@
1
+ import { type BashOpResult, type PendingBashResult } from "./constants.js";
2
+ export interface TrackedBashResult {
3
+ id: string;
4
+ command: string;
5
+ status: "ok" | "error" | "aborted";
6
+ exitCode?: number;
7
+ stdout: string;
8
+ stderr: string;
9
+ duration: number;
10
+ timingTier: string;
11
+ }
12
+ /**
13
+ * Process tracker for batch bash operations.
14
+ * Both the `batch` tool (launch side) and `batch_bash_poll` tool (read side)
15
+ * share the same instance.
16
+ */
17
+ export declare class BashProcessTracker {
18
+ private running;
19
+ private completed;
20
+ /** Launch a bash command. Returns immediately; the process runs in the background. */
21
+ launch(id: string, command: string, cwd: string, signal?: AbortSignal): void;
22
+ /** Check if a command is still running. */
23
+ isRunning(id: string): boolean;
24
+ /** Get the last N lines of a running process's stdout. */
25
+ getRunningTail(id: string): string;
26
+ /** Get the command of a running process. */
27
+ getRunningCommand(id: string): string | undefined;
28
+ /** Get the result of a completed/aborted command. Does NOT remove from cache. */
29
+ peekCompleted(id: string): TrackedBashResult | undefined;
30
+ /** Get the result of a completed/aborted command. Removes from completed cache. */
31
+ popCompleted(id: string): TrackedBashResult | undefined;
32
+ /** Get the start time of a running process. */
33
+ getStartedAt(id: string): number | undefined;
34
+ /** Check if a command has completed. */
35
+ hasCompleted(id: string): boolean;
36
+ /** Abort a running process by id. */
37
+ private abortById;
38
+ /** Abort all running processes (cleanup). */
39
+ abortAll(): void;
40
+ }
41
+ /** Generate a short random ID for bash ops that don't provide one. */
42
+ export declare function generateBashId(): string;
43
+ /** Normalize a bash op from prepareArguments into a canonical form. */
44
+ export declare function normalizeBashOp(raw: Record<string, unknown>): Record<string, unknown>;
45
+ /**
46
+ * Execute a batch of bash ops concurrently.
47
+ *
48
+ * Launches all commands in parallel, then waits until all finish or the
49
+ * soft timeout expires. The soft timeout is the max of per-op `t` values
50
+ * (if any), or the global default. Commands that haven't finished within
51
+ * the timeout are returned as "pending" with the last N lines of output.
52
+ * They continue running in the background and can be polled via batch_bash_poll.
53
+ */
54
+ export declare function executeBatchBash(ops: Array<{
55
+ i: string;
56
+ c: string;
57
+ t?: number;
58
+ h?: string;
59
+ }>, defaultCwd: string, tracker: BashProcessTracker, signal?: AbortSignal, softTimeoutMs?: number): Promise<BashOpResult[]>;
60
+ /** Poll for completed bash results. */
61
+ export declare function pollBatchBashResults(ids: string[], tracker: BashProcessTracker): PendingBashResult[];
62
+ export declare const BatchBashPollParams: any;
63
+ export declare function createBatchBashPollTool(tracker: BashProcessTracker): {
64
+ name: string;
65
+ label: string;
66
+ description: string;
67
+ promptSnippet: string;
68
+ promptGuidelines: string[];
69
+ parameters: any;
70
+ prepareArguments(input: unknown): unknown;
71
+ execute(_toolCallId: string, input: unknown, _signal?: AbortSignal, _onUpdate?: unknown): Promise<{
72
+ content: {
73
+ type: string;
74
+ text: string;
75
+ }[];
76
+ details: {
77
+ results: PendingBashResult[];
78
+ };
79
+ } | {
80
+ content: {
81
+ type: string;
82
+ text: string;
83
+ }[];
84
+ isError: boolean;
85
+ }>;
86
+ };
87
+ //# sourceMappingURL=batch-bash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-bash.d.ts","sourceRoot":"","sources":["../../src/batch/batch-bash.ts"],"names":[],"mappings":"AAiBA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAGtB,MAAM,gBAAgB,CAAC;AAgBxB,MAAM,WAAW,iBAAiB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,IAAI,GAAG,OAAO,GAAG,SAAS,CAAC;IACnC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,OAAO,CAAqC;IACpD,OAAO,CAAC,SAAS,CAAwC;IAEzD,sFAAsF;IACtF,MAAM,CACL,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,WAAW,GAClB,IAAI;IAoFP,2CAA2C;IAC3C,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAI9B,0DAA0D;IAC1D,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM;IAOlC,4CAA4C;IAC5C,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAIjD,iFAAiF;IACjF,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,iBAA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