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.
- package/README.md +16 -3
- package/package.json +1 -1
- 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/childWorkflow.test.ts +19 -0
- package/src/advisor/README.md +7 -3
- package/src/advisor/advisorNudge.js +3 -3
- package/src/advisor/advisorNudge.ts +3 -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/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/configDiagnostics.js +7 -3
- package/src/config/configDiagnostics.ts +6 -3
- 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/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 +4 -2
- package/src/loop.ts +4 -2
- package/src/main.js +40 -45
- package/src/main.tsx +33 -52
- package/src/plugins/artifactDelivery.js +76 -0
- package/src/plugins/artifactDelivery.ts +76 -0
- package/src/plugins/pluginApi.ts +2 -0
- package/src/plugins/pluginRunner.js +2 -0
- package/src/plugins/pluginRunner.ts +3 -0
- package/src/prompts/delegation.js +1 -1
- package/src/prompts/delegation.ts +1 -1
- package/src/prompts/policyRegistry.js +7 -6
- package/src/prompts/policyRegistry.ts +7 -6
- 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/runTurn.js +24 -3
- package/src/session/runTurn.ts +24 -3
- package/src/tools/advisor/advisor.js +1 -1
- package/src/tools/advisor/advisor.ts +1 -1
- package/src/tools/advisor/advisorCoordination.js +3 -2
- package/src/tools/advisor/advisorCoordination.ts +3 -2
- 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 +3 -0
- package/src/tools/agent/agent.ts +3 -0
- 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 +23 -5
- package/src/tools/agent/agentTypes.js +1 -1
- package/src/tools/agent/agentTypes.ts +1 -1
- 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/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/powershell/powershell.js +2 -0
- package/src/tools/powershell/powershell.ts +2 -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 +3 -3
- package/src/tools/toolPromptGuides.ts +3 -3
- package/src/tools/webfetch/webfetch.js +1 -1
- package/src/tools/webfetch/webfetch.ts +1 -1
- package/src/types.ts +4 -0
- package/src/ui/InputBox.js +2 -2
- package/src/ui/InputBox.tsx +2 -2
- 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 +22 -2
- package/src/ui/activityPresentation.ts +21 -2
- 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/useChat.js +41 -25
- package/src/ui/hooks/useChat.ts +30 -23
- package/src/web/protocol.ts +3 -2
- package/src/cli/wizards/advisorWizard.js +0 -152
- package/src/cli/wizards/advisorWizard.tsx +0 -203
package/src/main.tsx
CHANGED
|
@@ -63,7 +63,8 @@ import { BROWSER_TOOL_NAMES } from './runtime/agentRuntimeContext.js';
|
|
|
63
63
|
import { memoryToolAllowed } from './runtime/agentRuntimeContext.js';
|
|
64
64
|
import type { Message } from './types.js';
|
|
65
65
|
import { Root } from './ui/Root.js';
|
|
66
|
-
import { runPrintMode } from './cli/print.js';
|
|
66
|
+
import { emitJsonResult, runPrintMode } from './cli/print.js';
|
|
67
|
+
import { createCliLifecycle, flushCliOutput } from './cli/lifecycle.js';
|
|
67
68
|
import { resolveBrowserCliMode, disposeLocalBrowsers } from './cli/browser.js';
|
|
68
69
|
import { runStreamJsonMode } from './cli/streamJson.js';
|
|
69
70
|
import { extractFlagValue, normalizeArgs } from './cli/args.js';
|
|
@@ -156,8 +157,10 @@ async function main(): Promise<void> {
|
|
|
156
157
|
|
|
157
158
|
if (isPrintMode) {
|
|
158
159
|
// 先把输出格式解析出来——provider 缺失分支也要按 json 契约给信号。
|
|
159
|
-
//
|
|
160
|
+
// 输出协议拼错必须失败,不能静默回落 text 破坏宿主协议。
|
|
160
161
|
const rawFormat = extractFlagValue(args, ['--output-format']);
|
|
162
|
+
if (args.includes('--output-format') && !['text', 'json', 'stream-json'].includes(rawFormat ?? ''))
|
|
163
|
+
throw new Error('--output-format 只接受 text、json 或 stream-json');
|
|
161
164
|
// text(默认,逐字节向后兼容)/ json(一行结局契约)/ stream-json(逐行 LoopEvent,webchat broker 用)
|
|
162
165
|
const outputFormat: 'text' | 'json' | 'stream-json' =
|
|
163
166
|
rawFormat === 'json'
|
|
@@ -165,10 +168,12 @@ async function main(): Promise<void> {
|
|
|
165
168
|
: rawFormat === 'stream-json'
|
|
166
169
|
? 'stream-json'
|
|
167
170
|
: 'text';
|
|
168
|
-
//
|
|
171
|
+
// 未指定走内核默认;指定时拒绝缺值、小数、负数和数字后缀。
|
|
169
172
|
const rawMaxTurns = extractFlagValue(args, ['--max-turns']);
|
|
170
173
|
const parsedMaxTurns =
|
|
171
|
-
rawMaxTurns !== undefined ? Number
|
|
174
|
+
rawMaxTurns !== undefined ? Number(rawMaxTurns) : Number.NaN;
|
|
175
|
+
if (args.includes('--max-turns') && (!Number.isSafeInteger(parsedMaxTurns) || parsedMaxTurns <= 0))
|
|
176
|
+
throw new Error('--max-turns 必须是正整数');
|
|
172
177
|
const maxTurns = Number.isNaN(parsedMaxTurns) ? undefined : parsedMaxTurns;
|
|
173
178
|
|
|
174
179
|
// -s/--session <id>:选定同 cwd 下的哪个 session;缺省 'default'(向后兼容,
|
|
@@ -180,51 +185,18 @@ async function main(): Promise<void> {
|
|
|
180
185
|
extractFlagValue(args, ['-s', '--session']) ?? 'default',
|
|
181
186
|
);
|
|
182
187
|
} catch (error) {
|
|
183
|
-
|
|
184
|
-
process.exitCode = 2;
|
|
185
|
-
return;
|
|
188
|
+
throw new Error(`无效的 --session:${(error as Error).message}`);
|
|
186
189
|
}
|
|
187
190
|
await workspaceIndexService.register(getWorkingDir()).catch(() => {});
|
|
188
|
-
const sessionFile = sessionFileFor(getWorkingDir(), sessionId);
|
|
191
|
+
const sessionFile = process.env.MINIMAL_AGENT_CONTEXT_FILE || sessionFileFor(getWorkingDir(), sessionId);
|
|
189
192
|
|
|
190
193
|
// CLI 非交互模式:先 env,再 ~/.minimal-agent/config.json fallback;都没就退出
|
|
191
194
|
// (宿主 spawn 子进程时通常没 export env,靠 TUI 向导写出的 config.json 持久化)
|
|
192
195
|
const provider = await loadProviderLayered();
|
|
193
|
-
if (!provider)
|
|
194
|
-
// json 模式:先给宿主一行结构化信号(stop_reason='config_error'),再退出。
|
|
195
|
-
// 人类可读的中文提示仍走 stderr(json 契约只占 stdout 那一行)。
|
|
196
|
-
if (outputFormat === 'json') {
|
|
197
|
-
console.log(
|
|
198
|
-
JSON.stringify({
|
|
199
|
-
ok: false,
|
|
200
|
-
result: '',
|
|
201
|
-
is_error: true,
|
|
202
|
-
stop_reason: 'config_error',
|
|
203
|
-
num_turns: 0,
|
|
204
|
-
error: 'provider config not found',
|
|
205
|
-
}),
|
|
206
|
-
);
|
|
207
|
-
} else if (outputFormat === 'stream-json') {
|
|
208
|
-
// stream-json:吐一行 error 事件(webchat 前端识别为致命错误)
|
|
209
|
-
console.log(
|
|
210
|
-
JSON.stringify({
|
|
211
|
-
type: 'error',
|
|
212
|
-
error: 'provider config not found',
|
|
213
|
-
code: 'llm_error',
|
|
214
|
-
}),
|
|
215
|
-
);
|
|
216
|
-
}
|
|
217
|
-
process.stderr.write(
|
|
218
|
-
`\n未找到 provider 配置。\n\n` +
|
|
219
|
-
`请二选一:\n` +
|
|
220
|
-
` 1. 设置环境变量 MINIMAL_AGENT_BASE_URL / MINIMAL_AGENT_API_KEY / MINIMAL_AGENT_MODEL\n` +
|
|
221
|
-
` 2. 先直接运行 \`minimal-agent\`(TUI)在首次配置菜单里配好基座模型;菜单会写出 ~/.minimal-agent/config.json,之后 -p 模式自动复用\n\n`,
|
|
222
|
-
);
|
|
223
|
-
process.exit(1);
|
|
224
|
-
}
|
|
196
|
+
if (!provider) throw new Error('未找到 provider 配置。请设置 MINIMAL_AGENT_BASE_URL / MINIMAL_AGENT_API_KEY / MINIMAL_AGENT_MODEL,或先运行 TUI 配置向导。');
|
|
225
197
|
|
|
226
198
|
// stream-json 的 stdin 是双工控制通道(宿主可回灌 ask_answer),所以它**能**交互提问;
|
|
227
|
-
// text/json 的 `-p` 不能——
|
|
199
|
+
// text/json 的 `-p` 不能——AskUserQuestion 必须明确返回 interaction_unavailable。
|
|
228
200
|
// 否则模型会以为可以停下来等用户选。
|
|
229
201
|
const verbose = args.includes('--verbose') || args.includes('-v');
|
|
230
202
|
// 信任边界收敛在这一处:两个入口都不再自证「我是本机主人」(见 cli/memoryAccess.ts)。
|
|
@@ -238,9 +210,7 @@ async function main(): Promise<void> {
|
|
|
238
210
|
computerUseTraceDir = resolveComputerUseTraceDir(args);
|
|
239
211
|
browserMode = resolveBrowserCliMode(args);
|
|
240
212
|
} catch (error) {
|
|
241
|
-
|
|
242
|
-
process.exitCode = 2;
|
|
243
|
-
return;
|
|
213
|
+
throw new Error(`参数错误:${(error as Error).message}`);
|
|
244
214
|
}
|
|
245
215
|
if (computerUseTraceDir) {
|
|
246
216
|
process.stderr.write(
|
|
@@ -255,10 +225,11 @@ async function main(): Promise<void> {
|
|
|
255
225
|
(tool.name !== 'ComputerUse' || computerUseMode !== 'disabled') &&
|
|
256
226
|
(browserEnabled || !BROWSER_TOOL_NAMES.has(tool.name)),
|
|
257
227
|
);
|
|
258
|
-
const initialHistory =
|
|
228
|
+
const initialHistory = outputFormat === 'stream-json' && args.includes('--compact')
|
|
229
|
+
? await buildInitialHistory(sessionFile, visibleTools) : [];
|
|
259
230
|
// stream-json 走独立流式模式(webchat broker / 网关用);text/json 仍走原 runPrintMode(契约不变)。
|
|
260
231
|
if (outputFormat === 'stream-json') {
|
|
261
|
-
await runStreamJsonMode(provider, args, initialHistory, {
|
|
232
|
+
process.exitCode = await runStreamJsonMode(provider, args, initialHistory, {
|
|
262
233
|
maxTurns,
|
|
263
234
|
compact: args.includes('--compact'),
|
|
264
235
|
sessionFile,
|
|
@@ -270,7 +241,7 @@ async function main(): Promise<void> {
|
|
|
270
241
|
});
|
|
271
242
|
return;
|
|
272
243
|
}
|
|
273
|
-
await runPrintMode(provider, args, initialHistory, {
|
|
244
|
+
process.exitCode = await runPrintMode(provider, args, initialHistory, {
|
|
274
245
|
verbose,
|
|
275
246
|
outputFormat,
|
|
276
247
|
maxTurns,
|
|
@@ -362,6 +333,7 @@ minimal-agent - 轻量级 AI 编程助手
|
|
|
362
333
|
OpenAI 兼容图片参数:限制最长边像素
|
|
363
334
|
--clear 清空当前工作目录的会话(归档 + 清空)后退出
|
|
364
335
|
--compact 与 -p --output-format stream-json 连用:压缩当前会话
|
|
336
|
+
--compact-instructions <文本> 手动压缩的保留重点(最多 8,000 字符)
|
|
365
337
|
--workspace-doctor 只读诊断全局工作区索引、Session 数量和孤立历史
|
|
366
338
|
-h, --help 显示帮助信息
|
|
367
339
|
|
|
@@ -386,9 +358,18 @@ minimal-agent - 轻量级 AI 编程助手
|
|
|
386
358
|
`);
|
|
387
359
|
}
|
|
388
360
|
|
|
389
|
-
main().catch((
|
|
390
|
-
process.
|
|
391
|
-
|
|
392
|
-
);
|
|
393
|
-
|
|
361
|
+
main().catch(async (error) => {
|
|
362
|
+
const args = normalizeArgs(process.argv.slice(2));
|
|
363
|
+
const format = extractFlagValue(args, ['--output-format']);
|
|
364
|
+
const lifecycle = createCliLifecycle();
|
|
365
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
366
|
+
try {
|
|
367
|
+
if ((args.includes('-p') || args.includes('--print')) && format === 'json') {
|
|
368
|
+
emitJsonResult({ buffer: '', numTurns: 0, stopReason: 'config_error', error: message });
|
|
369
|
+
} else if ((args.includes('-p') || args.includes('--print')) && format === 'stream-json') {
|
|
370
|
+
process.stdout.write(JSON.stringify({ type: 'error', code: 'config_error', error: message }) + '\n');
|
|
371
|
+
} else process.stderr.write(`错误:${message}\n`);
|
|
372
|
+
await flushCliOutput();
|
|
373
|
+
} finally { lifecycle.dispose(); }
|
|
374
|
+
process.exitCode = 1;
|
|
394
375
|
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
3
|
+
import { filterToolsForRuntime } from '../runtime/agentRuntimeContext.js';
|
|
4
|
+
import { ALL_TOOLS, executeCatalogTool, getToolGateDetails } from '../tools/index.js';
|
|
5
|
+
/** Root plugin completion uses the same validated, durable delivery boundary as
|
|
6
|
+
* PresentResult. Artifact declarations are candidates, never verification proof.
|
|
7
|
+
* Kept outside workflow scripts so children cannot publish a parent's result. */
|
|
8
|
+
export async function* presentPluginArtifacts(paths, options) {
|
|
9
|
+
if (!paths.length)
|
|
10
|
+
return;
|
|
11
|
+
const runtime = options.runtimeContext;
|
|
12
|
+
const candidates = (options.availableTools ?? ALL_TOOLS).filter(tool => options.allowedTools === undefined || options.allowedTools.includes(tool.name));
|
|
13
|
+
const catalog = runtime ? filterToolsForRuntime(candidates, runtime) : candidates;
|
|
14
|
+
const definition = catalog.find(tool => tool.name === 'PresentResult');
|
|
15
|
+
if (!definition || (runtime && runtime.profile !== 'main')) {
|
|
16
|
+
yield { type: 'warning', message: '工作流文件已生成,但当前宿主未授权正式交付;未登记文件卡片。' };
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
options.signal?.throwIfAborted();
|
|
20
|
+
const id = randomUUID();
|
|
21
|
+
const args = JSON.stringify({
|
|
22
|
+
summary: '工作流产物(内容未独立验证)',
|
|
23
|
+
files: [...new Set(paths)].map(path => ({ path, verification: 'not_run' })),
|
|
24
|
+
});
|
|
25
|
+
const context = {
|
|
26
|
+
cwd: options.sessionState?.activeWorktree?.path ?? runtime?.cwd ?? getWorkingDir(),
|
|
27
|
+
history: options.history, sessionState: options.sessionState, provider: options.provider,
|
|
28
|
+
sessionId: runtime?.sessionId, workspaceId: runtime?.workspaceId,
|
|
29
|
+
surface: runtime?.surface, conversationMode: runtime?.conversationMode,
|
|
30
|
+
userMessageId: options.userMessageId, deliveryId: options.deliveryId ?? options.userMessageId,
|
|
31
|
+
toolCallId: id, toolGate: options.toolGate ?? runtime?.toolGate,
|
|
32
|
+
};
|
|
33
|
+
const message = { role: 'assistant', content: '', id: randomUUID(), timestamp: Date.now(),
|
|
34
|
+
...(options.messageProvenance ? { provenance: options.messageProvenance } : {}),
|
|
35
|
+
tool_calls: [{ id, type: 'function', function: { name: 'PresentResult', arguments: args } }] };
|
|
36
|
+
options.history.push(message);
|
|
37
|
+
yield { type: 'assistant_message', message };
|
|
38
|
+
yield { type: 'tool_start', toolName: 'PresentResult', toolCallId: id, argsPreview: args, argsFriendly: '登记工作流文件' };
|
|
39
|
+
let result;
|
|
40
|
+
let executed = false;
|
|
41
|
+
try {
|
|
42
|
+
const checked = definition.inputSchema.safeParse(JSON.parse(args));
|
|
43
|
+
if (!checked.success)
|
|
44
|
+
throw new Error('工作流交付清单无效:最多 50 个文件,路径不能为空');
|
|
45
|
+
const decision = await context.toolGate?.({ name: definition.name, argsJson: args,
|
|
46
|
+
isReadOnly: definition.isReadOnly ?? false, toolCallId: id,
|
|
47
|
+
...getToolGateDetails(definition, args, context) }, options.signal);
|
|
48
|
+
if (decision && !decision.allow)
|
|
49
|
+
throw new Error(decision.reason);
|
|
50
|
+
options.signal?.throwIfAborted();
|
|
51
|
+
executed = true;
|
|
52
|
+
result = await (options.executeTool
|
|
53
|
+
? options.executeTool('PresentResult', args, options.signal, context)
|
|
54
|
+
: executeCatalogTool(catalog, 'PresentResult', args, options.signal, context));
|
|
55
|
+
options.signal?.throwIfAborted();
|
|
56
|
+
if (result.ok && result.metadata?.kind === 'result_manifest' && options.commitFormalDelivery) {
|
|
57
|
+
if (!options.userMessageId)
|
|
58
|
+
throw new Error('缺少交付所属的用户回合');
|
|
59
|
+
await options.commitFormalDelivery({ toolCallId: id, turnId: options.userMessageId, manifest: result.metadata.manifest });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
result = { ok: false, error: `工作流产物未能正式交付:${error.message}` };
|
|
64
|
+
}
|
|
65
|
+
const content = result.ok ? result.content : result.error;
|
|
66
|
+
options.history.push({ role: 'tool', id: randomUUID(), timestamp: Date.now(), tool_call_id: id,
|
|
67
|
+
content, display_ok: result.ok, ...(result.metadata ? { display_metadata: result.metadata } : {}),
|
|
68
|
+
toolResultDisposition: executed ? 'executed' : 'not_executed',
|
|
69
|
+
...(options.messageProvenance ? { provenance: options.messageProvenance } : {}) });
|
|
70
|
+
yield { type: 'tool_end', toolName: 'PresentResult', toolCallId: id, executed,
|
|
71
|
+
ok: result.ok, content, ...(result.metadata ? { metadata: result.metadata } : {}) };
|
|
72
|
+
yield { type: 'tool_messages_committed' };
|
|
73
|
+
if (!result.ok)
|
|
74
|
+
yield { type: 'warning', message: content };
|
|
75
|
+
options.signal?.throwIfAborted();
|
|
76
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
3
|
+
import { filterToolsForRuntime } from '../runtime/agentRuntimeContext.js';
|
|
4
|
+
import { ALL_TOOLS, executeCatalogTool, getToolGateDetails } from '../tools/index.js';
|
|
5
|
+
import type { LoopEvent, Message, ToolCallContext, ToolResult } from '../types.js';
|
|
6
|
+
import type { PluginRunnerOptions } from './pluginRunner.js';
|
|
7
|
+
|
|
8
|
+
/** Root plugin completion uses the same validated, durable delivery boundary as
|
|
9
|
+
* PresentResult. Artifact declarations are candidates, never verification proof.
|
|
10
|
+
* Kept outside workflow scripts so children cannot publish a parent's result. */
|
|
11
|
+
export async function* presentPluginArtifacts(
|
|
12
|
+
paths: readonly string[], options: PluginRunnerOptions,
|
|
13
|
+
): AsyncGenerator<LoopEvent, void, void> {
|
|
14
|
+
if (!paths.length) return;
|
|
15
|
+
const runtime = options.runtimeContext;
|
|
16
|
+
const candidates = (options.availableTools ?? ALL_TOOLS).filter(tool =>
|
|
17
|
+
options.allowedTools === undefined || options.allowedTools.includes(tool.name));
|
|
18
|
+
const catalog = runtime ? filterToolsForRuntime(candidates, runtime) : candidates;
|
|
19
|
+
const definition = catalog.find(tool => tool.name === 'PresentResult');
|
|
20
|
+
if (!definition || (runtime && runtime.profile !== 'main')) {
|
|
21
|
+
yield { type: 'warning', message: '工作流文件已生成,但当前宿主未授权正式交付;未登记文件卡片。' };
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
options.signal?.throwIfAborted();
|
|
25
|
+
const id = randomUUID();
|
|
26
|
+
const args = JSON.stringify({
|
|
27
|
+
summary: '工作流产物(内容未独立验证)',
|
|
28
|
+
files: [...new Set(paths)].map(path => ({ path, verification: 'not_run' })),
|
|
29
|
+
});
|
|
30
|
+
const context: ToolCallContext = {
|
|
31
|
+
cwd: options.sessionState?.activeWorktree?.path ?? runtime?.cwd ?? getWorkingDir(),
|
|
32
|
+
history: options.history, sessionState: options.sessionState, provider: options.provider,
|
|
33
|
+
sessionId: runtime?.sessionId, workspaceId: runtime?.workspaceId,
|
|
34
|
+
surface: runtime?.surface, conversationMode: runtime?.conversationMode,
|
|
35
|
+
userMessageId: options.userMessageId, deliveryId: options.deliveryId ?? options.userMessageId,
|
|
36
|
+
toolCallId: id, toolGate: options.toolGate ?? runtime?.toolGate,
|
|
37
|
+
};
|
|
38
|
+
const message: Message = { role: 'assistant', content: '', id: randomUUID(), timestamp: Date.now(),
|
|
39
|
+
...(options.messageProvenance ? { provenance: options.messageProvenance } : {}),
|
|
40
|
+
tool_calls: [{ id, type: 'function', function: { name: 'PresentResult', arguments: args } }] };
|
|
41
|
+
options.history.push(message);
|
|
42
|
+
yield { type: 'assistant_message', message };
|
|
43
|
+
yield { type: 'tool_start', toolName: 'PresentResult', toolCallId: id, argsPreview: args, argsFriendly: '登记工作流文件' };
|
|
44
|
+
let result: ToolResult;
|
|
45
|
+
let executed = false;
|
|
46
|
+
try {
|
|
47
|
+
const checked = definition.inputSchema.safeParse(JSON.parse(args));
|
|
48
|
+
if (!checked.success) throw new Error('工作流交付清单无效:最多 50 个文件,路径不能为空');
|
|
49
|
+
const decision = await context.toolGate?.({ name: definition.name, argsJson: args,
|
|
50
|
+
isReadOnly: definition.isReadOnly ?? false, toolCallId: id,
|
|
51
|
+
...getToolGateDetails(definition, args, context) }, options.signal);
|
|
52
|
+
if (decision && !decision.allow) throw new Error(decision.reason);
|
|
53
|
+
options.signal?.throwIfAborted();
|
|
54
|
+
executed = true;
|
|
55
|
+
result = await (options.executeTool
|
|
56
|
+
? options.executeTool('PresentResult', args, options.signal, context)
|
|
57
|
+
: executeCatalogTool(catalog, 'PresentResult', args, options.signal, context));
|
|
58
|
+
options.signal?.throwIfAborted();
|
|
59
|
+
if (result.ok && result.metadata?.kind === 'result_manifest' && options.commitFormalDelivery) {
|
|
60
|
+
if (!options.userMessageId) throw new Error('缺少交付所属的用户回合');
|
|
61
|
+
await options.commitFormalDelivery({ toolCallId: id, turnId: options.userMessageId, manifest: result.metadata.manifest });
|
|
62
|
+
}
|
|
63
|
+
} catch (error) {
|
|
64
|
+
result = { ok: false, error: `工作流产物未能正式交付:${(error as Error).message}` };
|
|
65
|
+
}
|
|
66
|
+
const content = result.ok ? result.content : result.error;
|
|
67
|
+
options.history.push({ role: 'tool', id: randomUUID(), timestamp: Date.now(), tool_call_id: id,
|
|
68
|
+
content, display_ok: result.ok, ...(result.metadata ? { display_metadata: result.metadata } : {}),
|
|
69
|
+
toolResultDisposition: executed ? 'executed' : 'not_executed',
|
|
70
|
+
...(options.messageProvenance ? { provenance: options.messageProvenance } : {}) });
|
|
71
|
+
yield { type: 'tool_end', toolName: 'PresentResult', toolCallId: id, executed,
|
|
72
|
+
ok: result.ok, content, ...(result.metadata ? { metadata: result.metadata } : {}) };
|
|
73
|
+
yield { type: 'tool_messages_committed' };
|
|
74
|
+
if (!result.ok) yield { type: 'warning', message: content };
|
|
75
|
+
options.signal?.throwIfAborted();
|
|
76
|
+
}
|
package/src/plugins/pluginApi.ts
CHANGED
|
@@ -39,6 +39,8 @@ import type {
|
|
|
39
39
|
|
|
40
40
|
/** 框架传给插件的运行时上下文(仅暴露执行 LLM/工具 所需的最小集合)。 */
|
|
41
41
|
export interface PluginContext {
|
|
42
|
+
/** Host-controlled root artifact delivery; never a script/child capability. */
|
|
43
|
+
presentArtifacts?: (paths: readonly string[]) => AsyncGenerator<LoopEvent, void, void>;
|
|
42
44
|
/** Stable identity of this externally initiated execution (not the conversation). */
|
|
43
45
|
executionId?: string;
|
|
44
46
|
provider: Provider;
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
17
17
|
import { runQuery } from '../loop.js';
|
|
18
18
|
import { buildCommandInput, discoverPlugins, listAvailableCommands, parseSlashCommand, resolveCommand, } from './commandRouter.js';
|
|
19
|
+
import { presentPluginArtifacts } from './artifactDelivery.js';
|
|
19
20
|
import { loadPluginApi, loadPluginEntry } from './pluginLoader.js';
|
|
20
21
|
import { buildFallbackInput, parseExplicitPrefix, resolveSlashFallback, } from './slashFallback.js';
|
|
21
22
|
export async function* runWithPlugins(userInput, options) {
|
|
@@ -154,6 +155,7 @@ export async function* runWithPlugins(userInput, options) {
|
|
|
154
155
|
const api = entry.kind === 'ready' ? entry.api : null;
|
|
155
156
|
if (api?.runCommand) {
|
|
156
157
|
yield* api.runCommand(matched.cmd.name, matched.arguments, {
|
|
158
|
+
presentArtifacts: paths => presentPluginArtifacts(paths, options),
|
|
157
159
|
executionId: options.executionId,
|
|
158
160
|
provider,
|
|
159
161
|
history,
|
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
resolveCommand,
|
|
26
26
|
} from './commandRouter.js';
|
|
27
27
|
import type { PluginEvent } from './pluginApi.js';
|
|
28
|
+
import { presentPluginArtifacts } from './artifactDelivery.js';
|
|
28
29
|
import { loadPluginApi, loadPluginEntry } from './pluginLoader.js';
|
|
29
30
|
import {
|
|
30
31
|
type SlashTarget,
|
|
@@ -71,6 +72,7 @@ export interface PluginRunnerOptions {
|
|
|
71
72
|
/** Explicit delivery target chosen by the host; see RunQueryOptions.deliveryId. */
|
|
72
73
|
deliveryId?: RunQueryOptions['deliveryId'];
|
|
73
74
|
backgroundContinuation?: RunQueryOptions['backgroundContinuation'];
|
|
75
|
+
deferBackgroundNotifications?: RunQueryOptions['deferBackgroundNotifications'];
|
|
74
76
|
messageProvenance?: RunQueryOptions['messageProvenance'];
|
|
75
77
|
userBrowserReferences?: RunQueryOptions['userBrowserReferences'];
|
|
76
78
|
imageInputs?: RunQueryOptions['imageInputs'];
|
|
@@ -237,6 +239,7 @@ export async function* runWithPlugins(
|
|
|
237
239
|
const api = entry.kind === 'ready' ? entry.api : null;
|
|
238
240
|
if (api?.runCommand) {
|
|
239
241
|
yield* api.runCommand(matched.cmd.name, matched.arguments, {
|
|
242
|
+
presentArtifacts: paths => presentPluginArtifacts(paths, options),
|
|
240
243
|
executionId: options.executionId,
|
|
241
244
|
provider,
|
|
242
245
|
history,
|
|
@@ -3,7 +3,7 @@ import { CONFIG_LIMITS } from '../config/numericLimits.js';
|
|
|
3
3
|
export const RESEARCH_DELEGATION_POLICY = `- 大范围阅读与并行调研:问题与范围已清楚时直接并发,不必先铺路或自己读完一遍;范围不清才先看项目说明、目录或入口。多个独立问题各需多轮探索时,优先同轮派发多个 Agent(agent_type="explore");数量取决于独立工作量和宿主额度,不按文件数量机械切块。
|
|
4
4
|
- 少量已知文件同轮批量读;强依赖调用链自行跟进。只读委派无需写入铺路或 worktree,不为获得 shell 升级 general。
|
|
5
5
|
- 自包含任务书用 context.researchQuestions 写清问题、范围、停止条件,附证据与排除项,不复制主历史。explore 没有 Git/shell:变更审查未给 baseline 时宿主附 git diff HEAD,仅给 SHA/HEAD 则解析为该提交到工作区的 diff;其他区间由主 Agent 提供可读差异文件。主 Agent 执行测试并回传结果;缺基线只报告候选风险,不断言新引入。
|
|
6
|
-
- 修改任务先由主 Agent 定接口、验收和文件归属。若已有彼此独立、可验证的实现单元,下一步优先同轮派发 general,各自给出 write_scopes
|
|
6
|
+
- 修改任务先由主 Agent 定接口、验收和文件归属。若已有彼此独立、可验证的实现单元,下一步优先同轮派发 general,各自给出 write_scopes;不要铺路后又自己逐件实现。context.verification 明确谁运行哪些检查;局部共享写的构建/测试由主 Agent 承担,不要求子任务运行未授权命令。子任务完成分工可 result,将预定的主 Agent 验证写入 parentNextSteps;主 Agent 真正验证后才 accept。接口未定、写域重叠或只有一个短改动时直接处理。
|
|
7
7
|
- 主 Agent 还有独立工作才用后台,否则同轮前台并行即可。子任务返回后主 Agent 对照共同约定合并结论、冲突和缺口,检查组合效果,不拼接对话、不重复调查。`;
|
|
8
8
|
export const AGENT_TOOL_DESCRIPTION = '派发独立子任务并返回 agent_id:多路只读调查同轮发 explore;接口、验收和归属已明确的并行修改同轮发 general,各限 write_scopes。共享目录局部编辑不能跑 shell,主 Agent 集成后统一验证;worktree 不含未提交的铺路代码。任务书自包含,context 传接口、基线或 researchQuestions;depends_on 引用已验收前置任务。后台派发供主 Agent 推进其他工作;resume_agent_id 续接原子历史。TaskOutput 按需取完整交接。';
|
|
9
9
|
export function delegationRuntimeGuidance(input) {
|
|
@@ -4,7 +4,7 @@ import { CONFIG_LIMITS } from '../config/numericLimits.js';
|
|
|
4
4
|
export const RESEARCH_DELEGATION_POLICY = `- 大范围阅读与并行调研:问题与范围已清楚时直接并发,不必先铺路或自己读完一遍;范围不清才先看项目说明、目录或入口。多个独立问题各需多轮探索时,优先同轮派发多个 Agent(agent_type="explore");数量取决于独立工作量和宿主额度,不按文件数量机械切块。
|
|
5
5
|
- 少量已知文件同轮批量读;强依赖调用链自行跟进。只读委派无需写入铺路或 worktree,不为获得 shell 升级 general。
|
|
6
6
|
- 自包含任务书用 context.researchQuestions 写清问题、范围、停止条件,附证据与排除项,不复制主历史。explore 没有 Git/shell:变更审查未给 baseline 时宿主附 git diff HEAD,仅给 SHA/HEAD 则解析为该提交到工作区的 diff;其他区间由主 Agent 提供可读差异文件。主 Agent 执行测试并回传结果;缺基线只报告候选风险,不断言新引入。
|
|
7
|
-
- 修改任务先由主 Agent 定接口、验收和文件归属。若已有彼此独立、可验证的实现单元,下一步优先同轮派发 general,各自给出 write_scopes
|
|
7
|
+
- 修改任务先由主 Agent 定接口、验收和文件归属。若已有彼此独立、可验证的实现单元,下一步优先同轮派发 general,各自给出 write_scopes;不要铺路后又自己逐件实现。context.verification 明确谁运行哪些检查;局部共享写的构建/测试由主 Agent 承担,不要求子任务运行未授权命令。子任务完成分工可 result,将预定的主 Agent 验证写入 parentNextSteps;主 Agent 真正验证后才 accept。接口未定、写域重叠或只有一个短改动时直接处理。
|
|
8
8
|
- 主 Agent 还有独立工作才用后台,否则同轮前台并行即可。子任务返回后主 Agent 对照共同约定合并结论、冲突和缺口,检查组合效果,不拼接对话、不重复调查。`;
|
|
9
9
|
|
|
10
10
|
export const AGENT_TOOL_DESCRIPTION = '派发独立子任务并返回 agent_id:多路只读调查同轮发 explore;接口、验收和归属已明确的并行修改同轮发 general,各限 write_scopes。共享目录局部编辑不能跑 shell,主 Agent 集成后统一验证;worktree 不含未提交的铺路代码。任务书自包含,context 传接口、基线或 researchQuestions;depends_on 引用已验收前置任务。后台派发供主 Agent 推进其他工作;resume_agent_id 续接原子历史。TaskOutput 按需取完整交接。';
|
|
@@ -25,9 +25,10 @@ const MAIN_POLICIES = [
|
|
|
25
25
|
{
|
|
26
26
|
id: 'identity.working-style', layer: 'identity', profiles: ['main'], source: '01',
|
|
27
27
|
render: () => `# 工作方式
|
|
28
|
-
-
|
|
28
|
+
- 独立判断,不奉承;跟随用户语言,默认中文。
|
|
29
29
|
- 从用户措辞判断是讨论还是执行。明确要求实现、修改、修复、重构时直接完成;纯解释或评估时保持只读。
|
|
30
30
|
- 信息足够时自行选择稳健默认值。只有关键输入无法推断、存在影响方向的真实取舍,或不可逆高风险操作前才询问。
|
|
31
|
+
- 按领域专家的方法工作,不只模仿语气:明确约束与判据,选择适用方法和已授权工具,用反例或检查检验假设;简单任务不堆流程。
|
|
31
32
|
- 找根因并在职责所属层修复;说明重要取舍,不用临时 workaround 冒充完整解决。`,
|
|
32
33
|
},
|
|
33
34
|
{
|
|
@@ -251,11 +252,11 @@ const CAPABILITY_POLICIES = [
|
|
|
251
252
|
{
|
|
252
253
|
id: 'capability.advisor', layer: 'capability', profiles: MAIN_PROFILE, source: 'native',
|
|
253
254
|
requiresTools: ['Advisor'],
|
|
254
|
-
render: () => `- Advisor
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
255
|
+
render: () => `- Advisor(顾问模型)使用规则:第二意见由主 Agent 核实取舍,不授予权限、不替用户验收。它只能看到预算内的材料,note 补关键证据;仅用实际提供的只读工具核实,不运行命令或测试。
|
|
256
|
+
默认先明确范围、并行调查并补证据,必要调查与子任务验收之后再咨询、验证收尾;不为满足提醒在证据未齐时抢先咨询。重大取舍或改变既定方向之前、同一问题两次或以上处理失败后、冲突无法消解时,可带具体问题和证据提前问。换工具不清零失败次数,无关失败不合并。
|
|
257
|
+
默认检查当前交付依赖;independent 仅用于明确不依赖未返回报告的独立问题,不绕过依赖。必要搜索先做,Advisor 作为该批最后一个调用;读意见后再规划,仅对改变结论的新证据或未覆盖风险补问。
|
|
258
|
+
文字分析也是交付,自信、没文件不豁免;即时问答、进度、拼写修正无需咨询,不递归咨询来解释为什么咨询。引用日志不是本轮命令;自动咨询不问用户。
|
|
259
|
+
宿主提醒,不拦截工具也不替你调用。每次咨询只尝试一次,不设配额;失败、空答或超时自行继续,不转成人工审批、不声称已验证。缺材料先补查。
|
|
259
260
|
以代码、测试和用户要求核实意见:一手证据或用户明确要求否定才拒绝;自测通过不能证明意见错误,它可能没测到所指问题。已有证据与意见方向不同又无法判定时,不要默默改道,写明冲突再咨询一次。顾问不是事实来源。`,
|
|
260
261
|
},
|
|
261
262
|
{
|
|
@@ -72,9 +72,10 @@ const MAIN_POLICIES: PromptPolicySpec[] = [
|
|
|
72
72
|
{
|
|
73
73
|
id: 'identity.working-style', layer: 'identity', profiles: ['main'], source: '01',
|
|
74
74
|
render: () => `# 工作方式
|
|
75
|
-
-
|
|
75
|
+
- 独立判断,不奉承;跟随用户语言,默认中文。
|
|
76
76
|
- 从用户措辞判断是讨论还是执行。明确要求实现、修改、修复、重构时直接完成;纯解释或评估时保持只读。
|
|
77
77
|
- 信息足够时自行选择稳健默认值。只有关键输入无法推断、存在影响方向的真实取舍,或不可逆高风险操作前才询问。
|
|
78
|
+
- 按领域专家的方法工作,不只模仿语气:明确约束与判据,选择适用方法和已授权工具,用反例或检查检验假设;简单任务不堆流程。
|
|
78
79
|
- 找根因并在职责所属层修复;说明重要取舍,不用临时 workaround 冒充完整解决。`,
|
|
79
80
|
},
|
|
80
81
|
{
|
|
@@ -298,11 +299,11 @@ const CAPABILITY_POLICIES: PromptPolicySpec[] = [
|
|
|
298
299
|
{
|
|
299
300
|
id: 'capability.advisor', layer: 'capability', profiles: MAIN_PROFILE, source: 'native',
|
|
300
301
|
requiresTools: ['Advisor'],
|
|
301
|
-
render: () => `- Advisor
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
302
|
+
render: () => `- Advisor(顾问模型)使用规则:第二意见由主 Agent 核实取舍,不授予权限、不替用户验收。它只能看到预算内的材料,note 补关键证据;仅用实际提供的只读工具核实,不运行命令或测试。
|
|
303
|
+
默认先明确范围、并行调查并补证据,必要调查与子任务验收之后再咨询、验证收尾;不为满足提醒在证据未齐时抢先咨询。重大取舍或改变既定方向之前、同一问题两次或以上处理失败后、冲突无法消解时,可带具体问题和证据提前问。换工具不清零失败次数,无关失败不合并。
|
|
304
|
+
默认检查当前交付依赖;independent 仅用于明确不依赖未返回报告的独立问题,不绕过依赖。必要搜索先做,Advisor 作为该批最后一个调用;读意见后再规划,仅对改变结论的新证据或未覆盖风险补问。
|
|
305
|
+
文字分析也是交付,自信、没文件不豁免;即时问答、进度、拼写修正无需咨询,不递归咨询来解释为什么咨询。引用日志不是本轮命令;自动咨询不问用户。
|
|
306
|
+
宿主提醒,不拦截工具也不替你调用。每次咨询只尝试一次,不设配额;失败、空答或超时自行继续,不转成人工审批、不声称已验证。缺材料先补查。
|
|
306
307
|
以代码、测试和用户要求核实意见:一手证据或用户明确要求否定才拒绝;自测通过不能证明意见错误,它可能没测到所指问题。已有证据与意见方向不同又无法判定时,不要默默改道,写明冲突再咨询一次。顾问不是事实来源。`,
|
|
307
308
|
},
|
|
308
309
|
{
|
|
@@ -340,8 +340,8 @@ export async function buildTransientBundle(runtime, profile, tools, options = {}
|
|
|
340
340
|
? ''
|
|
341
341
|
: '当前宿主不能交互提问;不要等待用户选择,缺少关键输入时说明阻塞。',
|
|
342
342
|
runtime.backgroundWake &&
|
|
343
|
-
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell')
|
|
344
|
-
?
|
|
343
|
+
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell' || tool.name === 'Download')
|
|
344
|
+
? `后台任务(run_in_background)结束后,完成通知会作为系统事件自动送到你面前。长耗时任务适合后台执行。${tools.some(tool => tool.name === 'Download') ? 'Download 后台模式只允许新文件。' : ''}不要用 sleep 轮询、不要反复调 TaskOutput 空转、不要预测还没结束的任务的结果;启动后把当前进展说清楚就结束本轮。后台完成不抢占真人当前任务;空闲后按原交付目标排队接续。接续失败或中断时保留待处理状态,收到真人输入后恢复;先检查已有结果,不盲目重放已执行的写入。`
|
|
345
345
|
: '',
|
|
346
346
|
runtime.backgroundWake === false && runtime.surface === 'tui'
|
|
347
347
|
? '本会话自动续跑已暂停或达到连续唤醒上限。不要启动新的后台任务后承诺自动继续;需要用户再次输入才能恢复自动唤醒。已有任务的结果可用 TaskOutput 读取,未完成时如实说明。'
|
|
@@ -539,8 +539,8 @@ export async function buildTransientBundle(
|
|
|
539
539
|
? ''
|
|
540
540
|
: '当前宿主不能交互提问;不要等待用户选择,缺少关键输入时说明阻塞。',
|
|
541
541
|
runtime.backgroundWake &&
|
|
542
|
-
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell')
|
|
543
|
-
?
|
|
542
|
+
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell' || tool.name === 'Download')
|
|
543
|
+
? `后台任务(run_in_background)结束后,完成通知会作为系统事件自动送到你面前。长耗时任务适合后台执行。${tools.some(tool => tool.name === 'Download') ? 'Download 后台模式只允许新文件。' : ''}不要用 sleep 轮询、不要反复调 TaskOutput 空转、不要预测还没结束的任务的结果;启动后把当前进展说清楚就结束本轮。后台完成不抢占真人当前任务;空闲后按原交付目标排队接续。接续失败或中断时保留待处理状态,收到真人输入后恢复;先检查已有结果,不盲目重放已执行的写入。`
|
|
544
544
|
: '',
|
|
545
545
|
runtime.backgroundWake === false && runtime.surface === 'tui'
|
|
546
546
|
? '本会话自动续跑已暂停或达到连续唤醒上限。不要启动新的后台任务后承诺自动继续;需要用户再次输入才能恢复自动唤醒。已有任务的结果可用 TaskOutput 读取,未完成时如实说明。'
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** A conservative view for host intent heuristics, NOT an authorization parser.
|
|
2
|
+
* Keep the original request in model history. Only explicitly marked evidence
|
|
3
|
+
* is omitted here; prose is not guessed away because it resembles a log.
|
|
4
|
+
* Unfenced evidence lasts until an explicit request/resume heading. */
|
|
5
|
+
export function requestIntentText(input) {
|
|
6
|
+
const out = [];
|
|
7
|
+
let fence = '';
|
|
8
|
+
let evidence = false;
|
|
9
|
+
let bracketDepth = 0;
|
|
10
|
+
let remainder;
|
|
11
|
+
const consumeQuote = (line, start = 0) => {
|
|
12
|
+
for (let i = start; i < line.length; i++) {
|
|
13
|
+
if (line[i] === '【')
|
|
14
|
+
bracketDepth++;
|
|
15
|
+
if (line[i] === '】' && --bracketDepth === 0) {
|
|
16
|
+
remainder = line.slice(i + 1);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const lines = input.replace(/\r\n?/g, '\n').split('\n');
|
|
22
|
+
let index = 0;
|
|
23
|
+
while (index < lines.length || remainder !== undefined) {
|
|
24
|
+
const line = remainder ?? lines[index++];
|
|
25
|
+
remainder = undefined;
|
|
26
|
+
const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
27
|
+
if (fence) {
|
|
28
|
+
if (mark?.[0] === fence[0] && mark.length >= fence.length) {
|
|
29
|
+
fence = '';
|
|
30
|
+
evidence = false;
|
|
31
|
+
}
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (mark) {
|
|
35
|
+
fence = mark;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (/^\s*>/.test(line))
|
|
39
|
+
continue;
|
|
40
|
+
if (!bracketDepth && /^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i.test(line)) {
|
|
41
|
+
evidence = false;
|
|
42
|
+
out.push(line.replace(/^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i, ''));
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (bracketDepth) {
|
|
46
|
+
consumeQuote(line);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (evidence) {
|
|
50
|
+
if (line.trimStart().startsWith('【')) {
|
|
51
|
+
evidence = false;
|
|
52
|
+
consumeQuote(line.trimStart());
|
|
53
|
+
}
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (/^\s*(?:#{1,6}\s*)?(?:下面|以下)(?:是|为)?[^::【\n]{0,40}(?:日志|对话记录|聊天记录|回复|输出|引用|材料)\s*[::]?\s*$/.test(line)) {
|
|
57
|
+
evidence = true;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
// A labelled paste may follow the user's question on the same line.
|
|
61
|
+
const label = /(?:(?:下面|以下)(?:是|为)?(?:[^\n::【]{0,20})?(?:日志|对话记录|聊天记录|回复|输出|引用|材料)|(?<![\p{L}\p{N}_])(?:参考)?(?:日志|对话记录|聊天记录|引用|log|transcript|quoted text))\s*[::]/iu.exec(line);
|
|
62
|
+
if (label) {
|
|
63
|
+
out.push(line.slice(0, label.index));
|
|
64
|
+
const rest = line.slice(label.index + label[0].length).trim();
|
|
65
|
+
if (/^(`{3,}|~{3,})/.test(rest)) {
|
|
66
|
+
fence = /^(`{3,}|~{3,})/.exec(rest)[1];
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (!rest.startsWith('【')) {
|
|
70
|
+
evidence = true;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
consumeQuote(rest);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
// Chinese quotation blocks commonly used when asking whether a report is true.
|
|
77
|
+
const start = line.indexOf('【');
|
|
78
|
+
if (start >= 0 && /(?:说法|日志|记录|回复|输出|引用|材料|如下|下面|以下)/.test(line.slice(0, start))) {
|
|
79
|
+
out.push(line.slice(0, start));
|
|
80
|
+
consumeQuote(line, start);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
out.push(line);
|
|
84
|
+
}
|
|
85
|
+
return out.join('\n').trim();
|
|
86
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** A conservative view for host intent heuristics, NOT an authorization parser.
|
|
2
|
+
* Keep the original request in model history. Only explicitly marked evidence
|
|
3
|
+
* is omitted here; prose is not guessed away because it resembles a log.
|
|
4
|
+
* Unfenced evidence lasts until an explicit request/resume heading. */
|
|
5
|
+
export function requestIntentText(input: string): string {
|
|
6
|
+
const out: string[] = [];
|
|
7
|
+
let fence = '';
|
|
8
|
+
let evidence = false;
|
|
9
|
+
let bracketDepth = 0;
|
|
10
|
+
let remainder: string | undefined;
|
|
11
|
+
const consumeQuote = (line: string, start = 0) => {
|
|
12
|
+
for (let i = start; i < line.length; i++) {
|
|
13
|
+
if (line[i] === '【') bracketDepth++;
|
|
14
|
+
if (line[i] === '】' && --bracketDepth === 0) { remainder = line.slice(i + 1); return; }
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
const lines = input.replace(/\r\n?/g, '\n').split('\n');
|
|
18
|
+
let index = 0;
|
|
19
|
+
while (index < lines.length || remainder !== undefined) {
|
|
20
|
+
const line = remainder ?? lines[index++]!;
|
|
21
|
+
remainder = undefined;
|
|
22
|
+
const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
23
|
+
if (fence) {
|
|
24
|
+
if (mark?.[0] === fence[0] && mark.length >= fence.length) { fence = ''; evidence = false; }
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (mark) { fence = mark; continue; }
|
|
28
|
+
if (/^\s*>/.test(line)) continue;
|
|
29
|
+
if (!bracketDepth && /^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i.test(line)) {
|
|
30
|
+
evidence = false;
|
|
31
|
+
out.push(line.replace(/^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i, ''));
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (bracketDepth) {
|
|
35
|
+
consumeQuote(line);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (evidence) {
|
|
39
|
+
if (line.trimStart().startsWith('【')) { evidence = false; consumeQuote(line.trimStart()); }
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (/^\s*(?:#{1,6}\s*)?(?:下面|以下)(?:是|为)?[^::【\n]{0,40}(?:日志|对话记录|聊天记录|回复|输出|引用|材料)\s*[::]?\s*$/.test(line)) {
|
|
43
|
+
evidence = true;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
// A labelled paste may follow the user's question on the same line.
|
|
47
|
+
const label = /(?:(?:下面|以下)(?:是|为)?(?:[^\n::【]{0,20})?(?:日志|对话记录|聊天记录|回复|输出|引用|材料)|(?<![\p{L}\p{N}_])(?:参考)?(?:日志|对话记录|聊天记录|引用|log|transcript|quoted text))\s*[::]/iu.exec(line);
|
|
48
|
+
if (label) {
|
|
49
|
+
out.push(line.slice(0, label.index));
|
|
50
|
+
const rest = line.slice(label.index + label[0].length).trim();
|
|
51
|
+
if (/^(`{3,}|~{3,})/.test(rest)) { fence = /^(`{3,}|~{3,})/.exec(rest)![1]!; continue; }
|
|
52
|
+
if (!rest.startsWith('【')) { evidence = true; continue; }
|
|
53
|
+
consumeQuote(rest);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
// Chinese quotation blocks commonly used when asking whether a report is true.
|
|
57
|
+
const start = line.indexOf('【');
|
|
58
|
+
if (start >= 0 && /(?:说法|日志|记录|回复|输出|引用|材料|如下|下面|以下)/.test(line.slice(0, start))) {
|
|
59
|
+
out.push(line.slice(0, start));
|
|
60
|
+
consumeQuote(line, start);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
out.push(line);
|
|
64
|
+
}
|
|
65
|
+
return out.join('\n').trim();
|
|
66
|
+
}
|