anyclaude-sdk 0.3.0 → 0.4.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/README.md CHANGED
@@ -1,9 +1,13 @@
1
1
  # anyclaude-sdk
2
2
 
3
- Claude Code agent capabilities — tools, the tool loop, multi-turn conversations
4
- running **entirely in the browser** via [WebContainer](https://webcontainers.io),
5
- against **any OpenAI- or Anthropic-compatible LLM endpoint**. No backend, no OAuth,
6
- no native binaries.
3
+ Claude Code agent capabilities — tools, the tool loop, multi-turn conversations,
4
+ MCP, sub-agents, sessions against **any OpenAI- or Anthropic-compatible LLM
5
+ endpoint**, running in the **browser** ([WebContainer](https://webcontainers.io)),
6
+ **Node**, and **Bun**. No backend required, no OAuth, no native binaries.
7
+
8
+ > **Live demo:** [a full IDE running in your browser](https://anyclaude-docs.puter.site/demo/) ·
9
+ > **Docs:** [anyclaude-docs.puter.site](https://anyclaude-docs.puter.site) ·
10
+ > **React UI kit:** [`anyclaude-react`](anyclaude-react/)
7
11
 
8
12
  It exposes the same `query()` async-generator interface and the same `SDKMessage`
9
13
  envelope as `@anthropic-ai/claude-agent-sdk`, so code written against the official
@@ -267,18 +271,75 @@ await fs.writeFile('/app/index.ts', 'export const x = 1')
267
271
  const workspace = composeWorkspace(fs, new NoopCommandExecutor())
268
272
  ```
269
273
 
274
+ ## Serverless & the "survivor"
275
+
276
+ Run `query()` in a serverless function and stream `SDKMessage`s to the browser. For runs longer than the platform's time cap, checkpoint at a turn boundary and continue transparently in a fresh invocation:
277
+
278
+ ```ts
279
+ // pause near the deadline, persist to the store, emit a `paused` message
280
+ query({ prompt, workspace, llm, sessionStore, maxDurationMs: 20_000 })
281
+ // later — resume + continue the tool loop with NO new user message
282
+ query({ workspace, llm, sessionStore, resume: true, continueRun: true })
283
+ ```
284
+
285
+ Pluggable `SessionStore` adapters (all implement `SessionStoreLike`): `SessionStore` (IndexedDB), `MemorySessionStore`, `KVSessionStore` (Vercel KV / Upstash), `RedisSessionStore`, `PostgresSessionStore` (Neon / pg / postgres.js), `SupabaseSessionStore`.
286
+
287
+ ## Client-side tools — server brain, browser hands
288
+
289
+ Declare tools the **host** executes — e.g. run `bash` in the user's browser WebContainer while the agent loop runs on your server. The run pauses with a `client_tool_request`; the client executes it and you resume with the result:
290
+
291
+ ```ts
292
+ query({ prompt, llm, workspace, sessionId, clientTools: ['bash'] }) // → emits client_tool_request + pauses
293
+ query({ llm, workspace, sessionId, resume: true, continueRun: true, clientToolResults }) // → continues
294
+ ```
295
+
296
+ ## Interactive — `ask_user_question`
297
+
298
+ Provide `onAskUser` and the agent gains an `ask_user_question` tool to put a multiple-choice decision to the user:
299
+
300
+ ```ts
301
+ query({ prompt, workspace, llm, onAskUser: async ({ question, options }) => pickOne(question, options) })
302
+ ```
303
+
304
+ ## Hiding your prompt from the browser (projection)
305
+
306
+ The agent loop runs server-side, so your system prompt, tool instructions, and retrieved context live in the server→LLM request and **never reach the browser**. To also strip sensitive artifacts (reasoning, raw tool output / RAG, model identity) from the streamed messages, wrap the stream — a pure, opt-in output transform:
307
+
308
+ ```ts
309
+ import { projectMessages } from 'anyclaude-sdk'
310
+ for await (const m of projectMessages(query({ /* ... */ }), { preset: 'public' }))
311
+ res.write(JSON.stringify(m) + '\n')
312
+ ```
313
+
314
+ `paused` and `client_tool_request` control messages are always preserved. (Note: anything that *runs in the browser* — `createAgentClient` mode — necessarily exposes its request; use the server/endpoint path when the prompt is proprietary.)
315
+
316
+ ## React UI kit — `anyclaude-react`
317
+
318
+ ```bash
319
+ npm install anyclaude-react
320
+ ```
321
+
322
+ `useAgent()` plus restylable components — chat (`AgentChat`, `ChatPanel`, `Transcript`, `MarkdownMessage`, `Composer`, `Working`, `ToolCall`) and an IDE set (`Terminal`, `FileExplorer`, `CodeEditor`, `AskUser`). `createAgentClient` / `createEndpointClient` auto-stitch `paused` continuations and run `clientTools` in the browser.
323
+
324
+ ## Examples & live demo
325
+
326
+ Runnable Vite projects in [`examples/`](examples/): **`browser-ide`** (WebContainer IDE — real shell + Node in the tab), `browser-chat`, `vercel-kv-survivor`, `vercel-supabase-survivor`, `vercel-indexeddb-survivor`, **`vercel-clienttools`** (server brain / browser hands). Try the **[live demo](https://anyclaude-docs.puter.site/demo/)**.
327
+
270
328
  ## API
271
329
 
272
330
  - `query(options): AsyncGenerator<SDKMessage>` — main entry.
273
331
  - `prompt: string | AsyncIterable<SDKUserMessage>`
274
332
  - `workspace: FileSystem & CommandExecutor`
275
333
  - `llm: LLMClient`
276
- - `tools?`, `model?`, `systemPrompt?`, `maxTurns?` (default 50), `cwd?`, `abortController?`
277
- - `createOpenAIClient(options): LLMClient`
278
- - `createAnthropicClient(options): LLMClient`
279
- - `WebContainerWorkspace`, `MemoryFileSystem`, `NoopCommandExecutor`
334
+ - `tools?`, `extraTools?`, `allowedTools?`/`disallowedTools?`, `model?`, `systemPrompt?`/`appendSystemPrompt?`, `maxTurns?` (default 50), `cwd?`, `abortController?`
335
+ - serverless: `sessionStore?`, `resume?`, `maxDurationMs?`, `continueRun?`
336
+ - client tools: `clientTools?`, `clientToolResults?`; interactive: `onAskUser?`
337
+ - also: `mcpServers?`, `agents?`, `commands?`, `hooks?`, `background?`, `team?`, `memory?`, `permissionMode?`/`canUseTool?`, `messageQueue?`
338
+ - `createOpenAIClient` / `createAnthropicClient` / `createResponsesClient`
339
+ - `WebContainerWorkspace`, `MemoryFileSystem`, `NoopCommandExecutor`, `LocalSandbox`, `composeWorkspace`
340
+ - `defineTool` (custom tools), `projectMessages` (server-side stream redaction)
280
341
  - `ALL_CLAUDE_CODE_TOOLS`, individual tools, `toolDefs`, `toolByName`
281
- - All `SDK*` message types, `ContentBlockParam`, `LLMClient`, `ToolDef`, etc.
342
+ - All `SDK*` message types, `ContentBlockParam`, `LLMClient`, `ToolDef`, `SessionStoreLike`, etc.
282
343
 
283
344
  ## Differences from the official SDK
284
345
 
@@ -286,9 +347,11 @@ const workspace = composeWorkspace(fs, new NoopCommandExecutor())
286
347
  |---------|-------------|--------------------|
287
348
  | Auth | OAuth token | None required |
288
349
  | Backend | claude.ai API | Any OpenAI/Anthropic endpoint |
289
- | File ops | Native filesystem | WebContainer fs (pluggable) |
290
- | Commands | Native shell | jsh (WebContainer) |
291
- | MCP / slash commands / background tasks | Built-in | Not included |
350
+ | Runtime | Node only | Browser, Node, Bun |
351
+ | File ops | Native filesystem | Pluggable (WebContainer / Memory / IndexedDB / local) |
352
+ | Commands | Native shell | jsh (WebContainer) / local / client-side tools |
353
+ | MCP / slash commands / background tasks / sub-agents | Built-in | Built-in |
354
+ | Serverless survivor + prompt projection | — | Built-in |
292
355
 
293
356
  ## License
294
357
 
package/dist/index.d.ts CHANGED
@@ -13,6 +13,7 @@ export * from './mcp/index.js';
13
13
  export * from './commands/index.js';
14
14
  export * from './background/index.js';
15
15
  export * from './queue.js';
16
+ export { projectMessages, projectMessage, type ProjectionOptions, type ProjectionPreset, } from './projection.js';
16
17
  export * from './team/index.js';
17
18
  export * from './session/index.js';
18
19
  export * from './memory/index.js';
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ export * from './mcp/index.js';
15
15
  export * from './commands/index.js';
16
16
  export * from './background/index.js';
17
17
  export * from './queue.js';
18
+ export { projectMessages, projectMessage, } from './projection.js';
18
19
  export * from './team/index.js';
19
20
  export * from './session/index.js';
20
21
  export * from './memory/index.js';
@@ -0,0 +1,29 @@
1
+ import type { SDKMessage } from './types/index.js';
2
+ export type ProjectionPreset = 'public' | 'raw';
3
+ export interface ProjectionOptions {
4
+ /** 'public' (browser-safe defaults) or 'raw' (passthrough; only explicit opts apply). Default 'public'. */
5
+ preset?: ProjectionPreset;
6
+ /** Replace tool_result block content with a placeholder — hides raw tool output + RAG context. */
7
+ redactToolResults?: boolean;
8
+ /** Drop synthetic tool_result messages entirely instead of redacting their content. */
9
+ dropToolResults?: boolean;
10
+ /** Remove thinking/reasoning blocks and deltas. */
11
+ stripReasoning?: boolean;
12
+ /** Remove tool_use input args (tool NAMES still appear via usage). */
13
+ stripToolInput?: boolean;
14
+ /** Remove model/provider-identifying fields (model name, tool list, mcp servers, modelUsage). */
15
+ stripModelInfo?: boolean;
16
+ /** Placeholder substituted for redacted content. Default '[redacted]'. */
17
+ placeholder?: string;
18
+ /** Drop any message whose `type` or `subtype` is in this list. */
19
+ drop?: string[];
20
+ /** Custom transform applied last; return null to drop the message. */
21
+ redact?: (m: SDKMessage) => SDKMessage | null;
22
+ }
23
+ /** Project one message. Returns null to drop it. */
24
+ export declare function projectMessage(msg: SDKMessage, options?: ProjectionOptions): SDKMessage | null;
25
+ /**
26
+ * Wrap an SDKMessage stream, projecting each message for browser delivery.
27
+ * Pure output transform — does NOT affect the agent loop. Opt-in.
28
+ */
29
+ export declare function projectMessages(source: AsyncIterable<SDKMessage>, options?: ProjectionOptions): AsyncGenerator<SDKMessage>;
@@ -0,0 +1,99 @@
1
+ function resolve(o) {
2
+ const pub = (o.preset ?? 'public') === 'public';
3
+ return {
4
+ redactToolResults: o.redactToolResults ?? pub,
5
+ dropToolResults: o.dropToolResults ?? false,
6
+ stripReasoning: o.stripReasoning ?? pub,
7
+ stripToolInput: o.stripToolInput ?? false,
8
+ stripModelInfo: o.stripModelInfo ?? pub,
9
+ placeholder: o.placeholder ?? '[redacted]',
10
+ drop: o.drop ?? [],
11
+ redact: o.redact,
12
+ };
13
+ }
14
+ /** Project one message. Returns null to drop it. */
15
+ export function projectMessage(msg, options = {}) {
16
+ const o = resolve(options);
17
+ const m = msg;
18
+ const type = m.type;
19
+ const subtype = m.subtype;
20
+ if (o.drop.includes(type) || (subtype && o.drop.includes(subtype)))
21
+ return null;
22
+ // Control messages the client must act on — never alter (survivor + client tools).
23
+ if (type === 'system' && (subtype === 'paused' || subtype === 'client_tool_request')) {
24
+ return o.redact ? o.redact(msg) : msg;
25
+ }
26
+ let out = msg;
27
+ if (type === 'user') {
28
+ // Synthetic tool_result messages carry raw tool output + retrieved context.
29
+ const message = m.message;
30
+ const content = message?.content;
31
+ if (Array.isArray(content) && content.some((b) => b.type === 'tool_result')) {
32
+ if (o.dropToolResults)
33
+ return o.redact ? o.redact(msg) ?? null : null;
34
+ if (o.redactToolResults) {
35
+ const newContent = content.map((b) => b.type === 'tool_result' ? { ...b, content: o.placeholder } : b);
36
+ out = { ...m, message: { ...message, content: newContent } };
37
+ }
38
+ }
39
+ }
40
+ else if (type === 'assistant') {
41
+ const message = m.message;
42
+ let content = message.content;
43
+ if (o.stripReasoning)
44
+ content = content.filter((b) => b.type !== 'thinking');
45
+ if (o.stripToolInput)
46
+ content = content.map((b) => (b.type === 'tool_use' ? { ...b, input: {} } : b));
47
+ const newMessage = { ...message, content };
48
+ if (o.stripModelInfo)
49
+ newMessage.model = '';
50
+ out = { ...m, message: newMessage };
51
+ }
52
+ else if (type === 'stream_event') {
53
+ const event = m.event;
54
+ const et = event?.type;
55
+ if (o.stripReasoning) {
56
+ if (et === 'content_block_delta' && event.delta?.type === 'thinking_delta')
57
+ return null;
58
+ if (et === 'content_block_start' && event.content_block?.type === 'thinking')
59
+ return null;
60
+ }
61
+ if (o.stripModelInfo && et === 'message_start') {
62
+ const sm = { ...event.message };
63
+ delete sm.model;
64
+ out = { ...m, event: { ...event, message: sm } };
65
+ }
66
+ }
67
+ else if (type === 'system' && subtype === 'init') {
68
+ if (o.stripModelInfo) {
69
+ out = {
70
+ ...m,
71
+ model: '',
72
+ tools: [],
73
+ mcp_servers: [],
74
+ slash_commands: [],
75
+ skills: [],
76
+ agents: [],
77
+ apiKeySource: 'none',
78
+ cwd: '',
79
+ };
80
+ }
81
+ }
82
+ else if (type === 'result') {
83
+ if (o.stripModelInfo) {
84
+ out = { ...m, modelUsage: {} };
85
+ }
86
+ }
87
+ return o.redact ? o.redact(out) : out;
88
+ }
89
+ /**
90
+ * Wrap an SDKMessage stream, projecting each message for browser delivery.
91
+ * Pure output transform — does NOT affect the agent loop. Opt-in.
92
+ */
93
+ export async function* projectMessages(source, options = {}) {
94
+ for await (const m of source) {
95
+ const out = projectMessage(m, options);
96
+ if (out)
97
+ yield out;
98
+ }
99
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anyclaude-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Standalone, browser-compatible SDK providing Claude Code agent capabilities (tools, tool loop, multi-turn, MCP, sub-agents, sessions) against any OpenAI/Anthropic-compatible LLM endpoint. Runs in the browser (WebContainer), Node, and Bun — no backend required.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",