reflexive 0.1.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/CLAUDE.md ADDED
@@ -0,0 +1,77 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ Reflexive is an AI-powered introspection framework for Node.js applications using the Claude Agent SDK. It enables building applications by talking to them — an AI agent that lives inside your running application and can see logs, read source files, and modify code through chat conversation.
8
+
9
+ ## Commands
10
+
11
+ ```bash
12
+ npm run demo # Run self-instrumenting demo (library mode)
13
+ npm run demo:app # Run CLI mode monitoring demo-app.js
14
+ ```
15
+
16
+ There is no build step, test suite, or linter configured. The project runs directly as ES modules with Node.js >= 18.
17
+
18
+ ## Architecture
19
+
20
+ ### Two Operating Modes
21
+
22
+ **Library Mode** — Embed the agent inside your app:
23
+ ```javascript
24
+ import { makeReflexive } from 'reflexive';
25
+ const r = makeReflexive({ port: 3099, title: 'My App' });
26
+ r.setState('key', value); // Expose state to agent
27
+ ```
28
+
29
+ **CLI Mode** — Monitor any Node.js app from outside:
30
+ ```bash
31
+ reflexive [options] <script.js> [-- app-args]
32
+ ```
33
+
34
+ ### Single-File Implementation
35
+
36
+ All functionality lives in `src/reflexive.js` (~1,500 lines). This monolithic design is intentional — no build step, direct execution. Key components within:
37
+
38
+ - **AppState class** — Circular log buffer (500 entries), custom key-value state, event emitter
39
+ - **ProcessManager class** — Child process spawning, stdout/stderr capture, restart logic, file watching
40
+ - **MCP Server** — Tool definitions using Zod schemas for agent capabilities
41
+ - **Dashboard HTML generator** — Self-contained SPA with chat interface and log viewer
42
+ - **Chat streaming** — SSE-based real-time responses via Claude Agent SDK
43
+
44
+ ### Dashboard Server
45
+
46
+ Runs on port 3099 by default. Routes:
47
+ - `/reflexive` — Web dashboard UI
48
+ - `/reflexive/chat` — POST, SSE stream for chat
49
+ - `/reflexive/status` — GET, JSON status
50
+ - `/reflexive/logs` — GET, JSON logs with filtering
51
+
52
+ ### MCP Tools Pattern
53
+
54
+ Agent capabilities are exposed as MCP tools with Zod-validated parameters:
55
+ - Library mode: `get_app_status`, `get_logs`, `search_logs`, `get_custom_state`
56
+ - CLI mode: `get_process_state`, `get_output_logs`, `restart_process`, `stop_process`, `start_process`, `send_input`, `search_logs`
57
+
58
+ Additional tools can be registered via the `tools` option when calling `makeReflexive()`.
59
+
60
+ ### CLI Capability Flags
61
+
62
+ Dangerous operations are gated behind flags:
63
+ - `--write` — Allow file modifications
64
+ - `--shell` — Allow shell command execution
65
+ - `--watch` — Hot-reload on file changes
66
+
67
+ ## Dependencies
68
+
69
+ Only two runtime dependencies:
70
+ - `@anthropic-ai/claude-agent-sdk` — Claude AI integration
71
+ - `zod` — Parameter validation for MCP tools
72
+
73
+ ## Authentication
74
+
75
+ Requires Claude API access via either:
76
+ 1. Claude Code CLI authentication (recommended)
77
+ 2. `ANTHROPIC_API_KEY` environment variable
package/FAILURES.md ADDED
@@ -0,0 +1,245 @@
1
+ # Troubleshooting Reflexive
2
+
3
+ ## Quick Diagnosis
4
+
5
+ If something breaks, run this and paste the output when reporting:
6
+
7
+ ```bash
8
+ node --version
9
+ npm --version
10
+ npx reflexive --help
11
+ echo $ANTHROPIC_API_KEY | head -c 10
12
+ ```
13
+
14
+ ## Common Failures
15
+
16
+ ### "Authentication failed" or "Invalid API key"
17
+
18
+ **Symptom:** Agent won't respond, error about API key
19
+
20
+ **Fix:**
21
+ ```bash
22
+ # Option 1: Use Claude Code CLI auth (recommended)
23
+ npm install -g @anthropic-ai/claude-code
24
+ claude # Follow login prompts
25
+
26
+ # Option 2: Set API key directly
27
+ export ANTHROPIC_API_KEY=sk-ant-...
28
+ ```
29
+
30
+ **Check:** The Claude Code CLI stores credentials that Reflexive can use automatically. If you've logged in with `claude` before, it should just work.
31
+
32
+ ---
33
+
34
+ ### "Cannot find module 'reflexive'"
35
+
36
+ **Symptom:** Import fails or npx doesn't work
37
+
38
+ **Fix:**
39
+ ```bash
40
+ # If using npx, try clearing cache
41
+ npx clear-npx-cache
42
+ npx reflexive ./app.js
43
+
44
+ # If using as dependency
45
+ npm install reflexive
46
+ ```
47
+
48
+ ---
49
+
50
+ ### Dashboard loads but chat doesn't work
51
+
52
+ **Symptom:** You see the UI at localhost:3099 but messages don't get responses
53
+
54
+ **Causes:**
55
+ 1. No authentication (see above)
56
+ 2. Claude API is down
57
+ 3. Network/proxy blocking requests
58
+
59
+ **Debug:**
60
+ ```bash
61
+ # Check if you can reach Claude API
62
+ curl https://api.anthropic.com/v1/messages \
63
+ -H "x-api-key: $ANTHROPIC_API_KEY" \
64
+ -H "anthropic-version: 2023-06-01" \
65
+ -H "content-type: application/json" \
66
+ -d '{"model":"claude-sonnet-4-20250514","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}'
67
+ ```
68
+
69
+ ---
70
+
71
+ ### Process starts but agent can't see output
72
+
73
+ **Symptom:** Your app runs, but agent says "no logs" or can't see stdout
74
+
75
+ **Causes:**
76
+ 1. App uses a logging library that doesn't write to stdout
77
+ 2. Output is buffered
78
+
79
+ **Fix:**
80
+ ```bash
81
+ # Force unbuffered output
82
+ NODE_OPTIONS="--no-warnings" npx reflexive ./app.js
83
+
84
+ # Or in your app
85
+ process.stdout.write('message\n'); # Instead of console.log
86
+ ```
87
+
88
+ ---
89
+
90
+ ### "--debug doesn't work" / Breakpoints don't hit
91
+
92
+ **Symptom:** You set breakpoints but they never trigger
93
+
94
+ **Causes:**
95
+ 1. Code path not executed
96
+ 2. Source maps issue
97
+ 3. Node version < 18
98
+
99
+ **Check:**
100
+ ```bash
101
+ # Verify Node version
102
+ node --version # Should be >= 18
103
+
104
+ # Try with explicit debug port
105
+ npx reflexive --debug --node-args="--inspect=9229" ./app.js
106
+ ```
107
+
108
+ ---
109
+
110
+ ### "--inject causes app to crash"
111
+
112
+ **Symptom:** App crashes or behaves differently with --inject
113
+
114
+ **Causes:**
115
+ 1. Conflict with existing instrumentation (APM tools, etc)
116
+ 2. App uses non-standard module loading
117
+
118
+ **Fix:**
119
+ ```bash
120
+ # Try without injection first
121
+ npx reflexive ./app.js
122
+
123
+ # If that works, injection has a conflict
124
+ # Report the error message
125
+ ```
126
+
127
+ ---
128
+
129
+ ### "--eval returns undefined for everything"
130
+
131
+ **Symptom:** `evaluate_in_app` always returns undefined
132
+
133
+ **Causes:**
134
+ 1. Variable is out of scope
135
+ 2. Async timing issue
136
+ 3. Code threw but error was swallowed
137
+
138
+ **Debug:**
139
+ ```javascript
140
+ // Try wrapping in try/catch
141
+ evaluate_in_app({ code: "try { yourVar } catch(e) { e.message }" })
142
+ ```
143
+
144
+ ---
145
+
146
+ ### "Port 3099 already in use"
147
+
148
+ **Symptom:** Dashboard won't start
149
+
150
+ **Fix:**
151
+ ```bash
152
+ # Use different port
153
+ npx reflexive --port 4000 ./app.js
154
+
155
+ # Or kill the existing process
156
+ lsof -i :3099
157
+ kill -9 <PID>
158
+ ```
159
+
160
+ ---
161
+
162
+ ### File writes fail even with --write
163
+
164
+ **Symptom:** Agent says it can't write files
165
+
166
+ **Causes:**
167
+ 1. File permissions
168
+ 2. Path is outside working directory
169
+ 3. File is locked
170
+
171
+ **Check:**
172
+ ```bash
173
+ # Verify working directory
174
+ pwd
175
+ ls -la ./your-file.js
176
+ ```
177
+
178
+ ---
179
+
180
+ ### Shell commands fail even with --shell
181
+
182
+ **Symptom:** Agent can't run shell commands
183
+
184
+ **Causes:**
185
+ 1. Command not in PATH
186
+ 2. Permissions issue
187
+ 3. Shell not available
188
+
189
+ **Debug:**
190
+ ```bash
191
+ # Check what shell is available
192
+ echo $SHELL
193
+ which bash
194
+ ```
195
+
196
+ ---
197
+
198
+ ## Known Issues
199
+
200
+ ### Interactive mode (-i) with certain CLI tools
201
+
202
+ Some CLI tools that do complex terminal manipulation (curses, raw mode) may not work well with interactive mode. Stick to simple stdin/stdout tools.
203
+
204
+ ### Watch mode (-w) high CPU on large directories
205
+
206
+ If watching a directory with many files (node_modules), CPU may spike. Use .gitignore patterns or run from a subdirectory.
207
+
208
+ ### V8 debugger with worker threads
209
+
210
+ Breakpoints in worker threads may not work correctly. Main thread debugging works fine.
211
+
212
+ ---
213
+
214
+ ## Reporting Bugs
215
+
216
+ Include this information:
217
+
218
+ 1. **Command you ran:**
219
+ ```bash
220
+ npx reflexive --write --debug ./my-app.js
221
+ ```
222
+
223
+ 2. **Node and npm versions:**
224
+ ```bash
225
+ node --version && npm --version
226
+ ```
227
+
228
+ 3. **OS:**
229
+ ```bash
230
+ uname -a # or Windows version
231
+ ```
232
+
233
+ 4. **Error message:** Full stack trace if available
234
+
235
+ 5. **Minimal reproduction:** Smallest app.js that shows the problem
236
+
237
+ Open an issue at: https://github.com/anthropics/reflexive/issues
238
+
239
+ ---
240
+
241
+ ## Getting Help
242
+
243
+ - Check the [README](./README.md) for usage examples
244
+ - Search existing issues before opening a new one
245
+ - For Claude API issues, check https://status.anthropic.com
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # Reflexive
2
+
3
+ [VIDEO: demo.gif]
4
+
5
+ Embed Claude inside your running Node.js app. It sees logs, reads source, edits files, sets breakpoints, and responds to runtime events.
6
+
7
+ ## Quickstart
8
+
9
+ ```bash
10
+ echo "console.log('hello')" > app.js
11
+ npx reflexive --write app.js
12
+ # Open http://localhost:3099
13
+ # Say: "Turn this into an Express server with a /users endpoint"
14
+ ```
15
+
16
+ ## What This Is
17
+
18
+ Claude Agent SDK (Claude Code as a library) + your running Node.js process = an agent that:
19
+
20
+ - **Agent loop** - keeps working until done, tool calls, retries, reasoning
21
+ - **Process lifecycle** - start, stop, restart, watch for file changes
22
+ - **V8 debugger** - real breakpoints, stepping, scope inspection via Inspector protocol
23
+ - **Watch triggers** - pattern-match logs and auto-prompt the agent
24
+ - **File read/write + shell** - behind explicit flags
25
+
26
+ ```
27
+ +---------------------------------------------------------+
28
+ | reflexive CLI |
29
+ | - Dashboard server (chat UI + logs) |
30
+ | - Claude Agent SDK with MCP tools |
31
+ | - Process control, file ops, shell |
32
+ | |
33
+ | +---------------------------------------------------+ |
34
+ | | your-app.js (child process) | |
35
+ | | - stdout/stderr captured | |
36
+ | | - Optional: deep instrumentation via --inject | |
37
+ | +---------------------------------------------------+ |
38
+ +---------------------------------------------------------+
39
+ ```
40
+
41
+ ## Safety Model
42
+
43
+ **Default is read-only.** No flags = agent can see logs, read files, ask questions. Cannot modify anything.
44
+
45
+ Capabilities require explicit opt-in:
46
+
47
+ | Flag | Enables |
48
+ |------|---------|
49
+ | `--write` | File modification |
50
+ | `--shell` | Shell command execution |
51
+ | `--inject` | Deep instrumentation (console intercept, diagnostics, perf metrics) |
52
+ | `--eval` | Runtime code evaluation (implies --inject) |
53
+ | `--debug` | V8 Inspector debugging (breakpoints, stepping, scope inspection) |
54
+
55
+ This is a development tool. For production, use read-only mode.
56
+
57
+ ## Authentication
58
+
59
+ Choose one:
60
+
61
+ ```bash
62
+ # Option 1: Claude Code CLI (recommended)
63
+ npm install -g @anthropic-ai/claude-code
64
+ claude # Login once
65
+
66
+ # Option 2: API key
67
+ export ANTHROPIC_API_KEY=your-key
68
+ ```
69
+
70
+ ---
71
+
72
+ ## CLI Reference
73
+
74
+ ```bash
75
+ reflexive [options] [entry-file] [-- app-args...]
76
+ ```
77
+
78
+ ### Options
79
+
80
+ ```
81
+ -p, --port <port> Dashboard port (default: 3099)
82
+ -h, --host <host> Dashboard host (default: localhost)
83
+ -o, --open Open dashboard in browser
84
+ -w, --watch Restart on file changes
85
+ -i, --interactive Proxy stdin/stdout for CLI apps
86
+ --inject Deep instrumentation
87
+ --eval Runtime eval (DANGEROUS)
88
+ -d, --debug V8 Inspector debugging
89
+ --write Enable file writing
90
+ --shell Enable shell access
91
+ --dangerously-skip-permissions Enable everything
92
+ --node-args <args> Pass args to Node.js
93
+ ```
94
+
95
+ ### Examples
96
+
97
+ ```bash
98
+ # Basic - read-only monitoring
99
+ npx reflexive ./server.js
100
+
101
+ # Development - full control
102
+ npx reflexive --write --shell --watch ./server.js
103
+
104
+ # Debugging - set breakpoints, step through code
105
+ npx reflexive --debug ./server.js
106
+
107
+ # Deep instrumentation - GC stats, event loop, HTTP tracking
108
+ npx reflexive --inject ./server.js
109
+
110
+ # Pass args to your app
111
+ npx reflexive ./server.js -- --port 8080
112
+ ```
113
+
114
+ ## Library Mode
115
+
116
+ Embed the agent inside your app for deeper introspection:
117
+
118
+ ```javascript
119
+ import { makeReflexive } from 'reflexive';
120
+
121
+ const r = makeReflexive({
122
+ port: 3099,
123
+ title: 'My App',
124
+ tools: [] // Add custom MCP tools
125
+ });
126
+
127
+ // Console output captured automatically
128
+ console.log('Server started');
129
+
130
+ // Expose custom state the agent can query
131
+ r.setState('activeUsers', 42);
132
+ r.setState('cache.hitRate', 0.95);
133
+
134
+ // Programmatic chat
135
+ const answer = await r.chat("What's the memory usage?");
136
+ ```
137
+
138
+ ### Custom Tools
139
+
140
+ ```javascript
141
+ import { tool } from '@anthropic-ai/claude-agent-sdk';
142
+ import { z } from 'zod';
143
+
144
+ const r = makeReflexive({
145
+ tools: [
146
+ tool(
147
+ 'get_order',
148
+ 'Look up order by ID',
149
+ { orderId: z.string() },
150
+ async ({ orderId }) => ({
151
+ content: [{ type: 'text', text: JSON.stringify(orders.get(orderId)) }]
152
+ })
153
+ )
154
+ ]
155
+ });
156
+ ```
157
+
158
+ ## V8 Debugger
159
+
160
+ With `--debug`, the agent can set real breakpoints:
161
+
162
+ ```
163
+ You: "Set a breakpoint on line 42 of server.js"
164
+ Agent: [set_v8_breakpoint: file="server.js", line=42]
165
+ Breakpoint set.
166
+
167
+ ... request comes in ...
168
+
169
+ Agent: Breakpoint hit at server.js:42
170
+
171
+ Call Stack:
172
+ - handleRequest (server.js:42)
173
+ - processMiddleware (middleware.js:18)
174
+
175
+ Local Variables:
176
+ - req: { method: "POST", url: "/api/users" }
177
+ - user: { id: 123, name: "Alice" }
178
+
179
+ You: "What's in user.permissions?"
180
+ Agent: [evaluate_at_breakpoint: "user.permissions"]
181
+ ["read", "write", "admin"]
182
+
183
+ You: "Step into the next function"
184
+ Agent: [debugger_step_into]
185
+ Stepped to validateUser (auth.js:55)
186
+ ```
187
+
188
+ ## Watch Triggers
189
+
190
+ Click the eye icon on any log entry to create a watch. When that pattern appears again, the agent is automatically prompted.
191
+
192
+ Use cases:
193
+ - "When you see 'Error:', investigate and suggest a fix"
194
+ - "When 'user signed up' appears, summarize the signup"
195
+ - "When memory exceeds 500MB, analyze what's using it"
196
+
197
+ ## Injection Mode
198
+
199
+ With `--inject`, your app gets automatic instrumentation without code changes:
200
+
201
+ | What's Captured | Source |
202
+ |-----------------|--------|
203
+ | Console methods | log, info, warn, error, debug |
204
+ | HTTP requests | Incoming and outgoing via diagnostics_channel |
205
+ | GC events | Duration and type |
206
+ | Event loop | Latency histogram (p50, p99) |
207
+ | Uncaught errors | With stack traces |
208
+
209
+ Your app can optionally use the injected API:
210
+
211
+ ```javascript
212
+ if (process.reflexive) {
213
+ process.reflexive.setState('db.connections', pool.size);
214
+ process.reflexive.emit('userSignup', { userId: 123 });
215
+ }
216
+ ```
217
+
218
+ ## Runtime Eval
219
+
220
+ With `--eval`, the agent can execute code in your running app:
221
+
222
+ ```
223
+ You: "What's in the config object?"
224
+ Agent: [evaluate_in_app: code="config"]
225
+ { port: 3000, debug: true }
226
+
227
+ You: "Clear the cache"
228
+ Agent: [evaluate_in_app: code="cache.clear()"]
229
+ undefined
230
+ ```
231
+
232
+ **Warning:** `--eval` allows arbitrary code execution. Development only.
233
+
234
+ ## Dashboard
235
+
236
+ The web UI at `http://localhost:3099` provides:
237
+
238
+ - Real-time chat with the agent
239
+ - Live logs with ANSI color support
240
+ - Process controls (stop/restart)
241
+ - Watch pattern management
242
+ - Breakpoint controls (with --debug)
243
+
244
+ ## Demos
245
+
246
+ ```bash
247
+ npm run demo # Library mode - task queue
248
+ npm run demo:app # CLI mode - HTTP server
249
+ npm run demo:inject # Deep instrumentation
250
+ npm run demo:eval # Runtime eval
251
+ npm run demo:ai # AI-powered endpoints
252
+ ```
253
+
254
+ ---
255
+
256
+ ## Links
257
+
258
+ - Built on [Claude Agent SDK](https://docs.anthropic.com/en/docs/claude-code/agent-sdk) (Claude Code as a library)
259
+ - ~1500 lines, single file, no build step
260
+ - [Troubleshooting](./FAILURES.md)
261
+
262
+ ## License
263
+
264
+ MIT