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.
- package/README.md +16 -3
- package/package.json +1 -1
- package/plugins/cron-runner/README.md +23 -0
- package/plugins/cron-runner/commands/cron.md +7 -1
- package/plugins/cron-runner/plugin.js +9 -2
- package/plugins/cron-runner/plugin.ts +10 -2
- package/plugins/cron-runner/src/commands.js +112 -25
- package/plugins/cron-runner/src/commands.ts +154 -33
- package/plugins/cron-runner/src/contract.js +70 -0
- package/plugins/cron-runner/src/contract.ts +70 -0
- package/plugins/cron-runner/src/requests.js +22 -13
- package/plugins/cron-runner/src/requests.ts +34 -14
- package/plugins/cron-runner/src/runs.js +63 -10
- package/plugins/cron-runner/src/runs.ts +107 -15
- package/plugins/cron-runner/src/scheduler.js +188 -76
- package/plugins/cron-runner/src/scheduler.ts +277 -94
- package/plugins/cron-runner/src/schema.js +52 -17
- package/plugins/cron-runner/src/schema.ts +73 -22
- package/plugins/cron-runner/src/service.js +29 -8
- package/plugins/cron-runner/src/service.ts +71 -18
- package/plugins/cron-runner/src/store.js +92 -30
- package/plugins/cron-runner/src/store.ts +156 -53
- package/plugins/cron-runner/src/transaction.js +24 -0
- package/plugins/cron-runner/src/transaction.ts +36 -0
- package/plugins/cron-runner/src/types.ts +30 -4
- package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
- package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
- package/plugins/cron-runner/test/reliability.test.ts +2 -2
- package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
- package/plugins/workflow-runner/plugin.js +1 -0
- package/plugins/workflow-runner/plugin.ts +1 -0
- package/plugins/workflow-runner/src/index.js +1 -0
- package/plugins/workflow-runner/src/index.ts +2 -0
- package/plugins/workflow-runner/src/runner.js +6 -1
- package/plugins/workflow-runner/src/runner.ts +5 -1
- package/plugins/workflow-runner/src/types.ts +1 -0
- package/plugins/workflow-runner/test/api.test.ts +1 -0
- package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
- package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
- package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
- package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
- package/src/advisor/README.md +17 -6
- package/src/advisor/advisorNudge.js +23 -3
- package/src/advisor/advisorNudge.ts +20 -3
- package/src/advisor/deliveryReview.js +9 -2
- package/src/advisor/deliveryReview.ts +10 -2
- package/src/cli/args.js +1 -0
- package/src/cli/args.ts +1 -0
- package/src/cli/headlessTurn.js +143 -0
- package/src/cli/headlessTurn.ts +187 -0
- package/src/cli/lifecycle.js +52 -0
- package/src/cli/lifecycle.ts +59 -0
- package/src/cli/print.js +91 -240
- package/src/cli/print.ts +99 -301
- package/src/cli/quickModelSetup.js +3 -0
- package/src/cli/quickModelSetup.tsx +3 -0
- package/src/cli/streamJson.js +244 -334
- package/src/cli/streamJson.ts +248 -416
- package/src/cli/wizards/contextAdvisorWizard.js +0 -7
- package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
- package/src/cli/wizards/providerPresets.js +25 -14
- package/src/cli/wizards/providerPresets.ts +25 -14
- package/src/cli/wizards/providerWizard.js +29 -11
- package/src/cli/wizards/providerWizard.tsx +29 -11
- package/src/config/configDefaults.js +2 -2
- package/src/config/configDefaults.ts +2 -2
- package/src/config/configDiagnostics.js +7 -3
- package/src/config/configDiagnostics.ts +6 -3
- package/src/config/configFile.ts +1 -1
- package/src/context/compact.js +40 -10
- package/src/context/compact.ts +51 -12
- package/src/context/compactResources.js +39 -0
- package/src/context/compactResources.ts +35 -0
- package/src/context/manualCompact.js +20 -0
- package/src/context/manualCompact.ts +28 -0
- package/src/llm/client.js +4 -0
- package/src/llm/client.ts +4 -0
- package/src/llm/messageProvenance.js +1 -1
- package/src/llm/messageProvenance.ts +1 -1
- package/src/loop/README.md +4 -2
- package/src/loop/deliveryIntent.js +3 -2
- package/src/loop/deliveryIntent.ts +4 -2
- package/src/loop/messages.js +1 -0
- package/src/loop/messages.ts +1 -0
- package/src/loop/options.ts +2 -0
- package/src/loop.js +10 -2
- package/src/loop.ts +9 -2
- package/src/main.js +40 -45
- package/src/main.tsx +33 -52
- package/src/plugin-sdk.js +1 -1
- package/src/plugin-sdk.ts +1 -1
- package/src/plugins/artifactDelivery.js +76 -0
- package/src/plugins/artifactDelivery.ts +76 -0
- package/src/plugins/pluginApi.ts +4 -0
- package/src/plugins/pluginRunner.js +2 -0
- package/src/plugins/pluginRunner.ts +3 -0
- package/src/prompts/delegation.js +2 -2
- package/src/prompts/delegation.ts +2 -2
- package/src/prompts/policyRegistry.js +7 -5
- package/src/prompts/policyRegistry.ts +7 -5
- package/src/prompts/promptAssembly.js +2 -2
- package/src/prompts/promptAssembly.ts +2 -2
- package/src/runtime/requestIntent.js +86 -0
- package/src/runtime/requestIntent.ts +66 -0
- package/src/runtime/systemEvents.js +10 -1
- package/src/runtime/systemEvents.ts +9 -1
- package/src/session/commandTranscript.js +76 -0
- package/src/session/commandTranscript.ts +77 -0
- package/src/session/executionOutcome.js +25 -0
- package/src/session/executionOutcome.ts +34 -0
- package/src/session/runAgentTurn.js +8 -1
- package/src/session/runAgentTurn.ts +10 -1
- package/src/session/runTurn.js +40 -15
- package/src/session/runTurn.ts +38 -12
- package/src/session/sessionState.js +7 -2
- package/src/session/sessionState.ts +7 -2
- package/src/team/onlineToolContract.js +1 -0
- package/src/team/onlineToolContract.ts +1 -0
- package/src/tools/advisor/advisor.js +73 -30
- package/src/tools/advisor/advisor.ts +73 -33
- package/src/tools/advisor/advisorCoordination.js +44 -0
- package/src/tools/advisor/advisorCoordination.ts +45 -0
- package/src/tools/advisor/advisorDescription.js +1 -1
- package/src/tools/advisor/advisorDescription.ts +1 -1
- package/src/tools/agent/README.md +2 -0
- package/src/tools/agent/agent.js +7 -3
- package/src/tools/agent/agent.ts +7 -3
- package/src/tools/agent/agentHandoff.js +2 -1
- package/src/tools/agent/agentHandoff.ts +2 -1
- package/src/tools/agent/agentTaskService.js +26 -5
- package/src/tools/agent/agentTaskService.ts +25 -5
- package/src/tools/agent/agentTypes.js +2 -2
- package/src/tools/agent/agentTypes.ts +2 -2
- package/src/tools/agent/baselineAttach.js +14 -7
- package/src/tools/agent/baselineAttach.ts +14 -7
- package/src/tools/applypatch/applyPatch.js +39 -13
- package/src/tools/applypatch/applyPatch.ts +35 -15
- package/src/tools/bash/bash.js +3 -0
- package/src/tools/bash/bash.ts +3 -0
- package/src/tools/capabilities.js +1 -0
- package/src/tools/capabilities.ts +1 -0
- package/src/tools/download/download.js +147 -11
- package/src/tools/download/download.ts +193 -17
- package/src/tools/edit/edit.js +4 -4
- package/src/tools/edit/edit.ts +4 -4
- package/src/tools/edit/multi-edit.js +2 -2
- package/src/tools/edit/multi-edit.ts +2 -2
- package/src/tools/index.js +2 -0
- package/src/tools/index.ts +2 -0
- package/src/tools/powershell/powershell.js +2 -0
- package/src/tools/powershell/powershell.ts +2 -0
- package/src/tools/schedule/schedule.js +184 -0
- package/src/tools/schedule/schedule.ts +214 -0
- package/src/tools/shared/fileUtils.js +16 -6
- package/src/tools/shared/fileUtils.ts +15 -6
- package/src/tools/tasks/backgroundTaskService.js +108 -12
- package/src/tools/tasks/backgroundTaskService.ts +106 -14
- package/src/tools/tasks/taskOutput.js +15 -5
- package/src/tools/tasks/taskOutput.ts +13 -5
- package/src/tools/tasks/taskStop.js +2 -2
- package/src/tools/tasks/taskStop.ts +2 -2
- package/src/tools/toolPromptGuides.js +4 -3
- package/src/tools/toolPromptGuides.ts +4 -3
- package/src/tools/webfetch/webfetch.js +1 -1
- package/src/tools/webfetch/webfetch.ts +1 -1
- package/src/types.ts +6 -0
- package/src/ui/App.js +3 -1
- package/src/ui/App.tsx +2 -0
- package/src/ui/InputBox.js +2 -2
- package/src/ui/InputBox.tsx +2 -2
- package/src/ui/LiveArea.js +6 -1
- package/src/ui/LiveArea.tsx +6 -1
- package/src/ui/MessageList.js +2 -0
- package/src/ui/MessageList.tsx +2 -0
- package/src/ui/README.md +8 -2
- package/src/ui/activityPresentation.js +23 -3
- package/src/ui/activityPresentation.ts +22 -3
- package/src/ui/backgroundWake.js +20 -4
- package/src/ui/backgroundWake.ts +19 -4
- package/src/ui/commandTranscript.js +2 -69
- package/src/ui/commandTranscript.ts +2 -71
- package/src/ui/hooks/useBackgroundAgents.js +33 -0
- package/src/ui/hooks/useBackgroundAgents.ts +36 -0
- package/src/ui/hooks/useChat.js +46 -25
- package/src/ui/hooks/useChat.ts +36 -23
- package/src/web/protocol.ts +5 -2
- package/src/cli/wizards/advisorWizard.js +0 -152
- package/src/cli/wizards/advisorWizard.tsx +0 -203
package/src/session/runTurn.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { startTurnJournal } from '../memory/turnJournal.js';
|
|
|
26
26
|
import { createLearningModel } from '../memory/learningModel.js';
|
|
27
27
|
import type { PluginEvent } from '../plugins/pluginApi.js';
|
|
28
28
|
import { runWithPlugins } from '../plugins/pluginRunner.js';
|
|
29
|
+
import { captureCommandReply, commandRequest } from './commandTranscript.js';
|
|
29
30
|
import { upsertStableSystemMessage } from '../prompts/stableSystemPrompt.js';
|
|
30
31
|
import type {
|
|
31
32
|
ImageDetail,
|
|
@@ -87,6 +88,13 @@ export interface RunTurnOptions {
|
|
|
87
88
|
initialHistory?: Message[];
|
|
88
89
|
/** Defaults to true. False avoids reading, locking, or writing sessionFile. */
|
|
89
90
|
persist?: boolean;
|
|
91
|
+
/** Host setup runs after loading history under the session lock. */
|
|
92
|
+
prepare?: (history: Message[]) => Promise<Pick<RunTurnOptions,
|
|
93
|
+
'runtimeContext' | 'allowedTools' | 'sessionState' | 'transientBundle' |
|
|
94
|
+
'promptCache' | 'memoryContext' | 'computerRun'>>;
|
|
95
|
+
/** Release turn-owned resources before releasing the session lock. */
|
|
96
|
+
cleanup?: () => Promise<void>;
|
|
97
|
+
strictPersistence?: boolean;
|
|
90
98
|
}
|
|
91
99
|
|
|
92
100
|
/**
|
|
@@ -121,8 +129,18 @@ export async function* runTurn(
|
|
|
121
129
|
): AsyncGenerator<LoopEvent | PluginEvent, void, void> {
|
|
122
130
|
const persist = opts.persist !== false;
|
|
123
131
|
const release = persist ? await acquireContextLock(opts.sessionFile, opts.signal) : async () => {};
|
|
132
|
+
try {
|
|
133
|
+
yield* runLockedTurn(opts, persist);
|
|
134
|
+
} finally {
|
|
135
|
+
try { await opts.cleanup?.(); } finally { await release(); }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Initialization is also inside the lock lifetime; failures must not strand it. */
|
|
140
|
+
async function* runLockedTurn(opts: RunTurnOptions, persist: boolean): AsyncGenerator<LoopEvent | PluginEvent, void, void> {
|
|
124
141
|
const loaded = opts.initialHistory ?? (persist ? await loadContext(opts.sessionFile) : null);
|
|
125
142
|
const history: Message[] = buildInitialHistory(loaded, opts.systemPrompt);
|
|
143
|
+
if (opts.prepare) opts = { ...opts, ...await opts.prepare(history) };
|
|
126
144
|
const historyStart = history.length;
|
|
127
145
|
const userMessageId = opts.userMessageId ?? crypto.randomUUID();
|
|
128
146
|
// 会话原文记账:实现在 src/memory/turnJournal.ts(TUI 的 useChat 用同一份),
|
|
@@ -144,6 +162,13 @@ export async function* runTurn(
|
|
|
144
162
|
const trace = createLifecycleTrace('host');
|
|
145
163
|
let hostFailed = false;
|
|
146
164
|
try {
|
|
165
|
+
const commandReply = opts.userInput.trim().startsWith('/') ? captureCommandReply(userMessageId) : null;
|
|
166
|
+
if (commandReply) {
|
|
167
|
+
const request = commandRequest(opts.userInput, userMessageId);
|
|
168
|
+
history.push(request);
|
|
169
|
+
if (persist) await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
170
|
+
yield { type: 'injected_message', message: request };
|
|
171
|
+
}
|
|
147
172
|
for await (const event of runWithPlugins(opts.userInput, {
|
|
148
173
|
executionId: opts.executionId,
|
|
149
174
|
provider: opts.provider,
|
|
@@ -177,13 +202,18 @@ export async function* runTurn(
|
|
|
177
202
|
memoryContext: opts.memoryContext,
|
|
178
203
|
})) {
|
|
179
204
|
journal?.observe(event);
|
|
205
|
+
const commandResult = commandReply?.(event);
|
|
206
|
+
if (commandResult) {
|
|
207
|
+
history.push(commandResult);
|
|
208
|
+
yield { type: 'injected_message', message: commandResult };
|
|
209
|
+
}
|
|
180
210
|
// Stage records are user-visible history, not model instructions. Checkpoint
|
|
181
211
|
// at stage boundaries so a Runtime restart does not lose the whole workflow.
|
|
182
212
|
if (persist && (['user_message_committed', 'assistant_message', 'compact_start', 'turn_done'].includes(event.type)
|
|
183
213
|
|| (event.type === 'injected_message' && event.message && typeof event.message === 'object' && 'role' in event.message && event.message.role === 'system' && '_uiProgress' in event.message && event.message._uiProgress === true))) {
|
|
184
214
|
trace('save_start');
|
|
185
215
|
try {
|
|
186
|
-
await saveContext(history, opts.sessionFile);
|
|
216
|
+
await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
187
217
|
trace('save_end');
|
|
188
218
|
} catch (error) {
|
|
189
219
|
trace('save_error');
|
|
@@ -201,16 +231,12 @@ export async function* runTurn(
|
|
|
201
231
|
: { type: 'error', code: 'host_error' });
|
|
202
232
|
throw error;
|
|
203
233
|
} finally {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
if (persist) await saveContext(history, opts.sessionFile);
|
|
212
|
-
} finally {
|
|
213
|
-
await release();
|
|
214
|
-
}
|
|
234
|
+
if (!completedNormally && !hostFailed) journal?.observe({ type: 'interrupted' });
|
|
235
|
+
trace('memory_start');
|
|
236
|
+
await journal?.finish(history, historyStart).catch(error => {
|
|
237
|
+
process.stderr.write(`[minimal-agent memory] 本轮记忆收尾失败,不影响会话落盘:${(error as Error).message}\n`);
|
|
238
|
+
});
|
|
239
|
+
trace('memory_end');
|
|
240
|
+
if (persist) await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
215
241
|
}
|
|
216
242
|
}
|
|
@@ -76,12 +76,17 @@ export async function disposeDetachedSessionState(state) {
|
|
|
76
76
|
state.fileReads.entries.clear();
|
|
77
77
|
}
|
|
78
78
|
function prunePersistentStates(now, keepKey) {
|
|
79
|
+
// Capacity is a cache target, not authority to orphan running work. These
|
|
80
|
+
// sessions become evictable after their tasks settle or explicit disposal.
|
|
81
|
+
const evictable = (key, state) => key !== keepKey
|
|
82
|
+
&& ![...state.agentTasks.tasks.values()].some(task => task.status === 'running')
|
|
83
|
+
&& ![...state.backgroundTasks.tasks.values()].some(task => task.status === 'running');
|
|
79
84
|
const removable = [...persistentStates.entries()]
|
|
80
|
-
.filter(([key, entry]) => key
|
|
85
|
+
.filter(([key, entry]) => evictable(key, entry.state) && now - entry.lastUsedAt > MAX_IDLE_MS)
|
|
81
86
|
.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
|
|
82
87
|
while (persistentStates.size - removable.length > MAX_PERSISTENT_STATES) {
|
|
83
88
|
const next = [...persistentStates.entries()]
|
|
84
|
-
.filter(([key]) => key
|
|
89
|
+
.filter(([key, entry]) => evictable(key, entry.state) && !removable.some(([candidate]) => candidate === key))
|
|
85
90
|
.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt)[0];
|
|
86
91
|
if (!next)
|
|
87
92
|
break;
|
|
@@ -122,12 +122,17 @@ export async function disposeDetachedSessionState(state: SessionState): Promise<
|
|
|
122
122
|
}
|
|
123
123
|
|
|
124
124
|
function prunePersistentStates(now: number, keepKey: string): void {
|
|
125
|
+
// Capacity is a cache target, not authority to orphan running work. These
|
|
126
|
+
// sessions become evictable after their tasks settle or explicit disposal.
|
|
127
|
+
const evictable = (key: string, state: SessionState) => key !== keepKey
|
|
128
|
+
&& ![...state.agentTasks.tasks.values()].some(task => task.status === 'running')
|
|
129
|
+
&& ![...state.backgroundTasks.tasks.values()].some(task => task.status === 'running');
|
|
125
130
|
const removable = [...persistentStates.entries()]
|
|
126
|
-
.filter(([key, entry]) => key
|
|
131
|
+
.filter(([key, entry]) => evictable(key, entry.state) && now - entry.lastUsedAt > MAX_IDLE_MS)
|
|
127
132
|
.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
|
|
128
133
|
while (persistentStates.size - removable.length > MAX_PERSISTENT_STATES) {
|
|
129
134
|
const next = [...persistentStates.entries()]
|
|
130
|
-
.filter(([key]) => key
|
|
135
|
+
.filter(([key, entry]) => evictable(key, entry.state) && !removable.some(([candidate]) => candidate === key))
|
|
131
136
|
.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt)[0];
|
|
132
137
|
if (!next) break;
|
|
133
138
|
removable.push(next);
|
|
@@ -24,16 +24,15 @@
|
|
|
24
24
|
*/
|
|
25
25
|
import { z } from 'zod';
|
|
26
26
|
import { configService } from '../../config/configService.js';
|
|
27
|
-
import { CONFIG_LIMITS, normalizeLimited } from '../../config/numericLimits.js';
|
|
28
|
-
import { DEFAULT_ADVISOR_CONFIG } from '../../config/configDefaults.js';
|
|
29
27
|
import { expandAdvisorHistory } from '../../context/advisorHistory.js';
|
|
30
|
-
import { countMessagesTokens, estimateToolsTokens } from '../../context/tokenCounter.js';
|
|
28
|
+
import { countMessagesTokens, countTextTokens, estimateToolsTokens } from '../../context/tokenCounter.js';
|
|
31
29
|
import { completeGenerationTerminal } from '../../harness/generationReceipt.js';
|
|
32
30
|
import { chat } from '../../llm/client.js';
|
|
33
31
|
import { provenanceLabel } from '../../llm/messageProvenance.js';
|
|
34
32
|
import { derivePromptCacheContext } from '../../llm/promptCache.js';
|
|
35
33
|
import { CODE_REVIEW_RUBRIC } from '../../prompts/codeReview.js';
|
|
36
34
|
import { createSessionState } from '../../session/sessionState.js';
|
|
35
|
+
import { advisorCoordination } from './advisorCoordination.js';
|
|
37
36
|
import { safeSlice } from '../../utils/safeText.js';
|
|
38
37
|
import { ADVISOR_MAX_VERIFY_ROUNDS, checkAdvisorToolCall, clipVerifyResult, loadAdvisorVerifyTools, } from './advisorVerify.js';
|
|
39
38
|
import { toToolParameters } from '../../utils/zodToJson.js';
|
|
@@ -41,12 +40,11 @@ import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js';
|
|
|
41
40
|
import { ADVISOR_TOOL_DESCRIPTION } from './advisorDescription.js';
|
|
42
41
|
// ---------------- 1. Zod 输入 schema ----------------
|
|
43
42
|
const inputSchema = z.object({
|
|
43
|
+
purpose: z.enum(['independent', 'synthesis']).optional().describe('默认按当前交付做 synthesis,先核实依赖子任务;independent 须显式选择,仅用于已有证据上的独立问题,不依赖未返回报告。'),
|
|
44
|
+
depends_on: z.array(z.string().regex(/^agent_[0-9a-f-]{36}$/i)).max(32).optional().describe('本次咨询依赖的子任务 ID;须先获取报告并由主 Agent 验收。未就绪返回暂缓,不占用顾问请求。synthesis 未指定时检查当前交付的必要任务。'),
|
|
44
45
|
reviewMode: z.enum(['brief', 'full']).optional().describe('默认 brief 为重点第二意见;用户要求完整代码审查时用 full,并在 note 中说明变更审查/全项目审计、基线和覆盖范围。full 不扩大证据或输出预算,缺失时须报告未完成。'),
|
|
45
46
|
note: z
|
|
46
47
|
.string()
|
|
47
|
-
// 上限只做护栏:note 是执行助手主动强调的证据/疑点。真正的闸门是输入预算——
|
|
48
|
-
// note 超预算只会挤掉最旧的历史,不会炸请求。
|
|
49
|
-
.max(100_000, 'note 太长(>100000 字符)')
|
|
50
48
|
.optional()
|
|
51
49
|
.describe('可选:想让顾问重点挑战的疑点、起决定作用的证据,或放不进对话里的关键原文。顾问仅看到预算内材料;必要时补充决定性证据。'),
|
|
52
50
|
});
|
|
@@ -281,7 +279,13 @@ function fitAdvisorBudget(fixedHead, body, closing, inputBudget) {
|
|
|
281
279
|
let used = fixed + BUDGET_NOTICE_TOKENS;
|
|
282
280
|
const pinned = [];
|
|
283
281
|
if (firstUserIndex >= 0) {
|
|
284
|
-
|
|
282
|
+
// Do not collapse a nearly-fitting single request to 10% of the window.
|
|
283
|
+
// Prefer current requirements and recent evidence over an oversized first
|
|
284
|
+
// request; use the actual leftover space, not a fixed percentage quota.
|
|
285
|
+
const tailCost = countMessagesTokens(body.slice(firstUserIndex + 1));
|
|
286
|
+
const available = Math.max(0, inputBudget - used);
|
|
287
|
+
const anchor = Math.min(256, countMessagesTokens([body[firstUserIndex]]), available);
|
|
288
|
+
const first = fitMessage(body[firstUserIndex], available - Math.min(tailCost, available - anchor));
|
|
285
289
|
if (first) {
|
|
286
290
|
pinned.push(first);
|
|
287
291
|
used += countMessagesTokens([first]);
|
|
@@ -322,17 +326,22 @@ function fitAdvisorBudget(fixedHead, body, closing, inputBudget) {
|
|
|
322
326
|
return result;
|
|
323
327
|
}
|
|
324
328
|
/**
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
* 余量必须**随窗口放大**:本地估算是 chars/4(ASCII)+ 1/字(非 ASCII),对代码、JSON、
|
|
328
|
-
* 混排文本常低估 5–15%。旧公式 `min(4096, 10%)` 在 100 万窗口只留 4K,估算偏 1% 就超限,
|
|
329
|
-
* 服务商直接 `context_length_exceeded`;现在留 8% 窗口(至少 4096,且不超过 10%),
|
|
330
|
-
* 128K 窗口约 10K、100 万窗口约 80K。`reserved` 是 messages 之外的占用(核实工具 schema、
|
|
331
|
-
* 核实轮次回灌的结果)。
|
|
329
|
+
* 唯一容量来源:所选模型的窗口,扣除最大输出和实际工具 schema。
|
|
330
|
+
* 不再叠加独立配置配额或窗口比例折扣。估算误差由服务商明确超限后的有界重试纠正。
|
|
332
331
|
*/
|
|
333
332
|
export function advisorProviderInputBudget(contextWindow, maxTokens, reserved = 0) {
|
|
334
|
-
|
|
335
|
-
|
|
333
|
+
return Math.floor(contextWindow) - Math.ceil(maxTokens) - Math.max(0, Math.ceil(reserved));
|
|
334
|
+
}
|
|
335
|
+
/** Count only fields this protocol actually sends back on verification turns. */
|
|
336
|
+
export function countAdvisorRequestTokens(messages, provider, tools = []) {
|
|
337
|
+
let count = countMessagesTokens(messages) + estimateToolsTokens(tools);
|
|
338
|
+
if (!provider.apiFormat || provider.apiFormat === 'openai') {
|
|
339
|
+
for (const message of messages)
|
|
340
|
+
if (message.role === 'assistant') {
|
|
341
|
+
count += countTextTokens(message.reasoning_content ?? '') + countTextTokens(message.reasoning ?? '');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return count;
|
|
336
345
|
}
|
|
337
346
|
/**
|
|
338
347
|
* 等首个事件时的预填充宽限(毫秒):输入超过 10 万 token 的部分按约 5000 token/秒,最多 5 分钟。
|
|
@@ -400,9 +409,8 @@ export function buildAdvisorMessages(history, note, options = {}) {
|
|
|
400
409
|
};
|
|
401
410
|
const contextWindow = options.contextWindow ?? 1_000_000;
|
|
402
411
|
const maxTokens = options.maxTokens ?? 4096;
|
|
403
|
-
const configuredBudget = normalizeLimited(options.inputTokenBudget, CONFIG_LIMITS.advisorInputTokenBudget, DEFAULT_ADVISOR_CONFIG.inputTokenBudget);
|
|
404
412
|
const providerBudget = advisorProviderInputBudget(contextWindow, maxTokens, options.reservedTokens ?? 0);
|
|
405
|
-
const inputBudget = Math.min(
|
|
413
|
+
const inputBudget = Math.min(providerBudget, ...(options.hardInputCap !== undefined ? [Math.floor(options.hardInputCap)] : []));
|
|
406
414
|
if (inputBudget < 512)
|
|
407
415
|
throw new Error('顾问上下文窗口不足:请减少输出 token 上限或选择更大上下文模型。');
|
|
408
416
|
// 一切原样;只有放不进窗口时才收窄,且按固定顺序:更早请求的思考过程 → 最旧的整条消息。
|
|
@@ -486,6 +494,9 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
486
494
|
'本回合后续不要再次尝试自动调用 Advisor。',
|
|
487
495
|
};
|
|
488
496
|
}
|
|
497
|
+
const coordination = await advisorCoordination(input, ctx);
|
|
498
|
+
if (!coordination.ok)
|
|
499
|
+
return coordination;
|
|
489
500
|
if (ctx?.advisorCalls)
|
|
490
501
|
ctx.advisorCalls.used++;
|
|
491
502
|
const provider = advisor.provider;
|
|
@@ -497,7 +508,7 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
497
508
|
snapshot.config?.tools.openRouter?.apiKey,
|
|
498
509
|
snapshot.config?.tools.textToSpeech?.apiKey,
|
|
499
510
|
].filter((value) => !!value);
|
|
500
|
-
const note = input.note?.trim() || undefined;
|
|
511
|
+
const note = [input.note?.trim(), coordination.content].filter(Boolean).join('\n\n') || undefined;
|
|
501
512
|
// 有工作目录才给只读核实工具:没有 cwd 就没有「工作区」可限定(如无宿主上下文的手动咨询)。
|
|
502
513
|
const stillDelegated = (tool) => ctx?.delegationTools?.includes(tool)
|
|
503
514
|
&& (ctx.availableToolNames?.().has(tool.name) ?? true);
|
|
@@ -508,12 +519,11 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
508
519
|
const verificationState = verifyTools.length ? createSessionState() : undefined;
|
|
509
520
|
// 服务商报「超出上下文窗口」后收缩重试时才有值:按上次实际发出的估算量打折。
|
|
510
521
|
let hardInputCap;
|
|
511
|
-
const buildMessages = (canVerify
|
|
522
|
+
const buildMessages = (canVerify, history = ctx?.history ?? []) => buildAdvisorMessages(history, note, {
|
|
512
523
|
reviewMode: input.reviewMode,
|
|
513
524
|
supportsVision: advisor.supportsVision,
|
|
514
525
|
contextWindow: provider.contextWindow,
|
|
515
526
|
maxTokens: provider.maxTokens,
|
|
516
|
-
inputTokenBudget: advisor.inputTokenBudget,
|
|
517
527
|
conversationMode: ctx?.conversationMode,
|
|
518
528
|
background: ctx?.advisorBackground?.(),
|
|
519
529
|
redactSecrets: secrets,
|
|
@@ -523,12 +533,32 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
523
533
|
reservedTokens: canVerify ? estimateToolsTokens(verifyTools) : 0,
|
|
524
534
|
hardInputCap,
|
|
525
535
|
});
|
|
536
|
+
// Reuse the material already sent plus new observations. Don't re-add the
|
|
537
|
+
// project background/note or repeatedly normalize old provenance wrappers.
|
|
538
|
+
const reframeMessages = (history) => {
|
|
539
|
+
const system = advisorSystemMessage({ reviewMode: input.reviewMode, conversationMode: ctx?.conversationMode }, []);
|
|
540
|
+
const body = redactAdvisorHistory(history, secrets)
|
|
541
|
+
.filter(message => message.role !== 'system' && message.id !== 'advisor-reframe')
|
|
542
|
+
.map(message => message.role === 'tool' || (message.role === 'assistant' &&
|
|
543
|
+
(message.tool_calls?.length || message.reasoning || message.reasoning_content))
|
|
544
|
+
? normalizeAdvisorMessage(message, advisor.supportsVision === true) : message)
|
|
545
|
+
.filter((message) => message !== null);
|
|
546
|
+
const closing = { role: 'user', id: 'advisor-reframe',
|
|
547
|
+
content: '请基于保留的材料与刚才取得的核实证据给出意见;若存在省略,明确不能核实的部分,不再调用工具。' };
|
|
548
|
+
const limit = Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
549
|
+
const all = [system, ...body, closing];
|
|
550
|
+
return countMessagesTokens(all) <= limit ? all : fitAdvisorBudget([system], body, closing, limit);
|
|
551
|
+
};
|
|
526
552
|
let messages;
|
|
527
553
|
try {
|
|
528
554
|
messages = buildMessages(verifyTools.length > 0);
|
|
529
555
|
}
|
|
530
556
|
catch (error) {
|
|
531
|
-
|
|
557
|
+
// A schema must never make a viable text-only consultation fail.
|
|
558
|
+
if (!verifyTools.length)
|
|
559
|
+
throw error;
|
|
560
|
+
verifyTools.length = 0;
|
|
561
|
+
messages = buildMessages(false);
|
|
532
562
|
}
|
|
533
563
|
// 空闲超时:timeoutMs 是「没有任何新输出」的最长时间,不是总时长——顾问一直在产出
|
|
534
564
|
// (思考或写意见)就不该被掐断;预填充阶段没有输出,所以超大对话仍受它约束。
|
|
@@ -555,6 +585,8 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
555
585
|
const hardTimer = setTimeout(expire, hardCapMs);
|
|
556
586
|
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
|
557
587
|
let content = '';
|
|
588
|
+
let lastRequest = messages;
|
|
589
|
+
let lastRequestTokens = countAdvisorRequestTokens(messages, provider, verifyTools);
|
|
558
590
|
let reasoningChars = 0;
|
|
559
591
|
// 发布端节流:阶段切换(思考中→整理意见)立即发保证切换及时可见,同阶段后续 delta
|
|
560
592
|
// 以 ≥200ms 门控,与主循环流式 setState 的 100ms 节流纪律同量级。
|
|
@@ -579,7 +611,9 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
579
611
|
const toolCalls = [];
|
|
580
612
|
let completeStream = false;
|
|
581
613
|
// 每次请求(含核实轮)重新等首个事件:这一轮的输入规模决定它的预填充宽限。
|
|
582
|
-
|
|
614
|
+
lastRequest = advisorMessages;
|
|
615
|
+
lastRequestTokens = countAdvisorRequestTokens(advisorMessages, provider, tools);
|
|
616
|
+
armFirstEventWait(lastRequestTokens);
|
|
583
617
|
for await (const ev of chatFn({
|
|
584
618
|
provider,
|
|
585
619
|
messages: advisorMessages,
|
|
@@ -635,16 +669,25 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
635
669
|
let conversation = messages;
|
|
636
670
|
let offered = verifyTools.length > 0;
|
|
637
671
|
for (let round = 0;; round++) {
|
|
638
|
-
//
|
|
639
|
-
|
|
640
|
-
const roomForVerify = countMessagesTokens(conversation) + 30_000 <=
|
|
672
|
+
// Only account for the actual request. Future results are fitted when they arrive.
|
|
673
|
+
const roomForVerify = countAdvisorRequestTokens(conversation, provider, verifyTools) <=
|
|
641
674
|
Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
642
675
|
const withTools = offered && round < ADVISOR_MAX_VERIFY_ROUNDS && roomForVerify;
|
|
643
676
|
let turn;
|
|
644
677
|
try {
|
|
645
678
|
const tools = withTools ? verifyTools : [];
|
|
646
679
|
const system = advisorSystemMessage({ reviewMode: input.reviewMode, conversationMode: ctx?.conversationMode }, tools.map(tool => tool.name));
|
|
647
|
-
|
|
680
|
+
const request = [system, ...conversation.slice(1)];
|
|
681
|
+
const limit = Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
682
|
+
if (countAdvisorRequestTokens(request, provider, tools) > limit) {
|
|
683
|
+
// Keep the evidence just obtained, not the original pre-verification history.
|
|
684
|
+
// Reframe paired tool traffic as attributed review material before clipping.
|
|
685
|
+
offered = false;
|
|
686
|
+
conversation = reframeMessages(conversation);
|
|
687
|
+
ctx?.reportProgress?.('顾问核实材料接近模型窗口,保留近期证据转为纯评审…');
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
turn = await streamOnce(request, tools);
|
|
648
691
|
}
|
|
649
692
|
catch (error) {
|
|
650
693
|
// 任何一轮核实请求失败(服务商拒绝工具参数、要求回传思考内容等)都退回纯评审:
|
|
@@ -652,7 +695,7 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
652
695
|
// 超限不是「服务商不认工具参数」:退回纯评审只会原样再超一次,交给外层收缩重建。
|
|
653
696
|
if (withTools && !(error instanceof IncompleteAdvisorStream) && !combinedSignal.aborted && !isAdvisorContextOverflow(error)) {
|
|
654
697
|
offered = false;
|
|
655
|
-
conversation =
|
|
698
|
+
conversation = reframeMessages(conversation);
|
|
656
699
|
round = -1;
|
|
657
700
|
continue;
|
|
658
701
|
}
|
|
@@ -722,10 +765,10 @@ export async function runAdvisor(input, signal, ctx, chatFn = chat, runtime = {}
|
|
|
722
765
|
catch (e) {
|
|
723
766
|
if (shrink >= 2 || combinedSignal.aborted || !isAdvisorContextOverflow(e))
|
|
724
767
|
throw e;
|
|
725
|
-
hardInputCap = advisorShrunkInputCap(e,
|
|
768
|
+
hardInputCap = advisorShrunkInputCap(e, lastRequestTokens, shrink);
|
|
726
769
|
ctx?.reportProgress?.('顾问上下文超出模型窗口,缩减材料后重试…');
|
|
727
770
|
verifyTools.length = 0;
|
|
728
|
-
messages =
|
|
771
|
+
messages = reframeMessages(lastRequest);
|
|
729
772
|
}
|
|
730
773
|
}
|
|
731
774
|
}
|
|
@@ -26,17 +26,16 @@
|
|
|
26
26
|
import { z } from 'zod';
|
|
27
27
|
|
|
28
28
|
import { configService } from '../../config/configService.js';
|
|
29
|
-
import { CONFIG_LIMITS, normalizeLimited } from '../../config/numericLimits.js';
|
|
30
|
-
import { DEFAULT_ADVISOR_CONFIG } from '../../config/configDefaults.js';
|
|
31
29
|
import { expandAdvisorHistory } from '../../context/advisorHistory.js';
|
|
32
|
-
import { countMessagesTokens, estimateToolsTokens } from '../../context/tokenCounter.js';
|
|
30
|
+
import { countMessagesTokens, countTextTokens, estimateToolsTokens } from '../../context/tokenCounter.js';
|
|
33
31
|
import { completeGenerationTerminal } from '../../harness/generationReceipt.js';
|
|
34
32
|
import { chat } from '../../llm/client.js';
|
|
35
33
|
import { provenanceLabel } from '../../llm/messageProvenance.js';
|
|
36
34
|
import { derivePromptCacheContext } from '../../llm/promptCache.js';
|
|
37
35
|
import { CODE_REVIEW_RUBRIC } from '../../prompts/codeReview.js';
|
|
38
36
|
import { createSessionState } from '../../session/sessionState.js';
|
|
39
|
-
import type { Message, Tool, ToolCall, ToolCallContext, ToolResult } from '../../types.js';
|
|
37
|
+
import type { Message, Provider, Tool, ToolCall, ToolCallContext, ToolResult } from '../../types.js';
|
|
38
|
+
import { advisorCoordination } from './advisorCoordination.js';
|
|
40
39
|
import { safeSlice } from '../../utils/safeText.js';
|
|
41
40
|
import {
|
|
42
41
|
ADVISOR_MAX_VERIFY_ROUNDS,
|
|
@@ -50,12 +49,11 @@ import { ADVISOR_TOOL_DESCRIPTION } from './advisorDescription.js';
|
|
|
50
49
|
|
|
51
50
|
// ---------------- 1. Zod 输入 schema ----------------
|
|
52
51
|
const inputSchema = z.object({
|
|
52
|
+
purpose: z.enum(['independent', 'synthesis']).optional().describe('默认按当前交付做 synthesis,先核实依赖子任务;independent 须显式选择,仅用于已有证据上的独立问题,不依赖未返回报告。'),
|
|
53
|
+
depends_on: z.array(z.string().regex(/^agent_[0-9a-f-]{36}$/i)).max(32).optional().describe('本次咨询依赖的子任务 ID;须先获取报告并由主 Agent 验收。未就绪返回暂缓,不占用顾问请求。synthesis 未指定时检查当前交付的必要任务。'),
|
|
53
54
|
reviewMode: z.enum(['brief', 'full']).optional().describe('默认 brief 为重点第二意见;用户要求完整代码审查时用 full,并在 note 中说明变更审查/全项目审计、基线和覆盖范围。full 不扩大证据或输出预算,缺失时须报告未完成。'),
|
|
54
55
|
note: z
|
|
55
56
|
.string()
|
|
56
|
-
// 上限只做护栏:note 是执行助手主动强调的证据/疑点。真正的闸门是输入预算——
|
|
57
|
-
// note 超预算只会挤掉最旧的历史,不会炸请求。
|
|
58
|
-
.max(100_000, 'note 太长(>100000 字符)')
|
|
59
57
|
.optional()
|
|
60
58
|
.describe('可选:想让顾问重点挑战的疑点、起决定作用的证据,或放不进对话里的关键原文。顾问仅看到预算内材料;必要时补充决定性证据。'),
|
|
61
59
|
});
|
|
@@ -317,7 +315,13 @@ function fitAdvisorBudget(fixedHead: Message[], body: Message[], closing: Messag
|
|
|
317
315
|
let used = fixed + BUDGET_NOTICE_TOKENS;
|
|
318
316
|
const pinned: Message[] = [];
|
|
319
317
|
if (firstUserIndex >= 0) {
|
|
320
|
-
|
|
318
|
+
// Do not collapse a nearly-fitting single request to 10% of the window.
|
|
319
|
+
// Prefer current requirements and recent evidence over an oversized first
|
|
320
|
+
// request; use the actual leftover space, not a fixed percentage quota.
|
|
321
|
+
const tailCost = countMessagesTokens(body.slice(firstUserIndex + 1));
|
|
322
|
+
const available = Math.max(0, inputBudget - used);
|
|
323
|
+
const anchor = Math.min(256, countMessagesTokens([body[firstUserIndex]!]), available);
|
|
324
|
+
const first = fitMessage(body[firstUserIndex]!, available - Math.min(tailCost, available - anchor));
|
|
321
325
|
if (first) {
|
|
322
326
|
pinned.push(first);
|
|
323
327
|
used += countMessagesTokens([first]);
|
|
@@ -352,17 +356,22 @@ function fitAdvisorBudget(fixedHead: Message[], body: Message[], closing: Messag
|
|
|
352
356
|
}
|
|
353
357
|
|
|
354
358
|
/**
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
* 余量必须**随窗口放大**:本地估算是 chars/4(ASCII)+ 1/字(非 ASCII),对代码、JSON、
|
|
358
|
-
* 混排文本常低估 5–15%。旧公式 `min(4096, 10%)` 在 100 万窗口只留 4K,估算偏 1% 就超限,
|
|
359
|
-
* 服务商直接 `context_length_exceeded`;现在留 8% 窗口(至少 4096,且不超过 10%),
|
|
360
|
-
* 128K 窗口约 10K、100 万窗口约 80K。`reserved` 是 messages 之外的占用(核实工具 schema、
|
|
361
|
-
* 核实轮次回灌的结果)。
|
|
359
|
+
* 唯一容量来源:所选模型的窗口,扣除最大输出和实际工具 schema。
|
|
360
|
+
* 不再叠加独立配置配额或窗口比例折扣。估算误差由服务商明确超限后的有界重试纠正。
|
|
362
361
|
*/
|
|
363
362
|
export function advisorProviderInputBudget(contextWindow: number, maxTokens: number, reserved = 0): number {
|
|
364
|
-
|
|
365
|
-
|
|
363
|
+
return Math.floor(contextWindow) - Math.ceil(maxTokens) - Math.max(0, Math.ceil(reserved));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Count only fields this protocol actually sends back on verification turns. */
|
|
367
|
+
export function countAdvisorRequestTokens(messages: Message[], provider: Pick<Provider, 'apiFormat'>, tools: Tool[] = []): number {
|
|
368
|
+
let count = countMessagesTokens(messages) + estimateToolsTokens(tools);
|
|
369
|
+
if (!provider.apiFormat || provider.apiFormat === 'openai') {
|
|
370
|
+
for (const message of messages) if (message.role === 'assistant') {
|
|
371
|
+
count += countTextTokens(message.reasoning_content ?? '') + countTextTokens(message.reasoning ?? '');
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return count;
|
|
366
375
|
}
|
|
367
376
|
|
|
368
377
|
/**
|
|
@@ -410,6 +419,7 @@ export function buildAdvisorMessages(
|
|
|
410
419
|
supportsVision?: boolean;
|
|
411
420
|
contextWindow?: number;
|
|
412
421
|
maxTokens?: number;
|
|
422
|
+
/** @deprecated Ignored. Capacity comes exclusively from the selected model. */
|
|
413
423
|
inputTokenBudget?: number;
|
|
414
424
|
redactSecrets?: readonly string[];
|
|
415
425
|
conversationMode?: 'private' | 'group';
|
|
@@ -458,11 +468,8 @@ export function buildAdvisorMessages(
|
|
|
458
468
|
|
|
459
469
|
const contextWindow = options.contextWindow ?? 1_000_000;
|
|
460
470
|
const maxTokens = options.maxTokens ?? 4096;
|
|
461
|
-
const configuredBudget = normalizeLimited(
|
|
462
|
-
options.inputTokenBudget, CONFIG_LIMITS.advisorInputTokenBudget, DEFAULT_ADVISOR_CONFIG.inputTokenBudget);
|
|
463
471
|
const providerBudget = advisorProviderInputBudget(contextWindow, maxTokens, options.reservedTokens ?? 0);
|
|
464
472
|
const inputBudget = Math.min(
|
|
465
|
-
configuredBudget,
|
|
466
473
|
providerBudget,
|
|
467
474
|
...(options.hardInputCap !== undefined ? [Math.floor(options.hardInputCap)] : []),
|
|
468
475
|
);
|
|
@@ -582,6 +589,8 @@ export async function runAdvisor(
|
|
|
582
589
|
};
|
|
583
590
|
}
|
|
584
591
|
|
|
592
|
+
const coordination = await advisorCoordination(input, ctx);
|
|
593
|
+
if (!coordination.ok) return coordination;
|
|
585
594
|
if (ctx?.advisorCalls) ctx.advisorCalls.used++;
|
|
586
595
|
|
|
587
596
|
const provider = advisor.provider;
|
|
@@ -593,7 +602,7 @@ export async function runAdvisor(
|
|
|
593
602
|
snapshot.config?.tools.openRouter?.apiKey,
|
|
594
603
|
snapshot.config?.tools.textToSpeech?.apiKey,
|
|
595
604
|
].filter((value): value is string => !!value);
|
|
596
|
-
const note = input.note?.trim() || undefined;
|
|
605
|
+
const note = [input.note?.trim(), coordination.content].filter(Boolean).join('\n\n') || undefined;
|
|
597
606
|
// 有工作目录才给只读核实工具:没有 cwd 就没有「工作区」可限定(如无宿主上下文的手动咨询)。
|
|
598
607
|
const stillDelegated = (tool: Tool) => ctx?.delegationTools?.includes(tool)
|
|
599
608
|
&& (ctx.availableToolNames?.().has(tool.name) ?? true);
|
|
@@ -604,13 +613,12 @@ export async function runAdvisor(
|
|
|
604
613
|
const verificationState = verifyTools.length ? createSessionState() : undefined;
|
|
605
614
|
// 服务商报「超出上下文窗口」后收缩重试时才有值:按上次实际发出的估算量打折。
|
|
606
615
|
let hardInputCap: number | undefined;
|
|
607
|
-
const buildMessages = (canVerify: boolean): Message[] =>
|
|
608
|
-
buildAdvisorMessages(
|
|
616
|
+
const buildMessages = (canVerify: boolean, history = ctx?.history ?? []): Message[] =>
|
|
617
|
+
buildAdvisorMessages(history, note, {
|
|
609
618
|
reviewMode: input.reviewMode,
|
|
610
619
|
supportsVision: advisor.supportsVision,
|
|
611
620
|
contextWindow: provider.contextWindow,
|
|
612
621
|
maxTokens: provider.maxTokens,
|
|
613
|
-
inputTokenBudget: advisor.inputTokenBudget,
|
|
614
622
|
conversationMode: ctx?.conversationMode,
|
|
615
623
|
background: ctx?.advisorBackground?.(),
|
|
616
624
|
redactSecrets: secrets,
|
|
@@ -620,11 +628,30 @@ export async function runAdvisor(
|
|
|
620
628
|
reservedTokens: canVerify ? estimateToolsTokens(verifyTools) : 0,
|
|
621
629
|
hardInputCap,
|
|
622
630
|
});
|
|
631
|
+
// Reuse the material already sent plus new observations. Don't re-add the
|
|
632
|
+
// project background/note or repeatedly normalize old provenance wrappers.
|
|
633
|
+
const reframeMessages = (history: Message[]): Message[] => {
|
|
634
|
+
const system = advisorSystemMessage({ reviewMode: input.reviewMode, conversationMode: ctx?.conversationMode }, []);
|
|
635
|
+
const body = redactAdvisorHistory(history, secrets)
|
|
636
|
+
.filter(message => message.role !== 'system' && message.id !== 'advisor-reframe')
|
|
637
|
+
.map(message => message.role === 'tool' || (message.role === 'assistant' &&
|
|
638
|
+
(message.tool_calls?.length || message.reasoning || message.reasoning_content))
|
|
639
|
+
? normalizeAdvisorMessage(message, advisor.supportsVision === true) : message)
|
|
640
|
+
.filter((message): message is Message => message !== null);
|
|
641
|
+
const closing: Message = { role: 'user', id: 'advisor-reframe',
|
|
642
|
+
content: '请基于保留的材料与刚才取得的核实证据给出意见;若存在省略,明确不能核实的部分,不再调用工具。' };
|
|
643
|
+
const limit = Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
644
|
+
const all = [system, ...body, closing];
|
|
645
|
+
return countMessagesTokens(all) <= limit ? all : fitAdvisorBudget([system], body, closing, limit);
|
|
646
|
+
};
|
|
623
647
|
let messages: Message[];
|
|
624
648
|
try {
|
|
625
649
|
messages = buildMessages(verifyTools.length > 0);
|
|
626
650
|
} catch (error) {
|
|
627
|
-
|
|
651
|
+
// A schema must never make a viable text-only consultation fail.
|
|
652
|
+
if (!verifyTools.length) throw error;
|
|
653
|
+
verifyTools.length = 0;
|
|
654
|
+
messages = buildMessages(false);
|
|
628
655
|
}
|
|
629
656
|
|
|
630
657
|
// 空闲超时:timeoutMs 是「没有任何新输出」的最长时间,不是总时长——顾问一直在产出
|
|
@@ -653,6 +680,8 @@ export async function runAdvisor(
|
|
|
653
680
|
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
|
654
681
|
|
|
655
682
|
let content = '';
|
|
683
|
+
let lastRequest = messages;
|
|
684
|
+
let lastRequestTokens = countAdvisorRequestTokens(messages, provider, verifyTools);
|
|
656
685
|
let reasoningChars = 0;
|
|
657
686
|
// 发布端节流:阶段切换(思考中→整理意见)立即发保证切换及时可见,同阶段后续 delta
|
|
658
687
|
// 以 ≥200ms 门控,与主循环流式 setState 的 100ms 节流纪律同量级。
|
|
@@ -677,7 +706,9 @@ export async function runAdvisor(
|
|
|
677
706
|
const toolCalls: ToolCall[] = [];
|
|
678
707
|
let completeStream = false;
|
|
679
708
|
// 每次请求(含核实轮)重新等首个事件:这一轮的输入规模决定它的预填充宽限。
|
|
680
|
-
|
|
709
|
+
lastRequest = advisorMessages;
|
|
710
|
+
lastRequestTokens = countAdvisorRequestTokens(advisorMessages, provider, tools);
|
|
711
|
+
armFirstEventWait(lastRequestTokens);
|
|
681
712
|
for await (const ev of chatFn({
|
|
682
713
|
provider,
|
|
683
714
|
messages: advisorMessages,
|
|
@@ -726,23 +757,32 @@ export async function runAdvisor(
|
|
|
726
757
|
let conversation = messages;
|
|
727
758
|
let offered = verifyTools.length > 0;
|
|
728
759
|
for (let round = 0; ; round++) {
|
|
729
|
-
//
|
|
730
|
-
|
|
731
|
-
const roomForVerify = countMessagesTokens(conversation) + 30_000 <=
|
|
760
|
+
// Only account for the actual request. Future results are fitted when they arrive.
|
|
761
|
+
const roomForVerify = countAdvisorRequestTokens(conversation, provider, verifyTools) <=
|
|
732
762
|
Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
733
763
|
const withTools = offered && round < ADVISOR_MAX_VERIFY_ROUNDS && roomForVerify;
|
|
734
764
|
let turn: StreamTurn;
|
|
735
765
|
try {
|
|
736
766
|
const tools = withTools ? verifyTools : [];
|
|
737
767
|
const system = advisorSystemMessage({ reviewMode: input.reviewMode, conversationMode: ctx?.conversationMode }, tools.map(tool => tool.name));
|
|
738
|
-
|
|
768
|
+
const request = [system, ...conversation.slice(1)];
|
|
769
|
+
const limit = Math.min(advisorProviderInputBudget(provider.contextWindow, provider.maxTokens ?? 4096), hardInputCap ?? Infinity);
|
|
770
|
+
if (countAdvisorRequestTokens(request, provider, tools) > limit) {
|
|
771
|
+
// Keep the evidence just obtained, not the original pre-verification history.
|
|
772
|
+
// Reframe paired tool traffic as attributed review material before clipping.
|
|
773
|
+
offered = false;
|
|
774
|
+
conversation = reframeMessages(conversation);
|
|
775
|
+
ctx?.reportProgress?.('顾问核实材料接近模型窗口,保留近期证据转为纯评审…');
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
turn = await streamOnce(request, tools);
|
|
739
779
|
} catch (error) {
|
|
740
780
|
// 任何一轮核实请求失败(服务商拒绝工具参数、要求回传思考内容等)都退回纯评审:
|
|
741
781
|
// 改动之前单轮咨询是能成功的,加了核实不能让它反而整体失败。
|
|
742
782
|
// 超限不是「服务商不认工具参数」:退回纯评审只会原样再超一次,交给外层收缩重建。
|
|
743
783
|
if (withTools && !(error instanceof IncompleteAdvisorStream) && !combinedSignal.aborted && !isAdvisorContextOverflow(error)) {
|
|
744
784
|
offered = false;
|
|
745
|
-
conversation =
|
|
785
|
+
conversation = reframeMessages(conversation);
|
|
746
786
|
round = -1;
|
|
747
787
|
continue;
|
|
748
788
|
}
|
|
@@ -806,10 +846,10 @@ export async function runAdvisor(
|
|
|
806
846
|
break;
|
|
807
847
|
} catch (e) {
|
|
808
848
|
if (shrink >= 2 || combinedSignal.aborted || !isAdvisorContextOverflow(e)) throw e;
|
|
809
|
-
hardInputCap = advisorShrunkInputCap(e,
|
|
849
|
+
hardInputCap = advisorShrunkInputCap(e, lastRequestTokens, shrink);
|
|
810
850
|
ctx?.reportProgress?.('顾问上下文超出模型窗口,缩减材料后重试…');
|
|
811
851
|
verifyTools.length = 0;
|
|
812
|
-
messages =
|
|
852
|
+
messages = reframeMessages(lastRequest);
|
|
813
853
|
}
|
|
814
854
|
}
|
|
815
855
|
} catch (e) {
|