codex-copilot-dx 1.4.4 → 1.4.5
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/README.md +2 -1
- package/bin/cli.mjs +5 -4
- package/docs/ARCHITECTURE.md +16 -0
- package/docs/REFERENCE.md +34 -8
- package/package.json +1 -1
- package/src/access-settings.mjs +3 -1
- package/src/adapter.mjs +9 -1
- package/src/antigravity-chat-bridge.mjs +4 -2
- package/src/antigravity-handler.mjs +28 -16
- package/src/antigravity-images.mjs +3 -2
- package/src/antigravity-runtime.mjs +13 -3
- package/src/application-configuration.mjs +43 -0
- package/src/application-control.mjs +114 -0
- package/src/application-evidence.mjs +42 -0
- package/src/application-process.mjs +114 -0
- package/src/claude-gateway.mjs +24 -15
- package/src/cli-command-spec.mjs +7 -4
- package/src/cli-management.mjs +27 -2
- package/src/codex-image-host-launch.mjs +1 -2
- package/src/codex-launch-control.mjs +7 -7
- package/src/connection-management.mjs +18 -3
- package/src/connection-policy.mjs +3 -1
- package/src/connection-routing.mjs +7 -2
- package/src/connection-runtime.mjs +21 -5
- package/src/connection-view.mjs +9 -3
- package/src/context-compaction-wire.mjs +7 -6
- package/src/context-compaction.mjs +6 -4
- package/src/copilot-client.mjs +17 -13
- package/src/copilot-responses-compat.mjs +1 -0
- package/src/copilot-web.mjs +6 -2
- package/src/dashboard/applications.js +83 -0
- package/src/dashboard/connections.js +52 -14
- package/src/dashboard/console.js +19 -9
- package/src/dashboard/gemini.js +8 -5
- package/src/dashboard/index.html +16 -0
- package/src/dashboard/language.js +41 -0
- package/src/dashboard/ui.css +9 -0
- package/src/dashboard-api.mjs +6 -1
- package/src/dashboard.mjs +1 -0
- package/src/gemini-app.mjs +3 -2
- package/src/http-transport.mjs +5 -2
- package/src/launcher.mjs +6 -5
- package/src/native-images.mjs +1 -1
- package/src/provider-runtime.mjs +14 -9
- package/src/providers/api.mjs +18 -12
- package/src/providers/m365.mjs +9 -5
- package/src/request-admission.mjs +6 -0
- package/src/responses-bridge.mjs +5 -2
- package/src/responses-handler.mjs +2 -0
- package/src/responses-proxy.mjs +9 -4
- package/src/safe-upstream-error.mjs +9 -11
- package/src/service-control.mjs +29 -5
- package/src/settings-preferences.mjs +3 -3
- package/src/source-admission-state.mjs +29 -0
- package/src/source-admission.mjs +310 -0
- package/src/source-discovery-probe.mjs +35 -0
- package/src/source-discovery.mjs +112 -0
- package/src/source-response.mjs +134 -0
- package/src/source-transport.mjs +19 -0
- package/src/stream-contract.mjs +3 -1
- package/src/stream-performance.mjs +3 -1
- package/src/stream.mjs +6 -4
- package/src/upstream-body.mjs +9 -8
- package/src/user-settings.mjs +2 -2
package/src/providers/api.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { sourceTransport } from "../source-transport.mjs";
|
|
3
|
+
import { SOURCE_HTTP_CLIENT, sourceResponseFeedback, cancelSourceResponse } from "../source-response.mjs";
|
|
2
4
|
import { createRoutePlan } from "../route-plan.mjs";
|
|
3
5
|
import { accessError } from "../access-settings.mjs";
|
|
4
6
|
import { publicModelCatalog } from "../provider-metadata.mjs";
|
|
@@ -14,7 +16,7 @@ import { transportErrorDetails } from "../operation-error.mjs";
|
|
|
14
16
|
import { readSafeUpstreamReason } from "../safe-upstream-error.mjs";
|
|
15
17
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
16
18
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
17
|
-
import { markRequestObservation
|
|
19
|
+
import { markRequestObservation } from "../stream-performance.mjs";
|
|
18
20
|
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
19
21
|
import { createApiTokenCounter } from "./api-token-count.mjs";
|
|
20
22
|
import { apiModelDisplay } from "../api-model-display.mjs";
|
|
@@ -24,6 +26,7 @@ import { loadRuntimeConfig } from "../runtime-config.mjs";
|
|
|
24
26
|
import { currentRequestContext } from "../request-context.mjs";
|
|
25
27
|
import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
26
28
|
import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
|
|
29
|
+
import { SOURCE_LIMIT_EVIDENCE, sourceLimitFeedback } from "../source-admission.mjs";
|
|
27
30
|
|
|
28
31
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
29
32
|
export function apiCatalog(config, env = process.env) {
|
|
@@ -90,18 +93,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
90
93
|
const recovery = cooldown?.enter();let observed = false;
|
|
91
94
|
try {
|
|
92
95
|
const transport = !closed && network && (network.healthy?.() ?? true) ? network : await getNetwork(options.signal);
|
|
93
|
-
options.
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort });
|
|
98
|
-
}
|
|
99
|
-
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
96
|
+
const result = await sourceTransport(options, { send: transport.fetch, receiver: transport, args: [url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal }],
|
|
97
|
+
model: body?.model, bodyText: serialized, stream: body?.stream === true, observe: Boolean(body && options.observeUpstream !== false),
|
|
98
|
+
evidence: body && !options.countTokens ? { max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens,
|
|
99
|
+
reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort } : undefined });
|
|
100
100
|
const temporary = result.status === 502 || result.status === 503 || result.status === 504;
|
|
101
101
|
let retryAfterMs = 0;
|
|
102
102
|
if (temporary) { const retry = result.headers.get("retry-after");retryAfterMs = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - now()); }
|
|
103
103
|
cooldown?.complete(recovery, temporary, false, Number.isFinite(retryAfterMs) ? retryAfterMs : 0);observed = true;
|
|
104
|
-
if (result.status >= 300 && result.status < 400) { await result.
|
|
104
|
+
if (result.status >= 300 && result.status < 400) { await cancelSourceResponse(result).catch(() => {});throw accessError("ccdx_api_redirect_refused", 502); }
|
|
105
105
|
if (!result.ok) {
|
|
106
106
|
const adapted = api === "responses" && [400, 422].includes(result.status) && !options.compatibilityRetried && !options.skipCallLessRetry
|
|
107
107
|
? normalizeCallLessToolOutputs(body) : null;
|
|
@@ -110,9 +110,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
110
110
|
if (!adapted && !schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
|
|
111
111
|
const context = currentRequestContext();
|
|
112
112
|
const finishCapture = options.countTokens ? null : errorCapture?.claim(config.id, body?.model, api, result.status, context?.requestId);
|
|
113
|
-
let reason;
|
|
113
|
+
let reason, sourceLimit;
|
|
114
114
|
try {
|
|
115
115
|
reason = await readSafeUpstreamReason(result, { signal: options.signal, missingCallId: Boolean(adapted), rootToolSchema: schemaCandidate,
|
|
116
|
+
onSourceLimit: value => { sourceLimit = sourceLimitFeedback(result.status, result.headers, value, now());sourceResponseFeedback(result, value); },
|
|
116
117
|
...(finishCapture ? { diagnosticRedact: text => text.replaceAll(key, "[redacted]") } : {}) });
|
|
117
118
|
} finally {
|
|
118
119
|
const retained = finishCapture?.(reason?.diagnostic_message);
|
|
@@ -145,12 +146,16 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
145
146
|
const contextOverflow = api === "messages" && ["context_length_exceeded", "context_window_exceeded"].includes(reason?.code);
|
|
146
147
|
const message=(contextOverflow ? "prompt is too long. " : "")+(reason?.message||"The source rejected the request (HTTP "+result.status+"); no recognised technical reason was returned.")+" Source: "+redactDiagnosticText(config.name||config.id)+". Model: "+redactDiagnosticText(body?.model||"unknown")+". API: "+api+"."+(requestId?" Request: "+requestId+".":"");
|
|
147
148
|
const errorType = api === "messages" && ["input_length_invalid", "context_length_exceeded", "context_window_exceeded"].includes(reason?.code) ? "invalid_request_error" : "api_error";
|
|
148
|
-
|
|
149
|
+
const failure = new Response(JSON.stringify({ type: "error", error: { type: errorType, code, message,
|
|
149
150
|
...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
151
|
+
if (sourceLimit) Object.defineProperty(failure, SOURCE_LIMIT_EVIDENCE, { value: sourceLimit });
|
|
152
|
+
return failure;
|
|
150
153
|
}
|
|
151
154
|
return result;
|
|
152
155
|
} catch (error) {
|
|
153
|
-
|
|
156
|
+
const localAdmission = error.sourceQueue || error.origin === "source_admission";
|
|
157
|
+
if (!observed) cooldown?.complete(recovery, localAdmission ? false : confirmedNetworkFailure(error), options.signal?.aborted === true || localAdmission);
|
|
158
|
+
if (localAdmission) throw error;
|
|
154
159
|
if (options.signal?.aborted) throw error;
|
|
155
160
|
if (error.code === "ccdx_api_redirect_refused") throw error;
|
|
156
161
|
const failure = accessError("ccdx_api_network_unavailable", 502);
|
|
@@ -161,6 +166,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
161
166
|
}
|
|
162
167
|
const counter = createApiTokenCounter({ request: (body, options) => request(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens", body, options, "messages") });
|
|
163
168
|
const client = {
|
|
169
|
+
[SOURCE_HTTP_CLIENT]: true,
|
|
164
170
|
listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
|
|
165
171
|
getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
|
|
166
172
|
async responses(body, options = {}) {
|
package/src/providers/m365.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { sourceTransport } from "../source-transport.mjs";
|
|
3
|
+
import { SOURCE_HTTP_CLIENT } from "../source-response.mjs";
|
|
2
4
|
import { createM365Auth, m365Error } from "./m365-auth.mjs";
|
|
3
5
|
import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Binding } from "../m365-settings.mjs";
|
|
4
6
|
import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
@@ -7,7 +9,7 @@ import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs"
|
|
|
7
9
|
import { createRoutePlan } from "../route-plan.mjs";
|
|
8
10
|
import { CODEX_AUTO_REVIEW_MODEL } from "../models.mjs";
|
|
9
11
|
import { currentRequestContext } from "../request-context.mjs";
|
|
10
|
-
import { markRequestObservation, markUpstreamHeaders
|
|
12
|
+
import { markRequestObservation, markUpstreamHeaders } from "../stream-performance.mjs";
|
|
11
13
|
import { requestOptionsEvidence } from "../response-failures.mjs";
|
|
12
14
|
import { status } from "../status.mjs";
|
|
13
15
|
import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
@@ -126,12 +128,12 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
126
128
|
if (endpoint === "/models") { requestHeaders["Cache-Control"] = "no-cache";requestHeaders.Pragma = "no-cache"; }
|
|
127
129
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
128
130
|
if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
129
|
-
options.onUpstreamStart?.();
|
|
130
|
-
if (body) { if (options.observeUpstream !== false) markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
|
|
131
131
|
try {
|
|
132
132
|
const send = fetchImpl || await transport(options.signal);
|
|
133
|
-
const response = await send
|
|
134
|
-
...(serialized !== undefined ? { body: serialized } : {}), signal: options.signal, redirect: "manual" }
|
|
133
|
+
const response = await sourceTransport(options, { send, args: [`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
|
|
134
|
+
...(serialized !== undefined ? { body: serialized } : {}), signal: options.signal, redirect: "manual" }],
|
|
135
|
+
model: body?.model, bodyText: serialized, stream: body?.stream === true, observe: Boolean(body && options.observeUpstream !== false),
|
|
136
|
+
evidence: body && !options.countTokens ? { max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens } : undefined });
|
|
135
137
|
if (endpoint === "/models") {
|
|
136
138
|
const age = response.headers.get("age");
|
|
137
139
|
lastCatalogResponse = { http_status: response.status, request_id: response.headers.get("request-id") || response.headers.get("x-ms-request-id") || response.headers.get("x-request-id"),
|
|
@@ -144,6 +146,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
144
146
|
const headers = new Headers(response.headers);headers.delete("content-length");headers.delete("content-encoding");
|
|
145
147
|
return new Response(safe, { status: response.status, headers });
|
|
146
148
|
} catch (error) {
|
|
149
|
+
if (error.sourceQueue || error.origin === "source_admission") throw error;
|
|
147
150
|
if (options.signal?.aborted) throw options.signal.reason || error;
|
|
148
151
|
throw Object.assign(new Error(redactDiagnosticText(String(error.message).split(credential.token).join("[redacted]"))), {
|
|
149
152
|
code: /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_network_error", statusCode: 502,
|
|
@@ -196,6 +199,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
196
199
|
}
|
|
197
200
|
|
|
198
201
|
const client = {
|
|
202
|
+
[SOURCE_HTTP_CLIENT]: true,
|
|
199
203
|
async listModels({ signal } = {}) {
|
|
200
204
|
signal?.throwIfAborted();
|
|
201
205
|
if (!catalog) await refresh();
|
|
@@ -214,6 +214,12 @@ export function createRequestAdmission({
|
|
|
214
214
|
activeRequests = Math.max(0, activeRequests - 1);
|
|
215
215
|
drain();
|
|
216
216
|
};
|
|
217
|
+
release.resize = bytes => {
|
|
218
|
+
if (released || !Number.isSafeInteger(bytes) || bytes < 0) return;
|
|
219
|
+
const next = Math.max(1, Math.min(entry.weight, bytes));
|
|
220
|
+
if (next === entry.weight) return;
|
|
221
|
+
activeBytes -= entry.weight - next;entry.weight = next;drain();
|
|
222
|
+
};
|
|
217
223
|
const reserve = async (gate, weight, options) => {
|
|
218
224
|
const releaseSupplemental = await gate(weight, options);
|
|
219
225
|
if (released) {
|
package/src/responses-bridge.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { markToolActivity } from "./stream-performance.mjs";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { chatCompletions } from "./copilot.mjs";
|
|
4
4
|
import { webStreamLines } from "./stream.mjs";
|
|
5
|
+
import { cancelSourceResponse, sourceResponseAccepted, sourceResponseFailed } from "./source-response.mjs";
|
|
5
6
|
import { normalizeCallLessToolOutputs } from "./responses-tool-output.mjs";
|
|
6
7
|
import {
|
|
7
8
|
abortErrorStatusCode,
|
|
@@ -348,6 +349,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
348
349
|
try {
|
|
349
350
|
onUpstreamStart?.();
|
|
350
351
|
resp = await chatCompletionsFn(upstreamReq, {
|
|
352
|
+
sourceBodyManaged: true,
|
|
351
353
|
signal,
|
|
352
354
|
bodyText,
|
|
353
355
|
onUpstreamStart,
|
|
@@ -518,7 +520,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
518
520
|
})) {
|
|
519
521
|
if (!line.startsWith("data: ")) continue;
|
|
520
522
|
const data = line.slice(6).trim();
|
|
521
|
-
if (data === "[DONE]") { const completed = await emitTerminal(); onDone();
|
|
523
|
+
if (data === "[DONE]") { const completed = await emitTerminal();if (completed) sourceResponseAccepted(resp);onDone();return completed; }
|
|
522
524
|
let parsed;
|
|
523
525
|
try {
|
|
524
526
|
parsed = JSON.parse(data);
|
|
@@ -529,6 +531,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
529
531
|
);
|
|
530
532
|
}
|
|
531
533
|
const upstreamError = upstreamChatStreamError(parsed);
|
|
534
|
+
if (upstreamError) sourceResponseFailed(resp);
|
|
532
535
|
if (upstreamError) throw upstreamError;
|
|
533
536
|
if (parsed.model) actualModel = parsed.model;
|
|
534
537
|
if (parsed.usage) {
|
|
@@ -584,7 +587,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
584
587
|
} catch (e) {
|
|
585
588
|
if (e === downstreamClosed) {
|
|
586
589
|
markResponseTerminal("cancelled", { model: actualModel, origin: "client_disconnect" });
|
|
587
|
-
await resp
|
|
590
|
+
await cancelSourceResponse(resp).catch(() => {});
|
|
588
591
|
return false;
|
|
589
592
|
}
|
|
590
593
|
markResponseErrorOrigin("transport");
|
|
@@ -218,6 +218,7 @@ export function createResponsesHandler(options) {
|
|
|
218
218
|
}
|
|
219
219
|
};
|
|
220
220
|
const applyAdaptiveTimeout = (error) => {
|
|
221
|
+
if (error.sourceQueue) return error;
|
|
221
222
|
if (!["responses_prepare_timeout", "stream_handshake_timeout", "upstream_timeout"].includes(abort.reason)) {
|
|
222
223
|
return error;
|
|
223
224
|
}
|
|
@@ -462,6 +463,7 @@ export function createResponsesHandler(options) {
|
|
|
462
463
|
const toolChoice = chatReq.tool_choice;
|
|
463
464
|
startUpstreamTimeout();
|
|
464
465
|
const upstream = await chatCompletionsFn(chatReq, {
|
|
466
|
+
sourceBodyManaged: true,
|
|
465
467
|
signal: abort.signal,
|
|
466
468
|
bodyText,
|
|
467
469
|
onUpstreamStart: startUpstreamTimeout,
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { markToolActivity } from "./stream-performance.mjs";
|
|
2
|
+
import { observeSourceStreamFailure } from "./source-admission.mjs";
|
|
3
|
+
import { sourceResponseReader, cancelSourceReader, releaseSourceReader, sourceResponseAccepted } from "./source-response.mjs";
|
|
2
4
|
import { responses as copilotResponses } from "./copilot.mjs";
|
|
3
5
|
import {
|
|
4
6
|
logRequestFailure,
|
|
@@ -163,6 +165,7 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
163
165
|
}
|
|
164
166
|
if (!RESPONSES_TERMINAL_EVENT_TYPES.has(eventType)) return changed ? event : null;
|
|
165
167
|
if (eventType === "error" || eventType === "response.failed") {
|
|
168
|
+
observeSourceStreamFailure(state.sourceResponse, event.response?.error ?? event.error ?? event);
|
|
166
169
|
const response = { ...(event.response && typeof event.response === "object" ? event.response : {}), ...state.response };
|
|
167
170
|
const sequenceNumber = Number.isSafeInteger(state.lastSequence) && state.lastSequence > previousSequence
|
|
168
171
|
? state.lastSequence : Number.isSafeInteger(previousSequence) ? previousSequence + 1 : 0;
|
|
@@ -184,6 +187,7 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
184
187
|
);
|
|
185
188
|
}
|
|
186
189
|
state.sawTerminal = true;
|
|
190
|
+
sourceResponseAccepted(state.sourceResponse);
|
|
187
191
|
if (eventType === "response.completed") {
|
|
188
192
|
const response = event.response;
|
|
189
193
|
state.completed = { response, event };
|
|
@@ -502,8 +506,9 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
502
506
|
headersSent = true;
|
|
503
507
|
res.writeHead(resp.status, headers);
|
|
504
508
|
};
|
|
505
|
-
const reader = resp
|
|
509
|
+
const reader = sourceResponseReader(resp);
|
|
506
510
|
const streamState = {
|
|
511
|
+
sourceResponse: resp,
|
|
507
512
|
completed: null,
|
|
508
513
|
incomplete: null,
|
|
509
514
|
failure: null,
|
|
@@ -621,7 +626,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
621
626
|
if (!res.writableEnded) res.end();
|
|
622
627
|
return { successful: Boolean(streamState.completed), compacted: false };
|
|
623
628
|
} catch (error) {
|
|
624
|
-
markResponseErrorOrigin(
|
|
629
|
+
markResponseErrorOrigin(["privacy", "source_admission"].includes(error.origin) ? error.origin : "transport");
|
|
625
630
|
markStreamFailure();
|
|
626
631
|
logRequestFailure("Responses", error, options.abort);
|
|
627
632
|
writeHeaders();
|
|
@@ -631,8 +636,8 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
631
636
|
return { successful: false, compacted: false };
|
|
632
637
|
} finally {
|
|
633
638
|
keepalive.stop();
|
|
634
|
-
await reader
|
|
635
|
-
reader
|
|
639
|
+
await cancelSourceReader(reader).catch(() => {});
|
|
640
|
+
releaseSourceReader(reader);
|
|
636
641
|
}
|
|
637
642
|
}
|
|
638
643
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isMissingCallIdError } from "./responses-tool-output.mjs";
|
|
2
2
|
import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
|
|
3
3
|
import { redactDiagnosticText, boundedDiagnosticText } from "./diagnostic-text.mjs";
|
|
4
|
+
import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse } from "./source-response.mjs";
|
|
4
5
|
|
|
5
6
|
// Default evidence contains only fixed categories. A separately authorized
|
|
6
7
|
// one-shot capture can retain a bounded, redacted technical message.
|
|
@@ -26,10 +27,6 @@ const reasons = new Map([
|
|
|
26
27
|
const MAX_ACTIVE_READS = 4;
|
|
27
28
|
let activeReads = 0;
|
|
28
29
|
|
|
29
|
-
function cancelBody(body) {
|
|
30
|
-
try { void Promise.resolve(body?.cancel()).catch(() => {}); } catch {}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
30
|
export function safeUpstreamReason(code, status) {
|
|
34
31
|
const reason = typeof code === "string" ? reasons.get(code) : null;
|
|
35
32
|
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
@@ -78,20 +75,20 @@ function readChunk(reader, signal) {
|
|
|
78
75
|
const finish = (fn, value) => { if (settled) return;settled = true;signal.removeEventListener("abort", onAbort);fn(value); };
|
|
79
76
|
const onAbort = () => finish(reject, signal.reason);
|
|
80
77
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
81
|
-
reader.read().then(value => finish(resolve, value), error => finish(reject, error));
|
|
78
|
+
reader.read().then(value => { observeSourceRead(reader, value);finish(resolve, value); }, error => { failSourceRead(reader);finish(reject, error); });
|
|
82
79
|
if (signal.aborted) onAbort();
|
|
83
80
|
});
|
|
84
81
|
}
|
|
85
82
|
|
|
86
83
|
// Failure responses only. A stalled body or a stalled cancellation cannot delay
|
|
87
84
|
// the caller beyond the budget. The original request's cancellation wins.
|
|
88
|
-
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact } = {}) {
|
|
85
|
+
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact, onSourceLimit } = {}) {
|
|
89
86
|
if (signal?.aborted) {
|
|
90
|
-
|
|
87
|
+
void cancelSourceResponse(response).catch(() => {});
|
|
91
88
|
signal.throwIfAborted();
|
|
92
89
|
}
|
|
93
90
|
if (!response?.body) return null;
|
|
94
|
-
if (activeReads >= MAX_ACTIVE_READS) {
|
|
91
|
+
if (activeReads >= MAX_ACTIVE_READS) { void cancelSourceResponse(response).catch(() => {});return null; }
|
|
95
92
|
activeReads++;
|
|
96
93
|
const deadline = performance.now() + timeoutMs;
|
|
97
94
|
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -100,7 +97,7 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
|
|
|
100
97
|
try {
|
|
101
98
|
const length = Number(response.headers?.get?.("content-length"));
|
|
102
99
|
if (Number.isFinite(length) && length > maxBytes) return null;
|
|
103
|
-
reader = response
|
|
100
|
+
reader = sourceResponseReader(response);const chunks = [];let bytes = 0;
|
|
104
101
|
while (true) {
|
|
105
102
|
if (performance.now() >= deadline) controller.abort();
|
|
106
103
|
const { done, value } = await readChunk(reader, readSignal);
|
|
@@ -112,6 +109,7 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
|
|
|
112
109
|
}
|
|
113
110
|
const text = Buffer.concat(chunks, bytes).toString("utf8");
|
|
114
111
|
let value;try { value = JSON.parse(text); } catch { value=text; }
|
|
112
|
+
if (response.status === 429) try { onSourceLimit?.(value); } catch { /* Optional classification never alters the public error. */ }
|
|
115
113
|
const reason = missingCallId && isMissingCallIdError(response.status, text)
|
|
116
114
|
? { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." }
|
|
117
115
|
: rootToolSchema && isRootToolSchemaError(response.status, text)
|
|
@@ -127,9 +125,9 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
|
|
|
127
125
|
} finally {
|
|
128
126
|
clearTimeout(timer);
|
|
129
127
|
if (!finished) {
|
|
130
|
-
try { void
|
|
128
|
+
try { void (reader ? cancelSourceReader(reader) : cancelSourceResponse(response)).catch(() => {}); } catch {}
|
|
131
129
|
}
|
|
132
|
-
try { reader
|
|
130
|
+
try { releaseSourceReader(reader); } catch {}
|
|
133
131
|
activeReads--;
|
|
134
132
|
}
|
|
135
133
|
}
|
package/src/service-control.mjs
CHANGED
|
@@ -10,15 +10,29 @@ import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
|
10
10
|
import { settingsPreferencesSnapshot, writeSettingsPreferences } from "./settings-preferences.mjs";
|
|
11
11
|
import { predictionControlSnapshot, controlPrediction } from "./prediction-control.mjs";
|
|
12
12
|
import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
13
|
+
import { createApplicationControl } from "./application-control.mjs";
|
|
14
|
+
import { openCodex, autoLaunchEnabled } from "./launcher.mjs";
|
|
13
15
|
|
|
14
|
-
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
16
|
+
export function createServiceControl({ env = process.env, home, platform = process.platform, providerRuntime, clientIntegration, terminal,
|
|
15
17
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
16
18
|
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
17
|
-
clientVersions,
|
|
19
|
+
clientVersions, applicationControlFactory = createApplicationControl,
|
|
18
20
|
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
19
21
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
20
|
-
const options = { env, home };
|
|
22
|
+
const options = { env, home, platform };
|
|
21
23
|
const imageHostState = createImageHostState();
|
|
24
|
+
const applicationControl = applicationControlFactory({ ...options, providerRuntime, clientIntegration, imageHostState, port: adapterPort, host: adapterHost,
|
|
25
|
+
async openCodexApp() {
|
|
26
|
+
if (platform === "win32") {
|
|
27
|
+
const native = await clientIntegration?.start({ autoSetup: false });
|
|
28
|
+
if (!native?.pacUrl) return null;
|
|
29
|
+
const opened = await openCodex({ env: { ...env, CCDX_AUTO_LAUNCH: "1" }, platform, predictionPacUrl: native.pacUrl,
|
|
30
|
+
predictionApp: native.app, predictionProfile: native.profile, preparePredictionRoute: () => native.prepareRoute?.() });
|
|
31
|
+
return { status: opened ? "opened" : "open_failed" };
|
|
32
|
+
}
|
|
33
|
+
return codexLaunchControl("open", { ...options, intent: "app", configureClient: false, host: adapterHost, port: adapterPort,
|
|
34
|
+
integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] });
|
|
35
|
+
} });
|
|
22
36
|
let serial = Promise.resolve(), lastOperation = null, pending = 0;
|
|
23
37
|
const featureSnapshot = read => { try { return read(options); } catch { return { status: "unavailable" }; } };
|
|
24
38
|
function snapshot() {
|
|
@@ -30,6 +44,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
30
44
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
31
45
|
const localPrivacy = providerRuntime?.privacy?.snapshot();
|
|
32
46
|
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
|
|
47
|
+
applications: applicationControl.snapshot(),
|
|
33
48
|
features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
|
|
34
49
|
decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
|
|
35
50
|
...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
|
|
@@ -41,6 +56,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
41
56
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
42
57
|
state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
|
|
43
58
|
open_webui: { value: saved.open_webui, state: "next_start" },
|
|
59
|
+
codex_auto_launch: { value: env.CCDX_AUTO_LAUNCH ? autoLaunchEnabled(env, options) : saved.codex_auto_launch, state: "next_start", locked: Boolean(env.CCDX_AUTO_LAUNCH) },
|
|
44
60
|
image_enabled: { value: saved.image_enabled && imageConfigured && image.selected_available === true, state: !imageConfigured ? "needs_github_access" : image.selected_available ? "next_call" : "image_model_unavailable", configured: imageConfigured },
|
|
45
61
|
prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
|
|
46
62
|
: prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
|
|
@@ -53,13 +69,18 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
53
69
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
54
70
|
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
|
|
55
71
|
codex_app: ["action", "operation", "intent", "confirmed"],
|
|
72
|
+
application: ["action", "id", "operation", "confirmed", "fresh", "expected_pid", "expected_started"],
|
|
56
73
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
57
74
|
error_capture: ["action", "operation", "source", "model"],
|
|
58
75
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
59
76
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
60
77
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
61
78
|
lastOperation = null;
|
|
62
|
-
if (input.action === "
|
|
79
|
+
if (input.action === "application") {
|
|
80
|
+
if (input.fresh !== undefined && typeof input.fresh !== "boolean") throw new Error("Invalid application check");
|
|
81
|
+
if (input.expected_pid !== undefined && (!Number.isSafeInteger(input.expected_pid) || input.expected_pid <= 0 || !Number.isFinite(Date.parse(input.expected_started)))) throw new Error("Invalid application identity");
|
|
82
|
+
lastOperation = { feature: "application", result: await applicationControl.action(input) };
|
|
83
|
+
} else if (input.action === "error_capture") {
|
|
63
84
|
if (!providerRuntime?.captureUpstreamError) throw new Error("This service cannot capture upstream errors.");
|
|
64
85
|
lastOperation = { feature: "error_capture", result: providerRuntime.captureUpstreamError(input) };
|
|
65
86
|
} else if (input.action === "codex_app") {
|
|
@@ -92,6 +113,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
92
113
|
} else if (input.action === "nightly_update") {
|
|
93
114
|
writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
|
|
94
115
|
} else if (input.action === "preference") {
|
|
116
|
+
if (input.key === "codex_auto_launch" && env.CCDX_AUTO_LAUNCH) throw new Error("Automatic Codex launch is controlled by CCDX_AUTO_LAUNCH");
|
|
95
117
|
if (input.key === "prediction_enabled") await predictionControl(input.value ? "enable" : "disable", { ...options, integration: clientIntegration });
|
|
96
118
|
else writeServicePreference(input.key, input.value, options);
|
|
97
119
|
terminal?.apply?.({ ...servicePreferences(options) });
|
|
@@ -119,7 +141,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
119
141
|
}
|
|
120
142
|
return snapshot();
|
|
121
143
|
}
|
|
122
|
-
return { snapshot, busy: () => pending > 0
|
|
144
|
+
return { snapshot, applicationControl, busy: () => pending > 0 || applicationControl.busy?.() === true,
|
|
145
|
+
async inspectApplication(id, fresh = false) { await applicationControl.check(id, fresh);return snapshot(); },
|
|
146
|
+
action(input) {
|
|
123
147
|
if (input?.action === "client_versions") {
|
|
124
148
|
if (Object.keys(input).some(key => key !== "action")) return Promise.reject(new Error("Unknown setting action or field"));
|
|
125
149
|
if (clientVersions?.refresh) void Promise.resolve().then(() => clientVersions.refresh()).catch(() => {});
|
|
@@ -9,7 +9,7 @@ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-
|
|
|
9
9
|
import { withFileLockSync } from "./lock.mjs";
|
|
10
10
|
|
|
11
11
|
export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
|
|
12
|
-
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true });
|
|
12
|
+
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, codex_auto_launch: false });
|
|
13
13
|
const keys = Object.keys(SETTINGS_DEFAULTS);
|
|
14
14
|
const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
|
|
15
15
|
const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
@@ -30,8 +30,8 @@ function readBackup(options) {
|
|
|
30
30
|
const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
|
|
31
31
|
if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
|
|
32
32
|
|| Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
|
|
33
|
-
|| keys.filter(key => !key.startsWith("privacy_") &&
|
|
34
|
-
value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, ...value.values };
|
|
33
|
+
|| keys.filter(key => !key.startsWith("privacy_") && !["context_compaction_enabled", "codex_auto_launch"].includes(key)).some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
34
|
+
value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, codex_auto_launch: false, ...value.values };
|
|
35
35
|
checkedPreferenceValues(value.values);return value;
|
|
36
36
|
} catch (error) {
|
|
37
37
|
if (error.code === "ENOENT") return null;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createSourceAdmission } from "./source-admission.mjs";
|
|
3
|
+
import { userSettingsPath } from "./user-settings.mjs";
|
|
4
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
|
+
import { atomicWriteFile } from "./atomic-file.mjs";
|
|
6
|
+
|
|
7
|
+
export function createRuntimeSourceAdmission({ persistSourceState = false, ...options } = {}) {
|
|
8
|
+
if (!persistSourceState) return createSourceAdmission();
|
|
9
|
+
const file = path.join(path.dirname(userSettingsPath(options)), "source-capacity.json");
|
|
10
|
+
let learned = {}, dirty = false, timer, writing = Promise.resolve();
|
|
11
|
+
try {
|
|
12
|
+
const saved = JSON.parse(readBoundedFileSync(file, { maxBytes: 16384, encoding: "utf8" }));
|
|
13
|
+
if (saved.version === 1 && saved.entries && Object.keys(saved.entries).length <= 64) learned = Object.fromEntries(Object.entries(saved.entries)
|
|
14
|
+
.filter(([key, value]) => /^[a-f0-9]{64}$/.test(key) && Number.isSafeInteger(value.limit) && value.limit > 0 && value.limit <= 128 && Number.isFinite(value.at)));
|
|
15
|
+
} catch { /* Disposable capacity metadata is relearned; source configuration is never rewritten. */ }
|
|
16
|
+
const flush = () => {
|
|
17
|
+
clearTimeout(timer);timer = null;
|
|
18
|
+
if (!dirty) return writing;
|
|
19
|
+
dirty = false;const text = JSON.stringify({ version: 1, entries: learned }) + "\n";
|
|
20
|
+
writing = writing.catch(() => {}).then(() => atomicWriteFile(file, text)).catch(() => {});
|
|
21
|
+
return writing;
|
|
22
|
+
};
|
|
23
|
+
const scheduler = createSourceAdmission({ learned, onStable(key, limit) {
|
|
24
|
+
delete learned[key];learned[key] = { limit, at: Date.now() };
|
|
25
|
+
while (Object.keys(learned).length > 64) delete learned[Object.keys(learned)[0]];
|
|
26
|
+
dirty = true;if (!timer) { timer = setTimeout(flush, 1000);timer.unref?.(); }
|
|
27
|
+
} });
|
|
28
|
+
return { ...scheduler, async close() { scheduler.close();await flush(); } };
|
|
29
|
+
}
|