pi-crew 0.1.51 → 0.2.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 (239) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/README.md +176 -781
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +70 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/actions-reference.md +595 -0
  14. package/docs/commands-reference.md +347 -0
  15. package/docs/runtime-flow.md +148 -148
  16. package/index.ts +6 -6
  17. package/package.json +99 -99
  18. package/skills/async-worker-recovery/SKILL.md +42 -42
  19. package/skills/context-artifact-hygiene/SKILL.md +52 -52
  20. package/skills/delegation-patterns/SKILL.md +54 -54
  21. package/skills/mailbox-interactive/SKILL.md +40 -40
  22. package/skills/model-routing-context/SKILL.md +39 -39
  23. package/skills/multi-perspective-review/SKILL.md +58 -58
  24. package/skills/observability-reliability/SKILL.md +41 -41
  25. package/skills/orchestration/SKILL.md +157 -157
  26. package/skills/ownership-session-security/SKILL.md +41 -41
  27. package/skills/pi-extension-lifecycle/SKILL.md +39 -39
  28. package/skills/requirements-to-task-packet/SKILL.md +63 -63
  29. package/skills/resource-discovery-config/SKILL.md +41 -41
  30. package/skills/runtime-state-reader/SKILL.md +44 -44
  31. package/skills/secure-agent-orchestration-review/SKILL.md +45 -45
  32. package/skills/state-mutation-locking/SKILL.md +42 -42
  33. package/skills/systematic-debugging/SKILL.md +67 -67
  34. package/skills/ui-render-performance/SKILL.md +39 -39
  35. package/skills/verification-before-done/SKILL.md +57 -57
  36. package/skills/worktree-isolation/SKILL.md +39 -39
  37. package/src/adapters/claude-adapter.ts +25 -0
  38. package/src/adapters/codex-adapter.ts +21 -0
  39. package/src/adapters/cursor-adapter.ts +17 -0
  40. package/src/adapters/export-util.ts +137 -0
  41. package/src/adapters/index.ts +15 -0
  42. package/src/adapters/registry.ts +18 -0
  43. package/src/adapters/types.ts +23 -0
  44. package/src/agents/agent-config.ts +2 -0
  45. package/src/agents/agent-search.ts +98 -98
  46. package/src/agents/discover-agents.ts +2 -1
  47. package/src/config/config.ts +13 -1
  48. package/src/config/drift-detector.ts +211 -0
  49. package/src/config/markers.ts +327 -0
  50. package/src/config/resilient-parser.ts +108 -0
  51. package/src/config/suggestions.ts +74 -0
  52. package/src/extension/cross-extension-rpc.ts +103 -94
  53. package/src/extension/project-init.ts +21 -1
  54. package/src/extension/register.ts +45 -14
  55. package/src/extension/registration/commands.ts +77 -8
  56. package/src/extension/registration/subagent-tools.ts +10 -1
  57. package/src/extension/registration/team-tool.ts +10 -1
  58. package/src/extension/registration/viewers.ts +48 -34
  59. package/src/extension/run-bundle-schema.ts +89 -89
  60. package/src/extension/run-import.ts +25 -1
  61. package/src/extension/run-index.ts +5 -1
  62. package/src/extension/run-maintenance.ts +142 -68
  63. package/src/extension/team-manager-command.ts +10 -1
  64. package/src/extension/team-tool/doctor.ts +28 -3
  65. package/src/extension/team-tool/handle-settings.ts +195 -188
  66. package/src/extension/team-tool/inspect.ts +41 -41
  67. package/src/extension/team-tool/intent-policy.ts +42 -42
  68. package/src/extension/team-tool/lifecycle-actions.ts +27 -8
  69. package/src/extension/team-tool/plan.ts +19 -19
  70. package/src/extension/team-tool/run.ts +12 -1
  71. package/src/extension/team-tool.ts +11 -1
  72. package/src/i18n.ts +184 -184
  73. package/src/observability/exporters/otlp-exporter.ts +92 -77
  74. package/src/prompt/prompt-runtime.ts +72 -72
  75. package/src/runtime/agent-memory.ts +72 -72
  76. package/src/runtime/agent-observability.ts +114 -114
  77. package/src/runtime/async-marker.ts +26 -26
  78. package/src/runtime/attention-events.ts +28 -28
  79. package/src/runtime/auto-resume.ts +100 -0
  80. package/src/runtime/background-runner.ts +11 -1
  81. package/src/runtime/cancellation-token.ts +89 -89
  82. package/src/runtime/cancellation.ts +61 -61
  83. package/src/runtime/capability-inventory.ts +116 -116
  84. package/src/runtime/child-pi.ts +7 -2
  85. package/src/runtime/compaction-summary.ts +271 -0
  86. package/src/runtime/completion-guard.ts +190 -190
  87. package/src/runtime/crash-recovery.ts +33 -0
  88. package/src/runtime/delta-conflict.ts +360 -0
  89. package/src/runtime/direct-run.ts +35 -35
  90. package/src/runtime/foreground-control.ts +82 -82
  91. package/src/runtime/green-contract.ts +46 -46
  92. package/src/runtime/group-join.ts +106 -106
  93. package/src/runtime/heartbeat-gradient.ts +28 -28
  94. package/src/runtime/heartbeat-watcher.ts +124 -124
  95. package/src/runtime/iteration-hooks.ts +262 -0
  96. package/src/runtime/live-agent-control.ts +88 -88
  97. package/src/runtime/live-control-realtime.ts +36 -36
  98. package/src/runtime/live-extension-bridge.ts +150 -150
  99. package/src/runtime/live-irc.ts +92 -92
  100. package/src/runtime/live-session-health.ts +100 -100
  101. package/src/runtime/loop-gates.ts +129 -0
  102. package/src/runtime/metric-parser.ts +40 -0
  103. package/src/runtime/notebook-helpers.ts +90 -90
  104. package/src/runtime/orphan-sentinel.ts +7 -7
  105. package/src/runtime/parallel-research.ts +44 -44
  106. package/src/runtime/phase-progress.ts +217 -0
  107. package/src/runtime/pi-args.ts +38 -11
  108. package/src/runtime/pi-json-output.ts +111 -111
  109. package/src/runtime/pi-spawn.ts +57 -7
  110. package/src/runtime/policy-engine.ts +79 -79
  111. package/src/runtime/post-checks.ts +122 -0
  112. package/src/runtime/progress-event-coalescer.ts +43 -43
  113. package/src/runtime/prose-compressor.ts +164 -164
  114. package/src/runtime/recovery-recipes.ts +74 -74
  115. package/src/runtime/result-extractor.ts +121 -121
  116. package/src/runtime/role-permission.ts +39 -39
  117. package/src/runtime/sensitive-paths.ts +2 -2
  118. package/src/runtime/session-resources.ts +25 -25
  119. package/src/runtime/session-snapshot.ts +59 -59
  120. package/src/runtime/session-usage.ts +79 -79
  121. package/src/runtime/sidechain-output.ts +29 -29
  122. package/src/runtime/stream-preview.ts +177 -177
  123. package/src/runtime/supervisor-contact.ts +59 -59
  124. package/src/runtime/task-display.ts +38 -38
  125. package/src/runtime/task-graph.ts +207 -0
  126. package/src/runtime/task-quality.ts +207 -0
  127. package/src/runtime/task-runner/capabilities.ts +78 -78
  128. package/src/runtime/task-runner/live-executor.ts +7 -1
  129. package/src/runtime/task-runner/progress.ts +119 -119
  130. package/src/runtime/task-runner/prompt-pipeline.ts +64 -64
  131. package/src/runtime/task-runner/result-utils.ts +14 -14
  132. package/src/runtime/task-runner/run-projection.ts +103 -103
  133. package/src/runtime/task-runner/state-helpers.ts +22 -22
  134. package/src/runtime/team-runner.ts +117 -7
  135. package/src/runtime/worker-heartbeat.ts +21 -21
  136. package/src/runtime/worker-startup.ts +57 -57
  137. package/src/runtime/workflow-state.ts +187 -0
  138. package/src/runtime/workspace-tree.ts +298 -298
  139. package/src/schema/config-schema.ts +11 -0
  140. package/src/schema/validation-types.ts +148 -0
  141. package/src/skills/skill-templates.ts +374 -0
  142. package/src/state/active-run-registry.ts +35 -11
  143. package/src/state/atomic-write.ts +33 -26
  144. package/src/state/contracts.ts +1 -0
  145. package/src/state/event-reconstructor.ts +217 -0
  146. package/src/state/locks.ts +2 -13
  147. package/src/state/mailbox.ts +4 -3
  148. package/src/state/state-store.ts +32 -14
  149. package/src/state/task-claims.ts +44 -44
  150. package/src/state/types.ts +9 -0
  151. package/src/state/usage.ts +29 -29
  152. package/src/subagents/async-entry.ts +1 -1
  153. package/src/subagents/index.ts +3 -3
  154. package/src/subagents/live/control.ts +1 -1
  155. package/src/subagents/live/manager.ts +1 -1
  156. package/src/subagents/live/realtime.ts +1 -1
  157. package/src/subagents/live/session-runtime.ts +1 -1
  158. package/src/subagents/manager.ts +1 -1
  159. package/src/subagents/spawn.ts +1 -1
  160. package/src/teams/team-serializer.ts +38 -38
  161. package/src/types/diff.d.ts +18 -18
  162. package/src/ui/crew-footer.ts +101 -101
  163. package/src/ui/crew-select-list.ts +111 -111
  164. package/src/ui/crew-widget.ts +5 -2
  165. package/src/ui/dashboard-panes/cancellation-pane.ts +42 -42
  166. package/src/ui/dashboard-panes/capability-pane.ts +59 -59
  167. package/src/ui/dashboard-panes/mailbox-pane.ts +35 -35
  168. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  169. package/src/ui/dashboard-panes/progress-pane.ts +11 -0
  170. package/src/ui/dynamic-border.ts +25 -25
  171. package/src/ui/layout-primitives.ts +106 -106
  172. package/src/ui/loaders.ts +158 -158
  173. package/src/ui/render-coalescer.ts +51 -51
  174. package/src/ui/render-diff.ts +119 -119
  175. package/src/ui/render-scheduler.ts +143 -143
  176. package/src/ui/run-action-dispatcher.ts +10 -1
  177. package/src/ui/spinner.ts +17 -17
  178. package/src/ui/status-colors.ts +58 -58
  179. package/src/ui/syntax-highlight.ts +116 -116
  180. package/src/ui/transcript-entries.ts +258 -258
  181. package/src/utils/completion-dedupe.ts +63 -63
  182. package/src/utils/frontmatter.ts +68 -68
  183. package/src/utils/git.ts +262 -262
  184. package/src/utils/ids.ts +17 -17
  185. package/src/utils/incremental-reader.ts +104 -104
  186. package/src/utils/names.ts +27 -27
  187. package/src/utils/redaction.ts +44 -44
  188. package/src/utils/safe-paths.ts +47 -47
  189. package/src/utils/scan-cache.ts +136 -136
  190. package/src/utils/sleep.ts +40 -26
  191. package/src/utils/task-name-generator.ts +337 -337
  192. package/src/workflows/validate-workflow.ts +40 -40
  193. package/src/worktree/branch-freshness.ts +45 -45
  194. package/teams/default.team.md +12 -12
  195. package/teams/fast-fix.team.md +11 -11
  196. package/teams/implementation.team.md +18 -18
  197. package/teams/parallel-research.team.md +14 -14
  198. package/teams/research.team.md +11 -11
  199. package/teams/review.team.md +12 -12
  200. package/workflows/default.workflow.md +30 -29
  201. package/workflows/fast-fix.workflow.md +23 -22
  202. package/workflows/implementation.workflow.md +43 -43
  203. package/workflows/parallel-research.workflow.md +46 -46
  204. package/workflows/research.workflow.md +22 -22
  205. package/workflows/review.workflow.md +30 -30
  206. package/docs/refactor-tasks-phase3.md +0 -394
  207. package/docs/refactor-tasks-phase4.md +0 -564
  208. package/docs/refactor-tasks-phase5.md +0 -402
  209. package/docs/refactor-tasks-phase6.md +0 -662
  210. package/docs/refactor-tasks.md +0 -1484
  211. package/docs/research/AGENT-EXECUTION-ARCHITECTURE.md +0 -261
  212. package/docs/research/AGENT-LIFECYCLE-COMPARISON.md +0 -111
  213. package/docs/research/AUDIT_OH_MY_PI.md +0 -261
  214. package/docs/research/AUDIT_PI_CREW.md +0 -457
  215. package/docs/research/CAVEMAN-DEEP-RESEARCH.md +0 -281
  216. package/docs/research/COMPARISON_OH_MY_PI_VS_PI_CREW.md +0 -264
  217. package/docs/research/DEEP-RESEARCH-PI-POWERBAR.md +0 -343
  218. package/docs/research/DEEP_RESEARCH_SUBAGENT_ARCHITECTURE.md +0 -480
  219. package/docs/research/GAP_CLOSURE_IMPLEMENTATION_PLAN.md +0 -354
  220. package/docs/research/IMPLEMENTATION_PLAN.md +0 -385
  221. package/docs/research/LIVE-SESSION-PRODUCTION-READY-PLAN.md +0 -502
  222. package/docs/research/OH-MY-PI-DEEP-RESEARCH-v14.7.6.md +0 -266
  223. package/docs/research/REMAINING-GAPS-PLAN.md +0 -363
  224. package/docs/research/SESSION-SUMMARY-2026-05-08.md +0 -146
  225. package/docs/research/UI-RESPONSIVENESS-AUDIT.md +0 -173
  226. package/docs/research-awesome-agent-skills-distillation.md +0 -100
  227. package/docs/research-extension-examples.md +0 -297
  228. package/docs/research-extension-system.md +0 -324
  229. package/docs/research-oh-my-pi-distillation.md +0 -369
  230. package/docs/research-optimization-plan.md +0 -548
  231. package/docs/research-phase10-distillation.md +0 -199
  232. package/docs/research-phase11-distillation.md +0 -201
  233. package/docs/research-phase8-operator-experience-plan.md +0 -819
  234. package/docs/research-phase9-observability-reliability-plan.md +0 -1190
  235. package/docs/research-pi-coding-agent.md +0 -357
  236. package/docs/research-source-pi-crew-reference.md +0 -174
  237. package/docs/research-ui-optimization-plan.md +0 -480
  238. package/docs/source-runtime-refactor-map.md +0 -107
  239. package/src/utils/atomic-write.ts +0 -33
@@ -1,357 +0,0 @@
1
- # Research: pi-mono coding-agent Deep Read
2
-
3
- > Ngày: 2026-04-29 | Read-only research | Source: `source/pi-mono/packages/coding-agent/`
4
-
5
- ## 1. Vai trò trong monorepo
6
-
7
- `@mariozechner/pi-coding-agent` là package trung tâm nhất của pi-mono. Nó chứa CLI binary `pi`,
8
- toàn bộ agent session lifecycle, extension host system, 3 run modes, 7 built-in tools, session
9
- persistence, compaction, branch summarization, và SDK cho programmatic usage.
10
-
11
- Package version: `0.70.5` (lockstep với toàn bộ monorepo).
12
-
13
- ## 2. Cấu trúc source
14
-
15
- ```
16
- src/
17
- ├── cli.ts # Binary entry point (shebang #!/usr/bin/env node)
18
- ├── main.ts # CLI logic: parse args, dispatch mode (731 dòng)
19
- ├── index.ts # Public API exports (~250 dòng re-exports)
20
- ├── config.ts # Path constants (agentDir, VERSION, APP_NAME)
21
- ├── cli/ # CLI subsystems
22
- │ ├── args.ts # Argument parsing (yargs-style)
23
- │ ├── file-processor.ts # @file argument expansion
24
- │ ├── initial-message.ts # Build initial prompt from args/stdin
25
- │ ├── list-models.ts # --list-models output
26
- │ └── session-picker.ts # Interactive session selection
27
- ├── core/ # ═══ CORE LAYER ═══
28
- │ ├── agent-session.ts # AgentSession class (3099 dòng) — TRUNG TÂM
29
- │ ├── agent-session-runtime.ts # AgentSessionRuntime wrapper (session replacement)
30
- │ ├── agent-session-services.ts # Dịch vụ tạo cwd-bound runtime
31
- │ ├── sdk.ts # createAgentSession() public factory (~408 dòng)
32
- │ ├── session-manager.ts # Session file I/O, entries, tree (1425 dòng)
33
- │ ├── settings-manager.ts # settings.json manager (~1069 dòng)
34
- │ ├── system-prompt.ts # System prompt builder (172 dòng)
35
- │ ├── resource-loader.ts # Load extensions/skills/prompts/themes (~920 dòng)
36
- │ ├── model-registry.ts # Model + auth registry
37
- │ ├── model-resolver.ts # Model resolution / scope / fallback
38
- │ ├── keybindings.ts # Keybinding manager (KeybindingsManager)
39
- │ ├── messages.ts # AgentMessage type definitions + converters
40
- │ ├── bash-executor.ts # Bash execution abstraction layer
41
- │ ├── prompt-templates.ts # File-based prompt templates (@file expansion)
42
- │ ├── skills.ts # Skill loading + formatting for system prompt
43
- │ ├── slash-commands.ts # 21 built-in slash commands
44
- │ ├── event-bus.ts # Shared event bus for cross-extension communication
45
- │ ├── footer-data-provider.ts # Footer data provider (git branch + extension statuses)
46
- │ ├── auth-storage.ts # API key / OAuth credential storage
47
- │ ├── auth-guidance.ts # User-facing auth error messages
48
- │ ├── extensions/ # ═══ EXTENSION SYSTEM ═══
49
- │ │ ├── types.ts # Type surface (1545 dòng)
50
- │ │ ├── loader.ts # jiti-based extension loader (~607 dòng)
51
- │ │ ├── runner.ts # ExtensionRunner lifecycle manager (~1024 dòng)
52
- │ │ ├── wrapper.ts # Tool wrapping utilities
53
- │ │ └── index.ts # Re-exports (~170 dòng)
54
- │ ├── compaction/ # ═══ COMPACTION ═══
55
- │ │ ├── compaction.ts # Context compaction logic (~840 dòng)
56
- │ │ ├── branch-summarization.ts # Tree navigation summarization (~356 dòng)
57
- │ │ ├── utils.ts # File ops tracking + serialization
58
- │ │ └── index.ts
59
- │ └── tools/ # ═══ BUILT-IN TOOLS ═══
60
- │ ├── index.ts # Tool registry + factories (~198 dòng)
61
- │ ├── read.ts # File reading with truncation
62
- │ ├── bash.ts # Shell command execution
63
- │ ├── edit.ts # Exact text replacement
64
- │ ├── write.ts # File creation/overwrite
65
- │ ├── grep.ts # Regex search
66
- │ ├── find.ts # File name search
67
- │ ├── ls.ts # Directory listing
68
- │ ├── file-mutation-queue.ts # Serialized file writes
69
- │ ├── truncate.ts # Output truncation strategies
70
- │ └── render-utils.ts
71
- ├── modes/ # ═══ RUN MODES ═══
72
- │ ├── index.ts # Re-exports
73
- │ ├── interactive/ # Interactive TUI mode (5470 dòng)
74
- │ │ ├── interactive-mode.ts # Main TUI loop + all slash commands
75
- │ │ ├── components/ # 30+ TUI components (assistant messages, diffs, editors...)
76
- │ │ └── theme/ # Theme engine (JSON-based, hot-reload)
77
- │ ├── print-mode.ts # Non-interactive / JSON output mode
78
- │ └── rpc/ # JSON-RPC mode for embedding (parent-child protocol)
79
- │ ├── rpc-mode.ts # RPC server loop
80
- │ ├── rpc-client.ts # RPC client for SDK/programmatic use
81
- │ ├── rpc-types.ts # JSON-RPC message types
82
- │ └── jsonl.ts # JSONL output formatting
83
- └── utils/ # Shared utilities
84
- ├── clipboard.ts # Clipboard integration
85
- ├── frontmatter.ts # YAML frontmatter parser
86
- ├── shell.ts # Shell detection/config
87
- ├── paths.ts # Path utilities
88
- └── sleep.ts # Promise-based sleep
89
- ```
90
-
91
- ## 3. Các file chính - số dòng
92
-
93
- | File | Dòng | Mô tả |
94
- |---|---|---|
95
- | `modes/interactive/interactive-mode.ts` | 5470 | Interactive TUI + tất cả 21 slash command handlers |
96
- | `core/agent-session.ts` | 3099 | AgentSession class: prompt, compaction, bash, model management |
97
- | `core/extensions/types.ts` | 1545 | Toàn bộ type surface cho extension system |
98
- | `core/session-manager.ts` | 1425 | Session file I/O, entry types, tree operations |
99
- | `core/settings-manager.ts` | ~1069 | JSON settings management (global + project) |
100
- | `core/extensions/runner.ts` | ~1024 | ExtensionRunner: event emission, context binding |
101
- | `core/resource-loader.ts` | ~920 | Unified loader for extensions/skills/prompts/themes |
102
- | `core/compaction/compaction.ts` | ~840 | Compaction logic + cut-point detection |
103
- | `main.ts` | 731 | CLI entry: arg parsing → mode dispatch |
104
- | `core/extensions/loader.ts` | ~607 | jiti-based TypeScript module loading |
105
-
106
- ## 4. Luồng thực thi chính
107
-
108
- ### 4.1 Startup sequence (`main.ts`)
109
-
110
- ```
111
- main(args)
112
- ├── parseArgs(args) # Parse CLI flags
113
- ├── resolveAppMode() # interactive | print | json | rpc
114
- ├── runMigrations() # Upgrade old session formats
115
- ├── createSessionManager() # new/fork/continue/resume/in-memory
116
- ├── createAgentSessionRuntime(createRuntime) # Build full runtime
117
- │ └── createRuntime(cwd, agentDir, sessionManager)
118
- │ ├── createAgentSessionServices() # authStorage, modelRegistry, resourceLoader
119
- │ ├── resolveModelScope() # --models flag → scoped models
120
- │ ├── buildSessionOptions() # model, thinking, tools, scopedModels
121
- │ └── createAgentSessionFromServices() → AgentSession
122
- ├── readPipedStdin() # Pipe support
123
- ├── prepareInitialMessage() # text + images
124
- └── dispatch:
125
- ├── interactive → new InteractiveMode(runtime).run()
126
- ├── print/json → runPrintMode(runtime, {...})
127
- └── rpc → runRpcMode(runtime)
128
- ```
129
-
130
- ### 4.2 AgentSession.prompt() lifecycle
131
-
132
- ```
133
- session.prompt(text)
134
- ├── parseSkillBlock() # <skill name="..." location="...">
135
- ├── expandPromptTemplate() # @file expansion
136
- ├── emitInput() # Extension can transform/block input
137
- ├── emitBeforeAgentStart() # Extension can inject custom message / swap system prompt
138
- ├── agent.runAgentLoop()
139
- │ ├── context → extension transform messages
140
- │ ├── before_provider_request → extension modify payload
141
- │ ├── streamSimple(model, context, ...)
142
- │ ├── after_provider_response → extension observe response
143
- │ ├── tool_call → extension intercept/block/mutate args
144
- │ ├── tool_execution_start/update/end
145
- │ ├── tool_result → extension modify result
146
- │ └── auto-compaction check (after turn_end)
147
- └── emitAgentEnd()
148
- ```
149
-
150
- ### 4.3 Run modes
151
-
152
- | Mode | Class/Function | Đặc điểm |
153
- |---|---|---|
154
- | **Interactive** | `InteractiveMode` (5470 dòng) | Full TUI: chat history, editor, widgets, themes, overlays, keybindings |
155
- | **Print/JSON** | `runPrintMode()` | Pipe/script: plain text or JSON mode, no TUI |
156
- | **RPC** | `runRpcMode()` | JSON-RPC 2.0 over stdin/stdout — dùng làm child process protocol |
157
-
158
- ## 5. AgentSession class chi tiết
159
-
160
- ### 5.1 Properties
161
-
162
- ```typescript
163
- class AgentSession {
164
- readonly agent: Agent; // Core agent instance
165
- readonly sessionManager: SessionManager; // Session file I/O
166
- readonly settingsManager: SettingsManager;// Settings
167
-
168
- // Model access
169
- get model(): Model<any> | undefined;
170
- get thinkingLevel(): ThinkingLevel;
171
- get scopedModels(): Array<{model, thinkingLevel}>;
172
-
173
- // Tool access
174
- get toolNames(): string[]; // Currently active tools
175
- get tools(): ToolInfo[]; // All registered tools with metadata
176
- getAllTools(): ToolInfo[];
177
-
178
- // Context
179
- getContextUsage(): ContextUsage | undefined;
180
- isIdle(): boolean;
181
-
182
- // Core operations
183
- prompt(text, options?): Promise<void>; // Send user message
184
- abort(): void; // Abort current operation
185
- shutdown(): void; // Graceful shutdown
186
-
187
- // Model management
188
- cycleModel(forward?): ModelCycleResult; // Ctrl+P cycling
189
- setModel(model): Promise<boolean>; // Switch model
190
- setThinkingLevel(level): void;
191
-
192
- // Compaction
193
- compact(options?): void; // Manual compaction
194
- getSessionStats(): SessionStats; // Usage stats
195
- }
196
- ```
197
-
198
- ### 5.2 Internal state machine
199
-
200
- Key internal flags:
201
- - `_steeringMessages[]` / `_followUpMessages[]`: Queued messages
202
- - `_compactionAbortController` / `_autoCompactionAbortController`: Compaction control
203
- - `_overflowRecoveryAttempted`: Context overflow recovery flag
204
- - `_retryAttempt` / `_retryPromise`: Auto-retry state
205
- - `_bashAbortController` / `_pendingBashMessages[]`: Bash execution state
206
- - `_turnIndex`: Current turn counter
207
-
208
- ### 5.3 Tool hooks
209
-
210
- `_installAgentToolHooks()` installs interceptors on the Agent instance:
211
- - `beforeToolCall`: Check if extension wants to intercept/block
212
- - `onToolResult`: Check if extension wants to modify result
213
-
214
- ## 6. Session Persistence (`session-manager.ts`)
215
-
216
- ### 6.1 Session file format
217
-
218
- JSONL file (`.pi/sessions/{id}.jsonl`) với các entry types:
219
-
220
- | Entry Type | Purpose | Fields |
221
- |---|---|---|
222
- | `session` | Header | version, id, timestamp, cwd, parentSession |
223
- | `message` | AgentMessage (user/assistant/toolResult) | message |
224
- | `thinking_level_change` | Thinking level change | thinkingLevel |
225
- | `model_change` | Model switch | provider, modelId |
226
- | `compaction` | Compaction summary | summary, firstKeptEntryId, tokensBefore, details |
227
- | `branch_summary` | Branch navigation | summary, fromId, details |
228
- | `custom_message` | Extension-defined for LLM context | customType, content, display, details |
229
- | `custom` | Extension state (not in LLM context) | customType, data |
230
-
231
- Current version: `CURRENT_SESSION_VERSION = 3`
232
-
233
- ### 6.2 Session tree
234
-
235
- - Mỗi session có `parentSession` reference (khi fork)
236
- - `SessionManager.forkFrom()` tạo session mới
237
- - `buildSessionContext()` dựng messages từ entries (cả compaction + branch summary)
238
- - `navigateTree()` di chuyển giữa các branch trong cùng session
239
-
240
- ## 7. Compaction System
241
-
242
- ### 7.1 Auto-compaction (`compaction/compaction.ts`)
243
-
244
- Default settings:
245
- ```
246
- reserveTokens: 16384 # Dành cho system prompt + LLM response
247
- keepRecentTokens: 20000 # Giữ các messages gần đây
248
- ```
249
-
250
- Process:
251
- 1. `shouldCompact()` — kiểm tra context usage sau mỗi turn
252
- 2. `findCutPoint()` — tìm vị trí cắt dựa vào file operations
253
- 3. `prepareCompaction()` — build messagesToSummarize + turnPrefixMessages
254
- 4. `compact()` — serialize → LLM summarize → return CompactionResult
255
- 5. SessionManager lưu `CompactionEntry` + tạo session mới (reload)
256
-
257
- ### 7.2 Branch summarization (`compaction/branch-summarization.ts`)
258
-
259
- Khi user navigate session tree, tạo summary của branch hiện tại:
260
- - `collectEntriesForBranchSummary()` — thu thập entries cần summarize
261
- - `prepareBranchEntries()` — extract messages + file operations
262
- - `generateBranchSummary()` — gọi LLM tạo summary
263
-
264
- ### 7.3 Cut-point strategy
265
-
266
- Tìm cut-point dựa trên:
267
- - File operations: ưu tiên cắt ở điểm không có pending file modifications
268
- - Assistant messages: không cắt giữa tool calls
269
- - Keep recent tokens: giữ ít nhất `keepRecentTokens` cuối cùng
270
-
271
- ## 8. Built-in Tools
272
-
273
- 7 tools, mỗi tool có 2 representations:
274
- - `AgentTool` — runtime execution contract
275
- - `ToolDefinition` — type-safe definition với schema + render
276
-
277
- | Tool | File | Key params | Đặc điểm |
278
- |---|---|---|---|
279
- | `read` | `tools/read.ts` | path, offset, limit | Head/tail truncation, image support |
280
- | `bash` | `tools/bash.ts` | command, timeout | AbortController, timeout |
281
- | `edit` | `tools/edit.ts` | path, edits[{oldText,newText}] | Exact replacement, multi-edit |
282
- | `write` | `tools/write.ts` | path, content | Overwrite/create |
283
- | `grep` | `tools/grep.ts` | pattern, path | Regex search |
284
- | `find` | `tools/find.ts` | pattern, path | File name glob |
285
- | `ls` | `tools/ls.ts` | path | Directory listing |
286
-
287
- **File mutation queue** (`file-mutation-queue.ts`): Serializes write operations to prevent
288
- parallel tool conflicts. Used internally by edit/write tools.
289
-
290
- ## 9. Settings Manager (`settings-manager.ts`)
291
-
292
- Quản lý `settings.json` với các section:
293
-
294
- | Section | Key settings | Default |
295
- |---|---|---|
296
- | `compaction` | enabled, reserveTokens, keepRecentTokens | true, 16384, 20000 |
297
- | `retry` | enabled, maxRetries, baseDelayMs | true, 3, 2000 |
298
- | `retry.provider` | timeoutMs, maxRetries, maxRetryDelayMs | (SDK defaults) |
299
- | `terminal` | showImages, imageWidthCells, clearOnShrink, showTerminalProgress | true, 60, false, false |
300
- | `images` | autoResize, blockImages | true, false |
301
- | `thinkingBudgets` | minimal, low, medium, high | (per-level defaults) |
302
- | `markdown` | codeBlockIndent | " " |
303
-
304
- Scope: global (`~/.pi/agent/settings.json`) + project-local (`.pi/settings.json`).
305
-
306
- ## 10. Slash Commands
307
-
308
- 21 built-in commands (`slash-commands.ts`):
309
-
310
- | Command | Purpose |
311
- |---|---|
312
- | `settings` | Open settings menu |
313
- | `model` | Select model (selector UI) |
314
- | `scoped-models` | Enable/disable models for Ctrl+P |
315
- | `export` | Export session (HTML/JSONL) |
316
- | `import` | Import session from JSONL |
317
- | `share` | Share as GitHub gist |
318
- | `copy` | Copy last message |
319
- | `name` | Set session display name |
320
- | `session` | Show session info + stats |
321
- | `changelog` | Show changelog |
322
- | `hotkeys` | Show keyboard shortcuts |
323
- | `fork` | Fork from previous message |
324
- | `clone` | Duplicate session |
325
- | `tree` | Navigate session tree |
326
- | `login`/`logout` | Auth management |
327
- | `new` | Start new session |
328
- | `compact` | Manual compaction |
329
- | `resume` | Resume different session |
330
- | `reload` | Reload extensions/skills/themes |
331
- | `quit` | Exit |
332
-
333
- ## 11. RPC Mode
334
-
335
- JSON-RPC 2.0 protocol qua stdin/stdout:
336
-
337
- ```typescript
338
- // Request
339
- { "jsonrpc": "2.0", "id": 1, "method": "prompt", "params": { "text": "..." } }
340
-
341
- // Response
342
- { "jsonrpc": "2.0", "id": 1, "result": { "messages": [...], "usage": {...} } }
343
-
344
- // Notification (no id)
345
- { "jsonrpc": "2.0", "method": "event", "params": { "type": "message_start", ... } }
346
- ```
347
-
348
- Đây là protocol chính cho parent-child communication trong pi-subagents và pi-crew.
349
-
350
- ## 12. Các điểm đáng chú ý
351
-
352
- 1. **Interactive mode quá lớn** (5470 dòng) — chứa hầu hết slash command implementations
353
- 2. **AgentSession quá lớn** (3099 dòng) — mixed concerns: prompt, compaction, bash, lifecycle
354
- 3. **Extension type surface** (1545 dòng) — rất comprehensive nhưng complex
355
- 4. **Lockstep versioning** — tất cả packages cùng version 0.70.5
356
- 5. **jiti-based extension loading** — cho phép TypeScript extensions không cần compile
357
- 6. **Virtual modules** — cho Bun compiled binary, bundle sẵn các dependencies
@@ -1,174 +0,0 @@
1
- # Research: `source/pi-crew` as New Reference Source
2
-
3
- Date: 2026-04-29
4
- Reference source: `D:/my/my_project/source/pi-crew` (`@melihmucuk/pi-crew@1.0.14`, commit `c0631a3`)
5
- Current target: `D:/my/my_project/pi-crew` (`pi-crew@0.1.34`)
6
- Research run: `team_20260429091311_8047706b`
7
-
8
- > Note: the parallel research run produced useful artifacts, but child workers were marked failed because they did not exit within 5s after their final assistant message. The source audit content was still captured in result/shared artifacts.
9
-
10
- ## Executive Summary
11
-
12
- `source/pi-crew` is a compact, in-process subagent orchestration extension. It is not a team/workflow engine; instead, it focuses on fast non-blocking subagent sessions, owner-routed steering-message delivery, interactive subagents, and context-overflow recovery. It is valuable as a reference for **session-native subagent runtime**, **delivery semantics**, and **minimal interactive worker UX**.
13
-
14
- Current `pi-crew` is more powerful and durable: child Pi workers, teams/workflows, task graph scheduling, worktrees, mailbox, event logs, dashboard, notifications, and recovery state. The best path is not replacement; it is selective porting of patterns into `pi-crew`'s existing `live-session-runtime` / `SubagentManager` as an optional session-native lane.
15
-
16
- ## Source File Map
17
-
18
- | Area | Reference files |
19
- |---|---|
20
- | Extension entry/session hooks | `source/pi-crew/extension/index.ts` |
21
- | Runtime singleton | `source/pi-crew/extension/runtime/crew-runtime.ts` |
22
- | Delivery routing | `source/pi-crew/extension/runtime/delivery-coordinator.ts` |
23
- | State model/registry | `source/pi-crew/extension/runtime/subagent-state.ts`, `source/pi-crew/extension/runtime/subagent-registry.ts` |
24
- | Overflow recovery | `source/pi-crew/extension/runtime/overflow-recovery.ts` |
25
- | Session bootstrap | `source/pi-crew/extension/bootstrap-session.ts` |
26
- | Agent discovery | `source/pi-crew/extension/agent-discovery.ts` |
27
- | Tool registration | `source/pi-crew/extension/integration/register-tools.ts`, `source/pi-crew/extension/integration/tools/*.ts` |
28
- | Message renderers | `source/pi-crew/extension/integration/register-renderers.ts` |
29
- | Message formatting | `source/pi-crew/extension/subagent-messages.ts` |
30
- | Status widget | `source/pi-crew/extension/status-widget.ts` |
31
- | Architecture doc | `source/pi-crew/docs/architecture.md` |
32
-
33
- ## Architecture Observations
34
-
35
- ### Reference `source/pi-crew`
36
-
37
- - Process-level singleton `CrewRuntime` survives Pi runtime/session replacement and rebinds on `session_start`.
38
- - Subagents are in-process SDK `AgentSession`s created with `createAgentSession()`.
39
- - Parent/child linkage uses `SessionManager.newSession({ parentSession })`.
40
- - Subagent resource loading filters out the pi-crew extension through `extensionsOverride` to prevent recursive `crew_spawn` loops.
41
- - Results are delivered through Pi-native `sendMessage()` with explicit idle/streaming semantics.
42
- - Interactive subagents are first-class: `interactive: true` workers enter `waiting`; parent continues with `crew_respond`; cleanup is explicit with `crew_done`.
43
- - Overflow recovery tracks `agent_end`, `compaction_start/end`, and `auto_retry_start/end` events around `session.prompt()`.
44
- - State is in-memory only; subagent session files remain for post-hoc `/resume` inspection.
45
-
46
- ### Current `pi-crew`
47
-
48
- - Primary runtime is child Pi process execution with durable `.crew/state` manifests and artifacts.
49
- - It has workflow/team abstractions, task graphs, worktree support, event log, mailbox, dashboard panes, render scheduler, notifications, and diagnostic exports.
50
- - It already has `live-session-runtime.ts`, but the current product surface centers on durable child-process workers rather than interactive in-process subagents.
51
-
52
- ## Extension API Patterns Worth Reusing
53
-
54
- | Pattern | Reference source | Why it matters for current `pi-crew` |
55
- |---|---|---|
56
- | Owner-routed delivery by `sessionManager.getSessionId()` | `delivery-coordinator.ts` | Avoids sending async worker results to the wrong active session after `/resume`, `/new`, `/fork`, or multi-session use. |
57
- | Idle vs streaming delivery split | `subagent-messages.ts`, `delivery-coordinator.ts` | Prevents messages from getting stuck: idle sessions need `triggerTurn`; streaming sessions need `deliverAs: "steer"`. |
58
- | Deferred pending flush via `setTimeout(0)` | `delivery-coordinator.ts` | Avoids lost JSONL/custom-message persistence during resume before listeners reconnect. |
59
- | `extensionsOverride` filter | `bootstrap-session.ts` | Required for any in-process worker lane to prevent recursive subagent spawning. |
60
- | Fire-and-forget interactive response | `crew-respond.ts`, `crew-runtime.ts` | Lets parent stay responsive while an interactive worker continues in background. |
61
- | No duplicate done message | `crew-done.ts` | Avoids repeating the last subagent response during cleanup. |
62
- | Source-specific abort reasons | `crew-abort.ts`, `index.ts` shutdown handlers | Better diagnostics than generic "aborted by user". |
63
- | Emergency unrestricted abort command | `register-command.ts` | Useful escape hatch distinct from owner-scoped tool actions. |
64
- | Overflow tracker around SDK prompt | `overflow-recovery.ts` | Better UX for context overflow/compaction/retry in session-native workers. |
65
-
66
- ## Key Differences / Non-Goals
67
-
68
- | Dimension | Reference `source/pi-crew` | Current `pi-crew` |
69
- |---|---|---|
70
- | Runtime | In-process `AgentSession` | Child Pi processes + durable orchestration |
71
- | State | In-memory map | Durable manifests/event logs/artifacts |
72
- | Scope | Flat subagent spawn/respond/done | Teams, workflows, task graph, worktrees |
73
- | Result UX | Pi steering/custom messages | Tool results, mailbox, dashboard, async status |
74
- | Interactive workers | Native | Not yet first-class |
75
- | Worktree isolation | None | First-class |
76
- | Replay/restart | Limited | Strong durable recovery |
77
-
78
- Do **not** replace the current runtime wholesale. Reference `source/pi-crew` lacks durable state, worktrees, workflow scheduling, artifact indexing, and the Phase 8 operator experience. Its best value is a narrower session-native execution lane and delivery correctness patterns.
79
-
80
- ## Recommendations
81
-
82
- ### P0 — Adopt Delivery Semantics for Async/Live Results
83
-
84
- Implement or adapt a small owner-routed delivery coordinator in current `pi-crew`:
85
-
86
- - Key by owner `sessionId`, not session file.
87
- - Queue pending messages when owner inactive.
88
- - On `session_start`, flush pending messages on next macrotask.
89
- - Use idle/streaming split:
90
- - idle: `sendMessage(payload, { triggerTurn: true })`
91
- - streaming: `sendMessage(payload, { deliverAs: "steer", triggerTurn: true })`
92
- - Keep current mailbox/event-log as durable source of truth; use delivery coordinator only for live UX.
93
-
94
- Likely target files:
95
-
96
- - `pi-crew/src/extension/register.ts`
97
- - `pi-crew/src/runtime/subagent-manager.ts`
98
- - `pi-crew/src/runtime/live-session-runtime.ts`
99
- - `pi-crew/src/extension/notification-router.ts`
100
-
101
- ### P1 — Add Optional Session-Native Subagent Lane
102
-
103
- Build an opt-in lane on top of existing `live-session-runtime.ts` rather than changing the default child-process runtime:
104
-
105
- - `runtime.mode = "child-process" | "live-session" | "auto"` already exists conceptually; tighten semantics.
106
- - Use `SessionManager.newSession({ parentSession })` and `createAgentSession()` for in-process workers.
107
- - Filter `pi-crew` out of subagent resource loader extensions.
108
- - Persist minimal metadata to existing `.crew/state` so dashboards/recovery still work.
109
-
110
- This can reduce process startup overhead and blank console issues, while preserving child-process isolation as the safe default.
111
-
112
- ### P1 — Introduce Interactive Worker Semantics
113
-
114
- Add first-class interactive subagents without disrupting teams:
115
-
116
- - New status: `waiting` for interactive background workers.
117
- - `crew_agent_respond` / `crew_agent_done` or extend existing `crew_agent_steer` semantics.
118
- - Fire-and-forget response: parent tool returns immediately; worker response arrives as mailbox/steering message.
119
- - `done` performs cleanup only; no duplicate response.
120
-
121
- Likely target files:
122
-
123
- - `pi-crew/src/runtime/crew-agent-records.ts`
124
- - `pi-crew/src/runtime/subagent-manager.ts`
125
- - `pi-crew/src/extension/registration/subagent-tools.ts`
126
- - `pi-crew/src/state/mailbox.ts`
127
- - `pi-crew/src/ui/dashboard-panes/agents-pane.ts`
128
-
129
- ### P2 — Port Overflow Recovery Tracker for Live Sessions
130
-
131
- For session-native workers, wrap `AgentSession.prompt()` with an event tracker similar to `source/pi-crew/extension/runtime/overflow-recovery.ts`:
132
-
133
- - Track `compaction_start/end` and `auto_retry_start/end`.
134
- - Report recovered context overflow separately from hard failure.
135
- - Emit durable event-log records and dashboard health hints.
136
-
137
- This should not apply to child Pi workers directly; they already have process/transcript supervision.
138
-
139
- ### P2 — Improve Abort Reason Taxonomy
140
-
141
- Adopt explicit abort source reasons across all worker paths:
142
-
143
- - tool-triggered abort
144
- - command-triggered emergency abort
145
- - session quit cleanup
146
- - session replacement detach/deactivate
147
- - watchdog timeout
148
- - stale heartbeat kill
149
-
150
- This improves diagnostics, notification routing, and Phase 9 reliability work.
151
-
152
- ## Risks
153
-
154
- - In-process sessions reduce OS/process isolation; failures or leaks may affect the parent Pi process.
155
- - `extensionsOverride` is mandatory; missing it risks recursive subagent spawning.
156
- - Pi SDK internals may shift; keep this lane optional and covered by integration tests.
157
- - Delivery semantics must not bypass durable mailbox/event log; live messages are convenience, not source of truth.
158
- - Interactive workers can linger in memory; require TTL/status visibility and explicit cleanup.
159
-
160
- ## Suggested Follow-Up Plan
161
-
162
- 1. Write a focused design doc: `docs/research-session-native-runtime-plan.md`.
163
- 2. Spike delivery coordinator only; no runtime swap.
164
- 3. Add tests for idle/streaming/inactive owner delivery behavior.
165
- 4. Add optional `live-session` worker lane behind config.
166
- 5. Add interactive worker status/actions after live delivery is stable.
167
-
168
- ## Research Artifacts
169
-
170
- - `D:/my/my_project/.crew/artifacts/team_20260429091311_8047706b/results/01_discover.txt`
171
- - `D:/my/my_project/.crew/artifacts/team_20260429091311_8047706b/results/02_explore-shard-1.txt`
172
- - `D:/my/my_project/.crew/artifacts/team_20260429091311_8047706b/results/03_explore-shard-2.txt`
173
- - `D:/my/my_project/.crew/artifacts/team_20260429091311_8047706b/results/04_explore-shard-3.txt`
174
- - `D:/my/my_project/.crew/artifacts/team_20260429091311_8047706b/batches/01_discover+02_explore-shard-1+03_explore-shard-2+04_explore-shard-3.md`