pi-crew 0.1.37 → 0.1.39

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 (162) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +27 -0
  3. package/README.md +5 -0
  4. package/agents/analyst.md +11 -11
  5. package/agents/critic.md +11 -11
  6. package/agents/executor.md +11 -11
  7. package/agents/explorer.md +11 -11
  8. package/agents/planner.md +11 -11
  9. package/agents/reviewer.md +11 -11
  10. package/agents/security-reviewer.md +11 -11
  11. package/agents/test-engineer.md +11 -11
  12. package/agents/verifier.md +11 -11
  13. package/agents/writer.md +11 -11
  14. package/docs/refactor-tasks-phase3.md +394 -394
  15. package/docs/refactor-tasks-phase4.md +564 -564
  16. package/docs/refactor-tasks-phase5.md +402 -402
  17. package/docs/refactor-tasks-phase6.md +662 -662
  18. package/docs/research-extension-examples.md +297 -297
  19. package/docs/research-extension-system.md +324 -324
  20. package/docs/research-optimization-plan.md +548 -548
  21. package/docs/research-pi-coding-agent.md +357 -357
  22. package/docs/research-source-pi-crew-reference.md +174 -174
  23. package/docs/resource-formats.md +10 -8
  24. package/docs/runtime-flow.md +148 -148
  25. package/docs/source-runtime-refactor-map.md +83 -83
  26. package/docs/usage.md +6 -0
  27. package/index.ts +6 -6
  28. package/package.json +3 -3
  29. package/schema.json +2 -2
  30. package/src/agents/agent-serializer.ts +34 -34
  31. package/src/config/config.ts +8 -4
  32. package/src/extension/cross-extension-rpc.ts +82 -82
  33. package/src/extension/import-index.ts +18 -2
  34. package/src/extension/register.ts +11 -1
  35. package/src/extension/registration/compaction-guard.ts +125 -125
  36. package/src/extension/registration/subagent-helpers.ts +30 -6
  37. package/src/extension/registration/subagent-tools.ts +8 -3
  38. package/src/extension/result-watcher.ts +98 -98
  39. package/src/extension/run-import.ts +12 -2
  40. package/src/extension/run-index.ts +12 -2
  41. package/src/extension/run-maintenance.ts +24 -24
  42. package/src/extension/team-tool/api.ts +54 -14
  43. package/src/extension/team-tool/cancel.ts +31 -31
  44. package/src/extension/team-tool/doctor.ts +179 -179
  45. package/src/extension/team-tool/inspect.ts +41 -41
  46. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  47. package/src/extension/team-tool/plan.ts +19 -19
  48. package/src/extension/team-tool/status.ts +73 -73
  49. package/src/observability/correlation.ts +35 -35
  50. package/src/observability/event-to-metric.ts +54 -54
  51. package/src/observability/exporters/adapter.ts +24 -24
  52. package/src/observability/exporters/otlp-exporter.ts +65 -65
  53. package/src/observability/exporters/prometheus-exporter.ts +47 -47
  54. package/src/observability/metric-registry.ts +72 -72
  55. package/src/observability/metric-retention.ts +46 -46
  56. package/src/observability/metric-sink.ts +51 -51
  57. package/src/observability/metrics-primitives.ts +166 -166
  58. package/src/prompt/prompt-runtime.ts +68 -68
  59. package/src/runtime/agent-control.ts +64 -64
  60. package/src/runtime/agent-memory.ts +72 -72
  61. package/src/runtime/agent-observability.ts +114 -113
  62. package/src/runtime/async-marker.ts +26 -26
  63. package/src/runtime/background-runner.ts +53 -53
  64. package/src/runtime/crash-recovery.ts +56 -56
  65. package/src/runtime/crew-agent-records.ts +54 -9
  66. package/src/runtime/crew-agent-runtime.ts +58 -58
  67. package/src/runtime/deadletter.ts +36 -36
  68. package/src/runtime/direct-run.ts +35 -35
  69. package/src/runtime/foreground-control.ts +82 -82
  70. package/src/runtime/green-contract.ts +46 -46
  71. package/src/runtime/group-join.ts +88 -88
  72. package/src/runtime/heartbeat-gradient.ts +28 -28
  73. package/src/runtime/heartbeat-watcher.ts +80 -80
  74. package/src/runtime/live-agent-control.ts +87 -78
  75. package/src/runtime/live-agent-manager.ts +85 -85
  76. package/src/runtime/live-control-realtime.ts +36 -36
  77. package/src/runtime/live-session-runtime.ts +299 -299
  78. package/src/runtime/manifest-cache.ts +248 -212
  79. package/src/runtime/model-fallback.ts +261 -261
  80. package/src/runtime/parallel-research.ts +44 -44
  81. package/src/runtime/parallel-utils.ts +99 -99
  82. package/src/runtime/pi-json-output.ts +111 -111
  83. package/src/runtime/policy-engine.ts +78 -78
  84. package/src/runtime/post-exit-stdio-guard.ts +86 -86
  85. package/src/runtime/process-status.ts +56 -56
  86. package/src/runtime/progress-event-coalescer.ts +43 -43
  87. package/src/runtime/recovery-recipes.ts +74 -74
  88. package/src/runtime/retry-executor.ts +59 -59
  89. package/src/runtime/role-permission.ts +39 -39
  90. package/src/runtime/session-usage.ts +79 -79
  91. package/src/runtime/sidechain-output.ts +28 -28
  92. package/src/runtime/subagent-manager.ts +80 -12
  93. package/src/runtime/task-display.ts +38 -38
  94. package/src/runtime/task-output-context.ts +127 -106
  95. package/src/runtime/task-runner/live-executor.ts +98 -98
  96. package/src/runtime/task-runner/progress.ts +111 -111
  97. package/src/runtime/task-runner/result-utils.ts +14 -14
  98. package/src/runtime/task-runner/state-helpers.ts +22 -22
  99. package/src/runtime/team-runner.ts +1 -1
  100. package/src/runtime/worker-heartbeat.ts +21 -21
  101. package/src/runtime/worker-startup.ts +57 -57
  102. package/src/schema/config-schema.ts +21 -21
  103. package/src/schema/team-tool-schema.ts +100 -100
  104. package/src/state/artifact-store.ts +122 -108
  105. package/src/state/contracts.ts +105 -105
  106. package/src/state/jsonl-writer.ts +77 -77
  107. package/src/state/mailbox.ts +67 -22
  108. package/src/state/state-store.ts +36 -5
  109. package/src/state/task-claims.ts +42 -42
  110. package/src/state/usage.ts +29 -29
  111. package/src/subagents/async-entry.ts +1 -1
  112. package/src/subagents/index.ts +3 -3
  113. package/src/subagents/live/control.ts +1 -1
  114. package/src/subagents/live/manager.ts +1 -1
  115. package/src/subagents/live/realtime.ts +1 -1
  116. package/src/subagents/live/session-runtime.ts +1 -1
  117. package/src/subagents/manager.ts +1 -1
  118. package/src/subagents/spawn.ts +1 -1
  119. package/src/teams/discover-teams.ts +27 -5
  120. package/src/teams/team-serializer.ts +38 -36
  121. package/src/types/diff.d.ts +18 -18
  122. package/src/ui/crew-footer.ts +101 -101
  123. package/src/ui/crew-select-list.ts +111 -111
  124. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  125. package/src/ui/dynamic-border.ts +25 -25
  126. package/src/ui/layout-primitives.ts +106 -106
  127. package/src/ui/loaders.ts +158 -158
  128. package/src/ui/mascot.ts +441 -441
  129. package/src/ui/render-diff.ts +119 -119
  130. package/src/ui/run-dashboard.ts +5 -2
  131. package/src/ui/run-snapshot-cache.ts +19 -8
  132. package/src/ui/spinner.ts +17 -17
  133. package/src/ui/status-colors.ts +54 -54
  134. package/src/ui/syntax-highlight.ts +116 -116
  135. package/src/ui/transcript-viewer.ts +15 -1
  136. package/src/utils/completion-dedupe.ts +63 -63
  137. package/src/utils/file-coalescer.ts +84 -84
  138. package/src/utils/frontmatter.ts +36 -36
  139. package/src/utils/fs-watch.ts +31 -31
  140. package/src/utils/git.ts +262 -262
  141. package/src/utils/ids.ts +12 -12
  142. package/src/utils/names.ts +26 -26
  143. package/src/utils/paths.ts +3 -2
  144. package/src/utils/safe-paths.ts +34 -0
  145. package/src/utils/sleep.ts +32 -32
  146. package/src/utils/timings.ts +31 -31
  147. package/src/utils/visual.ts +159 -159
  148. package/src/workflows/discover-workflows.ts +30 -3
  149. package/src/workflows/validate-workflow.ts +40 -40
  150. package/src/worktree/branch-freshness.ts +45 -45
  151. package/teams/default.team.md +12 -12
  152. package/teams/fast-fix.team.md +11 -11
  153. package/teams/implementation.team.md +18 -18
  154. package/teams/parallel-research.team.md +14 -14
  155. package/teams/research.team.md +11 -11
  156. package/teams/review.team.md +12 -12
  157. package/workflows/default.workflow.md +29 -29
  158. package/workflows/fast-fix.workflow.md +22 -22
  159. package/workflows/implementation.workflow.md +38 -38
  160. package/workflows/parallel-research.workflow.md +46 -46
  161. package/workflows/research.workflow.md +22 -22
  162. package/workflows/review.workflow.md +30 -30
@@ -1,357 +1,357 @@
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
+ # 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