myclaude-code 8.8.8

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 (4) hide show
  1. package/README.md +925 -0
  2. package/dist/cli.js +16667 -0
  3. package/install.sh +87 -0
  4. package/package.json +39 -0
package/README.md ADDED
@@ -0,0 +1,925 @@
1
+ # myclaude v8.8.8
2
+
3
+ `myclaude` is the first green-branded release of `我的code`, packaged from the current working `dist/cli.js` bundle in this repository.
4
+
5
+ ## Install
6
+
7
+ Requirements:
8
+
9
+ - Node.js 18 or newer
10
+ - macOS or Linux shell environment
11
+
12
+ Global npm install:
13
+
14
+ ```bash
15
+ npm install -g myclaude-code
16
+ ```
17
+
18
+ One-line install:
19
+
20
+ ```bash
21
+ curl -fsSL https://raw.githubusercontent.com/mycode699/myclaude-code/main/install.sh | bash
22
+ ```
23
+
24
+ Install a specific version:
25
+
26
+ ```bash
27
+ curl -fsSL https://raw.githubusercontent.com/mycode699/myclaude-code/main/install.sh | bash -s -- 8.8.8
28
+ ```
29
+
30
+ After install, run:
31
+
32
+ ```bash
33
+ myclaude --version
34
+ ```
35
+
36
+ ## Release Flow
37
+
38
+ - Source repo: `https://github.com/mycode699/myclaude-code`
39
+ - Release assets are generated from the tracked `dist/cli.js` bundle
40
+ - Create and push a tag like `v8.8.8` to trigger GitHub Actions release packaging
41
+ - The same tag can also publish `myclaude-code` to npm when the `NPM_TOKEN` GitHub secret is configured
42
+ - The workflow uploads:
43
+ - `myclaude-v8.8.8-node.tar.gz`
44
+ - `myclaude-v8.8.8-node.zip`
45
+ - `install.sh`
46
+ - `SHA256SUMS`
47
+
48
+ ## Local Packaging
49
+
50
+ ```bash
51
+ npm run package:release
52
+ ```
53
+
54
+ Artifacts are written to `release-artifacts/`.
55
+
56
+ ## Source Note
57
+
58
+ This repository is still based on the extracted Claude Code source bundle and keeps the upstream research notes below for reference.
59
+
60
+ # Claude Code v2.1.88 — Source Code Analysis
61
+
62
+ > Extracted from npm package `@anthropic-ai/claude-code` version **2.1.88**.
63
+ > The published package ships a single bundled `cli.js` (~12MB). The `src/` directory in this repo contains the **unbundled TypeScript source** extracted from the npm tarball.
64
+
65
+ ---
66
+
67
+ ## Missing Modules Notice (108 modules)
68
+
69
+ > **This source is incomplete.** 108 modules referenced by `feature()`-gated branches are **not included** in the npm package.
70
+ > They exist only in Anthropic's internal monorepo and were dead-code-eliminated at compile time.
71
+ > They **cannot** be recovered from `cli.js`, `sdk-tools.d.ts`, or any published artifact.
72
+
73
+ ### Anthropic Internal Code (~70 modules, never published)
74
+
75
+ These modules have no source files anywhere in the npm package. They are internal Anthropic infrastructure.
76
+
77
+ | Module | Purpose | Feature Gate |
78
+ |--------|---------|-------------|
79
+ | `daemon/main.js` | Background daemon supervisor | `DAEMON` |
80
+ | `daemon/workerRegistry.js` | Daemon worker registry | `DAEMON` |
81
+ | `proactive/index.js` | Proactive notification system | `PROACTIVE` |
82
+ | `contextCollapse/index.js` | Context collapse service (experimental) | `CONTEXT_COLLAPSE` |
83
+ | `contextCollapse/operations.js` | Collapse operations | `CONTEXT_COLLAPSE` |
84
+ | `contextCollapse/persist.js` | Collapse persistence | `CONTEXT_COLLAPSE` |
85
+ | `skillSearch/featureCheck.js` | Remote skill feature check | `EXPERIMENTAL_SKILL_SEARCH` |
86
+ | `skillSearch/remoteSkillLoader.js` | Remote skill loader | `EXPERIMENTAL_SKILL_SEARCH` |
87
+ | `skillSearch/remoteSkillState.js` | Remote skill state | `EXPERIMENTAL_SKILL_SEARCH` |
88
+ | `skillSearch/telemetry.js` | Skill search telemetry | `EXPERIMENTAL_SKILL_SEARCH` |
89
+ | `skillSearch/localSearch.js` | Local skill search | `EXPERIMENTAL_SKILL_SEARCH` |
90
+ | `skillSearch/prefetch.js` | Skill prefetch | `EXPERIMENTAL_SKILL_SEARCH` |
91
+ | `coordinator/workerAgent.js` | Multi-agent coordinator worker | `COORDINATOR_MODE` |
92
+ | `bridge/peerSessions.js` | Bridge peer session management | `BRIDGE_MODE` |
93
+ | `assistant/index.js` | Kairos assistant mode | `KAIROS` |
94
+ | `assistant/AssistantSessionChooser.js` | Assistant session picker | `KAIROS` |
95
+ | `compact/reactiveCompact.js` | Reactive context compaction | `CACHED_MICROCOMPACT` |
96
+ | `compact/snipCompact.js` | Snip-based compaction | `HISTORY_SNIP` |
97
+ | `compact/snipProjection.js` | Snip projection | `HISTORY_SNIP` |
98
+ | `compact/cachedMCConfig.js` | Cached micro-compact config | `CACHED_MICROCOMPACT` |
99
+ | `sessionTranscript/sessionTranscript.js` | Session transcript service | `TRANSCRIPT_CLASSIFIER` |
100
+ | `commands/agents-platform/index.js` | Internal agents platform | `ant` (internal) |
101
+ | `commands/assistant/index.js` | Assistant command | `KAIROS` |
102
+ | `commands/buddy/index.js` | Buddy system notifications | `BUDDY` |
103
+ | `commands/fork/index.js` | Fork subagent command | `FORK_SUBAGENT` |
104
+ | `commands/peers/index.js` | Multi-peer commands | `BRIDGE_MODE` |
105
+ | `commands/proactive.js` | Proactive command | `PROACTIVE` |
106
+ | `commands/remoteControlServer/index.js` | Remote control server | `DAEMON` + `BRIDGE_MODE` |
107
+ | `commands/subscribe-pr.js` | GitHub PR subscription | `KAIROS_GITHUB_WEBHOOKS` |
108
+ | `commands/torch.js` | Internal debug tool | `TORCH` |
109
+ | `commands/workflows/index.js` | Workflow commands | `WORKFLOW_SCRIPTS` |
110
+ | `jobs/classifier.js` | Internal job classifier | `TEMPLATES` |
111
+ | `memdir/memoryShapeTelemetry.js` | Memory shape telemetry | `MEMORY_SHAPE_TELEMETRY` |
112
+ | `services/sessionTranscript/sessionTranscript.js` | Session transcript | `TRANSCRIPT_CLASSIFIER` |
113
+ | `tasks/LocalWorkflowTask/LocalWorkflowTask.js` | Local workflow task | `WORKFLOW_SCRIPTS` |
114
+ | `protectedNamespace.js` | Internal namespace guard | `ant` (internal) |
115
+ | `protectedNamespace.js` (envUtils) | Protected namespace runtime | `ant` (internal) |
116
+ | `coreTypes.generated.js` | Generated core types | `ant` (internal) |
117
+ | `devtools.js` | Internal dev tools | `ant` (internal) |
118
+ | `attributionHooks.js` | Internal attribution hooks | `COMMIT_ATTRIBUTION` |
119
+ | `systemThemeWatcher.js` | System theme watcher | `AUTO_THEME` |
120
+ | `udsClient.js` / `udsMessaging.js` | UDS messaging client | `UDS_INBOX` |
121
+ | `systemThemeWatcher.js` | Theme watcher | `AUTO_THEME` |
122
+
123
+ ### Feature-Gated Tools (~20 modules, DCE'd from bundle)
124
+
125
+ These tools have type signatures in `sdk-tools.d.ts` but their implementations were stripped at compile time.
126
+
127
+ | Tool | Purpose | Feature Gate |
128
+ |------|---------|-------------|
129
+ | `REPLTool` | Interactive REPL (VM sandbox) | `ant` (internal) |
130
+ | `SnipTool` | Context snipping | `HISTORY_SNIP` |
131
+ | `SleepTool` | Sleep/delay in agent loop | `PROACTIVE` / `KAIROS` |
132
+ | `MonitorTool` | MCP monitoring | `MONITOR_TOOL` |
133
+ | `OverflowTestTool` | Overflow testing | `OVERFLOW_TEST_TOOL` |
134
+ | `WorkflowTool` | Workflow execution | `WORKFLOW_SCRIPTS` |
135
+ | `WebBrowserTool` | Browser automation | `WEB_BROWSER_TOOL` |
136
+ | `TerminalCaptureTool` | Terminal capture | `TERMINAL_PANEL` |
137
+ | `TungstenTool` | Internal perf monitoring | `ant` (internal) |
138
+ | `VerifyPlanExecutionTool` | Plan verification | `CLAUDE_CODE_VERIFY_PLAN` |
139
+ | `SendUserFileTool` | Send files to users | `KAIROS` |
140
+ | `SubscribePRTool` | GitHub PR subscription | `KAIROS_GITHUB_WEBHOOKS` |
141
+ | `SuggestBackgroundPRTool` | Suggest background PRs | `KAIROS` |
142
+ | `PushNotificationTool` | Push notifications | `KAIROS` |
143
+ | `CtxInspectTool` | Context inspection | `CONTEXT_COLLAPSE` |
144
+ | `ListPeersTool` | List active peers | `UDS_INBOX` |
145
+ | `DiscoverSkillsTool` | Skill discovery | `EXPERIMENTAL_SKILL_SEARCH` |
146
+
147
+ ### Text/Prompt Assets (~6 files)
148
+
149
+ These are internal prompt templates and documentation, never published.
150
+
151
+ | File | Purpose |
152
+ |------|---------|
153
+ | `yolo-classifier-prompts/auto_mode_system_prompt.txt` | Auto-mode system prompt for classifier |
154
+ | `yolo-classifier-prompts/permissions_anthropic.txt` | Anthropic-internal permission prompt |
155
+ | `yolo-classifier-prompts/permissions_external.txt` | External user permission prompt |
156
+ | `verify/SKILL.md` | Verification skill documentation |
157
+ | `verify/examples/cli.md` | CLI verification examples |
158
+ | `verify/examples/server.md` | Server verification examples |
159
+
160
+ ### Why They're Missing
161
+
162
+ ```
163
+ Anthropic Internal Monorepo Published npm Package
164
+ ────────────────────────── ─────────────────────
165
+ feature('DAEMON') → true ──build──→ feature('DAEMON') → false
166
+ ↓ ↓
167
+ daemon/main.js ← INCLUDED ──bundle─→ daemon/main.js ← DELETED (DCE)
168
+ tools/REPLTool ← INCLUDED ──bundle─→ tools/REPLTool ← DELETED (DCE)
169
+ proactive/ ← INCLUDED ──bundle─→ (referenced but absent from src/)
170
+ ```
171
+
172
+ Bun's `feature()` is a **compile-time intrinsic**:
173
+ - Returns `true` in Anthropic's internal build → code is kept in the bundle
174
+ - Returns `false` in the published build → code is dead-code-eliminated
175
+ - The 108 modules simply do not exist anywhere in the published artifact
176
+
177
+ ---
178
+
179
+ ## Copyright & Disclaimer
180
+
181
+ ```
182
+ Copyright (c) Anthropic PBC. All rights reserved.
183
+
184
+ All source code in this repository is the intellectual property of Anthropic.
185
+ This repository is provided strictly for technical research and educational purposes.
186
+ Commercial use is strictly prohibited.
187
+
188
+ If you are the copyright owner and believe this repository infringes your rights,
189
+ please contact the repository owner for immediate removal.
190
+ ```
191
+
192
+ ---
193
+
194
+ ## Stats
195
+
196
+ | Item | Count |
197
+ |------|-------|
198
+ | Source files (.ts/.tsx) | ~1,884 |
199
+ | Lines of code | ~512,664 |
200
+ | Largest single file | `query.ts` (~785KB) |
201
+ | Built-in tools | ~40+ |
202
+ | Slash commands | ~80+ |
203
+ | Dependencies (node_modules) | ~192 packages |
204
+ | Runtime | Bun (compiled to Node.js >= 18 bundle) |
205
+
206
+ ---
207
+
208
+ ## The Agent Pattern
209
+
210
+ ```
211
+ THE CORE LOOP
212
+ =============
213
+
214
+ User --> messages[] --> Claude API --> response
215
+ |
216
+ stop_reason == "tool_use"?
217
+ / \
218
+ yes no
219
+ | |
220
+ execute tools return text
221
+ append tool_result
222
+ loop back -----------------> messages[]
223
+
224
+
225
+ That is the minimal agent loop. Claude Code wraps this loop
226
+ with a production-grade harness: permissions, streaming,
227
+ concurrency, compaction, sub-agents, persistence, and MCP.
228
+ ```
229
+
230
+ ---
231
+
232
+ ## Directory Reference
233
+
234
+ ```
235
+ src/
236
+ ├── main.tsx # REPL bootstrap, 4,683 lines
237
+ ├── QueryEngine.ts # SDK/headless query lifecycle engine
238
+ ├── query.ts # Main agent loop (785KB, largest file)
239
+ ├── Tool.ts # Tool interface + buildTool factory
240
+ ├── Task.ts # Task types, IDs, state base
241
+ ├── tools.ts # Tool registry, presets, filtering
242
+ ├── commands.ts # Slash command definitions
243
+ ├── context.ts # User input context
244
+ ├── cost-tracker.ts # API cost accumulation
245
+ ├── setup.ts # First-run setup flow
246
+
247
+ ├── bridge/ # Claude Desktop / remote bridge
248
+ │ ├── bridgeMain.ts # Session lifecycle manager
249
+ │ ├── bridgeApi.ts # HTTP client
250
+ │ ├── bridgeConfig.ts # Connection config
251
+ │ ├── bridgeMessaging.ts # Message relay
252
+ │ ├── sessionRunner.ts # Process spawning
253
+ │ ├── jwtUtils.ts # JWT refresh
254
+ │ ├── workSecret.ts # Auth tokens
255
+ │ └── capacityWake.ts # Capacity-based wakeup
256
+
257
+ ├── cli/ # CLI infrastructure
258
+ │ ├── handlers/ # Command handlers
259
+ │ └── transports/ # I/O transports (stdio, structured)
260
+
261
+ ├── commands/ # ~80 slash commands
262
+ │ ├── agents/ # Agent management
263
+ │ ├── compact/ # Context compaction
264
+ │ ├── config/ # Settings management
265
+ │ ├── help/ # Help display
266
+ │ ├── login/ # Authentication
267
+ │ ├── mcp/ # MCP server management
268
+ │ ├── memory/ # Memory system
269
+ │ ├── plan/ # Plan mode
270
+ │ ├── resume/ # Session resume
271
+ │ ├── review/ # Code review
272
+ │ └── ... # 70+ more commands
273
+
274
+ ├── components/ # React/Ink terminal UI
275
+ │ ├── design-system/ # Reusable UI primitives
276
+ │ ├── messages/ # Message rendering
277
+ │ ├── permissions/ # Permission dialogs
278
+ │ ├── PromptInput/ # Input field + suggestions
279
+ │ ├── LogoV2/ # Branding + welcome screen
280
+ │ ├── Settings/ # Settings panels
281
+ │ ├── Spinner.tsx # Loading indicators
282
+ │ └── ... # 40+ component groups
283
+
284
+ ├── entrypoints/ # Application entry points
285
+ │ ├── cli.tsx # CLI main (version, help, daemon)
286
+ │ ├── sdk/ # Agent SDK (types, sessions)
287
+ │ └── mcp.ts # MCP server entry
288
+
289
+ ├── hooks/ # React hooks
290
+ │ ├── useCanUseTool.tsx # Permission checking
291
+ │ ├── useReplBridge.tsx # Bridge connection
292
+ │ ├── notifs/ # Notification hooks
293
+ │ └── toolPermission/ # Tool permission handlers
294
+
295
+ ├── services/ # Business logic layer
296
+ │ ├── api/ # Claude API client
297
+ │ │ ├── claude.ts # Streaming API calls
298
+ │ │ ├── errors.ts # Error categorization
299
+ │ │ └── withRetry.ts # Retry logic
300
+ │ ├── analytics/ # Telemetry + GrowthBook
301
+ │ ├── compact/ # Context compression
302
+ │ ├── mcp/ # MCP connection management
303
+ │ ├── tools/ # Tool execution engine
304
+ │ │ ├── StreamingToolExecutor.ts # Parallel tool runner
305
+ │ │ └── toolOrchestration.ts # Batch orchestration
306
+ │ ├── plugins/ # Plugin loader
307
+ │ └── settingsSync/ # Cross-device settings
308
+
309
+ ├── state/ # Application state
310
+ │ ├── AppStateStore.ts # Store definition
311
+ │ └── AppState.tsx # React provider + hooks
312
+
313
+ ├── tasks/ # Task implementations
314
+ │ ├── LocalShellTask/ # Bash command execution
315
+ │ ├── LocalAgentTask/ # Sub-agent execution
316
+ │ ├── RemoteAgentTask/ # Remote agent via bridge
317
+ │ ├── InProcessTeammateTask/ # In-process teammate
318
+ │ └── DreamTask/ # Background thinking
319
+
320
+ ├── tools/ # 40+ tool implementations
321
+ │ ├── AgentTool/ # Sub-agent spawning + fork
322
+ │ ├── BashTool/ # Shell command execution
323
+ │ ├── FileReadTool/ # File reading (PDF, image, etc)
324
+ │ ├── FileEditTool/ # String-replace editing
325
+ │ ├── FileWriteTool/ # Full file creation
326
+ │ ├── GlobTool/ # File pattern search
327
+ │ ├── GrepTool/ # Content search (ripgrep)
328
+ │ ├── WebFetchTool/ # HTTP fetching
329
+ │ ├── WebSearchTool/ # Web search
330
+ │ ├── MCPTool/ # MCP tool wrapper
331
+ │ ├── SkillTool/ # Skill invocation
332
+ │ ├── AskUserQuestionTool/ # User interaction
333
+ │ └── ... # 30+ more tools
334
+
335
+ ├── types/ # Type definitions
336
+ │ ├── message.ts # Message discriminated unions
337
+ │ ├── permissions.ts # Permission types
338
+ │ ├── tools.ts # Tool progress types
339
+ │ └── ids.ts # Branded ID types
340
+
341
+ ├── utils/ # Utilities (largest directory)
342
+ │ ├── permissions/ # Permission rule engine
343
+ │ ├── messages/ # Message formatting
344
+ │ ├── model/ # Model selection logic
345
+ │ ├── settings/ # Settings management
346
+ │ ├── sandbox/ # Sandbox runtime adapter
347
+ │ ├── hooks/ # Hook execution
348
+ │ ├── memory/ # Memory system utils
349
+ │ ├── git/ # Git operations
350
+ │ ├── github/ # GitHub API
351
+ │ ├── bash/ # Bash execution helpers
352
+ │ ├── swarm/ # Multi-agent swarm
353
+ │ ├── telemetry/ # Telemetry reporting
354
+ │ └── ... # 30+ more util groups
355
+
356
+ └── vendor/ # Native module source stubs
357
+ ├── audio-capture-src/ # Audio input
358
+ ├── image-processor-src/ # Image processing
359
+ ├── modifiers-napi-src/ # Native modifiers
360
+ └── url-handler-src/ # URL handling
361
+ ```
362
+
363
+ ---
364
+
365
+ ## Architecture Overview
366
+
367
+ ```
368
+ ┌─────────────────────────────────────────────────────────────────────┐
369
+ │ ENTRY LAYER │
370
+ │ cli.tsx ──> main.tsx ──> REPL.tsx (interactive) │
371
+ │ └──> QueryEngine.ts (headless/SDK) │
372
+ └──────────────────────────────┬──────────────────────────────────────┘
373
+
374
+
375
+ ┌─────────────────────────────────────────────────────────────────────┐
376
+ │ QUERY ENGINE │
377
+ │ submitMessage(prompt) ──> AsyncGenerator<SDKMessage> │
378
+ │ │ │
379
+ │ ├── fetchSystemPromptParts() ──> assemble system prompt │
380
+ │ ├── processUserInput() ──> handle /commands │
381
+ │ ├── query() ──> main agent loop │
382
+ │ │ ├── StreamingToolExecutor ──> parallel tool execution │
383
+ │ │ ├── autoCompact() ──> context compression │
384
+ │ │ └── runTools() ──> tool orchestration │
385
+ │ └── yield SDKMessage ──> stream to consumer │
386
+ └──────────────────────────────┬──────────────────────────────────────┘
387
+
388
+ ┌────────────────┼────────────────┐
389
+ ▼ ▼ ▼
390
+ ┌──────────────────┐ ┌─────────────────┐ ┌──────────────────┐
391
+ │ TOOL SYSTEM │ │ SERVICE LAYER │ │ STATE LAYER │
392
+ │ │ │ │ │ │
393
+ │ Tool Interface │ │ api/claude.ts │ │ AppState Store │
394
+ │ ├─ call() │ │ API client │ │ ├─ permissions │
395
+ │ ├─ validate() │ │ compact/ │ │ ├─ fileHistory │
396
+ │ ├─ checkPerms() │ │ auto-compact │ │ ├─ agents │
397
+ │ ├─ render() │ │ mcp/ │ │ └─ fastMode │
398
+ │ └─ prompt() │ │ MCP protocol │ │ │
399
+ │ │ │ analytics/ │ │ React Context │
400
+ │ 40+ Built-in: │ │ telemetry │ │ ├─ useAppState │
401
+ │ ├─ BashTool │ │ tools/ │ │ └─ useSetState │
402
+ │ ├─ FileRead │ │ executor │ │ │
403
+ │ ├─ FileEdit │ │ plugins/ │ └──────────────────┘
404
+ │ ├─ Glob/Grep │ │ loader │
405
+ │ ├─ AgentTool │ │ settingsSync/ │
406
+ │ ├─ WebFetch │ │ cross-device │
407
+ │ └─ MCPTool │ │ oauth/ │
408
+ │ │ │ auth flow │
409
+ └──────────────────┘ └─────────────────┘
410
+ │ │
411
+ ▼ ▼
412
+ ┌──────────────────┐ ┌─────────────────┐
413
+ │ TASK SYSTEM │ │ BRIDGE LAYER │
414
+ │ │ │ │
415
+ │ Task Types: │ │ bridgeMain.ts │
416
+ │ ├─ local_bash │ │ session mgmt │
417
+ │ ├─ local_agent │ │ bridgeApi.ts │
418
+ │ ├─ remote_agent │ │ HTTP client │
419
+ │ ├─ in_process │ │ workSecret.ts │
420
+ │ ├─ dream │ │ auth tokens │
421
+ │ └─ workflow │ │ sessionRunner │
422
+ │ │ │ process spawn │
423
+ │ ID: prefix+8chr │ └─────────────────┘
424
+ │ b=bash a=agent │
425
+ │ r=remote t=team │
426
+ └──────────────────┘
427
+ ```
428
+
429
+ ---
430
+
431
+ ## Data Flow: A Single Query Lifecycle
432
+
433
+ ```
434
+ USER INPUT (prompt / slash command)
435
+
436
+
437
+ processUserInput() ← parse /commands, build UserMessage
438
+
439
+
440
+ fetchSystemPromptParts() ← tools → prompt sections, CLAUDE.md memory
441
+
442
+
443
+ recordTranscript() ← persist user message to disk (JSONL)
444
+
445
+
446
+ ┌─→ normalizeMessagesForAPI() ← strip UI-only fields, compact if needed
447
+ │ │
448
+ │ ▼
449
+ │ Claude API (streaming) ← POST /v1/messages with tools + system prompt
450
+ │ │
451
+ │ ▼
452
+ │ stream events ← message_start → content_block_delta → message_stop
453
+ │ │
454
+ │ ├─ text block ──────────────→ yield to consumer (SDK / REPL)
455
+ │ │
456
+ │ └─ tool_use block?
457
+ │ │
458
+ │ ▼
459
+ │ StreamingToolExecutor ← partition: concurrent-safe vs serial
460
+ │ │
461
+ │ ▼
462
+ │ canUseTool() ← permission check (hooks + rules + UI prompt)
463
+ │ │
464
+ │ ├─ DENY ────────────────→ append tool_result(error), continue loop
465
+ │ │
466
+ │ └─ ALLOW
467
+ │ │
468
+ │ ▼
469
+ │ tool.call() ← execute the tool (Bash, Read, Edit, etc.)
470
+ │ │
471
+ │ ▼
472
+ │ append tool_result ← push to messages[], recordTranscript()
473
+ │ │
474
+ └─────────┘ ← loop back to API call
475
+
476
+ ▼ (stop_reason != "tool_use")
477
+ yield result message ← final text, usage, cost, session_id
478
+ ```
479
+
480
+ ---
481
+
482
+ ## Tool System Architecture
483
+
484
+ ```
485
+ TOOL INTERFACE
486
+ ==============
487
+
488
+ buildTool(definition) ──> Tool<Input, Output, Progress>
489
+
490
+ Every tool implements:
491
+ ┌────────────────────────────────────────────────────────┐
492
+ │ LIFECYCLE │
493
+ │ ├── validateInput() → reject bad args early │
494
+ │ ├── checkPermissions() → tool-specific authz │
495
+ │ └── call() → execute and return result │
496
+ │ │
497
+ │ CAPABILITIES │
498
+ │ ├── isEnabled() → feature gate check │
499
+ │ ├── isConcurrencySafe() → can run in parallel? │
500
+ │ ├── isReadOnly() → no side effects? │
501
+ │ ├── isDestructive() → irreversible ops? │
502
+ │ └── interruptBehavior() → cancel or block on user? │
503
+ │ │
504
+ │ RENDERING (React/Ink) │
505
+ │ ├── renderToolUseMessage() → input display │
506
+ │ ├── renderToolResultMessage() → output display │
507
+ │ ├── renderToolUseProgressMessage() → spinner/status │
508
+ │ └── renderGroupedToolUse() → parallel tool groups │
509
+ │ │
510
+ │ AI FACING │
511
+ │ ├── prompt() → tool description for LLM │
512
+ │ ├── description() → dynamic description │
513
+ │ └── mapToolResultToAPI() → format for API response │
514
+ └────────────────────────────────────────────────────────┘
515
+ ```
516
+
517
+ ### Complete Tool Inventory
518
+
519
+ ```
520
+ FILE OPERATIONS SEARCH & DISCOVERY EXECUTION
521
+ ═════════════════ ══════════════════════ ══════════
522
+ FileReadTool GlobTool BashTool
523
+ FileEditTool GrepTool PowerShellTool
524
+ FileWriteTool ToolSearchTool
525
+ NotebookEditTool INTERACTION
526
+ ═══════════
527
+ WEB & NETWORK AGENT / TASK AskUserQuestionTool
528
+ ════════════════ ══════════════════ BriefTool
529
+ WebFetchTool AgentTool
530
+ WebSearchTool SendMessageTool PLANNING & WORKFLOW
531
+ TeamCreateTool ════════════════════
532
+ MCP PROTOCOL TeamDeleteTool EnterPlanModeTool
533
+ ══════════════ TaskCreateTool ExitPlanModeTool
534
+ MCPTool TaskGetTool EnterWorktreeTool
535
+ ListMcpResourcesTool TaskUpdateTool ExitWorktreeTool
536
+ ReadMcpResourceTool TaskListTool TodoWriteTool
537
+ TaskStopTool
538
+ TaskOutputTool SYSTEM
539
+ ════════
540
+ SKILLS & EXTENSIONS ConfigTool
541
+ ═════════════════════ SkillTool
542
+ SkillTool ScheduleCronTool
543
+ LSPTool SleepTool
544
+ TungstenTool
545
+ ```
546
+
547
+ ---
548
+
549
+ ## Permission System
550
+
551
+ ```
552
+ TOOL CALL REQUEST
553
+
554
+
555
+ ┌─ validateInput() ──────────────────────────────────┐
556
+ │ reject invalid inputs before any permission check │
557
+ └────────────────────┬───────────────────────────────┘
558
+
559
+
560
+ ┌─ PreToolUse Hooks ─────────────────────────────────┐
561
+ │ user-defined shell commands (settings.json hooks) │
562
+ │ can: approve, deny, or modify input │
563
+ └────────────────────┬───────────────────────────────┘
564
+
565
+
566
+ ┌─ Permission Rules ─────────────────────────────────┐
567
+ │ alwaysAllowRules: match tool name/pattern → auto │
568
+ │ alwaysDenyRules: match tool name/pattern → deny │
569
+ │ alwaysAskRules: match tool name/pattern → ask │
570
+ │ Sources: settings, CLI args, session decisions │
571
+ └────────────────────┬───────────────────────────────┘
572
+
573
+ no rule match?
574
+
575
+
576
+ ┌─ Interactive Prompt ───────────────────────────────┐
577
+ │ User sees tool name + input │
578
+ │ Options: Allow Once / Allow Always / Deny │
579
+ └────────────────────┬───────────────────────────────┘
580
+
581
+
582
+ ┌─ checkPermissions() ───────────────────────────────┐
583
+ │ Tool-specific logic (e.g. path sandboxing) │
584
+ └────────────────────┬───────────────────────────────┘
585
+
586
+ APPROVED → tool.call()
587
+ ```
588
+
589
+ ---
590
+
591
+ ## Sub-Agent & Multi-Agent Architecture
592
+
593
+ ```
594
+ MAIN AGENT
595
+ ==========
596
+
597
+ ┌───────────────┼───────────────┐
598
+ ▼ ▼ ▼
599
+ ┌──────────────┐ ┌──────────┐ ┌──────────────┐
600
+ │ FORK AGENT │ │ REMOTE │ │ IN-PROCESS │
601
+ │ │ │ AGENT │ │ TEAMMATE │
602
+ │ Fork process │ │ Bridge │ │ Same process │
603
+ │ Shared cache │ │ session │ │ Async context│
604
+ │ Fresh msgs[] │ │ Isolated │ │ Shared state │
605
+ └──────────────┘ └──────────┘ └──────────────┘
606
+
607
+ SPAWN MODES:
608
+ ├─ default → in-process, shared conversation
609
+ ├─ fork → child process, fresh messages[], shared file cache
610
+ ├─ worktree → isolated git worktree + fork
611
+ └─ remote → bridge to Claude Code Remote / container
612
+
613
+ COMMUNICATION:
614
+ ├─ SendMessageTool → agent-to-agent messages
615
+ ├─ TaskCreate/Update → shared task board
616
+ └─ TeamCreate/Delete → team lifecycle management
617
+
618
+ SWARM MODE (feature-gated):
619
+ ┌─────────────────────────────────────────────┐
620
+ │ Lead Agent │
621
+ │ ├── Teammate A ──> claims Task 1 │
622
+ │ ├── Teammate B ──> claims Task 2 │
623
+ │ └── Teammate C ──> claims Task 3 │
624
+ │ │
625
+ │ Shared: task board, message inbox │
626
+ │ Isolated: messages[], file cache, cwd │
627
+ └─────────────────────────────────────────────┘
628
+ ```
629
+
630
+ ---
631
+
632
+ ## Context Management (Compact System)
633
+
634
+ ```
635
+ CONTEXT WINDOW BUDGET
636
+ ═════════════════════
637
+
638
+ ┌─────────────────────────────────────────────────────┐
639
+ │ System Prompt (tools, permissions, CLAUDE.md) │
640
+ │ ══════════════════════════════════════════════ │
641
+ │ │
642
+ │ Conversation History │
643
+ │ ┌─────────────────────────────────────────────┐ │
644
+ │ │ [compacted summary of older messages] │ │
645
+ │ │ ═══════════════════════════════════════════ │ │
646
+ │ │ [compact_boundary marker] │ │
647
+ │ │ ─────────────────────────────────────────── │ │
648
+ │ │ [recent messages — full fidelity] │ │
649
+ │ │ user → assistant → tool_use → tool_result │ │
650
+ │ └─────────────────────────────────────────────┘ │
651
+ │ │
652
+ │ Current Turn (user + assistant response) │
653
+ └─────────────────────────────────────────────────────┘
654
+
655
+ THREE COMPRESSION STRATEGIES:
656
+ ├─ autoCompact → triggers when token count exceeds threshold
657
+ │ summarizes old messages via a compact API call
658
+ ├─ snipCompact → removes zombie messages and stale markers
659
+ │ (HISTORY_SNIP feature flag)
660
+ └─ contextCollapse → restructures context for efficiency
661
+ (CONTEXT_COLLAPSE feature flag)
662
+
663
+ COMPACTION FLOW:
664
+ messages[] ──> getMessagesAfterCompactBoundary()
665
+
666
+
667
+ older messages ──> Claude API (summarize) ──> compact summary
668
+
669
+
670
+ [summary] + [compact_boundary] + [recent messages]
671
+ ```
672
+
673
+ ---
674
+
675
+ ## MCP (Model Context Protocol) Integration
676
+
677
+ ```
678
+ ┌─────────────────────────────────────────────────────────┐
679
+ │ MCP ARCHITECTURE │
680
+ │ │
681
+ │ MCPConnectionManager.tsx │
682
+ │ ├── Server Discovery (config from settings.json) │
683
+ │ │ ├── stdio → spawn child process │
684
+ │ │ ├── sse → HTTP EventSource │
685
+ │ │ ├── http → Streamable HTTP │
686
+ │ │ ├── ws → WebSocket │
687
+ │ │ └── sdk → in-process transport │
688
+ │ │ │
689
+ │ ├── Client Lifecycle │
690
+ │ │ ├── connect → initialize → list tools │
691
+ │ │ ├── tool calls via MCPTool wrapper │
692
+ │ │ └── disconnect / reconnect with backoff │
693
+ │ │ │
694
+ │ ├── Authentication │
695
+ │ │ ├── OAuth 2.0 flow (McpOAuthConfig) │
696
+ │ │ ├── Cross-App Access (XAA / SEP-990) │
697
+ │ │ └── API key via headers │
698
+ │ │ │
699
+ │ └── Tool Registration │
700
+ │ ├── mcp__<server>__<tool> naming convention │
701
+ │ ├── Dynamic schema from MCP server │
702
+ │ ├── Permission passthrough to Claude Code │
703
+ │ └── Resource listing (ListMcpResourcesTool) │
704
+ │ │
705
+ └─────────────────────────────────────────────────────────┘
706
+ ```
707
+
708
+ ---
709
+
710
+ ## Bridge Layer (Claude Desktop / Remote)
711
+
712
+ ```
713
+ Claude Desktop / Web / Cowork Claude Code CLI
714
+ ══════════════════════════ ═════════════════
715
+
716
+ ┌───────────────────┐ ┌──────────────────┐
717
+ │ Bridge Client │ ←─ HTTP ──→ │ bridgeMain.ts │
718
+ │ (Desktop App) │ │ │
719
+ └───────────────────┘ │ Session Manager │
720
+ │ ├── spawn CLI │
721
+ PROTOCOL: │ ├── poll status │
722
+ ├─ JWT authentication │ ├── relay msgs │
723
+ ├─ Work secret exchange │ └── capacityWake │
724
+ ├─ Session lifecycle │ │
725
+ │ ├── create │ Backoff: │
726
+ │ ├── run │ ├─ conn: 2s→2m │
727
+ │ └─ stop │ └─ gen: 500ms→30s│
728
+ └─ Token refresh scheduler └──────────────────┘
729
+ ```
730
+
731
+ ---
732
+
733
+ ## Session Persistence
734
+
735
+ ```
736
+ SESSION STORAGE
737
+ ══════════════
738
+
739
+ ~/.claude/projects/<hash>/sessions/
740
+ └── <session-id>.jsonl ← append-only log
741
+ ├── {"type":"user",...}
742
+ ├── {"type":"assistant",...}
743
+ ├── {"type":"progress",...}
744
+ └── {"type":"system","subtype":"compact_boundary",...}
745
+
746
+ RESUME FLOW:
747
+ getLastSessionLog() ──> parse JSONL ──> rebuild messages[]
748
+
749
+ ├── --continue → last session in cwd
750
+ ├── --resume <id> → specific session
751
+ └── --fork-session → new ID, copy history
752
+
753
+ PERSISTENCE STRATEGY:
754
+ ├─ User messages → await write (blocking, for crash recovery)
755
+ ├─ Assistant msgs → fire-and-forget (order-preserving queue)
756
+ ├─ Progress → inline write (dedup on next query)
757
+ └─ Flush → on result yield / cowork eager flush
758
+ ```
759
+
760
+ ---
761
+
762
+ ## Feature Flag System
763
+
764
+ ```
765
+ DEAD CODE ELIMINATION (Bun compile-time)
766
+ ══════════════════════════════════════════
767
+
768
+ feature('FLAG_NAME') ──→ true → included in bundle
769
+ ──→ false → stripped from bundle
770
+
771
+ FLAGS (observed in source):
772
+ ├─ COORDINATOR_MODE → multi-agent coordinator
773
+ ├─ HISTORY_SNIP → aggressive history trimming
774
+ ├─ CONTEXT_COLLAPSE → context restructuring
775
+ ├─ DAEMON → background daemon workers
776
+ ├─ AGENT_TRIGGERS → cron/remote triggers
777
+ ├─ AGENT_TRIGGERS_REMOTE → remote trigger support
778
+ ├─ MONITOR_TOOL → MCP monitoring tool
779
+ ├─ WEB_BROWSER_TOOL → browser automation
780
+ ├─ VOICE_MODE → voice input/output
781
+ ├─ TEMPLATES → job classifier
782
+ ├─ EXPERIMENTAL_SKILL_SEARCH → skill discovery
783
+ ├─ KAIROS → push notifications, file sends
784
+ ├─ PROACTIVE → sleep tool, proactive behavior
785
+ ├─ OVERFLOW_TEST_TOOL → testing tool
786
+ ├─ TERMINAL_PANEL → terminal capture
787
+ ├─ WORKFLOW_SCRIPTS → workflow tool
788
+ ├─ CHICAGO_MCP → computer use MCP
789
+ ├─ DUMP_SYSTEM_PROMPT → prompt extraction (ant-only)
790
+ ├─ UDS_INBOX → peer discovery
791
+ ├─ ABLATION_BASELINE → experiment ablation
792
+ └─ UPGRADE_NOTICE → upgrade notifications
793
+
794
+ RUNTIME GATES:
795
+ ├─ process.env.USER_TYPE === 'ant' → Anthropic-internal features
796
+ └─ GrowthBook feature flags → A/B experiments at runtime
797
+ ```
798
+
799
+ ---
800
+
801
+ ## State Management
802
+
803
+ ```
804
+ ┌──────────────────────────────────────────────────────────┐
805
+ │ AppState Store │
806
+ │ │
807
+ │ AppState { │
808
+ │ toolPermissionContext: { │
809
+ │ mode: PermissionMode, ← default/plan/etc │
810
+ │ additionalWorkingDirectories, │
811
+ │ alwaysAllowRules, ← auto-approve │
812
+ │ alwaysDenyRules, ← auto-reject │
813
+ │ alwaysAskRules, ← always prompt │
814
+ │ isBypassPermissionsModeAvailable │
815
+ │ }, │
816
+ │ fileHistory: FileHistoryState, ← undo snapshots │
817
+ │ attribution: AttributionState, ← commit tracking │
818
+ │ verbose: boolean, │
819
+ │ mainLoopModel: string, ← active model │
820
+ │ fastMode: FastModeState, │
821
+ │ speculation: SpeculationState │
822
+ │ } │
823
+ │ │
824
+ │ React Integration: │
825
+ │ ├── AppStateProvider → creates store via createContext │
826
+ │ ├── useAppState(sel) → selector-based subscriptions │
827
+ │ └── useSetAppState() → immer-style updater function │
828
+ └──────────────────────────────────────────────────────────┘
829
+ ```
830
+
831
+ ---
832
+
833
+ ## The 12 Progressive Harness Mechanisms
834
+
835
+ This source code demonstrates 12 layered mechanisms that a production AI agent harness needs beyond the basic loop. Each builds on the previous:
836
+
837
+ ```
838
+ s01 THE LOOP "One loop & Bash is all you need"
839
+ query.ts: the while-true loop that calls Claude API,
840
+ checks stop_reason, executes tools, appends results.
841
+
842
+ s02 TOOL DISPATCH "Adding a tool = adding one handler"
843
+ Tool.ts + tools.ts: every tool registers into the dispatch
844
+ map. The loop stays identical. buildTool() factory provides
845
+ safe defaults.
846
+
847
+ s03 PLANNING "An agent without a plan drifts"
848
+ EnterPlanModeTool/ExitPlanModeTool + TodoWriteTool:
849
+ list steps first, then execute. Doubles completion rate.
850
+
851
+ s04 SUB-AGENTS "Break big tasks; clean context per subtask"
852
+ AgentTool + forkSubagent.ts: each child gets fresh messages[],
853
+ keeping the main conversation clean.
854
+
855
+ s05 KNOWLEDGE ON DEMAND "Load knowledge when you need it"
856
+ SkillTool + memdir/: inject via tool_result, not system prompt.
857
+ CLAUDE.md files loaded lazily per directory.
858
+
859
+ s06 CONTEXT COMPRESSION "Context fills up; make room"
860
+ services/compact/: three-layer strategy:
861
+ autoCompact (summarize) + snipCompact (trim) + contextCollapse
862
+
863
+ s07 PERSISTENT TASKS "Big goals → small tasks → disk"
864
+ TaskCreate/Update/Get/List: file-based task graph with
865
+ status tracking, dependencies, and persistence.
866
+
867
+ s08 BACKGROUND TASKS "Slow ops in background; agent keeps thinking"
868
+ DreamTask + LocalShellTask: daemon threads run commands,
869
+ inject notifications on completion.
870
+
871
+ s09 AGENT TEAMS "Too big for one → delegate to teammates"
872
+ TeamCreate/Delete + InProcessTeammateTask: persistent
873
+ teammates with async mailboxes.
874
+
875
+ s10 TEAM PROTOCOLS "Shared communication rules"
876
+ SendMessageTool: one request-response pattern drives
877
+ all negotiation between agents.
878
+
879
+ s11 AUTONOMOUS AGENTS "Teammates scan and claim tasks themselves"
880
+ coordinator/coordinatorMode.ts: idle cycle + auto-claim,
881
+ no need for lead to assign each task.
882
+
883
+ s12 WORKTREE ISOLATION "Each works in its own directory"
884
+ EnterWorktreeTool/ExitWorktreeTool: tasks manage goals,
885
+ worktrees manage directories, bound by ID.
886
+ ```
887
+
888
+ ---
889
+
890
+ ## Key Design Patterns
891
+
892
+ | Pattern | Where | Purpose |
893
+ |---------|-------|---------|
894
+ | **AsyncGenerator streaming** | `QueryEngine`, `query()` | Full-chain streaming from API to consumer |
895
+ | **Builder + Factory** | `buildTool()` | Safe defaults for tool definitions |
896
+ | **Branded Types** | `SystemPrompt`, `asSystemPrompt()` | Prevent string/array confusion |
897
+ | **Feature Flags + DCE** | `feature()` from `bun:bundle` | Compile-time dead code elimination |
898
+ | **Discriminated Unions** | `Message` types | Type-safe message handling |
899
+ | **Observer + State Machine** | `StreamingToolExecutor` | Tool execution lifecycle tracking |
900
+ | **Snapshot State** | `FileHistoryState` | Undo/redo for file operations |
901
+ | **Ring Buffer** | Error log | Bounded memory for long sessions |
902
+ | **Fire-and-Forget Write** | `recordTranscript()` | Non-blocking persistence with ordering |
903
+ | **Lazy Schema** | `lazySchema()` | Defer Zod schema evaluation for performance |
904
+ | **Context Isolation** | `AsyncLocalStorage` | Per-agent context in shared process |
905
+
906
+ ---
907
+
908
+ ## Build Notes
909
+
910
+ This source is **not directly compilable** from this repo alone:
911
+
912
+ - Missing `tsconfig.json`, build scripts, and Bun bundler config
913
+ - `feature()` calls are Bun compile-time intrinsics — resolved during bundling
914
+ - `MACRO.VERSION` is injected at build time
915
+ - `process.env.USER_TYPE === 'ant'` sections are Anthropic-internal
916
+ - The compiled `cli.js` is a self-contained 12MB bundle requiring only Node.js >= 18
917
+ - Source maps (`cli.js.map`, 60MB) map back to these source files for debugging
918
+
919
+ **See [QUICKSTART.md](QUICKSTART.md) for build instructions and workarounds.**
920
+
921
+ ---
922
+
923
+ ## License
924
+
925
+ All source code in this repository is copyright **Anthropic PBC**. This repository is for technical research and education only. See the original npm package for full license terms.