pi-crew 0.1.46 → 0.1.49
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.
- package/CHANGELOG.md +97 -0
- package/agents/analyst.md +11 -11
- package/agents/critic.md +11 -11
- package/agents/executor.md +11 -11
- package/agents/explorer.md +11 -11
- package/agents/planner.md +11 -11
- package/agents/reviewer.md +11 -11
- package/agents/security-reviewer.md +11 -11
- package/agents/test-engineer.md +11 -11
- package/agents/verifier.md +11 -11
- package/agents/writer.md +11 -11
- package/docs/next-upgrade-roadmap.md +117 -42
- package/docs/refactor-tasks-phase3.md +394 -394
- package/docs/refactor-tasks-phase4.md +564 -564
- package/docs/refactor-tasks-phase5.md +402 -402
- package/docs/refactor-tasks-phase6.md +662 -662
- package/docs/research/AGENT-EXECUTION-ARCHITECTURE.md +261 -0
- package/docs/research/AGENT-LIFECYCLE-COMPARISON.md +111 -0
- package/docs/research/AUDIT_OH_MY_PI.md +261 -0
- package/docs/research/AUDIT_PI_CREW.md +457 -0
- package/docs/research/CAVEMAN-DEEP-RESEARCH.md +281 -0
- package/docs/research/COMPARISON_OH_MY_PI_VS_PI_CREW.md +264 -0
- package/docs/research/DEEP-RESEARCH-PI-POWERBAR.md +343 -0
- package/docs/research/DEEP_RESEARCH_SUBAGENT_ARCHITECTURE.md +480 -0
- package/docs/research/GAP_CLOSURE_IMPLEMENTATION_PLAN.md +354 -0
- package/docs/research/IMPLEMENTATION_PLAN.md +385 -0
- package/docs/research/LIVE-SESSION-PRODUCTION-READY-PLAN.md +502 -0
- package/docs/research/OH-MY-PI-DEEP-RESEARCH-v14.7.6.md +266 -0
- package/docs/research/REMAINING-GAPS-PLAN.md +363 -0
- package/docs/research/SESSION-SUMMARY-2026-05-08.md +146 -0
- package/docs/research/UI-RESPONSIVENESS-AUDIT.md +173 -0
- package/docs/research-awesome-agent-skills-distillation.md +100 -100
- package/docs/research-extension-examples.md +297 -297
- package/docs/research-extension-system.md +324 -324
- package/docs/research-oh-my-pi-distillation.md +56 -9
- package/docs/research-optimization-plan.md +548 -548
- package/docs/research-phase10-distillation.md +198 -198
- package/docs/research-phase11-distillation.md +201 -201
- package/docs/research-pi-coding-agent.md +357 -357
- package/docs/research-source-pi-crew-reference.md +174 -174
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +107 -107
- package/index.ts +6 -6
- package/package.json +99 -98
- package/schema.json +8 -0
- package/skills/async-worker-recovery/SKILL.md +42 -42
- package/skills/context-artifact-hygiene/SKILL.md +52 -52
- package/skills/delegation-patterns/SKILL.md +54 -54
- package/skills/mailbox-interactive/SKILL.md +40 -40
- package/skills/model-routing-context/SKILL.md +39 -39
- package/skills/multi-perspective-review/SKILL.md +58 -58
- package/skills/observability-reliability/SKILL.md +41 -41
- package/skills/orchestration/SKILL.md +157 -0
- package/skills/ownership-session-security/SKILL.md +41 -41
- package/skills/pi-extension-lifecycle/SKILL.md +39 -39
- package/skills/requirements-to-task-packet/SKILL.md +63 -63
- package/skills/resource-discovery-config/SKILL.md +41 -41
- package/skills/runtime-state-reader/SKILL.md +44 -44
- package/skills/secure-agent-orchestration-review/SKILL.md +45 -45
- package/skills/state-mutation-locking/SKILL.md +42 -42
- package/skills/systematic-debugging/SKILL.md +67 -67
- package/skills/ui-render-performance/SKILL.md +39 -39
- package/skills/verification-before-done/SKILL.md +57 -57
- package/skills/worktree-isolation/SKILL.md +39 -39
- package/src/agents/agent-config.ts +6 -0
- package/src/agents/agent-search.ts +98 -0
- package/src/agents/agent-serializer.ts +4 -0
- package/src/agents/discover-agents.ts +17 -4
- package/src/config/config.ts +24 -0
- package/src/config/defaults.ts +11 -0
- package/src/extension/autonomous-policy.ts +26 -33
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/help.ts +1 -0
- package/src/extension/management.ts +5 -0
- package/src/extension/register.ts +58 -13
- package/src/extension/registration/commands.ts +33 -1
- package/src/extension/registration/compaction-guard.ts +125 -125
- package/src/extension/registration/team-tool.ts +6 -4
- package/src/extension/run-bundle-schema.ts +89 -89
- package/src/extension/run-index.ts +24 -18
- package/src/extension/run-maintenance.ts +68 -62
- package/src/extension/team-tool/api.ts +23 -2
- package/src/extension/team-tool/cancel.ts +86 -11
- package/src/extension/team-tool/context.ts +3 -0
- package/src/extension/team-tool/handle-settings.ts +188 -188
- package/src/extension/team-tool/inspect.ts +41 -41
- package/src/extension/team-tool/intent-policy.ts +42 -0
- package/src/extension/team-tool/lifecycle-actions.ts +47 -18
- package/src/extension/team-tool/parallel-dispatch.ts +156 -0
- package/src/extension/team-tool/plan.ts +19 -19
- package/src/extension/team-tool/respond.ts +10 -2
- package/src/extension/team-tool/run.ts +3 -2
- package/src/extension/team-tool/status.ts +1 -1
- package/src/extension/team-tool-types.ts +1 -0
- package/src/extension/team-tool.ts +13 -3
- package/src/hooks/registry.ts +61 -0
- package/src/hooks/types.ts +41 -0
- package/src/i18n.ts +184 -184
- package/src/observability/exporters/otlp-exporter.ts +77 -77
- package/src/prompt/prompt-runtime.ts +72 -72
- package/src/runtime/agent-control.ts +108 -2
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +114 -114
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/async-runner.ts +3 -1
- package/src/runtime/attention-events.ts +28 -28
- package/src/runtime/background-runner.ts +19 -0
- package/src/runtime/cancellation-token.ts +89 -0
- package/src/runtime/cancellation.ts +61 -51
- package/src/runtime/capability-inventory.ts +116 -0
- package/src/runtime/child-pi.ts +2 -1
- package/src/runtime/code-summary.ts +247 -0
- package/src/runtime/completion-guard.ts +190 -190
- package/src/runtime/crash-recovery.ts +181 -0
- package/src/runtime/crew-agent-records.ts +35 -7
- package/src/runtime/crew-agent-runtime.ts +1 -0
- package/src/runtime/custom-tools/irc-tool.ts +201 -0
- package/src/runtime/custom-tools/submit-result-tool.ts +90 -0
- package/src/runtime/delivery-coordinator.ts +3 -1
- package/src/runtime/direct-run.ts +35 -35
- package/src/runtime/effectiveness.ts +81 -76
- package/src/runtime/event-stream-bridge.ts +90 -0
- package/src/runtime/foreground-control.ts +82 -82
- package/src/runtime/green-contract.ts +46 -46
- package/src/runtime/group-join.ts +106 -106
- package/src/runtime/heartbeat-gradient.ts +28 -28
- package/src/runtime/heartbeat-watcher.ts +124 -124
- package/src/runtime/live-agent-control.ts +88 -88
- package/src/runtime/live-agent-manager.ts +78 -2
- package/src/runtime/live-control-realtime.ts +36 -36
- package/src/runtime/live-extension-bridge.ts +150 -0
- package/src/runtime/live-irc.ts +92 -0
- package/src/runtime/live-session-health.ts +100 -0
- package/src/runtime/live-session-runtime.ts +297 -7
- package/src/runtime/mcp-proxy.ts +113 -0
- package/src/runtime/notebook-helpers.ts +90 -0
- package/src/runtime/orphan-sentinel.ts +7 -0
- package/src/runtime/output-validator.ts +187 -0
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/parallel-utils.ts +57 -0
- package/src/runtime/parent-guard.ts +80 -0
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/policy-engine.ts +79 -79
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/prose-compressor.ts +164 -0
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/result-extractor.ts +121 -0
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/runtime-resolver.ts +1 -4
- package/src/runtime/semaphore.ts +131 -0
- package/src/runtime/sensitive-paths.ts +92 -0
- package/src/runtime/session-resources.ts +25 -25
- package/src/runtime/session-snapshot.ts +59 -59
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +29 -29
- package/src/runtime/stream-preview.ts +177 -0
- package/src/runtime/subagent-manager.ts +3 -2
- package/src/runtime/subprocess-tool-registry.ts +67 -0
- package/src/runtime/supervisor-contact.ts +59 -59
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +59 -9
- package/src/runtime/task-runner/capabilities.ts +78 -78
- package/src/runtime/task-runner/live-executor.ts +2 -0
- package/src/runtime/task-runner/progress.ts +119 -119
- package/src/runtime/task-runner/prompt-builder.ts +70 -8
- package/src/runtime/task-runner/prompt-pipeline.ts +64 -64
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/run-projection.ts +104 -0
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/task-runner.ts +75 -4
- package/src/runtime/team-runner.ts +60 -8
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/runtime/workspace-tree.ts +298 -0
- package/src/runtime/yield-handler.ts +189 -0
- package/src/schema/config-schema.ts +6 -0
- package/src/schema/team-tool-schema.ts +11 -1
- package/src/skills/discover-skills.ts +67 -0
- package/src/state/active-run-registry.ts +4 -2
- package/src/state/artifact-store.ts +4 -1
- package/src/state/atomic-write.ts +50 -1
- package/src/state/blob-store.ts +117 -0
- package/src/state/contracts.ts +1 -0
- package/src/state/event-log-rotation.ts +158 -0
- package/src/state/event-log.ts +52 -2
- package/src/state/mailbox.ts +87 -7
- package/src/state/state-store.ts +24 -4
- package/src/state/task-claims.ts +44 -44
- package/src/state/types.ts +20 -0
- package/src/state/usage.ts +29 -29
- package/src/subagents/async-entry.ts +1 -1
- package/src/subagents/index.ts +3 -3
- package/src/subagents/live/control.ts +1 -1
- package/src/subagents/live/manager.ts +1 -1
- package/src/subagents/live/realtime.ts +1 -1
- package/src/subagents/live/session-runtime.ts +1 -1
- package/src/subagents/manager.ts +1 -1
- package/src/subagents/spawn.ts +1 -1
- package/src/teams/team-serializer.ts +38 -38
- package/src/types/diff.d.ts +18 -18
- package/src/ui/agent-management-overlay.ts +144 -0
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/crew-widget.ts +11 -2
- package/src/ui/dashboard-panes/cancellation-pane.ts +43 -0
- package/src/ui/dashboard-panes/capability-pane.ts +60 -0
- package/src/ui/dashboard-panes/mailbox-pane.ts +35 -11
- package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
- package/src/ui/dynamic-border.ts +25 -25
- package/src/ui/layout-primitives.ts +106 -106
- package/src/ui/live-run-sidebar.ts +4 -0
- package/src/ui/loaders.ts +158 -158
- package/src/ui/powerbar-publisher.ts +77 -15
- package/src/ui/render-coalescer.ts +51 -0
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/render-scheduler.ts +143 -143
- package/src/ui/run-dashboard.ts +4 -0
- package/src/ui/run-event-bus.ts +209 -0
- package/src/ui/run-snapshot-cache.ts +68 -16
- package/src/ui/snapshot-types.ts +8 -0
- package/src/ui/spinner.ts +17 -17
- package/src/ui/status-colors.ts +58 -58
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/ui/transcript-entries.ts +258 -0
- package/src/utils/atomic-write.ts +33 -33
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/frontmatter.ts +68 -68
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +17 -12
- package/src/utils/incremental-reader.ts +104 -0
- package/src/utils/names.ts +27 -27
- package/src/utils/redaction.ts +44 -44
- package/src/utils/safe-paths.ts +47 -47
- package/src/utils/scan-cache.ts +137 -0
- package/src/utils/sleep.ts +32 -32
- package/src/utils/sse-parser.ts +134 -0
- package/src/utils/task-name-generator.ts +337 -0
- package/src/utils/visual.ts +33 -2
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/worktree/branch-freshness.ts +45 -45
- package/src/worktree/cleanup.ts +2 -1
- package/teams/default.team.md +12 -12
- package/teams/fast-fix.team.md +11 -11
- package/teams/implementation.team.md +18 -18
- package/teams/parallel-research.team.md +14 -14
- package/teams/research.team.md +11 -11
- package/teams/review.team.md +12 -12
- package/workflows/default.workflow.md +29 -29
- package/workflows/fast-fix.workflow.md +22 -22
- package/workflows/implementation.workflow.md +38 -38
- package/workflows/parallel-research.workflow.md +46 -46
- package/workflows/research.workflow.md +22 -22
- 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
|