minimal-agent 0.18.13 → 0.18.15
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 +2 -2
- package/package.json +1 -3
- package/plugins/workflow-runner/src/runtime/context.js +1 -1
- package/plugins/workflow-runner/src/runtime/context.ts +1 -1
- package/plugins/workflow-runner/test/embeddedExecution.test.ts +2 -5
- package/plugins/workflow-runner/test/execLifetime.test.ts +15 -2
- package/skills/ssh-remote-dev/SKILL.md +61 -0
- package/skills/ssh-remote-dev/agents/openai.yaml +4 -0
- package/src/advisor/README.md +62 -24
- package/src/advisor/advisorNudge.js +199 -0
- package/src/advisor/advisorNudge.ts +232 -0
- package/src/advisor/deliveryReview.js +35 -12
- package/src/advisor/deliveryReview.ts +35 -11
- package/src/advisor/presentation.js +7 -10
- package/src/advisor/presentation.ts +10 -13
- package/src/advisor/reviewContext.js +22 -58
- package/src/advisor/reviewContext.ts +24 -67
- package/src/cli/configMenu.js +17 -128
- package/src/cli/configMenu.tsx +17 -193
- package/src/cli/print.js +2 -0
- package/src/cli/print.ts +2 -0
- package/src/cli/streamJson.js +2 -0
- package/src/cli/streamJson.ts +2 -0
- package/src/cli/wizards/advisorWizard.js +9 -7
- package/src/cli/wizards/advisorWizard.tsx +9 -7
- package/src/cli/wizards/contextAdvisorWizard.js +9 -7
- package/src/cli/wizards/contextAdvisorWizard.tsx +9 -7
- package/src/cli/wizards/providerPresets.js +55 -18
- package/src/cli/wizards/providerPresets.ts +72 -19
- package/src/cli/wizards/providerWizard.js +51 -10
- package/src/cli/wizards/providerWizard.tsx +59 -9
- package/src/config/configDefaults.js +1 -1
- package/src/config/configDefaults.ts +1 -1
- package/src/config/configDiagnostics.js +1 -21
- package/src/config/configDiagnostics.ts +3 -23
- package/src/config/configFile.js +11 -4
- package/src/config/configFile.ts +27 -7
- package/src/config/configManagement.js +1 -0
- package/src/config/configManagement.ts +2 -0
- package/src/config/configService.js +12 -8
- package/src/config/configService.ts +16 -11
- package/src/config/numericLimits.js +0 -4
- package/src/config/numericLimits.ts +0 -4
- package/src/config/reasoningEffort.js +16 -0
- package/src/config/reasoningEffort.ts +18 -0
- package/src/context/budgetPlan.js +1 -1
- package/src/context/budgetPlan.ts +1 -1
- package/src/context/optimizeConversation.js +1 -1
- package/src/context/optimizeConversation.ts +1 -1
- package/src/harness/stallGuard.js +8 -13
- package/src/harness/stallGuard.ts +8 -12
- package/src/llm/client.js +64 -17
- package/src/llm/client.ts +62 -7
- package/src/llm/providers/anthropicFormat.js +3 -1
- package/src/llm/providers/anthropicFormat.ts +4 -1
- package/src/llm/providers/openaiFormat.js +14 -3
- package/src/llm/providers/openaiFormat.ts +17 -3
- package/src/llm/providers/responsesFormat.js +277 -0
- package/src/llm/providers/responsesFormat.ts +308 -0
- package/src/loop/README.md +18 -3
- package/src/loop/liveDiagramGate.js +63 -0
- package/src/loop/liveDiagramGate.ts +61 -0
- package/src/loop/messages.js +12 -0
- package/src/loop/messages.ts +13 -0
- package/src/loop/options.ts +7 -2
- package/src/loop/toolBatch.js +0 -1
- package/src/loop/toolBatch.ts +0 -1
- package/src/loop/toolExecutor.js +11 -46
- package/src/loop/toolExecutor.ts +12 -55
- package/src/loop/toolPresentation.js +2 -13
- package/src/loop/toolPresentation.ts +2 -13
- package/src/loop/toolSemantics.js +3 -4
- package/src/loop/toolSemantics.ts +4 -6
- package/src/loop.js +222 -214
- package/src/loop.ts +226 -232
- package/src/memory/dependencies.js +11 -3
- package/src/memory/dependencies.ts +11 -3
- package/src/memory/episodicMemory.js +59 -18
- package/src/memory/episodicMemory.ts +58 -18
- package/src/memory/experienceStore.js +4 -3
- package/src/memory/experienceStore.ts +4 -3
- package/src/memory/factCandidates.js +53 -1
- package/src/memory/factCandidates.ts +54 -1
- package/src/memory/factLearning.js +2 -2
- package/src/memory/factLearning.ts +2 -2
- package/src/memory/jobPolicy.js +24 -5
- package/src/memory/jobPolicy.ts +25 -5
- package/src/memory/learning.js +2 -2
- package/src/memory/learning.ts +2 -2
- package/src/memory/learningModel.js +7 -0
- package/src/memory/learningModel.ts +7 -0
- package/src/memory/managementService.js +8 -7
- package/src/memory/managementService.ts +16 -8
- package/src/memory/memoryService.js +104 -33
- package/src/memory/memoryService.ts +132 -28
- package/src/memory/projectKnowledge.js +39 -3
- package/src/memory/projectKnowledge.ts +45 -3
- package/src/memory/recallQuery.js +56 -0
- package/src/memory/recallQuery.ts +58 -0
- package/src/memory/retrieval.js +39 -10
- package/src/memory/retrieval.ts +46 -11
- package/src/memory/turnJournal.js +75 -10
- package/src/memory/turnJournal.ts +66 -10
- package/src/memory/types.ts +7 -1
- package/src/prompts/delegation.js +2 -1
- package/src/prompts/delegation.ts +3 -1
- package/src/prompts/policyRegistry.js +9 -12
- package/src/prompts/policyRegistry.ts +9 -12
- package/src/prompts/promptAssembly.js +6 -5
- package/src/prompts/promptAssembly.ts +8 -6
- package/src/prompts/visualPresentation.js +39 -10
- package/src/prompts/visualPresentation.ts +38 -9
- package/src/runtime/answerPreparation.js +1 -1
- package/src/runtime/answerPreparation.ts +1 -1
- package/src/runtime/commandCatalog.js +1 -0
- package/src/runtime/commandCatalog.ts +9 -0
- package/src/runtime/fileLock.js +19 -3
- package/src/runtime/fileLock.ts +19 -3
- package/src/runtime/invocationPolicy.js +1 -1
- package/src/runtime/invocationPolicy.ts +1 -1
- package/src/runtime/outputContract.js +0 -4
- package/src/runtime/outputContract.ts +0 -7
- package/src/session/runAgentTurn.js +3 -0
- package/src/session/runAgentTurn.ts +3 -0
- package/src/team/onlineToolContract.js +0 -1
- package/src/team/onlineToolContract.ts +0 -1
- package/src/tools/advisor/advisor.js +207 -365
- package/src/tools/advisor/advisor.ts +211 -383
- package/src/tools/agent/agentTypes.js +0 -1
- package/src/tools/agent/agentTypes.ts +0 -1
- package/src/tools/agent/coordinator.js +4 -1
- package/src/tools/agent/coordinator.ts +4 -1
- package/src/tools/bash/semantics.js +4 -5
- package/src/tools/bash/semantics.ts +4 -5
- package/src/tools/capabilities.js +2 -3
- package/src/tools/capabilities.ts +2 -4
- package/src/tools/index.js +0 -16
- package/src/tools/index.ts +0 -16
- package/src/tools/memory/maintenance.js +8 -9
- package/src/tools/memory/maintenance.ts +13 -11
- package/src/tools/memory/memory.js +5 -1
- package/src/tools/memory/memory.ts +5 -0
- package/src/tools/optimizeConversation/README.md +4 -6
- package/src/tools/toolPromptGuides.js +2 -9
- package/src/tools/toolPromptGuides.ts +2 -9
- package/src/types.ts +28 -105
- package/src/ui/App.js +22 -1
- package/src/ui/App.tsx +26 -1
- package/src/ui/MessageList.js +8 -44
- package/src/ui/MessageList.tsx +3 -81
- package/src/ui/effortCommand.js +19 -0
- package/src/ui/effortCommand.ts +36 -0
- package/src/ui/hooks/useChat.js +2 -0
- package/src/ui/hooks/useChat.ts +2 -0
- package/src/ui/toolProgress.js +1 -1
- package/src/ui/toolProgress.ts +1 -1
- package/src/web/protocol.ts +10 -3
- package/src/advisor/advisorCoordinator.js +0 -734
- package/src/advisor/advisorCoordinator.ts +0 -825
- package/src/cli/wizards/sshHostWizard.js +0 -156
- package/src/cli/wizards/sshHostWizard.tsx +0 -214
- package/src/context/sshHosts.js +0 -290
- package/src/context/sshHosts.ts +0 -312
- package/src/loop/publication.js +0 -94
- package/src/loop/publication.ts +0 -124
- package/src/runtime/finalAnswer.js +0 -9
- package/src/runtime/finalAnswer.ts +0 -13
- package/src/tools/advisor/advisorDecision.js +0 -79
- package/src/tools/advisor/advisorDecision.ts +0 -92
- package/src/tools/ssh/ssh.js +0 -152
- package/src/tools/ssh/ssh.ts +0 -167
- package/src/tools/ssh/sshAvailability.js +0 -35
- package/src/tools/ssh/sshAvailability.ts +0 -39
- package/src/tools/ssh/sshClient.js +0 -177
- package/src/tools/ssh/sshClient.ts +0 -189
- package/src/tools/ssh/sshDownload.js +0 -77
- package/src/tools/ssh/sshDownload.ts +0 -92
- package/src/tools/ssh/sshHostsTool.js +0 -36
- package/src/tools/ssh/sshHostsTool.ts +0 -48
- package/src/tools/ssh/sshUpload.js +0 -72
- package/src/tools/ssh/sshUpload.ts +0 -85
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================
|
|
3
|
+
* src/llm/providers/responsesFormat.ts —— OpenAI Responses API 协议
|
|
4
|
+
* ------------------------------------------------------------
|
|
5
|
+
* ⚠️ 未经真实端点验证:本机没有可用于付费调用的 OpenAI key,请求体与 SSE 事件字段
|
|
6
|
+
* 照官方文档(POST /v1/responses,stream:true)实现,配了手写的 SSE 录像单测,
|
|
7
|
+
* 没有做过真实 round-trip。拿到 key 后先跑一次真实对话冒烟(含一次工具调用)。
|
|
8
|
+
*
|
|
9
|
+
* 与 openaiFormat.ts / anthropicFormat.ts 同一分工:这里只做「内部 Message[]/Tool[]
|
|
10
|
+
* ⇄ Responses 协议形状」的翻译 + SSE 逐帧解析;重试/退避/空闲看门狗/就地退化
|
|
11
|
+
* 留在 client.ts。
|
|
12
|
+
*
|
|
13
|
+
* 设计取舍(都是为了让它在不依赖服务端会话状态的前提下正确):
|
|
14
|
+
* - 无状态:`store:false`,每次请求重发完整历史,不用 previous_response_id。
|
|
15
|
+
* 与本项目「history 是唯一事实源、压缩/快照在本地」的前提一致。
|
|
16
|
+
* - 工具 `strict:false`:Responses 的函数工具默认 strict:true,要求
|
|
17
|
+
* additionalProperties:false 且全字段 required;本项目的工具 schema 不满足,
|
|
18
|
+
* 不显式关掉就会整批 400。
|
|
19
|
+
* - 回传的 function_call 只带 call_id/name/arguments,**不带 id**:带上 fc_ id
|
|
20
|
+
* 而缺少配对的 reasoning 项,服务端会报错;无状态重发不保存 reasoning 项,
|
|
21
|
+
* 所以只能不带。代价是推理模型在多轮工具调用间丢失上一轮的推理上下文
|
|
22
|
+
* (质量略降,不影响正确性)。
|
|
23
|
+
* - 不请求 reasoning.summary:部分组织需要先做身份验证才能拿推理摘要,
|
|
24
|
+
* 请求了反而 400。服务端若主动发摘要增量,照常显示为思维链。
|
|
25
|
+
* ============================================================
|
|
26
|
+
*/
|
|
27
|
+
function userContent(content) {
|
|
28
|
+
if (typeof content === 'string')
|
|
29
|
+
return content;
|
|
30
|
+
return content.map((part) => {
|
|
31
|
+
if (part.type === 'text')
|
|
32
|
+
return { type: 'input_text', text: part.text };
|
|
33
|
+
if (part.type === 'image_url') {
|
|
34
|
+
const detail = part.image_url.detail;
|
|
35
|
+
return {
|
|
36
|
+
type: 'input_image',
|
|
37
|
+
image_url: part.image_url.url,
|
|
38
|
+
// 'default' 是本项目内部取值,Responses 只认 auto/low/high。
|
|
39
|
+
detail: detail === 'low' || detail === 'high' ? detail : 'auto',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return { type: 'input_text', text: '[视频内容未发送:Responses 格式的 provider 暂不支持视频输入]' };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** 内部 Message[](OpenAI Chat 形状)→ Responses 的 input 数组。 */
|
|
46
|
+
export function toResponsesInput(messages) {
|
|
47
|
+
const input = [];
|
|
48
|
+
for (const message of messages) {
|
|
49
|
+
if (message.role === 'system') {
|
|
50
|
+
input.push({ role: 'system', content: message.content });
|
|
51
|
+
}
|
|
52
|
+
else if (message.role === 'user') {
|
|
53
|
+
input.push({ role: 'user', content: userContent(message.content) });
|
|
54
|
+
}
|
|
55
|
+
else if (message.role === 'assistant') {
|
|
56
|
+
if (message.content) {
|
|
57
|
+
input.push({ role: 'assistant', content: [{ type: 'output_text', text: message.content }] });
|
|
58
|
+
}
|
|
59
|
+
for (const call of message.tool_calls ?? []) {
|
|
60
|
+
input.push({
|
|
61
|
+
type: 'function_call',
|
|
62
|
+
call_id: call.id,
|
|
63
|
+
name: call.function.name,
|
|
64
|
+
arguments: call.function.arguments || '{}',
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
input.push({ type: 'function_call_output', call_id: message.tool_call_id, output: message.content });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return input;
|
|
73
|
+
}
|
|
74
|
+
function looksLikeVersionedBase(url) {
|
|
75
|
+
try {
|
|
76
|
+
const path = new URL(url).pathname.replace(/\/+$/, '');
|
|
77
|
+
if (path === '' || path === '/')
|
|
78
|
+
return true;
|
|
79
|
+
return /^v\d+/.test(path.split('/').at(-1));
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** baseURL 是完整端点(以 /responses 结尾);只有「版本化基础路径」才自动补后缀。 */
|
|
86
|
+
export function buildResponsesUrl(provider) {
|
|
87
|
+
const url = provider.baseURL.trim().replace(/\/+$/, '');
|
|
88
|
+
if (!url || url.endsWith('/responses'))
|
|
89
|
+
return url;
|
|
90
|
+
return looksLikeVersionedBase(url) ? `${url}/responses` : url;
|
|
91
|
+
}
|
|
92
|
+
export function buildResponsesRequest(args) {
|
|
93
|
+
const { provider, cleanedMessages, tools } = args;
|
|
94
|
+
const functionTools = tools.map((tool) => ({
|
|
95
|
+
type: 'function',
|
|
96
|
+
name: tool.name,
|
|
97
|
+
description: typeof tool.description === 'function' ? tool.description() : tool.description,
|
|
98
|
+
parameters: tool.parameters,
|
|
99
|
+
strict: false,
|
|
100
|
+
}));
|
|
101
|
+
const body = {
|
|
102
|
+
model: provider.model,
|
|
103
|
+
input: toResponsesInput(cleanedMessages),
|
|
104
|
+
stream: true,
|
|
105
|
+
store: false,
|
|
106
|
+
};
|
|
107
|
+
if (functionTools.length > 0) {
|
|
108
|
+
body.tools = functionTools;
|
|
109
|
+
body.tool_choice = 'auto';
|
|
110
|
+
}
|
|
111
|
+
if (args.withMaxTokens && typeof provider.maxTokens === 'number' && provider.maxTokens > 0) {
|
|
112
|
+
body.max_output_tokens = provider.maxTokens;
|
|
113
|
+
}
|
|
114
|
+
if (args.withReasoningEffort && provider.reasoningEffort) {
|
|
115
|
+
body.reasoning = { effort: provider.reasoningEffort };
|
|
116
|
+
}
|
|
117
|
+
if (args.withResponseFormat && args.responseFormat) {
|
|
118
|
+
const schema = args.responseFormat.json_schema;
|
|
119
|
+
body.text = {
|
|
120
|
+
format: {
|
|
121
|
+
type: 'json_schema',
|
|
122
|
+
name: schema.name,
|
|
123
|
+
schema: schema.schema,
|
|
124
|
+
...(schema.strict !== undefined ? { strict: schema.strict } : {}),
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (args.withPromptCacheKey && args.promptCache?.scopeKey) {
|
|
129
|
+
body.prompt_cache_key = args.promptCache.scopeKey;
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
url: buildResponsesUrl(provider),
|
|
133
|
+
headers: {
|
|
134
|
+
'Content-Type': 'application/json',
|
|
135
|
+
Authorization: `Bearer ${provider.apiKey}`,
|
|
136
|
+
},
|
|
137
|
+
body: JSON.stringify(body),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/** 400 是否在抱怨 reasoning / effort 取值(模型不支持该档位,或根本不是推理模型)。 */
|
|
141
|
+
export function isReasoningEffortRejected(status, errText) {
|
|
142
|
+
if (status !== 400 && status !== 422)
|
|
143
|
+
return false;
|
|
144
|
+
const text = errText.toLowerCase();
|
|
145
|
+
// MiniMax 对 effort:'none' 回 `requires adaptive thinking`;Anthropic 兼容端点的字段叫 output_config.effort。
|
|
146
|
+
if (!text.includes('reasoning') && !text.includes('effort') && !text.includes('adaptive thinking'))
|
|
147
|
+
return false;
|
|
148
|
+
return (text.includes('not support') ||
|
|
149
|
+
text.includes('requires') ||
|
|
150
|
+
text.includes('unsupported') ||
|
|
151
|
+
text.includes('invalid') ||
|
|
152
|
+
text.includes('not valid') ||
|
|
153
|
+
text.includes('unknown') ||
|
|
154
|
+
text.includes('unrecognized') ||
|
|
155
|
+
text.includes('unexpected') ||
|
|
156
|
+
text.includes('not allowed') ||
|
|
157
|
+
text.includes('supported values'));
|
|
158
|
+
}
|
|
159
|
+
function finiteNonNegative(value) {
|
|
160
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
161
|
+
}
|
|
162
|
+
/** 每个请求一个新实例;把 Responses 的 SSE `data:` 载荷翻成 LlmStreamEvent。 */
|
|
163
|
+
export function createResponsesSSEParser() {
|
|
164
|
+
/** output_index → 本轮第几个工具调用(loop 按 index 合并分片)。 */
|
|
165
|
+
const toolIndex = new Map();
|
|
166
|
+
const streamedArguments = new Set();
|
|
167
|
+
let stopReason = 'unknown';
|
|
168
|
+
let sawToolCall = false;
|
|
169
|
+
let promptTokens;
|
|
170
|
+
let outputTokens;
|
|
171
|
+
let cachedTokens;
|
|
172
|
+
let promptCacheUsage = { reported: false };
|
|
173
|
+
const readUsage = (usage) => {
|
|
174
|
+
if (!usage || typeof usage !== 'object')
|
|
175
|
+
return;
|
|
176
|
+
const u = usage;
|
|
177
|
+
// input_tokens 已含命中缓存的部分(与 Chat Completions 的 prompt_tokens 同语义)。
|
|
178
|
+
promptTokens = finiteNonNegative(u.input_tokens) ?? promptTokens;
|
|
179
|
+
outputTokens = finiteNonNegative(u.output_tokens) ?? outputTokens;
|
|
180
|
+
const details = u.input_tokens_details;
|
|
181
|
+
if (details && typeof details === 'object') {
|
|
182
|
+
cachedTokens = finiteNonNegative(details.cached_tokens) ?? cachedTokens;
|
|
183
|
+
}
|
|
184
|
+
promptCacheUsage = {
|
|
185
|
+
reported: cachedTokens !== undefined,
|
|
186
|
+
...(promptTokens !== undefined ? { promptTokens } : {}),
|
|
187
|
+
...(cachedTokens !== undefined ? { cacheReadTokens: cachedTokens } : {}),
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
const done = () => ({
|
|
191
|
+
type: 'done',
|
|
192
|
+
stopReason,
|
|
193
|
+
promptTokens,
|
|
194
|
+
outputTokens,
|
|
195
|
+
cachedPromptTokens: cachedTokens,
|
|
196
|
+
promptCacheUsage,
|
|
197
|
+
});
|
|
198
|
+
const indexFor = (outputIndex) => {
|
|
199
|
+
let index = toolIndex.get(outputIndex);
|
|
200
|
+
if (index === undefined) {
|
|
201
|
+
index = toolIndex.size;
|
|
202
|
+
toolIndex.set(outputIndex, index);
|
|
203
|
+
}
|
|
204
|
+
return index;
|
|
205
|
+
};
|
|
206
|
+
return {
|
|
207
|
+
buildFallbackDone: done,
|
|
208
|
+
handleData(dataStr) {
|
|
209
|
+
if (dataStr === '[DONE]')
|
|
210
|
+
return [done()];
|
|
211
|
+
let data;
|
|
212
|
+
try {
|
|
213
|
+
data = JSON.parse(dataStr);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
switch (data.type) {
|
|
219
|
+
case 'response.output_text.delta':
|
|
220
|
+
return typeof data.delta === 'string' && data.delta
|
|
221
|
+
? [{ type: 'text_delta', delta: data.delta }]
|
|
222
|
+
: [];
|
|
223
|
+
case 'response.reasoning_summary_text.delta':
|
|
224
|
+
case 'response.reasoning_text.delta':
|
|
225
|
+
return typeof data.delta === 'string' && data.delta
|
|
226
|
+
? [{ type: 'reasoning_delta', field: 'reasoning', delta: data.delta }]
|
|
227
|
+
: [];
|
|
228
|
+
case 'response.output_item.added': {
|
|
229
|
+
const item = data.item;
|
|
230
|
+
if (item?.type !== 'function_call')
|
|
231
|
+
return [];
|
|
232
|
+
sawToolCall = true;
|
|
233
|
+
// id 用 call_id(回传 function_call_output 时必须对得上),不是 fc_ 的 item id。
|
|
234
|
+
return [{ type: 'tool_call_delta', index: indexFor(data.output_index ?? 0), id: item.call_id, name: item.name }];
|
|
235
|
+
}
|
|
236
|
+
case 'response.function_call_arguments.delta': {
|
|
237
|
+
const outputIndex = data.output_index ?? 0;
|
|
238
|
+
if (typeof data.delta !== 'string' || !data.delta)
|
|
239
|
+
return [];
|
|
240
|
+
streamedArguments.add(outputIndex);
|
|
241
|
+
return [{ type: 'tool_call_delta', index: indexFor(outputIndex), argumentsDelta: data.delta }];
|
|
242
|
+
}
|
|
243
|
+
case 'response.output_item.done': {
|
|
244
|
+
// 兜底:有的网关不发 arguments.delta,只在条目完成时给完整 arguments。
|
|
245
|
+
const item = data.item;
|
|
246
|
+
const outputIndex = data.output_index ?? 0;
|
|
247
|
+
if (item?.type !== 'function_call' || streamedArguments.has(outputIndex))
|
|
248
|
+
return [];
|
|
249
|
+
sawToolCall = true;
|
|
250
|
+
const arguments_ = typeof item.arguments === 'string' ? item.arguments : '';
|
|
251
|
+
return arguments_
|
|
252
|
+
? [{ type: 'tool_call_delta', index: indexFor(outputIndex), id: item.call_id, name: item.name, argumentsDelta: arguments_ }]
|
|
253
|
+
: [];
|
|
254
|
+
}
|
|
255
|
+
case 'response.completed':
|
|
256
|
+
readUsage(data.response?.usage);
|
|
257
|
+
stopReason = sawToolCall ? 'tool_calls' : 'stop';
|
|
258
|
+
return [done()];
|
|
259
|
+
case 'response.incomplete': {
|
|
260
|
+
readUsage(data.response?.usage);
|
|
261
|
+
const reason = data.response?.incomplete_details?.reason;
|
|
262
|
+
stopReason = reason === 'max_output_tokens' ? 'length' : sawToolCall ? 'tool_calls' : 'unknown';
|
|
263
|
+
return [done()];
|
|
264
|
+
}
|
|
265
|
+
case 'response.failed': {
|
|
266
|
+
const error = data.response?.error;
|
|
267
|
+
throw new Error(`OpenAI Responses 流式响应失败:${JSON.stringify(error ?? data.response ?? data)}`);
|
|
268
|
+
}
|
|
269
|
+
case 'error':
|
|
270
|
+
throw new Error(`OpenAI Responses 流式响应报错:${JSON.stringify(data.error ?? data)}`);
|
|
271
|
+
default:
|
|
272
|
+
// response.created / in_progress / content_part.* / output_text.done 等:已知安全的 no-op。
|
|
273
|
+
return [];
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================
|
|
3
|
+
* src/llm/providers/responsesFormat.ts —— OpenAI Responses API 协议
|
|
4
|
+
* ------------------------------------------------------------
|
|
5
|
+
* ⚠️ 未经真实端点验证:本机没有可用于付费调用的 OpenAI key,请求体与 SSE 事件字段
|
|
6
|
+
* 照官方文档(POST /v1/responses,stream:true)实现,配了手写的 SSE 录像单测,
|
|
7
|
+
* 没有做过真实 round-trip。拿到 key 后先跑一次真实对话冒烟(含一次工具调用)。
|
|
8
|
+
*
|
|
9
|
+
* 与 openaiFormat.ts / anthropicFormat.ts 同一分工:这里只做「内部 Message[]/Tool[]
|
|
10
|
+
* ⇄ Responses 协议形状」的翻译 + SSE 逐帧解析;重试/退避/空闲看门狗/就地退化
|
|
11
|
+
* 留在 client.ts。
|
|
12
|
+
*
|
|
13
|
+
* 设计取舍(都是为了让它在不依赖服务端会话状态的前提下正确):
|
|
14
|
+
* - 无状态:`store:false`,每次请求重发完整历史,不用 previous_response_id。
|
|
15
|
+
* 与本项目「history 是唯一事实源、压缩/快照在本地」的前提一致。
|
|
16
|
+
* - 工具 `strict:false`:Responses 的函数工具默认 strict:true,要求
|
|
17
|
+
* additionalProperties:false 且全字段 required;本项目的工具 schema 不满足,
|
|
18
|
+
* 不显式关掉就会整批 400。
|
|
19
|
+
* - 回传的 function_call 只带 call_id/name/arguments,**不带 id**:带上 fc_ id
|
|
20
|
+
* 而缺少配对的 reasoning 项,服务端会报错;无状态重发不保存 reasoning 项,
|
|
21
|
+
* 所以只能不带。代价是推理模型在多轮工具调用间丢失上一轮的推理上下文
|
|
22
|
+
* (质量略降,不影响正确性)。
|
|
23
|
+
* - 不请求 reasoning.summary:部分组织需要先做身份验证才能拿推理摘要,
|
|
24
|
+
* 请求了反而 400。服务端若主动发摘要增量,照常显示为思维链。
|
|
25
|
+
* ============================================================
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type {
|
|
29
|
+
ChatContentPart,
|
|
30
|
+
LlmStreamEvent,
|
|
31
|
+
LocalProvider,
|
|
32
|
+
Message,
|
|
33
|
+
PromptCacheContext,
|
|
34
|
+
PromptCacheUsage,
|
|
35
|
+
Tool,
|
|
36
|
+
} from '../../types.js';
|
|
37
|
+
|
|
38
|
+
type ResponsesItem = Record<string, unknown>;
|
|
39
|
+
|
|
40
|
+
function userContent(content: string | ChatContentPart[]): unknown {
|
|
41
|
+
if (typeof content === 'string') return content;
|
|
42
|
+
return content.map((part): Record<string, unknown> => {
|
|
43
|
+
if (part.type === 'text') return { type: 'input_text', text: part.text };
|
|
44
|
+
if (part.type === 'image_url') {
|
|
45
|
+
const detail = part.image_url.detail;
|
|
46
|
+
return {
|
|
47
|
+
type: 'input_image',
|
|
48
|
+
image_url: part.image_url.url,
|
|
49
|
+
// 'default' 是本项目内部取值,Responses 只认 auto/low/high。
|
|
50
|
+
detail: detail === 'low' || detail === 'high' ? detail : 'auto',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return { type: 'input_text', text: '[视频内容未发送:Responses 格式的 provider 暂不支持视频输入]' };
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 内部 Message[](OpenAI Chat 形状)→ Responses 的 input 数组。 */
|
|
58
|
+
export function toResponsesInput(messages: readonly Message[]): ResponsesItem[] {
|
|
59
|
+
const input: ResponsesItem[] = [];
|
|
60
|
+
for (const message of messages) {
|
|
61
|
+
if (message.role === 'system') {
|
|
62
|
+
input.push({ role: 'system', content: message.content });
|
|
63
|
+
} else if (message.role === 'user') {
|
|
64
|
+
input.push({ role: 'user', content: userContent(message.content) });
|
|
65
|
+
} else if (message.role === 'assistant') {
|
|
66
|
+
if (message.content) {
|
|
67
|
+
input.push({ role: 'assistant', content: [{ type: 'output_text', text: message.content }] });
|
|
68
|
+
}
|
|
69
|
+
for (const call of message.tool_calls ?? []) {
|
|
70
|
+
input.push({
|
|
71
|
+
type: 'function_call',
|
|
72
|
+
call_id: call.id,
|
|
73
|
+
name: call.function.name,
|
|
74
|
+
arguments: call.function.arguments || '{}',
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
input.push({ type: 'function_call_output', call_id: message.tool_call_id, output: message.content });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return input;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function looksLikeVersionedBase(url: string): boolean {
|
|
85
|
+
try {
|
|
86
|
+
const path = new URL(url).pathname.replace(/\/+$/, '');
|
|
87
|
+
if (path === '' || path === '/') return true;
|
|
88
|
+
return /^v\d+/.test(path.split('/').at(-1)!);
|
|
89
|
+
} catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** baseURL 是完整端点(以 /responses 结尾);只有「版本化基础路径」才自动补后缀。 */
|
|
95
|
+
export function buildResponsesUrl(provider: LocalProvider): string {
|
|
96
|
+
const url = provider.baseURL.trim().replace(/\/+$/, '');
|
|
97
|
+
if (!url || url.endsWith('/responses')) return url;
|
|
98
|
+
return looksLikeVersionedBase(url) ? `${url}/responses` : url;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface ResponsesRequestArgs {
|
|
102
|
+
provider: LocalProvider;
|
|
103
|
+
cleanedMessages: readonly Message[];
|
|
104
|
+
tools: Tool[];
|
|
105
|
+
withMaxTokens: boolean;
|
|
106
|
+
withReasoningEffort: boolean;
|
|
107
|
+
withPromptCacheKey?: boolean;
|
|
108
|
+
promptCache?: PromptCacheContext;
|
|
109
|
+
/** 与 Chat Completions 同形状的结构化输出要求,这里翻成 text.format。 */
|
|
110
|
+
responseFormat?: {
|
|
111
|
+
type: 'json_schema';
|
|
112
|
+
json_schema: { name: string; schema: Record<string, unknown>; strict?: boolean };
|
|
113
|
+
};
|
|
114
|
+
withResponseFormat: boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function buildResponsesRequest(args: ResponsesRequestArgs): {
|
|
118
|
+
url: string;
|
|
119
|
+
headers: Record<string, string>;
|
|
120
|
+
body: string;
|
|
121
|
+
} {
|
|
122
|
+
const { provider, cleanedMessages, tools } = args;
|
|
123
|
+
const functionTools = tools.map((tool) => ({
|
|
124
|
+
type: 'function',
|
|
125
|
+
name: tool.name,
|
|
126
|
+
description: typeof tool.description === 'function' ? tool.description() : tool.description,
|
|
127
|
+
parameters: tool.parameters,
|
|
128
|
+
strict: false,
|
|
129
|
+
}));
|
|
130
|
+
const body: Record<string, unknown> = {
|
|
131
|
+
model: provider.model,
|
|
132
|
+
input: toResponsesInput(cleanedMessages),
|
|
133
|
+
stream: true,
|
|
134
|
+
store: false,
|
|
135
|
+
};
|
|
136
|
+
if (functionTools.length > 0) {
|
|
137
|
+
body.tools = functionTools;
|
|
138
|
+
body.tool_choice = 'auto';
|
|
139
|
+
}
|
|
140
|
+
if (args.withMaxTokens && typeof provider.maxTokens === 'number' && provider.maxTokens > 0) {
|
|
141
|
+
body.max_output_tokens = provider.maxTokens;
|
|
142
|
+
}
|
|
143
|
+
if (args.withReasoningEffort && provider.reasoningEffort) {
|
|
144
|
+
body.reasoning = { effort: provider.reasoningEffort };
|
|
145
|
+
}
|
|
146
|
+
if (args.withResponseFormat && args.responseFormat) {
|
|
147
|
+
const schema = args.responseFormat.json_schema;
|
|
148
|
+
body.text = {
|
|
149
|
+
format: {
|
|
150
|
+
type: 'json_schema',
|
|
151
|
+
name: schema.name,
|
|
152
|
+
schema: schema.schema,
|
|
153
|
+
...(schema.strict !== undefined ? { strict: schema.strict } : {}),
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (args.withPromptCacheKey && args.promptCache?.scopeKey) {
|
|
158
|
+
body.prompt_cache_key = args.promptCache.scopeKey;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
url: buildResponsesUrl(provider),
|
|
162
|
+
headers: {
|
|
163
|
+
'Content-Type': 'application/json',
|
|
164
|
+
Authorization: `Bearer ${provider.apiKey}`,
|
|
165
|
+
},
|
|
166
|
+
body: JSON.stringify(body),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 400 是否在抱怨 reasoning / effort 取值(模型不支持该档位,或根本不是推理模型)。 */
|
|
171
|
+
export function isReasoningEffortRejected(status: number, errText: string): boolean {
|
|
172
|
+
if (status !== 400 && status !== 422) return false;
|
|
173
|
+
const text = errText.toLowerCase();
|
|
174
|
+
// MiniMax 对 effort:'none' 回 `requires adaptive thinking`;Anthropic 兼容端点的字段叫 output_config.effort。
|
|
175
|
+
if (!text.includes('reasoning') && !text.includes('effort') && !text.includes('adaptive thinking')) return false;
|
|
176
|
+
return (
|
|
177
|
+
text.includes('not support') ||
|
|
178
|
+
text.includes('requires') ||
|
|
179
|
+
text.includes('unsupported') ||
|
|
180
|
+
text.includes('invalid') ||
|
|
181
|
+
text.includes('not valid') ||
|
|
182
|
+
text.includes('unknown') ||
|
|
183
|
+
text.includes('unrecognized') ||
|
|
184
|
+
text.includes('unexpected') ||
|
|
185
|
+
text.includes('not allowed') ||
|
|
186
|
+
text.includes('supported values')
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function finiteNonNegative(value: unknown): number | undefined {
|
|
191
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 每个请求一个新实例;把 Responses 的 SSE `data:` 载荷翻成 LlmStreamEvent。 */
|
|
195
|
+
export function createResponsesSSEParser(): {
|
|
196
|
+
handleData(dataStr: string): LlmStreamEvent[];
|
|
197
|
+
buildFallbackDone(): LlmStreamEvent;
|
|
198
|
+
} {
|
|
199
|
+
/** output_index → 本轮第几个工具调用(loop 按 index 合并分片)。 */
|
|
200
|
+
const toolIndex = new Map<number, number>();
|
|
201
|
+
const streamedArguments = new Set<number>();
|
|
202
|
+
let stopReason: 'stop' | 'tool_calls' | 'length' | 'unknown' = 'unknown';
|
|
203
|
+
let sawToolCall = false;
|
|
204
|
+
let promptTokens: number | undefined;
|
|
205
|
+
let outputTokens: number | undefined;
|
|
206
|
+
let cachedTokens: number | undefined;
|
|
207
|
+
let promptCacheUsage: PromptCacheUsage = { reported: false };
|
|
208
|
+
|
|
209
|
+
const readUsage = (usage: unknown) => {
|
|
210
|
+
if (!usage || typeof usage !== 'object') return;
|
|
211
|
+
const u = usage as Record<string, unknown>;
|
|
212
|
+
// input_tokens 已含命中缓存的部分(与 Chat Completions 的 prompt_tokens 同语义)。
|
|
213
|
+
promptTokens = finiteNonNegative(u.input_tokens) ?? promptTokens;
|
|
214
|
+
outputTokens = finiteNonNegative(u.output_tokens) ?? outputTokens;
|
|
215
|
+
const details = u.input_tokens_details;
|
|
216
|
+
if (details && typeof details === 'object') {
|
|
217
|
+
cachedTokens = finiteNonNegative((details as Record<string, unknown>).cached_tokens) ?? cachedTokens;
|
|
218
|
+
}
|
|
219
|
+
promptCacheUsage = {
|
|
220
|
+
reported: cachedTokens !== undefined,
|
|
221
|
+
...(promptTokens !== undefined ? { promptTokens } : {}),
|
|
222
|
+
...(cachedTokens !== undefined ? { cacheReadTokens: cachedTokens } : {}),
|
|
223
|
+
};
|
|
224
|
+
};
|
|
225
|
+
const done = (): LlmStreamEvent => ({
|
|
226
|
+
type: 'done',
|
|
227
|
+
stopReason,
|
|
228
|
+
promptTokens,
|
|
229
|
+
outputTokens,
|
|
230
|
+
cachedPromptTokens: cachedTokens,
|
|
231
|
+
promptCacheUsage,
|
|
232
|
+
});
|
|
233
|
+
const indexFor = (outputIndex: number) => {
|
|
234
|
+
let index = toolIndex.get(outputIndex);
|
|
235
|
+
if (index === undefined) {
|
|
236
|
+
index = toolIndex.size;
|
|
237
|
+
toolIndex.set(outputIndex, index);
|
|
238
|
+
}
|
|
239
|
+
return index;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
buildFallbackDone: done,
|
|
244
|
+
handleData(dataStr: string): LlmStreamEvent[] {
|
|
245
|
+
if (dataStr === '[DONE]') return [done()];
|
|
246
|
+
let data: any;
|
|
247
|
+
try {
|
|
248
|
+
data = JSON.parse(dataStr);
|
|
249
|
+
} catch {
|
|
250
|
+
return [];
|
|
251
|
+
}
|
|
252
|
+
switch (data.type) {
|
|
253
|
+
case 'response.output_text.delta':
|
|
254
|
+
return typeof data.delta === 'string' && data.delta
|
|
255
|
+
? [{ type: 'text_delta', delta: data.delta }]
|
|
256
|
+
: [];
|
|
257
|
+
case 'response.reasoning_summary_text.delta':
|
|
258
|
+
case 'response.reasoning_text.delta':
|
|
259
|
+
return typeof data.delta === 'string' && data.delta
|
|
260
|
+
? [{ type: 'reasoning_delta', field: 'reasoning', delta: data.delta }]
|
|
261
|
+
: [];
|
|
262
|
+
case 'response.output_item.added': {
|
|
263
|
+
const item = data.item;
|
|
264
|
+
if (item?.type !== 'function_call') return [];
|
|
265
|
+
sawToolCall = true;
|
|
266
|
+
// id 用 call_id(回传 function_call_output 时必须对得上),不是 fc_ 的 item id。
|
|
267
|
+
return [{ type: 'tool_call_delta', index: indexFor(data.output_index ?? 0), id: item.call_id, name: item.name }];
|
|
268
|
+
}
|
|
269
|
+
case 'response.function_call_arguments.delta': {
|
|
270
|
+
const outputIndex = data.output_index ?? 0;
|
|
271
|
+
if (typeof data.delta !== 'string' || !data.delta) return [];
|
|
272
|
+
streamedArguments.add(outputIndex);
|
|
273
|
+
return [{ type: 'tool_call_delta', index: indexFor(outputIndex), argumentsDelta: data.delta }];
|
|
274
|
+
}
|
|
275
|
+
case 'response.output_item.done': {
|
|
276
|
+
// 兜底:有的网关不发 arguments.delta,只在条目完成时给完整 arguments。
|
|
277
|
+
const item = data.item;
|
|
278
|
+
const outputIndex = data.output_index ?? 0;
|
|
279
|
+
if (item?.type !== 'function_call' || streamedArguments.has(outputIndex)) return [];
|
|
280
|
+
sawToolCall = true;
|
|
281
|
+
const arguments_ = typeof item.arguments === 'string' ? item.arguments : '';
|
|
282
|
+
return arguments_
|
|
283
|
+
? [{ type: 'tool_call_delta', index: indexFor(outputIndex), id: item.call_id, name: item.name, argumentsDelta: arguments_ }]
|
|
284
|
+
: [];
|
|
285
|
+
}
|
|
286
|
+
case 'response.completed':
|
|
287
|
+
readUsage(data.response?.usage);
|
|
288
|
+
stopReason = sawToolCall ? 'tool_calls' : 'stop';
|
|
289
|
+
return [done()];
|
|
290
|
+
case 'response.incomplete': {
|
|
291
|
+
readUsage(data.response?.usage);
|
|
292
|
+
const reason = data.response?.incomplete_details?.reason;
|
|
293
|
+
stopReason = reason === 'max_output_tokens' ? 'length' : sawToolCall ? 'tool_calls' : 'unknown';
|
|
294
|
+
return [done()];
|
|
295
|
+
}
|
|
296
|
+
case 'response.failed': {
|
|
297
|
+
const error = data.response?.error;
|
|
298
|
+
throw new Error(`OpenAI Responses 流式响应失败:${JSON.stringify(error ?? data.response ?? data)}`);
|
|
299
|
+
}
|
|
300
|
+
case 'error':
|
|
301
|
+
throw new Error(`OpenAI Responses 流式响应报错:${JSON.stringify(data.error ?? data)}`);
|
|
302
|
+
default:
|
|
303
|
+
// response.created / in_progress / content_part.* / output_text.done 等:已知安全的 no-op。
|
|
304
|
+
return [];
|
|
305
|
+
}
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|
package/src/loop/README.md
CHANGED
|
@@ -11,11 +11,11 @@ decisions stay visible in one place: retry, consult, execute, publish or interru
|
|
|
11
11
|
| `toolExecutor.ts` | Single-call authorization, rules, leases, execution and delivery receipt |
|
|
12
12
|
| `toolBatch.ts` | Safe concurrency segments, question/advisor barriers and ordered commits |
|
|
13
13
|
| `progressStream.ts` | Callback-to-generator progress bridge and worker settlement |
|
|
14
|
-
| `publication.ts` | Final expression stream and fallback before first visible text |
|
|
15
14
|
| `messages.ts` | Model message projection, interrupts, screenshot lifecycle, tool deltas |
|
|
16
15
|
| `toolPresentation.ts` | Human-readable tool descriptions; no execution policy |
|
|
17
16
|
| `toolSemantics.ts` | Advisor side-effect classification |
|
|
18
17
|
| `deliveryIntent.ts` | Existing formal-delivery intent policy |
|
|
18
|
+
| `liveDiagramGate.ts` | Holds back a possible text-drawn diagram in a live answer until its fence closes |
|
|
19
19
|
|
|
20
20
|
## Ownership and invariants
|
|
21
21
|
|
|
@@ -29,8 +29,23 @@ decisions stay visible in one place: retry, consult, execute, publish or interru
|
|
|
29
29
|
Writes and interactive/advisor barriers do not become parallel work.
|
|
30
30
|
- Host execution hooks start only after preflight checks. UI `tool_start` is a
|
|
31
31
|
separate event: even a denied/deferred request receives a visible result.
|
|
32
|
-
-
|
|
33
|
-
|
|
32
|
+
- Before each request the orchestrator decides whether the answer can stream
|
|
33
|
+
live (`liveFinal`): only when no delivery check could still hold it back
|
|
34
|
+
(no owed formal delivery or unresolved delegation). The advisor is not such
|
|
35
|
+
a check: it only reminds (`advisor/advisorNudge.ts`) and never holds an answer
|
|
36
|
+
or defers a tool. Live text is never retracted — on
|
|
37
|
+
interruption or error only the text actually shown is committed, and pending
|
|
38
|
+
messages commit it as progress first. The ask correction applies only to
|
|
39
|
+
private drafts; the diagram correction also works live: `liveDiagramGate`
|
|
40
|
+
holds a possible text drawing until its fence closes, and a box stops the
|
|
41
|
+
visible answer right before it — the shown part becomes a progress message and
|
|
42
|
+
the model continues from there. Otherwise the candidate stays private until
|
|
43
|
+
every check passes and is published verbatim; no second tool-free request
|
|
44
|
+
rewrites it. Corrections retire the draft and add a transient reminder (the
|
|
45
|
+
diagram one carries the draft as internal material until the revised answer
|
|
46
|
+
itself arrives, across any skill-loading round); the kernel never
|
|
47
|
+
writes a tool call the model did not make, except the documented host-forced
|
|
48
|
+
Advisor checkpoint.
|
|
34
49
|
- Cancellation belongs to the host AbortSignal. Progress stream disposal waits for
|
|
35
50
|
active workers to settle; it does not grant permission to leave tools orphaned.
|
|
36
51
|
- Existing exports from `loop.ts` remain compatible for TUI, Desktop, subagents and
|