| 123456789101112131415161718192021222324252627282930313233343536 |
- // 手动冒烟测试:验证 Agent SDK 能用本机登录态运行,并观察消息流。
- // 用法:pnpm tsx scripts/smoke-claude.ts <cwd> [prompt]
- import { query } from '@anthropic-ai/claude-agent-sdk'
- const cwd = process.argv[2] ?? process.cwd()
- const prompt = process.argv[3] ?? '用 Bash 运行 `echo hello > out.txt`,然后读取 out.txt 告诉我内容。'
- const q = query({
- prompt,
- options: {
- cwd,
- model: 'haiku',
- settingSources: [],
- includePartialMessages: true,
- pathToClaudeCodeExecutable: `${process.env.HOME}/.local/bin/claude`,
- sandbox: { enabled: true, failIfUnavailable: true, allowUnsandboxedCommands: false },
- canUseTool: async (tool, input, opts) => {
- console.log('[canUseTool]', tool, JSON.stringify(input).slice(0, 200), opts.decisionReason ?? '')
- return { behavior: 'allow', updatedInput: input }
- },
- },
- })
- for await (const m of q) {
- if (m.type === 'stream_event') {
- const e = m.event
- if (e.type === 'content_block_delta' && e.delta.type === 'text_delta') process.stdout.write(e.delta.text)
- continue
- }
- const brief = m.type === 'system' ? `${m.subtype} ${'apiKeySource' in m ? m.apiKeySource : ''} ${'model' in m ? m.model : ''} ${'claude_code_version' in m ? m.claude_code_version : ''}`
- : m.type === 'assistant' ? m.message.content.map(b => b.type).join(',')
- : m.type === 'user' ? JSON.stringify(m.message.content).slice(0, 160)
- : m.type === 'result' ? `${m.subtype} cost=${m.total_cost_usd} turns=${m.num_turns}`
- : ''
- console.log(`\n<${m.type}> ${brief}`)
- }
|