codex-copilot-dx 1.3.20 → 1.3.21
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/bin/cli.mjs +10 -1
- package/docs/ARCHITECTURE.md +3 -1
- package/docs/REFERENCE.md +4 -2
- package/package.json +1 -1
- package/src/access-settings.mjs +48 -0
- package/src/claude-gateway.mjs +26 -1
- package/src/connection-client-sync.mjs +182 -0
- package/src/connection-management.mjs +264 -0
- package/src/connection-policy.mjs +321 -0
- package/src/connection-routing.mjs +183 -0
- package/src/connection-runtime.mjs +43 -1334
- package/src/connection-view.mjs +320 -0
- package/src/privacy-transform.mjs +32 -7
- package/src/responses-handler.mjs +7 -1
- package/src/responses-proxy.mjs +30 -9
- package/src/source-lifecycle.mjs +61 -0
- package/src/stream-errors.mjs +29 -5
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { imageModelCatalog, imageModelSelection } from "./image-models.mjs";
|
|
3
|
+
import { CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
|
|
4
|
+
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
5
|
+
import { sourceModels, clientModelExclusion } from "./client-model-plan.mjs";
|
|
6
|
+
import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
|
|
7
|
+
|
|
8
|
+
export function createConnectionView({ legacy, env, binding, plan, getSource, enabled, editable, modelDisplay, discoveries,
|
|
9
|
+
setup, credentialStates, lastClients, memoryModel, capabilitySupport, sharedSync, isManaged, getSettings, corePort, permitted }) {
|
|
10
|
+
const summaries = new WeakMap();
|
|
11
|
+
function summary(api) {
|
|
12
|
+
if (!summaries.has(api))
|
|
13
|
+
summaries.set(api, {
|
|
14
|
+
model_count: api.models.length,
|
|
15
|
+
codex_model_count: api.models.filter(model => model.protocols.includes("responses")).length,
|
|
16
|
+
protocols: Object.keys(api.endpoints),
|
|
17
|
+
});
|
|
18
|
+
return summaries.get(api);
|
|
19
|
+
}
|
|
20
|
+
function imageModels() {
|
|
21
|
+
const c = binding("codex");
|
|
22
|
+
return imageModelSelection(enabled("github") && c.allowed.includes("github")
|
|
23
|
+
? imageModelCatalog(legacy.github?.registry?.models) : [], c.image_model);
|
|
24
|
+
}
|
|
25
|
+
function clientSnapshot(id, config, compact, readPlan) {
|
|
26
|
+
const base = {
|
|
27
|
+
id,
|
|
28
|
+
name: CLIENT_NAMES[id],
|
|
29
|
+
...config.clients[id],
|
|
30
|
+
setup: setup[id] || null,
|
|
31
|
+
...(credentialStates[id] ? { credential_state: credentialStates[id] } : {}),
|
|
32
|
+
...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
|
|
33
|
+
observed_at: lastClients[id] || null,
|
|
34
|
+
};
|
|
35
|
+
if (compact) return base;
|
|
36
|
+
const revision = clientRevision(id),
|
|
37
|
+
compiled = readPlan(id);
|
|
38
|
+
return {
|
|
39
|
+
...base,
|
|
40
|
+
revision,
|
|
41
|
+
model_plan: {
|
|
42
|
+
...(id === "codex" ? { image: imageModels() } : {}),
|
|
43
|
+
default_model: compiled.defaultModel,
|
|
44
|
+
default_unavailable: compiled.defaultUnavailable,
|
|
45
|
+
models: compiled.models.map(model => ({
|
|
46
|
+
source: model.source_id,
|
|
47
|
+
id: model.id,
|
|
48
|
+
display_name: model.display_name,
|
|
49
|
+
public_id: model.public_id,
|
|
50
|
+
route_id: model.route_id,
|
|
51
|
+
capability: model.capability,
|
|
52
|
+
})),
|
|
53
|
+
unavailable: (config.clients[id].deployments || [])
|
|
54
|
+
.filter(
|
|
55
|
+
item => !compiled.models.some(model => model.source_id === item.source && model.id === item.model)
|
|
56
|
+
)
|
|
57
|
+
.map(item => ({
|
|
58
|
+
source: item.source,
|
|
59
|
+
id: item.model,
|
|
60
|
+
route_id: deploymentModelId(item.source, item.model),
|
|
61
|
+
reason: modelExclusion(id, item.source, item.model),
|
|
62
|
+
})),
|
|
63
|
+
available: config.clients[id].allowed
|
|
64
|
+
.filter(enabled)
|
|
65
|
+
.flatMap(source =>
|
|
66
|
+
sourceModels(getSource(source), id).map(model => ({
|
|
67
|
+
source,
|
|
68
|
+
id: model.id,
|
|
69
|
+
display_name: model.display_name || model.name || model.id,
|
|
70
|
+
route_id: deploymentModelId(source, model.id),
|
|
71
|
+
capability: model.capability || resolveModelCapabilities(model, { builtin: true }),
|
|
72
|
+
}))
|
|
73
|
+
),
|
|
74
|
+
sync: sharedSync(),
|
|
75
|
+
support: capabilitySupport,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function modelExclusion(id, sourceId, modelId, model, selected = false) {
|
|
80
|
+
if (!model) {
|
|
81
|
+
const source = getSource(sourceId), raw = source?.catalog?.() || source?.registry?.models?.data || [];
|
|
82
|
+
model = publicModelCatalog(raw.filter(value => value.id === modelId))[0];
|
|
83
|
+
}
|
|
84
|
+
return clientModelExclusion({ client: id, binding: binding(id), sourceId, sourceEnabled: enabled(sourceId), model, selected });
|
|
85
|
+
}
|
|
86
|
+
function catalogVisibility(catalog, sourceId) {
|
|
87
|
+
if (!catalog || !Array.isArray(catalog.models)) return catalog;
|
|
88
|
+
const selected = new Map(CLIENT_IDS.map(id => [id, new Set(plan(id).models.filter(model => model.source_id === sourceId).map(model => model.id))]));
|
|
89
|
+
return { ...catalog, models: catalog.models.map(model => ({ ...model,
|
|
90
|
+
client_visibility: CLIENT_IDS.map(id => ({ client: id,
|
|
91
|
+
reason: modelExclusion(id, sourceId, model.id, model, selected.get(id).has(model.id) || id === "codex" && sourceId === "github" && model.kind === "image" && imageModels().selected_model === model.id) })) })) };
|
|
92
|
+
}
|
|
93
|
+
function snapshot(compact = false) {
|
|
94
|
+
const state = legacy.snapshot(),
|
|
95
|
+
config = isManaged() ? getSettings() : editable();
|
|
96
|
+
const localPlans = new Map();
|
|
97
|
+
const readPlan = id => {
|
|
98
|
+
if (!localPlans.has(id)) localPlans.set(id, plan(id));
|
|
99
|
+
return localPlans.get(id);
|
|
100
|
+
};
|
|
101
|
+
return structuredClone({
|
|
102
|
+
source: "connections",
|
|
103
|
+
providers: [
|
|
104
|
+
{
|
|
105
|
+
id: "github",
|
|
106
|
+
name: "GitHub Copilot",
|
|
107
|
+
enabled: config.providers.github,
|
|
108
|
+
builtin: true,
|
|
109
|
+
protocols: ["responses"],
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
id: "m365",
|
|
113
|
+
name: "Microsoft 365",
|
|
114
|
+
enabled: config.providers.m365,
|
|
115
|
+
builtin: true,
|
|
116
|
+
protocols: ["messages", "responses"],
|
|
117
|
+
},
|
|
118
|
+
...config.apis.map(api => {
|
|
119
|
+
const { secret_ref, ...publicApi } = api,
|
|
120
|
+
revision = compact ? null : deploymentRevision(api, env);
|
|
121
|
+
return {
|
|
122
|
+
...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
|
|
123
|
+
...summary(api),
|
|
124
|
+
...(compact
|
|
125
|
+
? {}
|
|
126
|
+
: {
|
|
127
|
+
deployment_revision: revision,
|
|
128
|
+
model_display: Object.fromEntries(
|
|
129
|
+
api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])
|
|
130
|
+
),
|
|
131
|
+
}),
|
|
132
|
+
discovery: discoveries.get(api.id) || null,
|
|
133
|
+
builtin: false,
|
|
134
|
+
key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref),
|
|
135
|
+
};
|
|
136
|
+
}),
|
|
137
|
+
],
|
|
138
|
+
clients: CLIENT_IDS.map(id => clientSnapshot(id, config, compact, readPlan)),
|
|
139
|
+
...(!compact
|
|
140
|
+
? {
|
|
141
|
+
source_impacts: Object.fromEntries(
|
|
142
|
+
["github", "m365", ...config.apis.map(api => api.id)].map(id => [
|
|
143
|
+
id,
|
|
144
|
+
sourceImpact(id, readPlan),
|
|
145
|
+
])
|
|
146
|
+
),
|
|
147
|
+
}
|
|
148
|
+
: {}),
|
|
149
|
+
managed: isManaged(),
|
|
150
|
+
...(!compact ? { management_version: 1 } : {}),
|
|
151
|
+
m365_state: state.m365.state,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const clientRevision = id =>
|
|
155
|
+
createHash("sha256")
|
|
156
|
+
.update(JSON.stringify(binding(id)))
|
|
157
|
+
.digest("hex");
|
|
158
|
+
function sourceImpact(source, readPlan = plan) {
|
|
159
|
+
const clients = CLIENT_IDS.flatMap(id => {
|
|
160
|
+
const c = binding(id);
|
|
161
|
+
if (!c.enabled) return [];
|
|
162
|
+
const explicit = Array.isArray(c.deployments),
|
|
163
|
+
removed = explicit ? c.deployments.filter(item => item.source === source) : [];
|
|
164
|
+
if (explicit ? !removed.length : c.source !== source) return [];
|
|
165
|
+
const remaining = explicit ? c.deployments.length - removed.length : 0;
|
|
166
|
+
const defaultSource =
|
|
167
|
+
readPlan(id).routes.get(c.default_model)?.source ||
|
|
168
|
+
removed.find(item => deploymentModelId(source, item.model) === c.default_model)?.source ||
|
|
169
|
+
c.source;
|
|
170
|
+
const default_affected = defaultSource === source;
|
|
171
|
+
return [
|
|
172
|
+
{
|
|
173
|
+
id,
|
|
174
|
+
removed: explicit ? removed.length : sourceModels(getSource(source), id).length,
|
|
175
|
+
remaining,
|
|
176
|
+
default_affected,
|
|
177
|
+
needs_replacement: default_affected || remaining === 0,
|
|
178
|
+
},
|
|
179
|
+
];
|
|
180
|
+
});
|
|
181
|
+
const api = getSettings().apis.find(item => item.id === source),
|
|
182
|
+
profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
|
|
183
|
+
return {
|
|
184
|
+
clients,
|
|
185
|
+
revision: createHash("sha256")
|
|
186
|
+
.update(JSON.stringify([source, enabled(source), profile, CLIENT_IDS.map(id => binding(id))]))
|
|
187
|
+
.digest("hex"),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const methods = {
|
|
191
|
+
snapshot() {
|
|
192
|
+
const result = legacy.snapshot();
|
|
193
|
+
if (!isManaged()) return result;
|
|
194
|
+
const performance = legacy.claudePerformance.snapshot(),
|
|
195
|
+
totals = performance.by_route.messages.terminal_outcomes.totals;
|
|
196
|
+
const ms = performance.by_route.messages.by_provider.m365;
|
|
197
|
+
const m365Requests = ms
|
|
198
|
+
? {
|
|
199
|
+
...ms.terminal_outcomes.totals,
|
|
200
|
+
active: ms.active,
|
|
201
|
+
total: ms.requests,
|
|
202
|
+
performance: {
|
|
203
|
+
by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
|
|
204
|
+
active_total: ms.active,
|
|
205
|
+
active_requests: performance.active_requests.filter(row => row.provider === "m365"),
|
|
206
|
+
recent_requests: performance.recent_requests.filter(row => row.provider === "m365"),
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
: null;
|
|
210
|
+
return {
|
|
211
|
+
...result,
|
|
212
|
+
codex_provider: this.selection().codex,
|
|
213
|
+
connections: snapshot(true),
|
|
214
|
+
m365: {
|
|
215
|
+
...result.m365,
|
|
216
|
+
...(binding("codex").source === "m365"
|
|
217
|
+
? { preference: this.providerPreference(binding("codex").source) }
|
|
218
|
+
: {}),
|
|
219
|
+
claude: {
|
|
220
|
+
...result.m365.claude,
|
|
221
|
+
requests: m365Requests,
|
|
222
|
+
clients: Object.fromEntries(
|
|
223
|
+
[
|
|
224
|
+
["app", "claude_app"],
|
|
225
|
+
["code", "claude_code"],
|
|
226
|
+
].map(([short, id]) => [
|
|
227
|
+
short,
|
|
228
|
+
binding(id).enabled && binding(id).source === "m365"
|
|
229
|
+
? setup[id] || result.m365.claude.clients[short]
|
|
230
|
+
: "not_selected",
|
|
231
|
+
])
|
|
232
|
+
),
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
claude: {
|
|
236
|
+
base_url: `http://127.0.0.1:${corePort}/anthropic`,
|
|
237
|
+
gateway: CLIENT_IDS.some(
|
|
238
|
+
id => id !== "codex" && binding(id).enabled && permitted(id, binding(id).source)
|
|
239
|
+
)
|
|
240
|
+
? "running"
|
|
241
|
+
: "unavailable",
|
|
242
|
+
clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
|
|
243
|
+
requests: {
|
|
244
|
+
...totals,
|
|
245
|
+
active: performance.active_total,
|
|
246
|
+
total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total,
|
|
247
|
+
performance,
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
...Object.fromEntries(
|
|
251
|
+
getSettings().apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])
|
|
252
|
+
),
|
|
253
|
+
};
|
|
254
|
+
},
|
|
255
|
+
dashboardProviders() {
|
|
256
|
+
const builtins = legacy.dashboardProviders();
|
|
257
|
+
if (!isManaged()) return builtins.filter(source => source.enabled);
|
|
258
|
+
const definitions = snapshot(true).providers,
|
|
259
|
+
performance = legacy.claudePerformance.snapshot();
|
|
260
|
+
return definitions
|
|
261
|
+
.filter(item => item.enabled)
|
|
262
|
+
.map(item => {
|
|
263
|
+
const old = builtins.find(source => source.id === item.id),
|
|
264
|
+
source = item.builtin ? null : getSource(item.id);
|
|
265
|
+
const clients = CLIENT_IDS.filter(
|
|
266
|
+
id =>
|
|
267
|
+
binding(id).enabled &&
|
|
268
|
+
binding(id).allowed.includes(item.id) &&
|
|
269
|
+
(id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))
|
|
270
|
+
).map(id => ({
|
|
271
|
+
id,
|
|
272
|
+
name: CLIENT_NAMES[id],
|
|
273
|
+
selected:
|
|
274
|
+
binding(id).deployments?.some(model => model.source === item.id) ||
|
|
275
|
+
binding(id).source === item.id,
|
|
276
|
+
state: setup[id] || old?.clients?.find(client => client.id === id)?.state || "unknown",
|
|
277
|
+
gateway:
|
|
278
|
+
binding(id).deployments?.some(model => model.source === item.id) ||
|
|
279
|
+
binding(id).source === item.id
|
|
280
|
+
? "running"
|
|
281
|
+
: "standby",
|
|
282
|
+
last_request_at: lastClients[id] || null,
|
|
283
|
+
}));
|
|
284
|
+
return {
|
|
285
|
+
...old,
|
|
286
|
+
id: item.id,
|
|
287
|
+
name: item.name,
|
|
288
|
+
enabled: true,
|
|
289
|
+
generation: old?.generation || source?.registry.generation || 1,
|
|
290
|
+
state: old?.state || "configured",
|
|
291
|
+
auth: old?.auth || { state: "saved", token_cached: false },
|
|
292
|
+
selection: {
|
|
293
|
+
codex: clients.some(client => client.id === "codex"),
|
|
294
|
+
models_required: item.id !== "github",
|
|
295
|
+
},
|
|
296
|
+
clients,
|
|
297
|
+
models: old?.models || { count: item.model_count, source: "configured" },
|
|
298
|
+
requests: performance.by_route.messages.by_provider[item.id]
|
|
299
|
+
? {
|
|
300
|
+
...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
|
|
301
|
+
active: performance.by_route.messages.by_provider[item.id].active,
|
|
302
|
+
total: performance.by_route.messages.by_provider[item.id].requests,
|
|
303
|
+
}
|
|
304
|
+
: null,
|
|
305
|
+
};
|
|
306
|
+
});
|
|
307
|
+
},
|
|
308
|
+
dashboardCatalog(input = {}) {
|
|
309
|
+
if (!input.provider?.startsWith("api_")) {
|
|
310
|
+
const value = legacy.dashboardCatalog(input), source = input.provider || this.selection().codex;
|
|
311
|
+
return value?.then ? value.then(catalog => catalogVisibility(catalog, source)) : catalogVisibility(value, source);
|
|
312
|
+
}
|
|
313
|
+
if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
314
|
+
return catalogVisibility(getSource(input.provider).publicCatalog(
|
|
315
|
+
CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider))
|
|
316
|
+
), input.provider);
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
return { imageModels, snapshot, sourceImpact, clientRevision, catalogVisibility, methods };
|
|
320
|
+
}
|
|
@@ -13,21 +13,38 @@ const secretPatterns = [
|
|
|
13
13
|
];
|
|
14
14
|
const secretField = /(?:["']?\b(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password)\b["']?\s*[:=]\s*)(?:"((?:\\.|[^"\\\r\n])+)"|'((?:\\.|[^'\\\r\n])+)'|([^\s,;\r\n}]+))/gdi;
|
|
15
15
|
const personalKinds = new Set(["email", "phone", "account", "payment_card", "private_address", "private_date", "private_person"]);
|
|
16
|
+
const secretKeyPattern = /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i;
|
|
16
17
|
const kept = new Set(["model", "id", "type", "role", "name", "namespace", "server_label", "server_name", "call_id", "tool_use_id", "item_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id", "previous_response_id", "prompt_cache_key", "media_type", "mime_type", "stop_reason", "finish_reason", "status", "object", "event"]);
|
|
18
|
+
function parseToolArguments(text) {
|
|
19
|
+
return JSON.parse(text, (_key, value, context) => typeof value === "number" && String(value) !== context.source
|
|
20
|
+
? JSON.rawJSON(context.source) : value);
|
|
21
|
+
}
|
|
22
|
+
// Integers under 16 digits and ordinary short decimals round-trip as JSON text.
|
|
23
|
+
// Preserve longer values and cases where JSON.stringify changes their spelling.
|
|
24
|
+
const possibleLossyNumber = /(?:\d{16}|(?=\d+\.\d)(?=(?:\d|\.){17})\d+\.\d+|\d+\.\d*0(?=[,\]}\s]|$)|\b0\.0{6,}[1-9]|\d[eE][+-]?\d|-0(?=[,\]}\s]|$))/;
|
|
25
|
+
function overlayToolStrings(target, source) {
|
|
26
|
+
if (typeof source === "string") return source;
|
|
27
|
+
if (!source || typeof source !== "object") return target;
|
|
28
|
+
for (const [key, value] of Object.entries(source)) {
|
|
29
|
+
if (typeof value === "string") target[key] = value;
|
|
30
|
+
else if (value && typeof value === "object") overlayToolStrings(target[key], value);
|
|
31
|
+
}
|
|
32
|
+
return target;
|
|
33
|
+
}
|
|
17
34
|
function leaves(value, add, inArguments = false) {
|
|
18
35
|
if (typeof value === "string") return;
|
|
19
|
-
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i]
|
|
36
|
+
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i]) : leaves(value[i], add, inArguments);return; }
|
|
20
37
|
if (!value || typeof value !== "object") return;
|
|
21
38
|
if (!inArguments && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return;
|
|
22
39
|
for (const [key, item] of Object.entries(value)) {
|
|
23
40
|
if (!inArguments && kept.has(key)) continue;
|
|
24
|
-
if (typeof item === "string") add(value, key, item
|
|
41
|
+
if (typeof item === "string") add(value, key, item);
|
|
25
42
|
else leaves(item, add, inArguments);
|
|
26
43
|
}
|
|
27
44
|
}
|
|
28
45
|
function requestTexts(body, protocol) {
|
|
29
46
|
const items = [], nested = [];
|
|
30
|
-
const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret:
|
|
47
|
+
const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: secretKeyPattern.test(String(key)) }); };
|
|
31
48
|
const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
|
|
32
49
|
const args = (parent, key) => {
|
|
33
50
|
if (typeof parent[key] === "string") {
|
|
@@ -121,9 +138,10 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
121
138
|
const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
122
139
|
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
123
140
|
for (let i = 0; i < items.length; i++) {
|
|
124
|
-
const item = items[i],
|
|
141
|
+
const item = items[i], spans = rules(item.text, personal);let bytes;
|
|
125
142
|
if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
|
|
126
143
|
for (const span of found[i] || []) {
|
|
144
|
+
bytes ||= Buffer.from(item.text);
|
|
127
145
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
|
|
128
146
|
if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
|
|
129
147
|
const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
|
|
@@ -143,18 +161,25 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
143
161
|
}
|
|
144
162
|
if (end) item.parent[item.key] = output + item.text.slice(end);
|
|
145
163
|
}
|
|
146
|
-
if (total.count) for (const item of nested)
|
|
164
|
+
if (total.count) for (const item of nested) {
|
|
165
|
+
const ordinary = JSON.stringify(item.value), original = item.parent[item.key];
|
|
166
|
+
item.parent[item.key] = ordinary !== original && possibleLossyNumber.test(original)
|
|
167
|
+
? JSON.stringify(overlayToolStrings(parseToolArguments(original), item.value)) : ordinary;
|
|
168
|
+
}
|
|
147
169
|
const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
|
|
148
170
|
function restoreValue(value, inToolData = false) {
|
|
149
171
|
if (typeof value === "string") return restoreText(value);
|
|
150
172
|
if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
|
|
151
|
-
if (!value || typeof value !== "object") return value;
|
|
173
|
+
if (!value || typeof value !== "object" || JSON.isRawJSON(value)) return value;
|
|
152
174
|
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
|
|
153
175
|
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
|
|
154
176
|
: !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
155
177
|
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
|
|
156
178
|
}
|
|
157
|
-
function restoreArguments(text) {
|
|
179
|
+
function restoreArguments(text) {
|
|
180
|
+
if (!text.includes(TOKEN_START) && !text.includes("\\u")) return text;
|
|
181
|
+
try { return JSON.stringify(restoreValue(parseToolArguments(text), true)); } catch { return restoreText(text); }
|
|
182
|
+
}
|
|
158
183
|
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
159
184
|
restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
|
|
160
185
|
}
|
|
@@ -316,6 +316,7 @@ export function createResponsesHandler(options) {
|
|
|
316
316
|
};
|
|
317
317
|
if (streaming) {
|
|
318
318
|
let streamResponseHeaders = null;
|
|
319
|
+
const streamMetadata = { response: {}, model, sequenceNumber: 0 };
|
|
319
320
|
const keepalive = createSseKeepalive({ res, signal: abort.signal, intervalMs: keepaliveIntervalMs });
|
|
320
321
|
let successful;
|
|
321
322
|
try { successful = await forwardToChat(chatReq, async (event, data) => {
|
|
@@ -327,6 +328,11 @@ export function createResponsesHandler(options) {
|
|
|
327
328
|
keepalive.activity();
|
|
328
329
|
const written = await writeOrDrain(res, `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`, { signal: abort.signal });
|
|
329
330
|
if (!written) return false;
|
|
331
|
+
if (data.response && typeof data.response === "object") {
|
|
332
|
+
for (const key of ["id", "created_at", "model"]) if (data.response[key] !== undefined) streamMetadata.response[key] = data.response[key];
|
|
333
|
+
}
|
|
334
|
+
streamMetadata.sequenceNumber = Number.isSafeInteger(data.sequence_number) && data.sequence_number >= streamMetadata.sequenceNumber
|
|
335
|
+
? data.sequence_number + 1 : streamMetadata.sequenceNumber + 1;
|
|
330
336
|
if (event === "response.completed" || event === "response.incomplete") {
|
|
331
337
|
if (event === "response.completed") rememberResponseHistory(prepared, prepared.privacyRestore?.(data.response) || data.response);
|
|
332
338
|
recordResponsesUsage({ surface: prepared.surface, mode: "stream", model, response: data.response, event: data });
|
|
@@ -345,7 +351,7 @@ export function createResponsesHandler(options) {
|
|
|
345
351
|
sendJsonError(res, responseError, statusCode || 500);
|
|
346
352
|
return;
|
|
347
353
|
}
|
|
348
|
-
await endStreamWithError(res, error || new Error(errMsg), abort);
|
|
354
|
+
await endStreamWithError(res, error || new Error(errMsg), abort, streamMetadata);
|
|
349
355
|
}, {
|
|
350
356
|
signal: abort.signal,
|
|
351
357
|
abort,
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
parseResponsesCompactionResult,
|
|
30
30
|
} from "./responses-compaction.mjs";
|
|
31
31
|
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
32
|
-
import { endStreamWithError } from "./stream-errors.mjs";
|
|
32
|
+
import { endStreamWithError, responseFailedEvent } from "./stream-errors.mjs";
|
|
33
33
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
34
34
|
import {
|
|
35
35
|
incompleteUpstreamStream,
|
|
@@ -89,7 +89,7 @@ function normalizeMessageIds(state, event, eventType) {
|
|
|
89
89
|
state.messageIds.set(index, event.item.id);
|
|
90
90
|
}
|
|
91
91
|
const id = state.messageIds.get(index);
|
|
92
|
-
if (
|
|
92
|
+
if ((eventType === "response.output_item.added" || eventType === "response.output_item.done")
|
|
93
93
|
&& event.item?.type === "message") {
|
|
94
94
|
replaceId(event.item, "id", id);
|
|
95
95
|
} else if (MESSAGE_CONTENT_EVENT_TYPES.has(eventType)) {
|
|
@@ -122,7 +122,14 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
122
122
|
"upstream_stream_json_invalid",
|
|
123
123
|
);
|
|
124
124
|
}
|
|
125
|
-
const eventType = event.type || eventName;
|
|
125
|
+
const eventType = event.type || (event.error ? "error" : eventName);
|
|
126
|
+
const previousSequence = state.lastSequence;
|
|
127
|
+
state.lastSequence = event.sequence_number ?? previousSequence + 1;
|
|
128
|
+
if (event.response && typeof event.response === "object" && !Array.isArray(event.response)) {
|
|
129
|
+
if (typeof event.response.id === "string" && event.response.id) state.response.id = event.response.id;
|
|
130
|
+
if (Number.isSafeInteger(event.response.created_at) && event.response.created_at >= 0) state.response.created_at = event.response.created_at;
|
|
131
|
+
if (typeof event.response.model === "string" && event.response.model) state.response.model = event.response.model;
|
|
132
|
+
}
|
|
126
133
|
const changed = normalizeMessageIds(state, event, eventType);
|
|
127
134
|
const outputTokens = event.response?.usage?.output_tokens ?? event.usage?.output_tokens;
|
|
128
135
|
if (outputTokens !== undefined) markOutputTokens(outputTokens);
|
|
@@ -142,10 +149,20 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
142
149
|
state.toolArgumentGuard.observe(event.output_index ?? event.item_id ?? event.call_id, event.delta);
|
|
143
150
|
}
|
|
144
151
|
if (!RESPONSES_TERMINAL_EVENT_TYPES.has(eventType)) return changed ? event : null;
|
|
152
|
+
if (eventType === "error" || eventType === "response.failed") {
|
|
153
|
+
const response = { ...(event.response && typeof event.response === "object" ? event.response : {}), ...state.response };
|
|
154
|
+
const sequenceNumber = Number.isSafeInteger(state.lastSequence) && state.lastSequence > previousSequence
|
|
155
|
+
? state.lastSequence : Number.isSafeInteger(previousSequence) ? previousSequence + 1 : 0;
|
|
156
|
+
const failure = responseFailedEvent(event.response?.error ?? event.error ?? (eventType === "error" ? event : {}), {
|
|
157
|
+
response, model: state.model, sequenceNumber, template: eventType === "response.failed" ? event : undefined,
|
|
158
|
+
});
|
|
159
|
+
state.sawTerminal = true;
|
|
160
|
+
state.failure = { event: failure, eventType: "response.failed" };
|
|
161
|
+
return failure;
|
|
162
|
+
}
|
|
145
163
|
const expectedStatus = {
|
|
146
164
|
"response.completed": "completed",
|
|
147
165
|
"response.incomplete": "incomplete",
|
|
148
|
-
"response.failed": "failed",
|
|
149
166
|
}[eventType];
|
|
150
167
|
if (expectedStatus && (!event.response?.id || event.response.status !== expectedStatus)) {
|
|
151
168
|
throw invalidUpstreamStream(
|
|
@@ -154,9 +171,6 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
154
171
|
);
|
|
155
172
|
}
|
|
156
173
|
state.sawTerminal = true;
|
|
157
|
-
if (eventType === "response.failed" || eventType === "error") {
|
|
158
|
-
state.failure = { event, eventType };
|
|
159
|
-
}
|
|
160
174
|
if (eventType === "response.completed") {
|
|
161
175
|
const response = event.response;
|
|
162
176
|
state.completed = { response, event };
|
|
@@ -216,7 +230,9 @@ function createResponseSseTransformer(state) {
|
|
|
216
230
|
if (wroteData) return false;
|
|
217
231
|
wroteData = true;
|
|
218
232
|
return true;
|
|
219
|
-
}).map((line) => line.startsWith("data:") ? `data: ${JSON.stringify(changed)}`
|
|
233
|
+
}).map((line) => line.startsWith("data:") ? `data: ${JSON.stringify(changed)}`
|
|
234
|
+
: changed.type === "response.failed" && line.startsWith("event:") ? "event: response.failed" : line);
|
|
235
|
+
if (changed.type === "response.failed" && !eventName) rewritten.unshift("event: response.failed");
|
|
220
236
|
const newline = bareCR ? chunk.match(/\r\n|\r|\n/)?.[0] || "\n" : chunk.includes("\r\n") ? "\r\n" : "\n";
|
|
221
237
|
return Buffer.from(rewritten.join(newline)
|
|
222
238
|
+ frame.subarray(contentLength).toString("ascii"));
|
|
@@ -480,6 +496,9 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
480
496
|
failure: null,
|
|
481
497
|
sawTerminal: false,
|
|
482
498
|
sawOutput: false,
|
|
499
|
+
response: {},
|
|
500
|
+
model: reqContext.body?.model,
|
|
501
|
+
lastSequence: -1,
|
|
483
502
|
toolArgumentGuard: new ToolArgumentDeltaGuard(),
|
|
484
503
|
messageIds: new Map(),
|
|
485
504
|
};
|
|
@@ -592,7 +611,9 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
592
611
|
markStreamFailure();
|
|
593
612
|
logRequestFailure("Responses", error, options.abort);
|
|
594
613
|
writeHeaders();
|
|
595
|
-
await endStreamWithError(res, error, options.abort
|
|
614
|
+
await endStreamWithError(res, error, options.abort, {
|
|
615
|
+
response: streamState.response, model: streamState.model, sequenceNumber: streamState.lastSequence + 1,
|
|
616
|
+
});
|
|
596
617
|
return { successful: false, compacted: false };
|
|
597
618
|
} finally {
|
|
598
619
|
keepalive.stop();
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export function createSourceLifecycle({ legacy, secrets, log }) {
|
|
2
|
+
const active = new Map(), retired = new Set(), sourceSecrets = new WeakMap(), retiredSecrets = new Map(), cleanups = new Set();
|
|
3
|
+
|
|
4
|
+
function cleanSecrets(id) {
|
|
5
|
+
const refs = retiredSecrets.get(id);
|
|
6
|
+
if (!refs) return;
|
|
7
|
+
for (const ref of refs) {
|
|
8
|
+
if ([...active.keys()].some(source => sourceSecrets.get(source) === ref)) continue;
|
|
9
|
+
refs.delete(ref);
|
|
10
|
+
const task = secrets
|
|
11
|
+
.remove(ref)
|
|
12
|
+
.catch(() => {
|
|
13
|
+
log("warn", "Previous API credential cleanup needs review");
|
|
14
|
+
})
|
|
15
|
+
.finally(() => cleanups.delete(task));
|
|
16
|
+
cleanups.add(task);
|
|
17
|
+
}
|
|
18
|
+
if (!refs.size) retiredSecrets.delete(id);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function retire(source) {
|
|
22
|
+
if (active.get(source)) retired.add(source);
|
|
23
|
+
else source.close();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function track(source) {
|
|
27
|
+
const finishLegacy = legacy.track(source);
|
|
28
|
+
active.set(source, (active.get(source) || 0) + 1);
|
|
29
|
+
let done = false;
|
|
30
|
+
return () => {
|
|
31
|
+
if (done) return;
|
|
32
|
+
done = true;
|
|
33
|
+
finishLegacy?.();
|
|
34
|
+
const count = (active.get(source) || 1) - 1;
|
|
35
|
+
if (count) active.set(source, count);
|
|
36
|
+
else {
|
|
37
|
+
active.delete(source);
|
|
38
|
+
if (retired.delete(source)) source.close();
|
|
39
|
+
cleanSecrets(source.id);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
track,
|
|
46
|
+
retire,
|
|
47
|
+
rememberSource: (source, ref) => sourceSecrets.set(source, ref),
|
|
48
|
+
retireSecret(id, ref) {
|
|
49
|
+
if (!retiredSecrets.has(id)) retiredSecrets.set(id, new Set());
|
|
50
|
+
retiredSecrets.get(id).add(ref);
|
|
51
|
+
cleanSecrets(id);
|
|
52
|
+
},
|
|
53
|
+
busy: () => active.size > 0,
|
|
54
|
+
close() {
|
|
55
|
+
for (const source of retired) source.close();
|
|
56
|
+
active.clear();
|
|
57
|
+
for (const id of retiredSecrets.keys()) cleanSecrets(id);
|
|
58
|
+
return Promise.allSettled([...cleanups]);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/stream-errors.mjs
CHANGED
|
@@ -1,19 +1,43 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { writeOrDrain } from "./http-transport.mjs";
|
|
2
3
|
import { markStreamFailure } from "./stream-performance.mjs";
|
|
3
4
|
|
|
4
|
-
function
|
|
5
|
+
export function responseFailedEvent(error, { response, model, sequenceNumber, template } = {}) {
|
|
6
|
+
const prior = response && typeof response === "object" && !Array.isArray(response) ? response : {};
|
|
7
|
+
const detail = error && typeof error === "object" && !Array.isArray(error) ? error : {};
|
|
8
|
+
const code = typeof detail.code === "string" && detail.code ? detail.code : "upstream_stream_error";
|
|
9
|
+
const message = typeof detail.message === "string" && detail.message ? detail.message
|
|
10
|
+
: typeof error === "string" && error ? error : "Upstream stream failed";
|
|
11
|
+
return {
|
|
12
|
+
...template,
|
|
13
|
+
type: "response.failed",
|
|
14
|
+
sequence_number: Number.isSafeInteger(sequenceNumber) && sequenceNumber >= 0 ? sequenceNumber : 0,
|
|
15
|
+
response: {
|
|
16
|
+
...prior,
|
|
17
|
+
id: typeof prior.id === "string" && prior.id ? prior.id : `resp_ccdx_${randomUUID().replaceAll("-", "")}`,
|
|
18
|
+
object: "response",
|
|
19
|
+
created_at: Number.isSafeInteger(prior.created_at) && prior.created_at >= 0 ? prior.created_at : Math.floor(Date.now() / 1000),
|
|
20
|
+
model: typeof prior.model === "string" && prior.model ? prior.model : typeof model === "string" && model ? model : "unknown",
|
|
21
|
+
status: "failed",
|
|
22
|
+
output: Array.isArray(prior.output) ? prior.output : [],
|
|
23
|
+
error: { ...detail, code, message },
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function streamErrorData(error, abort, metadata) {
|
|
5
29
|
const code = abort?.reason || error?.code || "upstream_stream_error";
|
|
6
30
|
const message = `${code}: ${error?.message || "Upstream stream failed"}`;
|
|
7
|
-
return {
|
|
31
|
+
return responseFailedEvent({ code, message }, metadata);
|
|
8
32
|
}
|
|
9
33
|
|
|
10
|
-
export async function endStreamWithError(res, error, abort) {
|
|
34
|
+
export async function endStreamWithError(res, error, abort, metadata) {
|
|
11
35
|
markStreamFailure();
|
|
12
36
|
if (res.destroyed || res.writableEnded) return;
|
|
13
|
-
const data = streamErrorData(error, abort);
|
|
37
|
+
const data = streamErrorData(error, abort, metadata);
|
|
14
38
|
// Allow a final error frame after an upstream timeout, but never wait forever
|
|
15
39
|
// for a client that has stopped reading (including protocol-error paths).
|
|
16
|
-
await writeOrDrain(res, `event:
|
|
40
|
+
await writeOrDrain(res, `event: response.failed\ndata: ${JSON.stringify(data)}\n\n`, {
|
|
17
41
|
signal: AbortSignal.timeout(1000),
|
|
18
42
|
}).catch(() => false);
|
|
19
43
|
if (!res.destroyed && !res.writableEnded) res.end();
|