agent.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { Command } from "commander";
  2. import { runAgentLoop } from "@actalk/inkos-core";
  3. import { loadConfig, createClient, findProjectRoot, resolveContext, log, logError } from "../utils.js";
  4. export const agentCommand = new Command("agent")
  5. .description("Natural language agent mode (LLM orchestrates via tool-use)")
  6. .argument("<instruction>", "Natural language instruction")
  7. .option("--context <text>", "Additional context (natural language)")
  8. .option("--context-file <path>", "Read additional context from file")
  9. .option("--max-turns <n>", "Maximum agent turns", "20")
  10. .option("--json", "Output JSON (suppress progress messages)")
  11. .option("--quiet", "Suppress tool call logs")
  12. .action(async (instruction: string, opts) => {
  13. try {
  14. const config = await loadConfig();
  15. const client = createClient(config);
  16. const root = findProjectRoot();
  17. const context = await resolveContext(opts);
  18. const fullInstruction = context
  19. ? `${instruction}\n\n补充信息:${context}`
  20. : instruction;
  21. const maxTurns = parseInt(opts.maxTurns, 10);
  22. const result = await runAgentLoop(
  23. {
  24. client,
  25. model: config.llm.model,
  26. projectRoot: root,
  27. },
  28. fullInstruction,
  29. {
  30. maxTurns,
  31. onToolCall: opts.quiet || opts.json
  32. ? undefined
  33. : (name, args) => {
  34. log(` [tool] ${name}(${JSON.stringify(args)})`);
  35. },
  36. onToolResult: opts.quiet || opts.json
  37. ? undefined
  38. : (name, result) => {
  39. const preview = result.length > 200 ? `${result.slice(0, 200)}...` : result;
  40. log(` [result] ${name} → ${preview}`);
  41. },
  42. onMessage: opts.json
  43. ? undefined
  44. : (content) => {
  45. log(`\n${content}`);
  46. },
  47. },
  48. );
  49. if (opts.json) {
  50. log(JSON.stringify({ result }));
  51. }
  52. } catch (e) {
  53. if (opts.json) {
  54. log(JSON.stringify({ error: String(e) }));
  55. } else {
  56. logError(`Agent failed: ${e}`);
  57. }
  58. process.exit(1);
  59. }
  60. });