codexmate 0.0.31 → 0.0.32

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 (145) hide show
  1. package/README.md +363 -363
  2. package/README.zh.md +371 -371
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +324 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -69
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -150
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/zip-commands.js +510 -510
  23. package/cli.js +15829 -15778
  24. package/lib/automation.js +404 -404
  25. package/lib/cli-file-utils.js +151 -151
  26. package/lib/cli-models-utils.js +440 -440
  27. package/lib/cli-network-utils.js +190 -190
  28. package/lib/cli-path-utils.js +85 -85
  29. package/lib/cli-session-utils.js +121 -121
  30. package/lib/cli-sessions.js +426 -417
  31. package/lib/cli-utils.js +155 -155
  32. package/lib/cli-webhook.js +126 -126
  33. package/lib/download-artifacts.js +92 -92
  34. package/lib/mcp-stdio.js +453 -453
  35. package/lib/task-orchestrator.js +869 -869
  36. package/lib/text-diff.js +303 -303
  37. package/lib/workflow-engine.js +340 -340
  38. package/package.json +76 -76
  39. package/plugins/README.md +20 -20
  40. package/plugins/README.zh-CN.md +20 -20
  41. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  42. package/plugins/prompt-templates/computed.mjs +253 -253
  43. package/plugins/prompt-templates/index.mjs +8 -8
  44. package/plugins/prompt-templates/manifest.mjs +15 -15
  45. package/plugins/prompt-templates/methods.mjs +553 -553
  46. package/plugins/prompt-templates/overview.mjs +91 -91
  47. package/plugins/prompt-templates/ownership.mjs +19 -19
  48. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  49. package/plugins/prompt-templates/storage.mjs +64 -64
  50. package/plugins/registry.mjs +16 -16
  51. package/web-ui/app.js +647 -646
  52. package/web-ui/index.html +36 -36
  53. package/web-ui/logic.agents-diff.mjs +386 -386
  54. package/web-ui/logic.claude.mjs +168 -168
  55. package/web-ui/logic.codex.mjs +69 -69
  56. package/web-ui/logic.mjs +5 -5
  57. package/web-ui/logic.runtime.mjs +128 -128
  58. package/web-ui/logic.session-convert.mjs +70 -70
  59. package/web-ui/logic.sessions.mjs +781 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  62. package/web-ui/modules/app.computed.index.mjs +17 -17
  63. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  64. package/web-ui/modules/app.computed.session.mjs +693 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +651 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +861 -841
  69. package/web-ui/modules/app.methods.index.mjs +94 -94
  70. package/web-ui/modules/app.methods.install.mjs +205 -205
  71. package/web-ui/modules/app.methods.navigation.mjs +774 -774
  72. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  73. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  74. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  75. package/web-ui/modules/app.methods.providers.mjs +529 -529
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  78. package/web-ui/modules/app.methods.session-browser.mjs +1012 -984
  79. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  80. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  81. package/web-ui/modules/app.methods.startup-claude.mjs +537 -534
  82. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  83. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  84. package/web-ui/modules/config-mode.computed.mjs +124 -124
  85. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  86. package/web-ui/modules/i18n.dict.mjs +3177 -3174
  87. package/web-ui/modules/i18n.mjs +62 -62
  88. package/web-ui/modules/plugins.computed.mjs +3 -3
  89. package/web-ui/modules/plugins.methods.mjs +3 -3
  90. package/web-ui/modules/plugins.storage.mjs +11 -11
  91. package/web-ui/modules/provider-url-display.mjs +17 -17
  92. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  93. package/web-ui/modules/skills.computed.mjs +107 -107
  94. package/web-ui/modules/skills.methods.mjs +482 -482
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +503 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +185 -174
  98. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  99. package/web-ui/partials/index/modal-health-check.html +45 -45
  100. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  101. package/web-ui/partials/index/modal-skills.html +200 -200
  102. package/web-ui/partials/index/modals-basic.html +162 -162
  103. package/web-ui/partials/index/panel-config-claude.html +136 -194
  104. package/web-ui/partials/index/panel-config-codex.html +197 -357
  105. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  106. package/web-ui/partials/index/panel-dashboard.html +219 -219
  107. package/web-ui/partials/index/panel-docs.html +115 -147
  108. package/web-ui/partials/index/panel-market.html +177 -177
  109. package/web-ui/partials/index/panel-orchestration.html +391 -391
  110. package/web-ui/partials/index/panel-plugins.html +253 -253
  111. package/web-ui/partials/index/panel-sessions.html +313 -302
  112. package/web-ui/partials/index/panel-settings.html +190 -190
  113. package/web-ui/partials/index/panel-trash.html +83 -88
  114. package/web-ui/partials/index/panel-usage.html +138 -371
  115. package/web-ui/res/json5.min.js +1 -1
  116. package/web-ui/res/vue.global.prod.js +13 -13
  117. package/web-ui/session-helpers.mjs +591 -591
  118. package/web-ui/source-bundle.cjs +233 -233
  119. package/web-ui/styles/base-theme.css +281 -281
  120. package/web-ui/styles/bridge-pool.css +197 -197
  121. package/web-ui/styles/controls-forms.css +433 -422
  122. package/web-ui/styles/dashboard.css +406 -406
  123. package/web-ui/styles/docs-panel.css +245 -271
  124. package/web-ui/styles/feedback.css +108 -108
  125. package/web-ui/styles/health-check-dialog.css +144 -144
  126. package/web-ui/styles/layout-shell.css +638 -626
  127. package/web-ui/styles/modals-core.css +466 -466
  128. package/web-ui/styles/navigation-panels.css +391 -391
  129. package/web-ui/styles/openclaw-structured.css +266 -266
  130. package/web-ui/styles/plugins-panel.css +564 -564
  131. package/web-ui/styles/responsive.css +392 -454
  132. package/web-ui/styles/sessions-list.css +647 -417
  133. package/web-ui/styles/sessions-preview.css +407 -407
  134. package/web-ui/styles/sessions-toolbar-trash.css +518 -348
  135. package/web-ui/styles/sessions-usage.css +588 -1040
  136. package/web-ui/styles/settings-panel.css +349 -349
  137. package/web-ui/styles/skills-list.css +305 -305
  138. package/web-ui/styles/skills-market.css +429 -429
  139. package/web-ui/styles/task-orchestration.css +822 -822
  140. package/web-ui/styles/titles-cards.css +472 -472
  141. package/web-ui/styles/trash-panel.css +90 -90
  142. package/web-ui/styles/webhook.css +81 -81
  143. package/web-ui/styles.css +24 -24
  144. package/web-ui.html +17 -17
  145. package/web-ui/partials/index/panel-config-codex.html.bak +0 -337
@@ -1,903 +1,903 @@
1
- function normalizeSeverity(value) {
2
- const normalized = String(value || '').trim().toLowerCase();
3
- if (normalized === 'error' || normalized === 'critical') return 'error';
4
- if (normalized === 'warn' || normalized === 'warning') return 'warn';
5
- return 'info';
6
- }
7
-
8
- function normalizeLang(value) {
9
- const normalized = String(value || '').trim().toLowerCase();
10
- if (!normalized) return '';
11
- if (normalized === 'zh' || normalized.startsWith('zh-') || normalized.startsWith('zh_') || normalized.includes('chinese')) {
12
- return 'zh';
13
- }
14
- return 'en';
15
- }
16
-
17
- const DOCTOR_I18N = Object.freeze({
18
- en: Object.freeze({
19
- severity: Object.freeze({
20
- error: 'Error',
21
- warn: 'Warning',
22
- info: 'Info'
23
- }),
24
- area: Object.freeze({
25
- Doctor: 'Doctor',
26
- Config: 'Config',
27
- Observe: 'Observe',
28
- Operate: 'Operate',
29
- Reuse: 'Reuse'
30
- }),
31
- issue: Object.freeze({
32
- configNotReady: Object.freeze({
33
- problem: 'Config is not ready',
34
- impact: 'Provider/model cannot be read; model listing and requests may fail.'
35
- }),
36
- providerUnreachable: Object.freeze({
37
- impactAuth: 'Auth failure will cause model listing and chat requests to return 401/403.',
38
- impactNetwork: 'Unreachable provider will cause model listing and chat requests to fail or timeout.',
39
- message: Object.freeze({
40
- 'remote-model-probe-unreachable': 'Provider unreachable',
41
- 'remote-model-probe-auth-failed': 'Provider auth failed',
42
- 'remote-model-probe-not-found': 'Provider endpoint returned 404',
43
- 'remote-model-probe-http-error': 'Provider returned HTTP error',
44
- 'remote-model-probe-error': 'Provider probe failed'
45
- })
46
- }),
47
- configHealthFailed: Object.freeze({
48
- problem: 'Config health check failed',
49
- impact: 'Some features may be unavailable or behave unexpectedly.'
50
- }),
51
- usageError: Object.freeze({
52
- problem: 'Usage aggregation failed',
53
- impact: 'Usage charts and summaries may be unavailable; Doctor usage diagnostics will be incomplete.'
54
- }),
55
- usageMissingModel: Object.freeze({
56
- problem: 'Some sessions miss model metadata',
57
- impact: 'Usage attribution and cost estimates may be inaccurate.'
58
- }),
59
- tasksError: Object.freeze({
60
- problem: 'Task overview failed',
61
- impact: 'Task queue and run history may be unavailable.'
62
- }),
63
- tasksFailed: Object.freeze({
64
- problem: 'Failed task runs detected',
65
- impact: 'Automation pipelines may be blocked; inspect logs and retry after fixing inputs.'
66
- }),
67
- skillsError: Object.freeze({
68
- problem: 'Skills listing failed',
69
- impact: 'Skills marketplace may be unavailable.'
70
- }),
71
- skillsRootMissing: Object.freeze({
72
- problem: 'Skills directory is missing',
73
- impact: 'Skills install/scan will be empty; create the directory via Settings/Docs.'
74
- }),
75
- skillsMissingFiles: Object.freeze({
76
- problem: 'Some skills are missing skill.json',
77
- impact: 'Those skills may not run or sync properly.'
78
- })
79
- }),
80
- action: Object.freeze({
81
- openConfig: 'Open Config',
82
- checkProvider: 'Check provider config',
83
- openUsage: 'Open Usage',
84
- openSessions: 'Open Sessions',
85
- openTasks: 'Open Tasks',
86
- viewTaskLogs: 'View Tasks / Logs',
87
- openSkills: 'Open Skills'
88
- }),
89
- markdown: Object.freeze({
90
- title: 'Codexmate Doctor Report',
91
- generated: 'Generated',
92
- status: 'Status',
93
- statusOk: 'OK',
94
- statusNotOk: 'NOT OK',
95
- issues: 'Issues',
96
- noIssues: 'No actionable issues found.',
97
- issuesTitle: 'Issues',
98
- area: 'Area',
99
- impact: 'Impact',
100
- actions: 'Actions',
101
- open: 'Open',
102
- recheck: 'Re-check: run doctor again',
103
- export: Object.freeze({
104
- json: 'Export: doctor.json',
105
- md: 'Export: doctor.md'
106
- })
107
- })
108
- }),
109
- zh: Object.freeze({
110
- severity: Object.freeze({
111
- error: '严重',
112
- warn: '警告',
113
- info: '提示'
114
- }),
115
- area: Object.freeze({
116
- Doctor: 'Doctor',
117
- Config: '配置',
118
- Observe: '观测',
119
- Operate: '操作',
120
- Reuse: '复用'
121
- }),
122
- issue: Object.freeze({
123
- configNotReady: Object.freeze({
124
- problem: '配置文件未就绪',
125
- impact: '可能导致 provider/model 无法读取,模型列表与请求将不可用。'
126
- }),
127
- providerUnreachable: Object.freeze({
128
- impactAuth: '鉴权失败会导致模型列表/对话请求返回 401/403。',
129
- impactNetwork: '远端不可达会导致模型列表/对话请求失败或超时。',
130
- message: Object.freeze({
131
- 'remote-model-probe-unreachable': 'Provider 不可达',
132
- 'remote-model-probe-auth-failed': 'Provider 鉴权失败',
133
- 'remote-model-probe-not-found': 'Provider 返回 404',
134
- 'remote-model-probe-http-error': 'Provider 返回 HTTP 错误',
135
- 'remote-model-probe-error': 'Provider 探测失败'
136
- })
137
- }),
138
- configHealthFailed: Object.freeze({
139
- problem: '配置健康检查未通过',
140
- impact: '可能导致部分功能不可用或行为不符合预期。'
141
- }),
142
- usageError: Object.freeze({
143
- problem: 'Usage 统计异常',
144
- impact: 'Usage 页面可能无法展示趋势/汇总,Doctor 的用量诊断也会缺失。'
145
- }),
146
- usageMissingModel: Object.freeze({
147
- problem: '部分会话缺少模型信息',
148
- impact: '会导致用量归因与成本估算不准确。'
149
- }),
150
- tasksError: Object.freeze({
151
- problem: 'Tasks 状态读取失败',
152
- impact: '可能导致编排队列/运行记录无法展示。'
153
- }),
154
- tasksFailed: Object.freeze({
155
- problem: '存在失败的任务运行',
156
- impact: '可能导致自动化流水线中断,需要查看日志并重试或修复输入。'
157
- }),
158
- skillsError: Object.freeze({
159
- problem: 'Skills 列表读取失败',
160
- impact: '会导致 Skills 页面无法正常展示或安装。'
161
- }),
162
- skillsRootMissing: Object.freeze({
163
- problem: 'Skills 目录不存在',
164
- impact: '会导致 Skills 安装/扫描为空;可在 Settings/Docs 按指引初始化目录。'
165
- }),
166
- skillsMissingFiles: Object.freeze({
167
- problem: '存在缺失 skill.json 的技能',
168
- impact: '会导致部分技能无法被运行或同步。'
169
- })
170
- }),
171
- action: Object.freeze({
172
- openConfig: '打开 Config',
173
- checkProvider: '检查 Provider 配置',
174
- openUsage: '打开 Usage',
175
- openSessions: '打开 Sessions',
176
- openTasks: '打开 Tasks',
177
- viewTaskLogs: '查看 Tasks / Logs',
178
- openSkills: '打开 Skills'
179
- }),
180
- markdown: Object.freeze({
181
- title: 'Codexmate Doctor 报告',
182
- generated: '生成时间',
183
- status: '状态',
184
- statusOk: '通过',
185
- statusNotOk: '未通过',
186
- issues: '问题数',
187
- noIssues: '暂无可操作问题。',
188
- issuesTitle: '问题列表',
189
- area: '模块',
190
- impact: '影响',
191
- actions: '动作',
192
- open: '打开',
193
- recheck: '复检:重新运行 doctor',
194
- export: Object.freeze({
195
- json: '导出:doctor.json',
196
- md: '导出:doctor.md'
197
- })
198
- })
199
- })
200
- });
201
-
202
- function getI18n(lang) {
203
- const normalized = normalizeLang(lang);
204
- if (normalized === 'en') return DOCTOR_I18N.en;
205
- if (normalized === 'zh') return DOCTOR_I18N.zh;
206
- return DOCTOR_I18N.zh;
207
- }
208
-
209
- function buildIssue(id, severity, problem, impact, actions = [], data = null, meta = null) {
210
- const safeMeta = meta && typeof meta === 'object' ? meta : {};
211
- return {
212
- id: String(id || '').trim() || 'unknown',
213
- severity: normalizeSeverity(severity),
214
- areaKey: typeof safeMeta.areaKey === 'string' && safeMeta.areaKey.trim() ? safeMeta.areaKey.trim() : 'Doctor',
215
- area: typeof safeMeta.area === 'string' && safeMeta.area.trim() ? safeMeta.area.trim() : 'Doctor',
216
- severityLabel: typeof safeMeta.severityLabel === 'string' && safeMeta.severityLabel.trim() ? safeMeta.severityLabel.trim() : '',
217
- problemKey: typeof safeMeta.problemKey === 'string' && safeMeta.problemKey.trim() ? safeMeta.problemKey.trim() : '',
218
- problemParams: safeMeta.problemParams && typeof safeMeta.problemParams === 'object' ? safeMeta.problemParams : null,
219
- impactKey: typeof safeMeta.impactKey === 'string' && safeMeta.impactKey.trim() ? safeMeta.impactKey.trim() : '',
220
- impactParams: safeMeta.impactParams && typeof safeMeta.impactParams === 'object' ? safeMeta.impactParams : null,
221
- impactTags: Array.isArray(safeMeta.impactTags) ? safeMeta.impactTags.filter(Boolean) : [],
222
- impactScope: typeof safeMeta.impactScope === 'string' && safeMeta.impactScope.trim() ? safeMeta.impactScope.trim() : '',
223
- problem: String(problem || '').trim(),
224
- impact: String(impact || '').trim(),
225
- actions: Array.isArray(actions) ? actions : [],
226
- evidence: data && typeof data === 'object' ? data : null,
227
- data: data && typeof data === 'object' ? data : null
228
- };
229
- }
230
-
231
- function buildAction(type, payload = {}) {
232
- const normalizedType = String(type || '').trim();
233
- const safePayload = payload && typeof payload === 'object' ? payload : {};
234
- return {
235
- type: normalizedType,
236
- ...safePayload
237
- };
238
- }
239
-
240
- function findConfigHealthRemoteIssue(issues = []) {
241
- const list = Array.isArray(issues) ? issues : [];
242
- const remoteCodes = new Set([
243
- 'remote-model-probe-unreachable',
244
- 'remote-model-probe-auth-failed',
245
- 'remote-model-probe-not-found',
246
- 'remote-model-probe-http-error',
247
- 'remote-model-probe-error'
248
- ]);
249
- return list.find((issue) => issue && typeof issue.code === 'string' && remoteCodes.has(issue.code)) || null;
250
- }
251
-
252
- function summarizeSkillsIssues(payload) {
253
- const safe = payload && typeof payload === 'object' ? payload : {};
254
- const exists = safe.exists !== false;
255
- const items = Array.isArray(safe.items) ? safe.items : [];
256
- const missing = items.filter((item) => item && item.hasSkillFile === false).length;
257
- return { exists, total: items.length, missing, root: safe.root || '' };
258
- }
259
-
260
- function summarizeUsageIssues(sessions = []) {
261
- const list = Array.isArray(sessions) ? sessions : [];
262
- let missingModel = 0;
263
- for (const session of list) {
264
- if (!session || typeof session !== 'object') continue;
265
- const model = typeof session.model === 'string' ? session.model.trim() : '';
266
- if (!model) missingModel += 1;
267
- }
268
- return { total: list.length, missingModel };
269
- }
270
-
271
- function summarizeTaskIssues(taskOverview) {
272
- const safe = taskOverview && typeof taskOverview === 'object' ? taskOverview : {};
273
- const queue = Array.isArray(safe.queue) ? safe.queue : [];
274
- const runs = Array.isArray(safe.runs) ? safe.runs : [];
275
- const failedRuns = runs.filter((run) => {
276
- if (!run || typeof run !== 'object') return false;
277
- const status = String(run.status || '').trim().toLowerCase();
278
- return status === 'failed' || status === 'blocked' || status === 'cancelled';
279
- });
280
- const runningRuns = runs.filter((run) => {
281
- if (!run || typeof run !== 'object') return false;
282
- const status = String(run.status || '').trim().toLowerCase();
283
- return status === 'running' || status === 'queued';
284
- });
285
- return {
286
- queue: queue.length,
287
- runs: runs.length,
288
- running: runningRuns.length,
289
- failed: failedRuns.length,
290
- latestFailed: failedRuns.length ? failedRuns[0] : null
291
- };
292
- }
293
-
294
- function buildDefaultActions() {
295
- return [
296
- buildAction('run-check', { id: 'doctor' }),
297
- buildAction('export', { format: 'json' }),
298
- buildAction('export', { format: 'md' })
299
- ];
300
- }
301
-
302
- function ensureBaseActions(actions = []) {
303
- const list = Array.isArray(actions) ? [...actions] : [];
304
- const hasRun = list.some((item) => item && item.type === 'run-check');
305
- const hasExportJson = list.some((item) => item && item.type === 'export' && item.format === 'json');
306
- const hasExportMd = list.some((item) => item && item.type === 'export' && (item.format === 'md' || item.format === 'markdown'));
307
- if (!hasRun) {
308
- list.push(buildAction('run-check', { id: 'doctor' }));
309
- }
310
- if (!hasExportJson) {
311
- list.push(buildAction('export', { format: 'json' }));
312
- }
313
- if (!hasExportMd) {
314
- list.push(buildAction('export', { format: 'md' }));
315
- }
316
- return list;
317
- }
318
-
319
- function severityRank(severity) {
320
- const normalized = normalizeSeverity(severity);
321
- if (normalized === 'error') return 0;
322
- if (normalized === 'warn') return 1;
323
- return 2;
324
- }
325
-
326
- function issuePriorityRank(id) {
327
- const order = [
328
- 'config-not-ready',
329
- 'provider-unreachable',
330
- 'config-health-failed',
331
- 'usage-error',
332
- 'tasks-error',
333
- 'tasks-failed',
334
- 'skills-error',
335
- 'skills-root-missing',
336
- 'skills-missing-files',
337
- 'usage-missing-model'
338
- ];
339
- const key = String(id || '').trim();
340
- const index = order.indexOf(key);
341
- return index >= 0 ? index : 999;
342
- }
343
-
344
- function sortIssues(issues = []) {
345
- const list = Array.isArray(issues) ? [...issues] : [];
346
- list.sort((a, b) => {
347
- const rankA = severityRank(a && a.severity);
348
- const rankB = severityRank(b && b.severity);
349
- if (rankA !== rankB) return rankA - rankB;
350
- const priA = issuePriorityRank(a && a.id);
351
- const priB = issuePriorityRank(b && b.id);
352
- if (priA !== priB) return priA - priB;
353
- const idA = String(a && a.id || '');
354
- const idB = String(b && b.id || '');
355
- return idA.localeCompare(idB, 'en-US');
356
- });
357
- return list;
358
- }
359
-
360
- function renderDoctorMarkdown(report) {
361
- const safe = report && typeof report === 'object' ? report : {};
362
- const i18n = getI18n(safe.lang);
363
- const summary = safe.summary && typeof safe.summary === 'object' ? safe.summary : { total: 0, error: 0, warn: 0, info: 0 };
364
- const issues = Array.isArray(safe.issues) ? safe.issues : [];
365
- const lines = [];
366
- lines.push(`# ${i18n.markdown.title}`);
367
- lines.push('');
368
- lines.push(`- ${i18n.markdown.generated}: ${safe.generatedAt || ''}`);
369
- lines.push(`- ${i18n.markdown.status}: ${safe.ok ? i18n.markdown.statusOk : i18n.markdown.statusNotOk}`);
370
- lines.push(`- ${i18n.markdown.issues}: ${summary.total || 0} (${i18n.severity.error} ${summary.error || 0}, ${i18n.severity.warn} ${summary.warn || 0}, ${i18n.severity.info} ${summary.info || 0})`);
371
- lines.push('');
372
- if (!issues.length) {
373
- lines.push(i18n.markdown.noIssues);
374
- lines.push('');
375
- return lines.join('\n');
376
- }
377
- lines.push(`## ${i18n.markdown.issuesTitle}`);
378
- lines.push('');
379
- for (const issue of issues) {
380
- if (!issue || typeof issue !== 'object') continue;
381
- const severityLabel = issue.severityLabel || (i18n.severity[normalizeSeverity(issue.severity)] || String(issue.severity || '').toUpperCase());
382
- const header = `### [${severityLabel}] ${issue.problem || issue.id || ''}`;
383
- lines.push(header);
384
- if (issue.area) {
385
- lines.push(`- ${i18n.markdown.area}: ${issue.area}`);
386
- }
387
- if (issue.impact) {
388
- lines.push(`- ${i18n.markdown.impact}: ${issue.impact}`);
389
- }
390
- const actions = Array.isArray(issue.actions) ? issue.actions : [];
391
- if (actions.length) {
392
- lines.push(`- ${i18n.markdown.actions}:`);
393
- for (const action of actions) {
394
- if (!action || typeof action !== 'object') continue;
395
- if (action.type === 'navigate') {
396
- lines.push(` - ${i18n.markdown.open}: ${action.label || action.target || ''}`);
397
- continue;
398
- }
399
- if (action.type === 'run-check') {
400
- lines.push(` - ${i18n.markdown.recheck}`);
401
- continue;
402
- }
403
- if (action.type === 'export') {
404
- const fmt = action.format === 'md' ? 'md' : 'json';
405
- lines.push(` - ${fmt === 'md' ? i18n.markdown.export.md : i18n.markdown.export.json}`);
406
- continue;
407
- }
408
- lines.push(` - ${action.type}`);
409
- }
410
- }
411
- lines.push('');
412
- }
413
- return lines.join('\n');
414
- }
415
-
416
- function decorateIssue(issue, lang) {
417
- if (!issue || typeof issue !== 'object') return issue;
418
- const i18n = getI18n(lang);
419
- const areaKey = typeof issue.areaKey === 'string' && issue.areaKey.trim() ? issue.areaKey.trim() : 'Doctor';
420
- issue.areaKey = areaKey;
421
- issue.area = i18n.area[areaKey] || areaKey;
422
- issue.severity = normalizeSeverity(issue.severity);
423
- issue.severityLabel = i18n.severity[issue.severity] || issue.severityLabel || issue.severity;
424
- return issue;
425
- }
426
-
427
- function resolveProviderProblemText(i18n, remoteIssue) {
428
- const code = remoteIssue && typeof remoteIssue.code === 'string' ? remoteIssue.code : '';
429
- const mapped = code && i18n.issue.providerUnreachable.message
430
- ? i18n.issue.providerUnreachable.message[code]
431
- : '';
432
- if (mapped) return mapped;
433
- const fallback = i18n === DOCTOR_I18N.en ? 'Provider unreachable' : 'Provider 不可用';
434
- return fallback;
435
- }
436
-
437
- function buildNavigateAction(target, labelKey, label, labelParams = null) {
438
- return buildAction('navigate', {
439
- target,
440
- labelKey: String(labelKey || '').trim(),
441
- labelParams: labelParams && typeof labelParams === 'object' ? labelParams : null,
442
- label: String(label || '').trim()
443
- });
444
- }
445
-
446
- function buildIssueKeyMap() {
447
- return {
448
- configNotReady: {
449
- problemKey: 'doctor.issue.configNotReady.problem',
450
- impactKey: 'doctor.issue.configNotReady.impact'
451
- },
452
- providerUnreachable: {
453
- problemKeyPrefix: 'doctor.issue.providerUnreachable.problem.',
454
- impactAuthKey: 'doctor.issue.providerUnreachable.impactAuth',
455
- impactNetworkKey: 'doctor.issue.providerUnreachable.impactNetwork'
456
- },
457
- configHealthFailed: {
458
- problemKey: 'doctor.issue.configHealthFailed.problem',
459
- impactKey: 'doctor.issue.configHealthFailed.impact'
460
- },
461
- usageError: {
462
- problemKey: 'doctor.issue.usageError.problem',
463
- impactKey: 'doctor.issue.usageError.impact'
464
- },
465
- usageMissingModel: {
466
- problemKey: 'doctor.issue.usageMissingModel.problem',
467
- impactKey: 'doctor.issue.usageMissingModel.impact'
468
- },
469
- tasksError: {
470
- problemKey: 'doctor.issue.tasksError.problem',
471
- impactKey: 'doctor.issue.tasksError.impact'
472
- },
473
- tasksFailed: {
474
- problemKey: 'doctor.issue.tasksFailed.problem',
475
- impactKey: 'doctor.issue.tasksFailed.impact'
476
- },
477
- skillsError: {
478
- problemKey: 'doctor.issue.skillsError.problem',
479
- impactKey: 'doctor.issue.skillsError.impact'
480
- },
481
- skillsRootMissing: {
482
- problemKey: 'doctor.issue.skillsRootMissing.problem',
483
- impactKey: 'doctor.issue.skillsRootMissing.impact'
484
- },
485
- skillsMissingFiles: {
486
- problemKey: 'doctor.issue.skillsMissingFiles.problem',
487
- impactKey: 'doctor.issue.skillsMissingFiles.impact'
488
- }
489
- };
490
- }
491
-
492
- const ISSUE_KEYS = Object.freeze(buildIssueKeyMap());
493
-
494
- function resolveProviderProblemKey(code) {
495
- const normalized = String(code || '').trim();
496
- const suffix = normalized || 'unknown';
497
- return `${ISSUE_KEYS.providerUnreachable.problemKeyPrefix}${suffix}`;
498
- }
499
-
500
- function runChecks(context, checks = []) {
501
- const list = Array.isArray(checks) ? checks : [];
502
- const issues = [];
503
- for (const check of list) {
504
- if (typeof check !== 'function') continue;
505
- const result = check(context);
506
- if (!result) continue;
507
- if (Array.isArray(result)) {
508
- issues.push(...result.filter(Boolean));
509
- continue;
510
- }
511
- issues.push(result);
512
- }
513
- return issues;
514
- }
515
-
516
- async function buildDoctorReport(params = {}, deps = {}) {
517
- const options = params && typeof params === 'object' ? params : {};
518
- const resolvedLang = normalizeLang(options.lang) || normalizeLang(process.env.LANG) || 'zh';
519
- const i18n = getI18n(resolvedLang);
520
- const now = new Date().toISOString();
521
- const getStatusPayload = typeof deps.getStatusPayload === 'function' ? deps.getStatusPayload : () => null;
522
- const buildInstallStatusReport = typeof deps.buildInstallStatusReport === 'function' ? deps.buildInstallStatusReport : () => null;
523
- const buildConfigHealthReport = typeof deps.buildConfigHealthReport === 'function' ? deps.buildConfigHealthReport : null;
524
- const listSessionUsage = typeof deps.listSessionUsage === 'function' ? deps.listSessionUsage : null;
525
- const buildTaskOverviewPayload = typeof deps.buildTaskOverviewPayload === 'function' ? deps.buildTaskOverviewPayload : null;
526
- const listSkills = typeof deps.listSkills === 'function' ? deps.listSkills : null;
527
-
528
- const sources = {
529
- status: null,
530
- install: null,
531
- configHealth: null,
532
- usage: null,
533
- tasks: null,
534
- skills: null
535
- };
536
-
537
- sources.status = getStatusPayload();
538
- if (options.includeInstall !== false) {
539
- sources.install = buildInstallStatusReport();
540
- }
541
-
542
- if (buildConfigHealthReport) {
543
- try {
544
- sources.configHealth = await buildConfigHealthReport({
545
- remote: options.remote !== false
546
- });
547
- } catch (e) {
548
- sources.configHealth = { ok: false, error: e && e.message ? e.message : 'config health check failed', issues: [] };
549
- }
550
- }
551
-
552
- if (listSessionUsage && options.includeUsage !== false) {
553
- try {
554
- const range = typeof options.range === 'string' ? options.range.trim().toLowerCase() : '';
555
- const limit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
556
- const sessions = await listSessionUsage({
557
- source: 'all',
558
- limit
559
- });
560
- const summary = summarizeUsageIssues(sessions);
561
- sources.usage = {
562
- range: range === 'all' ? 'all' : (range === '30d' ? '30d' : '7d'),
563
- summary,
564
- sample: (Array.isArray(sessions) ? sessions : [])
565
- .slice(0, 10)
566
- .map((session) => ({
567
- source: session && session.source ? session.source : '',
568
- sessionId: session && session.sessionId ? session.sessionId : '',
569
- updatedAt: session && session.updatedAt ? session.updatedAt : '',
570
- model: session && session.model ? session.model : '',
571
- provider: session && session.provider ? session.provider : '',
572
- messageCount: session && session.messageCount ? session.messageCount : 0,
573
- totalTokens: session && session.totalTokens ? session.totalTokens : 0
574
- }))
575
- };
576
- } catch (e) {
577
- sources.usage = { error: e && e.message ? e.message : 'usage probe failed', range: '7d', summary: { total: 0, missingModel: 0 } };
578
- }
579
- }
580
-
581
- if (buildTaskOverviewPayload && options.includeTasks !== false) {
582
- try {
583
- const overview = buildTaskOverviewPayload({
584
- queueLimit: 20,
585
- runLimit: 20
586
- });
587
- sources.tasks = {
588
- summary: summarizeTaskIssues(overview),
589
- warnings: Array.isArray(overview && overview.warnings) ? overview.warnings : []
590
- };
591
- } catch (e) {
592
- sources.tasks = { error: e && e.message ? e.message : 'task overview failed' };
593
- }
594
- }
595
-
596
- if (listSkills && options.includeSkills !== false) {
597
- const targetApp = typeof options.targetApp === 'string' && options.targetApp.trim()
598
- ? options.targetApp.trim().toLowerCase()
599
- : 'codex';
600
- try {
601
- const raw = listSkills({ targetApp });
602
- const summary = summarizeSkillsIssues(raw);
603
- sources.skills = { targetApp, summary };
604
- } catch (e) {
605
- sources.skills = { error: e && e.message ? e.message : 'skills probe failed', targetApp };
606
- }
607
- }
608
-
609
- const status = sources.status && typeof sources.status === 'object' ? sources.status : {};
610
- const baseActions = buildDefaultActions();
611
- const context = {
612
- options,
613
- sources,
614
- status,
615
- baseActions,
616
- i18n
617
- };
618
-
619
- const issues = runChecks(context, [
620
- (ctx) => {
621
- if (ctx.status.configReady !== false && !(typeof ctx.status.configErrorType === 'string' && ctx.status.configErrorType.trim())) {
622
- return null;
623
- }
624
- return buildIssue(
625
- 'config-not-ready',
626
- 'error',
627
- ctx.i18n.issue.configNotReady.problem,
628
- ctx.i18n.issue.configNotReady.impact,
629
- ensureBaseActions([
630
- buildNavigateAction('config', 'doctor.action.openConfig', ctx.i18n.action.openConfig)
631
- ].concat(ctx.baseActions)),
632
- {
633
- configErrorType: ctx.status.configErrorType || '',
634
- configNotice: ctx.status.configNotice || ''
635
- },
636
- {
637
- areaKey: 'Config',
638
- problemKey: ISSUE_KEYS.configNotReady.problemKey,
639
- impactKey: ISSUE_KEYS.configNotReady.impactKey,
640
- impactTags: ['blocked'],
641
- impactScope: 'config'
642
- }
643
- );
644
- },
645
- (ctx) => {
646
- const configHealth = ctx.sources.configHealth && typeof ctx.sources.configHealth === 'object' ? ctx.sources.configHealth : null;
647
- if (!configHealth || configHealth.ok !== false) {
648
- return null;
649
- }
650
- const remoteIssue = findConfigHealthRemoteIssue(configHealth.issues || []);
651
- if (remoteIssue) {
652
- const impactKey = remoteIssue.code === 'remote-model-probe-auth-failed'
653
- ? ISSUE_KEYS.providerUnreachable.impactAuthKey
654
- : ISSUE_KEYS.providerUnreachable.impactNetworkKey;
655
- const impact = remoteIssue.code === 'remote-model-probe-auth-failed'
656
- ? ctx.i18n.issue.providerUnreachable.impactAuth
657
- : ctx.i18n.issue.providerUnreachable.impactNetwork;
658
- return buildIssue(
659
- 'provider-unreachable',
660
- 'error',
661
- resolveProviderProblemText(ctx.i18n, remoteIssue),
662
- impact,
663
- ensureBaseActions([
664
- buildNavigateAction('config', 'doctor.action.checkProvider', ctx.i18n.action.checkProvider)
665
- ].concat(ctx.baseActions)),
666
- { code: remoteIssue.code || '', statusCode: remoteIssue.statusCode || 0 },
667
- {
668
- areaKey: 'Config',
669
- problemKey: resolveProviderProblemKey(remoteIssue.code),
670
- impactKey,
671
- impactTags: ['blocked', 'network'],
672
- impactScope: 'provider'
673
- }
674
- );
675
- }
676
- if (Array.isArray(configHealth.issues) && configHealth.issues.length) {
677
- return buildIssue(
678
- 'config-health-failed',
679
- 'warn',
680
- ctx.i18n.issue.configHealthFailed.problem,
681
- ctx.i18n.issue.configHealthFailed.impact,
682
- ensureBaseActions([
683
- buildNavigateAction('config', 'doctor.action.openConfig', ctx.i18n.action.openConfig)
684
- ].concat(ctx.baseActions)),
685
- { issueCount: configHealth.issues.length },
686
- {
687
- areaKey: 'Config',
688
- problemKey: ISSUE_KEYS.configHealthFailed.problemKey,
689
- impactKey: ISSUE_KEYS.configHealthFailed.impactKey,
690
- impactTags: ['degraded'],
691
- impactScope: 'config'
692
- }
693
- );
694
- }
695
- return null;
696
- },
697
- (ctx) => {
698
- if (!ctx.sources.usage || typeof ctx.sources.usage !== 'object') return null;
699
- if (ctx.sources.usage.error) {
700
- return buildIssue(
701
- 'usage-error',
702
- 'warn',
703
- ctx.i18n.issue.usageError.problem,
704
- ctx.i18n.issue.usageError.impact,
705
- ensureBaseActions([
706
- buildNavigateAction('usage', 'doctor.action.openUsage', ctx.i18n.action.openUsage)
707
- ].concat(ctx.baseActions)),
708
- { error: ctx.sources.usage.error },
709
- {
710
- areaKey: 'Observe',
711
- problemKey: ISSUE_KEYS.usageError.problemKey,
712
- impactKey: ISSUE_KEYS.usageError.impactKey,
713
- impactTags: ['degraded'],
714
- impactScope: 'observe'
715
- }
716
- );
717
- }
718
- const summary = ctx.sources.usage.summary && typeof ctx.sources.usage.summary === 'object' ? ctx.sources.usage.summary : { total: 0, missingModel: 0 };
719
- if (Number(summary.missingModel || 0) <= 0) return null;
720
- return buildIssue(
721
- 'usage-missing-model',
722
- 'info',
723
- ctx.i18n.issue.usageMissingModel.problem,
724
- ctx.i18n.issue.usageMissingModel.impact,
725
- ensureBaseActions([
726
- buildNavigateAction('usage', 'doctor.action.openUsage', ctx.i18n.action.openUsage),
727
- buildNavigateAction('sessions', 'doctor.action.openSessions', ctx.i18n.action.openSessions)
728
- ].concat(ctx.baseActions)),
729
- summary,
730
- {
731
- areaKey: 'Observe',
732
- problemKey: ISSUE_KEYS.usageMissingModel.problemKey,
733
- impactKey: ISSUE_KEYS.usageMissingModel.impactKey,
734
- impactTags: ['data-quality'],
735
- impactScope: 'observe'
736
- }
737
- );
738
- },
739
- (ctx) => {
740
- if (!ctx.sources.tasks || typeof ctx.sources.tasks !== 'object') return null;
741
- if (ctx.sources.tasks.error) {
742
- return buildIssue(
743
- 'tasks-error',
744
- 'warn',
745
- ctx.i18n.issue.tasksError.problem,
746
- ctx.i18n.issue.tasksError.impact,
747
- ensureBaseActions([
748
- buildNavigateAction('orchestration', 'doctor.action.openTasks', ctx.i18n.action.openTasks)
749
- ].concat(ctx.baseActions)),
750
- { error: ctx.sources.tasks.error },
751
- {
752
- areaKey: 'Operate',
753
- problemKey: ISSUE_KEYS.tasksError.problemKey,
754
- impactKey: ISSUE_KEYS.tasksError.impactKey,
755
- impactTags: ['degraded'],
756
- impactScope: 'operate'
757
- }
758
- );
759
- }
760
- const summary = ctx.sources.tasks.summary && typeof ctx.sources.tasks.summary === 'object'
761
- ? ctx.sources.tasks.summary
762
- : summarizeTaskIssues(ctx.sources.tasks);
763
- if (Number(summary.failed || 0) <= 0) return null;
764
- return buildIssue(
765
- 'tasks-failed',
766
- 'warn',
767
- ctx.i18n.issue.tasksFailed.problem,
768
- ctx.i18n.issue.tasksFailed.impact,
769
- ensureBaseActions([
770
- buildNavigateAction('orchestration', 'doctor.action.viewTaskLogs', ctx.i18n.action.viewTaskLogs)
771
- ].concat(ctx.baseActions)),
772
- {
773
- failed: summary.failed || 0,
774
- latestFailed: summary.latestFailed
775
- ? {
776
- runId: summary.latestFailed.runId || '',
777
- status: summary.latestFailed.status || '',
778
- error: summary.latestFailed.error || ''
779
- }
780
- : null
781
- },
782
- {
783
- areaKey: 'Operate',
784
- problemKey: ISSUE_KEYS.tasksFailed.problemKey,
785
- impactKey: ISSUE_KEYS.tasksFailed.impactKey,
786
- impactTags: ['blocked'],
787
- impactScope: 'operate'
788
- }
789
- );
790
- },
791
- (ctx) => {
792
- if (!ctx.sources.skills || typeof ctx.sources.skills !== 'object') return null;
793
- if (ctx.sources.skills.error) {
794
- return buildIssue(
795
- 'skills-error',
796
- 'warn',
797
- ctx.i18n.issue.skillsError.problem,
798
- ctx.i18n.issue.skillsError.impact,
799
- ensureBaseActions([
800
- buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
801
- ].concat(ctx.baseActions)),
802
- { error: ctx.sources.skills.error },
803
- {
804
- areaKey: 'Reuse',
805
- problemKey: ISSUE_KEYS.skillsError.problemKey,
806
- impactKey: ISSUE_KEYS.skillsError.impactKey,
807
- impactTags: ['degraded'],
808
- impactScope: 'reuse'
809
- }
810
- );
811
- }
812
- const summary = ctx.sources.skills.summary && typeof ctx.sources.skills.summary === 'object'
813
- ? ctx.sources.skills.summary
814
- : summarizeSkillsIssues(ctx.sources.skills);
815
- if (!summary.exists) {
816
- return buildIssue(
817
- 'skills-root-missing',
818
- 'info',
819
- ctx.i18n.issue.skillsRootMissing.problem,
820
- ctx.i18n.issue.skillsRootMissing.impact,
821
- ensureBaseActions([
822
- buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
823
- ].concat(ctx.baseActions)),
824
- summary,
825
- {
826
- areaKey: 'Reuse',
827
- problemKey: ISSUE_KEYS.skillsRootMissing.problemKey,
828
- impactKey: ISSUE_KEYS.skillsRootMissing.impactKey,
829
- impactTags: ['degraded'],
830
- impactScope: 'reuse'
831
- }
832
- );
833
- }
834
- if (Number(summary.missing || 0) > 0) {
835
- return buildIssue(
836
- 'skills-missing-files',
837
- 'info',
838
- ctx.i18n.issue.skillsMissingFiles.problem,
839
- ctx.i18n.issue.skillsMissingFiles.impact,
840
- ensureBaseActions([
841
- buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
842
- ].concat(ctx.baseActions)),
843
- summary,
844
- {
845
- areaKey: 'Reuse',
846
- problemKey: ISSUE_KEYS.skillsMissingFiles.problemKey,
847
- impactKey: ISSUE_KEYS.skillsMissingFiles.impactKey,
848
- impactTags: ['data-quality'],
849
- impactScope: 'reuse'
850
- }
851
- );
852
- }
853
- return null;
854
- }
855
- ]);
856
-
857
- const sortedIssues = sortIssues(issues);
858
- sortedIssues.forEach((issue) => decorateIssue(issue, resolvedLang));
859
- const hasError = sortedIssues.some((item) => item && item.severity === 'error');
860
- const report = {
861
- schema: 1,
862
- generatedAt: now,
863
- lang: resolvedLang,
864
- ok: !hasError,
865
- issues: sortedIssues,
866
- sources
867
- };
868
- report.summary = {
869
- total: sortedIssues.length,
870
- error: sortedIssues.filter((item) => item.severity === 'error').length,
871
- warn: sortedIssues.filter((item) => item.severity === 'warn').length,
872
- info: sortedIssues.filter((item) => item.severity === 'info').length
873
- };
874
- return report;
875
- }
876
-
877
- function buildDoctorLegacyPayload(report) {
878
- const safe = report && typeof report === 'object' ? report : {};
879
- const issues = Array.isArray(safe.issues) ? safe.issues : [];
880
- const legacyIssues = issues
881
- .map((item) => ({
882
- code: item && item.id ? item.id : 'unknown',
883
- message: item && item.problem ? item.problem : ''
884
- }))
885
- .filter((item) => item.message);
886
- const configHealth = safe.sources && safe.sources.configHealth && typeof safe.sources.configHealth === 'object'
887
- ? safe.sources.configHealth
888
- : null;
889
- const remote = configHealth && configHealth.remote ? configHealth.remote : null;
890
- return {
891
- ok: safe.ok !== false,
892
- issues: legacyIssues,
893
- remote,
894
- report: safe
895
- };
896
- }
897
-
898
- module.exports = {
899
- buildDoctorReport,
900
- buildDoctorLegacyPayload,
901
- renderDoctorMarkdown,
902
- buildAction
903
- };
1
+ function normalizeSeverity(value) {
2
+ const normalized = String(value || '').trim().toLowerCase();
3
+ if (normalized === 'error' || normalized === 'critical') return 'error';
4
+ if (normalized === 'warn' || normalized === 'warning') return 'warn';
5
+ return 'info';
6
+ }
7
+
8
+ function normalizeLang(value) {
9
+ const normalized = String(value || '').trim().toLowerCase();
10
+ if (!normalized) return '';
11
+ if (normalized === 'zh' || normalized.startsWith('zh-') || normalized.startsWith('zh_') || normalized.includes('chinese')) {
12
+ return 'zh';
13
+ }
14
+ return 'en';
15
+ }
16
+
17
+ const DOCTOR_I18N = Object.freeze({
18
+ en: Object.freeze({
19
+ severity: Object.freeze({
20
+ error: 'Error',
21
+ warn: 'Warning',
22
+ info: 'Info'
23
+ }),
24
+ area: Object.freeze({
25
+ Doctor: 'Doctor',
26
+ Config: 'Config',
27
+ Observe: 'Observe',
28
+ Operate: 'Operate',
29
+ Reuse: 'Reuse'
30
+ }),
31
+ issue: Object.freeze({
32
+ configNotReady: Object.freeze({
33
+ problem: 'Config is not ready',
34
+ impact: 'Provider/model cannot be read; model listing and requests may fail.'
35
+ }),
36
+ providerUnreachable: Object.freeze({
37
+ impactAuth: 'Auth failure will cause model listing and chat requests to return 401/403.',
38
+ impactNetwork: 'Unreachable provider will cause model listing and chat requests to fail or timeout.',
39
+ message: Object.freeze({
40
+ 'remote-model-probe-unreachable': 'Provider unreachable',
41
+ 'remote-model-probe-auth-failed': 'Provider auth failed',
42
+ 'remote-model-probe-not-found': 'Provider endpoint returned 404',
43
+ 'remote-model-probe-http-error': 'Provider returned HTTP error',
44
+ 'remote-model-probe-error': 'Provider probe failed'
45
+ })
46
+ }),
47
+ configHealthFailed: Object.freeze({
48
+ problem: 'Config health check failed',
49
+ impact: 'Some features may be unavailable or behave unexpectedly.'
50
+ }),
51
+ usageError: Object.freeze({
52
+ problem: 'Usage aggregation failed',
53
+ impact: 'Usage charts and summaries may be unavailable; Doctor usage diagnostics will be incomplete.'
54
+ }),
55
+ usageMissingModel: Object.freeze({
56
+ problem: 'Some sessions miss model metadata',
57
+ impact: 'Usage attribution and cost estimates may be inaccurate.'
58
+ }),
59
+ tasksError: Object.freeze({
60
+ problem: 'Task overview failed',
61
+ impact: 'Task queue and run history may be unavailable.'
62
+ }),
63
+ tasksFailed: Object.freeze({
64
+ problem: 'Failed task runs detected',
65
+ impact: 'Automation pipelines may be blocked; inspect logs and retry after fixing inputs.'
66
+ }),
67
+ skillsError: Object.freeze({
68
+ problem: 'Skills listing failed',
69
+ impact: 'Skills marketplace may be unavailable.'
70
+ }),
71
+ skillsRootMissing: Object.freeze({
72
+ problem: 'Skills directory is missing',
73
+ impact: 'Skills install/scan will be empty; create the directory via Settings/Docs.'
74
+ }),
75
+ skillsMissingFiles: Object.freeze({
76
+ problem: 'Some skills are missing skill.json',
77
+ impact: 'Those skills may not run or sync properly.'
78
+ })
79
+ }),
80
+ action: Object.freeze({
81
+ openConfig: 'Open Config',
82
+ checkProvider: 'Check provider config',
83
+ openUsage: 'Open Usage',
84
+ openSessions: 'Open Sessions',
85
+ openTasks: 'Open Tasks',
86
+ viewTaskLogs: 'View Tasks / Logs',
87
+ openSkills: 'Open Skills'
88
+ }),
89
+ markdown: Object.freeze({
90
+ title: 'Codexmate Doctor Report',
91
+ generated: 'Generated',
92
+ status: 'Status',
93
+ statusOk: 'OK',
94
+ statusNotOk: 'NOT OK',
95
+ issues: 'Issues',
96
+ noIssues: 'No actionable issues found.',
97
+ issuesTitle: 'Issues',
98
+ area: 'Area',
99
+ impact: 'Impact',
100
+ actions: 'Actions',
101
+ open: 'Open',
102
+ recheck: 'Re-check: run doctor again',
103
+ export: Object.freeze({
104
+ json: 'Export: doctor.json',
105
+ md: 'Export: doctor.md'
106
+ })
107
+ })
108
+ }),
109
+ zh: Object.freeze({
110
+ severity: Object.freeze({
111
+ error: '严重',
112
+ warn: '警告',
113
+ info: '提示'
114
+ }),
115
+ area: Object.freeze({
116
+ Doctor: 'Doctor',
117
+ Config: '配置',
118
+ Observe: '观测',
119
+ Operate: '操作',
120
+ Reuse: '复用'
121
+ }),
122
+ issue: Object.freeze({
123
+ configNotReady: Object.freeze({
124
+ problem: '配置文件未就绪',
125
+ impact: '可能导致 provider/model 无法读取,模型列表与请求将不可用。'
126
+ }),
127
+ providerUnreachable: Object.freeze({
128
+ impactAuth: '鉴权失败会导致模型列表/对话请求返回 401/403。',
129
+ impactNetwork: '远端不可达会导致模型列表/对话请求失败或超时。',
130
+ message: Object.freeze({
131
+ 'remote-model-probe-unreachable': 'Provider 不可达',
132
+ 'remote-model-probe-auth-failed': 'Provider 鉴权失败',
133
+ 'remote-model-probe-not-found': 'Provider 返回 404',
134
+ 'remote-model-probe-http-error': 'Provider 返回 HTTP 错误',
135
+ 'remote-model-probe-error': 'Provider 探测失败'
136
+ })
137
+ }),
138
+ configHealthFailed: Object.freeze({
139
+ problem: '配置健康检查未通过',
140
+ impact: '可能导致部分功能不可用或行为不符合预期。'
141
+ }),
142
+ usageError: Object.freeze({
143
+ problem: 'Usage 统计异常',
144
+ impact: 'Usage 页面可能无法展示趋势/汇总,Doctor 的用量诊断也会缺失。'
145
+ }),
146
+ usageMissingModel: Object.freeze({
147
+ problem: '部分会话缺少模型信息',
148
+ impact: '会导致用量归因与成本估算不准确。'
149
+ }),
150
+ tasksError: Object.freeze({
151
+ problem: 'Tasks 状态读取失败',
152
+ impact: '可能导致编排队列/运行记录无法展示。'
153
+ }),
154
+ tasksFailed: Object.freeze({
155
+ problem: '存在失败的任务运行',
156
+ impact: '可能导致自动化流水线中断,需要查看日志并重试或修复输入。'
157
+ }),
158
+ skillsError: Object.freeze({
159
+ problem: 'Skills 列表读取失败',
160
+ impact: '会导致 Skills 页面无法正常展示或安装。'
161
+ }),
162
+ skillsRootMissing: Object.freeze({
163
+ problem: 'Skills 目录不存在',
164
+ impact: '会导致 Skills 安装/扫描为空;可在 Settings/Docs 按指引初始化目录。'
165
+ }),
166
+ skillsMissingFiles: Object.freeze({
167
+ problem: '存在缺失 skill.json 的技能',
168
+ impact: '会导致部分技能无法被运行或同步。'
169
+ })
170
+ }),
171
+ action: Object.freeze({
172
+ openConfig: '打开 Config',
173
+ checkProvider: '检查 Provider 配置',
174
+ openUsage: '打开 Usage',
175
+ openSessions: '打开 Sessions',
176
+ openTasks: '打开 Tasks',
177
+ viewTaskLogs: '查看 Tasks / Logs',
178
+ openSkills: '打开 Skills'
179
+ }),
180
+ markdown: Object.freeze({
181
+ title: 'Codexmate Doctor 报告',
182
+ generated: '生成时间',
183
+ status: '状态',
184
+ statusOk: '通过',
185
+ statusNotOk: '未通过',
186
+ issues: '问题数',
187
+ noIssues: '暂无可操作问题。',
188
+ issuesTitle: '问题列表',
189
+ area: '模块',
190
+ impact: '影响',
191
+ actions: '动作',
192
+ open: '打开',
193
+ recheck: '复检:重新运行 doctor',
194
+ export: Object.freeze({
195
+ json: '导出:doctor.json',
196
+ md: '导出:doctor.md'
197
+ })
198
+ })
199
+ })
200
+ });
201
+
202
+ function getI18n(lang) {
203
+ const normalized = normalizeLang(lang);
204
+ if (normalized === 'en') return DOCTOR_I18N.en;
205
+ if (normalized === 'zh') return DOCTOR_I18N.zh;
206
+ return DOCTOR_I18N.zh;
207
+ }
208
+
209
+ function buildIssue(id, severity, problem, impact, actions = [], data = null, meta = null) {
210
+ const safeMeta = meta && typeof meta === 'object' ? meta : {};
211
+ return {
212
+ id: String(id || '').trim() || 'unknown',
213
+ severity: normalizeSeverity(severity),
214
+ areaKey: typeof safeMeta.areaKey === 'string' && safeMeta.areaKey.trim() ? safeMeta.areaKey.trim() : 'Doctor',
215
+ area: typeof safeMeta.area === 'string' && safeMeta.area.trim() ? safeMeta.area.trim() : 'Doctor',
216
+ severityLabel: typeof safeMeta.severityLabel === 'string' && safeMeta.severityLabel.trim() ? safeMeta.severityLabel.trim() : '',
217
+ problemKey: typeof safeMeta.problemKey === 'string' && safeMeta.problemKey.trim() ? safeMeta.problemKey.trim() : '',
218
+ problemParams: safeMeta.problemParams && typeof safeMeta.problemParams === 'object' ? safeMeta.problemParams : null,
219
+ impactKey: typeof safeMeta.impactKey === 'string' && safeMeta.impactKey.trim() ? safeMeta.impactKey.trim() : '',
220
+ impactParams: safeMeta.impactParams && typeof safeMeta.impactParams === 'object' ? safeMeta.impactParams : null,
221
+ impactTags: Array.isArray(safeMeta.impactTags) ? safeMeta.impactTags.filter(Boolean) : [],
222
+ impactScope: typeof safeMeta.impactScope === 'string' && safeMeta.impactScope.trim() ? safeMeta.impactScope.trim() : '',
223
+ problem: String(problem || '').trim(),
224
+ impact: String(impact || '').trim(),
225
+ actions: Array.isArray(actions) ? actions : [],
226
+ evidence: data && typeof data === 'object' ? data : null,
227
+ data: data && typeof data === 'object' ? data : null
228
+ };
229
+ }
230
+
231
+ function buildAction(type, payload = {}) {
232
+ const normalizedType = String(type || '').trim();
233
+ const safePayload = payload && typeof payload === 'object' ? payload : {};
234
+ return {
235
+ type: normalizedType,
236
+ ...safePayload
237
+ };
238
+ }
239
+
240
+ function findConfigHealthRemoteIssue(issues = []) {
241
+ const list = Array.isArray(issues) ? issues : [];
242
+ const remoteCodes = new Set([
243
+ 'remote-model-probe-unreachable',
244
+ 'remote-model-probe-auth-failed',
245
+ 'remote-model-probe-not-found',
246
+ 'remote-model-probe-http-error',
247
+ 'remote-model-probe-error'
248
+ ]);
249
+ return list.find((issue) => issue && typeof issue.code === 'string' && remoteCodes.has(issue.code)) || null;
250
+ }
251
+
252
+ function summarizeSkillsIssues(payload) {
253
+ const safe = payload && typeof payload === 'object' ? payload : {};
254
+ const exists = safe.exists !== false;
255
+ const items = Array.isArray(safe.items) ? safe.items : [];
256
+ const missing = items.filter((item) => item && item.hasSkillFile === false).length;
257
+ return { exists, total: items.length, missing, root: safe.root || '' };
258
+ }
259
+
260
+ function summarizeUsageIssues(sessions = []) {
261
+ const list = Array.isArray(sessions) ? sessions : [];
262
+ let missingModel = 0;
263
+ for (const session of list) {
264
+ if (!session || typeof session !== 'object') continue;
265
+ const model = typeof session.model === 'string' ? session.model.trim() : '';
266
+ if (!model) missingModel += 1;
267
+ }
268
+ return { total: list.length, missingModel };
269
+ }
270
+
271
+ function summarizeTaskIssues(taskOverview) {
272
+ const safe = taskOverview && typeof taskOverview === 'object' ? taskOverview : {};
273
+ const queue = Array.isArray(safe.queue) ? safe.queue : [];
274
+ const runs = Array.isArray(safe.runs) ? safe.runs : [];
275
+ const failedRuns = runs.filter((run) => {
276
+ if (!run || typeof run !== 'object') return false;
277
+ const status = String(run.status || '').trim().toLowerCase();
278
+ return status === 'failed' || status === 'blocked' || status === 'cancelled';
279
+ });
280
+ const runningRuns = runs.filter((run) => {
281
+ if (!run || typeof run !== 'object') return false;
282
+ const status = String(run.status || '').trim().toLowerCase();
283
+ return status === 'running' || status === 'queued';
284
+ });
285
+ return {
286
+ queue: queue.length,
287
+ runs: runs.length,
288
+ running: runningRuns.length,
289
+ failed: failedRuns.length,
290
+ latestFailed: failedRuns.length ? failedRuns[0] : null
291
+ };
292
+ }
293
+
294
+ function buildDefaultActions() {
295
+ return [
296
+ buildAction('run-check', { id: 'doctor' }),
297
+ buildAction('export', { format: 'json' }),
298
+ buildAction('export', { format: 'md' })
299
+ ];
300
+ }
301
+
302
+ function ensureBaseActions(actions = []) {
303
+ const list = Array.isArray(actions) ? [...actions] : [];
304
+ const hasRun = list.some((item) => item && item.type === 'run-check');
305
+ const hasExportJson = list.some((item) => item && item.type === 'export' && item.format === 'json');
306
+ const hasExportMd = list.some((item) => item && item.type === 'export' && (item.format === 'md' || item.format === 'markdown'));
307
+ if (!hasRun) {
308
+ list.push(buildAction('run-check', { id: 'doctor' }));
309
+ }
310
+ if (!hasExportJson) {
311
+ list.push(buildAction('export', { format: 'json' }));
312
+ }
313
+ if (!hasExportMd) {
314
+ list.push(buildAction('export', { format: 'md' }));
315
+ }
316
+ return list;
317
+ }
318
+
319
+ function severityRank(severity) {
320
+ const normalized = normalizeSeverity(severity);
321
+ if (normalized === 'error') return 0;
322
+ if (normalized === 'warn') return 1;
323
+ return 2;
324
+ }
325
+
326
+ function issuePriorityRank(id) {
327
+ const order = [
328
+ 'config-not-ready',
329
+ 'provider-unreachable',
330
+ 'config-health-failed',
331
+ 'usage-error',
332
+ 'tasks-error',
333
+ 'tasks-failed',
334
+ 'skills-error',
335
+ 'skills-root-missing',
336
+ 'skills-missing-files',
337
+ 'usage-missing-model'
338
+ ];
339
+ const key = String(id || '').trim();
340
+ const index = order.indexOf(key);
341
+ return index >= 0 ? index : 999;
342
+ }
343
+
344
+ function sortIssues(issues = []) {
345
+ const list = Array.isArray(issues) ? [...issues] : [];
346
+ list.sort((a, b) => {
347
+ const rankA = severityRank(a && a.severity);
348
+ const rankB = severityRank(b && b.severity);
349
+ if (rankA !== rankB) return rankA - rankB;
350
+ const priA = issuePriorityRank(a && a.id);
351
+ const priB = issuePriorityRank(b && b.id);
352
+ if (priA !== priB) return priA - priB;
353
+ const idA = String(a && a.id || '');
354
+ const idB = String(b && b.id || '');
355
+ return idA.localeCompare(idB, 'en-US');
356
+ });
357
+ return list;
358
+ }
359
+
360
+ function renderDoctorMarkdown(report) {
361
+ const safe = report && typeof report === 'object' ? report : {};
362
+ const i18n = getI18n(safe.lang);
363
+ const summary = safe.summary && typeof safe.summary === 'object' ? safe.summary : { total: 0, error: 0, warn: 0, info: 0 };
364
+ const issues = Array.isArray(safe.issues) ? safe.issues : [];
365
+ const lines = [];
366
+ lines.push(`# ${i18n.markdown.title}`);
367
+ lines.push('');
368
+ lines.push(`- ${i18n.markdown.generated}: ${safe.generatedAt || ''}`);
369
+ lines.push(`- ${i18n.markdown.status}: ${safe.ok ? i18n.markdown.statusOk : i18n.markdown.statusNotOk}`);
370
+ lines.push(`- ${i18n.markdown.issues}: ${summary.total || 0} (${i18n.severity.error} ${summary.error || 0}, ${i18n.severity.warn} ${summary.warn || 0}, ${i18n.severity.info} ${summary.info || 0})`);
371
+ lines.push('');
372
+ if (!issues.length) {
373
+ lines.push(i18n.markdown.noIssues);
374
+ lines.push('');
375
+ return lines.join('\n');
376
+ }
377
+ lines.push(`## ${i18n.markdown.issuesTitle}`);
378
+ lines.push('');
379
+ for (const issue of issues) {
380
+ if (!issue || typeof issue !== 'object') continue;
381
+ const severityLabel = issue.severityLabel || (i18n.severity[normalizeSeverity(issue.severity)] || String(issue.severity || '').toUpperCase());
382
+ const header = `### [${severityLabel}] ${issue.problem || issue.id || ''}`;
383
+ lines.push(header);
384
+ if (issue.area) {
385
+ lines.push(`- ${i18n.markdown.area}: ${issue.area}`);
386
+ }
387
+ if (issue.impact) {
388
+ lines.push(`- ${i18n.markdown.impact}: ${issue.impact}`);
389
+ }
390
+ const actions = Array.isArray(issue.actions) ? issue.actions : [];
391
+ if (actions.length) {
392
+ lines.push(`- ${i18n.markdown.actions}:`);
393
+ for (const action of actions) {
394
+ if (!action || typeof action !== 'object') continue;
395
+ if (action.type === 'navigate') {
396
+ lines.push(` - ${i18n.markdown.open}: ${action.label || action.target || ''}`);
397
+ continue;
398
+ }
399
+ if (action.type === 'run-check') {
400
+ lines.push(` - ${i18n.markdown.recheck}`);
401
+ continue;
402
+ }
403
+ if (action.type === 'export') {
404
+ const fmt = action.format === 'md' ? 'md' : 'json';
405
+ lines.push(` - ${fmt === 'md' ? i18n.markdown.export.md : i18n.markdown.export.json}`);
406
+ continue;
407
+ }
408
+ lines.push(` - ${action.type}`);
409
+ }
410
+ }
411
+ lines.push('');
412
+ }
413
+ return lines.join('\n');
414
+ }
415
+
416
+ function decorateIssue(issue, lang) {
417
+ if (!issue || typeof issue !== 'object') return issue;
418
+ const i18n = getI18n(lang);
419
+ const areaKey = typeof issue.areaKey === 'string' && issue.areaKey.trim() ? issue.areaKey.trim() : 'Doctor';
420
+ issue.areaKey = areaKey;
421
+ issue.area = i18n.area[areaKey] || areaKey;
422
+ issue.severity = normalizeSeverity(issue.severity);
423
+ issue.severityLabel = i18n.severity[issue.severity] || issue.severityLabel || issue.severity;
424
+ return issue;
425
+ }
426
+
427
+ function resolveProviderProblemText(i18n, remoteIssue) {
428
+ const code = remoteIssue && typeof remoteIssue.code === 'string' ? remoteIssue.code : '';
429
+ const mapped = code && i18n.issue.providerUnreachable.message
430
+ ? i18n.issue.providerUnreachable.message[code]
431
+ : '';
432
+ if (mapped) return mapped;
433
+ const fallback = i18n === DOCTOR_I18N.en ? 'Provider unreachable' : 'Provider 不可用';
434
+ return fallback;
435
+ }
436
+
437
+ function buildNavigateAction(target, labelKey, label, labelParams = null) {
438
+ return buildAction('navigate', {
439
+ target,
440
+ labelKey: String(labelKey || '').trim(),
441
+ labelParams: labelParams && typeof labelParams === 'object' ? labelParams : null,
442
+ label: String(label || '').trim()
443
+ });
444
+ }
445
+
446
+ function buildIssueKeyMap() {
447
+ return {
448
+ configNotReady: {
449
+ problemKey: 'doctor.issue.configNotReady.problem',
450
+ impactKey: 'doctor.issue.configNotReady.impact'
451
+ },
452
+ providerUnreachable: {
453
+ problemKeyPrefix: 'doctor.issue.providerUnreachable.problem.',
454
+ impactAuthKey: 'doctor.issue.providerUnreachable.impactAuth',
455
+ impactNetworkKey: 'doctor.issue.providerUnreachable.impactNetwork'
456
+ },
457
+ configHealthFailed: {
458
+ problemKey: 'doctor.issue.configHealthFailed.problem',
459
+ impactKey: 'doctor.issue.configHealthFailed.impact'
460
+ },
461
+ usageError: {
462
+ problemKey: 'doctor.issue.usageError.problem',
463
+ impactKey: 'doctor.issue.usageError.impact'
464
+ },
465
+ usageMissingModel: {
466
+ problemKey: 'doctor.issue.usageMissingModel.problem',
467
+ impactKey: 'doctor.issue.usageMissingModel.impact'
468
+ },
469
+ tasksError: {
470
+ problemKey: 'doctor.issue.tasksError.problem',
471
+ impactKey: 'doctor.issue.tasksError.impact'
472
+ },
473
+ tasksFailed: {
474
+ problemKey: 'doctor.issue.tasksFailed.problem',
475
+ impactKey: 'doctor.issue.tasksFailed.impact'
476
+ },
477
+ skillsError: {
478
+ problemKey: 'doctor.issue.skillsError.problem',
479
+ impactKey: 'doctor.issue.skillsError.impact'
480
+ },
481
+ skillsRootMissing: {
482
+ problemKey: 'doctor.issue.skillsRootMissing.problem',
483
+ impactKey: 'doctor.issue.skillsRootMissing.impact'
484
+ },
485
+ skillsMissingFiles: {
486
+ problemKey: 'doctor.issue.skillsMissingFiles.problem',
487
+ impactKey: 'doctor.issue.skillsMissingFiles.impact'
488
+ }
489
+ };
490
+ }
491
+
492
+ const ISSUE_KEYS = Object.freeze(buildIssueKeyMap());
493
+
494
+ function resolveProviderProblemKey(code) {
495
+ const normalized = String(code || '').trim();
496
+ const suffix = normalized || 'unknown';
497
+ return `${ISSUE_KEYS.providerUnreachable.problemKeyPrefix}${suffix}`;
498
+ }
499
+
500
+ function runChecks(context, checks = []) {
501
+ const list = Array.isArray(checks) ? checks : [];
502
+ const issues = [];
503
+ for (const check of list) {
504
+ if (typeof check !== 'function') continue;
505
+ const result = check(context);
506
+ if (!result) continue;
507
+ if (Array.isArray(result)) {
508
+ issues.push(...result.filter(Boolean));
509
+ continue;
510
+ }
511
+ issues.push(result);
512
+ }
513
+ return issues;
514
+ }
515
+
516
+ async function buildDoctorReport(params = {}, deps = {}) {
517
+ const options = params && typeof params === 'object' ? params : {};
518
+ const resolvedLang = normalizeLang(options.lang) || normalizeLang(process.env.LANG) || 'zh';
519
+ const i18n = getI18n(resolvedLang);
520
+ const now = new Date().toISOString();
521
+ const getStatusPayload = typeof deps.getStatusPayload === 'function' ? deps.getStatusPayload : () => null;
522
+ const buildInstallStatusReport = typeof deps.buildInstallStatusReport === 'function' ? deps.buildInstallStatusReport : () => null;
523
+ const buildConfigHealthReport = typeof deps.buildConfigHealthReport === 'function' ? deps.buildConfigHealthReport : null;
524
+ const listSessionUsage = typeof deps.listSessionUsage === 'function' ? deps.listSessionUsage : null;
525
+ const buildTaskOverviewPayload = typeof deps.buildTaskOverviewPayload === 'function' ? deps.buildTaskOverviewPayload : null;
526
+ const listSkills = typeof deps.listSkills === 'function' ? deps.listSkills : null;
527
+
528
+ const sources = {
529
+ status: null,
530
+ install: null,
531
+ configHealth: null,
532
+ usage: null,
533
+ tasks: null,
534
+ skills: null
535
+ };
536
+
537
+ sources.status = getStatusPayload();
538
+ if (options.includeInstall !== false) {
539
+ sources.install = buildInstallStatusReport();
540
+ }
541
+
542
+ if (buildConfigHealthReport) {
543
+ try {
544
+ sources.configHealth = await buildConfigHealthReport({
545
+ remote: options.remote !== false
546
+ });
547
+ } catch (e) {
548
+ sources.configHealth = { ok: false, error: e && e.message ? e.message : 'config health check failed', issues: [] };
549
+ }
550
+ }
551
+
552
+ if (listSessionUsage && options.includeUsage !== false) {
553
+ try {
554
+ const range = typeof options.range === 'string' ? options.range.trim().toLowerCase() : '';
555
+ const limit = range === 'all' ? 2000 : (range === '30d' ? 1200 : 600);
556
+ const sessions = await listSessionUsage({
557
+ source: 'all',
558
+ limit
559
+ });
560
+ const summary = summarizeUsageIssues(sessions);
561
+ sources.usage = {
562
+ range: range === 'all' ? 'all' : (range === '30d' ? '30d' : '7d'),
563
+ summary,
564
+ sample: (Array.isArray(sessions) ? sessions : [])
565
+ .slice(0, 10)
566
+ .map((session) => ({
567
+ source: session && session.source ? session.source : '',
568
+ sessionId: session && session.sessionId ? session.sessionId : '',
569
+ updatedAt: session && session.updatedAt ? session.updatedAt : '',
570
+ model: session && session.model ? session.model : '',
571
+ provider: session && session.provider ? session.provider : '',
572
+ messageCount: session && session.messageCount ? session.messageCount : 0,
573
+ totalTokens: session && session.totalTokens ? session.totalTokens : 0
574
+ }))
575
+ };
576
+ } catch (e) {
577
+ sources.usage = { error: e && e.message ? e.message : 'usage probe failed', range: '7d', summary: { total: 0, missingModel: 0 } };
578
+ }
579
+ }
580
+
581
+ if (buildTaskOverviewPayload && options.includeTasks !== false) {
582
+ try {
583
+ const overview = buildTaskOverviewPayload({
584
+ queueLimit: 20,
585
+ runLimit: 20
586
+ });
587
+ sources.tasks = {
588
+ summary: summarizeTaskIssues(overview),
589
+ warnings: Array.isArray(overview && overview.warnings) ? overview.warnings : []
590
+ };
591
+ } catch (e) {
592
+ sources.tasks = { error: e && e.message ? e.message : 'task overview failed' };
593
+ }
594
+ }
595
+
596
+ if (listSkills && options.includeSkills !== false) {
597
+ const targetApp = typeof options.targetApp === 'string' && options.targetApp.trim()
598
+ ? options.targetApp.trim().toLowerCase()
599
+ : 'codex';
600
+ try {
601
+ const raw = listSkills({ targetApp });
602
+ const summary = summarizeSkillsIssues(raw);
603
+ sources.skills = { targetApp, summary };
604
+ } catch (e) {
605
+ sources.skills = { error: e && e.message ? e.message : 'skills probe failed', targetApp };
606
+ }
607
+ }
608
+
609
+ const status = sources.status && typeof sources.status === 'object' ? sources.status : {};
610
+ const baseActions = buildDefaultActions();
611
+ const context = {
612
+ options,
613
+ sources,
614
+ status,
615
+ baseActions,
616
+ i18n
617
+ };
618
+
619
+ const issues = runChecks(context, [
620
+ (ctx) => {
621
+ if (ctx.status.configReady !== false && !(typeof ctx.status.configErrorType === 'string' && ctx.status.configErrorType.trim())) {
622
+ return null;
623
+ }
624
+ return buildIssue(
625
+ 'config-not-ready',
626
+ 'error',
627
+ ctx.i18n.issue.configNotReady.problem,
628
+ ctx.i18n.issue.configNotReady.impact,
629
+ ensureBaseActions([
630
+ buildNavigateAction('config', 'doctor.action.openConfig', ctx.i18n.action.openConfig)
631
+ ].concat(ctx.baseActions)),
632
+ {
633
+ configErrorType: ctx.status.configErrorType || '',
634
+ configNotice: ctx.status.configNotice || ''
635
+ },
636
+ {
637
+ areaKey: 'Config',
638
+ problemKey: ISSUE_KEYS.configNotReady.problemKey,
639
+ impactKey: ISSUE_KEYS.configNotReady.impactKey,
640
+ impactTags: ['blocked'],
641
+ impactScope: 'config'
642
+ }
643
+ );
644
+ },
645
+ (ctx) => {
646
+ const configHealth = ctx.sources.configHealth && typeof ctx.sources.configHealth === 'object' ? ctx.sources.configHealth : null;
647
+ if (!configHealth || configHealth.ok !== false) {
648
+ return null;
649
+ }
650
+ const remoteIssue = findConfigHealthRemoteIssue(configHealth.issues || []);
651
+ if (remoteIssue) {
652
+ const impactKey = remoteIssue.code === 'remote-model-probe-auth-failed'
653
+ ? ISSUE_KEYS.providerUnreachable.impactAuthKey
654
+ : ISSUE_KEYS.providerUnreachable.impactNetworkKey;
655
+ const impact = remoteIssue.code === 'remote-model-probe-auth-failed'
656
+ ? ctx.i18n.issue.providerUnreachable.impactAuth
657
+ : ctx.i18n.issue.providerUnreachable.impactNetwork;
658
+ return buildIssue(
659
+ 'provider-unreachable',
660
+ 'error',
661
+ resolveProviderProblemText(ctx.i18n, remoteIssue),
662
+ impact,
663
+ ensureBaseActions([
664
+ buildNavigateAction('config', 'doctor.action.checkProvider', ctx.i18n.action.checkProvider)
665
+ ].concat(ctx.baseActions)),
666
+ { code: remoteIssue.code || '', statusCode: remoteIssue.statusCode || 0 },
667
+ {
668
+ areaKey: 'Config',
669
+ problemKey: resolveProviderProblemKey(remoteIssue.code),
670
+ impactKey,
671
+ impactTags: ['blocked', 'network'],
672
+ impactScope: 'provider'
673
+ }
674
+ );
675
+ }
676
+ if (Array.isArray(configHealth.issues) && configHealth.issues.length) {
677
+ return buildIssue(
678
+ 'config-health-failed',
679
+ 'warn',
680
+ ctx.i18n.issue.configHealthFailed.problem,
681
+ ctx.i18n.issue.configHealthFailed.impact,
682
+ ensureBaseActions([
683
+ buildNavigateAction('config', 'doctor.action.openConfig', ctx.i18n.action.openConfig)
684
+ ].concat(ctx.baseActions)),
685
+ { issueCount: configHealth.issues.length },
686
+ {
687
+ areaKey: 'Config',
688
+ problemKey: ISSUE_KEYS.configHealthFailed.problemKey,
689
+ impactKey: ISSUE_KEYS.configHealthFailed.impactKey,
690
+ impactTags: ['degraded'],
691
+ impactScope: 'config'
692
+ }
693
+ );
694
+ }
695
+ return null;
696
+ },
697
+ (ctx) => {
698
+ if (!ctx.sources.usage || typeof ctx.sources.usage !== 'object') return null;
699
+ if (ctx.sources.usage.error) {
700
+ return buildIssue(
701
+ 'usage-error',
702
+ 'warn',
703
+ ctx.i18n.issue.usageError.problem,
704
+ ctx.i18n.issue.usageError.impact,
705
+ ensureBaseActions([
706
+ buildNavigateAction('usage', 'doctor.action.openUsage', ctx.i18n.action.openUsage)
707
+ ].concat(ctx.baseActions)),
708
+ { error: ctx.sources.usage.error },
709
+ {
710
+ areaKey: 'Observe',
711
+ problemKey: ISSUE_KEYS.usageError.problemKey,
712
+ impactKey: ISSUE_KEYS.usageError.impactKey,
713
+ impactTags: ['degraded'],
714
+ impactScope: 'observe'
715
+ }
716
+ );
717
+ }
718
+ const summary = ctx.sources.usage.summary && typeof ctx.sources.usage.summary === 'object' ? ctx.sources.usage.summary : { total: 0, missingModel: 0 };
719
+ if (Number(summary.missingModel || 0) <= 0) return null;
720
+ return buildIssue(
721
+ 'usage-missing-model',
722
+ 'info',
723
+ ctx.i18n.issue.usageMissingModel.problem,
724
+ ctx.i18n.issue.usageMissingModel.impact,
725
+ ensureBaseActions([
726
+ buildNavigateAction('usage', 'doctor.action.openUsage', ctx.i18n.action.openUsage),
727
+ buildNavigateAction('sessions', 'doctor.action.openSessions', ctx.i18n.action.openSessions)
728
+ ].concat(ctx.baseActions)),
729
+ summary,
730
+ {
731
+ areaKey: 'Observe',
732
+ problemKey: ISSUE_KEYS.usageMissingModel.problemKey,
733
+ impactKey: ISSUE_KEYS.usageMissingModel.impactKey,
734
+ impactTags: ['data-quality'],
735
+ impactScope: 'observe'
736
+ }
737
+ );
738
+ },
739
+ (ctx) => {
740
+ if (!ctx.sources.tasks || typeof ctx.sources.tasks !== 'object') return null;
741
+ if (ctx.sources.tasks.error) {
742
+ return buildIssue(
743
+ 'tasks-error',
744
+ 'warn',
745
+ ctx.i18n.issue.tasksError.problem,
746
+ ctx.i18n.issue.tasksError.impact,
747
+ ensureBaseActions([
748
+ buildNavigateAction('orchestration', 'doctor.action.openTasks', ctx.i18n.action.openTasks)
749
+ ].concat(ctx.baseActions)),
750
+ { error: ctx.sources.tasks.error },
751
+ {
752
+ areaKey: 'Operate',
753
+ problemKey: ISSUE_KEYS.tasksError.problemKey,
754
+ impactKey: ISSUE_KEYS.tasksError.impactKey,
755
+ impactTags: ['degraded'],
756
+ impactScope: 'operate'
757
+ }
758
+ );
759
+ }
760
+ const summary = ctx.sources.tasks.summary && typeof ctx.sources.tasks.summary === 'object'
761
+ ? ctx.sources.tasks.summary
762
+ : summarizeTaskIssues(ctx.sources.tasks);
763
+ if (Number(summary.failed || 0) <= 0) return null;
764
+ return buildIssue(
765
+ 'tasks-failed',
766
+ 'warn',
767
+ ctx.i18n.issue.tasksFailed.problem,
768
+ ctx.i18n.issue.tasksFailed.impact,
769
+ ensureBaseActions([
770
+ buildNavigateAction('orchestration', 'doctor.action.viewTaskLogs', ctx.i18n.action.viewTaskLogs)
771
+ ].concat(ctx.baseActions)),
772
+ {
773
+ failed: summary.failed || 0,
774
+ latestFailed: summary.latestFailed
775
+ ? {
776
+ runId: summary.latestFailed.runId || '',
777
+ status: summary.latestFailed.status || '',
778
+ error: summary.latestFailed.error || ''
779
+ }
780
+ : null
781
+ },
782
+ {
783
+ areaKey: 'Operate',
784
+ problemKey: ISSUE_KEYS.tasksFailed.problemKey,
785
+ impactKey: ISSUE_KEYS.tasksFailed.impactKey,
786
+ impactTags: ['blocked'],
787
+ impactScope: 'operate'
788
+ }
789
+ );
790
+ },
791
+ (ctx) => {
792
+ if (!ctx.sources.skills || typeof ctx.sources.skills !== 'object') return null;
793
+ if (ctx.sources.skills.error) {
794
+ return buildIssue(
795
+ 'skills-error',
796
+ 'warn',
797
+ ctx.i18n.issue.skillsError.problem,
798
+ ctx.i18n.issue.skillsError.impact,
799
+ ensureBaseActions([
800
+ buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
801
+ ].concat(ctx.baseActions)),
802
+ { error: ctx.sources.skills.error },
803
+ {
804
+ areaKey: 'Reuse',
805
+ problemKey: ISSUE_KEYS.skillsError.problemKey,
806
+ impactKey: ISSUE_KEYS.skillsError.impactKey,
807
+ impactTags: ['degraded'],
808
+ impactScope: 'reuse'
809
+ }
810
+ );
811
+ }
812
+ const summary = ctx.sources.skills.summary && typeof ctx.sources.skills.summary === 'object'
813
+ ? ctx.sources.skills.summary
814
+ : summarizeSkillsIssues(ctx.sources.skills);
815
+ if (!summary.exists) {
816
+ return buildIssue(
817
+ 'skills-root-missing',
818
+ 'info',
819
+ ctx.i18n.issue.skillsRootMissing.problem,
820
+ ctx.i18n.issue.skillsRootMissing.impact,
821
+ ensureBaseActions([
822
+ buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
823
+ ].concat(ctx.baseActions)),
824
+ summary,
825
+ {
826
+ areaKey: 'Reuse',
827
+ problemKey: ISSUE_KEYS.skillsRootMissing.problemKey,
828
+ impactKey: ISSUE_KEYS.skillsRootMissing.impactKey,
829
+ impactTags: ['degraded'],
830
+ impactScope: 'reuse'
831
+ }
832
+ );
833
+ }
834
+ if (Number(summary.missing || 0) > 0) {
835
+ return buildIssue(
836
+ 'skills-missing-files',
837
+ 'info',
838
+ ctx.i18n.issue.skillsMissingFiles.problem,
839
+ ctx.i18n.issue.skillsMissingFiles.impact,
840
+ ensureBaseActions([
841
+ buildNavigateAction('market', 'doctor.action.openSkills', ctx.i18n.action.openSkills)
842
+ ].concat(ctx.baseActions)),
843
+ summary,
844
+ {
845
+ areaKey: 'Reuse',
846
+ problemKey: ISSUE_KEYS.skillsMissingFiles.problemKey,
847
+ impactKey: ISSUE_KEYS.skillsMissingFiles.impactKey,
848
+ impactTags: ['data-quality'],
849
+ impactScope: 'reuse'
850
+ }
851
+ );
852
+ }
853
+ return null;
854
+ }
855
+ ]);
856
+
857
+ const sortedIssues = sortIssues(issues);
858
+ sortedIssues.forEach((issue) => decorateIssue(issue, resolvedLang));
859
+ const hasError = sortedIssues.some((item) => item && item.severity === 'error');
860
+ const report = {
861
+ schema: 1,
862
+ generatedAt: now,
863
+ lang: resolvedLang,
864
+ ok: !hasError,
865
+ issues: sortedIssues,
866
+ sources
867
+ };
868
+ report.summary = {
869
+ total: sortedIssues.length,
870
+ error: sortedIssues.filter((item) => item.severity === 'error').length,
871
+ warn: sortedIssues.filter((item) => item.severity === 'warn').length,
872
+ info: sortedIssues.filter((item) => item.severity === 'info').length
873
+ };
874
+ return report;
875
+ }
876
+
877
+ function buildDoctorLegacyPayload(report) {
878
+ const safe = report && typeof report === 'object' ? report : {};
879
+ const issues = Array.isArray(safe.issues) ? safe.issues : [];
880
+ const legacyIssues = issues
881
+ .map((item) => ({
882
+ code: item && item.id ? item.id : 'unknown',
883
+ message: item && item.problem ? item.problem : ''
884
+ }))
885
+ .filter((item) => item.message);
886
+ const configHealth = safe.sources && safe.sources.configHealth && typeof safe.sources.configHealth === 'object'
887
+ ? safe.sources.configHealth
888
+ : null;
889
+ const remote = configHealth && configHealth.remote ? configHealth.remote : null;
890
+ return {
891
+ ok: safe.ok !== false,
892
+ issues: legacyIssues,
893
+ remote,
894
+ report: safe
895
+ };
896
+ }
897
+
898
+ module.exports = {
899
+ buildDoctorReport,
900
+ buildDoctorLegacyPayload,
901
+ renderDoctorMarkdown,
902
+ buildAction
903
+ };