minimal-agent 0.18.21 → 0.18.22

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 (127) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/workflow-runner/plugin.js +1 -0
  4. package/plugins/workflow-runner/plugin.ts +1 -0
  5. package/plugins/workflow-runner/src/index.js +1 -0
  6. package/plugins/workflow-runner/src/index.ts +2 -0
  7. package/plugins/workflow-runner/src/runner.js +6 -1
  8. package/plugins/workflow-runner/src/runner.ts +5 -1
  9. package/plugins/workflow-runner/src/types.ts +1 -0
  10. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  11. package/src/advisor/README.md +7 -3
  12. package/src/advisor/advisorNudge.js +3 -3
  13. package/src/advisor/advisorNudge.ts +3 -3
  14. package/src/advisor/deliveryReview.js +9 -2
  15. package/src/advisor/deliveryReview.ts +10 -2
  16. package/src/cli/args.js +1 -0
  17. package/src/cli/args.ts +1 -0
  18. package/src/cli/headlessTurn.js +143 -0
  19. package/src/cli/headlessTurn.ts +187 -0
  20. package/src/cli/lifecycle.js +52 -0
  21. package/src/cli/lifecycle.ts +59 -0
  22. package/src/cli/print.js +91 -240
  23. package/src/cli/print.ts +99 -301
  24. package/src/cli/quickModelSetup.js +3 -0
  25. package/src/cli/quickModelSetup.tsx +3 -0
  26. package/src/cli/streamJson.js +244 -334
  27. package/src/cli/streamJson.ts +248 -416
  28. package/src/cli/wizards/providerPresets.js +25 -14
  29. package/src/cli/wizards/providerPresets.ts +25 -14
  30. package/src/cli/wizards/providerWizard.js +29 -11
  31. package/src/cli/wizards/providerWizard.tsx +29 -11
  32. package/src/config/configDiagnostics.js +7 -3
  33. package/src/config/configDiagnostics.ts +6 -3
  34. package/src/context/compact.js +40 -10
  35. package/src/context/compact.ts +51 -12
  36. package/src/context/compactResources.js +39 -0
  37. package/src/context/compactResources.ts +35 -0
  38. package/src/context/manualCompact.js +20 -0
  39. package/src/context/manualCompact.ts +28 -0
  40. package/src/llm/client.js +4 -0
  41. package/src/llm/client.ts +4 -0
  42. package/src/llm/messageProvenance.js +1 -1
  43. package/src/llm/messageProvenance.ts +1 -1
  44. package/src/loop/deliveryIntent.js +3 -2
  45. package/src/loop/deliveryIntent.ts +4 -2
  46. package/src/loop/messages.js +1 -0
  47. package/src/loop/messages.ts +1 -0
  48. package/src/loop/options.ts +2 -0
  49. package/src/loop.js +4 -2
  50. package/src/loop.ts +4 -2
  51. package/src/main.js +40 -45
  52. package/src/main.tsx +33 -52
  53. package/src/plugins/artifactDelivery.js +76 -0
  54. package/src/plugins/artifactDelivery.ts +76 -0
  55. package/src/plugins/pluginApi.ts +2 -0
  56. package/src/plugins/pluginRunner.js +2 -0
  57. package/src/plugins/pluginRunner.ts +3 -0
  58. package/src/prompts/delegation.js +1 -1
  59. package/src/prompts/delegation.ts +1 -1
  60. package/src/prompts/policyRegistry.js +7 -6
  61. package/src/prompts/policyRegistry.ts +7 -6
  62. package/src/prompts/promptAssembly.js +2 -2
  63. package/src/prompts/promptAssembly.ts +2 -2
  64. package/src/runtime/requestIntent.js +86 -0
  65. package/src/runtime/requestIntent.ts +66 -0
  66. package/src/runtime/systemEvents.js +10 -1
  67. package/src/runtime/systemEvents.ts +9 -1
  68. package/src/session/commandTranscript.js +76 -0
  69. package/src/session/commandTranscript.ts +77 -0
  70. package/src/session/runTurn.js +24 -3
  71. package/src/session/runTurn.ts +24 -3
  72. package/src/tools/advisor/advisor.js +1 -1
  73. package/src/tools/advisor/advisor.ts +1 -1
  74. package/src/tools/advisor/advisorCoordination.js +3 -2
  75. package/src/tools/advisor/advisorCoordination.ts +3 -2
  76. package/src/tools/advisor/advisorDescription.js +1 -1
  77. package/src/tools/advisor/advisorDescription.ts +1 -1
  78. package/src/tools/agent/README.md +2 -0
  79. package/src/tools/agent/agent.js +3 -0
  80. package/src/tools/agent/agent.ts +3 -0
  81. package/src/tools/agent/agentHandoff.js +2 -1
  82. package/src/tools/agent/agentHandoff.ts +2 -1
  83. package/src/tools/agent/agentTaskService.js +26 -5
  84. package/src/tools/agent/agentTaskService.ts +23 -5
  85. package/src/tools/agent/agentTypes.js +1 -1
  86. package/src/tools/agent/agentTypes.ts +1 -1
  87. package/src/tools/applypatch/applyPatch.js +39 -13
  88. package/src/tools/applypatch/applyPatch.ts +35 -15
  89. package/src/tools/bash/bash.js +3 -0
  90. package/src/tools/bash/bash.ts +3 -0
  91. package/src/tools/download/download.js +147 -11
  92. package/src/tools/download/download.ts +193 -17
  93. package/src/tools/edit/edit.js +4 -4
  94. package/src/tools/edit/edit.ts +4 -4
  95. package/src/tools/edit/multi-edit.js +2 -2
  96. package/src/tools/edit/multi-edit.ts +2 -2
  97. package/src/tools/powershell/powershell.js +2 -0
  98. package/src/tools/powershell/powershell.ts +2 -0
  99. package/src/tools/shared/fileUtils.js +16 -6
  100. package/src/tools/shared/fileUtils.ts +15 -6
  101. package/src/tools/tasks/backgroundTaskService.js +108 -12
  102. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  103. package/src/tools/tasks/taskOutput.js +15 -5
  104. package/src/tools/tasks/taskOutput.ts +13 -5
  105. package/src/tools/tasks/taskStop.js +2 -2
  106. package/src/tools/tasks/taskStop.ts +2 -2
  107. package/src/tools/toolPromptGuides.js +3 -3
  108. package/src/tools/toolPromptGuides.ts +3 -3
  109. package/src/tools/webfetch/webfetch.js +1 -1
  110. package/src/tools/webfetch/webfetch.ts +1 -1
  111. package/src/types.ts +4 -0
  112. package/src/ui/InputBox.js +2 -2
  113. package/src/ui/InputBox.tsx +2 -2
  114. package/src/ui/MessageList.js +2 -0
  115. package/src/ui/MessageList.tsx +2 -0
  116. package/src/ui/README.md +8 -2
  117. package/src/ui/activityPresentation.js +22 -2
  118. package/src/ui/activityPresentation.ts +21 -2
  119. package/src/ui/backgroundWake.js +20 -4
  120. package/src/ui/backgroundWake.ts +19 -4
  121. package/src/ui/commandTranscript.js +2 -69
  122. package/src/ui/commandTranscript.ts +2 -71
  123. package/src/ui/hooks/useChat.js +41 -25
  124. package/src/ui/hooks/useChat.ts +30 -23
  125. package/src/web/protocol.ts +3 -2
  126. package/src/cli/wizards/advisorWizard.js +0 -152
  127. package/src/cli/wizards/advisorWizard.tsx +0 -203
@@ -1,4 +1,6 @@
1
1
  import { preserveAdvisorHistory } from './advisorHistory.js';
2
+ import { isSystemEventMessage } from '../runtime/systemEvents.js';
3
+ import { compactSkillReferences } from './compactResources.js';
2
4
 
3
5
  /**
4
6
  * ============================================================
@@ -113,7 +115,7 @@ function userText(content: Message['content']): string {
113
115
  */
114
116
  export function buildUserMessageLedger(messages: Message[]): string {
115
117
  const texts = messages
116
- .filter((message) => message.role === 'user')
118
+ .filter((message) => message.role === 'user' && !isSystemEventMessage(message))
117
119
  .map((message) => userText(message.content))
118
120
  .filter((text) =>
119
121
  text.length > 0
@@ -436,10 +438,42 @@ export interface ForceCompactResult extends CompactionMetadata {
436
438
  messages: Message[];
437
439
  before: number;
438
440
  after: number;
441
+ /** Explicit manual no-op: no model call or no reduction; nothing to persist. */
442
+ unchangedReason?: 'too-short' | 'no-benefit';
443
+ }
444
+
445
+ export interface CompactOptions { strict?: boolean; customInstructions?: string }
446
+
447
+ /** User-requested cleanup is not an emergency. Never truncate on failure or
448
+ * replace history with a larger result. Hosts persist before publishing it. */
449
+ export async function manualCompact(
450
+ messages: Message[], provider: Provider, signal?: AbortSignal,
451
+ chatFn: typeof chat = chat, promptCache?: PromptCacheContext,
452
+ options?: Pick<CompactOptions, 'customInstructions'>,
453
+ ): Promise<ForceCompactResult> {
454
+ signal?.throwIfAborted();
455
+ if (options?.customInstructions !== undefined && (typeof options.customInstructions !== 'string' || options.customInstructions.length > 8000))
456
+ throw new Error('压缩要求必须为不超过 8,000 字符的文本');
457
+ const before = countMessagesTokens(messages);
458
+ const unchanged = (unchangedReason: ForceCompactResult['unchangedReason']): ForceCompactResult => ({
459
+ messages, before, after: before, mode: 'llm-summary', degraded: false,
460
+ messagesRemoved: 0, tokensFreed: 0, unchangedReason,
461
+ });
462
+ const content = messages.filter(message => message.role !== 'system');
463
+ if (findTailWithCompleteToolChains(content).length >= content.length) return unchanged('too-short');
464
+ const result = await forceCompact(messages, provider, signal, chatFn, promptCache, { ...options, strict: true });
465
+ signal?.throwIfAborted();
466
+ return result.after < before ? result : unchanged('no-benefit');
467
+ }
468
+
469
+ export function manualCompactNotice(result: ForceCompactResult): string {
470
+ return result.unchangedReason === 'too-short' ? '可压缩历史较少,已保留原上下文,未请求模型。'
471
+ : result.unchangedReason === 'no-benefit' ? '摘要未减少上下文占用,已保留原上下文。'
472
+ : `压缩完成:${result.before} → ${result.after} tokens(估算)。`;
439
473
  }
440
474
 
441
475
  /**
442
- * 不看阈值,直接执行一次压缩。供 `/compact` 手动命令使用。
476
+ * 不看阈值,直接执行一次压缩。应急路径允许截断降级;手动入口使用 manualCompact。
443
477
  *
444
478
  * 与 autoCompactIfNeeded 共用同一段 runCompaction 逻辑;区别仅在于此函数
445
479
  * 永远跑压缩、不返回 `compacted` 字段(由调用方决定如何反馈)。
@@ -451,7 +485,7 @@ export async function forceCompact(
451
485
  /** Inherit the host execution service; default only for standalone callers. */
452
486
  chatFn: typeof chat = chat,
453
487
  promptCache?: PromptCacheContext,
454
- options?: { strict?: boolean },
488
+ options?: CompactOptions,
455
489
  ): Promise<ForceCompactResult> {
456
490
  const before = countMessagesTokens(messages);
457
491
  const compacted = await runCompaction(messages, provider, signal, chatFn, promptCache, options);
@@ -475,21 +509,21 @@ async function runCompaction(
475
509
  signal?: AbortSignal,
476
510
  chatFn: typeof chat = chat,
477
511
  promptCache?: PromptCacheContext,
478
- options?: { strict?: boolean },
512
+ options?: CompactOptions,
479
513
  ): Promise<{ messages: Message[] } & CompactionMetadata> {
480
514
  // 1. 找出原 system(保留它,避免 agent 失忆)
481
- const systemMsg = messages.find((m) => m.role === 'system');
515
+ const systemMessages = messages.filter((m) => m.role === 'system' && !m._uiProgress);
482
516
  const nonSystem = messages.filter((m) => m.role !== 'system');
483
517
 
484
518
  // 2. 构造给"压缩用"的请求:完整历史 + 七段式续接摘要 prompt
485
519
  // (即使最后 N 条会被原样保留在新历史里,也送给 LLM 看 —— 让它写得出
486
520
  // 高质量的 "Context for Continuing Work" 节,知道当前停在哪儿。)
487
521
  const compactRequest: Message[] = [
488
- ...(systemMsg ? [systemMsg] : []),
522
+ ...systemMessages,
489
523
  ...nonSystem,
490
524
  {
491
525
  role: 'user',
492
- content: buildCompactPrompt(),
526
+ content: buildCompactPrompt(options?.customInstructions),
493
527
  },
494
528
  ];
495
529
 
@@ -524,9 +558,10 @@ async function runCompaction(
524
558
  nonSystem.slice(0, nonSystem.length - failureTail.length),
525
559
  );
526
560
  const compactedMessages: Message[] = [
527
- ...(systemMsg ? [systemMsg] : []),
561
+ ...systemMessages,
528
562
  {
529
563
  role: 'user',
564
+ inputOrigin: 'compact-fallback',
530
565
  // ⚠️ 这里**故意不带** provider 原始报错:本条消息会进 history,既落盘也会在
531
566
  // 后续轮次重新发给模型,错误体里可能夹带 URL / 请求体 / 凭据。
532
567
  // 排障线索走 `compact_failed` 事件(只到 stderr / UI,不进 history)。
@@ -554,7 +589,9 @@ async function runCompaction(
554
589
  }
555
590
 
556
591
  const formattedSummary = formatCompactSummary(summary);
557
- if (options?.strict && !validateCompactSummary(formattedSummary).valid) {
592
+ const summaryBody = formattedSummary.replace(/^##\s+(?:Goal|Constraints|Verified evidence|Changes|Verification|Pending|Next action)[ \t]*(?:—|-)?[ \t]*/gmi, '').trim();
593
+ if (options?.strict && (!validateCompactSummary(formattedSummary).valid
594
+ || !summaryBody || /^(?:\s|Unknown[.!]?|未知[。]?)*$/i.test(summaryBody))) {
558
595
  throw new Error('COMPACTION_INVALID_SUMMARY');
559
596
  }
560
597
  if (!formattedSummary.trim()) {
@@ -565,9 +602,10 @@ async function runCompaction(
565
602
  nonSystem.slice(0, messagesRemoved),
566
603
  );
567
604
  const compactedMessages: Message[] = [
568
- ...(systemMsg ? [systemMsg] : []),
605
+ ...systemMessages,
569
606
  {
570
607
  role: 'user',
608
+ inputOrigin: 'compact-fallback',
571
609
  content: '(LLM 返回了无效摘要,已使用规则式截断继续会话)'
572
610
  + (failureLedger
573
611
  ? `\n\n<user_messages>\n以下是被截掉的那部分对话里**用户的原话**(程序逐字抽取)。摘要不存在,这里就是唯一残留的历史要求。\n${failureLedger}\n</user_messages>`
@@ -597,16 +635,17 @@ async function runCompaction(
597
635
  // 台账只覆盖**被丢弃的那一段**——recentTail 已经逐字保留,再抽一遍是重复烧 token。
598
636
  const messagesRemoved = nonSystem.length - recentTail.length;
599
637
  const compactedMessages: Message[] = [
600
- ...(systemMsg ? [systemMsg] : []),
638
+ ...systemMessages,
601
639
  {
602
640
  role: 'user',
641
+ inputOrigin: 'compact-summary',
603
642
  content: buildContinuationUserMessage({
604
643
  summary: cleanSummary,
605
644
  recentMessagesPreserved: recentTail.length > 0,
606
645
  userMessageLedger: buildUserMessageLedger(
607
646
  nonSystem.slice(0, messagesRemoved),
608
647
  ),
609
- }),
648
+ }) + compactSkillReferences(nonSystem),
610
649
  },
611
650
  ...recentTail,
612
651
  ];
@@ -0,0 +1,39 @@
1
+ import { isSystemEventMessage } from '../runtime/systemEvents.js';
2
+ import { expandAdvisorHistory } from './advisorHistory.js';
3
+ /** Reload hints, not a second copy of skill instructions. Only successful skill
4
+ * loads in the latest human turn qualify; never revive skills from older tasks. */
5
+ export function compactSkillReferences(messages) {
6
+ // Reuse the existing cold evidence archive across repeated compactions.
7
+ // Never parse model-written summaries to invent successful skill loads.
8
+ const evidence = expandAdvisorHistory(messages);
9
+ let start = evidence.length - 1;
10
+ while (start >= 0 && (evidence[start].role !== 'user' || isSystemEventMessage(evidence[start])))
11
+ start--;
12
+ if (start < 0)
13
+ return '';
14
+ const calls = new Map();
15
+ const successful = new Map();
16
+ for (const message of evidence.slice(start)) {
17
+ if (message.role === 'assistant')
18
+ for (const call of message.tool_calls ?? []) {
19
+ if (call.function.name !== 'Skill')
20
+ continue;
21
+ try {
22
+ const args = JSON.parse(call.function.arguments);
23
+ if (typeof args.name === 'string' && args.name.length <= 200)
24
+ calls.set(call.id, { name: args.name, ...(typeof args.sourceId === 'string' && /^[a-f0-9]{64}$/.test(args.sourceId) ? { sourceId: args.sourceId } : {}) });
25
+ }
26
+ catch { /* Invalid invocations carry no reload authority. */ }
27
+ }
28
+ if (message.role === 'tool' && message.display_ok === true) {
29
+ const skill = calls.get(message.tool_call_id);
30
+ if (skill)
31
+ successful.set(JSON.stringify(skill), skill);
32
+ }
33
+ }
34
+ const skills = [...successful.values()].slice(-8);
35
+ return skills.length ? '\n\n<skill_reload_references>\n'
36
+ + 'These are successful Skill loads from the latest human turn, not their instructions. If still needed for pending work, reload Skill before acting; do not treat remembered fragments as complete instructions or expand permissions. Task/agent status must be re-read from its existing ledger, not inferred from this summary.\n'
37
+ + JSON.stringify(skills).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
38
+ + '\n</skill_reload_references>' : '';
39
+ }
@@ -0,0 +1,35 @@
1
+ import type { Message } from '../types.js';
2
+ import { isSystemEventMessage } from '../runtime/systemEvents.js';
3
+ import { expandAdvisorHistory } from './advisorHistory.js';
4
+
5
+ /** Reload hints, not a second copy of skill instructions. Only successful skill
6
+ * loads in the latest human turn qualify; never revive skills from older tasks. */
7
+ export function compactSkillReferences(messages: readonly Message[]): string {
8
+ // Reuse the existing cold evidence archive across repeated compactions.
9
+ // Never parse model-written summaries to invent successful skill loads.
10
+ const evidence = expandAdvisorHistory(messages);
11
+ let start = evidence.length - 1;
12
+ while (start >= 0 && (evidence[start].role !== 'user' || isSystemEventMessage(evidence[start]))) start--;
13
+ if (start < 0) return '';
14
+ const calls = new Map<string, { name: string; sourceId?: string }>();
15
+ const successful = new Map<string, { name: string; sourceId?: string }>();
16
+ for (const message of evidence.slice(start)) {
17
+ if (message.role === 'assistant') for (const call of message.tool_calls ?? []) {
18
+ if (call.function.name !== 'Skill') continue;
19
+ try {
20
+ const args = JSON.parse(call.function.arguments);
21
+ if (typeof args.name === 'string' && args.name.length <= 200)
22
+ calls.set(call.id, { name: args.name, ...(typeof args.sourceId === 'string' && /^[a-f0-9]{64}$/.test(args.sourceId) ? { sourceId: args.sourceId } : {}) });
23
+ } catch { /* Invalid invocations carry no reload authority. */ }
24
+ }
25
+ if (message.role === 'tool' && message.display_ok === true) {
26
+ const skill = calls.get(message.tool_call_id);
27
+ if (skill) successful.set(JSON.stringify(skill), skill);
28
+ }
29
+ }
30
+ const skills = [...successful.values()].slice(-8);
31
+ return skills.length ? '\n\n<skill_reload_references>\n'
32
+ + 'These are successful Skill loads from the latest human turn, not their instructions. If still needed for pending work, reload Skill before acting; do not treat remembered fragments as complete instructions or expand permissions. Task/agent status must be re-read from its existing ledger, not inferred from this summary.\n'
33
+ + JSON.stringify(skills).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
34
+ + '\n</skill_reload_references>' : '';
35
+ }
@@ -0,0 +1,20 @@
1
+ import { acquireContextLock } from './contextLock.js';
2
+ import { loadContext, saveContext } from './persistContext.js';
3
+ import { manualCompact } from './compact.js';
4
+ /** Shared TUI/Desktop/headless transaction. Reload under the cross-process
5
+ * session lock; a failed/cancelled summary or save never replaces live history. */
6
+ export async function compactSession(input) {
7
+ const release = await acquireContextLock(input.sessionFile, input.signal);
8
+ try {
9
+ const disk = await loadContext(input.sessionFile);
10
+ const history = disk ? [...disk, ...(input.history ?? []).filter(message => message.role === 'system' && message._ephemeral && !message._uiProgress)] : [...(input.history ?? [])];
11
+ const result = await (input.compact ?? manualCompact)(history, input.provider, input.signal, undefined, input.promptCache, { customInstructions: input.customInstructions });
12
+ input.signal?.throwIfAborted();
13
+ if (!result.unchangedReason)
14
+ await saveContext(result.messages, input.sessionFile, { strict: true });
15
+ return result;
16
+ }
17
+ finally {
18
+ await release();
19
+ }
20
+ }
@@ -0,0 +1,28 @@
1
+ import { acquireContextLock } from './contextLock.js';
2
+ import { loadContext, saveContext } from './persistContext.js';
3
+ import { manualCompact } from './compact.js';
4
+ import type { Message, Provider, PromptCacheContext } from '../types.js';
5
+
6
+ /** Shared TUI/Desktop/headless transaction. Reload under the cross-process
7
+ * session lock; a failed/cancelled summary or save never replaces live history. */
8
+ export async function compactSession(input: {
9
+ sessionFile: string;
10
+ history?: Message[];
11
+ provider: Provider;
12
+ signal?: AbortSignal;
13
+ promptCache?: PromptCacheContext;
14
+ customInstructions?: string;
15
+ compact?: typeof manualCompact;
16
+ }) {
17
+ const release = await acquireContextLock(input.sessionFile, input.signal);
18
+ try {
19
+ const disk = await loadContext(input.sessionFile);
20
+ const history = disk ? [...disk, ...(input.history ?? []).filter(message =>
21
+ message.role === 'system' && message._ephemeral && !message._uiProgress)] : [...(input.history ?? [])];
22
+ const result = await (input.compact ?? manualCompact)(history, input.provider, input.signal,
23
+ undefined, input.promptCache, { customInstructions: input.customInstructions });
24
+ input.signal?.throwIfAborted();
25
+ if (!result.unchangedReason) await saveContext(result.messages, input.sessionFile, { strict: true });
26
+ return result;
27
+ } finally { await release(); }
28
+ }
package/src/llm/client.js CHANGED
@@ -218,6 +218,10 @@ function buildChatError(resp, body) {
218
218
  const status = resp.status;
219
219
  const code = providerErrorCode(body);
220
220
  const head = `[${status} ${resp.statusText}]${code ? ` ${code}` : ''}`;
221
+ if (code === 'InvalidSubscription') {
222
+ return new Error(`LLM 服务订阅不可用 ${head}:请在服务商控制台检查该 API Key 对应的 Coding Plan/模型订阅是否已开通、到期或支持当前模型。` +
223
+ '这不是上下文预算或网络故障,重复发送不会恢复订阅。可在模型设置中测试连接,或选择你已有权限的模型。');
224
+ }
221
225
  if (isClientAuthError(status)) {
222
226
  return new Error(`LLM 鉴权失败 ${head}:API key 可能失效、过期或无权访问 model "${resp.url.split('/').pop()}".\n` +
223
227
  `请检查 .env / ~/.minimal-agent/config.json 的模型配置。\n` +
package/src/llm/client.ts CHANGED
@@ -264,6 +264,10 @@ function buildChatError(resp: Response, body: string): Error {
264
264
  const status = resp.status;
265
265
  const code = providerErrorCode(body);
266
266
  const head = `[${status} ${resp.statusText}]${code ? ` ${code}` : ''}`;
267
+ if (code === 'InvalidSubscription') {
268
+ return new Error(`LLM 服务订阅不可用 ${head}:请在服务商控制台检查该 API Key 对应的 Coding Plan/模型订阅是否已开通、到期或支持当前模型。` +
269
+ '这不是上下文预算或网络故障,重复发送不会恢复订阅。可在模型设置中测试连接,或选择你已有权限的模型。');
270
+ }
267
271
  if (isClientAuthError(status)) {
268
272
  return new Error(
269
273
  `LLM 鉴权失败 ${head}:API key 可能失效、过期或无权访问 model "${resp.url.split('/').pop()}".\n` +
@@ -104,7 +104,7 @@ export function prepareMessagesForProvider(messages, conversationMode = 'private
104
104
  return messages
105
105
  .filter((message) => !(message.role === 'system' && message._ephemeral === true))
106
106
  .map((message) => {
107
- const { id, timestamp, presentation, attachments, browserReferences, display_metadata, display_ok, tool_result_policy, provenance, advisorTaskVersion, advisorCheckpoints, advisorMutatesWorkspace, advisorHistory, toolResultDisposition, generation, ...rest } = message;
107
+ const { id, timestamp, presentation, inputOrigin, attachments, browserReferences, display_metadata, display_ok, tool_result_policy, provenance, advisorTaskVersion, advisorCheckpoints, advisorMutatesWorkspace, advisorHistory, toolResultDisposition, generation, ...rest } = message;
108
108
  if (rest.role === 'user')
109
109
  turnProvenance = provenance;
110
110
  if (rest.role === 'user' || rest.role === 'assistant' || rest.role === 'tool') {
@@ -113,7 +113,7 @@ export function prepareMessagesForProvider(
113
113
  .filter((message) => !(message.role === 'system' && message._ephemeral === true))
114
114
  .map((message) => {
115
115
  const {
116
- id, timestamp, presentation, attachments, browserReferences, display_metadata, display_ok, tool_result_policy, provenance, advisorTaskVersion, advisorCheckpoints, advisorMutatesWorkspace, advisorHistory, toolResultDisposition, generation, ...rest
116
+ id, timestamp, presentation, inputOrigin, attachments, browserReferences, display_metadata, display_ok, tool_result_policy, provenance, advisorTaskVersion, advisorCheckpoints, advisorMutatesWorkspace, advisorHistory, toolResultDisposition, generation, ...rest
117
117
  } = message as Message & Record<string, unknown>;
118
118
  if (rest.role === 'user') turnProvenance = provenance;
119
119
  if (rest.role === 'user' || rest.role === 'assistant' || rest.role === 'tool') {
@@ -1,3 +1,4 @@
1
+ import { requestIntentText } from '../runtime/requestIntent.js';
1
2
  const DELIVERY_ARTIFACT = '(?:文件|合同|协议|方案|文档|表格|报告|图片|图像|海报|幻灯片|PPT|PDF|代码|脚本|压缩包|网页|页面|HTML|DOCX|XLSX|CSV|ZIP)';
2
3
  const DELIVERY_ACTION = '(?:发送|(?<![开研])发|交付|提交|(?<!宣)传(?!统)|制作|生成|创建|导出|输出|修改|更新|完成|写|起草|做|设计|整理)';
3
4
  const ENGLISH_DELIVERY_ARTIFACT = '(?:file|contract|document|report|spreadsheet|workbook|slides?|presentation|pdf|image|code|script|archive|zip|html|webpage|website)';
@@ -6,11 +7,11 @@ const ENGLISH_DELIVERY_ACTION = '(?:send|deliver|submit|provide|create|generate|
6
7
  export function expectsFormalDelivery(input) {
7
8
  // Questions about producing artifacts are not instructions to produce them.
8
9
  // Evaluate clauses independently so “解释原因,然后生成报告” still delivers.
9
- const clauses = input.split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
10
+ const clauses = requestIntentText(input).split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
10
11
  return clauses.some(expectsDeliveryClause);
11
12
  }
12
13
  function expectsDeliveryClause(input) {
13
- if (/为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't)\b/i.test(input))
14
+ if (/为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|不需要|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't|no need)\b/i.test(input))
14
15
  return false;
15
16
  const compact = input.replace(/\s+/g, '');
16
17
  const chinese = new RegExp(`${DELIVERY_ACTION}(?:给)?我?.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}${DELIVERY_ACTION}(?:给)?我?|给我.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}给我`, 'i');
@@ -1,3 +1,5 @@
1
+ import { requestIntentText } from '../runtime/requestIntent.js';
2
+
1
3
  const DELIVERY_ARTIFACT =
2
4
  '(?:文件|合同|协议|方案|文档|表格|报告|图片|图像|海报|幻灯片|PPT|PDF|代码|脚本|压缩包|网页|页面|HTML|DOCX|XLSX|CSV|ZIP)';
3
5
  const DELIVERY_ACTION =
@@ -11,13 +13,13 @@ const ENGLISH_DELIVERY_ACTION =
11
13
  export function expectsFormalDelivery(input: string): boolean {
12
14
  // Questions about producing artifacts are not instructions to produce them.
13
15
  // Evaluate clauses independently so “解释原因,然后生成报告” still delivers.
14
- const clauses = input.split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
16
+ const clauses = requestIntentText(input).split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
15
17
  return clauses.some(expectsDeliveryClause);
16
18
  }
17
19
 
18
20
  function expectsDeliveryClause(input: string): boolean {
19
21
  if (
20
- /为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't)\b/i.test(
22
+ /为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|不需要|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't|no need)\b/i.test(
21
23
  input,
22
24
  )
23
25
  )
@@ -79,6 +79,7 @@ export async function injectVisionFollowups(history, settled, provider) {
79
79
  const content = await buildUserContent({ text, images });
80
80
  const msg = {
81
81
  role: 'user',
82
+ inputOrigin: 'tool-observation',
82
83
  content,
83
84
  timestamp: Date.now(),
84
85
  id: crypto.randomUUID(),
@@ -91,6 +91,7 @@ export async function injectVisionFollowups(
91
91
  const content = await buildUserContent({ text, images });
92
92
  const msg: Message = {
93
93
  role: 'user',
94
+ inputOrigin: 'tool-observation',
94
95
  content,
95
96
  timestamp: Date.now(),
96
97
  id: crypto.randomUUID(),
@@ -142,6 +142,8 @@ export interface RunQueryOptions {
142
142
  deliveryId?: string;
143
143
  /** Trusted host continuation; never inferred from process output. */
144
144
  backgroundContinuation?: import('../tools/tasks/backgroundTaskService.js').BackgroundContinuation;
145
+ /** Host owns an idle continuation queue; do not consume other tasks in this turn. */
146
+ deferBackgroundNotifications?: boolean;
145
147
  /** Trusted local origin for every message created by this run. */
146
148
  messageProvenance?: import('../types.js').ConversationProvenance;
147
149
  /** Browser element chips are persisted for UI but stripped before provider calls. */
package/src/loop.js CHANGED
@@ -127,6 +127,8 @@ export async function* runQuery(userInput, options) {
127
127
  const executeToolFn = options.executeTool ??
128
128
  ((name, args, signal, ctx) => executeCatalogTool(hostCatalog, name, args, signal, ctx));
129
129
  const explicitFileDeliveryRequested = expectsFormalDelivery(options.backgroundContinuation?.request ?? userInput);
130
+ const backgroundNotificationIds = options.backgroundContinuation?.taskIds
131
+ ?? (options.deferBackgroundNotifications ? [] : undefined);
130
132
  const currentUserMessageId = options.userMessageId ?? crypto.randomUUID();
131
133
  let currentTransientBundle = options.transientBundle;
132
134
  let advisorContextBundle = currentTransientBundle;
@@ -515,7 +517,7 @@ export async function* runQuery(userInput, options) {
515
517
  };
516
518
  return;
517
519
  }
518
- history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)), ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds));
520
+ history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)), ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds));
519
521
  if (runtimeContext.profile === 'main')
520
522
  coordinationText = (await agentCoordinationContext(toolCallContext)).text;
521
523
  incrementTurn(sessionState?.microCompact);
@@ -1015,7 +1017,7 @@ export async function* runQuery(userInput, options) {
1015
1017
  const pendingMessages = [
1016
1018
  ...(options.takePendingMessages?.() ?? []),
1017
1019
  ...(await takeAgentNotifications(toolCallContext)),
1018
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
1020
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
1019
1021
  ];
1020
1022
  if (pendingMessages.length) {
1021
1023
  // A private draft is simply superseded; a live one was already read,
package/src/loop.ts CHANGED
@@ -166,6 +166,8 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
166
166
  const executeToolFn: NonNullable<RunQueryOptions['executeTool']> = options.executeTool ??
167
167
  ((name, args, signal, ctx) => executeCatalogTool(hostCatalog, name, args, signal, ctx));
168
168
  const explicitFileDeliveryRequested = expectsFormalDelivery(options.backgroundContinuation?.request ?? userInput);
169
+ const backgroundNotificationIds = options.backgroundContinuation?.taskIds
170
+ ?? (options.deferBackgroundNotifications ? [] : undefined);
169
171
  const currentUserMessageId = options.userMessageId ?? crypto.randomUUID();
170
172
 
171
173
  let currentTransientBundle = options.transientBundle;
@@ -600,7 +602,7 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
600
602
  history.push(
601
603
  ...(options.takePendingMessages?.() ?? []),
602
604
  ...(await takeAgentNotifications(toolCallContext)),
603
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
605
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
604
606
  );
605
607
  if (runtimeContext.profile === 'main') coordinationText = (await agentCoordinationContext(toolCallContext)).text;
606
608
  incrementTurn(sessionState?.microCompact);
@@ -1111,7 +1113,7 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
1111
1113
  const pendingMessages = [
1112
1114
  ...(options.takePendingMessages?.() ?? []),
1113
1115
  ...(await takeAgentNotifications(toolCallContext)),
1114
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
1116
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
1115
1117
  ];
1116
1118
  if (pendingMessages.length) {
1117
1119
  // A private draft is simply superseded; a live one was already read,
package/src/main.js CHANGED
@@ -33,7 +33,8 @@ import { ALL_TOOLS } from './tools/index.js';
33
33
  import { BROWSER_TOOL_NAMES } from './runtime/agentRuntimeContext.js';
34
34
  import { memoryToolAllowed } from './runtime/agentRuntimeContext.js';
35
35
  import { Root } from './ui/Root.js';
36
- import { runPrintMode } from './cli/print.js';
36
+ import { emitJsonResult, runPrintMode } from './cli/print.js';
37
+ import { createCliLifecycle, flushCliOutput } from './cli/lifecycle.js';
37
38
  import { resolveBrowserCliMode, disposeLocalBrowsers } from './cli/browser.js';
38
39
  import { runStreamJsonMode } from './cli/streamJson.js';
39
40
  import { extractFlagValue, normalizeArgs } from './cli/args.js';
@@ -108,17 +109,21 @@ async function main() {
108
109
  const isPrintMode = args.includes('-p') || args.includes('--print');
109
110
  if (isPrintMode) {
110
111
  // 先把输出格式解析出来——provider 缺失分支也要按 json 契约给信号。
111
- // 只接受 'text' | 'json',其它值(含拼错)一律回落 'text'(向后兼容)。
112
+ // 输出协议拼错必须失败,不能静默回落 text 破坏宿主协议。
112
113
  const rawFormat = extractFlagValue(args, ['--output-format']);
114
+ if (args.includes('--output-format') && !['text', 'json', 'stream-json'].includes(rawFormat ?? ''))
115
+ throw new Error('--output-format 只接受 text、json 或 stream-json');
113
116
  // text(默认,逐字节向后兼容)/ json(一行结局契约)/ stream-json(逐行 LoopEvent,webchat broker 用)
114
117
  const outputFormat = rawFormat === 'json'
115
118
  ? 'json'
116
119
  : rawFormat === 'stream-json'
117
120
  ? 'stream-json'
118
121
  : 'text';
119
- // --max-turns:parseInt,非法(NaN)→ undefined(走 loop 默认 200)
122
+ // 未指定走内核默认;指定时拒绝缺值、小数、负数和数字后缀。
120
123
  const rawMaxTurns = extractFlagValue(args, ['--max-turns']);
121
- const parsedMaxTurns = rawMaxTurns !== undefined ? Number.parseInt(rawMaxTurns, 10) : Number.NaN;
124
+ const parsedMaxTurns = rawMaxTurns !== undefined ? Number(rawMaxTurns) : Number.NaN;
125
+ if (args.includes('--max-turns') && (!Number.isSafeInteger(parsedMaxTurns) || parsedMaxTurns <= 0))
126
+ throw new Error('--max-turns 必须是正整数');
122
127
  const maxTurns = Number.isNaN(parsedMaxTurns) ? undefined : parsedMaxTurns;
123
128
  // -s/--session <id>:选定同 cwd 下的哪个 session;缺省 'default'(向后兼容,
124
129
  // 逐字节保持旧行为)。读、写必须用同一份解析结果——不能只让加载感知这个 flag,
@@ -128,44 +133,17 @@ async function main() {
128
133
  sessionId = validateSessionId(extractFlagValue(args, ['-s', '--session']) ?? 'default');
129
134
  }
130
135
  catch (error) {
131
- console.error(`无效的 --session:${error.message}`);
132
- process.exitCode = 2;
133
- return;
136
+ throw new Error(`无效的 --session:${error.message}`);
134
137
  }
135
138
  await workspaceIndexService.register(getWorkingDir()).catch(() => { });
136
- const sessionFile = sessionFileFor(getWorkingDir(), sessionId);
139
+ const sessionFile = process.env.MINIMAL_AGENT_CONTEXT_FILE || sessionFileFor(getWorkingDir(), sessionId);
137
140
  // CLI 非交互模式:先 env,再 ~/.minimal-agent/config.json fallback;都没就退出
138
141
  // (宿主 spawn 子进程时通常没 export env,靠 TUI 向导写出的 config.json 持久化)
139
142
  const provider = await loadProviderLayered();
140
- if (!provider) {
141
- // json 模式:先给宿主一行结构化信号(stop_reason='config_error'),再退出。
142
- // 人类可读的中文提示仍走 stderr(json 契约只占 stdout 那一行)。
143
- if (outputFormat === 'json') {
144
- console.log(JSON.stringify({
145
- ok: false,
146
- result: '',
147
- is_error: true,
148
- stop_reason: 'config_error',
149
- num_turns: 0,
150
- error: 'provider config not found',
151
- }));
152
- }
153
- else if (outputFormat === 'stream-json') {
154
- // stream-json:吐一行 error 事件(webchat 前端识别为致命错误)
155
- console.log(JSON.stringify({
156
- type: 'error',
157
- error: 'provider config not found',
158
- code: 'llm_error',
159
- }));
160
- }
161
- process.stderr.write(`\n未找到 provider 配置。\n\n` +
162
- `请二选一:\n` +
163
- ` 1. 设置环境变量 MINIMAL_AGENT_BASE_URL / MINIMAL_AGENT_API_KEY / MINIMAL_AGENT_MODEL\n` +
164
- ` 2. 先直接运行 \`minimal-agent\`(TUI)在首次配置菜单里配好基座模型;菜单会写出 ~/.minimal-agent/config.json,之后 -p 模式自动复用\n\n`);
165
- process.exit(1);
166
- }
143
+ if (!provider)
144
+ throw new Error('未找到 provider 配置。请设置 MINIMAL_AGENT_BASE_URL / MINIMAL_AGENT_API_KEY / MINIMAL_AGENT_MODEL,或先运行 TUI 配置向导。');
167
145
  // stream-json 的 stdin 是双工控制通道(宿主可回灌 ask_answer),所以它**能**交互提问;
168
- // text/json 的 `-p` 不能——askBridge 会自动选推荐项兜底。提示词必须如实说明,
146
+ // text/json 的 `-p` 不能——AskUserQuestion 必须明确返回 interaction_unavailable。
169
147
  // 否则模型会以为可以停下来等用户选。
170
148
  const verbose = args.includes('--verbose') || args.includes('-v');
171
149
  // 信任边界收敛在这一处:两个入口都不再自证「我是本机主人」(见 cli/memoryAccess.ts)。
@@ -180,9 +158,7 @@ async function main() {
180
158
  browserMode = resolveBrowserCliMode(args);
181
159
  }
182
160
  catch (error) {
183
- process.stderr.write(`参数错误:${error.message}\n`);
184
- process.exitCode = 2;
185
- return;
161
+ throw new Error(`参数错误:${error.message}`);
186
162
  }
187
163
  if (computerUseTraceDir) {
188
164
  process.stderr.write(`Computer Use 诊断记录目录:${computerUseTraceDir}\n`);
@@ -191,10 +167,11 @@ async function main() {
191
167
  const visibleTools = ALL_TOOLS.filter((tool) => memoryToolAllowed(tool.name, memoryAccess) &&
192
168
  (tool.name !== 'ComputerUse' || computerUseMode !== 'disabled') &&
193
169
  (browserEnabled || !BROWSER_TOOL_NAMES.has(tool.name)));
194
- const initialHistory = await buildInitialHistory(sessionFile, visibleTools);
170
+ const initialHistory = outputFormat === 'stream-json' && args.includes('--compact')
171
+ ? await buildInitialHistory(sessionFile, visibleTools) : [];
195
172
  // stream-json 走独立流式模式(webchat broker / 网关用);text/json 仍走原 runPrintMode(契约不变)。
196
173
  if (outputFormat === 'stream-json') {
197
- await runStreamJsonMode(provider, args, initialHistory, {
174
+ process.exitCode = await runStreamJsonMode(provider, args, initialHistory, {
198
175
  maxTurns,
199
176
  compact: args.includes('--compact'),
200
177
  sessionFile,
@@ -206,7 +183,7 @@ async function main() {
206
183
  });
207
184
  return;
208
185
  }
209
- await runPrintMode(provider, args, initialHistory, {
186
+ process.exitCode = await runPrintMode(provider, args, initialHistory, {
210
187
  verbose,
211
188
  outputFormat,
212
189
  maxTurns,
@@ -293,6 +270,7 @@ minimal-agent - 轻量级 AI 编程助手
293
270
  OpenAI 兼容图片参数:限制最长边像素
294
271
  --clear 清空当前工作目录的会话(归档 + 清空)后退出
295
272
  --compact 与 -p --output-format stream-json 连用:压缩当前会话
273
+ --compact-instructions <文本> 手动压缩的保留重点(最多 8,000 字符)
296
274
  --workspace-doctor 只读诊断全局工作区索引、Session 数量和孤立历史
297
275
  -h, --help 显示帮助信息
298
276
 
@@ -316,7 +294,24 @@ minimal-agent - 轻量级 AI 编程助手
316
294
  minimal-agent -p --browser=headless "打开本地开发站点并截图检查页面"
317
295
  `);
318
296
  }
319
- main().catch((e) => {
320
- process.stderr.write(`\n未捕获异常:${e.message}\n${e.stack ?? ''}\n`);
321
- process.exit(1);
297
+ main().catch(async (error) => {
298
+ const args = normalizeArgs(process.argv.slice(2));
299
+ const format = extractFlagValue(args, ['--output-format']);
300
+ const lifecycle = createCliLifecycle();
301
+ const message = error instanceof Error ? error.message : String(error);
302
+ try {
303
+ if ((args.includes('-p') || args.includes('--print')) && format === 'json') {
304
+ emitJsonResult({ buffer: '', numTurns: 0, stopReason: 'config_error', error: message });
305
+ }
306
+ else if ((args.includes('-p') || args.includes('--print')) && format === 'stream-json') {
307
+ process.stdout.write(JSON.stringify({ type: 'error', code: 'config_error', error: message }) + '\n');
308
+ }
309
+ else
310
+ process.stderr.write(`错误:${message}\n`);
311
+ await flushCliOutput();
312
+ }
313
+ finally {
314
+ lifecycle.dispose();
315
+ }
316
+ process.exitCode = 1;
322
317
  });