@tanstack/ai-claude-code 0.2.2 → 0.3.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/dist/esm/adapters/policy-map.js +44 -46
- package/dist/esm/adapters/policy-map.js.map +1 -1
- package/dist/esm/adapters/projection.js +146 -81
- package/dist/esm/adapters/projection.js.map +1 -1
- package/dist/esm/adapters/text.js +271 -296
- package/dist/esm/adapters/text.js.map +1 -1
- package/dist/esm/index.js +3 -13
- package/dist/esm/messages/prompt.js +28 -33
- package/dist/esm/messages/prompt.js.map +1 -1
- package/dist/esm/model-meta.js +20 -13
- package/dist/esm/model-meta.js.map +1 -1
- package/dist/esm/stream/translate.js +361 -359
- package/dist/esm/stream/translate.js.map +1 -1
- package/package.json +8 -8
- package/src/adapters/text.ts +92 -18
- package/dist/esm/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n SandboxCapability,\n approvalId,\n buildApprovalRequestedEvent,\n createBridgeEventChannel,\n getSandbox,\n getSandboxPolicy,\n getToolBridgeProvisioner,\n getWorkspaceProjection,\n mergeChunkStreams,\n nodeHttpBridgeProvisioner,\n resolveApproval,\n spawnNdjson,\n} from '@tanstack/ai-sandbox'\nimport { buildPrompt } from '../messages/prompt'\nimport { translateSdkStream } from '../stream/translate'\nimport { mapPolicyToClaudeFlags } from './policy-map'\nimport { projectClaudeWorkspace } from './projection'\nimport type { ClaudePolicyFlags } from './policy-map'\nimport type {\n BridgeEventChannel,\n HostToolBridge,\n PermissionToolResult,\n SandboxHandle,\n SandboxPolicy,\n} from '@tanstack/ai-sandbox'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n DefaultMessageMetadataByModality,\n Modality,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type { ClaudeCodeModel } from '../model-meta'\nimport type { ClaudeCodeTextProviderOptions } from '../provider-options'\nimport type { AgentSdkMessage } from '../stream/sdk-types'\n\nexport type ClaudeCodePermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n\nconst DEFAULT_WORKDIR = '/workspace'\n\nexport interface ClaudeCodeTextConfig {\n /**\n * Working directory inside the sandbox where `claude` runs. Defaults to\n * `/workspace` (the conventional sandbox workspace root).\n */\n cwd?: string\n /**\n * Claude Code permission mode passed via `--permission-mode`. Defaults to\n * `'bypassPermissions'` — a sandbox is isolated, so the agent is allowed to\n * edit files and run commands without prompting. Tighten via `defineSandboxPolicy`\n * / this option for less autonomy.\n */\n permissionMode?: ClaudeCodePermissionMode\n /** Built-in tools the harness may use (`--allowedTools`). */\n allowedTools?: Array<string>\n /** Built-in tools removed from the harness (`--disallowedTools`). */\n disallowedTools?: Array<string>\n /** Extra directories the agent may access (`--add-dir`). */\n addDirs?: Array<string>\n /** Maximum harness-internal turns (`--max-turns`). */\n maxTurns?: number\n /**\n * How `systemPrompts` from `chat()` are applied:\n * - `'append'` (default): `--append-system-prompt` on top of the preset.\n * - `'replace'`: `--system-prompt` as the entire system prompt.\n */\n systemPromptMode?: 'append' | 'replace'\n /** Path/name of the claude executable inside the sandbox. Defaults to `claude`. */\n claudeExecutable?: string\n /** Emit token-level deltas via `--include-partial-messages` (default true). */\n streamPartials?: boolean\n /** Extra environment variables for the claude process inside the sandbox. */\n env?: Record<string, string>\n /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */\n emitDiff?: boolean\n}\n\n/** POSIX single-quote escape for embedding values in the `claude …` command. */\nfunction q(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n/** Format a host tool-bridge as claude's `--mcp-config` JSON. */\nfunction bridgeToMcpConfig(bridge: HostToolBridge): string {\n return JSON.stringify({\n mcpServers: {\n [bridge.name]: {\n type: 'http',\n url: bridge.url,\n headers: { Authorization: `Bearer ${bridge.token}` },\n },\n },\n })\n}\n\nexport class ClaudeCodeTextAdapter<\n TModel extends ClaudeCodeModel,\n> extends BaseTextAdapter<\n TModel,\n ClaudeCodeTextProviderOptions,\n ReadonlyArray<Modality> & readonly ['text'],\n DefaultMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never\n> {\n readonly name = 'claude-code' as const\n\n // Harness adapter: requires a sandbox to run the agent CLI inside.\n override readonly requires = [SandboxCapability] as const\n\n private readonly adapterConfig: ClaudeCodeTextConfig\n\n constructor(config: ClaudeCodeTextConfig, model: TModel) {\n super({}, model)\n this.adapterConfig = config\n }\n\n private sandboxFrom(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): SandboxHandle {\n const ctx = options.capabilities\n if (!ctx) {\n throw new Error(\n 'Adapter \"claude-code\" requires a sandbox. Add withSandbox(defineSandbox({ ... })) ' +\n 'to chat() middleware (e.g. with the local-process or docker provider).',\n )\n }\n return getSandbox(ctx)\n }\n\n private workdir(options: TextOptions<ClaudeCodeTextProviderOptions>): string {\n return (\n options.modelOptions?.cwd ?? this.adapterConfig.cwd ?? DEFAULT_WORKDIR\n )\n }\n\n /** Build the `claude` command line (prompt goes via stdin, not argv). */\n private buildCommand(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n resume: string | undefined,\n policyFlags: ClaudePolicyFlags,\n mcpConfigPath: string | undefined,\n permissionPromptTool: string | undefined,\n ): string {\n const config = this.adapterConfig\n const modelOptions = options.modelOptions\n const exe = config.claudeExecutable ?? 'claude'\n\n const args: Array<string> = [\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--model',\n q(this.model),\n ]\n\n if (config.streamPartials !== false) args.push('--include-partial-messages')\n if (resume !== undefined) args.push('--resume', q(resume))\n\n // Precedence: per-call modelOptions > adapter config > policy > sandbox default.\n const permissionMode =\n modelOptions?.permissionMode ??\n config.permissionMode ??\n policyFlags.permissionMode ??\n 'bypassPermissions'\n args.push('--permission-mode', q(permissionMode))\n\n const maxTurns = modelOptions?.maxTurns ?? config.maxTurns\n if (maxTurns !== undefined) args.push('--max-turns', String(maxTurns))\n\n for (const dir of config.addDirs ?? []) args.push('--add-dir', q(dir))\n\n const allowedTools = [\n ...(modelOptions?.allowedTools ?? config.allowedTools ?? []),\n ...policyFlags.allowedTools,\n ]\n if (allowedTools.length > 0) {\n args.push('--allowedTools', q([...new Set(allowedTools)].join(',')))\n }\n const disallowedTools = [\n ...(modelOptions?.disallowedTools ?? config.disallowedTools ?? []),\n ...policyFlags.disallowedTools,\n ]\n if (disallowedTools.length > 0) {\n args.push('--disallowedTools', q([...new Set(disallowedTools)].join(',')))\n }\n\n const systemPrompts = normalizeSystemPrompts(options.systemPrompts)\n .map((prompt) => prompt.content)\n .filter((content) => content.trim() !== '')\n if (systemPrompts.length > 0) {\n const joined = systemPrompts.join('\\n\\n')\n const flag =\n config.systemPromptMode === 'replace'\n ? '--system-prompt'\n : '--append-system-prompt'\n args.push(flag, q(joined))\n }\n\n if (mcpConfigPath !== undefined) args.push('--mcp-config', q(mcpConfigPath))\n if (permissionPromptTool !== undefined) {\n args.push('--permission-prompt-tool', q(permissionPromptTool))\n }\n\n return `${exe} ${args.join(' ')}`\n }\n\n /**\n * Build the permission-prompt resolver the host MCP bridge exposes to claude\n * (`--permission-prompt-tool`). Maps claude's permission request onto the\n * sandbox policy + client approvals; on an `ask` action with no decision yet,\n * records an approval-requested event and denies (the client re-runs to grant).\n */\n private buildPermissionResolver(\n policy: SandboxPolicy | undefined,\n approvals: ReadonlyMap<string, boolean> | undefined,\n scripts: Record<string, string> | undefined,\n sink: Array<StreamChunk>,\n threadId: string,\n runId: string,\n ): (input: { tool_name?: string; input?: unknown }) => PermissionToolResult {\n const writeTools = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])\n const networkTools = new Set(['WebFetch', 'WebSearch'])\n return (request) => {\n const toolName = request.tool_name ?? 'tool'\n const cmdInput = request.input\n const command =\n toolName === 'Bash' &&\n cmdInput !== null &&\n typeof cmdInput === 'object' &&\n 'command' in cmdInput &&\n typeof (cmdInput as { command?: unknown }).command === 'string'\n ? (cmdInput as { command: string }).command\n : undefined\n const capability = writeTools.has(toolName)\n ? 'fileWrite'\n : networkTools.has(toolName)\n ? 'network'\n : undefined\n const id = approvalId({\n provider: 'claude-code',\n kind: command !== undefined ? 'command' : (capability ?? 'tool'),\n target: command ?? toolName,\n })\n const outcome = resolveApproval({\n policy,\n approvals,\n id,\n scripts,\n ...(command !== undefined ? { command } : {}),\n ...(capability !== undefined ? { capability } : {}),\n })\n if (outcome.needsApproval) {\n sink.push(\n buildApprovalRequestedEvent({\n approvalId: id,\n title: `Approve ${toolName}${command !== undefined ? `: ${command}` : ''}`,\n threadId,\n runId,\n detail: { provider: 'claude-code', toolName },\n }),\n )\n return {\n behavior: 'deny',\n message:\n 'Awaiting client approval. Approve in the UI and re-run to continue.',\n }\n }\n return outcome.decision === 'allow'\n ? { behavior: 'allow' }\n : { behavior: 'deny', message: 'Denied by sandbox policy.' }\n }\n }\n\n async *chatStream(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n let bridge: HostToolBridge | undefined\n let channel: BridgeEventChannel | undefined\n const approvalRequests: Array<StreamChunk> = []\n // Temp files written for the run (bridge MCP config, redirected prompt) that\n // carry the bearer token / prompt; removed in `finally` so they don't linger\n // in the sandbox after the run.\n let cleanupSandbox: SandboxHandle | undefined\n const tempFiles: Array<string> = []\n try {\n const sandbox = this.sandboxFrom(options)\n cleanupSandbox = sandbox\n const cwd = this.workdir(options)\n const runId = options.runId ?? this.generateId()\n const threadId = options.threadId ?? this.generateId()\n // Surfaces custom events from bridged tools (e.g. code mode console logs)\n // on this run's live output stream.\n channel = createBridgeEventChannel({ model: this.model, threadId, runId })\n\n // Idempotently project workspace skills/plugins/MCP into the sandbox in\n // claude's native format (guarded by the projection marker file).\n const projection = options.capabilities\n ? getWorkspaceProjection(options.capabilities, { optional: true })\n : undefined\n if (projection) await projectClaudeWorkspace(sandbox, projection)\n\n const policy = options.capabilities\n ? getSandboxPolicy(options.capabilities, { optional: true })\n : undefined\n\n // A permission-prompt tool gates the agent's native tools when a policy\n // can `ask`/`deny` (interactive approvals).\n const permission =\n policy !== undefined\n ? {\n toolName: 'approval_prompt',\n resolve: this.buildPermissionResolver(\n policy,\n options.approvals,\n projection?.scripts,\n approvalRequests,\n threadId,\n runId,\n ),\n }\n : undefined\n\n // Bridge chat()-provided server tools (and/or the permission tool) into\n // the sandbox over MCP.\n const hasTools = options.tools !== undefined && options.tools.length > 0\n if (hasTools || permission !== undefined) {\n const provisioner =\n (options.capabilities\n ? getToolBridgeProvisioner(options.capabilities, { optional: true })\n : undefined) ?? nodeHttpBridgeProvisioner\n bridge = await provisioner.provision(options.tools ?? [], {\n provider: sandbox.provider,\n context: options.context,\n emitCustomEvent: channel.emitCustomEvent,\n ...(permission !== undefined ? { permission } : {}),\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : {}),\n })\n }\n\n const { prompt, resume } = buildPrompt(\n options.messages,\n options.modelOptions?.sessionId,\n )\n // The bridge MCP config carries the per-run bearer token. Write it to a\n // file and pass claude the PATH, so the token never appears in argv (where\n // any process in the sandbox could read it via `ps` / `/proc/<pid>/cmdline`).\n let mcpConfigArg: string | undefined\n if (bridge) {\n // Pass claude a path RELATIVE to its cwd (the real workdir the handle\n // runs the process in). An absolute VIRTUAL path like `/workspace/…` is\n // wrong wherever claude runs outside a sandbox that literally uses\n // `/workspace` — e.g. local-process on Windows, where git-bash resolves\n // `/workspace` to `C:\\Program Files\\Git\\workspace` and the file is \"not\n // found\". The bare filename resolves correctly on every provider.\n const mcpConfigFile = `.tanstack-mcp-bridge-${runId}.json`\n const mcpConfigPath = `${cwd}/${mcpConfigFile}`\n await sandbox.fs.write(mcpConfigPath, bridgeToMcpConfig(bridge))\n tempFiles.push(mcpConfigPath)\n mcpConfigArg = mcpConfigFile\n }\n const command = this.buildCommand(\n options,\n resume,\n mapPolicyToClaudeFlags(policy),\n mcpConfigArg,\n bridge && permission\n ? `mcp__${bridge.name}__${permission.toolName}`\n : undefined,\n )\n\n // Deliver the prompt. The default feeds it over stdin (keeps it out of\n // argv). Providers without a writable host→process stdin (e.g. Cloudflare)\n // can't accept that write, so write the prompt to a file and redirect the\n // CLI's stdin from it in-shell (`claude -p … < file`) — still out of argv.\n let runCommand = command\n let stdinInput: string | undefined = prompt\n if (sandbox.capabilities.writableStdin === false) {\n const promptPath = `/tmp/tanstack-claude-prompt-${runId}`\n await sandbox.fs.write(promptPath, prompt)\n tempFiles.push(promptPath)\n runCommand = `${command} < ${q(promptPath)}`\n stdinInput = undefined\n }\n\n logger.request(\n `activity=chat provider=claude-code model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,\n { provider: 'claude-code', model: this.model },\n )\n\n const rawEvents = spawnNdjson(sandbox, runCommand, {\n cwd,\n ...(stdinInput !== undefined ? { input: stdinInput } : {}),\n // claude maps `bypassPermissions` to `--dangerously-skip-permissions`,\n // which it refuses to run as root. Sandbox containers routinely run as\n // root (Docker / Cloudflare), so set `IS_SANDBOX=1` — claude's\n // documented escape hatch for skip-permissions in an isolated\n // environment — merged over the sandbox env (a caller-provided value\n // wins). Safe to set unconditionally; it is a no-op for stricter modes.\n env: { IS_SANDBOX: '1', ...this.adapterConfig.env },\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : options.request?.signal\n ? { signal: options.request.signal }\n : {}),\n onNonJsonLine: (line) =>\n logger.provider(`provider=claude-code non-json line: ${line}`, {\n chunk: line,\n }),\n })\n\n async function* asMessages(): AsyncIterable<AgentSdkMessage> {\n for await (const event of rawEvents) yield event as AgentSdkMessage\n }\n\n yield* mergeChunkStreams(\n translateSdkStream(asMessages(), {\n model: this.model,\n runId,\n threadId,\n ...(options.parentRunId !== undefined && {\n parentRunId: options.parentRunId,\n }),\n genId: () => this.generateId(),\n onSdkMessage: (message) =>\n logger.provider(`provider=claude-code type=${message.type}`, {\n chunk: message,\n }),\n }),\n channel.stream,\n )\n\n // Surface the working-tree diff so UIs can render what the agent changed.\n if (this.adapterConfig.emitDiff !== false) {\n try {\n const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, {\n cwd,\n })\n if (diff.exitCode === 0 && diff.stdout.trim() !== '') {\n yield {\n type: EventType.CUSTOM,\n name: 'file.changed',\n value: { path: '.', diff: diff.stdout },\n timestamp: Date.now(),\n threadId,\n runId,\n }\n }\n } catch {\n // not a git repo / git unavailable — skip the diff event\n }\n }\n\n // Surface any pending approval requests (policy `ask` actions awaiting a\n // client decision); the client approves and re-runs to continue.\n for (const event of approvalRequests) yield event\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('claude-code.chatStream fatal', {\n error,\n source: 'claude-code.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n },\n }\n } finally {\n channel?.close()\n if (bridge) await bridge.close()\n // Remove the per-run token/prompt files. Best-effort: a cleanup failure\n // must not mask the run's own outcome.\n if (cleanupSandbox) {\n for (const path of tempFiles) {\n try {\n await cleanupSandbox.fs.remove(path)\n } catch {\n // file already gone / sandbox torn down — nothing to clean up\n }\n }\n }\n }\n }\n\n structuredOutput(\n _options: StructuredOutputOptions<ClaudeCodeTextProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n return Promise.reject(\n new Error(\n 'Structured output is not yet supported by the in-sandbox Claude Code adapter. ' +\n 'Use a model adapter (e.g. anthropic) for structured output, or omit outputSchema.',\n ),\n )\n }\n}\n\n/**\n * Creates a Claude Code harness adapter that runs **inside a sandbox**.\n *\n * Unlike HTTP provider adapters, this is a *harness* adapter: it spawns the\n * `claude` CLI inside the sandbox provided by `withSandbox(...)` (the adapter\n * declares `requires: [SandboxCapability]`), streams its `stream-json` stdout\n * back as AG-UI events, and lets Claude Code run its own agent loop and native\n * tools (Bash, file edits, search, …) against the sandbox workspace. The\n * sandbox image must provide the `claude` executable and `ANTHROPIC_API_KEY`\n * in its environment (e.g. via `workspace.secrets`). The session id is\n * surfaced via a CUSTOM `claude-code.session-id` event so follow-up calls can\n * resume through `modelOptions.sessionId`.\n */\nexport function claudeCodeText<TModel extends ClaudeCodeModel>(\n model: TModel,\n config: ClaudeCodeTextConfig = {},\n): ClaudeCodeTextAdapter<TModel> {\n return new ClaudeCodeTextAdapter(config, model)\n}\n"],"names":[],"mappings":";;;;;;;;AAiDA,MAAM,kBAAkB;AAwCxB,SAAS,EAAE,OAAuB;AAChC,SAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzC;AAGA,SAAS,kBAAkB,QAAgC;AACzD,SAAO,KAAK,UAAU;AAAA,IACpB,YAAY;AAAA,MACV,CAAC,OAAO,IAAI,GAAG;AAAA,QACb,MAAM;AAAA,QACN,KAAK,OAAO;AAAA,QACZ,SAAS,EAAE,eAAe,UAAU,OAAO,KAAK,GAAA;AAAA,MAAG;AAAA,IACrD;AAAA,EACF,CACD;AACH;AAEO,MAAM,8BAEH,gBAQR;AAAA,EACS,OAAO;AAAA;AAAA,EAGE,WAAW,CAAC,iBAAiB;AAAA,EAE9B;AAAA,EAEjB,YAAY,QAA8B,OAAe;AACvD,UAAM,CAAA,GAAI,KAAK;AACf,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEQ,YACN,SACe;AACf,UAAM,MAAM,QAAQ;AACpB,QAAI,CAAC,KAAK;AACR,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAAA,IAGJ;AACA,WAAO,WAAW,GAAG;AAAA,EACvB;AAAA,EAEQ,QA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AK;AAChD;"}
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { EventType, normalizeSystemPrompts } from '@tanstack/ai'\nimport { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport {\n SandboxCapability,\n alignedIfAttaching,\n approvalId,\n buildApprovalRequestedEvent,\n createBridgeEventChannel,\n createRunScopedIdGen,\n encodeRunId,\n getSandbox,\n getSandboxDurability,\n getSandboxPolicy,\n getToolBridgeProvisioner,\n getWorkspaceProjection,\n journalOptionsFor,\n mergeChunkStreams,\n nodeHttpBridgeProvisioner,\n resolveApproval,\n resolveDurableRunId,\n resolveDurableThreadId,\n spawnNdjson,\n} from '@tanstack/ai-sandbox'\nimport { buildPrompt } from '../messages/prompt'\nimport { translateSdkStream } from '../stream/translate'\nimport { mapPolicyToClaudeFlags } from './policy-map'\nimport { projectClaudeWorkspace } from './projection'\nimport type { ClaudePolicyFlags } from './policy-map'\nimport type {\n BridgeEventChannel,\n HostToolBridge,\n PermissionToolResult,\n SandboxHandle,\n SandboxPolicy,\n} from '@tanstack/ai-sandbox'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type {\n DefaultMessageMetadataByModality,\n Modality,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type { ClaudeCodeModel } from '../model-meta'\nimport type { ClaudeCodeTextProviderOptions } from '../provider-options'\nimport type { AgentSdkMessage } from '../stream/sdk-types'\n\nexport type ClaudeCodePermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n\nconst DEFAULT_WORKDIR = '/workspace'\n\nexport interface ClaudeCodeTextConfig {\n /**\n * Working directory inside the sandbox where `claude` runs. Defaults to\n * `/workspace` (the conventional sandbox workspace root).\n */\n cwd?: string\n /**\n * Claude Code permission mode passed via `--permission-mode`. Defaults to\n * `'bypassPermissions'` — a sandbox is isolated, so the agent is allowed to\n * edit files and run commands without prompting. Tighten via `defineSandboxPolicy`\n * / this option for less autonomy.\n */\n permissionMode?: ClaudeCodePermissionMode\n /** Built-in tools the harness may use (`--allowedTools`). */\n allowedTools?: Array<string>\n /** Built-in tools removed from the harness (`--disallowedTools`). */\n disallowedTools?: Array<string>\n /** Extra directories the agent may access (`--add-dir`). */\n addDirs?: Array<string>\n /** Maximum harness-internal turns (`--max-turns`). */\n maxTurns?: number\n /**\n * How `systemPrompts` from `chat()` are applied:\n * - `'append'` (default): `--append-system-prompt` on top of the preset.\n * - `'replace'`: `--system-prompt` as the entire system prompt.\n */\n systemPromptMode?: 'append' | 'replace'\n /** Path/name of the claude executable inside the sandbox. Defaults to `claude`. */\n claudeExecutable?: string\n /** Emit token-level deltas via `--include-partial-messages` (default true). */\n streamPartials?: boolean\n /** Extra environment variables for the claude process inside the sandbox. */\n env?: Record<string, string>\n /** Emit a `file.changed` CUSTOM event with the git diff after the run (default true). */\n emitDiff?: boolean\n}\n\n/** POSIX single-quote escape for embedding values in the `claude …` command. */\nfunction q(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n/** Format a host tool-bridge as claude's `--mcp-config` JSON. */\nfunction bridgeToMcpConfig(bridge: HostToolBridge): string {\n return JSON.stringify({\n mcpServers: {\n [bridge.name]: {\n type: 'http',\n url: bridge.url,\n headers: { Authorization: `Bearer ${bridge.token}` },\n },\n },\n })\n}\n\nexport class ClaudeCodeTextAdapter<\n TModel extends ClaudeCodeModel,\n> extends BaseTextAdapter<\n TModel,\n ClaudeCodeTextProviderOptions,\n ReadonlyArray<Modality> & readonly ['text'],\n DefaultMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never\n> {\n readonly name = 'claude-code' as const\n\n // Harness adapter: requires a sandbox to run the agent CLI inside.\n override readonly requires = [SandboxCapability] as const\n\n private readonly adapterConfig: ClaudeCodeTextConfig\n\n constructor(config: ClaudeCodeTextConfig, model: TModel) {\n super({}, model)\n this.adapterConfig = config\n }\n\n private sandboxFrom(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): SandboxHandle {\n const ctx = options.capabilities\n if (!ctx) {\n throw new Error(\n 'Adapter \"claude-code\" requires a sandbox. Add withSandbox(defineSandbox({ ... })) ' +\n 'to chat() middleware (e.g. with the local-process or docker provider).',\n )\n }\n return getSandbox(ctx)\n }\n\n private workdir(options: TextOptions<ClaudeCodeTextProviderOptions>): string {\n return (\n options.modelOptions?.cwd ?? this.adapterConfig.cwd ?? DEFAULT_WORKDIR\n )\n }\n\n /** Build the `claude` command line (prompt goes via stdin, not argv). */\n private buildCommand(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n resume: string | undefined,\n policyFlags: ClaudePolicyFlags,\n mcpConfigPath: string | undefined,\n permissionPromptTool: string | undefined,\n ): string {\n const config = this.adapterConfig\n const modelOptions = options.modelOptions\n const exe = config.claudeExecutable ?? 'claude'\n\n const args: Array<string> = [\n '-p',\n '--output-format',\n 'stream-json',\n '--verbose',\n '--model',\n q(this.model),\n ]\n\n if (config.streamPartials !== false) args.push('--include-partial-messages')\n if (resume !== undefined) args.push('--resume', q(resume))\n\n // Precedence: per-call modelOptions > adapter config > policy > sandbox default.\n const permissionMode =\n modelOptions?.permissionMode ??\n config.permissionMode ??\n policyFlags.permissionMode ??\n 'bypassPermissions'\n args.push('--permission-mode', q(permissionMode))\n\n const maxTurns = modelOptions?.maxTurns ?? config.maxTurns\n if (maxTurns !== undefined) args.push('--max-turns', String(maxTurns))\n\n for (const dir of config.addDirs ?? []) args.push('--add-dir', q(dir))\n\n const allowedTools = [\n ...(modelOptions?.allowedTools ?? config.allowedTools ?? []),\n ...policyFlags.allowedTools,\n ]\n if (allowedTools.length > 0) {\n args.push('--allowedTools', q([...new Set(allowedTools)].join(',')))\n }\n const disallowedTools = [\n ...(modelOptions?.disallowedTools ?? config.disallowedTools ?? []),\n ...policyFlags.disallowedTools,\n ]\n if (disallowedTools.length > 0) {\n args.push('--disallowedTools', q([...new Set(disallowedTools)].join(',')))\n }\n\n const systemPrompts = normalizeSystemPrompts(options.systemPrompts)\n .map((prompt) => prompt.content)\n .filter((content) => content.trim() !== '')\n if (systemPrompts.length > 0) {\n const joined = systemPrompts.join('\\n\\n')\n const flag =\n config.systemPromptMode === 'replace'\n ? '--system-prompt'\n : '--append-system-prompt'\n args.push(flag, q(joined))\n }\n\n if (mcpConfigPath !== undefined) args.push('--mcp-config', q(mcpConfigPath))\n if (permissionPromptTool !== undefined) {\n args.push('--permission-prompt-tool', q(permissionPromptTool))\n }\n\n return `${exe} ${args.join(' ')}`\n }\n\n /**\n * Build the permission-prompt resolver the host MCP bridge exposes to claude\n * (`--permission-prompt-tool`). Maps claude's permission request onto the\n * sandbox policy + client approvals; on an `ask` action with no decision yet,\n * records an approval-requested event and denies (the client re-runs to grant).\n */\n private buildPermissionResolver(\n policy: SandboxPolicy | undefined,\n approvals: ReadonlyMap<string, boolean> | undefined,\n scripts: Record<string, string> | undefined,\n sink: Array<StreamChunk>,\n threadId: string,\n runId: string,\n ): (input: { tool_name?: string; input?: unknown }) => PermissionToolResult {\n const writeTools = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])\n const networkTools = new Set(['WebFetch', 'WebSearch'])\n return (request) => {\n const toolName = request.tool_name ?? 'tool'\n const cmdInput = request.input\n const command =\n toolName === 'Bash' &&\n cmdInput !== null &&\n typeof cmdInput === 'object' &&\n 'command' in cmdInput &&\n typeof (cmdInput as { command?: unknown }).command === 'string'\n ? (cmdInput as { command: string }).command\n : undefined\n const capability = writeTools.has(toolName)\n ? 'fileWrite'\n : networkTools.has(toolName)\n ? 'network'\n : undefined\n const id = approvalId({\n provider: 'claude-code',\n kind: command !== undefined ? 'command' : (capability ?? 'tool'),\n target: command ?? toolName,\n })\n const outcome = resolveApproval({\n policy,\n approvals,\n id,\n scripts,\n ...(command !== undefined ? { command } : {}),\n ...(capability !== undefined ? { capability } : {}),\n })\n if (outcome.needsApproval) {\n sink.push(\n buildApprovalRequestedEvent({\n approvalId: id,\n title: `Approve ${toolName}${command !== undefined ? `: ${command}` : ''}`,\n threadId,\n runId,\n detail: { provider: 'claude-code', toolName },\n }),\n )\n return {\n behavior: 'deny',\n message:\n 'Awaiting client approval. Approve in the UI and re-run to continue.',\n }\n }\n return outcome.decision === 'allow'\n ? { behavior: 'allow' }\n : { behavior: 'deny', message: 'Denied by sandbox policy.' }\n }\n }\n\n async *chatStream(\n options: TextOptions<ClaudeCodeTextProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const { logger } = options\n let bridge: HostToolBridge | undefined\n let channel: BridgeEventChannel | undefined\n const approvalRequests: Array<StreamChunk> = []\n // Temp files written for the run (bridge MCP config, redirected prompt) that\n // carry the bearer token / prompt; removed in `finally` so they don't linger\n // in the sandbox after the run.\n let cleanupSandbox: SandboxHandle | undefined\n const tempFiles: Array<string> = []\n try {\n const sandbox = this.sandboxFrom(options)\n cleanupSandbox = sandbox\n const cwd = this.workdir(options)\n // Durability comes from `withSandbox(sandbox, { runs, durability })`, read\n // back off the capability bus. Absent it, everything below resolves to\n // exactly today's behavior (no journal option, no alignment, and a\n // generated `runId` when the caller didn't supply one).\n const durability = options.capabilities\n ? getSandboxDurability(options.capabilities, { optional: true })\n : undefined\n // The journaled path below derives its journal path and its\n // message-id generator from `runId`. A resuming host must recompute\n // the same `runId` to find the same journal file and reproduce the\n // same translated ids — that's only possible when the caller supplies\n // `runId` explicitly. `resolveDurableRunId` enforces that loudly (via\n // `DurableRunIdRequiredError`) whenever durability is wired, and falls\n // back to a fresh `this.generateId()` otherwise, preserving today's\n // behavior for non-durable runs.\n const runId = resolveDurableRunId(options.runId, {\n durable: durability !== undefined,\n adapter: 'claude-code',\n fallback: () => this.generateId(),\n })\n // `threadId` is stamped on every chunk `translateSdkStream` emits, so an\n // ATTACHING run that mints a fresh one replays a stream the stored log\n // cannot match at index 0. `resolveDurableThreadId` refuses that up front\n // instead of letting alignment discover it mid-stream; a durable FRESH run\n // and a non-durable run both keep the generated fallback untouched.\n const threadId = resolveDurableThreadId(options.threadId, {\n durable: durability !== undefined,\n attaching: durability?.attach === true,\n adapter: 'claude-code',\n fallback: () => this.generateId(),\n })\n // Surfaces custom events from bridged tools (e.g. code mode console logs)\n // on this run's live output stream.\n channel = createBridgeEventChannel({ model: this.model, threadId, runId })\n\n // Idempotently project workspace skills/plugins/MCP into the sandbox in\n // claude's native format (guarded by the projection marker file).\n const projection = options.capabilities\n ? getWorkspaceProjection(options.capabilities, { optional: true })\n : undefined\n if (projection) await projectClaudeWorkspace(sandbox, projection)\n\n const policy = options.capabilities\n ? getSandboxPolicy(options.capabilities, { optional: true })\n : undefined\n\n // A permission-prompt tool gates the agent's native tools when a policy\n // can `ask`/`deny` (interactive approvals).\n const permission =\n policy !== undefined\n ? {\n toolName: 'approval_prompt',\n resolve: this.buildPermissionResolver(\n policy,\n options.approvals,\n projection?.scripts,\n approvalRequests,\n threadId,\n runId,\n ),\n }\n : undefined\n\n // Bridge chat()-provided server tools (and/or the permission tool) into\n // the sandbox over MCP.\n const hasTools = options.tools !== undefined && options.tools.length > 0\n if (hasTools || permission !== undefined) {\n const provisioner =\n (options.capabilities\n ? getToolBridgeProvisioner(options.capabilities, { optional: true })\n : undefined) ?? nodeHttpBridgeProvisioner\n bridge = await provisioner.provision(options.tools ?? [], {\n provider: sandbox.provider,\n context: options.context,\n emitCustomEvent: channel.emitCustomEvent,\n ...(permission !== undefined ? { permission } : {}),\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : {}),\n })\n }\n\n const { prompt, resume } = buildPrompt(\n options.messages,\n options.modelOptions?.sessionId,\n )\n // Both files below name themselves after `runId`, and durability makes\n // `runId` CALLER-chosen. Raw, a `/` in it would silently turn each basename\n // into a nested path (writing outside the intended directory, or failing on\n // one that does not exist), `..` would climb out of that directory, and a\n // long id would fail the spawn with `ENAMETOOLONG`. `encodeRunId` collapses\n // any id to one bounded, injective path segment — the same encoder\n // `journalPaths` uses, so these files and the journal agree on how a given\n // id spells. Computed once so the two filenames cannot drift apart.\n const runIdSegment = encodeRunId(runId)\n\n // The bridge MCP config carries the per-run bearer token. Write it to a\n // file and pass claude the PATH, so the token never appears in argv (where\n // any process in the sandbox could read it via `ps` / `/proc/<pid>/cmdline`).\n let mcpConfigArg: string | undefined\n if (bridge) {\n // Pass claude a path RELATIVE to its cwd (the real workdir the handle\n // runs the process in). An absolute VIRTUAL path like `/workspace/…` is\n // wrong wherever claude runs outside a sandbox that literally uses\n // `/workspace` — e.g. local-process on Windows, where git-bash resolves\n // `/workspace` to `C:\\Program Files\\Git\\workspace` and the file is \"not\n // found\". The bare filename resolves correctly on every provider.\n const mcpConfigFile = `.tanstack-mcp-bridge-${runIdSegment}.json`\n const mcpConfigPath = `${cwd}/${mcpConfigFile}`\n await sandbox.fs.write(mcpConfigPath, bridgeToMcpConfig(bridge))\n tempFiles.push(mcpConfigPath)\n mcpConfigArg = mcpConfigFile\n }\n const command = this.buildCommand(\n options,\n resume,\n mapPolicyToClaudeFlags(policy),\n mcpConfigArg,\n bridge && permission\n ? `mcp__${bridge.name}__${permission.toolName}`\n : undefined,\n )\n\n // Deliver the prompt. The default feeds it over stdin (keeps it out of\n // argv). Providers without a writable host→process stdin (e.g. Cloudflare)\n // can't accept that write, so write the prompt to a file and redirect the\n // CLI's stdin from it in-shell (`claude -p … < file`) — still out of argv.\n let runCommand = command\n let stdinInput: string | undefined = prompt\n if (sandbox.capabilities.writableStdin === false) {\n const promptPath = `/tmp/tanstack-claude-prompt-${runIdSegment}`\n await sandbox.fs.write(promptPath, prompt)\n tempFiles.push(promptPath)\n runCommand = `${command} < ${q(promptPath)}`\n stdinInput = undefined\n }\n\n logger.request(\n `activity=chat provider=claude-code model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${resume ?? 'none'}`,\n { provider: 'claude-code', model: this.model },\n )\n\n const journalOptions = journalOptionsFor(durability, runId)\n const rawEvents = spawnNdjson(sandbox, runCommand, {\n cwd,\n ...(stdinInput !== undefined ? { input: stdinInput } : {}),\n // claude maps `bypassPermissions` to `--dangerously-skip-permissions`,\n // which it refuses to run as root. Sandbox containers routinely run as\n // root (Docker / Cloudflare), so set `IS_SANDBOX=1` — claude's\n // documented escape hatch for skip-permissions in an isolated\n // environment — merged over the sandbox env (a caller-provided value\n // wins). Safe to set unconditionally; it is a no-op for stricter modes.\n env: { IS_SANDBOX: '1', ...this.adapterConfig.env },\n ...(options.abortController?.signal\n ? { signal: options.abortController.signal }\n : options.request?.signal\n ? { signal: options.request.signal }\n : {}),\n onNonJsonLine: (line) =>\n logger.provider(`provider=claude-code non-json line: ${line}`, {\n chunk: line,\n }),\n // Journal + attach both come from the sandbox durability capability, so\n // the attach route configures takeover by passing `attach: true` to\n // `withSandbox` — `chat()` stays free of sandbox vocabulary. Omitted\n // entirely (not passed as `undefined`) when the run isn't durable, so\n // `spawnNdjson` takes its original, unjournaled path byte-for-byte.\n ...(journalOptions === undefined ? {} : { journal: journalOptions }),\n })\n\n async function* asMessages(): AsyncIterable<AgentSdkMessage> {\n for await (const event of rawEvents) yield event as AgentSdkMessage\n }\n\n // `mergeChunkStreams` splices `channel.stream` (host-tool-bridge CUSTOM\n // events from LIVE tool execution) into the deterministic translator\n // output. Those events do not occur on a replay, so a takeover's replay is\n // NOT chunk-for-chunk identical to what the log holds. `alignedIfAttaching`\n // handles it: alignment skips stored out-of-band CUSTOM entries within a\n // bounded window (see `align.ts`), so a bridged-tool run can be taken over\n // without a spurious `JournalReplayDivergedError` — while a genuine\n // determinism regression still throws. The wrap goes OUTSIDE the merge:\n // the stored log holds the previous host's merged output, so aligning the\n // pre-merge translated stream alone would compare against a log it never\n // produced. On a non-attaching run this is a pure passthrough (see\n // `alignedIfAttaching`'s `attach` guard).\n yield* alignedIfAttaching(\n mergeChunkStreams(\n translateSdkStream(asMessages(), {\n model: this.model,\n runId,\n threadId,\n ...(options.parentRunId !== undefined && {\n parentRunId: options.parentRunId,\n }),\n // Deterministic on the journaled path: two translations of the same\n // journal prefix from a fresh generator seeded with the same\n // `runId` mint the same message ids (unlike `this.generateId()`,\n // which mixes in `Date.now()` / `Math.random()`). See\n // `createRunScopedIdGen` in `@tanstack/ai-sandbox`.\n genId: createRunScopedIdGen(runId),\n onSdkMessage: (message) =>\n logger.provider(`provider=claude-code type=${message.type}`, {\n chunk: message,\n }),\n }),\n channel.stream,\n ),\n durability,\n logger,\n )\n\n // Surface the working-tree diff so UIs can render what the agent changed.\n if (this.adapterConfig.emitDiff !== false) {\n try {\n const diff = await sandbox.process.exec(`git -C ${q(cwd)} diff`, {\n cwd,\n })\n if (diff.exitCode === 0 && diff.stdout.trim() !== '') {\n yield {\n type: EventType.CUSTOM,\n name: 'file.changed',\n value: { path: '.', diff: diff.stdout },\n timestamp: Date.now(),\n threadId,\n runId,\n }\n }\n } catch {\n // not a git repo / git unavailable — skip the diff event\n }\n }\n\n // Surface any pending approval requests (policy `ask` actions awaiting a\n // client decision); the client approves and re-runs to continue.\n for (const event of approvalRequests) yield event\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n const rawEvent = toRunErrorRawEvent(error)\n logger.errors('claude-code.chatStream fatal', {\n error,\n source: 'claude-code.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n model: options.model,\n timestamp: Date.now(),\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n ...(rawEvent !== undefined && { rawEvent }),\n error: {\n message: err.message || 'Unknown error occurred',\n ...(err.code !== undefined && { code: err.code }),\n },\n }\n } finally {\n channel?.close()\n if (bridge) await bridge.close()\n // Remove the per-run token/prompt files. Best-effort: a cleanup failure\n // must not mask the run's own outcome.\n if (cleanupSandbox) {\n for (const path of tempFiles) {\n try {\n await cleanupSandbox.fs.remove(path)\n } catch {\n // file already gone / sandbox torn down — nothing to clean up\n }\n }\n }\n }\n }\n\n structuredOutput(\n _options: StructuredOutputOptions<ClaudeCodeTextProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n return Promise.reject(\n new Error(\n 'Structured output is not yet supported by the in-sandbox Claude Code adapter. ' +\n 'Use a model adapter (e.g. anthropic) for structured output, or omit outputSchema.',\n ),\n )\n }\n}\n\n/**\n * Creates a Claude Code harness adapter that runs **inside a sandbox**.\n *\n * Unlike HTTP provider adapters, this is a *harness* adapter: it spawns the\n * `claude` CLI inside the sandbox provided by `withSandbox(...)` (the adapter\n * declares `requires: [SandboxCapability]`), streams its `stream-json` stdout\n * back as AG-UI events, and lets Claude Code run its own agent loop and native\n * tools (Bash, file edits, search, …) against the sandbox workspace. The\n * sandbox image must provide the `claude` executable and `ANTHROPIC_API_KEY`\n * in its environment (e.g. via `workspace.secrets`). The session id is\n * surfaced via a CUSTOM `claude-code.session-id` event so follow-up calls can\n * resume through `modelOptions.sessionId`.\n */\nexport function claudeCodeText<TModel extends ClaudeCodeModel>(\n model: TModel,\n config: ClaudeCodeTextConfig = {},\n): ClaudeCodeTextAdapter<TModel> {\n return new ClaudeCodeTextAdapter(config, model)\n}\n"],"mappings":";;;;;;;;;AAwDA,IAAM,kBAAkB;;AAwCxB,SAAS,EAAE,OAAuB;CAChC,OAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,EAAE;AAC1C;;AAGA,SAAS,kBAAkB,QAAgC;CACzD,OAAO,KAAK,UAAU,EACpB,YAAY,GACT,OAAO,OAAO;EACb,MAAM;EACN,KAAK,OAAO;EACZ,SAAS,EAAE,eAAe,UAAU,OAAO,QAAQ;CACrD,EACF,EACF,CAAC;AACH;AAEA,IAAa,wBAAb,cAEU,gBAQR;CACA,OAAgB;CAGhB,WAA6B,CAAC,iBAAiB;CAE/C;CAEA,YAAY,QAA8B,OAAe;EACvD,MAAM,CAAC,GAAG,KAAK;EACf,KAAK,gBAAgB;CACvB;CAEA,YACE,SACe;EACf,MAAM,MAAM,QAAQ;EACpB,IAAI,CAAC,KACH,MAAM,IAAI,MACR,4JAEF;EAEF,OAAO,WAAW,GAAG;CACvB;CAEA,QAAgB,SAA6D;EAC3E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O,gCAAgC;IAC5C;IACA,QAAQ;GACV,CAAC;GACD,MAAM;IACJ,MAAM,UAAU;IAChB,OAAO,QAAQ;IACf,WAAW,KAAK,IAAI;IACpB,SAAS,IAAI,WAAW;IACxB,GAAI,IAAI,SAAS,KAAA,KAAa,EAAE,MAAM,IAAI,KAAK;IAC/C,GAAI,aAAa,KAAA,KAAa,EAAE,SAAS;IACzC,OAAO;KACL,SAAS,IAAI,WAAW;KACxB,GAAI,IAAI,SAAS,KAAA,KAAa,EAAE,MAAM,IAAI,KAAK;IACjD;GACF;EACF,UAAU;GACR,SAAS,MAAM;GACf,IAAI,QAAQ,MAAM,OAAO,MAAM;GAG/B,IAAI,gBACF,KAAK,MAAM,QAAQ,WACjB,IAAI;IACF,MAAM,eAAe,GAAG,OAAO,IAAI;GACrC,QAAQ,CAER;EAGN;CACF;CAEA,iBACE,UAC0C;EAC1C,OAAO,QAAQ,uBACb,IAAI,MACF,iKAEF,CACF;CACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,eACd,OACA,SAA+B,CAAC,GACD;CAC/B,OAAO,IAAI,sBAAsB,QAAQ,KAAK;AAChD"}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,15 +1,5 @@
|
|
|
1
|
+
import { buildPrompt } from "./messages/prompt.js";
|
|
2
|
+
import { BRIDGED_MCP_SERVER_NAME, SESSION_ID_EVENT, stripMcpPrefix, translateSdkStream } from "./stream/translate.js";
|
|
1
3
|
import { ClaudeCodeTextAdapter, claudeCodeText } from "./adapters/text.js";
|
|
2
4
|
import { CLAUDE_CODE_MODELS } from "./model-meta.js";
|
|
3
|
-
|
|
4
|
-
import { buildPrompt } from "./messages/prompt.js";
|
|
5
|
-
export {
|
|
6
|
-
BRIDGED_MCP_SERVER_NAME,
|
|
7
|
-
CLAUDE_CODE_MODELS,
|
|
8
|
-
ClaudeCodeTextAdapter,
|
|
9
|
-
SESSION_ID_EVENT,
|
|
10
|
-
buildPrompt,
|
|
11
|
-
claudeCodeText,
|
|
12
|
-
stripMcpPrefix,
|
|
13
|
-
translateSdkStream
|
|
14
|
-
};
|
|
15
|
-
//# sourceMappingURL=index.js.map
|
|
5
|
+
export { BRIDGED_MCP_SERVER_NAME, CLAUDE_CODE_MODELS, ClaudeCodeTextAdapter, SESSION_ID_EVENT, buildPrompt, claudeCodeText, stripMcpPrefix, translateSdkStream };
|
|
@@ -1,37 +1,32 @@
|
|
|
1
|
+
//#region src/messages/prompt.ts
|
|
1
2
|
function extractText(content) {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
(part) => part.type === "text" && typeof part.content === "string" ? part.content : ""
|
|
6
|
-
).join("");
|
|
3
|
+
if (content === null) return "";
|
|
4
|
+
if (typeof content === "string") return content;
|
|
5
|
+
return content.map((part) => part.type === "text" && typeof part.content === "string" ? part.content : "").join("");
|
|
7
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* Convert TanStack chat history into the Agent SDK's `{ prompt, resume }`
|
|
9
|
+
* inputs.
|
|
10
|
+
*
|
|
11
|
+
* With a `sessionId`, the harness already holds the conversation context, so
|
|
12
|
+
* only the trailing user message is sent and the session is resumed. Without
|
|
13
|
+
* one, prior turns are flattened into a plain-text transcript preamble (tool
|
|
14
|
+
* messages and tool-call-only assistant turns are harness-internal noise and
|
|
15
|
+
* are skipped; prompts are text-only in v1).
|
|
16
|
+
*/
|
|
8
17
|
function buildPrompt(messages, sessionId) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const priorTurns = messages.slice(0, -1).filter(
|
|
20
|
-
(message) => (message.role === "user" || message.role === "assistant") && extractText(message.content).trim() !== ""
|
|
21
|
-
).map(
|
|
22
|
-
(message) => `${message.role === "user" ? "User" : "Assistant"}: ${extractText(message.content).trim()}`
|
|
23
|
-
);
|
|
24
|
-
if (priorTurns.length === 0) {
|
|
25
|
-
return { prompt: lastUserText };
|
|
26
|
-
}
|
|
27
|
-
return {
|
|
28
|
-
prompt: `Previous conversation:
|
|
29
|
-
${priorTurns.join("\n")}
|
|
30
|
-
|
|
31
|
-
${lastUserText}`
|
|
32
|
-
};
|
|
18
|
+
const lastMessage = messages.at(-1);
|
|
19
|
+
const lastUserText = lastMessage?.role === "user" ? extractText(lastMessage.content).trim() : "";
|
|
20
|
+
if (!lastUserText) throw new Error("Claude Code adapter requires a trailing user message with text content.");
|
|
21
|
+
if (sessionId !== void 0) return {
|
|
22
|
+
prompt: lastUserText,
|
|
23
|
+
resume: sessionId
|
|
24
|
+
};
|
|
25
|
+
const priorTurns = messages.slice(0, -1).filter((message) => (message.role === "user" || message.role === "assistant") && extractText(message.content).trim() !== "").map((message) => `${message.role === "user" ? "User" : "Assistant"}: ${extractText(message.content).trim()}`);
|
|
26
|
+
if (priorTurns.length === 0) return { prompt: lastUserText };
|
|
27
|
+
return { prompt: `Previous conversation:\n${priorTurns.join("\n")}\n\n${lastUserText}` };
|
|
33
28
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
//# sourceMappingURL=prompt.js.map
|
|
29
|
+
//#endregion
|
|
30
|
+
export { buildPrompt };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=prompt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","sources":["../../../src/messages/prompt.ts"],"sourcesContent":["import type { ModelMessage } from '@tanstack/ai'\n\nexport interface BuiltPrompt {\n prompt: string\n /** Claude Code session id to resume, when the caller threaded one through. */\n resume?: string\n}\n\nfunction extractText(content: ModelMessage['content']): string {\n if (content === null) return ''\n if (typeof content === 'string') return content\n return content\n .map((part) =>\n part.type === 'text' && typeof part.content === 'string'\n ? part.content\n : '',\n )\n .join('')\n}\n\n/**\n * Convert TanStack chat history into the Agent SDK's `{ prompt, resume }`\n * inputs.\n *\n * With a `sessionId`, the harness already holds the conversation context, so\n * only the trailing user message is sent and the session is resumed. Without\n * one, prior turns are flattened into a plain-text transcript preamble (tool\n * messages and tool-call-only assistant turns are harness-internal noise and\n * are skipped; prompts are text-only in v1).\n */\nexport function buildPrompt(\n messages: Array<ModelMessage>,\n sessionId: string | undefined,\n): BuiltPrompt {\n const lastMessage = messages.at(-1)\n const lastUserText =\n lastMessage?.role === 'user' ? extractText(lastMessage.content).trim() : ''\n\n if (!lastUserText) {\n throw new Error(\n 'Claude Code adapter requires a trailing user message with text content.',\n )\n }\n\n if (sessionId !== undefined) {\n return { prompt: lastUserText, resume: sessionId }\n }\n\n const priorTurns = messages\n .slice(0, -1)\n .filter(\n (message) =>\n (message.role === 'user' || message.role === 'assistant') &&\n extractText(message.content).trim() !== '',\n )\n .map(\n (message) =>\n `${message.role === 'user' ? 'User' : 'Assistant'}: ${extractText(message.content).trim()}`,\n )\n\n if (priorTurns.length === 0) {\n return { prompt: lastUserText }\n }\n\n return {\n prompt: `Previous conversation:\\n${priorTurns.join('\\n')}\\n\\n${lastUserText}`,\n }\n}\n"],"
|
|
1
|
+
{"version":3,"file":"prompt.js","names":[],"sources":["../../../src/messages/prompt.ts"],"sourcesContent":["import type { ModelMessage } from '@tanstack/ai'\n\nexport interface BuiltPrompt {\n prompt: string\n /** Claude Code session id to resume, when the caller threaded one through. */\n resume?: string\n}\n\nfunction extractText(content: ModelMessage['content']): string {\n if (content === null) return ''\n if (typeof content === 'string') return content\n return content\n .map((part) =>\n part.type === 'text' && typeof part.content === 'string'\n ? part.content\n : '',\n )\n .join('')\n}\n\n/**\n * Convert TanStack chat history into the Agent SDK's `{ prompt, resume }`\n * inputs.\n *\n * With a `sessionId`, the harness already holds the conversation context, so\n * only the trailing user message is sent and the session is resumed. Without\n * one, prior turns are flattened into a plain-text transcript preamble (tool\n * messages and tool-call-only assistant turns are harness-internal noise and\n * are skipped; prompts are text-only in v1).\n */\nexport function buildPrompt(\n messages: Array<ModelMessage>,\n sessionId: string | undefined,\n): BuiltPrompt {\n const lastMessage = messages.at(-1)\n const lastUserText =\n lastMessage?.role === 'user' ? extractText(lastMessage.content).trim() : ''\n\n if (!lastUserText) {\n throw new Error(\n 'Claude Code adapter requires a trailing user message with text content.',\n )\n }\n\n if (sessionId !== undefined) {\n return { prompt: lastUserText, resume: sessionId }\n }\n\n const priorTurns = messages\n .slice(0, -1)\n .filter(\n (message) =>\n (message.role === 'user' || message.role === 'assistant') &&\n extractText(message.content).trim() !== '',\n )\n .map(\n (message) =>\n `${message.role === 'user' ? 'User' : 'Assistant'}: ${extractText(message.content).trim()}`,\n )\n\n if (priorTurns.length === 0) {\n return { prompt: lastUserText }\n }\n\n return {\n prompt: `Previous conversation:\\n${priorTurns.join('\\n')}\\n\\n${lastUserText}`,\n }\n}\n"],"mappings":";AAQA,SAAS,YAAY,SAA0C;CAC7D,IAAI,YAAY,MAAM,OAAO;CAC7B,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,OAAO,QACJ,KAAK,SACJ,KAAK,SAAS,UAAU,OAAO,KAAK,YAAY,WAC5C,KAAK,UACL,EACN,CAAC,CACA,KAAK,EAAE;AACZ;;;;;;;;;;;AAYA,SAAgB,YACd,UACA,WACa;CACb,MAAM,cAAc,SAAS,GAAG,EAAE;CAClC,MAAM,eACJ,aAAa,SAAS,SAAS,YAAY,YAAY,OAAO,CAAC,CAAC,KAAK,IAAI;CAE3E,IAAI,CAAC,cACH,MAAM,IAAI,MACR,yEACF;CAGF,IAAI,cAAc,KAAA,GAChB,OAAO;EAAE,QAAQ;EAAc,QAAQ;CAAU;CAGnD,MAAM,aAAa,SAChB,MAAM,GAAG,EAAE,CAAC,CACZ,QACE,aACE,QAAQ,SAAS,UAAU,QAAQ,SAAS,gBAC7C,YAAY,QAAQ,OAAO,CAAC,CAAC,KAAK,MAAM,EAC5C,CAAC,CACA,KACE,YACC,GAAG,QAAQ,SAAS,SAAS,SAAS,YAAY,IAAI,YAAY,QAAQ,OAAO,CAAC,CAAC,KAAK,GAC5F;CAEF,IAAI,WAAW,WAAW,GACxB,OAAO,EAAE,QAAQ,aAAa;CAGhC,OAAO,EACL,QAAQ,2BAA2B,WAAW,KAAK,IAAI,EAAE,MAAM,eACjE;AACF"}
|
package/dist/esm/model-meta.js
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
//#region src/model-meta.ts
|
|
2
|
+
/**
|
|
3
|
+
* Models known to work with Claude Code. The harness accepts any Anthropic
|
|
4
|
+
* model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),
|
|
5
|
+
* so this list exists for autocomplete — any string is accepted via the
|
|
6
|
+
* `(string & {})` escape hatch in {@link ClaudeCodeModel}.
|
|
7
|
+
*/
|
|
8
|
+
var CLAUDE_CODE_MODELS = [
|
|
9
|
+
"claude-opus-4-8",
|
|
10
|
+
"claude-opus-4-7",
|
|
11
|
+
"claude-opus-4-6",
|
|
12
|
+
"claude-sonnet-4-6",
|
|
13
|
+
"claude-haiku-4-5",
|
|
14
|
+
"opus",
|
|
15
|
+
"sonnet",
|
|
16
|
+
"haiku"
|
|
10
17
|
];
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
//# sourceMappingURL=model-meta.js.map
|
|
18
|
+
//#endregion
|
|
19
|
+
export { CLAUDE_CODE_MODELS };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=model-meta.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-meta.js","sources":["../../src/model-meta.ts"],"sourcesContent":["/**\n * Models known to work with Claude Code. The harness accepts any Anthropic\n * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),\n * so this list exists for autocomplete — any string is accepted via the\n * `(string & {})` escape hatch in {@link ClaudeCodeModel}.\n */\nexport const CLAUDE_CODE_MODELS = [\n 'claude-opus-4-8',\n 'claude-opus-4-7',\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n 'opus',\n 'sonnet',\n 'haiku',\n] as const\n\nexport type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number]\n\n/** Any Claude model id accepted by Claude Code; known ids get autocomplete. */\nexport type ClaudeCodeModel = KnownClaudeCodeModel | (string & {})\n"],"
|
|
1
|
+
{"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["/**\n * Models known to work with Claude Code. The harness accepts any Anthropic\n * model id (and the `opus` / `sonnet` / `haiku` aliases resolved by the CLI),\n * so this list exists for autocomplete — any string is accepted via the\n * `(string & {})` escape hatch in {@link ClaudeCodeModel}.\n */\nexport const CLAUDE_CODE_MODELS = [\n 'claude-opus-4-8',\n 'claude-opus-4-7',\n 'claude-opus-4-6',\n 'claude-sonnet-4-6',\n 'claude-haiku-4-5',\n 'opus',\n 'sonnet',\n 'haiku',\n] as const\n\nexport type KnownClaudeCodeModel = (typeof CLAUDE_CODE_MODELS)[number]\n\n/** Any Claude model id accepted by Claude Code; known ids get autocomplete. */\nexport type ClaudeCodeModel = KnownClaudeCodeModel | (string & {})\n"],"mappings":";;;;;;;AAMA,IAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|