smoke-claude.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // 手动冒烟测试:验证 Agent SDK 能用本机登录态运行,并观察消息流。
  2. // 用法:pnpm tsx scripts/smoke-claude.ts <cwd> [prompt]
  3. import { query } from '@anthropic-ai/claude-agent-sdk'
  4. const cwd = process.argv[2] ?? process.cwd()
  5. const prompt = process.argv[3] ?? '用 Bash 运行 `echo hello > out.txt`,然后读取 out.txt 告诉我内容。'
  6. const q = query({
  7. prompt,
  8. options: {
  9. cwd,
  10. model: 'haiku',
  11. settingSources: [],
  12. includePartialMessages: true,
  13. pathToClaudeCodeExecutable: `${process.env.HOME}/.local/bin/claude`,
  14. sandbox: { enabled: true, failIfUnavailable: true, allowUnsandboxedCommands: false },
  15. canUseTool: async (tool, input, opts) => {
  16. console.log('[canUseTool]', tool, JSON.stringify(input).slice(0, 200), opts.decisionReason ?? '')
  17. return { behavior: 'allow', updatedInput: input }
  18. },
  19. },
  20. })
  21. for await (const m of q) {
  22. if (m.type === 'stream_event') {
  23. const e = m.event
  24. if (e.type === 'content_block_delta' && e.delta.type === 'text_delta') process.stdout.write(e.delta.text)
  25. continue
  26. }
  27. 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 : ''}`
  28. : m.type === 'assistant' ? m.message.content.map(b => b.type).join(',')
  29. : m.type === 'user' ? JSON.stringify(m.message.content).slice(0, 160)
  30. : m.type === 'result' ? `${m.subtype} cost=${m.total_cost_usd} turns=${m.num_turns}`
  31. : ''
  32. console.log(`\n<${m.type}> ${brief}`)
  33. }