codex-copilot-dx 1.2.12 → 1.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +14 -14
  2. package/bin/cli.mjs +12 -8
  3. package/docs/ARCHITECTURE.md +54 -5
  4. package/docs/REFERENCE.md +91 -1
  5. package/package.json +2 -2
  6. package/src/access-settings.mjs +98 -0
  7. package/src/adapter.mjs +19 -7
  8. package/src/api-secrets.mjs +69 -0
  9. package/src/auto-review-model.mjs +4 -3
  10. package/src/claude-client-config.mjs +16 -11
  11. package/src/claude-gateway.mjs +11 -8
  12. package/src/cli-m365.mjs +48 -8
  13. package/src/cli-models.mjs +2 -1
  14. package/src/cli-options.mjs +1 -1
  15. package/src/cli-status.mjs +1 -1
  16. package/src/client-gateway-keys.mjs +29 -0
  17. package/src/codex-api-config.mjs +51 -0
  18. package/src/connection-runtime.mjs +289 -0
  19. package/src/conversation-source-guard.mjs +42 -0
  20. package/src/dashboard/connections.js +182 -0
  21. package/src/dashboard/console.js +6 -4
  22. package/src/dashboard/flow.js +4 -4
  23. package/src/dashboard/index.html +43 -0
  24. package/src/dashboard/language.js +85 -2
  25. package/src/dashboard/status.js +1 -1
  26. package/src/dashboard/ui.css +24 -0
  27. package/src/dashboard/ui.js +4 -2
  28. package/src/dashboard-api.mjs +19 -4
  29. package/src/dashboard.mjs +1 -0
  30. package/src/optional-routes.mjs +2 -2
  31. package/src/private-helper-environment.mjs +7 -0
  32. package/src/provider-management.mjs +1 -1
  33. package/src/provider-runtime.mjs +37 -5
  34. package/src/providers/api-network.mjs +51 -0
  35. package/src/providers/api.mjs +129 -0
  36. package/src/proxy-tunnel.mjs +6 -4
  37. package/src/responses-handler.mjs +6 -4
  38. package/src/startup-ui.mjs +9 -0
  39. package/src/stream-performance.mjs +7 -6
  40. package/src/terminal-console.mjs +1 -1
  41. package/src/usage-store.mjs +1 -1
  42. package/src/windows-http-network.mjs +11 -6
  43. package/src/windows-prediction-network.cs +6 -4
@@ -20,6 +20,7 @@
20
20
  <script src="/ui.js" defer></script>
21
21
  <script src="/console.js" defer></script>
22
22
  <script src="/tools.js" defer></script>
23
+ <script src="/connections.js" defer></script>
23
24
  <title data-i18n="ccdx_local_dashboard">CCDX · Dashboard</title>
24
25
  </head>
25
26
  <body>
@@ -70,6 +71,7 @@
70
71
  <label><span data-i18n="source">Source</span><select id="source-provider"></select></label>
71
72
  <label id="source-model-field" hidden><span data-i18n="conversation_model">Conversation model</span><select id="source-model"></select></label>
72
73
  <button id="apply-source" type="button" data-i18n="apply_source">Use this source</button>
74
+ <button type="button" data-client-access="codex" data-i18n="api_client_settings">Manage client access</button>
73
75
  </div>
74
76
  <p id="source-model-note" class="hint" data-i18n="github_model_in_codex">Choose your conversation model in Codex.</p>
75
77
  <div id="source-control-note" class="hint" role="status"></div>
@@ -125,6 +127,7 @@
125
127
  </details>
126
128
  </div>
127
129
  <div data-view="claude" hidden>
130
+ <div class="section-actions"><button type="button" data-client-access="claude_app" data-i18n="api_claude_app_settings">Claude App settings</button><button type="button" data-client-access="claude_code" data-i18n="api_claude_code_settings">Claude Code settings</button></div>
128
131
  <section class="panel dashboard-section" id="claude-connections">
129
132
  <h2 data-i18n="client_connections">APP SETUP</h2>
130
133
  <div class="table-wrap"><table><thead><tr><th data-i18n="client">APP</th><th data-i18n="connection_setup" data-i18n-title="configured_not_successful">Setup</th><th data-i18n="local_bridge">Local service</th><th data-i18n="last_request">LAST REQUEST</th></tr></thead><tbody id="claude-clients"></tbody></table></div>
@@ -286,6 +289,46 @@
286
289
  </details>
287
290
  </div>
288
291
  <div data-view="system" hidden>
292
+ <section class="panel dashboard-section" id="connection-sources">
293
+ <div class="panel-heading"><h2 data-i18n="model_services">Model sources</h2><button id="connection-add" type="button" data-i18n="api_add">Add API</button></div>
294
+ <div id="connection-source-list"></div>
295
+ </section>
296
+ <section class="panel dashboard-section" id="connection-clients">
297
+ <h2 data-i18n="api_clients">Clients</h2><div id="connection-client-list"></div>
298
+ </section>
299
+ <details id="connection-disabled" class="connection-disabled"><summary data-i18n="api_disabled">Disabled</summary><div id="connection-disabled-list"></div></details>
300
+ <section class="panel dashboard-section" id="connection-editor" hidden aria-labelledby="connection-editor-title">
301
+ <div class="panel-heading"><h2 id="connection-editor-title" data-i18n="api_add">Add API</h2><button type="button" id="connection-cancel" data-i18n="cancel">Cancel</button></div>
302
+ <form id="connection-api-form">
303
+ <div class="connection-fields">
304
+ <label><span data-i18n="api_name">Name</span><input id="connection-name" name="name" type="text" maxlength="60" required autocomplete="off"></label>
305
+ <label><span data-i18n="api_base">API address</span><input id="connection-base" name="base" type="url" required autocomplete="off" spellcheck="false" placeholder="https://api.example.com/v1"></label>
306
+ <label><span>API Key</span><input id="connection-key" name="key" type="password" autocomplete="off" spellcheck="false"><span class="hint" data-i18n="api_key_private">Stored separately. Never sent to clients.</span></label>
307
+ </div>
308
+ <fieldset><legend data-i18n="api_protocols">Available APIs</legend><div class="connection-checks"><label><input type="checkbox" name="protocol" value="messages" checked>Messages</label><label><input type="checkbox" name="protocol" value="responses" checked>Responses</label><label><input type="checkbox" name="protocol" value="chat">Chat Completions</label></div></fieldset>
309
+ <details class="tool-details"><summary data-i18n="api_endpoint_options">Addresses &amp; authentication</summary><div class="connection-fields">
310
+ <label>Messages<input name="messages_url" type="url"></label><label>Responses<input name="responses_url" type="url"></label><label>Chat Completions<input name="chat_url" type="url"></label>
311
+ <label><span data-i18n="api_messages_auth">Messages authentication</span><select name="auth_header"><option value="x-api-key">x-api-key</option><option value="bearer">Bearer token</option></select></label>
312
+ <label><span data-i18n="api_key_env">Read key from environment</span><input name="key_env" type="text" autocomplete="off" spellcheck="false" placeholder="CCDX_COMPANY_API_KEY"><span class="hint" data-i18n="api_key_env_hint">Optional for servers without a credential service. Set before starting CCDX.</span></label>
313
+ </div></details>
314
+ <fieldset><legend data-i18n="api_allowed_clients">Allowed clients</legend><div class="connection-checks" id="connection-allowed-clients"></div></fieldset>
315
+ <fieldset><legend data-i18n="model_catalog">Model list</legend><div class="section-actions"><button type="button" id="connection-discover" data-i18n="api_read_models">Read models</button><span class="hint" data-i18n="api_discovery_save_first">Save the API first. No chat request is sent.</span></div>
316
+ <details class="tool-details" id="connection-manual-model"><summary data-i18n="api_manual_model">Add a model manually</summary><div class="section-actions"><input type="text" id="connection-model-id" spellcheck="false" autocomplete="off" aria-label="Model ID" placeholder="Model ID"><button type="button" id="connection-model-add" data-i18n="api_add_model">Add model</button></div></details>
317
+ <p class="hint" data-i18n="api_model_protocol_hint">Choose the APIs each model supports.</p><div class="table-wrap"><table><thead><tr><th data-i18n="model">Model</th><th data-i18n="api_protocols">Available APIs</th><th></th></tr></thead><tbody id="connection-models"></tbody></table></div>
318
+ </fieldset>
319
+ <div class="section-actions"><button type="submit" data-i18n="api_save">Save</button></div>
320
+ </form>
321
+ </section>
322
+ <section class="panel dashboard-section" id="connection-client-editor" hidden aria-labelledby="connection-client-title">
323
+ <div class="panel-heading"><h2 id="connection-client-title"></h2><button type="button" id="connection-client-cancel" data-i18n="cancel">Cancel</button></div>
324
+ <form id="connection-client-form"><div class="connection-fields"><label><span data-i18n="api_current_source">Current source</span><select id="connection-current"></select></label><label id="connection-current-model-row"><span data-i18n="model">Model</span><select id="connection-current-model"></select></label></div>
325
+ <fieldset><legend data-i18n="api_allowed_sources">Allowed sources</legend><div id="connection-client-allowed" class="connection-checks"></div></fieldset>
326
+ <p class="hint" data-i18n="api_existing_requests">Existing requests keep their source. Use a new conversation after switching.</p>
327
+ <div class="section-actions"><button type="submit" data-i18n="api_save">Save</button></div>
328
+ </form>
329
+ </section>
330
+ <section class="panel dashboard-section" id="connection-disable-editor" hidden aria-labelledby="connection-disable-title"><h2 id="connection-disable-title" data-i18n="api_disable_source">Disable source</h2><p class="hint" data-i18n="api_choose_replacements">Choose another source or pause each affected client.</p><form id="connection-disable-form"><div id="connection-replacements" class="connection-fields"></div><div class="section-actions"><button type="submit" data-i18n="api_confirm_disable">Disable</button><button type="button" id="connection-disable-cancel" data-i18n="cancel">Cancel</button></div></form></section>
331
+ <p id="connection-note" class="hint" role="status" aria-live="polite"></p>
289
332
  <section class="panel dashboard-section" aria-labelledby="web-appearance-title">
290
333
  <h2 id="web-appearance-title" data-i18n="appearance_web_appearance">网页外观</h2>
291
334
  <div class="appearance-row">
@@ -1,5 +1,88 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "api_add": ["Add API", "添加 API"],
4
+ "api_clients": ["Clients", "客户端"],
5
+ "api_disabled": ["Disabled", "已关闭"],
6
+ "api_name": ["Name", "名称"],
7
+ "api_base": ["API address", "API 地址"],
8
+ "api_key_private": ["Stored separately. Never sent to clients.", "独立保存,不会传给客户端。"],
9
+ "api_key_env": ["Read key from environment", "从环境变量读取 Key"],
10
+ "api_key_env_hint": ["Optional for servers without a credential service. Set before starting CCDX.", "无系统密钥库时可用,需在启动前设置。"],
11
+ "ccdx_api_environment_key_missing": ["Set the named environment variable, then restart CCDX.", "请设置对应环境变量,然后重启 CCDX。"],
12
+ "api_protocols": ["Available APIs", "可用接口"],
13
+ "api_endpoint_options": ["Addresses & authentication", "接口地址与认证"],
14
+ "api_messages_auth": ["Messages authentication", "Messages 认证"],
15
+ "api_allowed_clients": ["Allowed clients", "允许使用的客户端"],
16
+ "api_read_models": ["Read models", "读取模型"],
17
+ "api_discovery_save_first": ["Save the API first. No chat request is sent.", "先保存来源;只读取模型目录。"],
18
+ "api_add_model": ["Add model", "添加模型"],
19
+ "api_manual_model": ["Add a model manually", "手工添加模型"],
20
+ "api_model_protocol_hint": ["Select the models to use and their supported APIs.", "勾选要使用的模型,再选择其支持的接口。"],
21
+ "api_model_protocol_required": ["Choose an API for {model}, or deselect it.", "请为 {model} 选择接口,或取消勾选该模型。"],
22
+ "api_remove_model": ["Remove", "移除"],
23
+ "api_save": ["Save", "保存"],
24
+ "api_current_source": ["Current source", "当前来源"],
25
+ "api_allowed_sources": ["Allowed sources", "允许使用的来源"],
26
+ "api_existing_requests": ["Existing requests keep their source. Use a new conversation after switching.", "已有请求不变;切换后请新建对话。"],
27
+ "api_disable_source": ["Disable source", "关闭来源"],
28
+ "api_choose_replacements": ["Choose another source or pause each affected client.", "为受影响的客户端换源,或暂停接入。"],
29
+ "api_confirm_disable": ["Disable", "确认关闭"],
30
+ "api_pause": ["Pause access", "暂停接入"],
31
+ "api_allowed_summary": ["Allowed: {clients}", "允许使用:{clients}"],
32
+ "api_none": ["Not assigned", "暂未分配"],
33
+ "api_account": ["Account", "查看账号"],
34
+ "api_manage": ["Manage", "管理"],
35
+ "api_restore": ["Enable again", "重新开启"],
36
+ "api_current_summary": ["Current source: {source}", "当前来源:{source}"],
37
+ "api_client_disabled": ["CCDX access is off; the app stays open.", "接入已关闭,应用保持运行。"],
38
+ "api_close_client": ["Disable client access", "关闭客户端接入"],
39
+ "api_no_disabled": ["No disabled items.", "没有已关闭的项目。"],
40
+ "api_saved": ["Saved. Reopen the app for first-time setup; existing requests stay unchanged.", "已保存。首次接入请重新打开应用。"],
41
+ "api_config_saved": ["API saved. Current client sources are unchanged.", "API 已保存,客户端来源未改变。"],
42
+ "api_provider_disabled": ["Source disabled. Its configuration was kept.", "来源已关闭,配置已保留。"],
43
+ "api_provider_enabled": ["Source enabled. Client selections are unchanged.", "来源已开启,客户端来源未改变。"],
44
+ "api_client_enabled": ["Client enabled. Choose a source to connect.", "客户端已开启,请选择来源。"],
45
+ "api_client_preserved": ["Saved. Existing custom or managed app settings were kept.", "已保存;已有自定义或托管配置已保留。"],
46
+ "api_client_config_failed": ["Source saved, but app configuration failed. Review Checks & repairs.", "来源已保存,客户端配置失败。请检查与修复。"],
47
+ "api_client_not_installed": ["Saved. The client app was not found.", "配置已保存,未发现客户端应用。"],
48
+ "api_key_keep": ["Saved; leave blank to keep", "已保存;留空不更换"],
49
+ "api_key_enter": ["Enter API key", "输入 API Key"],
50
+ "api_models_read": ["Models read. Review their APIs before saving.", "模型已读取;请确认接口后保存。"],
51
+ "api_configured_models": ["CONFIGURED MODELS", "已配置的模型"],
52
+ "api_no_enabled_sources": ["No source is enabled. Review Settings.", "暂无启用的来源,请查看设置。"],
53
+ "api_client_settings": ["Manage client access", "设置客户端接入"],
54
+ "api_claude_app_settings": ["Claude App settings", "设置 Claude App"],
55
+ "api_claude_code_settings": ["Claude Code settings", "设置 Claude Code"],
56
+ "ccdx_connections_unavailable": ["Restart the updated CCDX to manage connections.", "请重启更新后的 CCDX。"],
57
+ "ccdx_connections_invalid": ["Connection settings are unreadable; the file was kept.", "接入配置无法读取,原文件已保留。"],
58
+ "ccdx_connections_action_failed": ["Could not save connections. Try again.", "接入配置未保存,请重试。"],
59
+ "ccdx_connections_action_invalid": ["Review the selected clients and sources.", "请检查客户端与来源选择。"],
60
+ "ccdx_connections_conflict": ["Another process changed these settings. Restart CCDX before saving.", "其他进程已改动配置,请重启 CCDX。"],
61
+ "ccdx_api_url_invalid": ["Use a complete HTTPS address without credentials or query parameters.", "请用不含凭据或查询参数的 HTTPS 地址。"],
62
+ "ccdx_api_origin_mismatch": ["API addresses must use the same host and port.", "各接口须使用相同的主机和端口。"],
63
+ "ccdx_api_config_invalid": ["Review the API name, address and authentication.", "请检查 API 名称、地址和认证。"],
64
+ "ccdx_api_key_invalid": ["Enter a valid API key.", "请输入有效的 API Key。"],
65
+ "ccdx_api_secret_unavailable": ["The system credential store is unavailable. No plaintext fallback was used.", "系统凭据库不可用,未改用明文保存。"],
66
+ "ccdx_api_models_invalid": ["Use unique model IDs and choose a supported API for each.", "模型 ID 不能重复,且需选择可用接口。"],
67
+ "ccdx_api_name_exists": ["This source name is already used. Choose another name.", "来源名称已存在,请换一个名称。"],
68
+ "ccdx_api_model_reserved": ["codex-auto-review is reserved by CCDX. Enter the real upstream model ID.", "codex-auto-review 为内部名称,请填真实模型 ID。"],
69
+ "ccdx_connections_limit": ["Connection settings exceed the 8 MiB limit.", "接入配置超过 8 MiB 上限。"],
70
+ "ccdx_api_model_unavailable": ["Choose a configured model with the required API.", "请选择支持对应接口的已配置模型。"],
71
+ "ccdx_api_protocol_required": ["Claude needs Messages; Codex needs Responses.", "Claude 需 Messages;Codex 需 Responses。"],
72
+ "ccdx_api_effort_unavailable": ["Choose a reasoning level advertised by this model, or follow the client.", "请选择模型支持的推理档位,或跟随客户端。"],
73
+ "ccdx_source_in_use": ["Change the current source or pause its clients first.", "请先更换来源,或暂停相关客户端。"],
74
+ "ccdx_source_busy": ["A previous M365 request is still running. Let it finish before disabling.", "旧的 M365 请求仍在运行,请结束后关闭。"],
75
+ "ccdx_provider_environment_disabled": ["Microsoft 365 is disabled by CCDX_M365=0.", "Microsoft 365 已被环境设置关闭。"],
76
+ "ccdx_client_source_disabled": ["The client or source is disabled. Review Settings.", "客户端或来源已关闭,请查看设置。"],
77
+ "ccdx_client_source_mismatch": ["Save the selected source before changing its review model.", "请先保存来源,再修改审查模型。"],
78
+ "ccdx_conversation_source_changed": ["This history belongs to another source or key. Start a new conversation.", "此历史属于其他来源或 Key,请新建对话。"],
79
+ "ccdx_conversation_state_invalid": ["Conversation source records are unreadable. The existing file was kept.", "会话来源记录无法读取,原文件已保留。"],
80
+ "ccdx_api_catalog_invalid": ["The model list was invalid. Existing settings were kept.", "模型列表无效,已有配置已保留。"],
81
+ "ccdx_api_catalog_http_401": ["Model access was rejected (HTTP 401). Check the key.", "模型访问被拒绝(401),请检查 Key。"],
82
+ "ccdx_api_catalog_http_404": ["No model catalog here (404). Check the API prefix, such as /v1.", "模型目录不存在(404),请检查 API 前缀,如 /v1。"],
83
+ "ccdx_api_catalog_http_403": ["Model access was denied (HTTP 403). Check permissions.", "模型访问被拒绝(403),请检查权限。"],
84
+ "ccdx_api_network_unavailable": ["Could not reach the API. Proxy and TLS rules were kept.", "无法连接 API,代理和证书规则已保留。"],
85
+ "ccdx_api_limit": ["Up to 16 manual APIs are supported.", "最多可添加 16 个手工 API。"],
3
86
  "github_account_entry": ["GitHub account", "GitHub 账号"],
4
87
  "m365_account_entry": ["M365 account", "M365 账号"],
5
88
  "flow_count": ["{count} requests", "{count} 个请求"],
@@ -1086,7 +1169,7 @@
1086
1169
  try { if (localStorage.getItem(storageKey) === "zh") language = "zh"; } catch {}
1087
1170
  document.documentElement.lang = language === "zh" ? "zh-CN" : "en";
1088
1171
  const messages = new WeakMap();
1089
- const attributes = { textContent: "data-i18n", title: "data-i18n-title", "aria-label": "data-i18n-label" };
1172
+ const attributes = { textContent: "data-i18n", title: "data-i18n-title", "aria-label": "data-i18n-label", placeholder: "data-i18n-placeholder" };
1090
1173
 
1091
1174
  function format(key, values = {}) {
1092
1175
  const id = Object.hasOwn(translations, key) ? key : Object.hasOwn(legacyMessages, key) ? legacyMessages[key] : key;
@@ -1111,7 +1194,7 @@
1111
1194
 
1112
1195
  function apply() {
1113
1196
  document.documentElement.lang = language === "zh" ? "zh-CN" : "en";
1114
- for (const target of document.querySelectorAll("[data-i18n], [data-i18n-title], [data-i18n-label]")) {
1197
+ for (const target of document.querySelectorAll("[data-i18n], [data-i18n-title], [data-i18n-label], [data-i18n-placeholder]")) {
1115
1198
  for (const [attribute, marker] of Object.entries(attributes)) {
1116
1199
  if (!target.hasAttribute(marker)) continue;
1117
1200
  const saved = messages.get(target)?.[attribute];
@@ -225,7 +225,7 @@
225
225
  ? "active_active_failed_failed_delivery_failures_delivery"
226
226
  : "setup_state_unknown_ccdx_image_status", { active: number(image?.active), failed: number(image?.failed), delivery: number(image?.delivery_failures) });
227
227
 
228
- const claude = data.providers?.m365?.claude, claudeMetrics = claude?.requests?.performance;
228
+ const claude = data.providers?.claude || data.providers?.m365?.claude, claudeMetrics = claude?.requests?.performance;
229
229
  percentiles("claude-ttft-percentiles", claudeMetrics?.by_route?.messages?.ttft_ms);
230
230
  const sourceBody = element("source-requests-body");
231
231
  if (sourceBody) {
@@ -55,6 +55,30 @@ h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spac
55
55
  .meter::-webkit-progress-value { background: var(--accent-soft); }
56
56
  .meter::-moz-progress-bar { background: var(--accent-soft); }
57
57
  .dashboard-section { min-height: 0; margin-top: 11px; }
58
+ .connection-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 18px 0; border-bottom: 1px solid var(--border); min-width: 0; }
59
+ .connection-row:last-child { border-bottom: 0; padding-bottom: 0; }
60
+ .connection-row > div:first-child { min-width: 0; }
61
+ .connection-row h3 { margin: 0; color: var(--text); font-size: 13px; }
62
+ .connection-row p { margin: 5px 0 0; overflow-wrap: anywhere; }
63
+ .connection-actions, .connection-checks { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
64
+ .connection-actions { flex: 0 0 auto; }
65
+ .connection-checks label { display: inline-flex; align-items: center; gap: 7px; min-height: 30px; white-space: nowrap; }
66
+ .connection-checks input { flex: none; accent-color: var(--accent); }
67
+ .connection-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin: 18px 0; }
68
+ .connection-fields > label { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
69
+ .connection-fields input, .connection-fields select { width: 100%; min-width: 0; min-height: 38px; }
70
+ .connection-fields input, #connection-model-id { font: inherit; color: var(--text); background: var(--surface); border: 1px solid var(--button-border); border-radius: 2px; padding: 7px 10px; }
71
+ .connection-fields input:focus-visible, #connection-model-id:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
72
+ #connection-editor fieldset, #connection-client-editor fieldset { border: 0; padding: 0; margin: 22px 0; min-width: 0; }
73
+ #connection-editor legend, #connection-client-editor legend { padding: 0; margin-bottom: 9px; color: var(--text); }
74
+ #connection-models td { white-space: normal; overflow-wrap: anywhere; }
75
+ #connection-models td:first-child { min-width: 140px; }
76
+ #connection-models td:first-child label { display: inline-flex; align-items: center; gap: 8px; }
77
+ #connection-models td:first-child input { flex: none; accent-color: var(--accent); }
78
+ #connection-models td:last-child button { white-space: nowrap; }
79
+ .connection-disabled { padding: 8px 0 18px; color: var(--heading); }
80
+ .connection-disabled .connection-row { padding: 13px 0; }
81
+ @media (max-width: 650px) { .connection-fields { grid-template-columns: minmax(0, 1fr); } .connection-actions { gap: 9px; } .connection-row { gap: 10px; } }
58
82
  .heading-actions { display: flex; align-items: center; gap: 16px; }
59
83
  .heading-actions button { padding: 5px 9px; }
60
84
  .animation-options { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-top: 18px; }
@@ -114,6 +114,7 @@ function applyProviders(data, { changed }) {
114
114
  let reloadModels = false;
115
115
  const previous = new Map(providerEntries.map(entry => [entry.id, JSON.stringify([entry.generation, entry.auth?.account])]));
116
116
  providerEntries = data.providers;
117
+ if (!providerEntries.length) { text("models-state", "api_no_enabled_sources");emptyTable("live-models-body", 3, "api_no_enabled_sources"); }
117
118
  for (const [id] of modelSnapshots) {
118
119
  const provider = providerEntries.find(entry => entry.id === id);
119
120
  if (!provider) {
@@ -154,6 +155,7 @@ function applyProviders(data, { changed }) {
154
155
  }
155
156
  element("live-models-body").setAttribute("aria-labelledby", `model-provider-${selectedProvider}`);
156
157
  if (sourceChoicesChanged) window.dispatchEvent(new CustomEvent("ccdx:providers"));
158
+ if (!providerEntries.length) { text("models-state", "api_no_enabled_sources");emptyTable("live-models-body", 3, "api_no_enabled_sources");return; }
157
159
  if ((!wasInitialized || reloadModels || selectedProvider !== previousSelection) && !element("upstream-models").closest("[hidden]")) { dashboardRefresh.invalidate("models", { clear: true });void loadModels(); }
158
160
  }
159
161
 
@@ -281,7 +283,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
281
283
  variant: catalogProvider,
282
284
  load: async ({ signal, variant }) => {
283
285
  if (!variant) throw new Error("reading_provider_catalog");
284
- const data = await readDashboard(`/_ccdx/ui/models/live?provider=${encodeURIComponent(variant)}`, { signal, source: ["live", "catalog"] });
286
+ const data = await readDashboard(`/_ccdx/ui/models/live?provider=${encodeURIComponent(variant)}`, { signal, source: ["live", "catalog", "configured"] });
285
287
  if (!Array.isArray(data.models) || data.models.some(model => !model || typeof model.id !== "string" || !Array.isArray(model.endpoints))) throw new Error("Invalid model snapshot");
286
288
  return { ...data, provider: variant };
287
289
  },
@@ -290,7 +292,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
290
292
  state: state => {
291
293
  if (state.attemptVariant !== selectedProvider) return;
292
294
  element("refresh-models").disabled = Boolean(state.pending);
293
- text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
295
+ text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.source === "configured" ? "api_configured_models" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
294
296
  element("model-check-details").hidden = !state.error;
295
297
  if (state.error) {
296
298
  const message = String(state.error.message || state.error).slice(0, 240);
@@ -116,7 +116,7 @@ function dashboardProviders(providerStateFn, authStatusFn) {
116
116
  const local = authStatusFn()?.profiles?.codex || {};
117
117
  const entries = providerStateFn?.() || [{ id: "github", name: "GitHub Copilot", enabled: true, state: "unknown",
118
118
  clients: [{ id: "codex", name: "Codex App", selected: true, state: "configured" }] }];
119
- return entries.slice(0, 16).filter(entry => isProviderId(entry.id)).map(entry => {
119
+ return entries.slice(0, 18).filter(entry => isProviderId(entry.id)).map(entry => {
120
120
  const auth = entry.id === "github" ? { ...entry.auth,
121
121
  state: local.valid ? "saved" : local.configured ? "unavailable" : "unconfigured",
122
122
  account: local.valid ? local.login || "" : "" } : entry.auth || {};
@@ -147,6 +147,7 @@ export async function handleDashboardApi(req, res, pathname, {
147
147
  providerCatalogFn,
148
148
  providerStateFn,
149
149
  providerAccountsFn,
150
+ connectionsFn,
150
151
  updateStatusFn,
151
152
  serviceControl,
152
153
  applyAnimation,
@@ -167,6 +168,20 @@ export async function handleDashboardApi(req, res, pathname, {
167
168
  return tools.handle(req, res, pathname, sendJson, sameOrigin);
168
169
  }
169
170
 
171
+ if (pathname === "/_ccdx/ui/connections") {
172
+ if (!connectionsFn) { sendJson(res, 503, { error: "ccdx_connections_unavailable" });return; }
173
+ if (req.method === "GET") { try { sendJson(res, 200, await connectionsFn()); } catch { sendJson(res, 409, { error: "ccdx_connections_invalid" }); }return; }
174
+ if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
175
+ if (!sameOrigin(req)) { sendJson(res, 403, { error: "Connections require the same-origin dashboard" });return; }
176
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 415, { error: "Expected application/json" });return; }
177
+ const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
178
+ try {
179
+ const input = await readJsonBody(req, { maxBodyBytes: 256 * 1024, maxDecodedBodyBytes: 256 * 1024, signal: abort.signal });
180
+ abort.clearTimeout();const result = await connectionsFn(input);if (!res.destroyed && !res.writableEnded) sendJson(res, 200, result);
181
+ } catch (error) { sendJson(res, error.statusCode || 400, { error: /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_connections_action_failed" }); }
182
+ finally { abort.cleanup(); }return;
183
+ }
184
+
170
185
  if (pathname === PROVIDERS_PATH && req.method === "GET") {
171
186
  try { sendJson(res, 200, { source: "provider_status", providers: dashboardProviders(providerStateFn, authStatusFn) }); }
172
187
  catch { sendJson(res, 500, { error: "Could not read provider status" }); }
@@ -290,13 +305,13 @@ export async function handleDashboardApi(req, res, pathname, {
290
305
  }
291
306
  const models = catalog.models;
292
307
  sendJson(res, 200, {
293
- source: catalog.source === "catalog" ? "catalog" : "live",
294
- checked_at: catalog.source === "catalog" ? catalog.checkedAt : new Date().toISOString(),
308
+ source: ["catalog", "configured"].includes(catalog.source) ? catalog.source : "live",
309
+ checked_at: ["catalog", "configured"].includes(catalog.source) ? catalog.checkedAt : new Date().toISOString(),
295
310
  upstream_host: safeText(catalog?.upstreamHost || "GitHub Copilot", 120),
296
311
  advertised: finite(catalog?.advertised),
297
312
  selectable: models.filter(model => model.selectable !== false).length,
298
313
  models: models.slice(0, 500).map((model) => ({
299
- id: safeText(model.id, 100),
314
+ id: safeText(model.id, 160),
300
315
  vendor: safeText(model.vendor, 80),
301
316
  endpoints: Array.isArray(model.endpoints) ? model.endpoints.filter((value) => ["responses", "chat", "messages"].includes(value)) : [],
302
317
  preview: model.preview === true,
package/src/dashboard.mjs CHANGED
@@ -18,6 +18,7 @@ const ASSETS = new Map([
18
18
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
19
19
  ["/icons.js", ["./dashboard/icons.js", "text/javascript; charset=utf-8"]],
20
20
  ["/tools.js", ["./dashboard/tools.js", "text/javascript; charset=utf-8"]],
21
+ ["/connections.js", ["./dashboard/connections.js", "text/javascript; charset=utf-8"]],
21
22
  ]);
22
23
 
23
24
  export async function serveDashboard(req, res, pathname) {
@@ -1,5 +1,5 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
2
- export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
5
5
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
@@ -0,0 +1,7 @@
1
+ // Keep company routing and OS credential access; omit unrelated application secrets and Node hooks.
2
+ export function privateHelperEnvironment(env = process.env) {
3
+ const keys = new Set(["PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "SYSTEMROOT", "WINDIR", "APPDATA", "LOCALAPPDATA",
4
+ "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "NODE_EXTRA_CA_CERTS",
5
+ "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "DISPLAY"]);
6
+ return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
7
+ }
@@ -20,7 +20,7 @@ export async function handleProviderManagement(req, res, runtime) {
20
20
  || !["models", "switch", "on", "off", "remove", "auto-review", "accounts", "account"].includes(input.action)) throw httpError("Invalid provider action", 400);
21
21
  if (input.action === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw httpError("Select an available company account", 400);
22
22
  if (input.effort !== undefined && input.effort !== null && (typeof input.effort !== "string" || input.effort.length > 16)) throw httpError("Invalid reasoning effort", 400);
23
- for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > 128)) throw httpError("Invalid provider selection", 400);
23
+ for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > (key.includes("model") ? 160 : 128))) throw httpError("Invalid provider selection", 400);
24
24
  abort.clearTimeout();
25
25
  const result = await runtime.action(input);
26
26
  if (!res.destroyed && !res.writableEnded) { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result)); }
@@ -11,15 +11,30 @@ import { publicM365Accounts, accountChoiceId, m365AccountMessage } from "./provi
11
11
  import { providerRegistry } from "./provider-registry.mjs";
12
12
  import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
13
13
  import { m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
14
+ import { createConnectionRuntime } from "./connection-runtime.mjs";
15
+ import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
16
+ import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
14
17
 
15
18
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
16
19
  { code: reason, statusCode: 503 });
17
20
 
18
21
  // Composition owns source selection. Providers never modify Codex, prediction,
19
22
  // image configuration or each other's credentials.
20
- export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
23
+ export function createProviderRuntime(options = {}) {
24
+ options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
25
+ let connections;
26
+ const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => {
27
+ if (!fs.existsSync(accessSettingsPath(options))) return false;
28
+ const graph = readAccessSettings(options);
29
+ return graph.claude_private_keys || !["claude_app", "claude_code"].every(id => graph.clients[id].enabled && graph.clients[id].source === "m365" && graph.clients[id].allowed.includes("m365"));
30
+ },
31
+ onClaudeReady: () => connections?.syncClients() });
32
+ connections = createConnectionRuntime({ ...options, legacy });return connections;
33
+ }
34
+
35
+ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
21
36
  corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
22
- discoverM365 = requestM365Accounts } = {}) {
37
+ discoverM365 = requestM365Accounts, managedClaude, onClaudeReady } = {}) {
23
38
  const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
24
39
  profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
25
40
  return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
@@ -27,6 +42,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
27
42
  let reason = null, claudeReason = null, lastClients = {};
28
43
  let changingAccount = false;
29
44
  const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
45
+ const claudePerformance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
30
46
  const sources = new Map([[github.id, github]]);
31
47
  const dashboardProfiles = new Map();
32
48
  const dashboardGeneration = provider => {
@@ -36,10 +52,11 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
36
52
  };
37
53
  const sessions = new Map();let priorNamespace = null, requestOrder = 0, activeM365Requests = 0;
38
54
  let enabled;
39
- try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
55
+ try { enabled = readM365Settings(options).enabled && readAccessSettings(options).providers.m365 && env.CCDX_M365 !== "0"; }
40
56
  catch { enabled = false;reason = "m365_config_invalid"; }
41
57
 
42
58
  async function syncClaudeClients() {
59
+ if (managedClaude?.()) { await onClaudeReady?.();return; }
43
60
  const source = m365, profile = source?.profileId();
44
61
  if (!source || !gateway || closed || !enabled) return;
45
62
  await clientLifecycle.sync({ source, baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: () => ensureM365GatewayKey(options),
@@ -68,7 +85,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
68
85
  const apiKey = ensureM365GatewayKey(options);
69
86
  if (!gateway) {
70
87
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
71
- const opened = await start({ provider: m365, apiKey, port: corePort, env, log,
88
+ const opened = await start({ provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
72
89
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
73
90
  if (closed || !enabled) { await opened.close();return null; }
74
91
  gateway = opened;
@@ -135,7 +152,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
135
152
  if (closed) throw unavailable("m365_runtime_closed");
136
153
  if (candidate.models("claude").length) {
137
154
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
138
- opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log,
155
+ opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
139
156
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
140
157
  }
141
158
  candidate.commitSelection(discovered.binding);
@@ -191,6 +208,21 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
191
208
  return snapshot();
192
209
  }
193
210
  return {
211
+ claudePerformance,
212
+ source: id => sources.get(id),
213
+ async pauseM365() {
214
+ updateM365Settings({ enabled: false }, options);enabled = false;
215
+ // Existing handlers retain their source until their request finishes.
216
+ const previous = m365, oldGateway = gateway;m365 = null;gateway = null;sources.delete("m365");
217
+ await pending;await oldGateway?.close();return previous;
218
+ },
219
+ removeM365SavedProfile() {
220
+ if (activeM365Requests > 0) throw Object.assign(new Error("M365 requests are active; finish them before removing the account"), { code: "m365_profile_busy", statusCode: 409 });
221
+ const paths = m365Paths(options);
222
+ for (const file of [paths.account, paths.catalog, paths.gateway, paths.conversations]) {
223
+ try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); } catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
224
+ }
225
+ },
194
226
  github, current, snapshot, start: startM365, refresh: () => startM365(true),
195
227
  handleClaude(req, res) {
196
228
  if (changingAccount) { res.writeHead(409, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: { code: "m365_account_busy", message: m365AccountMessage("m365_account_busy") } }));return; }
@@ -0,0 +1,51 @@
1
+ import https from "node:https";
2
+ import { Readable } from "node:stream";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { resolveNetworkRoute, networkProxyFor, bypassNetworkProxy } from "../network-route.mjs";
6
+ import { createProxyAgent } from "../proxy-tunnel.mjs";
7
+ import { apiUrl, accessError } from "../access-settings.mjs";
8
+ import { privateHelperEnvironment } from "../private-helper-environment.mjs";
9
+
10
+ export async function createApiNetwork({ targets, env = process.env, platform = process.platform, signal,
11
+ requestImpl = https.request, exec = promisify(execFile), startWindowsNetwork } = {}) {
12
+ const urls = new Set(targets.map(raw => new URL(apiUrl(raw)).href));if (!urls.size || urls.size > 8) throw accessError("ccdx_api_url_invalid");
13
+ const first = new URL([...urls][0]);
14
+ let plan = resolveNetworkRoute({ env, checkApi: false }), worker;
15
+ if (!networkProxyFor(first, plan) && !bypassNetworkProxy(first.hostname, first.port || 443, plan)) {
16
+ if (platform === "darwin") {
17
+ const { stdout } = await exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2500, maxBuffer: 65536, signal });
18
+ plan = resolveNetworkRoute({ env, systemProxy: stdout, checkApi: false });
19
+ } else if (platform === "win32") {
20
+ const start = startWindowsNetwork || (await import("../windows-http-network.mjs")).startWindowsHttpNetwork;
21
+ worker = await start({ target: "api", apiTargets: [...urls], env: privateHelperEnvironment(env), signal, timeoutMs: 120000 });
22
+ requestImpl = worker.requestImpl;
23
+ }
24
+ }
25
+ const agent = worker ? undefined : createProxyAgent(plan);let closed = false;
26
+ return {
27
+ healthy: () => !closed && (!worker || worker.healthy()),
28
+ fetch(raw, init = {}) {
29
+ return new Promise((resolve, reject) => {
30
+ let url;try { url = new URL(raw); } catch { reject(accessError("ccdx_api_url_invalid"));return; }
31
+ if (closed || !urls.has(url.href) || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
32
+ if (init.signal?.aborted) { reject(init.signal.reason);return; }
33
+ let req, incoming;
34
+ const cleanup = () => init.signal?.removeEventListener("abort", abort);
35
+ const abort = () => { req?.destroy(init.signal.reason || accessError("ccdx_api_cancelled"));incoming?.destroy(); };
36
+ try {
37
+ req = requestImpl({ hostname: worker ? url.hostname : url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 443), protocol: "https:", path: url.pathname,
38
+ method: init.method || "GET", headers: { ...Object.fromEntries(new Headers(init.headers)), "accept-encoding": "identity" }, agent, rejectUnauthorized: true }, res => {
39
+ incoming = res;res.once("end", cleanup);res.once("close", cleanup);res.on("error", reject);
40
+ const headers = new Headers();for (const [key, value] of Object.entries(res.headers)) for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(key, String(item));
41
+ try { const empty = [204, 205, 304].includes(res.statusCode);if (empty) res.resume();resolve(new Response(empty ? null : Readable.toWeb(res), { status: res.statusCode, headers })); }
42
+ catch (error) { cleanup();res.destroy();reject(error); }
43
+ });
44
+ req.on("error", error => { cleanup();reject(error); });init.signal?.addEventListener("abort", abort, { once: true });
45
+ if (init.signal?.aborted) { abort();return; }req.end(init.body);
46
+ } catch (error) { cleanup();req?.destroy();reject(error); }
47
+ });
48
+ },
49
+ close() { closed = true;agent?.destroy();worker?.close(); },
50
+ };
51
+ }