claude-multi-session 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,545 @@
1
+ # claude-multi-session
2
+
3
+ **Multi-session orchestrator for Claude Code CLI** — spawn, control, pause, resume, and send multiple inputs to Claude Code sessions programmatically.
4
+
5
+ Built on Claude CLI's `stream-json` protocol for efficient multi-turn conversations using a single long-lived process per session.
6
+
7
+ ## Why?
8
+
9
+ Claude Code's `-p` (print) mode is one-shot: one prompt, one response. For larger projects you need:
10
+
11
+ - **Multi-turn conversations** — send follow-ups without restarting
12
+ - **Parallel sessions** — work on multiple tasks simultaneously
13
+ - **Pause & Resume** — stop a session and come back later
14
+ - **Session forking** — branch off to try different approaches
15
+ - **Cost tracking** — know what each session costs
16
+ - **Programmatic control** — use from scripts or other tools
17
+
18
+ This package solves all of the above with zero dependencies.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npm install -g claude-multi-session
24
+ ```
25
+
26
+ ### Quick Setup (MCP Integration)
27
+
28
+ After installing, run the setup wizard to register the MCP server with Claude Code:
29
+
30
+ ```bash
31
+ cms setup
32
+ ```
33
+
34
+ This adds 17 native tools to Claude Code (spawn_session, delegate_task, etc.) so Claude can manage sessions directly — no Bash commands needed.
35
+
36
+ **Non-interactive options:**
37
+ ```bash
38
+ cms setup --global # Register for all projects
39
+ cms setup --local # Register for current project only
40
+ cms setup --global --guide # Also add strategy guide to CLAUDE.md
41
+ cms setup --uninstall # Remove MCP integration
42
+ ```
43
+
44
+ ### CLI Usage
45
+
46
+ Use `cms` (or `claude-multi-session`) from anywhere:
47
+
48
+ ```bash
49
+ cms spawn --name my-task --prompt "Fix the auth bug"
50
+ cms send --name my-task --message "Also add tests"
51
+ ```
52
+
53
+ **Or use without installing:**
54
+ ```bash
55
+ npx claude-multi-session spawn --name my-task --prompt "Fix the auth bug"
56
+ ```
57
+
58
+ **Prerequisites:** [Claude Code CLI](https://claude.ai/code) must be installed and authenticated.
59
+
60
+ ## Quick Start
61
+
62
+ ```bash
63
+ # Start a session with a prompt
64
+ cms spawn --name fix-auth --prompt "Fix the authentication bug in auth.service.ts" --model sonnet
65
+
66
+ # Send follow-up messages (same session, full context retained)
67
+ cms send --name fix-auth --message "Also add input validation"
68
+ cms send --name fix-auth --message "Now write tests for it"
69
+
70
+ # Stop when done (can resume later)
71
+ cms stop --name fix-auth
72
+
73
+ # Resume days later
74
+ cms resume --name fix-auth --message "Actually, handle the edge case too"
75
+
76
+ # Check what happened
77
+ cms output --name fix-auth --full
78
+ ```
79
+
80
+ ## Commands
81
+
82
+ | Command | Description |
83
+ |---------|-------------|
84
+ | `spawn` | Start a new session |
85
+ | `send` | Send follow-up message (auto-resumes if stopped) |
86
+ | `resume` | Restore a stopped/paused session |
87
+ | `pause` | Pause session (process stays alive) |
88
+ | `fork` | Branch off into new session (keeps parent context) |
89
+ | `stop` | Gracefully stop (saves state, can resume later) |
90
+ | `kill` | Force kill a session |
91
+ | `status` | Show detailed session info |
92
+ | `output` | Get last response text |
93
+ | `list` | List all sessions |
94
+ | `history` | Show full interaction history |
95
+ | `delete` | Permanently remove a session |
96
+ | `batch` | Spawn multiple sessions from JSON file |
97
+ | `cleanup` | Remove old sessions |
98
+ | `delegate` | Smart task delegation with safety limits + control loop |
99
+ | `continue` | Send follow-up to a delegated session |
100
+
101
+ ## How It Works
102
+
103
+ ### Streaming Mode (Default)
104
+
105
+ Uses Claude CLI's `--input-format stream-json` to keep **one process alive** per session:
106
+
107
+ ```
108
+ spawn → starts ONE claude process (stays alive)
109
+ send → pipes message into stdin → reads response from stdout
110
+ send → pipes again → reads again (same process, no reload)
111
+ ```
112
+
113
+ **Benefits over the resume approach:**
114
+ - No process restart overhead (~2-3s saved per message)
115
+ - No conversation history reload (lower token cost)
116
+ - Instant follow-up responses
117
+
118
+ ### Session Persistence
119
+
120
+ Sessions are saved to `~/.claude-multi-session/sessions.json`. When a session is stopped, its Claude session ID is saved. When you resume it later, the system uses `--resume <session-id>` to restore the full conversation context.
121
+
122
+ ## Parallel Tasks
123
+
124
+ ### Batch Mode
125
+ ```bash
126
+ # Create a tasks.json file
127
+ echo '[
128
+ { "name": "task-1", "prompt": "Build login page", "model": "sonnet" },
129
+ { "name": "task-2", "prompt": "Build signup page", "model": "sonnet" },
130
+ { "name": "task-3", "prompt": "Build dashboard", "model": "sonnet" }
131
+ ]' > tasks.json
132
+
133
+ # Spawn all in parallel
134
+ cms batch --file tasks.json
135
+ ```
136
+
137
+ ### Programmatic API
138
+ ```javascript
139
+ const { SessionManager } = require('claude-multi-session');
140
+ const mgr = new SessionManager();
141
+
142
+ // Spawn multiple sessions in parallel
143
+ const results = await mgr.batch([
144
+ { name: 'task-1', prompt: 'Build login page', model: 'sonnet' },
145
+ { name: 'task-2', prompt: 'Build signup page', model: 'sonnet' },
146
+ ]);
147
+
148
+ // Send follow-ups
149
+ const r1 = await mgr.send('task-1', 'Add form validation');
150
+ const r2 = await mgr.send('task-2', 'Add password strength meter');
151
+
152
+ console.log(r1.text); // The response
153
+ console.log(r1.cost); // Cost in USD
154
+
155
+ mgr.stopAll();
156
+ ```
157
+
158
+ ## Forking Sessions
159
+
160
+ Fork creates a new session that starts with all the parent's conversation context:
161
+
162
+ ```bash
163
+ # Original session
164
+ cms spawn --name approach-a --prompt "Implement auth with sessions"
165
+ cms send --name approach-a --message "Add login endpoint"
166
+
167
+ # Fork to try a different approach (keeps all context from approach-a)
168
+ cms fork --name approach-a --new-name approach-b --message "Actually, use JWT instead"
169
+
170
+ # Now both sessions exist independently
171
+ cms send --name approach-a --message "Add session storage"
172
+ cms send --name approach-b --message "Add token refresh"
173
+ ```
174
+
175
+ ## Delegate (Control Loop + Safety Net)
176
+
177
+ The `delegate` system gives the parent Claude (or any automation) human-like control over child sessions:
178
+
179
+ 1. **Spawns** a session with the right permissions
180
+ 2. **Sends** the task
181
+ 3. **Monitors** for issues (permission denials, cost overruns, turn limits)
182
+ 4. **Auto-handles** permission retries
183
+ 5. **Returns** structured output for the parent to evaluate
184
+ 6. **Accepts** follow-up corrections via `continue`
185
+
186
+ ### CLI Usage
187
+
188
+ ```bash
189
+ # Delegate a task with a $1 budget limit
190
+ cms delegate --name fix-bug --task "Fix the auth bug in auth.service.ts" --max-cost 1.00
191
+
192
+ # Delegate with read-only mode (no file edits allowed)
193
+ cms delegate --name review --task "Review code quality of src/" --preset read-only
194
+
195
+ # Get structured JSON output (for programmatic use)
196
+ cms delegate --name task-1 --task "Count all TypeScript files" --model haiku --json
197
+
198
+ # Send follow-up corrections
199
+ cms continue --name fix-bug --message "Also add input validation"
200
+
201
+ # Full control with context and custom limits
202
+ cms delegate --name big-refactor --task "Refactor the auth module" \
203
+ --model opus --preset full --max-cost 5.00 --max-turns 100 \
204
+ --context "Use JWT tokens, not sessions"
205
+
206
+ # Disable safety net entirely (no cost/turn/path limits)
207
+ cms delegate --name trusted-task --task "Build the feature" --no-safety
208
+ ```
209
+
210
+ ### Permission Presets
211
+
212
+ | Preset | Permission Mode | Description |
213
+ |--------|----------------|-------------|
214
+ | `read-only` | default | Can search and read files only |
215
+ | `review` | default | Same as read-only (code review) |
216
+ | `edit` | acceptEdits | Can read and edit files (default) |
217
+ | `full` | bypassPermissions | Full access (use with caution) |
218
+ | `plan` | plan | Explore only, no execution |
219
+
220
+ ### Safety Net
221
+
222
+ Every delegated session has automatic safety limits:
223
+
224
+ - **Cost limit** — Auto-kills if cumulative cost exceeds threshold (default: $2.00)
225
+ - **Turn limit** — Auto-kills if agent turns exceed threshold (default: 50)
226
+ - **Time limit** — Timeout per interaction (default: 5 minutes)
227
+ - **Protected paths** — Warns on modifications to `.env`, `.git/`, `node_modules/`, etc.
228
+
229
+ ### Structured Output (--json)
230
+
231
+ When using `--json`, delegate returns machine-readable output:
232
+
233
+ ```json
234
+ {
235
+ "status": "completed",
236
+ "response": "Fixed the auth bug by...",
237
+ "cost": 0.0342,
238
+ "turns": 5,
239
+ "duration": 12340,
240
+ "sessionId": "abc123",
241
+ "name": "fix-bug",
242
+ "canContinue": true,
243
+ "toolsUsed": ["Read", "Edit", "Grep"],
244
+ "safety": {
245
+ "totalViolations": 0,
246
+ "violations": [],
247
+ "limits": { "maxCostUsd": 1.00, "maxTurns": 50 }
248
+ },
249
+ "error": null
250
+ }
251
+ ```
252
+
253
+ **Status values:** `completed`, `needs_input`, `failed`, `cost_exceeded`, `turns_exceeded`
254
+
255
+ ### Programmatic Delegate API
256
+
257
+ ```javascript
258
+ const { SessionManager, Delegate } = require('claude-multi-session');
259
+
260
+ const mgr = new SessionManager();
261
+ const delegate = new Delegate(mgr);
262
+
263
+ // One-shot delegation
264
+ const result = await delegate.run('fix-bug', {
265
+ task: 'Fix the authentication bug in auth.service.ts',
266
+ model: 'sonnet',
267
+ preset: 'edit',
268
+ maxCost: 1.00,
269
+ maxTurns: 30,
270
+ });
271
+
272
+ console.log(result.status); // 'completed'
273
+ console.log(result.response); // What the session did
274
+ console.log(result.cost); // $0.0342
275
+
276
+ // Disable safety net entirely
277
+ const noSafety = await delegate.run('trusted', {
278
+ task: 'Build the whole feature',
279
+ safety: false, // No cost/turn/path limits
280
+ });
281
+
282
+ // Multi-step with evaluation
283
+ const r1 = await delegate.run('feature', { task: 'Build login page' });
284
+ // Parent evaluates r1.response...
285
+ const r2 = await delegate.continue('feature', 'Good, now add form validation');
286
+ // Parent evaluates r2.response...
287
+ const r3 = await delegate.continue('feature', 'Perfect. Now write tests.');
288
+ delegate.finish('feature');
289
+ ```
290
+
291
+ ### SafetyNet Standalone
292
+
293
+ ```javascript
294
+ const { SafetyNet, StreamSession } = require('claude-multi-session');
295
+
296
+ const safety = new SafetyNet({
297
+ maxCostUsd: 0.50,
298
+ maxTurns: 20,
299
+ protectedPaths: ['.env', 'credentials/', '.git/'],
300
+ });
301
+
302
+ const session = new StreamSession({ name: 'task', model: 'haiku' });
303
+ session.start();
304
+ safety.attach(session);
305
+
306
+ // Safety net monitors all interactions
307
+ safety.on('violation', (v) => console.log('VIOLATION:', v.message));
308
+ safety.on('kill', (v) => console.log('SESSION KILLED:', v.message));
309
+
310
+ await session.send('Do something');
311
+ ```
312
+
313
+ ## Options
314
+
315
+ ### spawn
316
+ ```
317
+ --name <name> Session name (required)
318
+ --prompt <text> Initial prompt (required)
319
+ --model <model> Model: sonnet, opus, haiku (default: sonnet)
320
+ --stop Stop after first response (one-shot mode)
321
+ --work-dir <path> Working directory for claude
322
+ --permission-mode <mode> Permission mode: default, acceptEdits, bypassPermissions
323
+ --allowed-tools <t1,t2> Restrict available tools
324
+ --system-prompt <text> Append to system prompt
325
+ --max-budget <usd> Max budget in USD
326
+ --agent <name> Use a specific agent
327
+ ```
328
+
329
+ ### send
330
+ ```
331
+ --name <name> Session name (required)
332
+ --message <text> Message to send (required)
333
+ --stop Stop session after response
334
+ ```
335
+
336
+ ### delegate
337
+ ```
338
+ --name <name> Session name (required)
339
+ --task <text> Task description (required)
340
+ --model <model> Model: sonnet, opus, haiku (default: sonnet)
341
+ --preset <preset> Permission preset (default: edit)
342
+ --max-cost <usd> Max cost in USD (default: 2.00)
343
+ --max-turns <n> Max agent turns (default: 50)
344
+ --no-safety Disable safety net entirely (no cost/turn/path limits)
345
+ --context <text> Extra context to prepend to the task
346
+ --work-dir <path> Working directory
347
+ --system-prompt <text> Append to system prompt
348
+ --agent <name> Use a specific agent
349
+ --json Output structured JSON
350
+ ```
351
+
352
+ ### continue
353
+ ```
354
+ --name <name> Session name (required)
355
+ --message <text> Follow-up message (required)
356
+ --json Output structured JSON
357
+ ```
358
+
359
+ ## Programmatic API
360
+
361
+ ```javascript
362
+ const { SessionManager, StreamSession } = require('claude-multi-session');
363
+
364
+ // High-level API (recommended)
365
+ const mgr = new SessionManager({
366
+ defaultModel: 'sonnet',
367
+ defaultPermissionMode: 'default',
368
+ });
369
+
370
+ const { session, response } = await mgr.spawn('my-task', {
371
+ prompt: 'Fix the auth bug',
372
+ model: 'sonnet',
373
+ workDir: '/path/to/project',
374
+ });
375
+
376
+ const r2 = await mgr.send('my-task', 'Add tests');
377
+ mgr.stop('my-task');
378
+
379
+ // Low-level API (single session)
380
+ const session = new StreamSession({
381
+ name: 'direct',
382
+ model: 'haiku',
383
+ });
384
+ session.start();
385
+ const r1 = await session.send('Hello');
386
+ const r2 = await session.send('Follow up');
387
+ session.stop();
388
+ ```
389
+
390
+ ### Events
391
+
392
+ ```javascript
393
+ session.on('text', (text) => { /* partial text chunks */ });
394
+ session.on('tool-use', ({ name, input }) => { /* tool calls */ });
395
+ session.on('result', (response) => { /* complete response */ });
396
+ session.on('init', (data) => { /* session initialized */ });
397
+ session.on('error', (err) => { /* error occurred */ });
398
+ session.on('close', (code) => { /* process exited */ });
399
+ ```
400
+
401
+ ## Cost Tracking
402
+
403
+ Every interaction tracks cost:
404
+
405
+ ```bash
406
+ cms status --name my-task
407
+ # Shows: total cost, turns, interactions
408
+
409
+ cms history --name my-task
410
+ # Shows: cost per interaction
411
+ ```
412
+
413
+ ## Data Storage
414
+
415
+ Session data is stored in `~/.claude-multi-session/`:
416
+ - `sessions.json` — Session metadata, history, and config
417
+
418
+ Clean up old sessions:
419
+ ```bash
420
+ cms cleanup --days 7
421
+ ```
422
+
423
+ ## MCP Server (Claude Code Native Integration)
424
+
425
+ The MCP server exposes all multi-session tools as **native Claude Code tools**. Instead of running CLI commands via Bash, Claude calls tools directly — just like Read, Edit, or Grep.
426
+
427
+ ### Setup
428
+
429
+ **Automatic (recommended):**
430
+ ```bash
431
+ cms setup
432
+ ```
433
+ This interactive wizard registers the MCP server for you. See [Quick Setup](#quick-setup-mcp-integration) above.
434
+
435
+ **Manual — Option 1: Global install**
436
+ ```bash
437
+ npm install -g claude-multi-session
438
+ ```
439
+
440
+ Add to your Claude Code MCP config (`~/.claude/settings.json` or project `.claude/settings.json`):
441
+ ```json
442
+ {
443
+ "mcpServers": {
444
+ "multi-session": {
445
+ "command": "cms-mcp"
446
+ }
447
+ }
448
+ }
449
+ ```
450
+
451
+ **Manual — Option 2: Local (no install)**
452
+ ```json
453
+ {
454
+ "mcpServers": {
455
+ "multi-session": {
456
+ "command": "node",
457
+ "args": ["/absolute/path/to/claude-multi-session/bin/mcp.js"]
458
+ }
459
+ }
460
+ }
461
+ ```
462
+
463
+ ### Available MCP Tools
464
+
465
+ Once configured, Claude sees these tools:
466
+
467
+ **Session Management:**
468
+ | Tool | Description |
469
+ |------|-------------|
470
+ | `spawn_session` | Start a new session |
471
+ | `send_message` | Send message (auto-resumes if stopped) |
472
+ | `resume_session` | Resume a stopped session |
473
+ | `pause_session` | Pause a session |
474
+ | `fork_session` | Fork into a new session |
475
+ | `stop_session` | Gracefully stop |
476
+ | `kill_session` | Force kill |
477
+
478
+ **Information:**
479
+ | Tool | Description |
480
+ |------|-------------|
481
+ | `get_session_status` | Detailed session info |
482
+ | `get_last_output` | Last response text |
483
+ | `list_sessions` | List all sessions |
484
+ | `get_history` | Full interaction history |
485
+ | `delete_session` | Permanently delete |
486
+
487
+ **Delegate (Control Loop + Safety):**
488
+ | Tool | Description |
489
+ |------|-------------|
490
+ | `delegate_task` | Smart delegation with safety limits |
491
+ | `continue_task` | Send corrections to a delegated task |
492
+ | `finish_task` | Finish a task cleanly |
493
+ | `abort_task` | Emergency abort |
494
+
495
+ **Batch:**
496
+ | Tool | Description |
497
+ |------|-------------|
498
+ | `batch_spawn` | Spawn multiple sessions in parallel |
499
+
500
+ ### How Claude Uses It
501
+
502
+ With MCP configured, Claude can autonomously:
503
+
504
+ ```
505
+ User: "Build auth with login, signup, and password reset"
506
+
507
+ Claude thinks: "This has 3 independent parts. I'll delegate in parallel."
508
+
509
+ Claude calls:
510
+ → delegate_task(name="auth-login", task="Build login with JWT", model="sonnet")
511
+ → delegate_task(name="auth-signup", task="Build signup with validation", model="sonnet")
512
+ → delegate_task(name="auth-reset", task="Build password reset with email", model="sonnet")
513
+
514
+ Claude reads results, notices signup is missing email validation...
515
+
516
+ Claude calls:
517
+ → continue_task(name="auth-signup", message="Add email format validation")
518
+
519
+ All good now. Claude calls:
520
+ → finish_task(name="auth-login")
521
+ → finish_task(name="auth-signup")
522
+ → finish_task(name="auth-reset")
523
+
524
+ Claude: "Done! All 3 auth features implemented."
525
+ ```
526
+
527
+ ### Strategy Guide
528
+
529
+ See `STRATEGY.md` for the complete guide on:
530
+ - When to delegate vs do it yourself
531
+ - How to decompose tasks
532
+ - Model selection (haiku/sonnet/opus)
533
+ - Budget allocation
534
+ - The correction loop pattern
535
+ - Parallel coordination
536
+
537
+ ## Requirements
538
+
539
+ - **Node.js** >= 18
540
+ - **Claude Code CLI** installed and authenticated
541
+ - Zero npm dependencies
542
+
543
+ ## License
544
+
545
+ MIT