@shuind/dsh-codex-harness 0.3.2 → 0.3.3
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 +17 -0
- package/README.md +21 -41
- package/docs/preset-library.md +2 -2
- package/docs/tool-policy.md +1 -1
- package/lib/client.js +1826 -545
- package/lib/compact-command.js +7 -1
- package/lib/compaction.js +7 -1
- package/lib/hybrid-executor.js +23 -12
- package/lib/index.js +1229 -17
- package/lib/preferences.js +21 -2
- package/lib/tool-policy.js +11 -2
- package/lib/typert.js +42 -1
- package/lib/types/client/desktop.d.ts +20 -42
- package/lib/types/client/desktop.js +184 -127
- package/lib/types/client/index.d.ts +104 -39
- package/lib/types/client/index.js +97 -15
- package/lib/types/client/policy-drafts.d.ts +18 -0
- package/lib/types/client/policy-drafts.js +27 -0
- package/lib/types/client/policy-locale.d.ts +81 -32
- package/lib/types/client/policy-locale.js +197 -107
- package/lib/types/client/preset-manager.d.ts +25 -2
- package/lib/types/client/preset-manager.js +89 -5
- package/lib/types/client/preset-requests.d.ts +44 -1
- package/lib/types/client/preset-requests.js +150 -0
- package/lib/types/client/tool-policy.d.ts +6 -15
- package/lib/types/client/tool-policy.js +24 -39
- package/lib/types/contracts/preset-editor-schema.d.ts +35 -0
- package/lib/types/contracts/preset-editor-schema.js +39 -0
- package/lib/types/contracts/settings.d.ts +12 -0
- package/lib/types/contracts/settings.js +10 -1
- package/lib/types/contracts/ui-contracts.d.ts +48 -0
- package/lib/types/contracts/ui-contracts.js +58 -0
- package/lib/types/contracts/update.d.ts +73 -0
- package/lib/types/contracts/update.js +291 -0
- package/lib/types/entries/index.js +20 -2
- package/lib/types/entries/preferences.d.ts +2 -0
- package/lib/types/entries/preferences.js +9 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +1 -1
- package/lib/types/hybrid/hybrid-sdk.js +27 -13
- package/lib/types/presets/preset-editor.d.ts +13 -1
- package/lib/types/presets/preset-editor.js +24 -1
- package/lib/types/presets/pro-mode-store.d.ts +13 -0
- package/lib/types/presets/pro-mode-store.js +69 -0
- package/lib/types/responses/background-sse-codec.d.ts +23 -0
- package/lib/types/responses/background-sse-codec.js +230 -0
- package/lib/types/responses/background-stream.d.ts +28 -0
- package/lib/types/responses/background-stream.js +351 -0
- package/lib/types/responses/fetch-transport.js +24 -9
- package/lib/types/responses/wire-rewrite.d.ts +4 -0
- package/lib/types/responses/wire-rewrite.js +30 -4
- package/lib/types/tools/codex-subagent.d.ts +14 -0
- package/lib/types/tools/codex-subagent.js +269 -0
- package/lib/types/update/checker.d.ts +14 -0
- package/lib/types/update/checker.js +166 -0
- package/locale/en.json +1 -1
- package/locale/hybrid-executor/en.json +1 -1
- package/locale/hybrid-executor/zh.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -2
- package/src/client/desktop.tsx +359 -160
- package/src/client/index.tsx +122 -22
- package/src/client/policy-drafts.ts +45 -0
- package/src/client/policy-locale.ts +198 -106
- package/src/client/preset-manager.tsx +125 -4
- package/src/client/preset-requests.ts +185 -1
- package/src/client/tool-policy.tsx +29 -63
- package/src/contracts/preset-editor-schema.ts +44 -0
- package/src/contracts/settings.ts +20 -1
- package/src/contracts/ui-contracts.ts +87 -0
- package/src/contracts/update.ts +307 -0
- package/src/entries/index.ts +25 -2
- package/src/entries/preferences.ts +9 -0
- package/src/hybrid/hybrid-sdk.ts +28 -12
- package/src/presets/preset-editor.ts +31 -3
- package/src/presets/pro-mode-store.ts +80 -0
- package/src/responses/background-sse-codec.ts +237 -0
- package/src/responses/background-stream.ts +371 -0
- package/src/responses/fetch-transport.ts +28 -9
- package/src/responses/wire-rewrite.ts +34 -3
- package/src/tools/codex-subagent.ts +290 -0
- package/src/update/checker.ts +193 -0
- package/tsdown.config.ts +4 -0
|
@@ -6,13 +6,27 @@ function renderKey(name) {
|
|
|
6
6
|
function pad(indent) {
|
|
7
7
|
return ' '.repeat(indent);
|
|
8
8
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
const READ_DEFAULT_LIMIT_PATTERN = /\bDefaults to (\d+)\b/i;
|
|
10
|
+
const ALREADY_HAS_UPPER_BOUND = /<=|≤|at most|less than or equal|hard max/i;
|
|
11
|
+
function propertyConstraintHint(node, toolName, propName) {
|
|
12
|
+
if (toolName === 'read' && propName === 'limit') {
|
|
13
|
+
const desc = typeof node.description === 'string' ? node.description : '';
|
|
14
|
+
if (!ALREADY_HAS_UPPER_BOUND.test(desc)) {
|
|
15
|
+
const match = READ_DEFAULT_LIMIT_PATTERN.exec(desc);
|
|
16
|
+
if (match?.[1] !== undefined)
|
|
17
|
+
return `Hard max: <= ${match[1]} (paginate with offset)`;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
function docLines(description, indent, hint) {
|
|
23
|
+
const base = typeof description === 'string' ? description.replace(/\s+/gu, ' ').trim() : '';
|
|
24
|
+
const combined = base && hint
|
|
25
|
+
? `${base.endsWith('.') ? base : `${base}.`} ${hint}.`
|
|
26
|
+
: base || (hint ? `${hint}.` : '');
|
|
27
|
+
if (combined.length === 0)
|
|
14
28
|
return [];
|
|
15
|
-
return [`${pad(indent)}/** ${
|
|
29
|
+
return [`${pad(indent)}/** ${combined.replaceAll('*/', String.raw `*\/`)} */`];
|
|
16
30
|
}
|
|
17
31
|
function renderScalar(node, type) {
|
|
18
32
|
const broad = type === 'integer' ? 'number' : type;
|
|
@@ -26,7 +40,7 @@ function renderScalar(node, type) {
|
|
|
26
40
|
function containsUnion(text) {
|
|
27
41
|
return text.includes(' | ');
|
|
28
42
|
}
|
|
29
|
-
function renderObjectNode(node, indent) {
|
|
43
|
+
function renderObjectNode(node, indent, toolName) {
|
|
30
44
|
const properties = node.properties ?? {};
|
|
31
45
|
const required = new Set(node.required ?? []);
|
|
32
46
|
const keys = Object.keys(properties).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
@@ -35,7 +49,7 @@ function renderObjectNode(node, indent) {
|
|
|
35
49
|
const child = properties[key];
|
|
36
50
|
if (child === undefined)
|
|
37
51
|
continue;
|
|
38
|
-
lines.push(...docLines(child.description, indent + 1));
|
|
52
|
+
lines.push(...docLines(child.description, indent + 1, propertyConstraintHint(child, toolName, key)));
|
|
39
53
|
const optional = required.has(key) ? '' : '?';
|
|
40
54
|
lines.push(`${pad(indent + 1)}${renderKey(key)}${optional}: ${renderNode(child, indent + 1)};`);
|
|
41
55
|
}
|
|
@@ -46,7 +60,7 @@ function renderObjectNode(node, indent) {
|
|
|
46
60
|
return '{}';
|
|
47
61
|
return `{\n${lines.join('\n')}\n${pad(indent)}}`;
|
|
48
62
|
}
|
|
49
|
-
function renderNode(node, indent) {
|
|
63
|
+
function renderNode(node, indent, toolName) {
|
|
50
64
|
if (Array.isArray(node.oneOf) && node.oneOf.length > 0) {
|
|
51
65
|
return node.oneOf.map(branch => renderNode(branch, indent)).join(' | ');
|
|
52
66
|
}
|
|
@@ -54,7 +68,7 @@ function renderNode(node, indent) {
|
|
|
54
68
|
case undefined:
|
|
55
69
|
return 'JsonValue';
|
|
56
70
|
case 'object':
|
|
57
|
-
return renderObjectNode(node, indent);
|
|
71
|
+
return renderObjectNode(node, indent, toolName);
|
|
58
72
|
case 'array': {
|
|
59
73
|
const itemText = node.items === undefined ? 'JsonValue' : renderNode(node.items, indent);
|
|
60
74
|
return containsUnion(itemText) ? `(${itemText})[]` : `${itemText}[]`;
|
|
@@ -70,10 +84,10 @@ function renderNode(node, indent) {
|
|
|
70
84
|
}
|
|
71
85
|
}
|
|
72
86
|
/** Render one supported JSON Schema node to TypeScript, degrading invalid schemas safely. */
|
|
73
|
-
export function jsonSchemaToTs(schema, indent = 0) {
|
|
87
|
+
export function jsonSchemaToTs(schema, indent = 0, toolName) {
|
|
74
88
|
try {
|
|
75
89
|
assertSupportedJsonSchema(schema);
|
|
76
|
-
return renderNode(schema, indent);
|
|
90
|
+
return renderNode(schema, indent, toolName);
|
|
77
91
|
}
|
|
78
92
|
catch {
|
|
79
93
|
return 'unknown';
|
|
@@ -166,7 +180,7 @@ export function renderHybridToolsSdk(schemas, language = 'typescript', programFo
|
|
|
166
180
|
const outputMembers = [];
|
|
167
181
|
for (const schema of sorted) {
|
|
168
182
|
argsMembers.push(...docLines(schema.description, 1));
|
|
169
|
-
argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`);
|
|
183
|
+
argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1, schema.name)};`);
|
|
170
184
|
outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`);
|
|
171
185
|
}
|
|
172
186
|
const declaration = [
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/** Read-only Host Remote service for inspecting declarative agent presets. */
|
|
2
2
|
import type { Context } from '@deepseek-ai/cordis';
|
|
3
3
|
import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
4
|
-
import type { PresetCatalog, PresetDefinitionDocument, PresetPromptCatalog } from '../contracts/ui-contracts.ts';
|
|
4
|
+
import type { CodexSubagentModelCatalog, PresetCatalog, PresetDefinitionDocument, PresetPromptCatalog } from '../contracts/ui-contracts.ts';
|
|
5
5
|
import type { PresetToolCatalog } from '../contracts/tool-policy-contract.ts';
|
|
6
|
+
import type { HarnessUpdateResult } from '../contracts/update.ts';
|
|
6
7
|
export type { PresetDefinitionDocument } from '../contracts/ui-contracts.ts';
|
|
7
8
|
export interface AgentPresetsForEditor {
|
|
8
9
|
readonly defaultId?: string;
|
|
@@ -42,6 +43,17 @@ export declare class CodexPresetEditor extends TypertRemoteService {
|
|
|
42
43
|
tools(id: string): Promise<PresetToolCatalog>;
|
|
43
44
|
prompts(id: string): Promise<PresetPromptCatalog>;
|
|
44
45
|
read(id: string): Promise<PresetDefinitionDocument>;
|
|
46
|
+
proModeGet(sessionId: string): Promise<{
|
|
47
|
+
enabled: boolean;
|
|
48
|
+
}>;
|
|
49
|
+
proModeSet(input: {
|
|
50
|
+
sessionId: string;
|
|
51
|
+
enabled: boolean;
|
|
52
|
+
}): Promise<{
|
|
53
|
+
enabled: boolean;
|
|
54
|
+
}>;
|
|
55
|
+
updateCheck(): Promise<HarnessUpdateResult>;
|
|
56
|
+
codexSubagentModels(): Promise<CodexSubagentModelCatalog>;
|
|
45
57
|
}
|
|
46
58
|
export default CodexPresetEditor;
|
|
47
59
|
//# sourceMappingURL=preset-editor.d.ts.map
|
|
@@ -2,6 +2,9 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
|
2
2
|
import { PRESET_EDITOR_SERVICE } from "../contracts/preset-editor-schema.js";
|
|
3
3
|
import { readPresetPromptCatalog } from "./preset-prompt-catalog.js";
|
|
4
4
|
import { readPresetToolCatalog } from "./preset-tool-catalog.js";
|
|
5
|
+
import { proModeStoreFor } from "./pro-mode-store.js";
|
|
6
|
+
import { readCodexSubagentModels } from "../tools/codex-subagent.js";
|
|
7
|
+
import { checkForHarnessUpdate } from "../update/checker.js";
|
|
5
8
|
export class CodexPresetEditor extends TypertRemoteService {
|
|
6
9
|
static inject = ['agentPresets'];
|
|
7
10
|
agentPresets;
|
|
@@ -58,6 +61,26 @@ export class CodexPresetEditor extends TypertRemoteService {
|
|
|
58
61
|
composition: doc.content,
|
|
59
62
|
};
|
|
60
63
|
}
|
|
64
|
+
async proModeGet(sessionId) {
|
|
65
|
+
if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.length > 256) {
|
|
66
|
+
throw new Error('invalid-session-id');
|
|
67
|
+
}
|
|
68
|
+
const store = proModeStoreFor(this.toolContext ?? this);
|
|
69
|
+
return { enabled: store.get(sessionId) };
|
|
70
|
+
}
|
|
71
|
+
async proModeSet(input) {
|
|
72
|
+
if (typeof input !== 'object' || input === null || typeof input.enabled !== 'boolean') {
|
|
73
|
+
throw new Error('invalid-pro-mode-input');
|
|
74
|
+
}
|
|
75
|
+
const store = proModeStoreFor(this.toolContext ?? this);
|
|
76
|
+
return { enabled: store.set(input.sessionId, input.enabled) };
|
|
77
|
+
}
|
|
78
|
+
async updateCheck() {
|
|
79
|
+
return checkForHarnessUpdate();
|
|
80
|
+
}
|
|
81
|
+
async codexSubagentModels() {
|
|
82
|
+
return readCodexSubagentModels(this.toolContext);
|
|
83
|
+
}
|
|
61
84
|
}
|
|
62
85
|
// Same decorator registration as the host, consumable by the Vitest transform.
|
|
63
86
|
function markRemoteMethod(methodName) {
|
|
@@ -75,7 +98,7 @@ function markRemoteMethod(methodName) {
|
|
|
75
98
|
for (const initializer of initializers)
|
|
76
99
|
initializer.call(receiver);
|
|
77
100
|
}
|
|
78
|
-
for (const method of ['catalog', 'tools', 'prompts', 'read'])
|
|
101
|
+
for (const method of ['catalog', 'tools', 'prompts', 'read', 'proModeGet', 'proModeSet', 'updateCheck', 'codexSubagentModels'])
|
|
79
102
|
markRemoteMethod(method);
|
|
80
103
|
export default CodexPresetEditor;
|
|
81
104
|
//# sourceMappingURL=preset-editor.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Ephemeral in-memory per-session OpenAI API Pro mode flags (never persisted). */
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
export interface SessionProModeStore {
|
|
4
|
+
get(sessionId: string | undefined): boolean;
|
|
5
|
+
set(sessionId: string, enabled: boolean): boolean;
|
|
6
|
+
delete(sessionId: string): void;
|
|
7
|
+
clear(): void;
|
|
8
|
+
readonly size: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function createSessionProModeStore(maxEntries?: number): SessionProModeStore;
|
|
11
|
+
/** Resolve the ephemeral Pro-mode store bound to this Cordis root context. */
|
|
12
|
+
export declare function proModeStoreFor(ctx: Context | object): SessionProModeStore;
|
|
13
|
+
//# sourceMappingURL=pro-mode-store.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Ephemeral in-memory per-session OpenAI API Pro mode flags (never persisted). */
|
|
2
|
+
const MAX_SESSION_ENTRIES = 256;
|
|
3
|
+
const MAX_SESSION_ID_LENGTH = 256;
|
|
4
|
+
function normalizeSessionId(sessionId) {
|
|
5
|
+
if (typeof sessionId !== 'string')
|
|
6
|
+
return undefined;
|
|
7
|
+
const trimmed = sessionId.trim();
|
|
8
|
+
if (trimmed.length === 0 || trimmed.length > MAX_SESSION_ID_LENGTH)
|
|
9
|
+
return undefined;
|
|
10
|
+
return trimmed;
|
|
11
|
+
}
|
|
12
|
+
export function createSessionProModeStore(maxEntries = MAX_SESSION_ENTRIES) {
|
|
13
|
+
const enabledSessions = new Map();
|
|
14
|
+
return {
|
|
15
|
+
get(sessionId) {
|
|
16
|
+
const key = normalizeSessionId(sessionId);
|
|
17
|
+
if (key === undefined)
|
|
18
|
+
return false;
|
|
19
|
+
if (!enabledSessions.has(key))
|
|
20
|
+
return false;
|
|
21
|
+
// Refresh LRU position on active lookup.
|
|
22
|
+
enabledSessions.delete(key);
|
|
23
|
+
enabledSessions.set(key, true);
|
|
24
|
+
return true;
|
|
25
|
+
},
|
|
26
|
+
set(sessionId, enabled) {
|
|
27
|
+
const key = normalizeSessionId(sessionId);
|
|
28
|
+
if (key === undefined)
|
|
29
|
+
throw new Error('invalid-session-id');
|
|
30
|
+
if (!enabled) {
|
|
31
|
+
enabledSessions.delete(key);
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
if (enabledSessions.has(key))
|
|
35
|
+
enabledSessions.delete(key);
|
|
36
|
+
while (enabledSessions.size >= maxEntries) {
|
|
37
|
+
const oldest = enabledSessions.keys().next().value;
|
|
38
|
+
if (oldest === undefined)
|
|
39
|
+
break;
|
|
40
|
+
enabledSessions.delete(oldest);
|
|
41
|
+
}
|
|
42
|
+
enabledSessions.set(key, true);
|
|
43
|
+
return true;
|
|
44
|
+
},
|
|
45
|
+
delete(sessionId) {
|
|
46
|
+
const key = normalizeSessionId(sessionId);
|
|
47
|
+
if (key !== undefined)
|
|
48
|
+
enabledSessions.delete(key);
|
|
49
|
+
},
|
|
50
|
+
clear() {
|
|
51
|
+
enabledSessions.clear();
|
|
52
|
+
},
|
|
53
|
+
get size() {
|
|
54
|
+
return enabledSessions.size;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const storesByRoot = new WeakMap();
|
|
59
|
+
/** Resolve the ephemeral Pro-mode store bound to this Cordis root context. */
|
|
60
|
+
export function proModeStoreFor(ctx) {
|
|
61
|
+
const root = ctx.root ?? ctx;
|
|
62
|
+
let store = storesByRoot.get(root);
|
|
63
|
+
if (store === undefined) {
|
|
64
|
+
store = createSessionProModeStore();
|
|
65
|
+
storesByRoot.set(root, store);
|
|
66
|
+
}
|
|
67
|
+
return store;
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=pro-mode-store.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Pure OpenAI Responses background SSE helpers: URL/body predicates, frame parsing, and poll synthesis. */
|
|
2
|
+
import type { JsonObject } from './wire-rewrite.ts';
|
|
3
|
+
export declare const ENCODER: TextEncoder;
|
|
4
|
+
export declare const KEEPALIVE_WIRE_CHUNK: Uint8Array<ArrayBuffer>;
|
|
5
|
+
export declare const SYNTHETIC_KEEPALIVE_OUTPUT_INDEX = 999999;
|
|
6
|
+
export declare const PIAI_VISIBLE_EVENT_TYPES: Set<string>;
|
|
7
|
+
export declare const TERMINAL_EVENT_TYPES: Set<string>;
|
|
8
|
+
/** True only for the official OpenAI Platform Responses API over HTTPS. */
|
|
9
|
+
export declare function isOfficialOpenAiResponsesUrl(url: string): boolean;
|
|
10
|
+
/** Enable background+store alongside streaming on eligible OpenAI Pro bodies. */
|
|
11
|
+
export declare function applyBackgroundStreamBody(body: JsonObject): JsonObject;
|
|
12
|
+
export declare function normalizeResponsesBaseUrl(url: string): string;
|
|
13
|
+
export declare function buildBackgroundControlHeaders(source: Headers, accept: string): Headers;
|
|
14
|
+
export declare function encodeSseEvent(eventType: string, payload: unknown): Uint8Array;
|
|
15
|
+
export declare function asObject(value: unknown): JsonObject | undefined;
|
|
16
|
+
export declare function parseSseEventJson(frame: string): JsonObject | undefined;
|
|
17
|
+
export declare function isSseContentType(headers: Headers): boolean;
|
|
18
|
+
export declare function shouldFallbackToPolling(status: number, errorText: string): boolean;
|
|
19
|
+
export declare function isRetryableStatus(status: number): boolean;
|
|
20
|
+
export declare function cancelledFailureEvent(response: unknown): JsonObject;
|
|
21
|
+
/** Synthesize SSE events for a polled terminal Responses object without duplicating completed items. */
|
|
22
|
+
export declare function synthesizePolledResponseSseFrames(polled: JsonObject, openedOutputIndices: ReadonlySet<number>, completedOutputIndices: ReadonlySet<number>): Uint8Array[];
|
|
23
|
+
//# sourceMappingURL=background-sse-codec.d.ts.map
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/** Pure OpenAI Responses background SSE helpers: URL/body predicates, frame parsing, and poll synthesis. */
|
|
2
|
+
export const ENCODER = new TextEncoder();
|
|
3
|
+
export const KEEPALIVE_WIRE_CHUNK = ENCODER.encode(': keepalive\n\n');
|
|
4
|
+
export const SYNTHETIC_KEEPALIVE_OUTPUT_INDEX = 999_999;
|
|
5
|
+
const STREAM_EXPIRED_PATTERN = /no longer be streamed|more than 5 minutes|cannot be streamed|not streamable|stream.*expired/i;
|
|
6
|
+
const HOP_BY_HOP_OR_BODY_HEADERS = new Set([
|
|
7
|
+
'accept',
|
|
8
|
+
'connection',
|
|
9
|
+
'content-encoding',
|
|
10
|
+
'content-length',
|
|
11
|
+
'content-type',
|
|
12
|
+
'host',
|
|
13
|
+
'transfer-encoding',
|
|
14
|
+
]);
|
|
15
|
+
export const PIAI_VISIBLE_EVENT_TYPES = new Set([
|
|
16
|
+
'response.output_item.added',
|
|
17
|
+
'response.reasoning_summary_text.delta',
|
|
18
|
+
'response.reasoning_summary_part.done',
|
|
19
|
+
'response.reasoning_text.delta',
|
|
20
|
+
'response.output_text.delta',
|
|
21
|
+
'response.refusal.delta',
|
|
22
|
+
'response.function_call_arguments.delta',
|
|
23
|
+
'response.function_call_arguments.done',
|
|
24
|
+
'response.custom_tool_call_input.delta',
|
|
25
|
+
'response.custom_tool_call_input.done',
|
|
26
|
+
'response.output_item.done',
|
|
27
|
+
'response.completed',
|
|
28
|
+
'response.incomplete',
|
|
29
|
+
'response.failed',
|
|
30
|
+
'error',
|
|
31
|
+
]);
|
|
32
|
+
export const TERMINAL_EVENT_TYPES = new Set([
|
|
33
|
+
'response.completed',
|
|
34
|
+
'response.incomplete',
|
|
35
|
+
'response.failed',
|
|
36
|
+
'response.cancelled',
|
|
37
|
+
'error',
|
|
38
|
+
]);
|
|
39
|
+
/** True only for the official OpenAI Platform Responses API over HTTPS. */
|
|
40
|
+
export function isOfficialOpenAiResponsesUrl(url) {
|
|
41
|
+
try {
|
|
42
|
+
const parsed = new URL(url);
|
|
43
|
+
return parsed.protocol === 'https:'
|
|
44
|
+
&& parsed.hostname.toLowerCase() === 'api.openai.com'
|
|
45
|
+
&& parsed.pathname.replace(/\/+$/, '').endsWith('/responses');
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Enable background+store alongside streaming on eligible OpenAI Pro bodies. */
|
|
52
|
+
export function applyBackgroundStreamBody(body) {
|
|
53
|
+
if (body.stream !== true || body.background === false)
|
|
54
|
+
return body;
|
|
55
|
+
return { ...body, background: true, store: true, stream: true };
|
|
56
|
+
}
|
|
57
|
+
export function normalizeResponsesBaseUrl(url) {
|
|
58
|
+
const parsed = new URL(url);
|
|
59
|
+
parsed.search = '';
|
|
60
|
+
parsed.hash = '';
|
|
61
|
+
parsed.pathname = parsed.pathname.replace(/\/+$/, '');
|
|
62
|
+
return parsed.toString();
|
|
63
|
+
}
|
|
64
|
+
export function buildBackgroundControlHeaders(source, accept) {
|
|
65
|
+
const headers = new Headers();
|
|
66
|
+
source.forEach((value, key) => {
|
|
67
|
+
if (!HOP_BY_HOP_OR_BODY_HEADERS.has(key.toLowerCase()))
|
|
68
|
+
headers.set(key, value);
|
|
69
|
+
});
|
|
70
|
+
headers.set('accept', accept);
|
|
71
|
+
return headers;
|
|
72
|
+
}
|
|
73
|
+
export function encodeSseEvent(eventType, payload) {
|
|
74
|
+
return ENCODER.encode(`event: ${eventType}\ndata: ${JSON.stringify(payload)}\n\n`);
|
|
75
|
+
}
|
|
76
|
+
export function asObject(value) {
|
|
77
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
78
|
+
? value
|
|
79
|
+
: undefined;
|
|
80
|
+
}
|
|
81
|
+
export function parseSseEventJson(frame) {
|
|
82
|
+
const dataLines = [];
|
|
83
|
+
for (const rawLine of frame.split(/\r?\n/)) {
|
|
84
|
+
if (rawLine.startsWith('data:')) {
|
|
85
|
+
const rest = rawLine.slice(5);
|
|
86
|
+
dataLines.push(rest.startsWith(' ') ? rest.slice(1) : rest);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (dataLines.length === 0)
|
|
90
|
+
return undefined;
|
|
91
|
+
const data = dataLines.join('\n');
|
|
92
|
+
if (data === '' || data === '[DONE]')
|
|
93
|
+
return undefined;
|
|
94
|
+
try {
|
|
95
|
+
return asObject(JSON.parse(data));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export function isSseContentType(headers) {
|
|
102
|
+
const contentType = headers.get('content-type');
|
|
103
|
+
return contentType === null || contentType.toLowerCase().includes('text/event-stream');
|
|
104
|
+
}
|
|
105
|
+
export function shouldFallbackToPolling(status, errorText) {
|
|
106
|
+
if (status === 410)
|
|
107
|
+
return true;
|
|
108
|
+
if ((status === 400 || status === 422) && STREAM_EXPIRED_PATTERN.test(errorText))
|
|
109
|
+
return true;
|
|
110
|
+
return status === 400 && errorText.trim().length > 0;
|
|
111
|
+
}
|
|
112
|
+
export function isRetryableStatus(status) {
|
|
113
|
+
return status === 408 || status === 429 || status >= 500;
|
|
114
|
+
}
|
|
115
|
+
export function cancelledFailureEvent(response) {
|
|
116
|
+
const record = asObject(response) ?? {};
|
|
117
|
+
const existingError = asObject(record.error);
|
|
118
|
+
return {
|
|
119
|
+
type: 'response.failed',
|
|
120
|
+
response: {
|
|
121
|
+
...record,
|
|
122
|
+
status: 'cancelled',
|
|
123
|
+
error: existingError ?? { code: 'cancelled', message: 'Response was cancelled' },
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function skeletonForAddedItem(item) {
|
|
128
|
+
switch (item.type) {
|
|
129
|
+
case 'reasoning': return { ...item, summary: [], content: [] };
|
|
130
|
+
case 'message': return { ...item, content: [] };
|
|
131
|
+
case 'function_call': return { ...item, arguments: '' };
|
|
132
|
+
case 'custom_tool_call': return { ...item, input: '' };
|
|
133
|
+
default: return item;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function deltaFramesForNewItem(index, item) {
|
|
137
|
+
const frames = [];
|
|
138
|
+
if (item.type === 'reasoning') {
|
|
139
|
+
const summaries = Array.isArray(item.summary)
|
|
140
|
+
? item.summary.map(part => asObject(part)?.text).filter((text) => typeof text === 'string' && text.length > 0)
|
|
141
|
+
: [];
|
|
142
|
+
const contents = Array.isArray(item.content)
|
|
143
|
+
? item.content.map(part => asObject(part)?.text).filter((text) => typeof text === 'string' && text.length > 0)
|
|
144
|
+
: [];
|
|
145
|
+
const text = summaries.length > 0 ? summaries.join('\n\n') : contents.join('\n\n');
|
|
146
|
+
if (text.length > 0) {
|
|
147
|
+
frames.push(encodeSseEvent('response.reasoning_summary_text.delta', {
|
|
148
|
+
type: 'response.reasoning_summary_text.delta',
|
|
149
|
+
output_index: index,
|
|
150
|
+
delta: text,
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else if (item.type === 'message' && Array.isArray(item.content)) {
|
|
155
|
+
for (const rawPart of item.content) {
|
|
156
|
+
const part = asObject(rawPart);
|
|
157
|
+
if (part === undefined)
|
|
158
|
+
continue;
|
|
159
|
+
if (part.type === 'output_text' && typeof part.text === 'string' && part.text.length > 0) {
|
|
160
|
+
frames.push(encodeSseEvent('response.output_text.delta', {
|
|
161
|
+
type: 'response.output_text.delta',
|
|
162
|
+
output_index: index,
|
|
163
|
+
delta: part.text,
|
|
164
|
+
}));
|
|
165
|
+
}
|
|
166
|
+
else if (part.type === 'refusal' && typeof part.refusal === 'string' && part.refusal.length > 0) {
|
|
167
|
+
frames.push(encodeSseEvent('response.refusal.delta', {
|
|
168
|
+
type: 'response.refusal.delta',
|
|
169
|
+
output_index: index,
|
|
170
|
+
delta: part.refusal,
|
|
171
|
+
}));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
else if (item.type === 'function_call' && typeof item.arguments === 'string' && item.arguments.length > 0) {
|
|
176
|
+
frames.push(encodeSseEvent('response.function_call_arguments.delta', {
|
|
177
|
+
type: 'response.function_call_arguments.delta',
|
|
178
|
+
output_index: index,
|
|
179
|
+
delta: item.arguments,
|
|
180
|
+
}));
|
|
181
|
+
}
|
|
182
|
+
else if (item.type === 'custom_tool_call' && typeof item.input === 'string' && item.input.length > 0) {
|
|
183
|
+
frames.push(encodeSseEvent('response.custom_tool_call_input.delta', {
|
|
184
|
+
type: 'response.custom_tool_call_input.delta',
|
|
185
|
+
output_index: index,
|
|
186
|
+
delta: item.input,
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
return frames;
|
|
190
|
+
}
|
|
191
|
+
/** Synthesize SSE events for a polled terminal Responses object without duplicating completed items. */
|
|
192
|
+
export function synthesizePolledResponseSseFrames(polled, openedOutputIndices, completedOutputIndices) {
|
|
193
|
+
const frames = [];
|
|
194
|
+
const output = Array.isArray(polled.output) ? polled.output : [];
|
|
195
|
+
for (let index = 0; index < output.length; index++) {
|
|
196
|
+
if (completedOutputIndices.has(index))
|
|
197
|
+
continue;
|
|
198
|
+
const item = asObject(output[index]);
|
|
199
|
+
if (item === undefined)
|
|
200
|
+
continue;
|
|
201
|
+
if (!openedOutputIndices.has(index)) {
|
|
202
|
+
frames.push(encodeSseEvent('response.output_item.added', {
|
|
203
|
+
type: 'response.output_item.added',
|
|
204
|
+
output_index: index,
|
|
205
|
+
item: skeletonForAddedItem(item),
|
|
206
|
+
}));
|
|
207
|
+
frames.push(...deltaFramesForNewItem(index, item));
|
|
208
|
+
}
|
|
209
|
+
frames.push(encodeSseEvent('response.output_item.done', {
|
|
210
|
+
type: 'response.output_item.done',
|
|
211
|
+
output_index: index,
|
|
212
|
+
item,
|
|
213
|
+
}));
|
|
214
|
+
}
|
|
215
|
+
const status = typeof polled.status === 'string' ? polled.status : 'completed';
|
|
216
|
+
if (status === 'completed') {
|
|
217
|
+
frames.push(encodeSseEvent('response.completed', { type: 'response.completed', response: polled }));
|
|
218
|
+
}
|
|
219
|
+
else if (status === 'incomplete') {
|
|
220
|
+
frames.push(encodeSseEvent('response.incomplete', { type: 'response.incomplete', response: polled }));
|
|
221
|
+
}
|
|
222
|
+
else if (status === 'cancelled') {
|
|
223
|
+
frames.push(encodeSseEvent('response.failed', cancelledFailureEvent(polled)));
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
frames.push(encodeSseEvent('response.failed', { type: 'response.failed', response: polled }));
|
|
227
|
+
}
|
|
228
|
+
return frames;
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=background-sse-codec.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resilient OpenAI Responses background+streaming transport for API Pro mode.
|
|
3
|
+
*
|
|
4
|
+
* Wraps official `api.openai.com/v1/responses` SSE streams with:
|
|
5
|
+
* 1. Mid-stream SSE resume via `GET /responses/{id}?stream=true&starting_after={seq}`;
|
|
6
|
+
* 2. Seamless fallback to `GET /responses/{id}` polling after OpenAI's 5-minute
|
|
7
|
+
* streaming replay window expires, synthesizing only missing SSE events;
|
|
8
|
+
* 3. Wire (`: keepalive`) + DSH watchdog keepalives so 5-minute idle timeouts
|
|
9
|
+
* do not abort active Pro reasoning;
|
|
10
|
+
* 4. Best-effort `POST /responses/{id}/cancel` on user abort before completion.
|
|
11
|
+
*/
|
|
12
|
+
import { applyBackgroundStreamBody, isOfficialOpenAiResponsesUrl, synthesizePolledResponseSseFrames } from './background-sse-codec.ts';
|
|
13
|
+
export { applyBackgroundStreamBody, isOfficialOpenAiResponsesUrl, synthesizePolledResponseSseFrames };
|
|
14
|
+
export interface BackgroundStreamTimingOptions {
|
|
15
|
+
wireKeepaliveIntervalMs?: number;
|
|
16
|
+
watchdogKeepaliveIntervalMs?: number;
|
|
17
|
+
pollIntervalMs?: number;
|
|
18
|
+
reconnectBaseDelayMs?: number;
|
|
19
|
+
maxReconnectDelayMs?: number;
|
|
20
|
+
maxTransientErrors?: number;
|
|
21
|
+
cancelTimeoutMs?: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Wrap an initial 200 SSE `POST /v1/responses` response with transparent
|
|
25
|
+
* sequence-tracked SSE resume, >5-minute poll fallback, keepalives, and cancel.
|
|
26
|
+
*/
|
|
27
|
+
export declare function wrapResilientBackgroundSseResponse(initialResponse: Response, request: Request, fetchImpl: typeof fetch, timing?: BackgroundStreamTimingOptions): Response;
|
|
28
|
+
//# sourceMappingURL=background-stream.d.ts.map
|