codex-copilot-dx 1.3.7 → 1.3.9
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 +7 -16
- package/bin/cli.mjs +55 -31
- package/docs/ARCHITECTURE.md +25 -1
- package/docs/REFERENCE.md +45 -10
- package/package.json +3 -3
- package/src/claude-gateway.mjs +21 -18
- package/src/cli-command-spec.mjs +3 -2
- package/src/cli-image.mjs +2 -80
- package/src/cli-options.mjs +1 -1
- package/src/client-integration.mjs +11 -4
- package/src/connection-runtime.mjs +1 -0
- package/src/dashboard/connections.js +5 -1
- package/src/dashboard/console.js +12 -6
- package/src/dashboard/features.js +73 -0
- package/src/dashboard/index.html +15 -14
- package/src/dashboard/language.js +60 -16
- package/src/dashboard/tools.js +4 -1
- package/src/dashboard/ui.js +1 -1
- package/src/dashboard/usage.js +2 -2
- package/src/dashboard-api.mjs +7 -2
- package/src/dashboard-tools.mjs +2 -1
- package/src/dashboard.mjs +1 -0
- package/src/doctor-compat.mjs +19 -13
- package/src/doctor.mjs +1 -1
- package/src/image-setup.mjs +110 -0
- package/src/local-privacy.mjs +15 -11
- package/src/local-tools.mjs +8 -2
- package/src/messages-history-transfer.mjs +12 -2
- package/src/messages-system-policy.mjs +20 -0
- package/src/model-capabilities.mjs +2 -2
- package/src/native-prediction-profile.mjs +5 -2
- package/src/native-prediction.mjs +18 -2
- package/src/optional-routes.mjs +1 -1
- package/src/prediction-control.mjs +64 -0
- package/src/prediction-operations.mjs +68 -0
- package/src/prediction-preference.mjs +75 -0
- package/src/privacy-model.mjs +35 -21
- package/src/privacy-transform.mjs +35 -4
- package/src/providers/m365.mjs +5 -2
- package/src/service-control.mjs +33 -7
- package/src/service-supervisor.mjs +39 -18
- package/src/service-worker.mjs +13 -1
- package/src/terminal-console.mjs +2 -2
- package/src/usage-analytics.mjs +6 -1
- package/src/usage-store.mjs +21 -8
- package/src/usage.mjs +18 -5
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
limit_default: ["Use default", "使用默认值"],
|
|
4
|
+
ccdx_prediction_app_open: ["Quit Codex, then continue setup here.", "请退出 Codex,再在此继续配置。"], feature_read_failed: ["Settings could not be read. Existing files were preserved.", "无法读取设置,原有文件已保留。"],
|
|
5
|
+
prediction_setup_again: ["Set up again", "重新配置"], prediction_bridge_missing: ["Not ready. Check and repair, or quit Codex and set up again.", "尚未就绪。请检查修复,或退出 Codex 后重新配置。"],
|
|
6
|
+
predictions_enable: ["Input suggestions", "输入建议"],
|
|
7
|
+
feature_continue: ["Continue setup", "继续配置"],
|
|
8
|
+
prediction_open: ["Open Codex", "打开 Codex"],
|
|
9
|
+
feature_remove: ["Remove setup", "移除接入"],
|
|
10
|
+
image_setup: ["Configure image generation", "配置图片生成"],
|
|
11
|
+
image_key_keep: ["Leave empty to keep the key for the same address.", "同一地址留空可保留原密钥。"],
|
|
12
|
+
update_install_now: ["Install update", "安装更新"],
|
|
13
|
+
advanced_terminal: ["Advanced: terminal commands", "高级:终端命令"],
|
|
14
|
+
compatibility_test: ["Test Codex model compatibility", "测试 Codex 模型兼容性"],
|
|
15
|
+
compatibility_scope: ["Tests Codex Responses, streaming and compaction. Uses quota.", "测试 Codex Responses、流式响应与压缩,会消耗用量。"],
|
|
16
|
+
advanced_limits: ["Advanced: request limits", "高级:请求限制"],
|
|
17
|
+
decoded_limit: ["Decoded request limit (MiB)", "解码后请求上限(MiB)"],
|
|
18
|
+
prediction_remove_confirm: ["Remove the CCDX prediction trust and route? Quit Codex to finish cleanup.", "移除 CCDX 预测信任与路由?退出 Codex 后才能完成清理。"],
|
|
19
|
+
image_remove_confirm: ["Remove the image service key and CCDX image integration?", "移除图片服务密钥与 CCDX 图片接入?"],
|
|
20
|
+
update_install_confirm: ["Install the latest stable release and switch CCDX when idle? Active work postpones the switch.", "安装最新稳定版并在空闲时切换 CCDX?有执行中的工作时会推迟切换。"],
|
|
21
|
+
image_models_ready: ["Models read. Choose a model, then save.", "已读取模型。选择模型后保存。"],
|
|
22
|
+
image_setup_saved: ["Image generation configured. Existing App tasks may need to refresh their tools.", "图片生成已配置。现有 App 任务可能需要刷新工具。"],
|
|
23
|
+
feature_unavailable: ["Restart the updated CCDX to use these controls.", "重启更新后的 CCDX 以使用这些控制。"],
|
|
24
|
+
prediction_quit_continue: ["Quit Codex, then continue setup here. No terminal command is needed.", "请退出 Codex,再在此继续配置。无需终端命令。"],
|
|
25
|
+
prediction_ready: ["Enabled. App and thread eligibility still apply.", "已开启。仍受 App 与会话适用条件限制。"],
|
|
26
|
+
prediction_disabled: ["Disabled. Cached suggestions may require a normal App restart to clear.", "已关闭。缓存建议可能需要正常重开 App 才会清除。"],
|
|
27
|
+
feature_pending: ["Waiting for Codex to close", "等待 Codex 退出"],
|
|
28
|
+
update_external_launch: ["This launch cannot update itself. Use the installer or the installed CCDX command.", "此启动方式无法自行更新。请使用安装器或已安装的 CCDX 命令。"],
|
|
29
|
+
update_idle_switch: ["Switches the service only when idle.", "仅在空闲时切换服务。"],
|
|
30
|
+
manual_update_checking: ["Checking the release…", "正在检查版本…"],
|
|
31
|
+
manual_update_preparing: ["Downloading and verifying…", "正在下载与验证…"],
|
|
32
|
+
manual_update_switching: ["Switching the service…", "正在切换服务…"],
|
|
33
|
+
manual_update_updated: ["Update completed.", "更新完成。"],
|
|
34
|
+
manual_update_current: ["Already current.", "已是最新版。"],
|
|
35
|
+
manual_update_deferred: ["Active work postponed this update. Try again when idle.", "执行中的工作推迟了更新。空闲后请重试。"],
|
|
36
|
+
manual_update_failed: ["Update failed; check the diagnostic report.", "更新失败,请查看诊断报告。"],
|
|
37
|
+
api_remove_source: ["Delete API", "删除 API"],
|
|
38
|
+
api_remove_source_confirm: ["Delete this disabled API and its saved key?", "删除此已停用 API 及其保存的密钥?"],
|
|
39
|
+
|
|
3
40
|
privacy_heading: ["ADVANCED", "高级"], privacy_enable: ["Local masking", "本地脱敏"], privacy_scope: ["Conversation and tool text. Images and predictions keep their current behavior.", "检查对话和工具文本。图片与预测保持原有行为。"], privacy_state_checking: ["On · checking locally", "已开启 · 本地检查中"],
|
|
4
41
|
privacy_personal: ["Include personal information", "同时保护个人信息"], privacy_personal_hint: ["Names and addresses may be mistaken for code.", "姓名和地址可能与代码混淆。"], privacy_try: ["Try locally", "本地试用"], privacy_sample: ["Sample text", "试用文本"], privacy_check: ["Check text", "检查文本"], privacy_remove: ["Delete model", "删除模型"],
|
|
5
42
|
privacy_download: ["Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.", "下载约 39 MB 模型及本地组件。检查可能增加等待或误识别。"], privacy_fail_closed: ["If a check cannot finish, the request is not sent.", "检查未完成时,请求不会发出。"], privacy_confirm: ["Download & enable", "下载并开启"],
|
|
@@ -265,6 +302,7 @@
|
|
|
265
302
|
"cap_field_parallel_tools": ["Parallel tool calls", "并行工具调用"],
|
|
266
303
|
"cap_field_streaming": ["Streaming", "流式输出"],
|
|
267
304
|
"cap_field_structured_output": ["Structured output", "结构化输出"],
|
|
305
|
+
"cap_field_mid_conversation_system": ["Native mid-conversation system messages", "原位中途系统消息"],
|
|
268
306
|
"cap_field_web_search": ["Native search APIs (messages, responses, chat)", "原生搜索接口(messages、responses、chat)"],
|
|
269
307
|
|
|
270
308
|
"api_add": ["Add API", "添加 API"],
|
|
@@ -356,8 +394,8 @@
|
|
|
356
394
|
"flow_count": ["{count} requests", "{count} 个请求"],
|
|
357
395
|
"flow_count_lower": ["≥{count} requests", "≥{count} 个请求"],
|
|
358
396
|
"flow_app_codex": ["Codex", "Codex"],
|
|
359
|
-
"prediction_first_setup": ["Quit Codex before first setup: ccdx prediction
|
|
360
|
-
"image_first_setup": ["First setup: ccdx
|
|
397
|
+
"prediction_first_setup": ["Quit Codex before first setup: ccdx app codex prediction setup", "首次配置前请退出 Codex:ccdx app codex prediction setup"],
|
|
398
|
+
"image_first_setup": ["First setup: ccdx app codex image setup", "首次配置:ccdx app codex image setup"],
|
|
361
399
|
"record_scope": ["Record scope", "记录范围"],
|
|
362
400
|
"estimated_percentiles": ["Approx. first-output P50 / P95", "首个输出 P50 / P95(约)"],
|
|
363
401
|
"percentile_values": ["{p50} / {p95} ms · {samples} samples", "{p50} / {p95} ms · {samples} 次样本"],
|
|
@@ -528,7 +566,7 @@
|
|
|
528
566
|
"bar_chart": ["Bar chart", "柱状图"],
|
|
529
567
|
"line_chart": ["Line chart", "曲线图"],
|
|
530
568
|
"approx_cache_hit_rate": ["Approx. cache hit rate", "粗略缓存命中率"],
|
|
531
|
-
"runtime_cache_hit_basis": ["Reused
|
|
569
|
+
"runtime_cache_hit_basis": ["Reused / input tokens from records with valid counts for both. ~ Partial coverage. — No valid input basis.", "仅按输入和缓存读取均有效的记录计算。\n~:覆盖不完整。—:没有有效的输入依据。"],
|
|
532
570
|
"provider_status_scope": ["Source and application status", "模型来源与应用状态"],
|
|
533
571
|
"version_updates": ["VERSION & UPDATES", "版本与更新"],
|
|
534
572
|
"copy_command": ["Copy command", "复制指令"],
|
|
@@ -741,7 +779,7 @@
|
|
|
741
779
|
"local_bridge": ["Local service", "本机服务"],
|
|
742
780
|
"client_route": ["App settings requests", "应用请求"],
|
|
743
781
|
"visible_candidate": ["Suggestion displayed", "建议显示"],
|
|
744
|
-
"configured_does_not_mean_displayed_use_ccdx_prediction_status_fo": ["Check suggestion status: ccdx prediction status", "检查建议状态:ccdx prediction status"],
|
|
782
|
+
"configured_does_not_mean_displayed_use_ccdx_prediction_status_fo": ["Check suggestion status: ccdx app codex prediction status", "检查建议状态:ccdx app codex prediction status"],
|
|
745
783
|
"enabled": ["Enabled", "已开启"],
|
|
746
784
|
"disabled": ["Disabled", "已关闭"],
|
|
747
785
|
"running_f4cca": ["Running", "运行中"],
|
|
@@ -855,11 +893,12 @@
|
|
|
855
893
|
"aggregating_local_usage_metadata": ["Counting local usage…", "正在统计本机用量。"],
|
|
856
894
|
"calls": ["REQUESTS", "请求次数"],
|
|
857
895
|
"input": ["INPUT USAGE", "输入用量"],
|
|
896
|
+
"cache_write": ["CACHE WRITE", "缓存写入"],
|
|
858
897
|
"cache_read": ["REUSED INPUT", "复用输入"],
|
|
859
898
|
"output": ["OUTPUT USAGE", "输出用量"],
|
|
860
899
|
"total": ["TOTAL", "总用量"],
|
|
861
900
|
"cache_hit": ["REUSE RATE", "复用比例"],
|
|
862
|
-
"cache_hit_recorded_cached_input_tokens_incomplete_history_unavai": ["Unit: Token. Reuse is included in input. ~ Partial; — Unknown.", "单位 Token
|
|
901
|
+
"cache_hit_recorded_cached_input_tokens_incomplete_history_unavai": ["Unit: Token. Reuse is included in input. Rate uses records with valid input and cache-read counts. ~ Partial coverage; — Unknown.", "单位 Token;复用已计入输入。比例仅按输入和缓存读取均有效的记录计算。~ 为覆盖不完整,— 为未知。"],
|
|
863
902
|
"usage_analytics": ["USAGE TRENDS", "用量趋势"],
|
|
864
903
|
"model_5e2c6": ["Model", "模型"],
|
|
865
904
|
"all_models": ["All models", "全部模型"],
|
|
@@ -901,7 +940,7 @@
|
|
|
901
940
|
"unconfirmed": ["NOT CONFIRMED", "未确认"],
|
|
902
941
|
"service_token_ttl_duration": ["Sign-in valid for {duration}", "登录信息剩余有效期:{duration}"],
|
|
903
942
|
"service_token_not_cached": ["No saved access details.", "暂无已保存的访问信息。"],
|
|
904
|
-
"source_source_live_ccdx_models": ["
|
|
943
|
+
"source_source_live_ccdx_models": ["Catalog source: {source}", "列表来源:{source}"],
|
|
905
944
|
"built_in": ["built-in list", "内置列表"],
|
|
906
945
|
"cache": ["existing list", "已有列表"],
|
|
907
946
|
"live": ["online list", "在线列表"],
|
|
@@ -912,7 +951,7 @@
|
|
|
912
951
|
"count_succeeded": ["{count} succeeded", "成功:{count}次"],
|
|
913
952
|
"not_initialized": ["NOT CONFIRMED", "未确认"],
|
|
914
953
|
"active_active_failed_failed_delivery_failures_delivery": ["Running: {active} / generation failed: {failed}\nFile delivery failed: {delivery}", "进行中:{active}/生成失败:{failed}\n文件交付失败:{delivery}"],
|
|
915
|
-
"setup_state_unknown_ccdx_image_status": ["
|
|
954
|
+
"setup_state_unknown_ccdx_image_status": ["Use Configure image generation below.", "请在下方配置图片生成。"],
|
|
916
955
|
"snapshot_time": ["Status updated {time}", "状态更新:{time}"],
|
|
917
956
|
"status_unavailable_check_ccdx_then_refresh": ["Cannot read status. Check CCDX and refresh.", "无法读取状态。\n请检查 CCDX 后刷新。"],
|
|
918
957
|
"count_retained_requests_events": ["{count} records retained", "保留:{count}条"],
|
|
@@ -979,13 +1018,13 @@
|
|
|
979
1018
|
"log_unavailable": ["READ FAILED", "读取失败"],
|
|
980
1019
|
"no_usage_summary_available": ["Cannot read usage records.", "无法读取用量记录。"],
|
|
981
1020
|
"analytics_unavailable_refresh_usage_to_retry": ["Trends unavailable. Refresh Model usage to retry.", "统计失败,请刷新用量。"],
|
|
982
|
-
"animation_settings_are_invalid_inspect_them_with_ccdx_animation": ["
|
|
983
|
-
"animation_setting_was_not_saved_check_ccdx_animation": ["
|
|
1021
|
+
"animation_settings_are_invalid_inspect_them_with_ccdx_animation": ["Animation setting is invalid. Choose a style here.", "动效设置无效,请在此重新选择样式。"],
|
|
1022
|
+
"animation_setting_was_not_saved_check_ccdx_animation": ["Animation was not saved. Check the selection and retry.", "动效未保存,请检查选择后重试。"],
|
|
984
1023
|
"could_not_read_local_usage_summary": ["Cannot read usage. Refresh to retry.", "无法读取用量,请刷新。"],
|
|
985
|
-
"live_model_lookup_timed_out_retry_or_run_ccdx_models": ["Model lookup timed out.
|
|
986
|
-
"github_token_not_found_start_ccdx_to_sign_in": ["
|
|
987
|
-
"live_model_lookup_failed_run_ccdx_models_for_details": ["Could not get models
|
|
988
|
-
"live_model_lookup_failed_http_status_run_ccdx_models_for_details": ["Model lookup failed: HTTP {status}
|
|
1024
|
+
"live_model_lookup_timed_out_retry_or_run_ccdx_models": ["Model lookup timed out. Refresh the selected source.", "模型查询超时,请刷新所选来源。"],
|
|
1025
|
+
"github_token_not_found_start_ccdx_to_sign_in": ["Sign in under Model sources → GitHub.", "请在模型来源 → GitHub 中登录。"],
|
|
1026
|
+
"live_model_lookup_failed_run_ccdx_models_for_details": ["Could not get models. Check the selected source.", "模型查询失败,请检查所选来源。"],
|
|
1027
|
+
"live_model_lookup_failed_http_status_run_ccdx_models_for_details": ["Model lookup failed: HTTP {status}. Check the selected source.", "模型查询失败:HTTP {status},请检查所选来源。"],
|
|
989
1028
|
"select_a_listed_animation_theme": ["Choose an animation from the list.", "请选择列表中的动效。"],
|
|
990
1029
|
"animation_changes_require_the_same_origin_dashboard": ["Save from this computer’s dashboard.", "请从本机面板保存动效。"],
|
|
991
1030
|
"animation_changes_require_application_json": ["Invalid save format.", "保存格式有误。"],
|
|
@@ -1059,8 +1098,8 @@
|
|
|
1059
1098
|
"Buffer limit MiB": "buffer_limit_mib",
|
|
1060
1099
|
"Apply limit": "apply_limit",
|
|
1061
1100
|
"Clear inactive buffer": "clear_inactive_buffer",
|
|
1062
|
-
"Pause keeps the provider configuration. Running calls can finish. First-time setup: ccdx
|
|
1063
|
-
"Pause keeps the existing trust and route. Codex may retain cached suggestions. First-time setup: quit Codex, then ccdx prediction
|
|
1101
|
+
"Pause keeps the provider configuration. Running calls can finish. First-time setup: ccdx app codex image setup.": "pause_keeps_the_provider_configuration_running_calls_can_finish_",
|
|
1102
|
+
"Pause keeps the existing trust and route. Codex may retain cached suggestions. First-time setup: quit Codex, then ccdx app codex prediction setup.": "pause_keeps_the_existing_trust_and_route_codex_may_retain_cached",
|
|
1064
1103
|
"SERVICE SETTINGS": "service_settings",
|
|
1065
1104
|
"Saved preference and effective state are separate. Environment overrides and client restarts are shown explicitly.": "saved_preference_and_effective_state_are_separate_environment_ov",
|
|
1066
1105
|
"Terminal animation": "terminal_animation",
|
|
@@ -1142,7 +1181,7 @@
|
|
|
1142
1181
|
"Local bridge": "local_bridge",
|
|
1143
1182
|
"Client route": "client_route",
|
|
1144
1183
|
"Visible candidate": "visible_candidate",
|
|
1145
|
-
"Configured does not mean displayed. Use ccdx prediction status for details.": "configured_does_not_mean_displayed_use_ccdx_prediction_status_fo",
|
|
1184
|
+
"Configured does not mean displayed. Use ccdx app codex prediction status for details.": "configured_does_not_mean_displayed_use_ccdx_prediction_status_fo",
|
|
1146
1185
|
"Enabled": "enabled",
|
|
1147
1186
|
"Disabled": "disabled",
|
|
1148
1187
|
"Running": "running_f4cca",
|
|
@@ -1395,6 +1434,11 @@
|
|
|
1395
1434
|
"GitHub token not found. Start ccdx to sign in.": "github_token_not_found_start_ccdx_to_sign_in",
|
|
1396
1435
|
"Live model lookup failed. Run ccdx models for details.": "live_model_lookup_failed_run_ccdx_models_for_details",
|
|
1397
1436
|
"Live model lookup failed (HTTP {status}). Run ccdx models for details.": "live_model_lookup_failed_http_status_run_ccdx_models_for_details",
|
|
1437
|
+
"Live model lookup timed out. Retry or run ccdx app codex models.": "live_model_lookup_timed_out_retry_or_run_ccdx_models",
|
|
1438
|
+
"Live model lookup failed. Run ccdx app codex models for details.": "live_model_lookup_failed_run_ccdx_models_for_details",
|
|
1439
|
+
"Live model lookup failed (HTTP {status}). Run ccdx app codex models for details.": "live_model_lookup_failed_http_status_run_ccdx_models_for_details",
|
|
1440
|
+
"Animation settings are invalid; inspect them with ccdx config animation": "animation_settings_are_invalid_inspect_them_with_ccdx_animation",
|
|
1441
|
+
"Animation setting was not saved; check ccdx config animation": "animation_setting_was_not_saved_check_ccdx_animation",
|
|
1398
1442
|
"Select a listed animation theme": "select_a_listed_animation_theme",
|
|
1399
1443
|
"Animation changes require the same-origin dashboard": "animation_changes_require_the_same_origin_dashboard",
|
|
1400
1444
|
"Animation changes require application/json": "animation_changes_require_application_json",
|
package/src/dashboard/tools.js
CHANGED
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
async function api(path, body) {
|
|
44
44
|
const response = await fetch(`/_ccdx/ui/${path}`, { method: body ? "POST" : "GET", cache: "no-store",
|
|
45
45
|
headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
|
|
46
|
-
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(35000) });
|
|
46
|
+
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(body?.action === "compatibility" ? 600000 : 35000) });
|
|
47
47
|
const data = await response.json();
|
|
48
48
|
if (!response.ok) throw Object.assign(new Error("tools_action_failed"), { code: data.code || "tools_action_failed" });
|
|
49
49
|
return data;
|
|
@@ -165,6 +165,8 @@
|
|
|
165
165
|
field(fields, "tools_backup", data.backup);
|
|
166
166
|
el("config-preview-details").textContent = data.checks.map(check => check.message).join("\n");
|
|
167
167
|
text("checks-note", "tools_review_repair");
|
|
168
|
+
} else if (action.action === "compatibility") {
|
|
169
|
+
el("compatibility-note").textContent = (data.checks || []).map(check => check.message).join(" · ");
|
|
168
170
|
} else if (action.action === "repair") {
|
|
169
171
|
el("config-repair-preview").hidden = true;repairPreview = null;
|
|
170
172
|
if (data.local?.checked_at) renderChecks(data.local);
|
|
@@ -181,6 +183,7 @@
|
|
|
181
183
|
for (const [id, action] of [["check-local", "check"], ["check-network", "network"], ["export-report", "report"], ["preview-config-repair", "preview"]]) {
|
|
182
184
|
el(id).addEventListener("click", () => void localAction({ action }, el(id)));
|
|
183
185
|
}
|
|
186
|
+
el("check-compatibility")?.addEventListener("click", () => { if (window.confirm(language.format("compatibility_scope"))) void localAction({ action: "compatibility", confirmed: true }, el("check-compatibility")); });
|
|
184
187
|
el("apply-config-repair").addEventListener("click", () => { if (repairPreview) void localAction({ action: "repair", revision: repairPreview.revision }, el("apply-config-repair")); });
|
|
185
188
|
el("cancel-config-repair").addEventListener("click", () => { repairPreview = null;el("config-repair-preview").hidden = true; });
|
|
186
189
|
el("check-account-link").addEventListener("click", () => { chooseProvider("github");location.hash = "models"; });
|
package/src/dashboard/ui.js
CHANGED
|
@@ -339,7 +339,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
339
339
|
if (!state.error) catalogReadDetails(evidence);
|
|
340
340
|
if (state.error) {
|
|
341
341
|
const message = String(state.error.message || state.error).slice(0, 240);
|
|
342
|
-
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
|
|
342
|
+
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx (?:app codex )?models for details\.$/.exec(message);
|
|
343
343
|
const sourceReason = /^Model catalog unavailable \/ (m365_[a-z0-9_]+)$/.exec(message);
|
|
344
344
|
const diagnostic = state.error.diagnostic || {}, network = diagnostic.network, catalog = diagnostic.catalog;
|
|
345
345
|
const reason = catalog ? phrase(`catalog_cause_${catalog.cause_code}`) : network ? phrase(`network_cause_${network.cause_code}`) : httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
|
package/src/dashboard/usage.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
function usageValues(row) {
|
|
12
12
|
const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
|
|
13
13
|
? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
|
|
14
|
-
return [row.model, number(row.requests), number(row.input_tokens), number(row.cache_read_tokens), number(row.output_tokens), number(row.total_tokens), rate];
|
|
14
|
+
return [row.model, number(row.requests), number(row.input_tokens), number(row.cache_read_tokens), number(row.cache_write_input_tokens), number(row.output_tokens), number(row.total_tokens), rate];
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
let usageData = null;
|
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
if (total.requests > 0) {
|
|
113
113
|
body.append(tableRow(usageValues(total), { total: true }));
|
|
114
114
|
for (const row of rows) body.append(tableRow(usageValues(row)));
|
|
115
|
-
} else { emptyTable("usage-body",
|
|
115
|
+
} else { emptyTable("usage-body", 8, "no_usage_records"); }
|
|
116
116
|
element("clear-usage-day").hidden = !day;
|
|
117
117
|
text("usage-state", day ? day.date : "local_log");
|
|
118
118
|
text("usage-note", "records_records_shown_of_models_models_shown_day", {
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -95,7 +95,12 @@ function usageRow(model, values) {
|
|
|
95
95
|
requests: finite(values.requests),
|
|
96
96
|
input_tokens: finite(values.input_tokens),
|
|
97
97
|
cache_read_tokens: cacheReadTokens(values) ?? null,
|
|
98
|
+
cache_write_input_tokens: values.cache_write_input_tokens ?? null,
|
|
98
99
|
cache_hit_rate: usageCacheHitRate(values),
|
|
100
|
+
cache_hit_known_requests: values.cache_hit_known_requests ?? null,
|
|
101
|
+
cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
|
|
102
|
+
cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
|
|
103
|
+
cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
|
|
99
104
|
cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
|
|
100
105
|
output_tokens: finite(values.output_tokens),
|
|
101
106
|
total_tokens: finite(values.total_tokens),
|
|
@@ -237,12 +242,12 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
237
242
|
if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 415, { error: "Expected application/json" });return; }
|
|
238
243
|
const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
|
|
239
244
|
try {
|
|
240
|
-
const input = await readJsonBody(req, { maxBodyBytes:
|
|
245
|
+
const input = await readJsonBody(req, { maxBodyBytes: 16384, maxDecodedBodyBytes: 16384, signal: abort.signal });
|
|
241
246
|
abort.clearTimeout();const data = await serviceControl.action(input);
|
|
242
247
|
if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
|
|
243
248
|
} catch (error) {
|
|
244
249
|
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300),
|
|
245
|
-
...(/^(?:m365_[a-z_]+|ccdx_settings_[a-z_]
|
|
250
|
+
...(/^(?:m365_[a-z_]+|ccdx_settings_[a-z_]+|ccdx_prediction_app_open)$/.test(error.code || "") ? { code: error.code } : {}) });
|
|
246
251
|
} finally { abort.cleanup(); }
|
|
247
252
|
return;
|
|
248
253
|
}
|
package/src/dashboard-tools.mjs
CHANGED
|
@@ -24,12 +24,13 @@ export function createDashboardTools(options = {}) {
|
|
|
24
24
|
const input = await readJsonBody(req, { maxBodyBytes: 4096, maxDecodedBodyBytes: 4096, signal: abort.signal });
|
|
25
25
|
abort.clearTimeout();
|
|
26
26
|
const fields = account ? { check: ["action"], start: ["action", "reauth"], cancel: ["action", "id"], logout: ["action", "confirmed"], reload: ["action"] }
|
|
27
|
-
: { check: ["action"], preview: ["action"], repair: ["action", "revision"], network: ["action"], report: ["action"] };
|
|
27
|
+
: { check: ["action"], preview: ["action"], repair: ["action", "revision"], network: ["action"], report: ["action"], compatibility: ["action", "confirmed"] };
|
|
28
28
|
const allowed = input && typeof input === "object" && !Array.isArray(input) && fields[input.action];
|
|
29
29
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key)) || (input.action === "start" && input.reauth !== undefined && typeof input.reauth !== "boolean")) {
|
|
30
30
|
sendJson(res, 400, { error: "tools_invalid_action", code: "tools_invalid_action" });return;
|
|
31
31
|
}
|
|
32
32
|
const target = account ? accounts : local;
|
|
33
|
+
if (input.action === "compatibility" && input.confirmed !== true) { sendJson(res, 400, { error: "Confirm model requests and quota use" });return; }
|
|
33
34
|
if (!account && input.action === "report" && !local.snapshot().checked_at) await local.check();
|
|
34
35
|
const value = await (input.action === "start" ? target.start({ reauth: input.reauth })
|
|
35
36
|
: input.action === "cancel" ? target.cancel(input.id) : input.action === "logout" ? target.logout(input)
|
package/src/dashboard.mjs
CHANGED
|
@@ -13,6 +13,7 @@ const ASSETS = new Map([
|
|
|
13
13
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
14
14
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
15
15
|
["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
|
|
16
|
+
["/features.js", ["./dashboard/features.js", "text/javascript; charset=utf-8"]],
|
|
16
17
|
["/preferences.js", ["./dashboard/preferences.js", "text/javascript; charset=utf-8"]],
|
|
17
18
|
["/time.js", ["./dashboard/time.js", "text/javascript; charset=utf-8"]],
|
|
18
19
|
["/view-boundary.js", ["./dashboard/view-boundary.js", "text/javascript; charset=utf-8"]],
|
package/src/doctor-compat.mjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
|
|
2
2
|
import { readBoundedResponseText } from "./upstream-body.mjs";
|
|
3
|
+
import { readClientGatewayKeys } from "./client-gateway-keys.mjs";
|
|
4
|
+
import { isLoopbackHost } from "./security.mjs";
|
|
5
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
6
|
|
|
4
7
|
function localGatewayBaseUrl(host, port) {
|
|
5
8
|
const normalized = host === "0.0.0.0" ? "127.0.0.1" : host === "::" ? "::1" : host;
|
|
@@ -20,10 +23,8 @@ export function selectCompatibilityModels(models) {
|
|
|
20
23
|
const candidates = copilotModelData(models)
|
|
21
24
|
.filter((model) => model?.model_picker_enabled !== false)
|
|
22
25
|
.filter((model) => {
|
|
23
|
-
const id = String(model?.id || "");
|
|
24
26
|
const endpoints = modelEndpoints(model);
|
|
25
|
-
return
|
|
26
|
-
&& (endpoints.includes("/responses") || endpoints.includes("/v1/responses"));
|
|
27
|
+
return endpoints.includes("/responses") || endpoints.includes("/v1/responses");
|
|
27
28
|
});
|
|
28
29
|
const responsesOnly = [...candidates].reverse()
|
|
29
30
|
.find((model) => !modelEndpoints(model).includes("/chat/completions"));
|
|
@@ -34,7 +35,7 @@ async function fetchTextWithTimeout(fetchImpl, url, init, timeoutMs) {
|
|
|
34
35
|
const controller = new AbortController();
|
|
35
36
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
36
37
|
try {
|
|
37
|
-
const resp = await fetchImpl(url, { ...init, signal: controller.signal });
|
|
38
|
+
const resp = await fetchImpl(url, { ...init, redirect: "error", signal: controller.signal });
|
|
38
39
|
return { resp, text: await readBoundedResponseText(resp, { maxBytes: 4 * 1024 * 1024, signal: controller.signal, label: "Doctor response" }) };
|
|
39
40
|
} finally {
|
|
40
41
|
clearTimeout(timer);
|
|
@@ -42,14 +43,14 @@ async function fetchTextWithTimeout(fetchImpl, url, init, timeoutMs) {
|
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
function responseFailure(resp, text) {
|
|
45
|
-
const detail = String(text || "").replace(/\s+/g, " ").trim().slice(0, 240);
|
|
46
|
+
const detail = redactDiagnosticText(String(text || "")).replace(/\s+/g, " ").trim().slice(0, 240);
|
|
46
47
|
return new Error(`HTTP ${resp.status}${detail ? `: ${detail}` : ""}`);
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
async function compatibilityRequest(fetchImpl, url, body, timeoutMs) {
|
|
50
|
+
async function compatibilityRequest(fetchImpl, url, body, timeoutMs, headers) {
|
|
50
51
|
const { resp, text } = await fetchTextWithTimeout(fetchImpl, url, {
|
|
51
52
|
method: "POST",
|
|
52
|
-
headers: { "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
|
|
53
|
+
headers: { ...headers, "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
|
|
53
54
|
body: JSON.stringify(body),
|
|
54
55
|
}, timeoutMs);
|
|
55
56
|
if (!resp.ok) throw responseFailure(resp, text);
|
|
@@ -92,11 +93,16 @@ export async function inspectAdapterCompatibility({
|
|
|
92
93
|
port = 2026,
|
|
93
94
|
fetchImpl = fetch,
|
|
94
95
|
timeoutMs = 120000,
|
|
96
|
+
home, env = process.env,
|
|
95
97
|
} = {}) {
|
|
96
98
|
const baseUrl = localGatewayBaseUrl(host, port);
|
|
99
|
+
let headers = {};
|
|
100
|
+
if (isLoopbackHost(new URL(baseUrl).hostname)) {
|
|
101
|
+
try { headers = { Authorization: `Bearer ${readClientGatewayKeys({ home, env, create: false }).codex}` }; } catch { /* Unconfigured credentials remain a normal access-check failure. */ }
|
|
102
|
+
}
|
|
97
103
|
const checks = [];
|
|
98
104
|
const models = await runCompatibilityCheck(checks, "Compatibility model discovery", async () => {
|
|
99
|
-
const { resp, text } = await fetchTextWithTimeout(fetchImpl, `${baseUrl}/v1/models`, { headers: { Accept: "application/json" } }, timeoutMs);
|
|
105
|
+
const { resp, text } = await fetchTextWithTimeout(fetchImpl, `${baseUrl}/v1/models`, { headers: { ...headers, Accept: "application/json" } }, timeoutMs);
|
|
100
106
|
if (!resp.ok) throw responseFailure(resp, text);
|
|
101
107
|
const parsed = JSON.parse(text);
|
|
102
108
|
if (!copilotModelData(parsed).length) throw new Error("model list is empty");
|
|
@@ -106,7 +112,7 @@ export async function inspectAdapterCompatibility({
|
|
|
106
112
|
|
|
107
113
|
const { responsesModel } = selectCompatibilityModels(models);
|
|
108
114
|
if (!responsesModel) {
|
|
109
|
-
checks.push({ kind: "err", message: "Compatibility Responses check failed: no
|
|
115
|
+
checks.push({ kind: "err", message: "Compatibility Responses check failed: no selected model advertises /responses" });
|
|
110
116
|
return checks;
|
|
111
117
|
}
|
|
112
118
|
|
|
@@ -115,7 +121,7 @@ export async function inspectAdapterCompatibility({
|
|
|
115
121
|
model: CODEX_AUTO_REVIEW_MODEL,
|
|
116
122
|
stream: false,
|
|
117
123
|
input: "Reply with OK only.",
|
|
118
|
-
}, timeoutMs);
|
|
124
|
+
}, timeoutMs, headers);
|
|
119
125
|
parseResponseObject(text);
|
|
120
126
|
});
|
|
121
127
|
|
|
@@ -124,7 +130,7 @@ export async function inspectAdapterCompatibility({
|
|
|
124
130
|
model: responsesModel,
|
|
125
131
|
stream: false,
|
|
126
132
|
input: "Reply with OK only.",
|
|
127
|
-
}, timeoutMs);
|
|
133
|
+
}, timeoutMs, headers);
|
|
128
134
|
return parseResponseObject(text);
|
|
129
135
|
});
|
|
130
136
|
|
|
@@ -135,7 +141,7 @@ export async function inspectAdapterCompatibility({
|
|
|
135
141
|
stream: true,
|
|
136
142
|
previous_response_id: firstResponse.id,
|
|
137
143
|
input: "Reply with OK again.",
|
|
138
|
-
}, timeoutMs);
|
|
144
|
+
}, timeoutMs, headers);
|
|
139
145
|
const events = text.split(/\r?\n\r?\n/).map(block => {
|
|
140
146
|
const data = block.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("\n");
|
|
141
147
|
try { return JSON.parse(data); } catch { return null; }
|
|
@@ -152,7 +158,7 @@ export async function inspectAdapterCompatibility({
|
|
|
152
158
|
model: responsesModel,
|
|
153
159
|
stream: false,
|
|
154
160
|
input: "Compact this short context.",
|
|
155
|
-
}, timeoutMs);
|
|
161
|
+
}, timeoutMs, headers);
|
|
156
162
|
parseCompactionResponse(text);
|
|
157
163
|
});
|
|
158
164
|
|
package/src/doctor.mjs
CHANGED
|
@@ -295,7 +295,7 @@ export async function collectDoctorChecks({
|
|
|
295
295
|
checks.push({ kind: "err", message: "Compatibility checks require a running, version-compatible codex-copilot-dx adapter" });
|
|
296
296
|
} else {
|
|
297
297
|
checks.push(...await inspectAdapterCompatibilityFn({
|
|
298
|
-
host,
|
|
298
|
+
home, env, host,
|
|
299
299
|
port,
|
|
300
300
|
fetchImpl,
|
|
301
301
|
timeoutMs: compatTimeoutMs,
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
4
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
5
|
+
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
6
|
+
import { computeImageMcpCodexConfig } from "./config.mjs";
|
|
7
|
+
import { updateImageSkill } from "./image-skill.mjs";
|
|
8
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
9
|
+
import { imageProviderConfigPath, inspectImageProvider, normalizeImageEndpoint, readImageProviderConfig, validateImageProviderConfig } from "./image-provider-config.mjs";
|
|
10
|
+
export function fileContent(filePath) {
|
|
11
|
+
try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(fs.readFileSync(filePath)); }
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error?.code === "ENOENT") return "";
|
|
14
|
+
if (error?.code === "ERR_ENCODING_INVALID_ENCODED_DATA") {
|
|
15
|
+
throw new Error("Codex configuration is not valid UTF-8 TOML; no configuration changes were written");
|
|
16
|
+
}
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function enableImageProvider(options) {
|
|
22
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => enableImageProviderUnlocked(options));
|
|
23
|
+
}
|
|
24
|
+
function enableImageProviderUnlocked({ providerConfig, providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
25
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
26
|
+
enabled: true,
|
|
27
|
+
adapterPort,
|
|
28
|
+
adapterHost,
|
|
29
|
+
});
|
|
30
|
+
const normalized = validateImageProviderConfig(providerConfig, { filePath: providerPath });
|
|
31
|
+
const skill = updateImageSkill({ enabled: true, codexPath, adapterPort, adapterHost });
|
|
32
|
+
try {
|
|
33
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
34
|
+
throw new Error("Codex configuration changed during image setup; retry to preserve the newer settings");
|
|
35
|
+
}
|
|
36
|
+
atomicWriteFilePairSync(
|
|
37
|
+
codexPath,
|
|
38
|
+
codex.content,
|
|
39
|
+
providerPath,
|
|
40
|
+
`${JSON.stringify(normalized, null, 2)}\n`,
|
|
41
|
+
{ mode: 0o600, writeFile: atomicWriteFileIfChangedSync },
|
|
42
|
+
);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
skill.rollback();
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return { codexChanged: codex.changed, config: normalized };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function disableImageProvider(options) {
|
|
51
|
+
if (!fs.existsSync(options.codexPath)) return disableImageProviderUnlocked(options);
|
|
52
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => disableImageProviderUnlocked(options));
|
|
53
|
+
}
|
|
54
|
+
function disableImageProviderUnlocked({ providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
55
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
56
|
+
enabled: false,
|
|
57
|
+
adapterPort,
|
|
58
|
+
adapterHost,
|
|
59
|
+
});
|
|
60
|
+
const providerExists = fs.existsSync(providerPath);
|
|
61
|
+
const skill = updateImageSkill({ enabled: false, codexPath, adapterPort, adapterHost });
|
|
62
|
+
try {
|
|
63
|
+
if (fs.existsSync(codexPath)) {
|
|
64
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
65
|
+
throw new Error("Codex configuration changed during image cleanup; retry to preserve the newer settings");
|
|
66
|
+
}
|
|
67
|
+
atomicWriteFilePairSync(codexPath, codex.content, providerPath, null, {
|
|
68
|
+
mode: 0o600, writeFile: atomicWriteFileIfChangedSync,
|
|
69
|
+
});
|
|
70
|
+
} else if (providerExists) {
|
|
71
|
+
fs.unlinkSync(providerPath);
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
skill.rollback();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
return { changed: providerExists || codex.changed || skill.changed, preservedGuidance: Boolean(skill.preserved) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function syncEnabledImageSkill({ home = os.homedir(), env = process.env, codexPath = codexPaths({ env, home }).config, ...options } = {}) {
|
|
81
|
+
return updateImageSkill({ ...options, enabled: true, codexPath });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
export function imageSetupSummary(options = {}) {
|
|
86
|
+
const value = readImageProviderConfig({ ...options, strict: true });
|
|
87
|
+
if (!value) return { configured: false };
|
|
88
|
+
const endpoint = new URL(value.endpoint);
|
|
89
|
+
return { configured: true, endpoint: endpoint.origin + endpoint.pathname, model: value.model, protocol: value.protocol };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function configureImageSetup({ operation, endpoint, key, model }, options = {}) {
|
|
93
|
+
const { env = process.env, home = os.homedir(), adapterPort = 2026, adapterHost = "127.0.0.1", fetchImpl = fetch } = options;
|
|
94
|
+
const codexPath = codexPaths({ env, home }).config, providerPath = imageProviderConfigPath({ env, home });
|
|
95
|
+
if (operation === "remove") return { configured: false, ...disableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost }) };
|
|
96
|
+
if (!["inspect", "setup"].includes(operation)) throw new Error("Choose image inspect, setup or remove");
|
|
97
|
+
const current = readImageProviderConfig({ env, home, strict: true });
|
|
98
|
+
const normalized = normalizeImageEndpoint(endpoint || current?.endpoint);
|
|
99
|
+
const sameOrigin = current && new URL(normalized).origin === new URL(current.endpoint).origin;
|
|
100
|
+
const apiKey = String(key || "").trim() || (sameOrigin ? current.api_key : "");
|
|
101
|
+
if (!apiKey) throw new Error("Enter an image API key for this address");
|
|
102
|
+
const inspected = await inspectImageProvider({ endpoint: normalized, apiKey, fetchImpl,
|
|
103
|
+
selectModel: ids => model || (ids.includes(current?.model) ? current.model : ids[0]) });
|
|
104
|
+
if (operation === "inspect") return { endpoint: inspected.endpoint, models: inspected.modelIds, protocol: inspected.protocol };
|
|
105
|
+
if (!model || !inspected.modelIds.includes(model)) throw new Error("Choose a listed image model");
|
|
106
|
+
enableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost,
|
|
107
|
+
providerConfig: { endpoint: inspected.endpoint, api_key: apiKey, model, protocol: inspected.protocol } });
|
|
108
|
+
if (!servicePreferences({ env, home }).image_enabled) writeServicePreference("image_enabled", true, { env, home });
|
|
109
|
+
return imageSetupSummary({ env, home });
|
|
110
|
+
}
|
package/src/local-privacy.mjs
CHANGED
|
@@ -6,12 +6,13 @@ import { withFileLockSync } from "./lock.mjs";
|
|
|
6
6
|
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
7
7
|
import { createChangeSignal } from "./activity-events.mjs";
|
|
8
8
|
import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
|
|
9
|
-
import { maskPrivacyRequest, protectPrivacyResponse } from "./privacy-transform.mjs";
|
|
9
|
+
import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache } from "./privacy-transform.mjs";
|
|
10
10
|
import { markRequestObservation } from "./stream-performance.mjs";
|
|
11
11
|
|
|
12
12
|
export function createLocalPrivacy(options = {}) {
|
|
13
13
|
const changes = createChangeSignal(), secret = randomBytes(32), cache = new Map(), flights = new Map(), responses = new WeakMap(), policies = new WeakMap();
|
|
14
14
|
const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
|
|
15
|
+
const rules = createPrivacyRuleCache();
|
|
15
16
|
let cacheBytes = 0, generation = 0, pending = null, disposed = false;
|
|
16
17
|
let keyLoaded = false, actionError = null;
|
|
17
18
|
const settings = () => {
|
|
@@ -19,7 +20,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
19
20
|
return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
|
|
20
21
|
};
|
|
21
22
|
const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
|
|
22
|
-
const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
|
|
23
|
+
const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, rule_cache: rules.stats(), ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
|
|
23
24
|
function loadKey() {
|
|
24
25
|
if (keyLoaded) return;
|
|
25
26
|
const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
@@ -37,18 +38,21 @@ export function createLocalPrivacy(options = {}) {
|
|
|
37
38
|
});changes.changed();
|
|
38
39
|
}
|
|
39
40
|
async function find(texts, { signal } = {}) {
|
|
40
|
-
const waiting = [], fresh = [], entries = [];
|
|
41
|
+
const waiting = [], fresh = [], entries = [], batches = new Set();
|
|
42
|
+
const batch = { controller: new AbortController(), waiters: 0, settled: false };
|
|
41
43
|
for (const text of texts) {
|
|
42
44
|
const key = createHash("sha256").update(text).digest("hex");
|
|
43
45
|
if (cache.has(key)) {
|
|
44
46
|
const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
|
|
45
|
-
} else if (flights.has(key)
|
|
47
|
+
} else if (flights.has(key) && !flights.get(key).batch.controller.signal.aborted) { const entry = flights.get(key);waiting.push(entry.promise);batches.add(entry.batch); }
|
|
46
48
|
else {
|
|
47
|
-
const entry = Promise.withResolvers();entry.key = key;flights.set(key, entry);
|
|
49
|
+
const entry = Promise.withResolvers();entry.key = key;entry.batch = batch;flights.set(key, entry);batches.add(batch);
|
|
48
50
|
waiting.push(entry.promise);fresh.push(text);entries.push(entry);
|
|
49
51
|
}
|
|
50
52
|
}
|
|
51
|
-
|
|
53
|
+
for (const work of batches) work.waiters++;
|
|
54
|
+
if (fresh.length) void model.find(fresh, { signal: batch.controller.signal }).then(found => {
|
|
55
|
+
if (batch.controller.signal.aborted) throw privacyFailure("cancelled");
|
|
52
56
|
if (!Array.isArray(found) || found.length !== fresh.length) throw privacyFailure("engine_invalid");
|
|
53
57
|
for (let i = 0; i < found.length; i++) {
|
|
54
58
|
const cost = Buffer.byteLength(JSON.stringify(found[i] || [])) + 128, entry = entries[i];
|
|
@@ -59,11 +63,11 @@ export function createLocalPrivacy(options = {}) {
|
|
|
59
63
|
}
|
|
60
64
|
entry.resolve(found[i] || []);
|
|
61
65
|
}
|
|
62
|
-
}).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }));
|
|
66
|
+
}).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => { batch.settled = true;entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }); });
|
|
63
67
|
let listener;
|
|
64
68
|
const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
|
|
65
69
|
try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
|
|
66
|
-
finally { signal?.removeEventListener("abort", listener); }
|
|
70
|
+
finally { signal?.removeEventListener("abort", listener);for (const work of batches) if (--work.waiters === 0 && !work.settled) work.controller.abort(privacyFailure("cancelled")); }
|
|
67
71
|
}
|
|
68
72
|
async function prepare(body, { protocol, client, signal, res, policy } = {}) {
|
|
69
73
|
const saved = policy || settings();if (!saved.enabled) return body;
|
|
@@ -71,7 +75,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
71
75
|
loadKey();
|
|
72
76
|
const start = performance.now();
|
|
73
77
|
const deadline = AbortSignal.timeout(15000);let session;
|
|
74
|
-
try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
|
|
78
|
+
try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
|
|
75
79
|
catch (error) { if (deadline.aborted && !signal?.aborted) throw privacyFailure("check_timeout");throw error; }
|
|
76
80
|
if (signal?.aborted) { session.release();throw signal.reason; }
|
|
77
81
|
markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
|
|
@@ -107,7 +111,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
107
111
|
const current = ++generation;
|
|
108
112
|
const work = (async () => {
|
|
109
113
|
actionError = null;loadKey();
|
|
110
|
-
if (!await model.installed()) await model.download();
|
|
114
|
+
if (!await model.installed({ current: true })) await model.download();
|
|
111
115
|
if (current !== generation) return;
|
|
112
116
|
await model.load();if (current !== generation) return;
|
|
113
117
|
save({ privacy_enabled: true }, input.revision);
|
|
@@ -132,5 +136,5 @@ export function createLocalPrivacy(options = {}) {
|
|
|
132
136
|
},
|
|
133
137
|
restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
|
|
134
138
|
settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
|
|
135
|
-
close() { disposed = true;generation++;model.close();cache.clear();cacheBytes = 0;secret.fill(0); } };
|
|
139
|
+
close() { disposed = true;generation++;model.close();cache.clear();rules.clear();cacheBytes = 0;secret.fill(0); } };
|
|
136
140
|
}
|