codex-openai-proxy 0.1.0-rc.0

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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +253 -0
  3. package/dist/app-server/app-server.d.ts +39 -0
  4. package/dist/app-server/app-server.js +261 -0
  5. package/dist/app-server/app-server.js.map +1 -0
  6. package/dist/app-server/auth.d.ts +16 -0
  7. package/dist/app-server/auth.js +102 -0
  8. package/dist/app-server/auth.js.map +1 -0
  9. package/dist/app-server/json-rpc.d.ts +29 -0
  10. package/dist/app-server/json-rpc.js +141 -0
  11. package/dist/app-server/json-rpc.js.map +1 -0
  12. package/dist/bin.d.ts +2 -0
  13. package/dist/bin.js +11 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/cli/cli.d.ts +6 -0
  16. package/dist/cli/cli.js +319 -0
  17. package/dist/cli/cli.js.map +1 -0
  18. package/dist/continuation/state.d.ts +71 -0
  19. package/dist/continuation/state.js +460 -0
  20. package/dist/continuation/state.js.map +1 -0
  21. package/dist/core/abort.d.ts +13 -0
  22. package/dist/core/abort.js +74 -0
  23. package/dist/core/abort.js.map +1 -0
  24. package/dist/core/canonical.d.ts +6 -0
  25. package/dist/core/canonical.js +22 -0
  26. package/dist/core/canonical.js.map +1 -0
  27. package/dist/core/config.d.ts +33 -0
  28. package/dist/core/config.js +139 -0
  29. package/dist/core/config.js.map +1 -0
  30. package/dist/core/logger.d.ts +17 -0
  31. package/dist/core/logger.js +44 -0
  32. package/dist/core/logger.js.map +1 -0
  33. package/dist/core/policy.d.ts +98 -0
  34. package/dist/core/policy.js +242 -0
  35. package/dist/core/policy.js.map +1 -0
  36. package/dist/core/redact.d.ts +2 -0
  37. package/dist/core/redact.js +35 -0
  38. package/dist/core/redact.js.map +1 -0
  39. package/dist/http/chat-execute.d.ts +24 -0
  40. package/dist/http/chat-execute.js +491 -0
  41. package/dist/http/chat-execute.js.map +1 -0
  42. package/dist/http/chat-normalize.d.ts +100 -0
  43. package/dist/http/chat-normalize.js +379 -0
  44. package/dist/http/chat-normalize.js.map +1 -0
  45. package/dist/http/chat-sse.d.ts +14 -0
  46. package/dist/http/chat-sse.js +52 -0
  47. package/dist/http/chat-sse.js.map +1 -0
  48. package/dist/http/chat-validate.d.ts +37 -0
  49. package/dist/http/chat-validate.js +190 -0
  50. package/dist/http/chat-validate.js.map +1 -0
  51. package/dist/http/chat.d.ts +8 -0
  52. package/dist/http/chat.js +137 -0
  53. package/dist/http/chat.js.map +1 -0
  54. package/dist/http/errors.d.ts +19 -0
  55. package/dist/http/errors.js +56 -0
  56. package/dist/http/errors.js.map +1 -0
  57. package/dist/http/server.d.ts +19 -0
  58. package/dist/http/server.js +254 -0
  59. package/dist/http/server.js.map +1 -0
  60. package/package.json +67 -0
  61. package/protocol/VERSION.json +10 -0
  62. package/protocol/schemas/response-mapping.schema.json +38 -0
  63. package/protocol/schemas/x-codex.schema.json +12 -0
@@ -0,0 +1,100 @@
1
+ import type { JsonRpcTransport } from "../app-server/json-rpc.js";
2
+ import type { Logger } from "../core/logger.js";
3
+ import type { PendingToolCall } from "../continuation/state.js";
4
+ /** Standard token usage, with details present only when app-server reports them. */
5
+ export interface Usage {
6
+ prompt_tokens: number;
7
+ completion_tokens: number;
8
+ total_tokens: number;
9
+ prompt_tokens_details?: {
10
+ cached_tokens: number;
11
+ };
12
+ completion_tokens_details?: {
13
+ reasoning_tokens: number;
14
+ };
15
+ }
16
+ /** Function metadata shared by normalized calls and their correlated results. */
17
+ export interface NormalizedFunction {
18
+ name: string;
19
+ arguments: string;
20
+ }
21
+ /** One function-shaped call with its stable streaming index. */
22
+ export interface NormalizedToolCall {
23
+ index: number;
24
+ id: string;
25
+ type: "function";
26
+ function: NormalizedFunction;
27
+ }
28
+ /** Bounded lifecycle data attached to one normalized tool result. */
29
+ export interface NormalizedToolResultData {
30
+ status: string;
31
+ content?: unknown;
32
+ exit_code?: unknown;
33
+ error?: NormalizedError;
34
+ progress_type?: string;
35
+ stream?: string;
36
+ message?: string;
37
+ patch?: unknown;
38
+ }
39
+ /** One self-correlating result for a normalized function-shaped call. */
40
+ export interface NormalizedToolResult {
41
+ id: string;
42
+ type: "function";
43
+ function: NormalizedFunction;
44
+ result: NormalizedToolResultData;
45
+ }
46
+ /** Public fields emitted by one normalized lifecycle event. */
47
+ export interface NormalizedDelta {
48
+ content?: string;
49
+ reasoning?: string;
50
+ tool_calls?: NormalizedToolCall[];
51
+ tool_results?: NormalizedToolResult[];
52
+ }
53
+ /** Structured public subset of an app-server tool error. */
54
+ export interface NormalizedError {
55
+ message?: string;
56
+ code?: string;
57
+ }
58
+ /** One normalized delta shared by streaming and aggregate output. */
59
+ export interface NormalizedEvent {
60
+ delta?: NormalizedDelta;
61
+ finishReason?: "stop" | "length" | "tool_calls" | "content_filter";
62
+ usage?: Usage;
63
+ error?: string;
64
+ }
65
+ /** Aggregate fields derived from the shared normalized event stream. */
66
+ export interface AggregatedNormalizedEvents {
67
+ content: string;
68
+ reasoning: string;
69
+ toolCalls: NormalizedToolCall[];
70
+ toolResults: NormalizedToolResult[];
71
+ finishReason: string | null;
72
+ usage?: Usage;
73
+ }
74
+ /** Explicit handling selected for one pinned app-server notification method. */
75
+ type NotificationBehavior = "normalize" | "progress" | "ignore" | "diagnose";
76
+ /** Notification methods that the HTTP translation intentionally handles. */
77
+ export declare const HANDLED_NOTIFICATION_METHODS: ReadonlySet<string>;
78
+ /** Returns the explicit behavior, diagnosing unclassified future methods. */
79
+ export declare function notificationBehavior(method: string): NotificationBehavior;
80
+ /** Aggregates normalized events for non-streaming output without HTTP state. */
81
+ export declare function aggregateNormalizedEvents(events: AsyncIterable<NormalizedEvent> | Iterable<NormalizedEvent>): Promise<AggregatedNormalizedEvents>;
82
+ /** Converts one app-server notification into zero or more public events. */
83
+ export declare function normalizeNotification(method: string, value: unknown): NormalizedEvent[];
84
+ /** Maintains stable item-to-choice indexes while normalizing interleaved events. */
85
+ export declare class EventNormalizer {
86
+ #private;
87
+ /** Converts one authoritative dynamic request to a function tool call. */
88
+ dynamicToolCall(call: PendingToolCall): NormalizedEvent;
89
+ /** Emits an accepted dynamic result together with its matching call. */
90
+ dynamicToolResult(call: PendingToolCall, content: string): NormalizedEvent;
91
+ /** Converts one app-server notification into zero or more public events. */
92
+ normalize(method: string, value: unknown): NormalizedEvent[];
93
+ }
94
+ /** Checks notification correlation without exposing foreign-thread activity. */
95
+ export declare function matchesTurn(value: unknown, threadId: string | undefined, turnId: string | undefined): boolean;
96
+ /** Records safe structural metadata once per unexposed method and transport. */
97
+ export declare function diagnoseUnexposedNotification(method: string, params: unknown, rpc: JsonRpcTransport, log: Logger): void;
98
+ /** Rejects notifications already established as belonging to another turn. */
99
+ export declare function isEstablishedUnrelatedNotification(value: unknown, threadId: string | undefined, turnId: string | undefined): boolean;
100
+ export {};
@@ -0,0 +1,379 @@
1
+ import { createHash } from "node:crypto";
2
+ import { record } from "../core/canonical.js";
3
+ import { HttpError } from "./errors.js";
4
+ /** Maximum distinct unexposed methods diagnosed for one app-server transport. */
5
+ const MAX_DIAGNOSTIC_METHODS = 32;
6
+ /** Classifies pinned notification methods without implicitly exposing them. */
7
+ const NOTIFICATION_BEHAVIORS = new Map([
8
+ ["error", "normalize"],
9
+ ["item/agentMessage/delta", "normalize"],
10
+ ["item/autoApprovalReview/started", "diagnose"],
11
+ ["item/autoApprovalReview/completed", "diagnose"],
12
+ ["item/commandExecution/outputDelta", "progress"],
13
+ ["item/commandExecution/terminalInteraction", "diagnose"],
14
+ ["item/fileChange/outputDelta", "progress"],
15
+ ["item/fileChange/patchUpdated", "progress"],
16
+ ["item/mcpToolCall/progress", "progress"],
17
+ ["item/plan/delta", "progress"],
18
+ ["item/reasoning/summaryPartAdded", "ignore"],
19
+ ["item/reasoning/summaryTextDelta", "normalize"],
20
+ ["item/reasoning/textDelta", "normalize"],
21
+ ["item/started", "normalize"],
22
+ ["item/completed", "normalize"],
23
+ ["serverRequest/resolved", "ignore"],
24
+ ["thread/tokenUsage/updated", "normalize"],
25
+ ["turn/completed", "normalize"],
26
+ ]);
27
+ /** Notification methods that the HTTP translation intentionally handles. */
28
+ export const HANDLED_NOTIFICATION_METHODS = new Set([...NOTIFICATION_BEHAVIORS]
29
+ .filter(([, behavior]) => behavior !== "diagnose")
30
+ .map(([method]) => method));
31
+ /** Unexposed notification methods diagnosed for each transport generation. */
32
+ const DIAGNOSED_NOTIFICATION_METHODS = new WeakMap();
33
+ /** Returns the explicit behavior, diagnosing unclassified future methods. */
34
+ export function notificationBehavior(method) {
35
+ return NOTIFICATION_BEHAVIORS.get(method) ?? "diagnose";
36
+ }
37
+ /** Aggregates normalized events for non-streaming output without HTTP state. */
38
+ export async function aggregateNormalizedEvents(events) {
39
+ let content = "";
40
+ let reasoning = "";
41
+ const toolCalls = new Map();
42
+ const toolResults = [];
43
+ let finishReason = null;
44
+ let usage;
45
+ for await (const event of events) {
46
+ if (event.error)
47
+ throw new HttpError(502, event.error, "server_error", "app_server_error");
48
+ if (typeof event.delta?.content === "string")
49
+ content += event.delta.content;
50
+ if (typeof event.delta?.reasoning === "string")
51
+ reasoning += event.delta.reasoning;
52
+ for (const call of event.delta?.tool_calls ?? [])
53
+ toolCalls.set(call.index, call);
54
+ toolResults.push(...(event.delta?.tool_results ?? []));
55
+ if (event.finishReason)
56
+ finishReason = event.finishReason;
57
+ if (event.usage)
58
+ usage = event.usage;
59
+ }
60
+ return {
61
+ content,
62
+ reasoning,
63
+ toolCalls: [...toolCalls.entries()]
64
+ .sort(([left], [right]) => left - right)
65
+ .map(([, call]) => call),
66
+ toolResults,
67
+ finishReason,
68
+ ...(usage ? { usage } : {}),
69
+ };
70
+ }
71
+ /** Converts one app-server notification into zero or more public events. */
72
+ export function normalizeNotification(method, value) {
73
+ return new EventNormalizer().normalize(method, value);
74
+ }
75
+ /** Maintains stable item-to-choice indexes while normalizing interleaved events. */
76
+ export class EventNormalizer {
77
+ #toolCalls = new Map();
78
+ #nextToolIndex = 0;
79
+ #sawClientTool = false;
80
+ /** Converts one authoritative dynamic request to a function tool call. */
81
+ dynamicToolCall(call) {
82
+ const argumentsJson = JSON.stringify(call.arguments ?? {});
83
+ const publicCall = this.#allocateToolCall(call.callId, call.name, argumentsJson);
84
+ return { delta: { tool_calls: [publicCall] } };
85
+ }
86
+ /** Emits an accepted dynamic result together with its matching call. */
87
+ dynamicToolResult(call, content) {
88
+ const publicCall = this.#allocateToolCall(call.callId, call.name, JSON.stringify(call.arguments ?? {}));
89
+ return {
90
+ delta: {
91
+ tool_calls: [publicCall],
92
+ tool_results: [
93
+ {
94
+ id: call.callId,
95
+ type: "function",
96
+ function: publicCall.function,
97
+ result: { status: "completed", content },
98
+ },
99
+ ],
100
+ },
101
+ };
102
+ }
103
+ /** Converts one app-server notification into zero or more public events. */
104
+ normalize(method, value) {
105
+ const params = record(value);
106
+ if (!params)
107
+ return [];
108
+ if (method === "item/agentMessage/delta" &&
109
+ typeof params.delta === "string")
110
+ return [{ delta: { content: params.delta } }];
111
+ if (method === "item/reasoning/summaryTextDelta" &&
112
+ typeof params.delta === "string")
113
+ return [{ delta: { reasoning: params.delta } }];
114
+ if (method === "item/reasoning/textDelta" &&
115
+ typeof params.delta === "string")
116
+ return [{ delta: { reasoning: params.delta } }];
117
+ if (method === "thread/tokenUsage/updated") {
118
+ const usage = record(record(params.tokenUsage)?.last);
119
+ if (!usage)
120
+ return [];
121
+ return [{ usage: toUsage(usage) }];
122
+ }
123
+ if (method === "error") {
124
+ const error = record(params.error);
125
+ return [
126
+ {
127
+ error: typeof error?.message === "string"
128
+ ? error.message
129
+ : "The app-server turn failed.",
130
+ },
131
+ ];
132
+ }
133
+ if (method === "turn/completed") {
134
+ const turn = record(params.turn);
135
+ const status = turn?.status;
136
+ if (status === "completed")
137
+ return [{ finishReason: this.#sawClientTool ? "tool_calls" : "stop" }];
138
+ if (status === "interrupted")
139
+ return [{ finishReason: "length" }];
140
+ const error = record(turn?.error);
141
+ return [
142
+ {
143
+ error: typeof error?.message === "string"
144
+ ? error.message
145
+ : `The app-server turn ended with status ${String(status)}.`,
146
+ },
147
+ ];
148
+ }
149
+ if (method === "item/started" || method === "item/completed") {
150
+ const item = record(params.item);
151
+ if (method === "item/started" && item?.type === "dynamicToolCall") {
152
+ this.#sawClientTool = true;
153
+ const itemId = String(item.id);
154
+ const publicCall = this.#allocateToolCall(itemId, String(item.tool), JSON.stringify(item.arguments ?? {}));
155
+ return [{ delta: { tool_calls: [publicCall] } }];
156
+ }
157
+ if (!item ||
158
+ item.type === "agentMessage" ||
159
+ item.type === "reasoning" ||
160
+ item.type === "userMessage")
161
+ return [];
162
+ return [
163
+ this.#internalItem(method === "item/started" ? "started" : "completed", item),
164
+ ];
165
+ }
166
+ if (notificationBehavior(method) === "progress")
167
+ return [this.#internalProgress(method, params)];
168
+ return [];
169
+ }
170
+ /** Emits an internal call, or a self-correlating call/result pair. */
171
+ #internalItem(lifecycle, item) {
172
+ const id = String(item.id);
173
+ const existing = this.#toolCalls.get(id);
174
+ let call = existing;
175
+ if (!call) {
176
+ const shape = internalToolShape(item);
177
+ call = this.#allocateToolCall(id, shape.name, shape.arguments);
178
+ }
179
+ if (lifecycle === "started")
180
+ return { delta: { tool_calls: [call] } };
181
+ return {
182
+ delta: {
183
+ // Streaming clients concatenate function arguments by call index, so a
184
+ // previously announced call must not repeat its complete arguments.
185
+ ...(!existing ? { tool_calls: [call] } : {}),
186
+ tool_results: [internalToolResult(item, call)],
187
+ },
188
+ };
189
+ }
190
+ /** Emits bounded progress as a self-correlating tool result. */
191
+ #internalProgress(method, params) {
192
+ const id = String(params.itemId);
193
+ const existing = this.#toolCalls.get(id);
194
+ const call = existing ??
195
+ this.#allocateToolCall(id, safeToolName(method.slice("item/".length)), "{}");
196
+ return {
197
+ delta: {
198
+ // Orphan progress still introduces a reconstructable call, while later
199
+ // progress carries only the nonstandard self-correlating result.
200
+ ...(!existing ? { tool_calls: [call] } : {}),
201
+ tool_results: [progressToolResult(method, params, call)],
202
+ },
203
+ };
204
+ }
205
+ /** Allocates one monotonically increasing index for each call or item ID. */
206
+ #allocateToolCall(id, name, argumentsJson) {
207
+ const existing = this.#toolCalls.get(id);
208
+ if (existing)
209
+ return existing;
210
+ const call = {
211
+ index: this.#nextToolIndex++,
212
+ id,
213
+ type: "function",
214
+ function: { name: safeToolName(name), arguments: argumentsJson },
215
+ };
216
+ this.#toolCalls.set(id, call);
217
+ return call;
218
+ }
219
+ }
220
+ /** Extracts the turn identifier a notification correlates to, if present. */
221
+ function notificationTurnId(params) {
222
+ return typeof params.turnId === "string"
223
+ ? params.turnId
224
+ : record(params.turn)?.id;
225
+ }
226
+ /** Checks notification correlation without exposing foreign-thread activity. */
227
+ export function matchesTurn(value, threadId, turnId) {
228
+ const params = record(value);
229
+ if (!params)
230
+ return true;
231
+ return params.threadId === threadId && notificationTurnId(params) === turnId;
232
+ }
233
+ /** Maps a pinned internal ThreadItem to a function-shaped call. */
234
+ function internalToolShape(item) {
235
+ const kind = typeof item.type === "string" ? item.type : "unknown";
236
+ const details = {};
237
+ for (const key of [
238
+ "command",
239
+ "changes",
240
+ "server",
241
+ "tool",
242
+ "arguments",
243
+ "query",
244
+ "action",
245
+ "prompt",
246
+ ])
247
+ if (item[key] !== undefined)
248
+ details[key] = item[key];
249
+ return {
250
+ name: typeof item.tool === "string" ? item.tool : kind,
251
+ arguments: JSON.stringify(details),
252
+ };
253
+ }
254
+ /** Produces a valid function name from an app-server method or item kind. */
255
+ function safeToolName(value) {
256
+ const normalized = value.replaceAll(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128);
257
+ return normalized || "unknown_tool";
258
+ }
259
+ /** Maps a terminal internal ThreadItem to a self-contained tool result. */
260
+ function internalToolResult(item, call) {
261
+ const result = item.result ?? item.aggregatedOutput ?? item.action;
262
+ return {
263
+ id: String(item.id),
264
+ type: "function",
265
+ function: call.function,
266
+ result: {
267
+ status: typeof item.status === "string" ? item.status : "completed",
268
+ ...(result !== undefined ? { content: boundValue(result) } : {}),
269
+ ...(item.exitCode !== undefined ? { exit_code: item.exitCode } : {}),
270
+ ...(item.error !== undefined
271
+ ? { error: normalizeError(item.error) }
272
+ : {}),
273
+ },
274
+ };
275
+ }
276
+ /** Maps correlated item deltas to a bounded in-progress tool result. */
277
+ function progressToolResult(method, params, call) {
278
+ const subtype = method.slice("item/".length).split("/")[1] ?? "update";
279
+ const output = typeof params.delta === "string"
280
+ ? params.delta.slice(0, 64 * 1024)
281
+ : undefined;
282
+ const message = typeof params.message === "string"
283
+ ? params.message.slice(0, 8 * 1024)
284
+ : undefined;
285
+ return {
286
+ id: String(params.itemId),
287
+ type: "function",
288
+ function: call.function,
289
+ result: {
290
+ status: "in_progress",
291
+ progress_type: subtype,
292
+ ...(typeof params.stream === "string" ? { stream: params.stream } : {}),
293
+ ...(output !== undefined ? { content: output } : {}),
294
+ ...(message !== undefined ? { message } : {}),
295
+ ...(params.patch !== undefined
296
+ ? { patch: boundValue(params.patch) }
297
+ : {}),
298
+ },
299
+ };
300
+ }
301
+ /** Bounds structured tool payloads without changing primitive values. */
302
+ function boundValue(value) {
303
+ if (typeof value === "string")
304
+ return value.slice(0, 64 * 1024);
305
+ const encoded = JSON.stringify(value);
306
+ return encoded.length <= 64 * 1024 ? value : encoded.slice(0, 64 * 1024);
307
+ }
308
+ /** Reduces an app-server error to its documented structured public fields. */
309
+ function normalizeError(value) {
310
+ const error = record(value);
311
+ if (!error)
312
+ return { message: String(value) };
313
+ return {
314
+ ...(typeof error.message === "string" ? { message: error.message } : {}),
315
+ ...(typeof error.code === "string" ? { code: error.code } : {}),
316
+ };
317
+ }
318
+ /** Maps exact app-server last-turn usage to the standard usage object. */
319
+ function toUsage(value) {
320
+ const input = finite(value.inputTokens, "inputTokens");
321
+ const output = finite(value.outputTokens, "outputTokens");
322
+ const result = {
323
+ prompt_tokens: input,
324
+ completion_tokens: output,
325
+ total_tokens: finite(value.totalTokens, "totalTokens"),
326
+ };
327
+ if (typeof value.cachedInputTokens === "number")
328
+ result.prompt_tokens_details = { cached_tokens: value.cachedInputTokens };
329
+ if (typeof value.reasoningOutputTokens === "number")
330
+ result.completion_tokens_details = {
331
+ reasoning_tokens: value.reasoningOutputTokens,
332
+ };
333
+ return result;
334
+ }
335
+ /** Records safe structural metadata once per unexposed method and transport. */
336
+ export function diagnoseUnexposedNotification(method, params, rpc, log) {
337
+ let diagnosed = DIAGNOSED_NOTIFICATION_METHODS.get(rpc);
338
+ if (!diagnosed) {
339
+ diagnosed = new Set();
340
+ DIAGNOSED_NOTIFICATION_METHODS.set(rpc, diagnosed);
341
+ }
342
+ if (diagnosed.has(method))
343
+ return;
344
+ if (diagnosed.size >= MAX_DIAGNOSTIC_METHODS)
345
+ return;
346
+ diagnosed.add(method);
347
+ const value = record(params);
348
+ const keys = value ? Object.keys(value) : [];
349
+ log("debug", "unknown_app_server_event", {
350
+ method_fingerprint: diagnosticFingerprint(method),
351
+ params_type: Array.isArray(params)
352
+ ? "array"
353
+ : params === null
354
+ ? "null"
355
+ : typeof params,
356
+ field_count: keys.length,
357
+ field_fingerprints: keys.slice(0, 32).map(diagnosticFingerprint).sort(),
358
+ });
359
+ }
360
+ /** Hashes an untrusted diagnostic name without retaining its sensitive value. */
361
+ function diagnosticFingerprint(value) {
362
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
363
+ }
364
+ /** Rejects notifications already established as belonging to another turn. */
365
+ export function isEstablishedUnrelatedNotification(value, threadId, turnId) {
366
+ const params = record(value);
367
+ if (!params)
368
+ return false;
369
+ if (threadId && params.threadId !== threadId)
370
+ return true;
371
+ return Boolean(turnId && notificationTurnId(params) !== turnId);
372
+ }
373
+ /** Requires a finite usage count without estimating it. */
374
+ function finite(value, name) {
375
+ if (typeof value !== "number" || !Number.isFinite(value))
376
+ throw new Error(`Invalid app-server usage ${name}.`);
377
+ return value;
378
+ }
379
+ //# sourceMappingURL=chat-normalize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-normalize.js","sourceRoot":"","sources":["../../src/http/ch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S,MAAM,CAAC,KAAc,EAAE,IAAY;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,GAAG,CAAC,CAAC;IACvD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { ServerResponse } from "node:http";
2
+ import type { NormalizedDelta } from "./chat-normalize.js";
3
+ /** Creates a conventional single-choice streaming chunk. */
4
+ export declare function chunk(id: string, created: number, model: string, delta: NormalizedDelta | {
5
+ role: "assistant";
6
+ }, finishReason: string | null): Record<string, unknown>;
7
+ /** Writes one JSON SSE data frame while respecting HTTP backpressure. */
8
+ export declare function writeSse(response: ServerResponse, value: unknown): Promise<void>;
9
+ /** Writes the single terminal OpenAI-shaped error allowed on an SSE stream. */
10
+ export declare function writeSseError(response: ServerResponse, message: string): Promise<void>;
11
+ /** Writes one SSE data frame and waits for drain when required. */
12
+ export declare function writeFrame(response: ServerResponse, data: string): Promise<void>;
13
+ /** Serializes one SSE data frame without performing I/O. */
14
+ export declare function serializeSseFrame(data: string): string;
@@ -0,0 +1,52 @@
1
+ import { errorEnvelope } from "./errors.js";
2
+ /** Creates a conventional single-choice streaming chunk. */
3
+ export function chunk(id, created, model, delta, finishReason) {
4
+ return {
5
+ id,
6
+ object: "chat.completion.chunk",
7
+ created,
8
+ model,
9
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
10
+ };
11
+ }
12
+ /** Writes one JSON SSE data frame while respecting HTTP backpressure. */
13
+ export async function writeSse(response, value) {
14
+ await writeFrame(response, JSON.stringify(value));
15
+ }
16
+ /** Writes the single terminal OpenAI-shaped error allowed on an SSE stream. */
17
+ export async function writeSseError(response, message) {
18
+ await writeSse(response, errorEnvelope(message, "server_error", "app_server_error", null));
19
+ }
20
+ /** Writes one SSE data frame and waits for drain when required. */
21
+ export async function writeFrame(response, data) {
22
+ if (response.destroyed || response.writableEnded)
23
+ throw new Error("The HTTP response closed before the SSE frame was sent.");
24
+ if (!response.write(serializeSseFrame(data))) {
25
+ // close may have fired synchronously during write, before listeners attach.
26
+ if (response.destroyed || response.writableEnded)
27
+ throw new Error("The HTTP response closed while sending an SSE frame.");
28
+ await new Promise((resolve) => {
29
+ const cleanup = () => {
30
+ response.off("drain", onDrain);
31
+ response.off("close", onClose);
32
+ };
33
+ const onDrain = () => {
34
+ cleanup();
35
+ resolve();
36
+ };
37
+ const onClose = () => {
38
+ cleanup();
39
+ resolve();
40
+ };
41
+ response.once("drain", onDrain);
42
+ response.once("close", onClose);
43
+ });
44
+ if (response.destroyed && !response.writableFinished)
45
+ throw new Error("The HTTP response closed while sending an SSE frame.");
46
+ }
47
+ }
48
+ /** Serializes one SSE data frame without performing I/O. */
49
+ export function serializeSseFrame(data) {
50
+ return `data: ${data}\n\n`;
51
+ }
52
+ //# sourceMappingURL=chat-sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-sse.js","sourceRoot":"","sources":["../../src/http/chat-sse.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,4DAA4D;AAC5D,MAAM,UAAU,KAAK,CACnB,EAAU,EACV,OAAe,EACf,KAAa,EACb,KAA8C,EAC9C,YAA2B;IAE3B,OAAO;QACL,EAAE;QACF,MAAM,EAAE,uBAAuB;QAC/B,OAAO;QACP,KAAK;QACL,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,CAAC;KAC5D,CAAC;AACJ,CAAC;AAED,yEAAyE;AACzE,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,QAAwB,EACxB,KAAc;IAEd,MAAM,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK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AK,CAAC,sDAAsD,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED,4DAA4D;AAC5D,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,OAAO,SAAS,IAAI,MAAM,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { Logger } from "../core/logger.js";
2
+ import { type EffectivePolicy, type PolicyError, type RequestPolicy } from "../core/policy.js";
3
+ import type { PendingToolCall } from "../continuation/state.js";
4
+ import { HttpError } from "./errors.js";
5
+ /** A validated text-only Chat Completions message. */
6
+ export interface ChatMessage {
7
+ role: "system" | "developer" | "user" | "assistant" | "tool";
8
+ content: string;
9
+ toolCallId?: string;
10
+ toolCalls?: Array<{
11
+ id: string;
12
+ name: string;
13
+ arguments: string;
14
+ }>;
15
+ }
16
+ /** The Stage 04 request subset after validation. */
17
+ export interface ChatRequest {
18
+ model: string;
19
+ messages: ChatMessage[];
20
+ stream: boolean;
21
+ includeUsage: boolean;
22
+ dynamicTools: Array<Record<string, unknown>>;
23
+ previousResponseId?: string;
24
+ policy: EffectivePolicy;
25
+ }
26
+ /** A validated request awaiting filesystem and managed-policy resolution. */
27
+ export type ParsedChatRequest = Omit<ChatRequest, "policy"> & {
28
+ requestPolicy: RequestPolicy;
29
+ };
30
+ /** Validates the deliberately narrow request surface implemented in Stage 04. */
31
+ export declare function validateRequest(value: unknown, log: Logger, requestId: string, implicitToolContinuation: boolean): ParsedChatRequest;
32
+ /** Converts a safe policy failure to the public OpenAI error envelope. */
33
+ export declare function policyHttpError(error: PolicyError): HttpError;
34
+ /** Maps prior messages to raw Responses API history without flattening roles. */
35
+ export declare function toHistoryItem(message: ChatMessage): Record<string, unknown>;
36
+ /** Validates a complete, single-use result set for a suspended tool batch. */
37
+ export declare function validateToolResults(messages: ChatMessage[], pending: PendingToolCall[]): Map<string, string>;