@wukonglabs/wukong 0.0.9 → 0.0.10

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.
Files changed (65) hide show
  1. package/dist/cli/exit-codes.js +12 -16
  2. package/dist/cli/exit-codes.js.map +1 -1
  3. package/dist/cli/help.js +4 -8
  4. package/dist/cli/help.js.map +1 -1
  5. package/dist/cli/session-commands.js +1 -4
  6. package/dist/cli/session-commands.js.map +1 -1
  7. package/dist/cli/summary.js +2 -6
  8. package/dist/cli/summary.js.map +1 -1
  9. package/dist/cli/workspace-commands.js +1 -4
  10. package/dist/cli/workspace-commands.js.map +1 -1
  11. package/dist/index.js +344 -121
  12. package/dist/index.js.map +1 -1
  13. package/dist/sigint-handler.d.ts +62 -0
  14. package/dist/sigint-handler.d.ts.map +1 -0
  15. package/dist/sigint-handler.js +62 -0
  16. package/dist/sigint-handler.js.map +1 -0
  17. package/dist/tui/app.d.ts +57 -0
  18. package/dist/tui/app.d.ts.map +1 -0
  19. package/dist/tui/app.js +194 -0
  20. package/dist/tui/app.js.map +1 -0
  21. package/dist/tui/header.d.ts +24 -0
  22. package/dist/tui/header.d.ts.map +1 -0
  23. package/dist/tui/header.js +26 -0
  24. package/dist/tui/header.js.map +1 -0
  25. package/dist/tui/permission-card.d.ts +27 -0
  26. package/dist/tui/permission-card.d.ts.map +1 -0
  27. package/dist/tui/permission-card.js +75 -0
  28. package/dist/tui/permission-card.js.map +1 -0
  29. package/dist/tui/plan-panel.d.ts +29 -0
  30. package/dist/tui/plan-panel.d.ts.map +1 -0
  31. package/dist/tui/plan-panel.js +26 -0
  32. package/dist/tui/plan-panel.js.map +1 -0
  33. package/dist/tui/response-panel.d.ts +49 -0
  34. package/dist/tui/response-panel.d.ts.map +1 -0
  35. package/dist/tui/response-panel.js +13 -0
  36. package/dist/tui/response-panel.js.map +1 -0
  37. package/dist/tui/run-ink.d.ts +22 -0
  38. package/dist/tui/run-ink.d.ts.map +1 -0
  39. package/dist/tui/run-ink.js +31 -0
  40. package/dist/tui/run-ink.js.map +1 -0
  41. package/dist/tui/should-use-tui.d.ts +25 -0
  42. package/dist/tui/should-use-tui.d.ts.map +1 -0
  43. package/dist/tui/should-use-tui.js +29 -0
  44. package/dist/tui/should-use-tui.js.map +1 -0
  45. package/dist/tui/text-input.d.ts +52 -0
  46. package/dist/tui/text-input.d.ts.map +1 -0
  47. package/dist/tui/text-input.js +321 -0
  48. package/dist/tui/text-input.js.map +1 -0
  49. package/dist/tui/thinking-panel.d.ts +40 -0
  50. package/dist/tui/thinking-panel.d.ts.map +1 -0
  51. package/dist/tui/thinking-panel.js +54 -0
  52. package/dist/tui/thinking-panel.js.map +1 -0
  53. package/dist/tui/tool-cards.d.ts +30 -0
  54. package/dist/tui/tool-cards.d.ts.map +1 -0
  55. package/dist/tui/tool-cards.js +34 -0
  56. package/dist/tui/tool-cards.js.map +1 -0
  57. package/dist/tui/use-input-history.d.ts +40 -0
  58. package/dist/tui/use-input-history.d.ts.map +1 -0
  59. package/dist/tui/use-input-history.js +123 -0
  60. package/dist/tui/use-input-history.js.map +1 -0
  61. package/dist/tui/use-plan-state.d.ts +4 -0
  62. package/dist/tui/use-plan-state.d.ts.map +1 -0
  63. package/dist/tui/use-plan-state.js +73 -0
  64. package/dist/tui/use-plan-state.js.map +1 -0
  65. package/package.json +7 -2
package/dist/index.js CHANGED
@@ -1,52 +1,20 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || (function () {
20
- var ownKeys = function(o) {
21
- ownKeys = Object.getOwnPropertyNames || function (o) {
22
- var ar = [];
23
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
- return ar;
25
- };
26
- return ownKeys(o);
27
- };
28
- return function (mod) {
29
- if (mod && mod.__esModule) return mod;
30
- var result = {};
31
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
- __setModuleDefault(result, mod);
33
- return result;
34
- };
35
- })();
36
- Object.defineProperty(exports, "__esModule", { value: true });
37
- const readline = __importStar(require("node:readline"));
38
- const fs = __importStar(require("node:fs/promises"));
39
- const path = __importStar(require("node:path"));
40
- const os = __importStar(require("node:os"));
2
+ import * as readline from "node:readline";
3
+ import * as fs from "node:fs/promises";
4
+ import * as path from "node:path";
5
+ import * as os from "node:os";
41
6
  // ── 核心能力全部来自独立发布的 SDK 包 ──
42
7
  // CLI 只做参数解析、会话编排与输出渲染,组装逻辑(createAgent)在 SDK 内。
43
- const wukong_agent_sdk_1 = require("@wukonglabs/wukong-agent-sdk");
8
+ import { createAgent, SessionManager, collectSmartContext, AutoVerifier, DEFAULT_VERIFY_CONFIG, compactIfNeeded, loadConfig, Logger, setGlobalLogger, resolveWorkspace, getDefaultEventBus, ToolAuthorizer, } from "@wukonglabs/wukong-agent-sdk";
44
9
  // ── CLI 本地模块(不属于 SDK 对外能力) ──
45
- const exit_codes_js_1 = require("./cli/exit-codes.js");
46
- const help_js_1 = require("./cli/help.js");
47
- const summary_js_1 = require("./cli/summary.js");
48
- const session_commands_js_1 = require("./cli/session-commands.js");
49
- const workspace_commands_js_1 = require("./cli/workspace-commands.js");
10
+ import { EXIT_CODES, resolveExitCode } from "./cli/exit-codes.js";
11
+ import { HELP_TEXT, formatVersion } from "./cli/help.js";
12
+ import { buildJsonSummary } from "./cli/summary.js";
13
+ import { runSessionCommand } from "./cli/session-commands.js";
14
+ import { runWorkspaceCommand } from "./cli/workspace-commands.js";
15
+ import { shouldUseTuiFromProcess } from "./tui/should-use-tui.js";
16
+ import { runInk } from "./tui/run-ink.js";
17
+ import { createAbortController } from "./sigint-handler.js";
50
18
  function parseArgs(argv) {
51
19
  const args = argv.slice(2);
52
20
  const result = {
@@ -264,23 +232,25 @@ function parseArgs(argv) {
264
232
  }
265
233
  return result;
266
234
  }
267
- async function initAgent(cfg, logger, confirmMode, thinking, ciMode = false, planMode = 'auto', overrides, onStream, tracerOpts) {
268
- return (0, wukong_agent_sdk_1.createAgent)({
269
- config: cfg,
270
- logger,
271
- confirmMode,
272
- thinking,
273
- ciMode,
274
- planMode,
275
- overrides,
276
- onStream,
277
- tracer: tracerOpts,
235
+ async function initAgent(opts) {
236
+ return createAgent({
237
+ config: opts.cfg,
238
+ logger: opts.logger,
239
+ confirmMode: opts.confirmMode,
240
+ thinking: opts.thinking,
241
+ ciMode: opts.ciMode ?? false,
242
+ planMode: opts.planMode ?? 'auto',
243
+ overrides: opts.overrides,
244
+ onStream: opts.onStream,
245
+ tracer: opts.tracerOpts,
246
+ shouldAbort: opts.shouldAbort,
247
+ authorizeTool: opts.authorizeTool,
278
248
  });
279
249
  }
280
250
  async function runAgentCommand(cliArgs) {
281
- const logger = new wukong_agent_sdk_1.Logger({ jsonMode: cliArgs.json, level: cliArgs.verbose ? 'debug' : 'info' });
282
- (0, wukong_agent_sdk_1.setGlobalLogger)(logger);
283
- const cfg = await (0, wukong_agent_sdk_1.loadConfig)();
251
+ const logger = new Logger({ jsonMode: cliArgs.json, level: cliArgs.verbose ? 'debug' : 'info' });
252
+ setGlobalLogger(logger);
253
+ const cfg = await loadConfig();
284
254
  applyPermissionOverrides(cfg, cliArgs, logger);
285
255
  const resolvedConfirmMode = cliArgs.yes ? 'never' : (cliArgs.confirmMode ?? cfg.tools.confirmMode ?? 'smart');
286
256
  const resolvedThinking = resolveThinking(cliArgs, cfg);
@@ -291,7 +261,7 @@ async function runAgentCommand(cliArgs) {
291
261
  const sessionStrategy = resolveCliSessionStrategy(cliArgs, isCiMode, logger);
292
262
  if (sessionStrategy === null) {
293
263
  // 参数冲突,已经打过日志,直接退出
294
- process.exit(exit_codes_js_1.EXIT_CODES.CONFIG_ERROR);
264
+ process.exit(EXIT_CODES.CONFIG_ERROR);
295
265
  }
296
266
  const isEphemeral = cliArgs.ephemeral || isCiMode;
297
267
  // ── 流式输出回调 ──
@@ -328,12 +298,13 @@ async function runAgentCommand(cliArgs) {
328
298
  break;
329
299
  }
330
300
  };
331
- const { llm, contextBuilder, agent, effectiveMaxSteps, resolvedModel } = await initAgent(cfg, logger, resolvedConfirmMode, resolvedThinking, isCiMode, cliArgs.planMode, {
332
- maxSteps: cliArgs.maxSteps,
333
- contextWindow: cliArgs.contextWindow,
334
- }, onStream, { enabled: !cliArgs.noTrace });
335
- const sessionManager = new wukong_agent_sdk_1.SessionManager(cfg.sessions.dir);
336
- const workspace = (0, wukong_agent_sdk_1.resolveWorkspace)();
301
+ const { llm, contextBuilder, agent, effectiveMaxSteps, resolvedModel } = await initAgent({
302
+ cfg, logger, confirmMode: resolvedConfirmMode, thinking: resolvedThinking, ciMode: isCiMode, planMode: cliArgs.planMode,
303
+ overrides: { maxSteps: cliArgs.maxSteps, contextWindow: cliArgs.contextWindow },
304
+ onStream, tracerOpts: { enabled: !cliArgs.noTrace },
305
+ });
306
+ const sessionManager = new SessionManager(cfg.sessions.dir);
307
+ const workspace = resolveWorkspace();
337
308
  const resolved = await sessionManager.resolveSession({ workspace, strategy: sessionStrategy });
338
309
  const session = resolved.session;
339
310
  const sessionUuidShort = resolved.session.ref?.sessionUuid.slice(0, 8) ?? "";
@@ -344,7 +315,7 @@ async function runAgentCommand(cliArgs) {
344
315
  version: 2,
345
316
  runId: "",
346
317
  status: "error",
347
- exitCode: exit_codes_js_1.EXIT_CODES.CONFIG_ERROR,
318
+ exitCode: EXIT_CODES.CONFIG_ERROR,
348
319
  summary: "缺少 --message 参数",
349
320
  result: { payloads: [] },
350
321
  };
@@ -353,7 +324,7 @@ async function runAgentCommand(cliArgs) {
353
324
  else {
354
325
  logger.error("❌ 缺少 --message 参数。用法: wukong agent --message \"你的消息\"");
355
326
  }
356
- process.exit(exit_codes_js_1.EXIT_CODES.CONFIG_ERROR);
327
+ process.exit(EXIT_CODES.CONFIG_ERROR);
357
328
  }
358
329
  logger.info(`📡 LLM: ${resolvedModel}`);
359
330
  logger.info(`📂 会话: ${sessionUuidShort} @ ${workspace.root}` +
@@ -379,7 +350,7 @@ async function runAgentCommand(cliArgs) {
379
350
  let smartContextText;
380
351
  if (!cliArgs.noSmartContext && userMessage) {
381
352
  try {
382
- const sc = await (0, wukong_agent_sdk_1.collectSmartContext)(userMessage, process.cwd());
353
+ const sc = await collectSmartContext(userMessage, process.cwd());
383
354
  if (sc.contextText && sc.files.length > 0) {
384
355
  smartContextText = sc.contextText;
385
356
  logger.info(`📂 Smart Context: 注入 ${sc.files.length} 个相关文件摘要 (~${sc.estimatedTokens} token)`);
@@ -396,14 +367,14 @@ async function runAgentCommand(cliArgs) {
396
367
  ...result.newMessages,
397
368
  ]);
398
369
  const allMessages = contextBuilder.build(session, "");
399
- await (0, wukong_agent_sdk_1.compactIfNeeded)(session, allMessages, llm, cfg.sessions.compaction);
370
+ await compactIfNeeded(session, allMessages, llm, cfg.sessions.compaction);
400
371
  // ── 自动验证 ──
401
372
  let verification;
402
373
  const agentVerifyCfg = cfg.agent.verify;
403
374
  const shouldVerify = !cliArgs.noVerify && (cliArgs.verify || agentVerifyCfg?.enabled);
404
375
  if (shouldVerify && !result.aborted) {
405
376
  const verifyConfig = {
406
- ...wukong_agent_sdk_1.DEFAULT_VERIFY_CONFIG,
377
+ ...DEFAULT_VERIFY_CONFIG,
407
378
  ...(agentVerifyCfg ?? {}),
408
379
  enabled: true,
409
380
  // CLI 参数覆盖:验证超时
@@ -411,7 +382,7 @@ async function runAgentCommand(cliArgs) {
411
382
  // CI 模式下默认包含 build 命令
412
383
  includeBuild: isCiMode,
413
384
  };
414
- const verifier = new wukong_agent_sdk_1.AutoVerifier(verifyConfig, logger);
385
+ const verifier = new AutoVerifier(verifyConfig, logger);
415
386
  verification = await verifier.verifyAndFix(process.cwd(), async (fixPrompt) => {
416
387
  // 让 Agent 执行修复
417
388
  const fixMessages = contextBuilder.build(session, fixPrompt);
@@ -424,7 +395,7 @@ async function runAgentCommand(cliArgs) {
424
395
  }, cliArgs.verifyCommand ?? undefined);
425
396
  }
426
397
  // ── 计算退出码 ──
427
- const exitCode = (0, exit_codes_js_1.resolveExitCode)({
398
+ const exitCode = resolveExitCode({
428
399
  aborted: result.aborted,
429
400
  steps: result.steps,
430
401
  maxSteps: effectiveMaxSteps,
@@ -447,8 +418,8 @@ async function runAgentCommand(cliArgs) {
447
418
  const filesModified = extractModifiedFiles(result.trace);
448
419
  // 推断 status
449
420
  const status = result.aborted ? 'error'
450
- : exitCode === exit_codes_js_1.EXIT_CODES.TASK_INCOMPLETE ? 'incomplete'
451
- : exitCode === exit_codes_js_1.EXIT_CODES.VERIFY_FAILED ? 'verify_failed'
421
+ : exitCode === EXIT_CODES.TASK_INCOMPLETE ? 'incomplete'
422
+ : exitCode === EXIT_CODES.VERIFY_FAILED ? 'verify_failed'
452
423
  : 'success';
453
424
  const metrics = result.metrics;
454
425
  const durationMs = metrics?.durationMs ?? 0;
@@ -457,7 +428,7 @@ async function runAgentCommand(cliArgs) {
457
428
  runId: `run_${Date.now()}`,
458
429
  status,
459
430
  exitCode,
460
- summary: (0, summary_js_1.buildJsonSummary)(result.response, {
431
+ summary: buildJsonSummary(result.response, {
461
432
  steps: result.steps,
462
433
  totalTokens: result.totalTokens.prompt + result.totalTokens.completion,
463
434
  }),
@@ -565,7 +536,7 @@ async function runAgentCommand(cliArgs) {
565
536
  version: 2,
566
537
  runId: `run_${Date.now()}`,
567
538
  status: "error",
568
- exitCode: exit_codes_js_1.EXIT_CODES.LLM_ERROR,
539
+ exitCode: EXIT_CODES.LLM_ERROR,
569
540
  summary: error instanceof Error ? error.message : String(error),
570
541
  result: { payloads: [] },
571
542
  };
@@ -574,7 +545,7 @@ async function runAgentCommand(cliArgs) {
574
545
  else {
575
546
  logger.error("❌ Agent 执行出错:", error);
576
547
  }
577
- process.exit(exit_codes_js_1.EXIT_CODES.LLM_ERROR);
548
+ process.exit(EXIT_CODES.LLM_ERROR);
578
549
  }
579
550
  }
580
551
  /** 从 trace 中提取被修改的文件路径 */
@@ -702,13 +673,67 @@ async function persistWukongConfig(setup, logger) {
702
673
  logger.warn(`⚠️ 配置写入失败(本次运行仍可继续): ${String(err)}`);
703
674
  }
704
675
  }
676
+ /** 输入历史持久化文件路径(~/.wukong/history.jsonl,每行一条) */
677
+ function inputHistoryPath() {
678
+ return path.join(os.homedir(), '.wukong', 'history.jsonl');
679
+ }
680
+ /**
681
+ * 读取持久化的输入历史(跨 session 共享)。
682
+ *
683
+ * 文件格式:JSONL,每行一个 JSON 字符串(带引号),便于 append。
684
+ * 失败(文件不存在/解析错误)返回空数组,不阻塞启动。
685
+ */
686
+ async function loadInputHistory() {
687
+ const file = inputHistoryPath();
688
+ let content;
689
+ try {
690
+ content = await fs.readFile(file, 'utf8');
691
+ }
692
+ catch {
693
+ return [];
694
+ }
695
+ const entries = [];
696
+ for (const line of content.split('\n')) {
697
+ const trimmed = line.trim();
698
+ if (!trimmed)
699
+ continue;
700
+ try {
701
+ const parsed = JSON.parse(trimmed);
702
+ if (typeof parsed === 'string' && parsed.length > 0) {
703
+ entries.push(parsed);
704
+ }
705
+ }
706
+ catch {
707
+ // 损坏行跳过
708
+ }
709
+ }
710
+ // 最多返回最近 1000 条
711
+ return entries.slice(-1000);
712
+ }
713
+ /**
714
+ * 追加一条输入历史到持久化文件。
715
+ * 失败静默(历史持久化不是关键路径)。
716
+ */
717
+ async function appendInputHistory(entry) {
718
+ const trimmed = entry.trim();
719
+ if (!trimmed)
720
+ return;
721
+ const file = inputHistoryPath();
722
+ try {
723
+ await fs.mkdir(path.dirname(file), { recursive: true });
724
+ await fs.appendFile(file, JSON.stringify(trimmed) + '\n', { mode: 0o600 });
725
+ }
726
+ catch {
727
+ // 静默失败
728
+ }
729
+ }
705
730
  async function runInteractive(cliArgs) {
706
- const logger = new wukong_agent_sdk_1.Logger({ jsonMode: false });
707
- (0, wukong_agent_sdk_1.setGlobalLogger)(logger);
731
+ const logger = new Logger({ jsonMode: false });
732
+ setGlobalLogger(logger);
708
733
  logger.info("🐒 Wukong (悟空) v0.1.0");
709
734
  logger.info("========================");
710
735
  logger.info("");
711
- const cfg = await (0, wukong_agent_sdk_1.loadConfig)();
736
+ const cfg = await loadConfig();
712
737
  applyPermissionOverrides(cfg, cliArgs, logger);
713
738
  // ── 未配置模型时:TTY 下进入交互式向导,非 TTY 下打印手动配置指引 ──
714
739
  if (!hasConfiguredProvider(cfg)) {
@@ -719,12 +744,12 @@ async function runInteractive(cliArgs) {
719
744
  logger.error(" export LLM_BASE_URL=https://api.deepseek.com/v1 # OpenAI 兼容端点");
720
745
  logger.error(" export LLM_MODEL=deepseek-chat");
721
746
  logger.error(" 或编辑 ~/.wukong/wukong.json(详见 README 的「配置」章节)。");
722
- process.exit(exit_codes_js_1.EXIT_CODES.CONFIG_ERROR);
747
+ process.exit(EXIT_CODES.CONFIG_ERROR);
723
748
  }
724
749
  const setup = await runSetupWizard(logger);
725
750
  if (!setup) {
726
751
  logger.error("❌ 配置未完成,无法启动。可参考 README 手动配置后重试。");
727
- process.exit(exit_codes_js_1.EXIT_CODES.CONFIG_ERROR);
752
+ process.exit(EXIT_CODES.CONFIG_ERROR);
728
753
  }
729
754
  await persistWukongConfig(setup, logger);
730
755
  // 直接注入内存配置,无需重新加载(避免本地 wukong.json 遮蔽全局配置的边界情况)
@@ -735,7 +760,90 @@ async function runInteractive(cliArgs) {
735
760
  }
736
761
  const resolvedConfirmMode = cliArgs.yes ? 'never' : (cliArgs.confirmMode ?? cfg.tools.confirmMode ?? 'smart');
737
762
  const resolvedThinking = resolveThinking(cliArgs, cfg);
738
- // ── 流式输出回调(交互模式) ──
763
+ const sessionManager = new SessionManager(cfg.sessions.dir);
764
+ const workspace = resolveWorkspace();
765
+ // 交互模式不视为 CI(即使被 pipe,交互模式一定不会被 --yes/--json 触发)
766
+ const interactiveStrategy = resolveCliSessionStrategy(cliArgs, /* isCiMode */ false, logger);
767
+ if (interactiveStrategy === null) {
768
+ process.exit(EXIT_CODES.CONFIG_ERROR);
769
+ }
770
+ const resolvedInteractive = await sessionManager.resolveSession({
771
+ workspace,
772
+ strategy: interactiveStrategy,
773
+ });
774
+ const session = resolvedInteractive.session;
775
+ const sessionUuidShort = resolvedInteractive.session.ref?.sessionUuid.slice(0, 8) ?? "";
776
+ // ── 判定是否启用 TUI(§3.1 M1 降级矩阵) ──
777
+ const useTui = shouldUseTuiFromProcess();
778
+ if (!useTui) {
779
+ // 降级到 readline(readline 路径装 process SIGINT handler)
780
+ return runInteractiveReadline(cliArgs, cfg, logger, resolvedConfirmMode, resolvedThinking, session, workspace, sessionUuidShort, resolvedInteractive.created);
781
+ }
782
+ // ── TUI 路径(Ink raw mode 拦截 Ctrl+C,不装 process handler,由 TextInput onAbort 触发) ──
783
+ return runInteractiveTui(cliArgs, cfg, logger, resolvedConfirmMode, resolvedThinking, session, workspace, sessionUuidShort);
784
+ }
785
+ /**
786
+ * readline 降级路径(原 runInteractive 的实现,保持完全不变)。
787
+ *
788
+ * 触发条件(见 shouldUseTui):
789
+ * - WUKONG_TUI=off
790
+ * - CI=true
791
+ * - stdin/stdout 非 TTY
792
+ * - TERM=dumb
793
+ */
794
+ async function runInteractiveReadline(cliArgs, cfg, logger, resolvedConfirmMode, resolvedThinking, session, workspace, sessionUuidShort, sessionCreated) {
795
+ // §3.3 M3:graceful shutdown(readline 路径装 process SIGINT handler)
796
+ const abortController = createAbortController({
797
+ onFirstAbort: () => {
798
+ process.stderr.write('\n\n⚠️ 收到中断信号,正在优雅退出(等当前步骤完成)...\n');
799
+ process.stderr.write(' 再按一次 Ctrl+C 立即退出(session 可能不完整)\n');
800
+ },
801
+ onSecondAbort: () => {
802
+ process.stderr.write('\n\n⏏️ 立即退出\n');
803
+ },
804
+ installProcessHandler: true,
805
+ });
806
+ const shouldAbort = abortController.shouldAbort;
807
+ // §3.6 M1:工具授权器(readline 路径用简单 question UI)
808
+ const authorizer = new ToolAuthorizer({
809
+ workspaceRoot: workspace.root,
810
+ ciMode: false,
811
+ uiCallback: async (req) => {
812
+ return new Promise((resolve) => {
813
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
814
+ process.stderr.write(`\n🔒 授权请求: ${req.toolName} (step ${req.step})\n`);
815
+ process.stderr.write(` 参数: ${req.argumentsJson.slice(0, 200)}\n`);
816
+ rl.question('[y]仅本次 [s]session [l]本项目 [g]全局 [n]拒绝 [x]永久拒绝: ', (ans) => {
817
+ rl.close();
818
+ const c = ans.trim().toLowerCase();
819
+ switch (c) {
820
+ case 's':
821
+ resolve({ approved: true, decision: 'session' });
822
+ break;
823
+ case 'l':
824
+ resolve({ approved: true, decision: 'always-local' });
825
+ break;
826
+ case 'g':
827
+ resolve({ approved: true, decision: 'always-global' });
828
+ break;
829
+ case 'n':
830
+ resolve({ approved: false, decision: 'no' });
831
+ break;
832
+ case 'x':
833
+ resolve({ approved: false, decision: 'no-always' });
834
+ break;
835
+ default:
836
+ resolve({ approved: true, decision: 'once' });
837
+ break;
838
+ }
839
+ });
840
+ });
841
+ },
842
+ });
843
+ const authorizeTool = async (req) => {
844
+ return authorizer.requestAuthorization(req);
845
+ };
846
+ // ── 流式输出回调(交互模式 readline 降级) ──
739
847
  let interactiveStreamStarted = false;
740
848
  const onStream = (event) => {
741
849
  switch (event.type) {
@@ -760,36 +868,24 @@ async function runInteractive(cliArgs) {
760
868
  break;
761
869
  }
762
870
  };
763
- const { llm, tools, contextBuilder, agent, resolvedModel } = await initAgent(cfg, logger, resolvedConfirmMode, resolvedThinking, false, cliArgs.planMode, {
764
- maxSteps: cliArgs.maxSteps,
765
- contextWindow: cliArgs.contextWindow,
766
- }, onStream, { enabled: !cliArgs.noTrace });
871
+ const { llm, tools, contextBuilder, agent, resolvedModel } = await initAgent({
872
+ cfg, logger, confirmMode: resolvedConfirmMode, thinking: resolvedThinking, planMode: cliArgs.planMode,
873
+ overrides: { maxSteps: cliArgs.maxSteps, contextWindow: cliArgs.contextWindow },
874
+ onStream, tracerOpts: { enabled: !cliArgs.noTrace },
875
+ shouldAbort, authorizeTool,
876
+ });
767
877
  logger.info(`📡 LLM: ${resolvedModel}`);
768
878
  logger.info(`🔧 已注册 ${tools.size} 个工具: ${tools.listNames().join(", ")}`);
769
- const sessionManager = new wukong_agent_sdk_1.SessionManager(cfg.sessions.dir);
770
- const workspace = (0, wukong_agent_sdk_1.resolveWorkspace)();
771
- // 交互模式不视为 CI(即使被 pipe,交互模式一定不会被 --yes/--json 触发)
772
- const interactiveStrategy = resolveCliSessionStrategy(cliArgs, /* isCiMode */ false, logger);
773
- if (interactiveStrategy === null) {
774
- process.exit(exit_codes_js_1.EXIT_CODES.CONFIG_ERROR);
775
- }
776
- const resolvedInteractive = await sessionManager.resolveSession({
777
- workspace,
778
- strategy: interactiveStrategy,
779
- });
780
- const session = resolvedInteractive.session;
781
- const sessionUuidShort = resolvedInteractive.session.ref?.sessionUuid.slice(0, 8) ?? "";
782
879
  logger.info(`📂 会话存储: ${cfg.sessions.dir}`);
783
880
  logger.info(`📂 会话: ${sessionUuidShort} @ ${workspace.root}` +
784
- ` (${session.recordCount} 条记录${resolvedInteractive.created ? ", 新建" : ""})`);
881
+ ` (${session.recordCount} 条记录${sessionCreated ? ", 新建" : ""})`);
785
882
  logger.info(`📜 历史记录: ${session.recordCount} 条`);
786
883
  logger.info("");
787
884
  async function sendMessage(input) {
788
- // ── Smart Context 收集(交互模式首条消息) ──
789
885
  let smartContextText;
790
886
  if (!cliArgs.noSmartContext && session.recordCount === 0) {
791
887
  try {
792
- const sc = await (0, wukong_agent_sdk_1.collectSmartContext)(input, process.cwd());
888
+ const sc = await collectSmartContext(input, process.cwd());
793
889
  if (sc.contextText && sc.files.length > 0) {
794
890
  smartContextText = sc.contextText;
795
891
  logger.info(`📂 Smart Context: 注入 ${sc.files.length} 个相关文件摘要 (~${sc.estimatedTokens} token)`);
@@ -800,9 +896,8 @@ async function runInteractive(cliArgs) {
800
896
  }
801
897
  }
802
898
  const messages = contextBuilder.build(session, input, undefined, smartContextText);
803
- interactiveStreamStarted = false; // 重置流式状态
899
+ interactiveStreamStarted = false;
804
900
  const result = await agent.runWithMessages(messages);
805
- // 如果已经流式输出了,不需要再重复打印
806
901
  if (!interactiveStreamStarted) {
807
902
  logger.info(`\nWukong: ${result.response}`);
808
903
  }
@@ -812,8 +907,7 @@ async function runInteractive(cliArgs) {
812
907
  ...result.newMessages,
813
908
  ]);
814
909
  const allMessages = contextBuilder.build(session, "");
815
- await (0, wukong_agent_sdk_1.compactIfNeeded)(session, allMessages, llm, cfg.sessions.compaction);
816
- return result;
910
+ await compactIfNeeded(session, allMessages, llm, cfg.sessions.compaction);
817
911
  }
818
912
  if (cliArgs.test) {
819
913
  logger.info("🧪 测试模式:发送一条测试消息...");
@@ -844,6 +938,7 @@ async function runInteractive(cliArgs) {
844
938
  if (trimmed.toLowerCase() === "exit") {
845
939
  logger.info("👋 再见!");
846
940
  rl.close();
941
+ abortController.uninstall();
847
942
  return;
848
943
  }
849
944
  if (trimmed.toLowerCase() === "clear") {
@@ -863,6 +958,128 @@ async function runInteractive(cliArgs) {
863
958
  };
864
959
  ask();
865
960
  }
961
+ /**
962
+ * TUI 路径(Ink 渲染)。
963
+ *
964
+ * 与 readline 路径的差异:
965
+ * - onStream 通过 streamSinkRef 桥接给 App,由 App 渲染流式文本(不走 stdout)
966
+ * - sendMessage 返回 CompletedRun,供 App 展示统计信息
967
+ * - 输入用 Ink TextInput(多行 + 历史 + Ctrl+R)
968
+ *
969
+ * M1 简化:model 用 cfg.agent.defaultModel 作为初始显示值(initAgent 内部的
970
+ * resolvedModel 通常与之一致;即便不一致也不影响功能,只影响 Header 显示)。
971
+ * M2 引入 step counter 时会顺便修这个 —— 届时通过 EventBus 的 run_start 事件
972
+ * 携带真实 model,App 订阅后更新即可。
973
+ */
974
+ async function runInteractiveTui(cliArgs, cfg, logger, resolvedConfirmMode, resolvedThinking, session, workspace, sessionUuidShort) {
975
+ // §3.3 M3:graceful shutdown(TUI 路径不装 process handler,Ink raw mode 拦截 Ctrl+C)
976
+ // TextInput 的 onAbort → requestAbort,实现两次 Ctrl+C 语义
977
+ const abortController = createAbortController({
978
+ onFirstAbort: () => {
979
+ // 提示通过 App 状态显示(不直接写 stderr,避免打乱 Ink 渲染)
980
+ },
981
+ onSecondAbort: () => {
982
+ // 二次直接退出,Ink unmount 由 process.exit 触发
983
+ },
984
+ installProcessHandler: false,
985
+ });
986
+ const shouldAbort = abortController.shouldAbort;
987
+ // §3.6 M1:工具授权器(交互模式;CI 模式 runAgentCommand 不创建)
988
+ const authorizer = new ToolAuthorizer({
989
+ workspaceRoot: workspace.root,
990
+ ciMode: false,
991
+ });
992
+ const authorizeTool = async (req) => {
993
+ return authorizer.requestAuthorization(req);
994
+ };
995
+ // 读取持久化输入历史(可选,失败不阻塞)
996
+ const initialHistory = await loadInputHistory().catch(() => []);
997
+ // agent 引用:sendMessage 通过它跑 agent;init 完成前为 null
998
+ const agentRef = {
999
+ llm: null,
1000
+ contextBuilder: null,
1001
+ agent: null,
1002
+ };
1003
+ const handlers = {
1004
+ eventBus: getDefaultEventBus(),
1005
+ clearSession: async () => {
1006
+ await session.clear();
1007
+ },
1008
+ // 与 initAgent 内部逻辑一致(effectiveMaxSteps = overrides?.maxSteps ?? cfg.agent.maxSteps)
1009
+ maxSteps: cliArgs.maxSteps ?? cfg.agent.maxSteps,
1010
+ // §3.3 M3:Ctrl+C 两次语义(TextInput onAbort → requestAbort)
1011
+ requestAbort: abortController.requestAbort,
1012
+ isAbortRequested: abortController.isFirstAbortReceived,
1013
+ // §3.6 M1:工具授权器(App 把 uiCallback 桥接到 PermissionCard)
1014
+ authorizer,
1015
+ sendMessage: async (input) => {
1016
+ if (!agentRef.agent || !agentRef.contextBuilder || !agentRef.llm) {
1017
+ throw new Error('Agent 未初始化');
1018
+ }
1019
+ // 持久化输入历史(异步,不阻塞)
1020
+ void appendInputHistory(input);
1021
+ let smartContextText;
1022
+ if (!cliArgs.noSmartContext && session.recordCount === 0) {
1023
+ try {
1024
+ const sc = await collectSmartContext(input, process.cwd());
1025
+ if (sc.contextText && sc.files.length > 0) {
1026
+ smartContextText = sc.contextText;
1027
+ }
1028
+ }
1029
+ catch {
1030
+ // Smart Context 失败不影响主流程
1031
+ }
1032
+ }
1033
+ const messages = agentRef.contextBuilder.build(session, input, undefined, smartContextText);
1034
+ const result = await agentRef.agent.runWithMessages(messages);
1035
+ await session.appendMessages([
1036
+ { role: "user", content: input },
1037
+ ...result.newMessages,
1038
+ ]);
1039
+ const allMessages = agentRef.contextBuilder.build(session, "");
1040
+ await compactIfNeeded(session, allMessages, agentRef.llm, cfg.sessions.compaction);
1041
+ const durationMs = result.metrics?.durationMs ?? 0;
1042
+ return {
1043
+ response: result.response,
1044
+ steps: result.steps,
1045
+ totalTokens: result.totalTokens,
1046
+ durationMs,
1047
+ };
1048
+ },
1049
+ };
1050
+ // 启动 Ink(App 会立即渲染,但 agent 还没 init;用户输入会被 sendMessage 拦截)
1051
+ const inkHandle = runInk({
1052
+ model: cfg.agent.defaultModel ?? 'unknown',
1053
+ sessionUuidShort,
1054
+ workspaceRoot: workspace.root,
1055
+ handlers,
1056
+ initialHistory,
1057
+ });
1058
+ // init agent,把 Ink 的 onStream 传进去
1059
+ const { llm, contextBuilder, agent } = await initAgent({
1060
+ cfg, logger, confirmMode: resolvedConfirmMode, thinking: resolvedThinking, planMode: cliArgs.planMode,
1061
+ overrides: { maxSteps: cliArgs.maxSteps, contextWindow: cliArgs.contextWindow },
1062
+ onStream: inkHandle.onStream, tracerOpts: { enabled: !cliArgs.noTrace },
1063
+ shouldAbort, authorizeTool,
1064
+ });
1065
+ agentRef.llm = llm;
1066
+ agentRef.contextBuilder = contextBuilder;
1067
+ agentRef.agent = agent;
1068
+ // test 模式:发一条消息验证后退出
1069
+ if (cliArgs.test) {
1070
+ try {
1071
+ await handlers.sendMessage('请列出当前目录下有哪些文件和文件夹。');
1072
+ process.stderr.write("\n✅ 测试通过,AI 对话正常!\n");
1073
+ inkHandle.unmount();
1074
+ process.exit(0);
1075
+ }
1076
+ catch (error) {
1077
+ process.stderr.write(`\n❌ 测试失败: ${String(error)}\n`);
1078
+ inkHandle.unmount();
1079
+ process.exit(1);
1080
+ }
1081
+ }
1082
+ }
866
1083
  /**
867
1084
  * 把 CLI 参数(--session-id / --continue / --new)与运行模式(CI/交互)综合起来,
868
1085
  * 得到 SessionManager.resolveSession() 需要的 strategy 对象。
@@ -934,13 +1151,19 @@ function resolveThinking(cliArgs, cfg) {
934
1151
  }
935
1152
  async function main() {
936
1153
  const cliArgs = parseArgs(process.argv);
1154
+ // 把 --yes / --json 反射到 env,让 SDK 层的 config loader 也能识别
1155
+ // CI 模式(§1.3)。参见 core 里 isCiMode()。
1156
+ if (cliArgs.yes)
1157
+ process.env.WUKONG_YES = "1";
1158
+ if (cliArgs.json)
1159
+ process.env.WUKONG_JSON = "1";
937
1160
  // 优先处理 --help 和 --version
938
1161
  if (cliArgs.help) {
939
- process.stdout.write(help_js_1.HELP_TEXT + '\n');
1162
+ process.stdout.write(HELP_TEXT + '\n');
940
1163
  process.exit(0);
941
1164
  }
942
1165
  if (cliArgs.version) {
943
- process.stdout.write((0, help_js_1.formatVersion)() + '\n');
1166
+ process.stdout.write(formatVersion() + '\n');
944
1167
  process.exit(0);
945
1168
  }
946
1169
  switch (cliArgs.command) {
@@ -959,20 +1182,20 @@ async function main() {
959
1182
  }
960
1183
  }
961
1184
  async function runSessionSubcommand(cliArgs) {
962
- const logger = new wukong_agent_sdk_1.Logger({ jsonMode: false });
963
- (0, wukong_agent_sdk_1.setGlobalLogger)(logger);
964
- const cfg = await (0, wukong_agent_sdk_1.loadConfig)();
965
- const manager = new wukong_agent_sdk_1.SessionManager(cfg.sessions.dir);
966
- const workspace = (0, wukong_agent_sdk_1.resolveWorkspace)();
967
- const code = await (0, session_commands_js_1.runSessionCommand)({ manager, workspace, args: cliArgs.positional });
1185
+ const logger = new Logger({ jsonMode: false });
1186
+ setGlobalLogger(logger);
1187
+ const cfg = await loadConfig();
1188
+ const manager = new SessionManager(cfg.sessions.dir);
1189
+ const workspace = resolveWorkspace();
1190
+ const code = await runSessionCommand({ manager, workspace, args: cliArgs.positional });
968
1191
  process.exit(code);
969
1192
  }
970
1193
  async function runWorkspaceSubcommand(cliArgs) {
971
- const logger = new wukong_agent_sdk_1.Logger({ jsonMode: false });
972
- (0, wukong_agent_sdk_1.setGlobalLogger)(logger);
973
- const cfg = await (0, wukong_agent_sdk_1.loadConfig)();
974
- const manager = new wukong_agent_sdk_1.SessionManager(cfg.sessions.dir);
975
- const code = await (0, workspace_commands_js_1.runWorkspaceCommand)({ manager, args: cliArgs.positional });
1194
+ const logger = new Logger({ jsonMode: false });
1195
+ setGlobalLogger(logger);
1196
+ const cfg = await loadConfig();
1197
+ const manager = new SessionManager(cfg.sessions.dir);
1198
+ const code = await runWorkspaceCommand({ manager, args: cliArgs.positional });
976
1199
  process.exit(code);
977
1200
  }
978
1201
  main().catch((err) => {