minimal-agent 0.18.7 → 0.18.8
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/package.json +1 -1
- package/src/context/persistContext.js +5 -1
- package/src/context/persistContext.ts +5 -2
- package/src/loop.js +42 -20
- package/src/loop.ts +39 -18
- package/src/memory/fileStore.js +2 -34
- package/src/memory/fileStore.ts +2 -26
- package/src/prompts/policyRegistry.js +4 -8
- package/src/prompts/policyRegistry.ts +6 -8
- package/src/prompts/promptAssembly.js +16 -23
- package/src/prompts/promptAssembly.ts +22 -27
- package/src/prompts/visualPresentation.js +28 -0
- package/src/prompts/visualPresentation.ts +26 -0
- package/src/runtime/agentRuntimeContext.js +3 -0
- package/src/runtime/agentRuntimeContext.ts +4 -0
- package/src/runtime/fileLock.js +75 -0
- package/src/runtime/fileLock.ts +73 -0
- package/src/runtime/finalAnswer.js +4 -2
- package/src/runtime/finalAnswer.ts +6 -2
- package/src/runtime/outputContract.js +17 -0
- package/src/runtime/outputContract.ts +34 -0
- package/src/session/runAgentTurn.js +7 -2
- package/src/session/runAgentTurn.ts +7 -2
- package/src/session/runtimeStore.js +11 -28
- package/src/session/runtimeStore.ts +9 -23
- package/src/tools/agent/agent.js +7 -5
- package/src/tools/agent/agent.ts +7 -4
- package/src/tools/skill/searchSkills.js +2 -2
- package/src/tools/skill/searchSkills.ts +2 -2
- package/src/tools/skill/skill.js +4 -0
- package/src/tools/skill/skill.ts +3 -0
- package/src/types.ts +4 -0
- package/src/web/protocol.ts +3 -1
|
@@ -88,6 +88,7 @@ const stablePromptCache = new Map<string, string>();
|
|
|
88
88
|
import { normalizeBrowserRuntime } from '../runtime/browserRuntimeContext.js';
|
|
89
89
|
|
|
90
90
|
export interface PromptRuntimeContext {
|
|
91
|
+
output?: import('../runtime/outputContract.js').OutputContract;
|
|
91
92
|
surface: PromptSurface;
|
|
92
93
|
host?: 'desktop' | 'tui' | 'cli' | 'stream-json' | 'workflow';
|
|
93
94
|
conversationMode: import('../runtime/agentRuntimeContext.js').ConversationMode;
|
|
@@ -377,6 +378,22 @@ async function buildAdvisorTransient(
|
|
|
377
378
|
return buildAdvisorStatusLine();
|
|
378
379
|
}
|
|
379
380
|
|
|
381
|
+
/** One default contract for stable, transient and combined prompt entry points.
|
|
382
|
+
* Preserve explicit legacy fields at this compatibility boundary; omission never
|
|
383
|
+
* grants memory, browser or vision capabilities.
|
|
384
|
+
*/
|
|
385
|
+
function resolvePromptRuntime(options: AssemblePromptOptions): PromptRuntimeContext {
|
|
386
|
+
return {
|
|
387
|
+
surface: (options.profile ?? 'main') === 'main' ? 'cli' : 'subagent',
|
|
388
|
+
conversationMode: 'private',
|
|
389
|
+
cwd: options.cwd,
|
|
390
|
+
interactiveAsk: true,
|
|
391
|
+
supervisedBrowser: false,
|
|
392
|
+
ownerLocalSession: false,
|
|
393
|
+
...options.runtime,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
380
397
|
export async function assemblePromptEnvelope(
|
|
381
398
|
options: AssemblePromptOptions,
|
|
382
399
|
): Promise<PromptEnvelope> {
|
|
@@ -387,15 +404,7 @@ export async function assemblePromptEnvelope(
|
|
|
387
404
|
includeProjectInstructions = true,
|
|
388
405
|
includePlugins = profile === 'main',
|
|
389
406
|
} = options;
|
|
390
|
-
const runtime
|
|
391
|
-
surface: profile === 'main' ? 'cli' : 'subagent',
|
|
392
|
-
conversationMode: 'private',
|
|
393
|
-
cwd,
|
|
394
|
-
interactiveAsk: true,
|
|
395
|
-
supervisedBrowser: false,
|
|
396
|
-
ownerLocalSession: false,
|
|
397
|
-
...options.runtime,
|
|
398
|
-
};
|
|
407
|
+
const runtime = resolvePromptRuntime(options);
|
|
399
408
|
|
|
400
409
|
const { base, capabilities, stableContext } = await buildStableBase(
|
|
401
410
|
cwd,
|
|
@@ -439,6 +448,7 @@ async function buildStableBase(
|
|
|
439
448
|
const stableContext: StablePromptContext = {
|
|
440
449
|
profile,
|
|
441
450
|
surface: runtime.surface,
|
|
451
|
+
output: runtime.output,
|
|
442
452
|
cwd,
|
|
443
453
|
capabilities,
|
|
444
454
|
toolNames: new Set(tools.map((tool) => tool.name)),
|
|
@@ -458,19 +468,12 @@ export async function assembleStablePrompt(
|
|
|
458
468
|
options: AssemblePromptOptions,
|
|
459
469
|
): Promise<string> {
|
|
460
470
|
const profile = options.profile ?? 'main';
|
|
461
|
-
const runtime
|
|
462
|
-
surface: profile === 'main' ? 'cli' : 'subagent',
|
|
463
|
-
conversationMode: 'private',
|
|
464
|
-
cwd: options.cwd,
|
|
465
|
-
interactiveAsk: true,
|
|
466
|
-
supervisedBrowser: false,
|
|
467
|
-
ownerLocalSession: false,
|
|
468
|
-
...options.runtime,
|
|
469
|
-
};
|
|
471
|
+
const runtime = resolvePromptRuntime(options);
|
|
470
472
|
const key = [
|
|
471
473
|
options.cwd,
|
|
472
474
|
profile,
|
|
473
475
|
runtime.surface,
|
|
476
|
+
JSON.stringify(runtime.output ?? null),
|
|
474
477
|
runtime.conversationMode,
|
|
475
478
|
createHash('sha256')
|
|
476
479
|
.update(
|
|
@@ -784,15 +787,7 @@ export async function buildTransientPromptBundle(
|
|
|
784
787
|
options: AssemblePromptOptions,
|
|
785
788
|
): Promise<ContextBundle> {
|
|
786
789
|
const profile = options.profile ?? 'main';
|
|
787
|
-
const runtime
|
|
788
|
-
surface: profile === 'main' ? 'cli' : 'subagent',
|
|
789
|
-
conversationMode: 'private',
|
|
790
|
-
cwd: options.cwd,
|
|
791
|
-
interactiveAsk: true,
|
|
792
|
-
supervisedBrowser: false,
|
|
793
|
-
ownerLocalSession: false,
|
|
794
|
-
...options.runtime,
|
|
795
|
-
};
|
|
790
|
+
const runtime = resolvePromptRuntime(options);
|
|
796
791
|
return buildTransientBundle(runtime, profile, options.tools, {
|
|
797
792
|
includeProjectInstructions: options.includeProjectInstructions ?? true,
|
|
798
793
|
includePlugins: options.includePlugins ?? profile === 'main',
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { resolveOutputContract } from '../runtime/outputContract.js';
|
|
2
|
+
/** One output contract shared by preparation and tool-free publication. */
|
|
3
|
+
export function visualPresentation(target) {
|
|
4
|
+
const output = typeof target === 'string' ? resolveOutputContract(target) : target;
|
|
5
|
+
const common = '按需配图,优先 Mermaid/SVG;用户指定 ASCII、代码/目录树除外。';
|
|
6
|
+
if (output.format === 'rich-markdown')
|
|
7
|
+
return `${common}\nDesktop/Web 聊天支持 ${output.diagrams.length ? output.diagrams.join(' 和 ') + ' 围栏' : 'Markdown,未声明图形渲染'},不用裸 HTML。仅用已声明的图形格式替代字符框图;最终表达同样生效。${output.images ? '支持图片。' : ''}${output.attachments ? '附件须真实提交。' : ''}无法可靠画图则用文字/表格。`;
|
|
8
|
+
if (output.format === 'terminal')
|
|
9
|
+
return `${common}\nCLI/TUI 直接回复用文字/表格/紧凑 ASCII,生成文件仍优先 Mermaid/SVG。`;
|
|
10
|
+
if (output.format === 'structured')
|
|
11
|
+
return '仅按调用方结构化协议输出,不插入 Markdown 围栏或图形源码。';
|
|
12
|
+
return `${common}\n跟随最终阅读载体,不等同于终端:Web 用 mermaid/svg 围栏;保持协议契约,未知不假定可渲染。`;
|
|
13
|
+
}
|
|
14
|
+
/** Conservative signal on PRIVATE candidates only, never a frontend converter.
|
|
15
|
+
* Require box borders in prose fences; ordinary code, trees and arrows are not diagrams.
|
|
16
|
+
*/
|
|
17
|
+
export function needsDiagramPreparation(candidate, request) {
|
|
18
|
+
const rejectsAscii = /(?:不要|不用|避免|别用|without|not|instead of)[^\n。!?]{0,24}(?:ascii|字符图|纯文本图)/i.test(request);
|
|
19
|
+
if (!rejectsAscii && /ascii|字符图|纯文本图|原样|不要.*(?:mermaid|svg)/i.test(request))
|
|
20
|
+
return false;
|
|
21
|
+
const fences = candidate.matchAll(/^(?:```|~~~)(?:text|plaintext)?[ \t]*\r?\n([\s\S]*?)^(?:```|~~~)[ \t]*$/gm);
|
|
22
|
+
for (const [, body] of fences) {
|
|
23
|
+
const borders = body.split('\n').filter(line => /[┌┐└┘┏┓┗┛+][─━\-]{3,}[┌┐└┘┏┓┗┛+]/.test(line));
|
|
24
|
+
if (borders.length >= 2 && /[│┃|].*\S.*[│┃|]/.test(body))
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AgentSurface } from '../runtime/agentRuntimeContext.js';
|
|
2
|
+
import { resolveOutputContract, type OutputContract } from '../runtime/outputContract.js';
|
|
3
|
+
|
|
4
|
+
/** One output contract shared by preparation and tool-free publication. */
|
|
5
|
+
export function visualPresentation(target: AgentSurface | OutputContract): string {
|
|
6
|
+
const output = typeof target === 'string' ? resolveOutputContract(target) : target;
|
|
7
|
+
const common = '按需配图,优先 Mermaid/SVG;用户指定 ASCII、代码/目录树除外。';
|
|
8
|
+
if (output.format === 'rich-markdown') return `${common}\nDesktop/Web 聊天支持 ${output.diagrams.length ? output.diagrams.join(' 和 ') + ' 围栏' : 'Markdown,未声明图形渲染'},不用裸 HTML。仅用已声明的图形格式替代字符框图;最终表达同样生效。${output.images ? '支持图片。' : ''}${output.attachments ? '附件须真实提交。' : ''}无法可靠画图则用文字/表格。`;
|
|
9
|
+
if (output.format === 'terminal') return `${common}\nCLI/TUI 直接回复用文字/表格/紧凑 ASCII,生成文件仍优先 Mermaid/SVG。`;
|
|
10
|
+
if (output.format === 'structured') return '仅按调用方结构化协议输出,不插入 Markdown 围栏或图形源码。';
|
|
11
|
+
return `${common}\n跟随最终阅读载体,不等同于终端:Web 用 mermaid/svg 围栏;保持协议契约,未知不假定可渲染。`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Conservative signal on PRIVATE candidates only, never a frontend converter.
|
|
15
|
+
* Require box borders in prose fences; ordinary code, trees and arrows are not diagrams.
|
|
16
|
+
*/
|
|
17
|
+
export function needsDiagramPreparation(candidate: string, request: string): boolean {
|
|
18
|
+
const rejectsAscii = /(?:不要|不用|避免|别用|without|not|instead of)[^\n。!?]{0,24}(?:ascii|字符图|纯文本图)/i.test(request);
|
|
19
|
+
if (!rejectsAscii && /ascii|字符图|纯文本图|原样|不要.*(?:mermaid|svg)/i.test(request)) return false;
|
|
20
|
+
const fences = candidate.matchAll(/^(?:```|~~~)(?:text|plaintext)?[ \t]*\r?\n([\s\S]*?)^(?:```|~~~)[ \t]*$/gm);
|
|
21
|
+
for (const [, body] of fences) {
|
|
22
|
+
const borders = body!.split('\n').filter(line => /[┌┐└┘┏┓┗┛+][─━\-]{3,}[┌┐└┘┏┓┗┛+]/.test(line));
|
|
23
|
+
if (borders.length >= 2 && /[│┃|].*\S.*[│┃|]/.test(body!)) return true;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { resolveOutputContract } from './outputContract.js';
|
|
2
|
+
export { WEB_OUTPUT, resolveOutputContract } from './outputContract.js';
|
|
1
3
|
import { isMemoryToolName } from '../tools/capabilities.js';
|
|
2
4
|
import { normalizeBrowserRuntime } from './browserRuntimeContext.js';
|
|
3
5
|
export function normalizeMemoryAccess(access) {
|
|
@@ -12,6 +14,7 @@ export function createAgentRuntimeContext(input) {
|
|
|
12
14
|
const { browser: rawBrowser, ...rest } = input;
|
|
13
15
|
return Object.freeze({
|
|
14
16
|
...rest,
|
|
17
|
+
output: resolveOutputContract(input.surface, input.output),
|
|
15
18
|
...(rawBrowser
|
|
16
19
|
? {
|
|
17
20
|
browser: normalizeBrowserRuntime(rawBrowser),
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Tool, ToolAvailability, ToolCallContext } from '../types.js';
|
|
2
2
|
import type { ToolGate } from '../toolGate.js';
|
|
3
|
+
import { resolveOutputContract, type OutputContract } from './outputContract.js';
|
|
4
|
+
export { WEB_OUTPUT, resolveOutputContract, type OutputContract } from './outputContract.js';
|
|
3
5
|
import { isMemoryToolName } from '../tools/capabilities.js';
|
|
4
6
|
import type { ComputerAutomationIntent } from '../tools/computeruse/computerIntent.js';
|
|
5
7
|
|
|
@@ -26,6 +28,7 @@ export type MemoryAccessInput = MemoryAccess | 'local-owner';
|
|
|
26
28
|
*/
|
|
27
29
|
export interface AgentRuntimeContext {
|
|
28
30
|
readonly surface: AgentSurface;
|
|
31
|
+
readonly output?: OutputContract;
|
|
29
32
|
/** Concrete frontend identity; surface remains the execution capability class. */
|
|
30
33
|
readonly host?: 'desktop' | 'tui' | 'cli' | 'stream-json' | 'workflow';
|
|
31
34
|
readonly profile: AgentProfile;
|
|
@@ -75,6 +78,7 @@ export function createAgentRuntimeContext(
|
|
|
75
78
|
const { browser: rawBrowser, ...rest } = input;
|
|
76
79
|
return Object.freeze({
|
|
77
80
|
...rest,
|
|
81
|
+
output: resolveOutputContract(input.surface, input.output),
|
|
78
82
|
...(rawBrowser
|
|
79
83
|
? {
|
|
80
84
|
browser: normalizeBrowserRuntime(rawBrowser),
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { mkdir, stat } from 'node:fs/promises';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import lockfile from 'proper-lockfile';
|
|
6
|
+
/** Shared heartbeat protocol for local file-backed stores, not a database lock.
|
|
7
|
+
* Never reclaim legacy regular-file locks: old hosts do not speak this protocol.
|
|
8
|
+
* proper-lockfile fails closed on compromised ownership (its default handler).
|
|
9
|
+
*/
|
|
10
|
+
export async function acquireStateFileLock(path, options = {}) {
|
|
11
|
+
const { signal, waitMs = 15_000, label = 'STATE' } = options;
|
|
12
|
+
signal?.throwIfAborted();
|
|
13
|
+
const target = resolve(path);
|
|
14
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
15
|
+
const deadline = Date.now() + waitMs;
|
|
16
|
+
while (true) {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
const legacy = await stat(`${target}.lock`).catch((error) => {
|
|
19
|
+
if (error.code === 'ENOENT')
|
|
20
|
+
return null;
|
|
21
|
+
throw error;
|
|
22
|
+
});
|
|
23
|
+
if (legacy?.isFile()) {
|
|
24
|
+
throw new Error(`${label}_LEGACY_LOCK:请停止旧版本宿主并检查遗留锁:${target}.lock`);
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
let owned = false;
|
|
28
|
+
let identity;
|
|
29
|
+
const guardedFs = {
|
|
30
|
+
...fs,
|
|
31
|
+
rmdir(lockPath, callback) {
|
|
32
|
+
if (!owned)
|
|
33
|
+
return fs.rmdir(lockPath, callback);
|
|
34
|
+
// Also guard immediate release, before the next heartbeat could detect
|
|
35
|
+
// replacement. Never recursively remove a lock directory.
|
|
36
|
+
fs.stat(lockPath, (error, current) => {
|
|
37
|
+
if (error || !identity || current.dev !== identity.dev ||
|
|
38
|
+
current.ino !== identity.ino || current.birthtimeMs !== identity.birthtimeMs) {
|
|
39
|
+
callback(Object.assign(new Error(`锁所有权已丢失:${target}`), { code: 'ECOMPROMISED' }));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
fs.rmdir(lockPath, callback);
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
const release = await lockfile.lock(target, {
|
|
47
|
+
fs: guardedFs,
|
|
48
|
+
realpath: false,
|
|
49
|
+
retries: 0,
|
|
50
|
+
stale: 120_000,
|
|
51
|
+
update: 10_000,
|
|
52
|
+
});
|
|
53
|
+
owned = true;
|
|
54
|
+
try {
|
|
55
|
+
identity = await stat(`${target}.lock`);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
await release().catch(() => undefined);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
if (signal?.aborted) {
|
|
62
|
+
await release();
|
|
63
|
+
signal.throwIfAborted();
|
|
64
|
+
}
|
|
65
|
+
return release;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error.code !== 'ELOCKED')
|
|
69
|
+
throw error;
|
|
70
|
+
if (Date.now() >= deadline)
|
|
71
|
+
throw new Error(`${label}_LOCK_TIMEOUT:等待文件锁超时:${target}`);
|
|
72
|
+
await delay(40, undefined, { signal });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { mkdir, stat } from 'node:fs/promises';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import lockfile from 'proper-lockfile';
|
|
6
|
+
|
|
7
|
+
/** Shared heartbeat protocol for local file-backed stores, not a database lock.
|
|
8
|
+
* Never reclaim legacy regular-file locks: old hosts do not speak this protocol.
|
|
9
|
+
* proper-lockfile fails closed on compromised ownership (its default handler).
|
|
10
|
+
*/
|
|
11
|
+
export async function acquireStateFileLock(
|
|
12
|
+
path: string,
|
|
13
|
+
options: { signal?: AbortSignal; waitMs?: number; label?: string } = {},
|
|
14
|
+
): Promise<() => Promise<void>> {
|
|
15
|
+
const { signal, waitMs = 15_000, label = 'STATE' } = options;
|
|
16
|
+
signal?.throwIfAborted();
|
|
17
|
+
const target = resolve(path);
|
|
18
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
19
|
+
const deadline = Date.now() + waitMs;
|
|
20
|
+
while (true) {
|
|
21
|
+
signal?.throwIfAborted();
|
|
22
|
+
const legacy = await stat(`${target}.lock`).catch((error) => {
|
|
23
|
+
if (error.code === 'ENOENT') return null;
|
|
24
|
+
throw error;
|
|
25
|
+
});
|
|
26
|
+
if (legacy?.isFile()) {
|
|
27
|
+
throw new Error(`${label}_LEGACY_LOCK:请停止旧版本宿主并检查遗留锁:${target}.lock`);
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
let owned = false;
|
|
31
|
+
let identity: fs.Stats | undefined;
|
|
32
|
+
const guardedFs = {
|
|
33
|
+
...fs,
|
|
34
|
+
rmdir(lockPath: fs.PathLike, callback: fs.NoParamCallback) {
|
|
35
|
+
if (!owned) return fs.rmdir(lockPath, callback);
|
|
36
|
+
// Also guard immediate release, before the next heartbeat could detect
|
|
37
|
+
// replacement. Never recursively remove a lock directory.
|
|
38
|
+
fs.stat(lockPath, (error, current) => {
|
|
39
|
+
if (error || !identity || current.dev !== identity.dev ||
|
|
40
|
+
current.ino !== identity.ino || current.birthtimeMs !== identity.birthtimeMs) {
|
|
41
|
+
callback(Object.assign(new Error(`锁所有权已丢失:${target}`), { code: 'ECOMPROMISED' }));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
fs.rmdir(lockPath, callback);
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
const release = await lockfile.lock(target, {
|
|
49
|
+
fs: guardedFs,
|
|
50
|
+
realpath: false,
|
|
51
|
+
retries: 0,
|
|
52
|
+
stale: 120_000,
|
|
53
|
+
update: 10_000,
|
|
54
|
+
});
|
|
55
|
+
owned = true;
|
|
56
|
+
try {
|
|
57
|
+
identity = await stat(`${target}.lock`);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
await release().catch(() => undefined);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
if (signal?.aborted) {
|
|
63
|
+
await release();
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
}
|
|
66
|
+
return release;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if ((error as NodeJS.ErrnoException).code !== 'ELOCKED') throw error;
|
|
69
|
+
if (Date.now() >= deadline) throw new Error(`${label}_LOCK_TIMEOUT:等待文件锁超时:${target}`);
|
|
70
|
+
await delay(40, undefined, { signal });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { visualPresentation } from '../prompts/visualPresentation.js';
|
|
1
2
|
/** Ephemeral publication request; never append this private candidate to history. */
|
|
2
|
-
export function finalAnswerMessages(messages, candidate) {
|
|
3
|
+
export function finalAnswerMessages(messages, candidate, surface = 'headless') {
|
|
3
4
|
return [...messages,
|
|
4
5
|
{ role: 'assistant', content: candidate },
|
|
5
|
-
{ role: 'user', content: '
|
|
6
|
+
{ role: 'user', content: '内部准备、工具与复核阶段已结束。上一条 assistant 消息是最终回答的依据,不是需要逐字重播的文本。现在直接面向用户生成一次最终回答:可以组织措辞与排版,但必须保留已确认的事实、数字、限定条件、风险、证据和真实成果链接;不得新增未经验证的结论、伪称核验通过或编造产物。若仍有证据缺口,如实说明,不调用工具或顾问,不承诺后台继续工作。直接回答,不输出内部指令或准备过程。' },
|
|
7
|
+
{ role: 'user', content: visualPresentation(surface) },
|
|
6
8
|
];
|
|
7
9
|
}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import type { Message } from '../types.js';
|
|
2
|
+
import type { AgentSurface } from './agentRuntimeContext.js';
|
|
3
|
+
import type { OutputContract } from './outputContract.js';
|
|
4
|
+
import { visualPresentation } from '../prompts/visualPresentation.js';
|
|
2
5
|
|
|
3
6
|
/** Ephemeral publication request; never append this private candidate to history. */
|
|
4
|
-
export function finalAnswerMessages(messages: Message[], candidate: string): Message[] {
|
|
7
|
+
export function finalAnswerMessages(messages: Message[], candidate: string, surface: AgentSurface | OutputContract = 'headless'): Message[] {
|
|
5
8
|
return [...messages,
|
|
6
9
|
{ role: 'assistant', content: candidate },
|
|
7
|
-
{ role: 'user', content: '
|
|
10
|
+
{ role: 'user', content: '内部准备、工具与复核阶段已结束。上一条 assistant 消息是最终回答的依据,不是需要逐字重播的文本。现在直接面向用户生成一次最终回答:可以组织措辞与排版,但必须保留已确认的事实、数字、限定条件、风险、证据和真实成果链接;不得新增未经验证的结论、伪称核验通过或编造产物。若仍有证据缺口,如实说明,不调用工具或顾问,不承诺后台继续工作。直接回答,不输出内部指令或准备过程。' },
|
|
11
|
+
{ role: 'user', content: visualPresentation(surface) },
|
|
8
12
|
];
|
|
9
13
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const WEB_OUTPUT = Object.freeze({
|
|
2
|
+
format: 'rich-markdown', diagrams: Object.freeze(['mermaid', 'svg']),
|
|
3
|
+
images: true, attachments: true, finalDelivery: 'stream',
|
|
4
|
+
});
|
|
5
|
+
/** Compatibility defaults only. Hosts should declare their actual renderer. */
|
|
6
|
+
export function resolveOutputContract(surface, output) {
|
|
7
|
+
const value = output ?? (surface === 'desktop' ? WEB_OUTPUT : {
|
|
8
|
+
format: surface === 'tui' || surface === 'cli' ? 'terminal' : 'unknown',
|
|
9
|
+
diagrams: [], images: false, attachments: false,
|
|
10
|
+
finalDelivery: surface === 'tui' ? 'stream' : 'atomic',
|
|
11
|
+
});
|
|
12
|
+
return Object.freeze({ ...value, diagrams: Object.freeze(value.format === 'rich-markdown' ? [...new Set(value.diagrams)] : []) });
|
|
13
|
+
}
|
|
14
|
+
/** Publication changes tool access, not the renderer or local execution rights. */
|
|
15
|
+
export function toolsForResponsePhase(tools, phase) {
|
|
16
|
+
return phase === 'publication' ? [] : [...tools];
|
|
17
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AgentSurface } from './agentRuntimeContext.js';
|
|
2
|
+
|
|
3
|
+
/** Trusted host presentation declaration, never an execution permission. */
|
|
4
|
+
export interface OutputContract {
|
|
5
|
+
readonly format: 'rich-markdown' | 'terminal' | 'structured' | 'unknown';
|
|
6
|
+
readonly diagrams: readonly ('mermaid' | 'svg')[];
|
|
7
|
+
readonly images: boolean;
|
|
8
|
+
readonly attachments: boolean;
|
|
9
|
+
readonly finalDelivery: 'stream' | 'atomic';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const WEB_OUTPUT: OutputContract = Object.freeze({
|
|
13
|
+
format: 'rich-markdown', diagrams: Object.freeze(['mermaid', 'svg'] as const),
|
|
14
|
+
images: true, attachments: true, finalDelivery: 'stream',
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
/** Compatibility defaults only. Hosts should declare their actual renderer. */
|
|
18
|
+
export function resolveOutputContract(surface: AgentSurface, output?: OutputContract): OutputContract {
|
|
19
|
+
const value: OutputContract = output ?? (surface === 'desktop' ? WEB_OUTPUT : {
|
|
20
|
+
format: surface === 'tui' || surface === 'cli' ? 'terminal' : 'unknown',
|
|
21
|
+
diagrams: [], images: false, attachments: false,
|
|
22
|
+
finalDelivery: surface === 'tui' ? 'stream' : 'atomic',
|
|
23
|
+
});
|
|
24
|
+
return Object.freeze({ ...value, diagrams: Object.freeze(
|
|
25
|
+
value.format === 'rich-markdown' ? [...new Set(value.diagrams)] : [],
|
|
26
|
+
) });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type ResponsePhase = 'preparation' | 'publication';
|
|
30
|
+
|
|
31
|
+
/** Publication changes tool access, not the renderer or local execution rights. */
|
|
32
|
+
export function toolsForResponsePhase<T>(tools: readonly T[], phase: ResponsePhase): T[] {
|
|
33
|
+
return phase === 'publication' ? [] : [...tools];
|
|
34
|
+
}
|
|
@@ -5,7 +5,8 @@ import { listSessionSummaries, updateSessionMetadata, } from '../context/session
|
|
|
5
5
|
import { workspaceIndexService } from '../context/workspaceIndex.js';
|
|
6
6
|
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
7
7
|
import { modelRefFromLegacy } from '../modelRef.js';
|
|
8
|
-
import {
|
|
8
|
+
import { browserPromptRuntime, buildTransientPromptBundle, } from '../prompts/system.js';
|
|
9
|
+
import { assembleStablePrompt } from '../prompts/promptAssembly.js';
|
|
9
10
|
import { createAgentRuntimeContext, filterToolsForRuntime, memoryContextFromRuntime, } from '../runtime/agentRuntimeContext.js';
|
|
10
11
|
import { filterToolsForCategories } from '../team/toolPolicy.js';
|
|
11
12
|
import { ALL_TOOLS } from '../tools/index.js';
|
|
@@ -119,6 +120,7 @@ deps = {}) {
|
|
|
119
120
|
// 稳定层进 history[0](runTurn 每轮重写它,必须逐字节可复现,见 runTurn.ts 的缓存不变量);
|
|
120
121
|
// 易变层每轮单独计算,仅附加到当前用户消息的模型副本。
|
|
121
122
|
const runtimeContext = createAgentRuntimeContext({
|
|
123
|
+
output: opts.output,
|
|
122
124
|
surface: 'headless',
|
|
123
125
|
profile: 'main',
|
|
124
126
|
cwd: effectiveCwd,
|
|
@@ -146,11 +148,14 @@ deps = {}) {
|
|
|
146
148
|
const turnTools = provider.source === 'gateway'
|
|
147
149
|
? filterToolsForCategories(runtimeTools, effectiveGatewayCategories)
|
|
148
150
|
: runtimeTools;
|
|
149
|
-
const systemPrompt = await
|
|
151
|
+
const systemPrompt = await assembleStablePrompt({ cwd: effectiveCwd, tools: turnTools, runtime: {
|
|
152
|
+
surface: runtimeContext.surface, output: runtimeContext.output,
|
|
153
|
+
} });
|
|
150
154
|
const transientBundle = await buildTransientPromptBundle({
|
|
151
155
|
cwd: effectiveCwd,
|
|
152
156
|
tools: turnTools,
|
|
153
157
|
runtime: {
|
|
158
|
+
output: runtimeContext.output,
|
|
154
159
|
surface: 'headless',
|
|
155
160
|
cwd: effectiveCwd,
|
|
156
161
|
workspaceId: workspace?.id,
|
|
@@ -9,10 +9,10 @@ import { workspaceIndexService } from '../context/workspaceIndex.js';
|
|
|
9
9
|
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
10
10
|
import { type ModelRef, modelRefFromLegacy } from '../modelRef.js';
|
|
11
11
|
import {
|
|
12
|
-
buildBaseSystemPrompt,
|
|
13
12
|
browserPromptRuntime,
|
|
14
13
|
buildTransientPromptBundle,
|
|
15
14
|
} from '../prompts/system.js';
|
|
15
|
+
import { assembleStablePrompt } from '../prompts/promptAssembly.js';
|
|
16
16
|
import {
|
|
17
17
|
createAgentRuntimeContext,
|
|
18
18
|
filterToolsForRuntime,
|
|
@@ -31,6 +31,7 @@ import {
|
|
|
31
31
|
} from './sessionState.js';
|
|
32
32
|
|
|
33
33
|
export interface RunAgentTurnOptions {
|
|
34
|
+
output?: import('../runtime/outputContract.js').OutputContract;
|
|
34
35
|
/** Host execution identity: distinct triggers must not reuse completed plugin work. */
|
|
35
36
|
executionId?: string;
|
|
36
37
|
input: string;
|
|
@@ -178,6 +179,7 @@ export async function runAgentTurn(
|
|
|
178
179
|
// 稳定层进 history[0](runTurn 每轮重写它,必须逐字节可复现,见 runTurn.ts 的缓存不变量);
|
|
179
180
|
// 易变层每轮单独计算,仅附加到当前用户消息的模型副本。
|
|
180
181
|
const runtimeContext = createAgentRuntimeContext({
|
|
182
|
+
output: opts.output,
|
|
181
183
|
surface: 'headless',
|
|
182
184
|
profile: 'main',
|
|
183
185
|
cwd: effectiveCwd,
|
|
@@ -216,11 +218,14 @@ export async function runAgentTurn(
|
|
|
216
218
|
provider.source === 'gateway'
|
|
217
219
|
? filterToolsForCategories(runtimeTools, effectiveGatewayCategories)
|
|
218
220
|
: runtimeTools;
|
|
219
|
-
const systemPrompt = await
|
|
221
|
+
const systemPrompt = await assembleStablePrompt({ cwd: effectiveCwd, tools: turnTools, runtime: {
|
|
222
|
+
surface: runtimeContext.surface, output: runtimeContext.output,
|
|
223
|
+
} });
|
|
220
224
|
const transientBundle = await buildTransientPromptBundle({
|
|
221
225
|
cwd: effectiveCwd,
|
|
222
226
|
tools: turnTools,
|
|
223
227
|
runtime: {
|
|
228
|
+
output: runtimeContext.output,
|
|
224
229
|
surface: 'headless',
|
|
225
230
|
cwd: effectiveCwd,
|
|
226
231
|
workspaceId: workspace?.id,
|
|
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { mkdir, open, readFile, readdir, rename, rm, stat, } from 'node:fs/promises';
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { agentStateDir } from '../context/agentHome.js';
|
|
5
|
+
import { acquireStateFileLock } from '../runtime/fileLock.js';
|
|
5
6
|
function segment(value, fallback) {
|
|
6
7
|
return ((value ?? fallback).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 120) ||
|
|
7
8
|
fallback);
|
|
@@ -20,38 +21,20 @@ export async function withRuntimeFileLock(path, work) {
|
|
|
20
21
|
const tail = previous.then(() => current);
|
|
21
22
|
queues.set(key, tail);
|
|
22
23
|
await previous.catch(() => undefined);
|
|
23
|
-
let
|
|
24
|
-
const lockPath = `${path}.lock`;
|
|
24
|
+
let unlock;
|
|
25
25
|
try {
|
|
26
|
-
await
|
|
27
|
-
const deadline = Date.now() + 10_000;
|
|
28
|
-
while (!lockHandle) {
|
|
29
|
-
try {
|
|
30
|
-
lockHandle = await open(lockPath, 'wx', 0o600);
|
|
31
|
-
await lockHandle.writeFile(`${process.pid}\n${Date.now()}\n`);
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
if (error.code !== 'EEXIST')
|
|
35
|
-
throw error;
|
|
36
|
-
const age = Date.now() -
|
|
37
|
-
(await stat(lockPath).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;
|
|
38
|
-
if (age > 30_000)
|
|
39
|
-
await rm(lockPath, { force: true });
|
|
40
|
-
else if (Date.now() >= deadline)
|
|
41
|
-
throw new Error(`runtime lock timeout: ${path}`);
|
|
42
|
-
else
|
|
43
|
-
await new Promise((r) => setTimeout(r, 25));
|
|
44
|
-
}
|
|
45
|
-
}
|
|
26
|
+
unlock = await acquireStateFileLock(key, { label: 'RUNTIME' });
|
|
46
27
|
return await work();
|
|
47
28
|
}
|
|
48
29
|
finally {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
queues.
|
|
30
|
+
try {
|
|
31
|
+
await unlock?.();
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
release();
|
|
35
|
+
if (queues.get(key) === tail)
|
|
36
|
+
queues.delete(key);
|
|
37
|
+
}
|
|
55
38
|
}
|
|
56
39
|
}
|
|
57
40
|
export async function readRuntimeJson(path, fallback) {
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import { dirname, join, resolve } from 'node:path';
|
|
12
12
|
|
|
13
13
|
import { agentStateDir } from '../context/agentHome.js';
|
|
14
|
+
import { acquireStateFileLock } from '../runtime/fileLock.js';
|
|
14
15
|
|
|
15
16
|
export interface RuntimeIdentity {
|
|
16
17
|
workspaceId?: string;
|
|
@@ -47,32 +48,17 @@ export async function withRuntimeFileLock<T>(
|
|
|
47
48
|
const tail = previous.then(() => current);
|
|
48
49
|
queues.set(key, tail);
|
|
49
50
|
await previous.catch(() => undefined);
|
|
50
|
-
let
|
|
51
|
-
const lockPath = `${path}.lock`;
|
|
51
|
+
let unlock: (() => Promise<void>) | undefined;
|
|
52
52
|
try {
|
|
53
|
-
await
|
|
54
|
-
const deadline = Date.now() + 10_000;
|
|
55
|
-
while (!lockHandle) {
|
|
56
|
-
try {
|
|
57
|
-
lockHandle = await open(lockPath, 'wx', 0o600);
|
|
58
|
-
await lockHandle.writeFile(`${process.pid}\n${Date.now()}\n`);
|
|
59
|
-
} catch (error) {
|
|
60
|
-
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
|
|
61
|
-
const age =
|
|
62
|
-
Date.now() -
|
|
63
|
-
(await stat(lockPath).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;
|
|
64
|
-
if (age > 30_000) await rm(lockPath, { force: true });
|
|
65
|
-
else if (Date.now() >= deadline)
|
|
66
|
-
throw new Error(`runtime lock timeout: ${path}`);
|
|
67
|
-
else await new Promise((r) => setTimeout(r, 25));
|
|
68
|
-
}
|
|
69
|
-
}
|
|
53
|
+
unlock = await acquireStateFileLock(key, { label: 'RUNTIME' });
|
|
70
54
|
return await work();
|
|
71
55
|
} finally {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
56
|
+
try {
|
|
57
|
+
await unlock?.();
|
|
58
|
+
} finally {
|
|
59
|
+
release();
|
|
60
|
+
if (queues.get(key) === tail) queues.delete(key);
|
|
61
|
+
}
|
|
76
62
|
}
|
|
77
63
|
}
|
|
78
64
|
|