codex-copilot-dx 1.4.3 → 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 +4 -1
- package/bin/cli.mjs +5 -4
- package/docs/ARCHITECTURE.md +20 -0
- package/docs/REFERENCE.md +42 -8
- package/package.json +1 -1
- package/src/access-settings.mjs +5 -2
- package/src/adapter.mjs +9 -1
- package/src/antigravity-chat-bridge.mjs +4 -2
- package/src/antigravity-handler.mjs +51 -24
- 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 +30 -17
- package/src/cli-command-spec.mjs +7 -4
- package/src/cli-management.mjs +37 -4
- package/src/client-effort.mjs +28 -0
- package/src/client-model-plan.mjs +2 -1
- 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 +9 -1
- package/src/connection-routing.mjs +8 -2
- package/src/connection-runtime.mjs +21 -5
- package/src/connection-view.mjs +12 -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 +71 -18
- package/src/dashboard/console.js +19 -9
- package/src/dashboard/gemini.js +8 -5
- package/src/dashboard/index.html +17 -0
- package/src/dashboard/language.js +45 -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 +6 -3
- 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/dashboard/index.html
CHANGED
|
@@ -38,8 +38,17 @@
|
|
|
38
38
|
<section class="intro">
|
|
39
39
|
<h1><span id="page-title" data-i18n="overview">Overview</span></h1>
|
|
40
40
|
<p id="page-settings-note" class="hint" role="status"></p>
|
|
41
|
+
<div id="application-launch" hidden>
|
|
42
|
+
<button type="button" id="application-open"><span aria-hidden="true">↗</span><span id="application-open-label" data-i18n="application_open">Open app</span></button>
|
|
43
|
+
<span id="application-state" class="hint" role="status" aria-live="polite"></span>
|
|
44
|
+
</div>
|
|
41
45
|
<div id="preferences-status" class="preferences-status" role="status" aria-live="polite" hidden></div>
|
|
42
46
|
</section>
|
|
47
|
+
<div id="application-reopen-confirm" class="section-actions" hidden>
|
|
48
|
+
<span data-i18n="application_reopen_warning">Reopening may interrupt current tasks.</span>
|
|
49
|
+
<button type="button" id="application-reopen-cancel" data-i18n="cancel">Cancel</button>
|
|
50
|
+
<button type="button" id="application-reopen-apply" data-i18n="application_reopen">Reopen</button>
|
|
51
|
+
</div>
|
|
43
52
|
|
|
44
53
|
|
|
45
54
|
<div data-view="overview">
|
|
@@ -54,6 +63,7 @@
|
|
|
54
63
|
<section class="panel dashboard-section"><h2 data-i18n="this_run_usage">THIS RUN</h2><p id="runtime-usage" class="table-note"></p><p class="table-note"><span data-i18n="approx_cache_hit_rate">Approx. cache hit rate</span>: <strong id="runtime-cache-hit" data-i18n-title="runtime_cache_hit_basis" title="Reused / input tokens from records with valid counts for both. ~ Partial coverage. — No valid input basis.">—</strong></p><p class="hint" data-i18n="updated_from_returned_usage_not_a_live_bill_pending_usage_is_not">Counts returned usage only. Pending usage is not included. This is not a live bill.</p></section>
|
|
55
64
|
</div>
|
|
56
65
|
<div data-view="codex" hidden>
|
|
66
|
+
<div class="setting-row" id="codex-auto-launch-row"><label for="codex-auto-launch" data-i18n="codex_auto_launch">Open Codex when CCDX starts</label><input id="codex-auto-launch" type="checkbox" role="switch"><span id="codex-auto-launch-note" class="hint" data-i18n="next_ccdx_start">Next CCDX start.</span></div>
|
|
57
67
|
<div id="codex-model-management"> <section class="connection-access" id="connection-clients">
|
|
58
68
|
<div id="connection-client-list"></div>
|
|
59
69
|
<details id="connection-disabled-clients" class="connection-disabled" hidden><summary data-i18n="api_disabled_clients">Disabled clients</summary><div id="connection-disabled-client-list"></div></details>
|
|
@@ -69,6 +79,7 @@
|
|
|
69
79
|
<p id="connection-setup-state" class="client-sync-state" role="status" aria-live="polite"></p>
|
|
70
80
|
<p id="connection-capability-state" class="hint" hidden></p>
|
|
71
81
|
<div class="table-wrap"><table class="binding-table"><thead><tr><th data-i18n="model">Model</th><th data-i18n="source">Source</th><th data-i18n="cap_context">Context</th><th data-i18n="cap_reasoning">Reasoning</th><th data-i18n="cap_default">Default</th></tr></thead><tbody id="connection-bindings"></tbody></table></div>
|
|
82
|
+
<p id="connection-effort-note" class="hint" data-i18n="cap_effort_scope" hidden>Used only when the app omits a reasoning level.</p>
|
|
72
83
|
<div class="setting-row"><label for="connection-auto-sync" data-i18n="cap_auto_sync">Sync model settings</label><input id="connection-auto-sync" type="checkbox" role="switch" checked><span class="hint" data-i18n="cap_sync_scope">Preserves your manual settings.</span></div>
|
|
73
84
|
<div class="section-actions"><button type="submit" data-i18n="api_save">Save</button><button type="button" id="connection-client-cancel" data-i18n="cap_discard_changes">Discard changes</button><button type="button" id="connection-sync-preview" data-i18n="cap_sync_preview">Review sync</button></div>
|
|
74
85
|
<p id="connection-client-note" class="hint" role="status" aria-live="polite"></p>
|
|
@@ -268,6 +279,12 @@
|
|
|
268
279
|
<div class="section-actions"><button id="source-access-save" type="submit" data-i18n="api_save" disabled>Save</button><button id="source-access-cancel" type="button" data-i18n="cap_discard_changes" disabled>Discard changes</button></div>
|
|
269
280
|
<p id="source-access-note" class="hint" role="status" aria-live="polite"></p>
|
|
270
281
|
</form>
|
|
282
|
+
<details class="tool-details" id="source-concurrency"><summary data-i18n="source_concurrency">Concurrency · Auto</summary>
|
|
283
|
+
<form id="source-limit-form"><div class="connection-fields"><label><span data-i18n="source_concurrency_maximum">Maximum concurrency</span><input id="source-limit-maximum" type="number" min="1" max="128" step="1" inputmode="numeric" placeholder="Auto" data-i18n-placeholder="source_concurrency_auto"></label></div>
|
|
284
|
+
<p class="hint" data-i18n="source_concurrency_hint">Leave blank for Auto. A value only sets its ceiling.</p>
|
|
285
|
+
<div class="section-actions"><button id="source-limit-save" type="submit" data-i18n="api_save" disabled>Save</button></div><p id="source-limit-note" class="hint" role="status" aria-live="polite"></p>
|
|
286
|
+
</form>
|
|
287
|
+
</details>
|
|
271
288
|
</section>
|
|
272
289
|
<details class="panel dashboard-section model-catalog" id="upstream-models" open>
|
|
273
290
|
<summary class="panel-heading"><h2 data-i18n="model_catalog">MODEL LIST</h2><span id="models-state" role="status" aria-live="polite" data-i18n="checking_live">CHECKING</span></summary>
|
|
@@ -365,6 +365,42 @@
|
|
|
365
365
|
"cap_visible_model": ["Available models", "可用模型"],
|
|
366
366
|
"cap_context": ["Context", "上下文"],
|
|
367
367
|
"cap_reasoning": ["Reasoning", "推理"],
|
|
368
|
+
"cap_effort_follow": ["Follow app", "跟随应用"],
|
|
369
|
+
"application_open": ["Open app", "打开应用"],
|
|
370
|
+
"application_focus": ["Switch to app", "切换到应用"],
|
|
371
|
+
"application_reopen": ["Reopen", "重新打开"],
|
|
372
|
+
"application_check": ["Check state", "检查状态"],
|
|
373
|
+
"application_opening": ["Opening…", "正在打开…"],
|
|
374
|
+
"application_connected": ["Connected", "已接入"],
|
|
375
|
+
"application_pending": ["Connection unconfirmed", "接入待确认"],
|
|
376
|
+
"application_stopped": ["Not running", "未运行"],
|
|
377
|
+
"application_unknown": ["App state unconfirmed", "应用状态待确认"],
|
|
378
|
+
"application_not_installed": ["Not installed", "未安装"],
|
|
379
|
+
"application_unsupported": ["Unavailable on this platform", "当前平台暂不支持"],
|
|
380
|
+
"application_multiple": ["Multiple app processes found", "检测到多个应用进程"],
|
|
381
|
+
"application_reload_pending": ["Configuration pending load", "配置待加载"],
|
|
382
|
+
"application_reopen_warning": ["Reopening may interrupt current tasks.", "重新打开可能中断当前任务。"],
|
|
383
|
+
"application_action_failed": ["Could not open the app. Check its state and retry.", "未能打开应用,请检查状态后重试。"],
|
|
384
|
+
"application_action_open_failed": ["Could not open the app.", "未能打开应用。"],
|
|
385
|
+
"application_action_focus_unavailable": ["Could not switch to the running app.", "无法切换到运行中的应用。"],
|
|
386
|
+
"application_action_quit_refused": ["The app did not accept the quit request.", "应用未接受退出请求。"],
|
|
387
|
+
"application_action_quit_timeout": ["Finish tasks and quit the app manually, then open it here.", "请完成任务并手动退出应用,再从这里打开。"],
|
|
388
|
+
"application_action_app_changed": ["The app process changed. Check its state again.", "应用进程已变化,请重新检查。"],
|
|
389
|
+
"application_action_needs_app_relaunch": ["Reopen the app to load the configuration.", "重新打开应用以加载配置。"],
|
|
390
|
+
"application_action_route_conflict": ["Existing routing was preserved. Check the app configuration.", "已有路由已保留,请检查应用配置。"],
|
|
391
|
+
"codex_auto_launch": ["Open Codex when CCDX starts", "启动 CCDX 时打开 Codex"],
|
|
392
|
+
"application_preference_failed": ["Not saved. Try again.", "未保存,请重试。"],
|
|
393
|
+
"source_concurrency": ["Concurrency · Auto", "并发 · 自动"],
|
|
394
|
+
"source_concurrency_auto": ["Auto", "自动"],
|
|
395
|
+
"source_concurrency_maximum": ["Maximum concurrency", "最大并发"],
|
|
396
|
+
"source_concurrency_hint": ["Leave blank for Auto. A value only sets its ceiling.", "留空自动调节,填写数值仅设上限。"],
|
|
397
|
+
"ccdx_source_queue_full": ["The source is busy; its waiting queue is full.", "来源繁忙,等待队列已满。"],
|
|
398
|
+
"ccdx_source_queue_timeout": ["Waiting for the source timed out.", "等待来源超时。"],
|
|
399
|
+
"ccdx_source_limited": ["The source is limited. Retry after its recovery time.", "来源限流,请在恢复后重试。"],
|
|
400
|
+
"ccdx_source_limit_invalid": ["Choose Auto or a maximum from 1 to 128.", "请选择自动,或设置 1~128 的上限。"],
|
|
401
|
+
"cap_effort_scope": ["Used only when the app omits a reasoning level.", "应用未指定档位时生效。"],
|
|
402
|
+
"cap_effort_unavailable": ["{effort} (unavailable)", "{effort}(已不可用)"],
|
|
403
|
+
"ccdx_client_effort_unavailable": ["The saved reasoning level is unavailable. Choose a declared level or follow the app.", "已保存的推理档位不可用,请选择支持的档位或跟随应用。"],
|
|
368
404
|
"cap_search": ["Search", "联网搜索"],
|
|
369
405
|
"cap_default": ["Default", "默认"],
|
|
370
406
|
"cap_set_default": ["Set default", "设为默认"],
|
|
@@ -390,6 +426,15 @@
|
|
|
390
426
|
"cap_details_draft": ["Details updated. Save the source to apply.", "能力已加入草稿,请保存来源。"],
|
|
391
427
|
"cap_preview_scope": ["Save to apply. Restart Claude after its settings change.", "保存后同步;Claude 配置更新后需重启。"],
|
|
392
428
|
"import_source": ["Import", "导入"],
|
|
429
|
+
"import_file": ["Choose file", "选择文件"],
|
|
430
|
+
"import_discovery_not_found": ["No configuration found. You can import an exported file.", "未找到配置,可使用导出文件导入。"],
|
|
431
|
+
"import_discovery_empty": ["No supported API configuration found.", "没有可直接导入的 API 配置。"],
|
|
432
|
+
"import_discovery_busy": ["Configuration is busy. Try again later or import a file.", "配置正忙,请稍后重试或使用文件导入。"],
|
|
433
|
+
"import_discovery_unreadable": ["Could not read configuration. Existing settings were kept.", "无法读取配置,已有设置已保留。"],
|
|
434
|
+
"import_discovery_unsupported": ["Unsupported configuration format. Use an exported JSON file.", "配置格式暂不支持,请使用导出的 JSON 文件。"],
|
|
435
|
+
"import_discovery_skipped": ["Some configurations need manual review and were skipped.", "已跳过需手动核对的配置。"],
|
|
436
|
+
"import_discovery_truncated": ["Results are limited. Import a file for other configurations.", "列表已限量,其余配置可使用文件导入。"],
|
|
437
|
+
"ccdx_import_discovery_invalid": ["Choose CC Switch or Magpie, or import a JSON file.", "请选择 CC Switch、Magpie,或导入 JSON 文件。"],
|
|
393
438
|
"import_preview": ["Import preview", "导入预览"],
|
|
394
439
|
"import_review": ["Review draft", "检查草稿"],
|
|
395
440
|
"import_scope": ["API metadata only. Configure the key before saving; client access is granted separately.", "只导入 API 元数据。保存前配置密钥,应用权限另行设置。"],
|
package/src/dashboard/ui.css
CHANGED
|
@@ -38,6 +38,15 @@ button[aria-busy="true"] { cursor: progress; }
|
|
|
38
38
|
h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spacing: -.035em; }
|
|
39
39
|
.status-icon { display: block; grid-row: 1 / 3; width: 44px; height: 44px; color: var(--accent); }
|
|
40
40
|
.intro p { margin: 0; color: var(--subtle); font-size: 11px; }
|
|
41
|
+
.intro.has-application-launch { align-items:center; flex-wrap:wrap; }
|
|
42
|
+
.intro.has-application-launch #page-settings-note { order:3; flex-basis:100%; }
|
|
43
|
+
.intro.has-application-launch #page-settings-note:empty { display:none; }
|
|
44
|
+
#application-launch { display:flex; flex-direction:column; align-items:flex-end; gap:5px; margin-left:auto; }
|
|
45
|
+
#application-open { min-width:116px; display:inline-flex; align-items:center; justify-content:center; gap:8px; }
|
|
46
|
+
#application-state { margin:0; min-height:18px; }
|
|
47
|
+
#application-reopen-confirm { justify-content:flex-end; flex-wrap:wrap; margin:0 0 18px; }
|
|
48
|
+
#application-reopen-confirm > span { flex:1 1 200px; }
|
|
49
|
+
#codex-auto-launch-row { margin-bottom:18px; }
|
|
41
50
|
.snapshot-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: baseline; gap: 8px 18px; min-width: 0; }
|
|
42
51
|
.intro .snapshot-meta p { margin: 0; overflow-wrap: anywhere; }
|
|
43
52
|
.overview { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 11px; }
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -248,7 +248,12 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
248
248
|
if (pathname === "/_ccdx/ui/settings") {
|
|
249
249
|
if (!serviceControl) { sendJson(res, 503, { error: "Settings require the running service; restart the updated CCDX" });return; }
|
|
250
250
|
if (req.method === "GET") {
|
|
251
|
-
try {
|
|
251
|
+
try {
|
|
252
|
+
const query = new URL(req.url, "http://localhost").searchParams, app = query.get("application");
|
|
253
|
+
if (app && !["codex", "claude_app", "antigravity"].includes(app)) { sendJson(res, 400, { error: "Unknown application" });return; }
|
|
254
|
+
const data = app && serviceControl.inspectApplication ? await serviceControl.inspectApplication(app, query.get("fresh") === "1") : serviceControl.snapshot();
|
|
255
|
+
sendJson(res, 200, data);
|
|
256
|
+
} catch { sendJson(res, 409, { error: "Service settings are unreadable; existing settings were preserved" }); }
|
|
252
257
|
return;
|
|
253
258
|
}
|
|
254
259
|
if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
|
package/src/dashboard.mjs
CHANGED
|
@@ -25,6 +25,7 @@ const ASSETS = new Map([
|
|
|
25
25
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
26
26
|
["/preferences.js", ["./dashboard/preferences.js", "text/javascript; charset=utf-8"]],
|
|
27
27
|
["/features.js", ["./dashboard/features.js", "text/javascript; charset=utf-8"]],
|
|
28
|
+
["/applications.js", ["./dashboard/applications.js", "text/javascript; charset=utf-8"]],
|
|
28
29
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
29
30
|
["/tools.js", ["./dashboard/tools.js", "text/javascript; charset=utf-8"]],
|
|
30
31
|
["/connections.js", ["./dashboard/connections.js", "text/javascript; charset=utf-8"]],
|
package/src/gemini-app.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
3
4
|
import {execFile} from "node:child_process";
|
|
4
5
|
import {promisify} from "node:util";
|
|
5
6
|
|
|
@@ -23,9 +24,9 @@ export async function inspectGeminiApp({platform=process.platform,app="/Applicat
|
|
|
23
24
|
|
|
24
25
|
// A launch plan is reviewable without changing files, credentials, or running apps.
|
|
25
26
|
// A prepared environment is not evidence that the App has adopted the route.
|
|
26
|
-
export function planGeminiAppLaunch(state,{cloudCodeUrl,env=process.env,managedGateway=false}={}) {
|
|
27
|
+
export function planGeminiAppLaunch(state,{cloudCodeUrl,env=process.env,home=os.homedir(),managedGateway=false}={}) {
|
|
27
28
|
if(!["running","stopped","multiple"].includes(state?.status))return {status:state?.status||"unknown"};
|
|
28
|
-
if(state.status==="stopped"
|
|
29
|
+
if(state.status==="stopped"&&!["/Applications/Gemini.app",path.join(home,"Applications/Gemini.app")].includes(state.app))throw new Error("Unrecognized Gemini App location");
|
|
29
30
|
const url=new URL(cloudCodeUrl);
|
|
30
31
|
if(url.protocol!=="http:"||url.hostname!=="127.0.0.1"||!url.port||Number(url.port)<1||url.username||url.password||url.search||url.hash)throw new Error("Gemini route must use a local CCDX endpoint");
|
|
31
32
|
if(managedGateway||Object.entries(env).some(([key,value])=>key.startsWith("AGY_LLM_GATEWAY_")&&value)||env.CLOUD_CODE_URL&&env.CLOUD_CODE_URL!==url.href)return {status:"route_conflict"};
|
package/src/http-transport.mjs
CHANGED
|
@@ -99,7 +99,7 @@ async function readRequestBuffer(req, maxBytes, signal) {
|
|
|
99
99
|
return Buffer.concat(chunks);
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal) {
|
|
102
|
+
async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, onBytes) {
|
|
103
103
|
const contentLength = requestContentLength(req);
|
|
104
104
|
if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
|
|
105
105
|
throw payloadTooLarge("Raw", maxBodyBytes);
|
|
@@ -138,6 +138,7 @@ async function readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal)
|
|
|
138
138
|
}
|
|
139
139
|
},
|
|
140
140
|
});
|
|
141
|
+
onBytes?.(total);
|
|
141
142
|
if (preallocatedLength) {
|
|
142
143
|
if (!allocated) return "";
|
|
143
144
|
return new TextDecoder().decode(overflow ? Buffer.concat(overflow, total) : allocated.subarray(0, total));
|
|
@@ -198,9 +199,10 @@ export async function readJsonBody(req, {
|
|
|
198
199
|
if (signal?.aborted) throw admissionAbortError(signal);
|
|
199
200
|
const encodings = contentEncodings(req.headers?.["content-encoding"]);
|
|
200
201
|
if (encodings.every((encoding) => encoding === "identity")) {
|
|
201
|
-
return parse(await readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal));
|
|
202
|
+
return parse(await readIdentityText(req, maxBodyBytes, maxDecodedBodyBytes, signal, bytes => admission?.resize?.(bytes)));
|
|
202
203
|
}
|
|
203
204
|
const buffer = await readRequestBuffer(req, maxBodyBytes, signal);
|
|
205
|
+
admission?.resize?.(buffer.length);
|
|
204
206
|
let releaseDecompression = () => {};
|
|
205
207
|
let decodedReservation;
|
|
206
208
|
let retainDecodedReservation = false;
|
|
@@ -272,6 +274,7 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
|
|
|
272
274
|
context?.onHttpError?.({ code: err?.code || err?.jsonBody?.error?.code,
|
|
273
275
|
origin: context.errorOrigin || (statusCode < 500 ? "client_validation" : "local_transport") });
|
|
274
276
|
const headers = { "Content-Type": "application/json" };
|
|
277
|
+
if (Number.isFinite(err?.retryAfterMs) && err.retryAfterMs > 0) headers["Retry-After"] = String(Math.ceil(err.retryAfterMs / 1000));
|
|
275
278
|
if (err?.origin === "privacy" && Number.isInteger(err.retryAfter) && err.retryAfter > 0) headers["Retry-After"] = String(err.retryAfter);
|
|
276
279
|
if (statusCode === 408 || statusCode === 413) headers.Connection = "close";
|
|
277
280
|
res.writeHead(statusCode, headers);
|
|
@@ -324,7 +327,7 @@ export function isAbortLikeError(err) {
|
|
|
324
327
|
|
|
325
328
|
export function abortErrorStatusCode(reason) {
|
|
326
329
|
if (reason === "request_body_timeout") return 408;
|
|
327
|
-
if (["responses_prepare_timeout", "messages_prepare_timeout", "upstream_timeout", "stream_handshake_timeout", "stream_idle_timeout"].includes(reason)) return 504;
|
|
330
|
+
if (["responses_prepare_timeout", "messages_prepare_timeout", "upstream_timeout", "stream_handshake_timeout", "stream_idle_timeout", "compaction_idle_timeout"].includes(reason)) return 504;
|
|
328
331
|
if (reason === "client_aborted" || reason === "client_closed") return 499;
|
|
329
332
|
return 502;
|
|
330
333
|
}
|
package/src/launcher.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { installedWindowsPredictionApp, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
|
|
5
5
|
import { status } from "./status.mjs";
|
|
6
6
|
import { isPredictionPacUrl } from "./prediction-pac.mjs";
|
|
7
|
+
import { readUserSettings } from "./user-settings.mjs";
|
|
7
8
|
|
|
8
9
|
export { ensureAuth } from "./auth.mjs";
|
|
9
10
|
|
|
@@ -14,9 +15,9 @@ const APP_PATH_CANDIDATES = [
|
|
|
14
15
|
"/Applications/ChatGPT.app",
|
|
15
16
|
];
|
|
16
17
|
|
|
17
|
-
export function autoLaunchEnabled(env = process.env) {
|
|
18
|
+
export function autoLaunchEnabled(env = process.env, options = {}) {
|
|
18
19
|
const raw = env.CCDX_AUTO_LAUNCH;
|
|
19
|
-
if (raw === undefined || raw === "") return true;
|
|
20
|
+
if (raw === undefined || raw === "") return readUserSettings({ ...options, env, strict: true }).codex_auto_launch === true;
|
|
20
21
|
return !/^(0|false|no|off)$/i.test(String(raw).trim());
|
|
21
22
|
}
|
|
22
23
|
|
|
@@ -88,7 +89,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
88
89
|
if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
|
|
89
90
|
onPredictionRoute("persisted");log(status("info", "Codex already running"));return true;
|
|
90
91
|
}
|
|
91
|
-
throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then
|
|
92
|
+
throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then open it from its CCDX page; no process was stopped");
|
|
92
93
|
}
|
|
93
94
|
await preparePredictionRoute?.();
|
|
94
95
|
const launched = await new Promise(resolve => {
|
|
@@ -120,7 +121,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
120
121
|
}
|
|
121
122
|
|
|
122
123
|
if (!autoLaunchEnabled(env)) {
|
|
123
|
-
log(status("info", "Auto-open is off. Open Codex
|
|
124
|
+
log(status("info", "Auto-open is off. Open Codex from its Web UI page."));
|
|
124
125
|
return false;
|
|
125
126
|
}
|
|
126
127
|
|
|
@@ -143,7 +144,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
143
144
|
if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
|
|
144
145
|
onPredictionRoute("persisted");log(status("info", "Codex already running"));return true;
|
|
145
146
|
}
|
|
146
|
-
throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then
|
|
147
|
+
throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then open it from its CCDX page; no process was stopped");
|
|
147
148
|
}
|
|
148
149
|
await preparePredictionRoute?.();
|
|
149
150
|
if (!await tryOpen([predictionApp, ...imageArgs, ...extraArgs], { spawnImpl })) {
|
package/src/native-images.mjs
CHANGED
|
@@ -86,7 +86,7 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
86
86
|
const context = currentRequestContext();
|
|
87
87
|
if (context) { context.provider = "github";context.streamPerformance?.setProvider?.("github"); }
|
|
88
88
|
abort.setTimeout(timeoutMs);
|
|
89
|
-
const forward = input => client.images(operation, { ...body, prompt: input.input }, { signal: abort.signal });
|
|
89
|
+
const forward = input => client.images(operation, { ...body, prompt: input.input }, { signal: abort.signal, sourceBodyManaged: true });
|
|
90
90
|
const call = privacy?.wrap ? privacy.wrap(forward, { res, protocol: "responses", client: "codex" }) : forward;
|
|
91
91
|
const response = await call({ input: body.prompt }, { signal: abort.signal });
|
|
92
92
|
if (!response.ok) {
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -19,6 +19,9 @@ import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
|
|
|
19
19
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
20
20
|
import { M365_API_HOST } from "./providers/m365-endpoint.mjs";
|
|
21
21
|
import { m365CatalogDiagnostic, m365CatalogMessage } from "./providers/m365-catalog-diagnostic.mjs";
|
|
22
|
+
import { admittedSource } from "./source-admission.mjs";
|
|
23
|
+
import { createRuntimeSourceAdmission } from "./source-admission-state.mjs";
|
|
24
|
+
import { createApplicationEvidence } from "./application-evidence.mjs";
|
|
22
25
|
|
|
23
26
|
const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
|
|
24
27
|
{ code: reason, statusCode: 503 });
|
|
@@ -27,6 +30,8 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
|
|
|
27
30
|
// image configuration or each other's credentials.
|
|
28
31
|
export function createProviderRuntime(options = {}) {
|
|
29
32
|
options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
|
|
33
|
+
options.sourceAdmission ||= createRuntimeSourceAdmission(options);
|
|
34
|
+
options.applicationEvidence ||= createApplicationEvidence();
|
|
30
35
|
const compaction = options.compaction || createContextCompactionService({ enabled() { try { return servicePreferences(options).context_compaction_enabled; } catch { return false; } } });
|
|
31
36
|
let connections;
|
|
32
37
|
const legacy = createBuiltinProviderRuntime({ ...options, compaction, managedClaude: () => connections?.managesClaude() !== false,
|
|
@@ -37,10 +42,10 @@ export function createProviderRuntime(options = {}) {
|
|
|
37
42
|
|
|
38
43
|
function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGithubCatalog, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
|
|
39
44
|
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
40
|
-
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration, privacy, compaction } = {}) {
|
|
41
|
-
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
45
|
+
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration, privacy, compaction, sourceAdmission, applicationEvidence } = {}) {
|
|
46
|
+
const options = { home, env, platform }, github = admittedSource({ ...createGithubProvider({ client: githubClient,
|
|
42
47
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
43
|
-
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
48
|
+
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry }, sourceAdmission);
|
|
44
49
|
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
45
50
|
let reason = null, claudeReason = null, lastClients = {};
|
|
46
51
|
let changingAccount = false;
|
|
@@ -76,10 +81,10 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
|
|
|
76
81
|
if (!m365) {
|
|
77
82
|
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
78
83
|
if (closed || !enabled) return null;
|
|
79
|
-
m365 = factory({ home, env, log, onCatalog() {
|
|
84
|
+
m365 = admittedSource(factory({ home, env, log, onCatalog() {
|
|
80
85
|
// Reconcile after refresh, outside inference serialization and without a watcher.
|
|
81
86
|
setImmediate(() => { if (!pending && gateway && !closed && enabled) void syncClaudeClients(); });
|
|
82
|
-
} });
|
|
87
|
+
} }), sourceAdmission);
|
|
83
88
|
sources.set(m365.id, m365);
|
|
84
89
|
}
|
|
85
90
|
await m365.refresh();if (closed || !enabled) return null;
|
|
@@ -90,7 +95,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
|
|
|
90
95
|
if (!gateway) {
|
|
91
96
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
92
97
|
const opened = await start({ privacy, compaction, provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
|
|
93
|
-
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
98
|
+
onRequest({ client }, req) { lastClients[client] = new Date().toISOString();applicationEvidence?.accept(req, "claude_app", "inference"); } });
|
|
94
99
|
if (closed || !enabled) { await opened.close();return null; }
|
|
95
100
|
gateway = opened;
|
|
96
101
|
}
|
|
@@ -149,15 +154,15 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
|
|
|
149
154
|
if (!chosen) throw Object.assign(new Error("Account list changed. Check again and select an available account."), { code: "m365_account_selection_stale", statusCode: 409 });
|
|
150
155
|
const switched = discovered.binding && m365AccountKey(discovered.binding) !== m365AccountKey(chosen);
|
|
151
156
|
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
152
|
-
candidate = factory({ home, env, log, persist: false,
|
|
157
|
+
candidate = admittedSource(factory({ home, env, log, persist: false,
|
|
153
158
|
account: { ...chosen, selection_source: "manual", ...(switched || discovered.binding?.history_isolation ? { history_isolation: true } : {}) },
|
|
154
|
-
onCatalog() { if (candidate === m365 && !closed) setImmediate(() => { if (candidate === m365 && !closed) void syncClaudeClients(); }); } });
|
|
159
|
+
onCatalog() { if (candidate === m365 && !closed) setImmediate(() => { if (candidate === m365 && !closed) void syncClaudeClients(); }); } }), sourceAdmission);
|
|
155
160
|
await candidate.refresh();
|
|
156
161
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
157
162
|
if (candidate.models("claude").length) {
|
|
158
163
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
159
164
|
opened = await start({ privacy, compaction, provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
|
|
160
|
-
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
165
|
+
onRequest({ client }, req) { lastClients[client] = new Date().toISOString();applicationEvidence?.accept(req, "claude_app", "inference"); } });
|
|
161
166
|
}
|
|
162
167
|
candidate.commitSelection(discovered.binding);
|
|
163
168
|
const previous = m365, previousGateway = gateway;
|
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,
|