@openclaw/codex 2026.6.8 → 2026.6.9-beta.1
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/dist/{notification-correlation-BGoG0N90.js → app-server-policy-KpyUye2D.js} +15 -74
- package/dist/attempt-notifications-Meja3TX6.js +249 -0
- package/dist/{client-factory-C71Xdb6z.js → client-factory-CPuoOOx6.js} +3 -2
- package/dist/{client-DovmVtbr.js → client-m7XiCQpO.js} +24 -2
- package/dist/{command-handlers-DHecBkuc.js → command-handlers-CqS0Kv3Z.js} +17 -13
- package/dist/{compact-GEKusemL.js → compact-CMVlldii.js} +5 -5
- package/dist/{computer-use-D1qxvTE_.js → computer-use-qLm7Gf35.js} +3 -3
- package/dist/{config-DJXpBkGf.js → config-BksX0T33.js} +160 -20
- package/dist/{conversation-binding-CbnMilVW.js → conversation-binding-DBof5w9J.js} +166 -58
- package/dist/doctor-contract-api.js +37 -3
- package/dist/harness.js +6 -6
- package/dist/index.js +108 -27
- package/dist/media-understanding-provider-CiwPkR58.js +463 -0
- package/dist/media-understanding-provider.js +1 -355
- package/dist/{models-DRKnOpzF.js → models-BsyV1Psm.js} +2 -2
- package/dist/{plugin-app-cache-key-kIqpGTQj.js → plugin-app-cache-key-CN9zBiCG.js} +17 -6
- package/dist/{protocol-oeJQu4rs.js → protocol-dh-ETiNd.js} +4 -1
- package/dist/{protocol-validators-B48C6S9O.js → protocol-validators-B19q5BIX.js} +210 -16
- package/dist/{native-hook-relay-C3i3FYtc.js → provider-capabilities-BOvTfMhF.js} +803 -78
- package/dist/{provider-C5P6352f.js → provider-qJygHQx4.js} +4 -4
- package/dist/provider.js +1 -1
- package/dist/{request-BxZ40QKY.js → request-DTIEyUrA.js} +2 -2
- package/dist/{run-attempt-D_q-VrpR.js → run-attempt-DRhB6bTc.js} +421 -774
- package/dist/{sandbox-guard-C-Yv9uwY.js → sandbox-guard-3tnjhjFb.js} +37 -10
- package/dist/{session-binding-ElbcSq2o.js → session-binding-BRUi8y6E.js} +27 -8
- package/dist/{shared-client-jFMumCOe.js → shared-client-Bg5d7VV9.js} +4 -4
- package/dist/{side-question-DqKLfWMB.js → side-question-BdYL4kj1.js} +106 -42
- package/dist/{thread-lifecycle-cban34w3.js → thread-lifecycle-CbJqqnEw.js} +912 -616
- package/dist/web-search-contract-api.js +10 -0
- package/dist/web-search-provider.runtime-DrpQ8Cyd.js +74 -0
- package/dist/web-search-provider.shared-BrZmlqyR.js +32 -0
- package/npm-shrinkwrap.json +2 -2
- package/openclaw.plugin.json +129 -4
- package/package.json +4 -4
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { CODEX_PROVIDER_ID, FALLBACK_CODEX_MODELS } from "./provider-catalog.js";
|
|
2
|
+
import { n as isJsonObject } from "./protocol-dh-ETiNd.js";
|
|
3
|
+
import { M as mergeCodexThreadConfigs, r as buildCodexRuntimeThreadConfig } from "./thread-lifecycle-CbJqqnEw.js";
|
|
4
|
+
import { S as readCodexNotificationItem } from "./attempt-notifications-Meja3TX6.js";
|
|
5
|
+
import { d as resolveCodexAppServerRuntimeOptions } from "./config-BksX0T33.js";
|
|
6
|
+
import { i as assertCodexTurnStartResponse, l as readCodexTurnCompletedNotification, o as readCodexErrorNotification, r as assertCodexThreadStartResponse } from "./protocol-validators-B19q5BIX.js";
|
|
7
|
+
import { i as readModelListResult } from "./models-BsyV1Psm.js";
|
|
8
|
+
import { validateJsonSchemaValue } from "openclaw/plugin-sdk/json-schema-runtime";
|
|
9
|
+
import fs from "node:fs/promises";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
12
|
+
import { resolvePreferredOpenClawTmpDir, withTempWorkspace } from "openclaw/plugin-sdk/temp-path";
|
|
13
|
+
//#region extensions/codex/src/app-server/bounded-turn.ts
|
|
14
|
+
const CODEX_PRIVATE_STDIO_ARGS = [
|
|
15
|
+
"app-server",
|
|
16
|
+
"--listen",
|
|
17
|
+
"stdio://"
|
|
18
|
+
];
|
|
19
|
+
const OPENCLAW_CODEX_APP_SERVER_ARGS_ENV_VAR = "OPENCLAW_CODEX_APP_SERVER_ARGS";
|
|
20
|
+
const CODEX_BOUNDED_THREAD_CONFIG = {
|
|
21
|
+
"features.multi_agent": false,
|
|
22
|
+
"features.apps": false,
|
|
23
|
+
"features.plugins": false,
|
|
24
|
+
"features.image_generation": false,
|
|
25
|
+
"features.standalone_web_search": false,
|
|
26
|
+
web_search: "disabled"
|
|
27
|
+
};
|
|
28
|
+
const CODEX_PRIVATE_BOUNDED_THREAD_CONFIG = {
|
|
29
|
+
"features.hooks": false,
|
|
30
|
+
notify: []
|
|
31
|
+
};
|
|
32
|
+
async function runBoundedCodexAppServerTurn(params) {
|
|
33
|
+
const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.options.pluginConfig });
|
|
34
|
+
if (params.isolation === "configured-transport") return await runBoundedCodexAppServerTurnInWorkspace(params, appServer, { cwd: params.agentDir?.trim() || process.cwd() });
|
|
35
|
+
if (appServer.start.transport !== "stdio") throw new Error("Bounded Codex turns require stdio transport so native tools can be isolated.");
|
|
36
|
+
return await withTempWorkspace({
|
|
37
|
+
rootDir: resolvePreferredOpenClawTmpDir(),
|
|
38
|
+
prefix: "codex-bounded-turn-"
|
|
39
|
+
}, async (workspace) => {
|
|
40
|
+
const codexHome = path.join(workspace.dir, "codex-home");
|
|
41
|
+
const cwd = path.join(workspace.dir, "workspace");
|
|
42
|
+
await Promise.all([fs.mkdir(codexHome, { recursive: true }), fs.mkdir(cwd, { recursive: true })]);
|
|
43
|
+
return await runBoundedCodexAppServerTurnInWorkspace(params, appServer, {
|
|
44
|
+
codexHome,
|
|
45
|
+
cwd
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function runBoundedCodexAppServerTurnInWorkspace(params, appServer, workspace) {
|
|
50
|
+
const timeoutMs = resolveTimerTimeoutMs(params.timeoutMs, 100, 100);
|
|
51
|
+
const agentDir = params.agentDir?.trim() || void 0;
|
|
52
|
+
const startOptions = workspace.codexHome ? buildPrivateCodexAppServerStartOptions(appServer.start, workspace.codexHome) : appServer.start;
|
|
53
|
+
const ownsClient = !params.options.clientFactory;
|
|
54
|
+
const client = params.options.clientFactory ? await params.options.clientFactory(startOptions, params.profile, agentDir, params.config, { timeoutMs }) : await import("./shared-client-Bg5d7VV9.js").then((n) => n.c).then(({ createIsolatedCodexAppServerClient }) => createIsolatedCodexAppServerClient({
|
|
55
|
+
startOptions,
|
|
56
|
+
timeoutMs,
|
|
57
|
+
authProfileId: params.profile,
|
|
58
|
+
agentDir,
|
|
59
|
+
authProfileStore: params.authProfileStore,
|
|
60
|
+
config: params.config
|
|
61
|
+
}));
|
|
62
|
+
const abortController = new AbortController();
|
|
63
|
+
const abortFromCaller = () => abortController.abort(params.signal?.reason ?? "aborted");
|
|
64
|
+
if (params.signal?.aborted) abortFromCaller();
|
|
65
|
+
else params.signal?.addEventListener("abort", abortFromCaller, { once: true });
|
|
66
|
+
const timeout = setTimeout(() => abortController.abort("timeout"), timeoutMs);
|
|
67
|
+
timeout.unref?.();
|
|
68
|
+
try {
|
|
69
|
+
const model = await resolveCodexBoundedTurnModel({
|
|
70
|
+
client,
|
|
71
|
+
selection: params.model,
|
|
72
|
+
requiredModalities: params.requiredModalities,
|
|
73
|
+
timeoutMs,
|
|
74
|
+
signal: abortController.signal
|
|
75
|
+
});
|
|
76
|
+
const thread = assertCodexThreadStartResponse(await client.request("thread/start", {
|
|
77
|
+
model,
|
|
78
|
+
modelProvider: "openai",
|
|
79
|
+
cwd: workspace.cwd,
|
|
80
|
+
approvalPolicy: "on-request",
|
|
81
|
+
sandbox: "read-only",
|
|
82
|
+
serviceName: "OpenClaw",
|
|
83
|
+
developerInstructions: params.developerInstructions,
|
|
84
|
+
config: buildCodexRuntimeThreadConfig(resolveBoundedThreadConfig(params, workspace), { nativeCodeModeEnabled: false }),
|
|
85
|
+
environments: [],
|
|
86
|
+
dynamicTools: [],
|
|
87
|
+
experimentalRawEvents: true,
|
|
88
|
+
persistExtendedHistory: false,
|
|
89
|
+
ephemeral: true
|
|
90
|
+
}, {
|
|
91
|
+
timeoutMs,
|
|
92
|
+
signal: abortController.signal
|
|
93
|
+
}));
|
|
94
|
+
const collector = createCodexBoundedTurnCollector(thread.thread.id, params.taskLabel);
|
|
95
|
+
const cleanup = client.addNotificationHandler(collector.handleNotification);
|
|
96
|
+
const requestCleanup = client.addRequestHandler(createCodexBoundedApprovalHandler(params.taskLabel));
|
|
97
|
+
try {
|
|
98
|
+
const turn = assertCodexTurnStartResponse(await client.request("turn/start", {
|
|
99
|
+
threadId: thread.thread.id,
|
|
100
|
+
input: params.input,
|
|
101
|
+
cwd: workspace.cwd,
|
|
102
|
+
approvalPolicy: "on-request",
|
|
103
|
+
model,
|
|
104
|
+
effort: "low"
|
|
105
|
+
}, {
|
|
106
|
+
timeoutMs,
|
|
107
|
+
signal: abortController.signal
|
|
108
|
+
}));
|
|
109
|
+
return {
|
|
110
|
+
...await collector.collect(turn.turn, {
|
|
111
|
+
timeoutMs,
|
|
112
|
+
signal: abortController.signal
|
|
113
|
+
}),
|
|
114
|
+
model
|
|
115
|
+
};
|
|
116
|
+
} finally {
|
|
117
|
+
requestCleanup();
|
|
118
|
+
cleanup();
|
|
119
|
+
}
|
|
120
|
+
} finally {
|
|
121
|
+
clearTimeout(timeout);
|
|
122
|
+
params.signal?.removeEventListener("abort", abortFromCaller);
|
|
123
|
+
if (ownsClient) client.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function resolveBoundedThreadConfig(params, workspace) {
|
|
127
|
+
const boundedConfig = mergeCodexThreadConfigs(CODEX_BOUNDED_THREAD_CONFIG, params.threadConfig) ?? CODEX_BOUNDED_THREAD_CONFIG;
|
|
128
|
+
return workspace.codexHome ? mergeCodexThreadConfigs(boundedConfig, CODEX_PRIVATE_BOUNDED_THREAD_CONFIG) ?? boundedConfig : boundedConfig;
|
|
129
|
+
}
|
|
130
|
+
function buildPrivateCodexAppServerStartOptions(start, codexHome) {
|
|
131
|
+
const privateEnv = Object.fromEntries(Object.entries(start.env ?? {}).filter(([name]) => name.trim().toUpperCase() !== OPENCLAW_CODEX_APP_SERVER_ARGS_ENV_VAR));
|
|
132
|
+
const clearEnv = (start.clearEnv ?? []).filter((name) => {
|
|
133
|
+
const normalized = name.trim().toUpperCase();
|
|
134
|
+
return normalized !== "CODEX_HOME" && normalized !== OPENCLAW_CODEX_APP_SERVER_ARGS_ENV_VAR;
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
...start,
|
|
138
|
+
args: [...CODEX_PRIVATE_STDIO_ARGS],
|
|
139
|
+
env: {
|
|
140
|
+
...privateEnv,
|
|
141
|
+
CODEX_HOME: codexHome
|
|
142
|
+
},
|
|
143
|
+
clearEnv: [...clearEnv, OPENCLAW_CODEX_APP_SERVER_ARGS_ENV_VAR]
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function createCodexBoundedApprovalHandler(taskLabel) {
|
|
147
|
+
return (request) => {
|
|
148
|
+
if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return {
|
|
149
|
+
decision: "decline",
|
|
150
|
+
reason: `OpenClaw Codex ${taskLabel} does not grant tool or file approvals.`
|
|
151
|
+
};
|
|
152
|
+
if (request.method === "item/permissions/requestApproval") return {
|
|
153
|
+
permissions: {},
|
|
154
|
+
scope: "turn"
|
|
155
|
+
};
|
|
156
|
+
if (request.method.includes("requestApproval")) return {
|
|
157
|
+
decision: "decline",
|
|
158
|
+
reason: `OpenClaw Codex ${taskLabel} does not grant native approvals.`
|
|
159
|
+
};
|
|
160
|
+
if (request.method === "mcpServer/elicitation/request") return { action: "decline" };
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
async function resolveCodexBoundedTurnModel(params) {
|
|
164
|
+
const listed = readModelListResult(await params.client.request("model/list", {
|
|
165
|
+
limit: null,
|
|
166
|
+
cursor: null,
|
|
167
|
+
includeHidden: false
|
|
168
|
+
}, {
|
|
169
|
+
timeoutMs: Math.min(params.timeoutMs, 5e3),
|
|
170
|
+
signal: params.signal
|
|
171
|
+
})).models;
|
|
172
|
+
if (params.selection.mode === "live-default") {
|
|
173
|
+
const supported = listed.filter((entry) => params.requiredModalities.every((modality) => entry.inputModalities.includes(modality)));
|
|
174
|
+
const selected = supported.find((entry) => entry.isDefault) ?? supported[0];
|
|
175
|
+
if (!selected) throw new Error(`Codex app-server has no model supporting ${params.requiredModalities.join(" and ")} input.`);
|
|
176
|
+
return selected.model;
|
|
177
|
+
}
|
|
178
|
+
const model = params.selection.id;
|
|
179
|
+
const match = listed.find((entry) => entry.model === model || entry.id === model);
|
|
180
|
+
if (!match) throw new Error(`Codex app-server model not found: ${model}`);
|
|
181
|
+
if (params.requiredModalities.includes("image") && !match.inputModalities.includes("image")) throw new Error(`Codex app-server model does not support images: ${model}`);
|
|
182
|
+
if (params.requiredModalities.includes("text") && !match.inputModalities.includes("text")) throw new Error(`Codex app-server model does not support text: ${model}`);
|
|
183
|
+
return model;
|
|
184
|
+
}
|
|
185
|
+
function createCodexBoundedTurnCollector(threadId, taskLabel) {
|
|
186
|
+
let turnId;
|
|
187
|
+
let completedTurn;
|
|
188
|
+
let promptError;
|
|
189
|
+
const pending = [];
|
|
190
|
+
const completedItems = /* @__PURE__ */ new Map();
|
|
191
|
+
const assistantTextByItem = /* @__PURE__ */ new Map();
|
|
192
|
+
const assistantItemOrder = [];
|
|
193
|
+
let resolveCompletion;
|
|
194
|
+
const completion = new Promise((resolve) => {
|
|
195
|
+
resolveCompletion = resolve;
|
|
196
|
+
});
|
|
197
|
+
const rememberAssistantText = (itemId, text) => {
|
|
198
|
+
if (!text) return;
|
|
199
|
+
if (!assistantTextByItem.has(itemId)) assistantItemOrder.push(itemId);
|
|
200
|
+
assistantTextByItem.set(itemId, text);
|
|
201
|
+
};
|
|
202
|
+
const handleNotification = (notification) => {
|
|
203
|
+
const params = isJsonObject(notification.params) ? notification.params : void 0;
|
|
204
|
+
if (!params || readString(params, "threadId") !== threadId) return;
|
|
205
|
+
if (!turnId) {
|
|
206
|
+
pending.push(notification);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (readNotificationTurnId(params) !== turnId) return;
|
|
210
|
+
if (notification.method === "item/completed") {
|
|
211
|
+
const item = readCodexNotificationItem(notification.params);
|
|
212
|
+
if (item) {
|
|
213
|
+
completedItems.set(item.id, item);
|
|
214
|
+
if (item.type === "agentMessage" && typeof item.text === "string") rememberAssistantText(item.id, item.text);
|
|
215
|
+
}
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (notification.method === "item/agentMessage/delta") {
|
|
219
|
+
const itemId = readString(params, "itemId") ?? readString(params, "id") ?? "assistant";
|
|
220
|
+
const delta = readString(params, "delta") ?? "";
|
|
221
|
+
rememberAssistantText(itemId, `${assistantTextByItem.get(itemId) ?? ""}${delta}`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (notification.method === "turn/completed") {
|
|
225
|
+
completedTurn = readCodexTurnCompletedNotification(notification.params)?.turn ?? completedTurn;
|
|
226
|
+
resolveCompletion?.();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (notification.method === "error") {
|
|
230
|
+
promptError = readCodexErrorNotification(notification.params)?.error.message ?? `codex app-server ${taskLabel} turn failed`;
|
|
231
|
+
resolveCompletion?.();
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
return {
|
|
235
|
+
handleNotification,
|
|
236
|
+
async collect(startedTurn, options) {
|
|
237
|
+
turnId = startedTurn.id;
|
|
238
|
+
if (isTerminalTurn(startedTurn)) completedTurn = startedTurn;
|
|
239
|
+
for (const notification of pending.splice(0)) handleNotification(notification);
|
|
240
|
+
if (!completedTurn && !promptError) await waitForTurnCompletion({
|
|
241
|
+
completion,
|
|
242
|
+
timeoutMs: options.timeoutMs,
|
|
243
|
+
signal: options.signal,
|
|
244
|
+
taskLabel
|
|
245
|
+
});
|
|
246
|
+
if (promptError) throw new Error(promptError);
|
|
247
|
+
if (completedTurn?.status === "failed") throw new Error(completedTurn.error?.message ?? `codex app-server ${taskLabel} turn failed`);
|
|
248
|
+
const items = collectCompletedItems(completedTurn?.items, completedItems);
|
|
249
|
+
const itemText = collectAssistantTextFromItems(items);
|
|
250
|
+
const deltaText = assistantItemOrder.map((itemId) => assistantTextByItem.get(itemId)?.trim()).filter((text) => Boolean(text)).join("\n\n").trim();
|
|
251
|
+
const text = (itemText || deltaText).trim();
|
|
252
|
+
if (!text) throw new Error(`Codex app-server ${taskLabel} turn returned no text.`);
|
|
253
|
+
return {
|
|
254
|
+
text,
|
|
255
|
+
items
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
function collectCompletedItems(turnItems, notificationItems) {
|
|
261
|
+
const items = new Map(notificationItems);
|
|
262
|
+
for (const item of turnItems ?? []) items.set(item.id, item);
|
|
263
|
+
return [...items.values()];
|
|
264
|
+
}
|
|
265
|
+
async function waitForTurnCompletion(params) {
|
|
266
|
+
if (params.signal.aborted) throw new Error(`codex app-server ${params.taskLabel} turn aborted`);
|
|
267
|
+
let timeout;
|
|
268
|
+
let cleanupAbort;
|
|
269
|
+
try {
|
|
270
|
+
await Promise.race([params.completion, new Promise((_, reject) => {
|
|
271
|
+
timeout = setTimeout(() => reject(/* @__PURE__ */ new Error(`codex app-server ${params.taskLabel} turn timed out`)), params.timeoutMs);
|
|
272
|
+
timeout.unref?.();
|
|
273
|
+
const abortListener = () => reject(/* @__PURE__ */ new Error(`codex app-server ${params.taskLabel} turn aborted`));
|
|
274
|
+
params.signal.addEventListener("abort", abortListener, { once: true });
|
|
275
|
+
cleanupAbort = () => params.signal.removeEventListener("abort", abortListener);
|
|
276
|
+
})]);
|
|
277
|
+
} finally {
|
|
278
|
+
if (timeout) clearTimeout(timeout);
|
|
279
|
+
cleanupAbort?.();
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function collectAssistantTextFromItems(items) {
|
|
283
|
+
return (items ?? []).filter((item) => item.type === "agentMessage").map((item) => item.text.trim()).filter(Boolean).join("\n\n").trim();
|
|
284
|
+
}
|
|
285
|
+
function readNotificationTurnId(record) {
|
|
286
|
+
const direct = readString(record, "turnId");
|
|
287
|
+
if (direct) return direct;
|
|
288
|
+
return isJsonObject(record.turn) ? readString(record.turn, "id") : void 0;
|
|
289
|
+
}
|
|
290
|
+
function readString(record, key) {
|
|
291
|
+
const value = record[key];
|
|
292
|
+
return typeof value === "string" ? value : void 0;
|
|
293
|
+
}
|
|
294
|
+
function isTerminalTurn(turn) {
|
|
295
|
+
return turn.status === "completed" || turn.status === "interrupted" || turn.status === "failed";
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region extensions/codex/media-understanding-provider.ts
|
|
299
|
+
/**
|
|
300
|
+
* Codex-backed media understanding provider for bounded image description and
|
|
301
|
+
* structured extraction turns.
|
|
302
|
+
*/
|
|
303
|
+
const DEFAULT_CODEX_IMAGE_MODEL = FALLBACK_CODEX_MODELS.find((model) => model.inputModalities.includes("image"))?.id ?? FALLBACK_CODEX_MODELS[0]?.id;
|
|
304
|
+
const DEFAULT_CODEX_IMAGE_PROMPT = "Describe the image.";
|
|
305
|
+
/**
|
|
306
|
+
* Builds the media-understanding provider that delegates image tasks to an
|
|
307
|
+
* isolated Codex app-server session.
|
|
308
|
+
*/
|
|
309
|
+
function buildCodexMediaUnderstandingProvider(options = {}) {
|
|
310
|
+
return {
|
|
311
|
+
id: CODEX_PROVIDER_ID,
|
|
312
|
+
capabilities: ["image"],
|
|
313
|
+
...DEFAULT_CODEX_IMAGE_MODEL ? { defaultModels: { image: DEFAULT_CODEX_IMAGE_MODEL } } : {},
|
|
314
|
+
describeImage: async (req) => describeCodexImages({
|
|
315
|
+
images: [{
|
|
316
|
+
buffer: req.buffer,
|
|
317
|
+
fileName: req.fileName,
|
|
318
|
+
mime: req.mime
|
|
319
|
+
}],
|
|
320
|
+
provider: req.provider,
|
|
321
|
+
model: req.model,
|
|
322
|
+
prompt: req.prompt,
|
|
323
|
+
maxTokens: req.maxTokens,
|
|
324
|
+
timeoutMs: req.timeoutMs,
|
|
325
|
+
profile: req.profile,
|
|
326
|
+
preferredProfile: req.preferredProfile,
|
|
327
|
+
authStore: req.authStore,
|
|
328
|
+
agentDir: req.agentDir,
|
|
329
|
+
cfg: req.cfg
|
|
330
|
+
}, options),
|
|
331
|
+
describeImages: async (req) => describeCodexImages(req, options),
|
|
332
|
+
extractStructured: async (req) => extractCodexStructured(req, options)
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
async function describeCodexImages(req, options) {
|
|
336
|
+
const model = req.model.trim();
|
|
337
|
+
if (!model) throw new Error("Codex image understanding requires model id.");
|
|
338
|
+
const { text } = await runBoundedCodexAppServerTurn({
|
|
339
|
+
config: req.cfg,
|
|
340
|
+
model: {
|
|
341
|
+
mode: "required",
|
|
342
|
+
id: model
|
|
343
|
+
},
|
|
344
|
+
profile: req.profile,
|
|
345
|
+
timeoutMs: req.timeoutMs,
|
|
346
|
+
agentDir: req.agentDir,
|
|
347
|
+
authProfileStore: req.authStore,
|
|
348
|
+
options,
|
|
349
|
+
taskLabel: "image understanding",
|
|
350
|
+
developerInstructions: "You are OpenClaw's bounded image-understanding worker. Describe only the provided image content. Do not call tools, edit files, or ask follow-up questions.",
|
|
351
|
+
input: [{
|
|
352
|
+
type: "text",
|
|
353
|
+
text: buildCodexImagePrompt(req),
|
|
354
|
+
text_elements: []
|
|
355
|
+
}, ...req.images.map((image) => ({
|
|
356
|
+
type: "image",
|
|
357
|
+
url: `data:${image.mime ?? "image/png"};base64,${image.buffer.toString("base64")}`
|
|
358
|
+
}))],
|
|
359
|
+
requiredModalities: ["text", "image"],
|
|
360
|
+
isolation: "configured-transport"
|
|
361
|
+
});
|
|
362
|
+
return {
|
|
363
|
+
text,
|
|
364
|
+
model
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async function extractCodexStructured(req, options) {
|
|
368
|
+
const model = req.model.trim();
|
|
369
|
+
if (!model) throw new Error("Codex structured extraction requires model id.");
|
|
370
|
+
if (!req.instructions.trim()) throw new Error("Codex structured extraction requires instructions.");
|
|
371
|
+
if (req.input.length === 0) throw new Error("Codex structured extraction requires at least one input.");
|
|
372
|
+
if (!req.input.some((entry) => entry.type === "image")) throw new Error("Codex structured extraction requires at least one image input.");
|
|
373
|
+
const { text } = await runBoundedCodexAppServerTurn({
|
|
374
|
+
config: req.cfg,
|
|
375
|
+
model: {
|
|
376
|
+
mode: "required",
|
|
377
|
+
id: model
|
|
378
|
+
},
|
|
379
|
+
profile: req.profile,
|
|
380
|
+
timeoutMs: req.timeoutMs,
|
|
381
|
+
agentDir: req.agentDir,
|
|
382
|
+
authProfileStore: req.authStore,
|
|
383
|
+
options,
|
|
384
|
+
taskLabel: "structured extraction",
|
|
385
|
+
developerInstructions: "You are OpenClaw's bounded structured-extraction worker. Return only the requested extraction. Do not call tools, edit files, ask follow-up questions, or include secrets.",
|
|
386
|
+
input: buildCodexStructuredInput(req),
|
|
387
|
+
requiredModalities: requiredStructuredModalities(),
|
|
388
|
+
isolation: "configured-transport"
|
|
389
|
+
});
|
|
390
|
+
return normalizeStructuredExtractionResult({
|
|
391
|
+
text,
|
|
392
|
+
model,
|
|
393
|
+
provider: req.provider,
|
|
394
|
+
req
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
function buildCodexImagePrompt(req) {
|
|
398
|
+
const prompt = req.prompt?.trim() || DEFAULT_CODEX_IMAGE_PROMPT;
|
|
399
|
+
if (req.images.length <= 1) return prompt;
|
|
400
|
+
return `${prompt}\n\nAnalyze all ${req.images.length} images together.`;
|
|
401
|
+
}
|
|
402
|
+
function requiredStructuredModalities() {
|
|
403
|
+
return ["text", "image"];
|
|
404
|
+
}
|
|
405
|
+
function buildCodexStructuredInput(req) {
|
|
406
|
+
return [{
|
|
407
|
+
type: "text",
|
|
408
|
+
text: buildStructuredExtractionPrompt(req),
|
|
409
|
+
text_elements: []
|
|
410
|
+
}, ...req.input.map((entry) => {
|
|
411
|
+
if (entry.type === "text") return {
|
|
412
|
+
type: "text",
|
|
413
|
+
text: entry.text,
|
|
414
|
+
text_elements: []
|
|
415
|
+
};
|
|
416
|
+
return {
|
|
417
|
+
type: "image",
|
|
418
|
+
url: `data:${entry.mime ?? "image/png"};base64,${entry.buffer.toString("base64")}`
|
|
419
|
+
};
|
|
420
|
+
})];
|
|
421
|
+
}
|
|
422
|
+
function buildStructuredExtractionPrompt(req) {
|
|
423
|
+
return [
|
|
424
|
+
req.instructions.trim(),
|
|
425
|
+
req.schemaName ? `Schema name: ${req.schemaName}` : void 0,
|
|
426
|
+
req.jsonSchema ? `JSON schema:\n${JSON.stringify(req.jsonSchema)}` : void 0,
|
|
427
|
+
req.jsonMode === false ? "Return the extraction as concise text." : "Return valid JSON only. Do not wrap the JSON in Markdown fences."
|
|
428
|
+
].filter((part) => Boolean(part)).join("\n\n");
|
|
429
|
+
}
|
|
430
|
+
function isJsonSchemaObject(value) {
|
|
431
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
432
|
+
}
|
|
433
|
+
function normalizeStructuredExtractionResult(params) {
|
|
434
|
+
const result = {
|
|
435
|
+
text: params.text,
|
|
436
|
+
model: params.model,
|
|
437
|
+
provider: params.provider,
|
|
438
|
+
contentType: params.req.jsonMode === false ? "text" : "json"
|
|
439
|
+
};
|
|
440
|
+
if (params.req.jsonMode !== false) {
|
|
441
|
+
try {
|
|
442
|
+
result.parsed = JSON.parse(params.text);
|
|
443
|
+
} catch {
|
|
444
|
+
throw new Error("Codex structured extraction returned invalid JSON.");
|
|
445
|
+
}
|
|
446
|
+
if (isJsonSchemaObject(params.req.jsonSchema)) {
|
|
447
|
+
const validation = validateJsonSchemaValue({
|
|
448
|
+
schema: params.req.jsonSchema,
|
|
449
|
+
cacheKey: "codex.media-understanding.extractStructured",
|
|
450
|
+
value: result.parsed,
|
|
451
|
+
cache: false
|
|
452
|
+
});
|
|
453
|
+
if (!validation.ok) {
|
|
454
|
+
const message = validation.errors.map((error) => error.text).join("; ") || "invalid";
|
|
455
|
+
throw new Error(`Codex structured extraction JSON did not match schema: ${message}`);
|
|
456
|
+
}
|
|
457
|
+
result.parsed = validation.value;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return result;
|
|
461
|
+
}
|
|
462
|
+
//#endregion
|
|
463
|
+
export { runBoundedCodexAppServerTurn as n, buildCodexMediaUnderstandingProvider as t };
|