minimal-agent 0.18.20 → 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 (188) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/cron-runner/README.md +23 -0
  4. package/plugins/cron-runner/commands/cron.md +7 -1
  5. package/plugins/cron-runner/plugin.js +9 -2
  6. package/plugins/cron-runner/plugin.ts +10 -2
  7. package/plugins/cron-runner/src/commands.js +112 -25
  8. package/plugins/cron-runner/src/commands.ts +154 -33
  9. package/plugins/cron-runner/src/contract.js +70 -0
  10. package/plugins/cron-runner/src/contract.ts +70 -0
  11. package/plugins/cron-runner/src/requests.js +22 -13
  12. package/plugins/cron-runner/src/requests.ts +34 -14
  13. package/plugins/cron-runner/src/runs.js +63 -10
  14. package/plugins/cron-runner/src/runs.ts +107 -15
  15. package/plugins/cron-runner/src/scheduler.js +188 -76
  16. package/plugins/cron-runner/src/scheduler.ts +277 -94
  17. package/plugins/cron-runner/src/schema.js +52 -17
  18. package/plugins/cron-runner/src/schema.ts +73 -22
  19. package/plugins/cron-runner/src/service.js +29 -8
  20. package/plugins/cron-runner/src/service.ts +71 -18
  21. package/plugins/cron-runner/src/store.js +92 -30
  22. package/plugins/cron-runner/src/store.ts +156 -53
  23. package/plugins/cron-runner/src/transaction.js +24 -0
  24. package/plugins/cron-runner/src/transaction.ts +36 -0
  25. package/plugins/cron-runner/src/types.ts +30 -4
  26. package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
  27. package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
  28. package/plugins/cron-runner/test/reliability.test.ts +2 -2
  29. package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
  30. package/plugins/workflow-runner/plugin.js +1 -0
  31. package/plugins/workflow-runner/plugin.ts +1 -0
  32. package/plugins/workflow-runner/src/index.js +1 -0
  33. package/plugins/workflow-runner/src/index.ts +2 -0
  34. package/plugins/workflow-runner/src/runner.js +6 -1
  35. package/plugins/workflow-runner/src/runner.ts +5 -1
  36. package/plugins/workflow-runner/src/types.ts +1 -0
  37. package/plugins/workflow-runner/test/api.test.ts +1 -0
  38. package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
  39. package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
  40. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  41. package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
  42. package/src/advisor/README.md +17 -6
  43. package/src/advisor/advisorNudge.js +23 -3
  44. package/src/advisor/advisorNudge.ts +20 -3
  45. package/src/advisor/deliveryReview.js +9 -2
  46. package/src/advisor/deliveryReview.ts +10 -2
  47. package/src/cli/args.js +1 -0
  48. package/src/cli/args.ts +1 -0
  49. package/src/cli/headlessTurn.js +143 -0
  50. package/src/cli/headlessTurn.ts +187 -0
  51. package/src/cli/lifecycle.js +52 -0
  52. package/src/cli/lifecycle.ts +59 -0
  53. package/src/cli/print.js +91 -240
  54. package/src/cli/print.ts +99 -301
  55. package/src/cli/quickModelSetup.js +3 -0
  56. package/src/cli/quickModelSetup.tsx +3 -0
  57. package/src/cli/streamJson.js +244 -334
  58. package/src/cli/streamJson.ts +248 -416
  59. package/src/cli/wizards/contextAdvisorWizard.js +0 -7
  60. package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
  61. package/src/cli/wizards/providerPresets.js +25 -14
  62. package/src/cli/wizards/providerPresets.ts +25 -14
  63. package/src/cli/wizards/providerWizard.js +29 -11
  64. package/src/cli/wizards/providerWizard.tsx +29 -11
  65. package/src/config/configDefaults.js +2 -2
  66. package/src/config/configDefaults.ts +2 -2
  67. package/src/config/configDiagnostics.js +7 -3
  68. package/src/config/configDiagnostics.ts +6 -3
  69. package/src/config/configFile.ts +1 -1
  70. package/src/context/compact.js +40 -10
  71. package/src/context/compact.ts +51 -12
  72. package/src/context/compactResources.js +39 -0
  73. package/src/context/compactResources.ts +35 -0
  74. package/src/context/manualCompact.js +20 -0
  75. package/src/context/manualCompact.ts +28 -0
  76. package/src/llm/client.js +4 -0
  77. package/src/llm/client.ts +4 -0
  78. package/src/llm/messageProvenance.js +1 -1
  79. package/src/llm/messageProvenance.ts +1 -1
  80. package/src/loop/README.md +4 -2
  81. package/src/loop/deliveryIntent.js +3 -2
  82. package/src/loop/deliveryIntent.ts +4 -2
  83. package/src/loop/messages.js +1 -0
  84. package/src/loop/messages.ts +1 -0
  85. package/src/loop/options.ts +2 -0
  86. package/src/loop.js +10 -2
  87. package/src/loop.ts +9 -2
  88. package/src/main.js +40 -45
  89. package/src/main.tsx +33 -52
  90. package/src/plugin-sdk.js +1 -1
  91. package/src/plugin-sdk.ts +1 -1
  92. package/src/plugins/artifactDelivery.js +76 -0
  93. package/src/plugins/artifactDelivery.ts +76 -0
  94. package/src/plugins/pluginApi.ts +4 -0
  95. package/src/plugins/pluginRunner.js +2 -0
  96. package/src/plugins/pluginRunner.ts +3 -0
  97. package/src/prompts/delegation.js +2 -2
  98. package/src/prompts/delegation.ts +2 -2
  99. package/src/prompts/policyRegistry.js +7 -5
  100. package/src/prompts/policyRegistry.ts +7 -5
  101. package/src/prompts/promptAssembly.js +2 -2
  102. package/src/prompts/promptAssembly.ts +2 -2
  103. package/src/runtime/requestIntent.js +86 -0
  104. package/src/runtime/requestIntent.ts +66 -0
  105. package/src/runtime/systemEvents.js +10 -1
  106. package/src/runtime/systemEvents.ts +9 -1
  107. package/src/session/commandTranscript.js +76 -0
  108. package/src/session/commandTranscript.ts +77 -0
  109. package/src/session/executionOutcome.js +25 -0
  110. package/src/session/executionOutcome.ts +34 -0
  111. package/src/session/runAgentTurn.js +8 -1
  112. package/src/session/runAgentTurn.ts +10 -1
  113. package/src/session/runTurn.js +40 -15
  114. package/src/session/runTurn.ts +38 -12
  115. package/src/session/sessionState.js +7 -2
  116. package/src/session/sessionState.ts +7 -2
  117. package/src/team/onlineToolContract.js +1 -0
  118. package/src/team/onlineToolContract.ts +1 -0
  119. package/src/tools/advisor/advisor.js +73 -30
  120. package/src/tools/advisor/advisor.ts +73 -33
  121. package/src/tools/advisor/advisorCoordination.js +44 -0
  122. package/src/tools/advisor/advisorCoordination.ts +45 -0
  123. package/src/tools/advisor/advisorDescription.js +1 -1
  124. package/src/tools/advisor/advisorDescription.ts +1 -1
  125. package/src/tools/agent/README.md +2 -0
  126. package/src/tools/agent/agent.js +7 -3
  127. package/src/tools/agent/agent.ts +7 -3
  128. package/src/tools/agent/agentHandoff.js +2 -1
  129. package/src/tools/agent/agentHandoff.ts +2 -1
  130. package/src/tools/agent/agentTaskService.js +26 -5
  131. package/src/tools/agent/agentTaskService.ts +25 -5
  132. package/src/tools/agent/agentTypes.js +2 -2
  133. package/src/tools/agent/agentTypes.ts +2 -2
  134. package/src/tools/agent/baselineAttach.js +14 -7
  135. package/src/tools/agent/baselineAttach.ts +14 -7
  136. package/src/tools/applypatch/applyPatch.js +39 -13
  137. package/src/tools/applypatch/applyPatch.ts +35 -15
  138. package/src/tools/bash/bash.js +3 -0
  139. package/src/tools/bash/bash.ts +3 -0
  140. package/src/tools/capabilities.js +1 -0
  141. package/src/tools/capabilities.ts +1 -0
  142. package/src/tools/download/download.js +147 -11
  143. package/src/tools/download/download.ts +193 -17
  144. package/src/tools/edit/edit.js +4 -4
  145. package/src/tools/edit/edit.ts +4 -4
  146. package/src/tools/edit/multi-edit.js +2 -2
  147. package/src/tools/edit/multi-edit.ts +2 -2
  148. package/src/tools/index.js +2 -0
  149. package/src/tools/index.ts +2 -0
  150. package/src/tools/powershell/powershell.js +2 -0
  151. package/src/tools/powershell/powershell.ts +2 -0
  152. package/src/tools/schedule/schedule.js +184 -0
  153. package/src/tools/schedule/schedule.ts +214 -0
  154. package/src/tools/shared/fileUtils.js +16 -6
  155. package/src/tools/shared/fileUtils.ts +15 -6
  156. package/src/tools/tasks/backgroundTaskService.js +108 -12
  157. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  158. package/src/tools/tasks/taskOutput.js +15 -5
  159. package/src/tools/tasks/taskOutput.ts +13 -5
  160. package/src/tools/tasks/taskStop.js +2 -2
  161. package/src/tools/tasks/taskStop.ts +2 -2
  162. package/src/tools/toolPromptGuides.js +4 -3
  163. package/src/tools/toolPromptGuides.ts +4 -3
  164. package/src/tools/webfetch/webfetch.js +1 -1
  165. package/src/tools/webfetch/webfetch.ts +1 -1
  166. package/src/types.ts +6 -0
  167. package/src/ui/App.js +3 -1
  168. package/src/ui/App.tsx +2 -0
  169. package/src/ui/InputBox.js +2 -2
  170. package/src/ui/InputBox.tsx +2 -2
  171. package/src/ui/LiveArea.js +6 -1
  172. package/src/ui/LiveArea.tsx +6 -1
  173. package/src/ui/MessageList.js +2 -0
  174. package/src/ui/MessageList.tsx +2 -0
  175. package/src/ui/README.md +8 -2
  176. package/src/ui/activityPresentation.js +23 -3
  177. package/src/ui/activityPresentation.ts +22 -3
  178. package/src/ui/backgroundWake.js +20 -4
  179. package/src/ui/backgroundWake.ts +19 -4
  180. package/src/ui/commandTranscript.js +2 -69
  181. package/src/ui/commandTranscript.ts +2 -71
  182. package/src/ui/hooks/useBackgroundAgents.js +33 -0
  183. package/src/ui/hooks/useBackgroundAgents.ts +36 -0
  184. package/src/ui/hooks/useChat.js +46 -25
  185. package/src/ui/hooks/useChat.ts +36 -23
  186. package/src/web/protocol.ts +5 -2
  187. package/src/cli/wizards/advisorWizard.js +0 -152
  188. 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
  import { chat } from '../llm/client.js';
3
5
  import { countMessagesTokens } from './tokenCounter.js';
4
6
  const NO_TOOLS_PREAMBLE = `Respond with text only. Do not call tools. Return exactly one <summary>...</summary> block.
@@ -64,7 +66,7 @@ function userText(content) {
64
66
  */
65
67
  export function buildUserMessageLedger(messages) {
66
68
  const texts = messages
67
- .filter((message) => message.role === 'user')
69
+ .filter((message) => message.role === 'user' && !isSystemEventMessage(message))
68
70
  .map((message) => userText(message.content))
69
71
  .filter((text) => text.length > 0
70
72
  && !text.startsWith(CONTINUATION_MARKER)
@@ -282,8 +284,31 @@ export async function autoCompactIfNeeded(messages, provider, opts) {
282
284
  const after = countMessagesTokens(compacted.messages);
283
285
  return { ...compacted, compacted: true, before, after };
284
286
  }
287
+ /** User-requested cleanup is not an emergency. Never truncate on failure or
288
+ * replace history with a larger result. Hosts persist before publishing it. */
289
+ export async function manualCompact(messages, provider, signal, chatFn = chat, promptCache, options) {
290
+ signal?.throwIfAborted();
291
+ if (options?.customInstructions !== undefined && (typeof options.customInstructions !== 'string' || options.customInstructions.length > 8000))
292
+ throw new Error('压缩要求必须为不超过 8,000 字符的文本');
293
+ const before = countMessagesTokens(messages);
294
+ const unchanged = (unchangedReason) => ({
295
+ messages, before, after: before, mode: 'llm-summary', degraded: false,
296
+ messagesRemoved: 0, tokensFreed: 0, unchangedReason,
297
+ });
298
+ const content = messages.filter(message => message.role !== 'system');
299
+ if (findTailWithCompleteToolChains(content).length >= content.length)
300
+ return unchanged('too-short');
301
+ const result = await forceCompact(messages, provider, signal, chatFn, promptCache, { ...options, strict: true });
302
+ signal?.throwIfAborted();
303
+ return result.after < before ? result : unchanged('no-benefit');
304
+ }
305
+ export function manualCompactNotice(result) {
306
+ return result.unchangedReason === 'too-short' ? '可压缩历史较少,已保留原上下文,未请求模型。'
307
+ : result.unchangedReason === 'no-benefit' ? '摘要未减少上下文占用,已保留原上下文。'
308
+ : `压缩完成:${result.before} → ${result.after} tokens(估算)。`;
309
+ }
285
310
  /**
286
- * 不看阈值,直接执行一次压缩。供 `/compact` 手动命令使用。
311
+ * 不看阈值,直接执行一次压缩。应急路径允许截断降级;手动入口使用 manualCompact。
287
312
  *
288
313
  * 与 autoCompactIfNeeded 共用同一段 runCompaction 逻辑;区别仅在于此函数
289
314
  * 永远跑压缩、不返回 `compacted` 字段(由调用方决定如何反馈)。
@@ -308,17 +333,17 @@ chatFn = chat, promptCache, options) {
308
333
  */
309
334
  async function runCompaction(messages, provider, signal, chatFn = chat, promptCache, options) {
310
335
  // 1. 找出原 system(保留它,避免 agent 失忆)
311
- const systemMsg = messages.find((m) => m.role === 'system');
336
+ const systemMessages = messages.filter((m) => m.role === 'system' && !m._uiProgress);
312
337
  const nonSystem = messages.filter((m) => m.role !== 'system');
313
338
  // 2. 构造给"压缩用"的请求:完整历史 + 七段式续接摘要 prompt
314
339
  // (即使最后 N 条会被原样保留在新历史里,也送给 LLM 看 —— 让它写得出
315
340
  // 高质量的 "Context for Continuing Work" 节,知道当前停在哪儿。)
316
341
  const compactRequest = [
317
- ...(systemMsg ? [systemMsg] : []),
342
+ ...systemMessages,
318
343
  ...nonSystem,
319
344
  {
320
345
  role: 'user',
321
- content: buildCompactPrompt(),
346
+ content: buildCompactPrompt(options?.customInstructions),
322
347
  },
323
348
  ];
324
349
  // 3. 调 LLM(用同一个 chat() 但不传工具,避免模型尝试调用工具)
@@ -356,9 +381,10 @@ async function runCompaction(messages, provider, signal, chatFn = chat, promptCa
356
381
  const failureTail = findTailWithCompleteToolChains(nonSystem);
357
382
  const failureLedger = buildUserMessageLedger(nonSystem.slice(0, nonSystem.length - failureTail.length));
358
383
  const compactedMessages = [
359
- ...(systemMsg ? [systemMsg] : []),
384
+ ...systemMessages,
360
385
  {
361
386
  role: 'user',
387
+ inputOrigin: 'compact-fallback',
362
388
  // ⚠️ 这里**故意不带** provider 原始报错:本条消息会进 history,既落盘也会在
363
389
  // 后续轮次重新发给模型,错误体里可能夹带 URL / 请求体 / 凭据。
364
390
  // 排障线索走 `compact_failed` 事件(只到 stderr / UI,不进 history)。
@@ -383,7 +409,9 @@ async function runCompaction(messages, provider, signal, chatFn = chat, promptCa
383
409
  };
384
410
  }
385
411
  const formattedSummary = formatCompactSummary(summary);
386
- if (options?.strict && !validateCompactSummary(formattedSummary).valid) {
412
+ const summaryBody = formattedSummary.replace(/^##\s+(?:Goal|Constraints|Verified evidence|Changes|Verification|Pending|Next action)[ \t]*(?:—|-)?[ \t]*/gmi, '').trim();
413
+ if (options?.strict && (!validateCompactSummary(formattedSummary).valid
414
+ || !summaryBody || /^(?:\s|Unknown[.!]?|未知[。]?)*$/i.test(summaryBody))) {
387
415
  throw new Error('COMPACTION_INVALID_SUMMARY');
388
416
  }
389
417
  if (!formattedSummary.trim()) {
@@ -393,9 +421,10 @@ async function runCompaction(messages, provider, signal, chatFn = chat, promptCa
393
421
  throw new Error('COMPACTION_INVALID_SUMMARY');
394
422
  const failureLedger = buildUserMessageLedger(nonSystem.slice(0, messagesRemoved));
395
423
  const compactedMessages = [
396
- ...(systemMsg ? [systemMsg] : []),
424
+ ...systemMessages,
397
425
  {
398
426
  role: 'user',
427
+ inputOrigin: 'compact-fallback',
399
428
  content: '(LLM 返回了无效摘要,已使用规则式截断继续会话)'
400
429
  + (failureLedger
401
430
  ? `\n\n<user_messages>\n以下是被截掉的那部分对话里**用户的原话**(程序逐字抽取)。摘要不存在,这里就是唯一残留的历史要求。\n${failureLedger}\n</user_messages>`
@@ -420,14 +449,15 @@ async function runCompaction(messages, provider, signal, chatFn = chat, promptCa
420
449
  // 台账只覆盖**被丢弃的那一段**——recentTail 已经逐字保留,再抽一遍是重复烧 token。
421
450
  const messagesRemoved = nonSystem.length - recentTail.length;
422
451
  const compactedMessages = [
423
- ...(systemMsg ? [systemMsg] : []),
452
+ ...systemMessages,
424
453
  {
425
454
  role: 'user',
455
+ inputOrigin: 'compact-summary',
426
456
  content: buildContinuationUserMessage({
427
457
  summary: cleanSummary,
428
458
  recentMessagesPreserved: recentTail.length > 0,
429
459
  userMessageLedger: buildUserMessageLedger(nonSystem.slice(0, messagesRemoved)),
430
- }),
460
+ }) + compactSkillReferences(nonSystem),
431
461
  },
432
462
  ...recentTail,
433
463
  ];
@@ -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') {
@@ -53,8 +53,10 @@ decisions stay visible in one place: retry, consult, execute, publish or interru
53
53
  rewrites it. Corrections retire the draft and add a transient reminder (the
54
54
  diagram one carries the draft as internal material until the revised answer
55
55
  itself arrives, across any skill-loading round); the kernel never
56
- writes a tool call the model did not make, except the documented host-forced
57
- Advisor checkpoint.
56
+ writes a tool call the model did not make. Advisor failures do not trigger
57
+ repeated consultation on unchanged evidence, including the optional follow-up.
58
+ - A non-terminal/truncated model response retains its text generation receipt
59
+ and yields an incomplete turn, never a successful child result or cron run.
58
60
  - Cancellation belongs to the host AbortSignal. Progress stream disposal waits for
59
61
  active workers to settle; it does not grant permission to leave tools orphaned.
60
62
  - Existing exports from `loop.ts` remain compatible for TUI, Desktop, subagents and
@@ -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;
@@ -208,6 +210,7 @@ export async function* runQuery(userInput, options) {
208
210
  agentHandoff: options.agentHandoff,
209
211
  messageProvenance: options.messageProvenance,
210
212
  memoryAccess: runtimeContext.memoryAccess,
213
+ owner: runtimeContext.owner,
211
214
  conversationMode: runtimeContext.conversationMode ?? 'private',
212
215
  surface: runtimeContext.surface,
213
216
  workspaceId: runtimeContext.workspaceId,
@@ -514,7 +517,7 @@ export async function* runQuery(userInput, options) {
514
517
  };
515
518
  return;
516
519
  }
517
- history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)), ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds));
520
+ history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)), ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds));
518
521
  if (runtimeContext.profile === 'main')
519
522
  coordinationText = (await agentCoordinationContext(toolCallContext)).text;
520
523
  incrementTurn(sessionState?.microCompact);
@@ -1014,7 +1017,7 @@ export async function* runQuery(userInput, options) {
1014
1017
  const pendingMessages = [
1015
1018
  ...(options.takePendingMessages?.() ?? []),
1016
1019
  ...(await takeAgentNotifications(toolCallContext)),
1017
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
1020
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
1018
1021
  ];
1019
1022
  if (pendingMessages.length) {
1020
1023
  // A private draft is simply superseded; a live one was already read,
@@ -1216,6 +1219,11 @@ export async function* runQuery(userInput, options) {
1216
1219
  yield { type: 'warning', message: warning };
1217
1220
  yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage };
1218
1221
  }
1222
+ else if (!completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal)) {
1223
+ const warning = '模型响应未完整结束,已有文字与工具结果已保留;不能将本轮或子任务记为成功完成。';
1224
+ yield { type: 'warning', message: warning };
1225
+ yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage };
1226
+ }
1219
1227
  else if (resultPresented && presentedResultUnverified) {
1220
1228
  const warning = '结果已提交,但至少一个文件尚未通过结构化验证。';
1221
1229
  yield { type: 'warning', message: warning };
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;
@@ -251,6 +253,7 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
251
253
  agentHandoff: options.agentHandoff,
252
254
  messageProvenance: options.messageProvenance,
253
255
  memoryAccess: runtimeContext.memoryAccess,
256
+ owner: runtimeContext.owner,
254
257
  conversationMode: runtimeContext.conversationMode ?? 'private',
255
258
  surface: runtimeContext.surface,
256
259
  workspaceId: runtimeContext.workspaceId,
@@ -599,7 +602,7 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
599
602
  history.push(
600
603
  ...(options.takePendingMessages?.() ?? []),
601
604
  ...(await takeAgentNotifications(toolCallContext)),
602
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
605
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
603
606
  );
604
607
  if (runtimeContext.profile === 'main') coordinationText = (await agentCoordinationContext(toolCallContext)).text;
605
608
  incrementTurn(sessionState?.microCompact);
@@ -1110,7 +1113,7 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
1110
1113
  const pendingMessages = [
1111
1114
  ...(options.takePendingMessages?.() ?? []),
1112
1115
  ...(await takeAgentNotifications(toolCallContext)),
1113
- ...takeBackgroundNotifications(toolCallContext, options.backgroundContinuation?.taskIds),
1116
+ ...takeBackgroundNotifications(toolCallContext, backgroundNotificationIds),
1114
1117
  ];
1115
1118
  if (pendingMessages.length) {
1116
1119
  // A private draft is simply superseded; a live one was already read,
@@ -1304,6 +1307,10 @@ export async function* runQuery(userInput: string, options: RunQueryOptions): As
1304
1307
  const warning = '交付未完成:用户明确要求提供文件,但本轮没有成功提交可打开的文件结果。';
1305
1308
  yield { type: 'warning', message: warning };
1306
1309
  yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage };
1310
+ } else if (!completeGenerationTerminal(lastFinishReason, streamEndedWithoutTerminal)) {
1311
+ const warning = '模型响应未完整结束,已有文字与工具结果已保留;不能将本轮或子任务记为成功完成。';
1312
+ yield { type: 'warning', message: warning };
1313
+ yield { type: 'turn_done', completionStatus: 'delivery_incomplete', warning, usage };
1307
1314
  } else if (resultPresented && presentedResultUnverified) {
1308
1315
  const warning = '结果已提交,但至少一个文件尚未通过结构化验证。';
1309
1316
  yield { type: 'warning', message: warning };