@parcha/agentrun-harness-codex 0.0.0-stage → 0.1.0-beta.101
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/CHANGELOG.md +349 -0
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +80 -2
- package/dist/adapter.d.ts +93 -0
- package/dist/adapter.js +375 -0
- package/dist/app-server.d.ts +53 -0
- package/dist/app-server.js +105 -0
- package/dist/binary.d.ts +31 -0
- package/dist/binary.js +74 -0
- package/dist/catalog.d.ts +35 -0
- package/dist/catalog.js +104 -0
- package/dist/code-mode.d.ts +171 -0
- package/dist/code-mode.js +514 -0
- package/dist/config.d.ts +84 -0
- package/dist/config.js +214 -0
- package/dist/facts.d.ts +2 -0
- package/dist/facts.js +40 -0
- package/dist/harness.d.ts +210 -0
- package/dist/harness.js +1112 -0
- package/dist/host/kernel.d.ts +20 -0
- package/dist/host/kernel.js +3 -0
- package/dist/host/machine.d.ts +81 -0
- package/dist/host/machine.js +355 -0
- package/dist/host/policy.d.ts +113 -0
- package/dist/host/policy.js +683 -0
- package/dist/host/process.d.ts +151 -0
- package/dist/host/process.js +50 -0
- package/dist/host/sandbox.d.ts +36 -0
- package/dist/host/sandbox.js +35 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +10 -0
- package/dist/rollout.d.ts +96 -0
- package/dist/rollout.js +170 -0
- package/dist/schema.d.ts +14 -0
- package/dist/schema.js +178 -0
- package/dist/scripts.d.ts +218 -0
- package/dist/scripts.js +409 -0
- package/dist/tool-images.d.ts +7 -0
- package/dist/tool-images.js +18 -0
- package/dist/transcript.d.ts +20 -0
- package/dist/transcript.js +73 -0
- package/dist/verify.d.ts +62 -0
- package/dist/verify.js +155 -0
- package/dist/versions.d.ts +43 -0
- package/dist/versions.js +72 -0
- package/package.json +72 -4
- package/vendor/durable-harness/UPSTREAM.json +39 -0
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
import { PLAN_LIMIT_CODE, PLAN_LIMIT_WORDS } from "@parcha/agentrun-kernel";
|
|
2
|
+
import { lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, responsesInputOverhead, responsesInputAfter, responsesLocalInputTokens } from "@parcha/agentrun-kernel/host";
|
|
3
|
+
export const CODEX_RESPONSES_ROUTES = Object.freeze([
|
|
4
|
+
{ method: "GET", path: "/", local: 404 },
|
|
5
|
+
{ method: "POST", path: "/v1/responses", headers: ["accept"] },
|
|
6
|
+
]);
|
|
7
|
+
/** The keys a Responses request from the pinned CLI may carry; `client_metadata` is dropped, anything else refused. */
|
|
8
|
+
const BODY_KEYS = new Set(["model", "input", "tools", "tool_choice", "parallel_tool_calls", "reasoning", "store", "stream", "include", "prompt_cache_key", "max_output_tokens", "text"]);
|
|
9
|
+
/** What `text` may say: the output's format (plain text, or the JSON schema a node's output schema becomes) and its
|
|
10
|
+
* verbosity. */
|
|
11
|
+
const TEXT_KEYS = new Set(["format", "verbosity"]);
|
|
12
|
+
const VERBOSITY = new Set(["low", "medium", "high"]);
|
|
13
|
+
const SCHEMA_FORMAT_KEYS = new Set(["type", "name", "schema", "strict"]);
|
|
14
|
+
const DROPPED_KEYS = new Set(["client_metadata"]);
|
|
15
|
+
/** What `include` may ask for: the encrypted reasoning the CLI sends back on its next request (`store` is false). */
|
|
16
|
+
const INCLUDE = new Set(["reasoning.encrypted_content"]);
|
|
17
|
+
/** What the host's own side request (ProxyRequestContext.host) may carry beside: a native search's limit on its hosted
|
|
18
|
+
* calls (`max_tool_calls`, which only narrows it) and the sources its results cite. */
|
|
19
|
+
const SIDE_KEYS = new Set(["max_tool_calls"]);
|
|
20
|
+
const SIDE_INCLUDE = new Set(["web_search_call.action.sources"]);
|
|
21
|
+
/** Provider-hosted tools the CLI adds to every request whatever its config says: dropped, never offered. */
|
|
22
|
+
const DROPPED_TOOLS = new Set(["web_search", "web_search_preview"]);
|
|
23
|
+
/** The web search tool the pinned CLI sends with `web_search = "live"` through the session's provider, recorded
|
|
24
|
+
* (test/fixtures/responses-request-web-search-live.json): its keys and their values, and nothing else. */
|
|
25
|
+
const LIVE_SEARCH = Object.freeze({ type: "web_search", external_web_access: true });
|
|
26
|
+
const isLiveSearch = (tool) => Object.keys(tool).length === Object.keys(LIVE_SEARCH).length && Object.entries(LIVE_SEARCH).every(([key, value]) => tool[key] === value);
|
|
27
|
+
/**
|
|
28
|
+
* OpenAI's price of one web search call by model: "Web search (all models)", $10.00 / 1k calls, with its search content
|
|
29
|
+
* tokens billed at the model's rates in the response's own usage (https://developers.openai.com/api/docs/pricing, Tools).
|
|
30
|
+
* The GPT-6 family (gpt-6-luna, gpt-6.1-sol, gpt-6.1-terra, ...) is among "all models", as GPT-5 is.
|
|
31
|
+
* gpt-4o-mini and gpt-4.1-mini bill each call's search content as a fixed block of 8,000 input tokens instead, so they are
|
|
32
|
+
* not listed: their searches, like any model's not listed here (a gateway's own id, say), are an unknown cost, never $0.
|
|
33
|
+
*/
|
|
34
|
+
const WEB_SEARCH_USD = [
|
|
35
|
+
[/^(?:gpt-6|gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/, NATIVE_SEARCH_USD],
|
|
36
|
+
[/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/, NATIVE_SEARCH_USD],
|
|
37
|
+
];
|
|
38
|
+
/** The price of one web search call on `model`, or undefined when it is not known. */
|
|
39
|
+
export function webSearchUsd(model) {
|
|
40
|
+
return WEB_SEARCH_USD.find(([pattern]) => pattern.test(model))?.[1];
|
|
41
|
+
}
|
|
42
|
+
/** `price` with each web search a response ran added at its model's per-call price. Unknown (null) when the tokens' price
|
|
43
|
+
* is, when the response did not say how many searches it ran, or when the model's search price is not known; a response
|
|
44
|
+
* that ran none costs what its tokens do. */
|
|
45
|
+
export function withWebSearches(price) {
|
|
46
|
+
return (model, usage) => {
|
|
47
|
+
const tokens = price(model, usage);
|
|
48
|
+
const searches = usage.webSearches;
|
|
49
|
+
if (searches === 0 || tokens === null)
|
|
50
|
+
return tokens;
|
|
51
|
+
const each = webSearchUsd(model);
|
|
52
|
+
return typeof searches === "number" && each !== undefined ? tokens + searches * each : null;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** What a ChatGPT plan's Responses API does not take: dropped from a request on it. */
|
|
56
|
+
const PLAN_DROPPED_KEYS = new Set(["max_output_tokens", "temperature", "top_p", "metadata", "user", "safety_identifier", "truncation", "background", "prompt_cache_retention"]);
|
|
57
|
+
const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
58
|
+
/** A list of tool definitions with no provider-hosted tool but the live web search when `search` is on, less any not the
|
|
59
|
+
* session's own (`allowed`, by name). */
|
|
60
|
+
function ownTools(tools, allowed, search = false) {
|
|
61
|
+
if (!Array.isArray(tools))
|
|
62
|
+
throw new ProxyRefusal(400, "tools is not a list");
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const tool of tools) {
|
|
65
|
+
if (!isPlain(tool))
|
|
66
|
+
throw new ProxyRefusal(400, "a tool definition is not an object");
|
|
67
|
+
const type = typeof tool.type === "string" ? tool.type : "";
|
|
68
|
+
const name = typeof tool.name === "string" ? tool.name : "";
|
|
69
|
+
if (search && type === "web_search") {
|
|
70
|
+
if (!isLiveSearch(tool))
|
|
71
|
+
throw new ProxyRefusal(403, "a web search tool other than the live one this session offers is not offered to its model");
|
|
72
|
+
out.push(tool);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (DROPPED_TOOLS.has(type))
|
|
76
|
+
continue;
|
|
77
|
+
if (type === "namespace") {
|
|
78
|
+
// A namespace holds the tools of a built-in family: only the session's own ones stay, and an empty one goes. One of
|
|
79
|
+
// an MCP server's (`mcp__<server>`) holds none of the session's: Codex binds no MCP server of its own.
|
|
80
|
+
const kept = ownTools(tool.tools, name.startsWith("mcp__") ? new Set() : allowed);
|
|
81
|
+
if (kept.length)
|
|
82
|
+
out.push({ ...tool, tools: kept });
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (type !== "function" && type !== "custom")
|
|
86
|
+
throw new ProxyRefusal(403, "a provider-hosted or unknown kind of tool is not offered to this session's model");
|
|
87
|
+
if (allowed.has(name))
|
|
88
|
+
out.push(tool);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
/** The function and custom tools a side request offers, by name (its own client tools). */
|
|
93
|
+
const sideToolNames = (tools) => new Set(Array.isArray(tools) ? tools.filter((tool) => isPlain(tool) && (tool.type === "function" || tool.type === "custom") && typeof tool.name === "string").map((tool) => tool.name) : []);
|
|
94
|
+
/** `tool_choice` as the provider gets it: a mode, a function of the session's own, or the web search when it is on. */
|
|
95
|
+
function toolChoice(choice, allowed, search = false) {
|
|
96
|
+
if (choice === "auto" || choice === "none" || choice === "required")
|
|
97
|
+
return choice;
|
|
98
|
+
if (isPlain(choice) && choice.type === "function" && typeof choice.name === "string" && allowed.has(choice.name))
|
|
99
|
+
return choice;
|
|
100
|
+
if (search && isPlain(choice) && choice.type === "web_search" && Object.keys(choice).length === 1)
|
|
101
|
+
return choice;
|
|
102
|
+
throw new ProxyRefusal(400, "tool_choice names a mode or tool this session does not offer");
|
|
103
|
+
}
|
|
104
|
+
/** `text` as the provider gets it: only a format (`{ type: "text" }`, or `{ type: "json_schema", name, schema, strict? }`)
|
|
105
|
+
* and a verbosity. */
|
|
106
|
+
function textOptions(text) {
|
|
107
|
+
const refuse = () => { throw new ProxyRefusal(400, "text carries something other than a plain-text or JSON-schema format and a verbosity"); };
|
|
108
|
+
if (!isPlain(text) || !Object.keys(text).every((key) => TEXT_KEYS.has(key)))
|
|
109
|
+
refuse();
|
|
110
|
+
const { format, verbosity } = text;
|
|
111
|
+
if (verbosity !== undefined && !(typeof verbosity === "string" && VERBOSITY.has(verbosity)))
|
|
112
|
+
refuse();
|
|
113
|
+
if (format !== undefined) {
|
|
114
|
+
if (!isPlain(format))
|
|
115
|
+
refuse();
|
|
116
|
+
const f = format;
|
|
117
|
+
if (f.type === "text") {
|
|
118
|
+
if (Object.keys(f).length !== 1)
|
|
119
|
+
refuse();
|
|
120
|
+
}
|
|
121
|
+
else if (f.type === "json_schema") {
|
|
122
|
+
if (!Object.keys(f).every((key) => SCHEMA_FORMAT_KEYS.has(key)))
|
|
123
|
+
refuse();
|
|
124
|
+
if (typeof f.name !== "string" || !isPlain(f.schema) || (f.strict !== undefined && typeof f.strict !== "boolean"))
|
|
125
|
+
refuse();
|
|
126
|
+
}
|
|
127
|
+
else
|
|
128
|
+
refuse();
|
|
129
|
+
}
|
|
130
|
+
return text;
|
|
131
|
+
}
|
|
132
|
+
/** A Responses usage object in the proxy's terms, or undefined when it is not one. */
|
|
133
|
+
function usageFrom(usage) {
|
|
134
|
+
if (!isPlain(usage))
|
|
135
|
+
return undefined;
|
|
136
|
+
const count = (value) => (typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined);
|
|
137
|
+
const input = count(usage.input_tokens);
|
|
138
|
+
const output = count(usage.output_tokens);
|
|
139
|
+
if (input === undefined || output === undefined)
|
|
140
|
+
return undefined;
|
|
141
|
+
const details = isPlain(usage.input_tokens_details) ? usage.input_tokens_details : {};
|
|
142
|
+
const cacheRead = count(details.cached_tokens) ?? 0;
|
|
143
|
+
const cacheWrite = count(details.cache_write_tokens) ?? 0;
|
|
144
|
+
// The reasoning tokens of its output, when it says them: what the run has seen its model reason (ProxyUsage.reasoning).
|
|
145
|
+
// Its billed input, input + cacheRead + cacheWrite, is `input_tokens` whole: the cached tokens are part of it.
|
|
146
|
+
const reasoning = isPlain(usage.output_tokens_details) ? count(usage.output_tokens_details.reasoning_tokens) : undefined;
|
|
147
|
+
return { input: Math.max(0, input - cacheRead - cacheWrite), output, cacheRead, cacheWrite, ...(reasoning === undefined ? {} : { reasoning }) };
|
|
148
|
+
}
|
|
149
|
+
/** The object starting at `text[start]` (a `{`), as JSON text, or undefined when it does not close in `text`. Strings are
|
|
150
|
+
* skipped whole, so a brace inside one is not counted. */
|
|
151
|
+
function objectAt(text, start) {
|
|
152
|
+
let depth = 0;
|
|
153
|
+
for (let i = start; i < text.length; i++) {
|
|
154
|
+
const c = text[i];
|
|
155
|
+
if (c === "\"") {
|
|
156
|
+
for (i++; i < text.length && text[i] !== "\""; i++)
|
|
157
|
+
if (text[i] === "\\")
|
|
158
|
+
i++;
|
|
159
|
+
}
|
|
160
|
+
else if (c === "{")
|
|
161
|
+
depth++;
|
|
162
|
+
else if (c === "}" && --depth === 0)
|
|
163
|
+
return text.slice(start, i + 1);
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
const PAID_END = new Set(["response.completed", "response.incomplete"]);
|
|
168
|
+
/**
|
|
169
|
+
* The end of the stream's last event when its line was cut at the window's start (a line longer than the window): the
|
|
170
|
+
* text after the last line break, past a closing `data: [DONE]`. A line kept from its start (`data:`) is not one: it was
|
|
171
|
+
* read whole, or it was cut short at the stream's end, and is not read. Undefined when there is none.
|
|
172
|
+
*/
|
|
173
|
+
function cutEnd(text) {
|
|
174
|
+
const last = text.split("\n").map((line) => line.trim()).filter((line) => line && line !== "data: [DONE]" && !line.startsWith("event:") && !line.startsWith(":")).at(-1);
|
|
175
|
+
return last === undefined || last.startsWith("data:") ? undefined : last;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The value of `key` in the response an answer ends with: a stream's `response.completed` (or `response.incomplete`),
|
|
179
|
+
* each `data:` line parsed on its own, or a whole JSON body's. The proxy keeps only the first and last 64 KiB of a long
|
|
180
|
+
* answer, and the completed event carries the whole response (its tools and encrypted reasoning), so its line can be cut
|
|
181
|
+
* at the window's start: then the last `"<key>": {` in the text, whatever its spacing (the kernel's `lastObjectOf`: the
|
|
182
|
+
* response's, which a JSON string cannot contain unescaped), is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
|
|
183
|
+
* of the last event (`cutEnd`), since the events before the terminal one carry a `tool_usage` of their own (a count of
|
|
184
|
+
* 0 as the response starts). No completed event, or no `key` in it, is undefined.
|
|
185
|
+
*/
|
|
186
|
+
function endValue(text, key) {
|
|
187
|
+
let found;
|
|
188
|
+
let ended = false;
|
|
189
|
+
for (const line of text.split("\n")) {
|
|
190
|
+
if (!line.startsWith("data:"))
|
|
191
|
+
continue;
|
|
192
|
+
const data = line.slice(5).trim();
|
|
193
|
+
if (!data.startsWith("{"))
|
|
194
|
+
continue;
|
|
195
|
+
let event;
|
|
196
|
+
try {
|
|
197
|
+
event = JSON.parse(data);
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
continue; // a line the window cut
|
|
201
|
+
}
|
|
202
|
+
if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type)) {
|
|
203
|
+
ended = true;
|
|
204
|
+
found = isPlain(event.response) ? event.response[key] : undefined;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (ended)
|
|
208
|
+
return found;
|
|
209
|
+
const whole = text.trimStart();
|
|
210
|
+
if (whole.startsWith("{")) {
|
|
211
|
+
try {
|
|
212
|
+
const body = JSON.parse(whole);
|
|
213
|
+
if (isPlain(body) && body.object === "response")
|
|
214
|
+
return body[key];
|
|
215
|
+
}
|
|
216
|
+
catch { }
|
|
217
|
+
}
|
|
218
|
+
const scope = key === "usage" ? text : cutEnd(text);
|
|
219
|
+
return scope === undefined ? undefined : lastObjectOf(scope, key);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
|
|
223
|
+
* `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
|
|
224
|
+
* own, as endValue reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
|
|
225
|
+
*
|
|
226
|
+
* The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
|
|
227
|
+
* than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
|
|
228
|
+
* order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
|
|
229
|
+
* tools and the output (OpenAI's; a LiteLLM gateway's, `id`, `created_at`, `incomplete_details`, ..., `output`, keeps it
|
|
230
|
+
* ahead of the output too), so `incomplete_details` is near the line's start. It is read only on a line that is the event's
|
|
231
|
+
* own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
|
|
232
|
+
* before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
|
|
233
|
+
* `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
|
|
234
|
+
*/
|
|
235
|
+
export function filtered(text, lineStarts = []) {
|
|
236
|
+
const end = answerEnd(text, lineStarts);
|
|
237
|
+
return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Whether the provider cut the answer at its output limit: its end is an `incomplete` response whose
|
|
241
|
+
* `incomplete_details.reason` is `max_output_tokens`, with the output tokens its usage reports when the end was read whole.
|
|
242
|
+
* Read as `filtered` reads its stop, but keyed only on the data's own `type` (`response.incomplete`), never on an `event:`
|
|
243
|
+
* line: a gateway's Responses stream is data alone. Any other reason (`content_filter`) is no cut. Codex 0.164 takes a cut
|
|
244
|
+
* answer as a stream error and asks for it again, each time paid; the harness ends the turn first.
|
|
245
|
+
*/
|
|
246
|
+
export function cut(text, lineStarts = []) {
|
|
247
|
+
const end = answerEnd(text, lineStarts, false);
|
|
248
|
+
if (!(isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "max_output_tokens"))
|
|
249
|
+
return undefined;
|
|
250
|
+
const output = isPlain(end.usage) ? end.usage.output_tokens : undefined;
|
|
251
|
+
return typeof output === "number" && Number.isSafeInteger(output) && output >= 0 ? { outputTokens: output } : {};
|
|
252
|
+
}
|
|
253
|
+
/** The response an answer ends with: its stream's terminal event's, a whole body's, or a kept line start's (`filtered`).
|
|
254
|
+
* `byName`: a kept start an `event: response.incomplete` line names is the stop's too (else only its data's type). */
|
|
255
|
+
function answerEnd(text, lineStarts, byName = true) {
|
|
256
|
+
let end = terminalResponse(text.split("\n"), false, byName);
|
|
257
|
+
if (end === undefined) {
|
|
258
|
+
const whole = text.trimStart();
|
|
259
|
+
if (whole.startsWith("{")) {
|
|
260
|
+
try {
|
|
261
|
+
const body = JSON.parse(whole);
|
|
262
|
+
if (isPlain(body) && body.object === "response")
|
|
263
|
+
end = body;
|
|
264
|
+
}
|
|
265
|
+
catch { }
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return end ?? terminalResponse(lineStarts, true, byName);
|
|
269
|
+
}
|
|
270
|
+
/** The response of the last terminal event in `lines` (`filtered`), each `data:` line parsed on its own; with `starts`,
|
|
271
|
+
* the lines are kept starts, and one that is a `response.incomplete` event's (by its name when `byName`, or its data's
|
|
272
|
+
* type ahead of its response) is read from its start. */
|
|
273
|
+
function terminalResponse(lines, starts, byName = true) {
|
|
274
|
+
let end;
|
|
275
|
+
let named = false;
|
|
276
|
+
for (const line of lines) {
|
|
277
|
+
if (line.startsWith("event:")) {
|
|
278
|
+
named = byName && line.slice(6).trim() === "response.incomplete";
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (!line.startsWith("data:"))
|
|
282
|
+
continue;
|
|
283
|
+
const data = line.slice(5).trim();
|
|
284
|
+
const incomplete = named || ownIncomplete(data);
|
|
285
|
+
named = false;
|
|
286
|
+
if (!data.startsWith("{"))
|
|
287
|
+
continue;
|
|
288
|
+
try {
|
|
289
|
+
const event = JSON.parse(data);
|
|
290
|
+
if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type))
|
|
291
|
+
end = event.response;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
// A line the window cut (skipped), or a kept start the event's name says is the stop's.
|
|
295
|
+
if (starts && incomplete)
|
|
296
|
+
end = startOfResponse(data) ?? end;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return end;
|
|
300
|
+
}
|
|
301
|
+
const RESPONSE_KEY = /"response"\s*:\s*\{/;
|
|
302
|
+
const INCOMPLETE_TYPE = /"type"\s*:\s*"response\.incomplete"/;
|
|
303
|
+
const DETAILS_KEY = /"incomplete_details"\s*:\s*\{/;
|
|
304
|
+
/** Whether a kept start's data is a `response.incomplete` event's own: its `type` says so ahead of its `response` (a
|
|
305
|
+
* quote of it in an answer's text is escaped, so it never reads as one). */
|
|
306
|
+
function ownIncomplete(data) {
|
|
307
|
+
const type = data.search(INCOMPLETE_TYPE);
|
|
308
|
+
const response = data.search(RESPONSE_KEY);
|
|
309
|
+
return type >= 0 && (response < 0 || type < response);
|
|
310
|
+
}
|
|
311
|
+
/** The status and `incomplete_details` of the response a `response.incomplete` event's line starts with (`filtered`), or
|
|
312
|
+
* undefined when the line's kept start does not hold them. */
|
|
313
|
+
function startOfResponse(data) {
|
|
314
|
+
const response = data.search(RESPONSE_KEY);
|
|
315
|
+
if (response < 0)
|
|
316
|
+
return undefined;
|
|
317
|
+
const found = DETAILS_KEY.exec(data.slice(response));
|
|
318
|
+
if (!found)
|
|
319
|
+
return undefined;
|
|
320
|
+
const json = objectAt(data, response + found.index + found[0].length - 1);
|
|
321
|
+
if (json === undefined)
|
|
322
|
+
return undefined;
|
|
323
|
+
try {
|
|
324
|
+
return { status: "incomplete", incomplete_details: JSON.parse(json) };
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
|
|
331
|
+
export function usageOf(text) {
|
|
332
|
+
return usageFrom(endValue(text, "usage"));
|
|
333
|
+
}
|
|
334
|
+
/** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
|
|
335
|
+
* what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
|
|
336
|
+
export function webSearchesOf(text) {
|
|
337
|
+
const used = endValue(text, "tool_usage");
|
|
338
|
+
const search = isPlain(used) ? used.web_search : undefined;
|
|
339
|
+
const count = isPlain(search) ? search.num_requests : undefined;
|
|
340
|
+
return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined;
|
|
341
|
+
}
|
|
342
|
+
/** The text of a tool output item: a string, or the text of each of its parts. */
|
|
343
|
+
/** Codex's status header of a tool output: the text it starts with (its first part), never what the script printed after it. */
|
|
344
|
+
function statusText(item) {
|
|
345
|
+
if (typeof item.output === "string")
|
|
346
|
+
return item.output;
|
|
347
|
+
const first = Array.isArray(item.output) ? item.output[0] : undefined;
|
|
348
|
+
return isPlain(first) && typeof first.text === "string" ? first.text : "";
|
|
349
|
+
}
|
|
350
|
+
/** Whether a script of code mode is still running, from the request's input alone: an `exec` whose output said "Script running
|
|
351
|
+
* with cell ID N" (it yielded and went on), and no later `wait` on N whose output says the script ended. */
|
|
352
|
+
function cellRunning(input) {
|
|
353
|
+
const execs = new Set();
|
|
354
|
+
const waits = new Map();
|
|
355
|
+
const cells = new Set();
|
|
356
|
+
for (const item of input) {
|
|
357
|
+
if (!isPlain(item) || typeof item.call_id !== "string")
|
|
358
|
+
continue;
|
|
359
|
+
const running = /^Script running with cell ID (\S+)/.exec(statusText(item));
|
|
360
|
+
if (item.type === "custom_tool_call" && item.name === "exec")
|
|
361
|
+
execs.add(item.call_id);
|
|
362
|
+
else if (item.type === "custom_tool_call_output" && execs.has(item.call_id) && running)
|
|
363
|
+
cells.add(running[1]);
|
|
364
|
+
else if (item.type === "function_call" && item.name === "wait" && typeof item.arguments === "string") {
|
|
365
|
+
try {
|
|
366
|
+
const cell = JSON.parse(item.arguments).cell_id;
|
|
367
|
+
if (cell !== undefined)
|
|
368
|
+
waits.set(item.call_id, String(cell));
|
|
369
|
+
}
|
|
370
|
+
catch { }
|
|
371
|
+
}
|
|
372
|
+
else if (item.type === "function_call_output" && waits.has(item.call_id) && !running)
|
|
373
|
+
cells.delete(waits.get(item.call_id));
|
|
374
|
+
}
|
|
375
|
+
return cells.size > 0;
|
|
376
|
+
}
|
|
377
|
+
/** The code-mode runtime a request may carry: Codex's `exec` (a custom tool) and `wait` (a function), in the `functions`
|
|
378
|
+
* namespace of an `additional_tools` item. Every other tool the item lists is dropped, and an item of any other shape is
|
|
379
|
+
* refused. Other input items pass as they are. */
|
|
380
|
+
const CODE_MODE_TOOLS = new Map([["exec", "custom"], ["wait", "function"]]);
|
|
381
|
+
function codeModeCarrier(item, offerExec) {
|
|
382
|
+
if (!isPlain(item) || item.type !== "additional_tools")
|
|
383
|
+
return item;
|
|
384
|
+
if (!Array.isArray(item.tools))
|
|
385
|
+
throw new ProxyRefusal(400, "an additional_tools item has no tools list");
|
|
386
|
+
const kept = [];
|
|
387
|
+
for (const namespace of item.tools) {
|
|
388
|
+
if (!isPlain(namespace) || namespace.type !== "namespace" || !Array.isArray(namespace.tools))
|
|
389
|
+
throw new ProxyRefusal(400, "an additional_tools item holds something other than a namespace");
|
|
390
|
+
if (namespace.name !== "functions")
|
|
391
|
+
continue;
|
|
392
|
+
const own = namespace.tools.filter((tool) => isPlain(tool) && typeof tool.name === "string" && CODE_MODE_TOOLS.get(tool.name) === tool.type && (offerExec || tool.name !== "exec"));
|
|
393
|
+
kept.push({ ...namespace, tools: own });
|
|
394
|
+
}
|
|
395
|
+
return { ...item, tools: kept };
|
|
396
|
+
}
|
|
397
|
+
/** An event that is not whole by this many characters is not read: the answer is then reported as not watched. */
|
|
398
|
+
const EVENT_CAP = 4 * 1024 * 1024;
|
|
399
|
+
/** Reads an answer's server-sent events as they pass (lines end in LF, CRLF or a bare CR; an event is its `data:` lines joined
|
|
400
|
+
* with LF, ended by a blank line), and tells `announce` of each code-mode `exec` call it holds. One that cannot be read to its
|
|
401
|
+
* end (an event over the cap) is reported as failed. `end` closes the answer. */
|
|
402
|
+
function watchResponse(announce) {
|
|
403
|
+
announce.response();
|
|
404
|
+
let line = "";
|
|
405
|
+
let held = false; // a CR ended the last piece: an LF that starts the next belongs to it
|
|
406
|
+
let data = [];
|
|
407
|
+
let size = 0;
|
|
408
|
+
let broken = false;
|
|
409
|
+
const fail = () => {
|
|
410
|
+
if (broken)
|
|
411
|
+
return;
|
|
412
|
+
broken = true;
|
|
413
|
+
announce.failed();
|
|
414
|
+
};
|
|
415
|
+
const dispatch = () => {
|
|
416
|
+
const text = data.join("\n");
|
|
417
|
+
data = [];
|
|
418
|
+
size = 0;
|
|
419
|
+
if (!text.includes("custom_tool_call"))
|
|
420
|
+
return;
|
|
421
|
+
let event;
|
|
422
|
+
try {
|
|
423
|
+
event = JSON.parse(text);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const item = isPlain(event) && event.type === "response.output_item.done" && isPlain(event.item) ? event.item : undefined;
|
|
429
|
+
if (item?.type === "custom_tool_call" && item.name === "exec" && typeof item.call_id === "string")
|
|
430
|
+
announce.exec(item.call_id, typeof item.input === "string" ? item.input : "");
|
|
431
|
+
};
|
|
432
|
+
const endLine = () => {
|
|
433
|
+
const done = line;
|
|
434
|
+
line = "";
|
|
435
|
+
if (done === "")
|
|
436
|
+
return dispatch();
|
|
437
|
+
if (done.startsWith("data:")) {
|
|
438
|
+
const value = done.slice(done.startsWith("data: ") ? 6 : 5);
|
|
439
|
+
size += value.length + 1;
|
|
440
|
+
if (size > EVENT_CAP)
|
|
441
|
+
return fail();
|
|
442
|
+
data.push(value);
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
return {
|
|
446
|
+
failed: () => fail(),
|
|
447
|
+
end: () => announce.end(),
|
|
448
|
+
chunk(text) {
|
|
449
|
+
if (broken)
|
|
450
|
+
return;
|
|
451
|
+
for (let i = 0; i < text.length; i++) {
|
|
452
|
+
const ch = text[i];
|
|
453
|
+
if (held) {
|
|
454
|
+
held = false;
|
|
455
|
+
if (ch === "\n")
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
if (ch === "\n")
|
|
459
|
+
endLine();
|
|
460
|
+
else if (ch === "\r") {
|
|
461
|
+
endLine();
|
|
462
|
+
held = true;
|
|
463
|
+
}
|
|
464
|
+
else {
|
|
465
|
+
line += ch;
|
|
466
|
+
if (line.length > EVENT_CAP)
|
|
467
|
+
return fail();
|
|
468
|
+
}
|
|
469
|
+
if (broken)
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/** The tokens a request keeps for its answer when its output is limited. */
|
|
476
|
+
export const ANSWER_TOKENS_LEAST = 1024;
|
|
477
|
+
/** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
|
|
478
|
+
* OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
|
|
479
|
+
* incomplete with no answer. The figures are pi-ai's thinking budgets by level (xhigh at high's). */
|
|
480
|
+
export const REASONING_TOKENS_ALLOWED = Object.freeze({ minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 16384 });
|
|
481
|
+
/** The output tokens a Responses body asks for at most: its `max_output_tokens` (as `apply` clamped it). */
|
|
482
|
+
export function responsesOutputAsked(body) {
|
|
483
|
+
const asked = body.max_output_tokens;
|
|
484
|
+
return typeof asked === "number" && Number.isSafeInteger(asked) && asked > 0 ? asked : undefined;
|
|
485
|
+
}
|
|
486
|
+
/** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus, when it reasons, its
|
|
487
|
+
* reasoning effort's allowance, or, once the run has seen its model reason (`seen.most`, the most reasoning tokens one
|
|
488
|
+
* of its answers reported), twice that most, never past the allowance. OpenAI's reasoning shares the output limit, so a
|
|
489
|
+
* limit is a least, not a budget: the request is still sent with all the output the cap fits, and an answer the limit
|
|
490
|
+
* cuts is said to be the cap's cut (ModelTicket.capCut). */
|
|
491
|
+
export function responsesOutputLeast(body, seen) {
|
|
492
|
+
const effort = responsesEffort(body);
|
|
493
|
+
const allowed = effort === undefined ? 0 : REASONING_TOKENS_ALLOWED[effort] ?? 0;
|
|
494
|
+
const most = seen?.most;
|
|
495
|
+
const reasoning = typeof most === "number" && Number.isSafeInteger(most) && most >= 0 ? Math.min(allowed, 2 * most) : allowed;
|
|
496
|
+
return ANSWER_TOKENS_LEAST + reasoning;
|
|
497
|
+
}
|
|
498
|
+
/** The reasoning effort a Responses body asks its model at (`reasoning.effort`), when it names one. */
|
|
499
|
+
export function responsesEffort(body) {
|
|
500
|
+
return isPlain(body.reasoning) && typeof body.reasoning.effort === "string" && body.reasoning.effort.length > 0 ? body.reasoning.effort : undefined;
|
|
501
|
+
}
|
|
502
|
+
/** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
|
|
503
|
+
* streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
|
|
504
|
+
* own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
|
|
505
|
+
* estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
|
|
506
|
+
* did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
|
|
507
|
+
export function responsesReasoningHidden(body, fallback) {
|
|
508
|
+
const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
|
|
509
|
+
if (effort === "none")
|
|
510
|
+
return 0;
|
|
511
|
+
const budget = effort === undefined ? undefined : REASONING_TOKENS_ALLOWED[effort];
|
|
512
|
+
return budget ?? responsesOutputAsked(body) ?? fallback;
|
|
513
|
+
}
|
|
514
|
+
/** The Responses stream's events whose deltas are reasoning: its summary, and its reasoning text where a model sends it. */
|
|
515
|
+
const REASONING_DELTAS = new Set(["response.reasoning_summary_text.delta", "response.reasoning_text.delta"]);
|
|
516
|
+
/** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
|
|
517
|
+
* function call's arguments and every other event. */
|
|
518
|
+
export function responsesReasoningBytes(event) {
|
|
519
|
+
const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
520
|
+
if (!data.startsWith("{"))
|
|
521
|
+
return 0;
|
|
522
|
+
const parsed = JSON.parse(data);
|
|
523
|
+
return typeof parsed.type === "string" && REASONING_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
|
|
524
|
+
}
|
|
525
|
+
/** The Responses stream's events whose deltas are content: answer text, reasoning, and a tool call's input. */
|
|
526
|
+
const CONTENT_DELTAS = new Set([
|
|
527
|
+
"response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta",
|
|
528
|
+
"response.function_call_arguments.delta", "response.custom_tool_call_input.delta",
|
|
529
|
+
]);
|
|
530
|
+
/** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
|
|
531
|
+
* (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
|
|
532
|
+
export function responsesContentBytes(event) {
|
|
533
|
+
const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
534
|
+
if (!data.startsWith("{"))
|
|
535
|
+
return 0;
|
|
536
|
+
const parsed = JSON.parse(data);
|
|
537
|
+
return typeof parsed.type === "string" && CONTENT_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
|
|
538
|
+
}
|
|
539
|
+
/** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
|
|
540
|
+
export function limitResponsesOutput(body, max) {
|
|
541
|
+
const asked = responsesOutputAsked(body);
|
|
542
|
+
return { ...body, max_output_tokens: asked === undefined ? max : Math.min(asked, max) };
|
|
543
|
+
}
|
|
544
|
+
/** `body` (a Responses body) with `text` as a note the model reads after everything the client sent: one developer message
|
|
545
|
+
* at the end of `input`. Caching is by prefix, so the earlier items stay a hit; the client's next request, which sends
|
|
546
|
+
* its own input whole, does not carry it. */
|
|
547
|
+
export function addResponsesNote(body, text) {
|
|
548
|
+
const input = Array.isArray(body.input) ? body.input : [];
|
|
549
|
+
return { ...body, input: [...input, { type: "message", role: "developer", content: [{ type: "input_text", text }] }] };
|
|
550
|
+
}
|
|
551
|
+
/** The error codes OpenAI's Responses API gives a ChatGPT plan's request past its limit, with status 429. */
|
|
552
|
+
const PLAN_LIMIT_ERRORS = new Set(["usage_limit_exceeded", "subscription_sharing_usage_limit_exceeded"]);
|
|
553
|
+
/** A ChatGPT plan's 429 past its limit (PLAN_LIMIT_ERRORS, as the error's `code` or `type`): final, in PLAN_LIMIT_WORDS.
|
|
554
|
+
* Any other error goes through as it came (a 429 for the rate, which its client waits out and asks again). */
|
|
555
|
+
export function planLimitOf(status, body) {
|
|
556
|
+
if (status !== 429)
|
|
557
|
+
return undefined;
|
|
558
|
+
let parsed;
|
|
559
|
+
try {
|
|
560
|
+
parsed = JSON.parse(body);
|
|
561
|
+
}
|
|
562
|
+
catch {
|
|
563
|
+
return undefined;
|
|
564
|
+
}
|
|
565
|
+
const error = isPlain(parsed) && isPlain(parsed.error) ? parsed.error : isPlain(parsed) ? parsed : undefined;
|
|
566
|
+
const named = [error?.code, error?.type].some((value) => typeof value === "string" && PLAN_LIMIT_ERRORS.has(value));
|
|
567
|
+
return named ? { message: PLAN_LIMIT_WORDS, code: PLAN_LIMIT_CODE } : undefined;
|
|
568
|
+
}
|
|
569
|
+
export function codexPolicy(options) {
|
|
570
|
+
const allowed = new Set(options.tools);
|
|
571
|
+
const maxOutputTokens = options.maxOutputTokens ?? 32_000;
|
|
572
|
+
const search = options.webSearch === "live";
|
|
573
|
+
const plan = options.plan === true;
|
|
574
|
+
const tokensOf = search ? (text, body) => {
|
|
575
|
+
const usage = usageOf(text);
|
|
576
|
+
// A request that offered no search (`body`, the one it was sent with: a host's side request through the session's
|
|
577
|
+
// port, a learned workflow's node that offers only `submit`) ran none: 0, read from the request, never an unknown
|
|
578
|
+
// count that would make its whole known cost unknown (withWebSearches). One that offered it reads its answer.
|
|
579
|
+
const offered = Array.isArray(body?.tools) && body.tools.some((tool) => typeof tool === "object" && tool !== null && isLiveSearch(tool));
|
|
580
|
+
if (usage && body && !offered)
|
|
581
|
+
return { ...usage, webSearches: 0 };
|
|
582
|
+
return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
|
|
583
|
+
} : usageOf;
|
|
584
|
+
return {
|
|
585
|
+
id: "codex",
|
|
586
|
+
routes: CODEX_RESPONSES_ROUTES,
|
|
587
|
+
addNote: addResponsesNote,
|
|
588
|
+
keyOf(headers) {
|
|
589
|
+
const auth = String(headers.authorization ?? "");
|
|
590
|
+
return auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
|
591
|
+
},
|
|
592
|
+
authHeaders: (credential) => ({ authorization: `Bearer ${credential}`, ...(plan ? { originator: "agentrun" } : {}) }),
|
|
593
|
+
apply(body, _route, context) {
|
|
594
|
+
// The live search, offered by the request, goes only while the host says web_search may run now: read before this
|
|
595
|
+
// request is shaped, never once for the session. A read that fails offers none.
|
|
596
|
+
const asking = search && options.searchAllowed && isPlain(body) && Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search");
|
|
597
|
+
if (!asking)
|
|
598
|
+
return shaped(body, context, search);
|
|
599
|
+
return options.searchAllowed().then((now) => shaped(body, context, now === true), () => shaped(body, context, false));
|
|
600
|
+
},
|
|
601
|
+
usageOf: plan ? (text, body) => {
|
|
602
|
+
const usage = tokensOf(text, body);
|
|
603
|
+
return usage && { ...usage, billing: "plan" };
|
|
604
|
+
} : tokensOf,
|
|
605
|
+
...(plan ? { finalError: planLimitOf } : {}),
|
|
606
|
+
filtered,
|
|
607
|
+
cut,
|
|
608
|
+
watch: options.announce ? () => watchResponse(options.announce) : undefined,
|
|
609
|
+
unwatched: options.announce ? () => options.announce.failed() : undefined,
|
|
610
|
+
modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
|
|
611
|
+
outputAsked: responsesOutputAsked,
|
|
612
|
+
outputLeast: responsesOutputLeast,
|
|
613
|
+
effortOf: responsesEffort,
|
|
614
|
+
reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
|
|
615
|
+
reasoningBytesOf: responsesReasoningBytes,
|
|
616
|
+
contentBytesOf: responsesContentBytes,
|
|
617
|
+
// A plan request is held at $0, so it is never counted. A body that offers the live search has no input bound
|
|
618
|
+
// (below), and is never counted into one.
|
|
619
|
+
...(plan ? {} : {
|
|
620
|
+
limitOutput: limitResponsesOutput,
|
|
621
|
+
countInputLocally: (body) => (search && Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search") ? undefined : responsesLocalInputTokens(body)),
|
|
622
|
+
// A later request of the session, bounded by the earlier one its provider billed and the items it appends.
|
|
623
|
+
inputAfter: responsesInputAfter,
|
|
624
|
+
}),
|
|
625
|
+
// The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
|
|
626
|
+
// stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured (and never
|
|
627
|
+
// counted into a number).
|
|
628
|
+
serverInputOverhead: search ? (body) => {
|
|
629
|
+
if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
|
|
630
|
+
return undefined;
|
|
631
|
+
return responsesInputOverhead(body);
|
|
632
|
+
} : responsesInputOverhead,
|
|
633
|
+
};
|
|
634
|
+
/** The body the provider gets, the live search offered only when `searchNow`. */
|
|
635
|
+
function shaped(body, context, searchNow) {
|
|
636
|
+
if (!isPlain(body))
|
|
637
|
+
throw new ProxyRefusal(400, "the body is not a JSON object");
|
|
638
|
+
// The host's own request beside Codex's (ProxyRequestContext.host) offers its own client tools (a learned workflow
|
|
639
|
+
// node's `submit`); every other rule is the session's, a provider-hosted tool refused as ever.
|
|
640
|
+
const own = context?.host !== undefined ? sideToolNames(body.tools) : allowed;
|
|
641
|
+
const out = {};
|
|
642
|
+
for (const [key, value] of Object.entries(body)) {
|
|
643
|
+
if (DROPPED_KEYS.has(key) || (plan && PLAN_DROPPED_KEYS.has(key)))
|
|
644
|
+
continue;
|
|
645
|
+
if (!BODY_KEYS.has(key) && !(context?.host !== undefined && SIDE_KEYS.has(key)))
|
|
646
|
+
throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
|
|
647
|
+
out[key] = value;
|
|
648
|
+
}
|
|
649
|
+
if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && (INCLUDE.has(item) || (context?.host !== undefined && SIDE_INCLUDE.has(item)))))) {
|
|
650
|
+
throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
|
|
651
|
+
}
|
|
652
|
+
if (out.stream !== undefined && typeof out.stream !== "boolean")
|
|
653
|
+
throw new ProxyRefusal(400, "stream is not a boolean");
|
|
654
|
+
if (out.reasoning !== undefined && !isPlain(out.reasoning))
|
|
655
|
+
throw new ProxyRefusal(400, "reasoning is not an object");
|
|
656
|
+
if (out.text !== undefined)
|
|
657
|
+
out.text = textOptions(out.text);
|
|
658
|
+
// Without the search now, its tool is dropped as a session without one drops it (DROPPED_TOOLS).
|
|
659
|
+
if (out.tools !== undefined)
|
|
660
|
+
out.tools = ownTools(out.tools, own, searchNow);
|
|
661
|
+
if (out.tool_choice !== undefined)
|
|
662
|
+
out.tool_choice = toolChoice(out.tool_choice, own, searchNow);
|
|
663
|
+
if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
|
|
664
|
+
// While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
|
|
665
|
+
const offerExec = !cellRunning(out.input);
|
|
666
|
+
out.input = out.input.map((item) => codeModeCarrier(item, offerExec));
|
|
667
|
+
// One `exec` is open at a time (the session's barrier for a code-mode call rests on it): a code-mode request that allows
|
|
668
|
+
// parallel calls is refused, and one that says nothing is sent with them off. A classic request is as the CLI sent it.
|
|
669
|
+
if (out.parallel_tool_calls !== undefined && typeof out.parallel_tool_calls !== "boolean")
|
|
670
|
+
throw new ProxyRefusal(400, "parallel_tool_calls is not a boolean");
|
|
671
|
+
if (out.parallel_tool_calls === true)
|
|
672
|
+
throw new ProxyRefusal(400, "parallel tool calls are not allowed in code mode: the model writes one exec at a time");
|
|
673
|
+
out.parallel_tool_calls = false;
|
|
674
|
+
}
|
|
675
|
+
if (plan) {
|
|
676
|
+
if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.role === "system"))
|
|
677
|
+
throw new ProxyRefusal(400, "A ChatGPT plan takes no system-role message: give those words as instructions or a developer message.");
|
|
678
|
+
return { ...out, model: options.model, store: false };
|
|
679
|
+
}
|
|
680
|
+
const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
|
|
681
|
+
return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
|
|
682
|
+
}
|
|
683
|
+
}
|