@dsh-workbench/shared 0.1.13 → 0.1.15

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 (83) hide show
  1. package/dist/components/CardHead.js +3 -2
  2. package/dist/components/Field.css +16 -0
  3. package/dist/components/Field.d.ts +8 -0
  4. package/dist/components/Field.js +8 -0
  5. package/dist/components/Link.css +22 -0
  6. package/dist/components/Link.d.ts +10 -0
  7. package/dist/components/Link.js +8 -0
  8. package/dist/components/LongTaskRow.css +0 -15
  9. package/dist/components/LongTaskRow.js +3 -4
  10. package/dist/components/TextField.css +5 -0
  11. package/dist/host/browser-find.d.ts +38 -0
  12. package/dist/host/browser-find.js +242 -0
  13. package/dist/host/browser-read.d.ts +26 -0
  14. package/dist/host/browser-read.js +240 -0
  15. package/dist/host/http.d.ts +6 -1
  16. package/dist/host/http.js +2 -1
  17. package/dist/host/opencli-runtime.d.ts +3 -0
  18. package/dist/host/opencli-runtime.js +10 -0
  19. package/dist/host/opencli-window.d.ts +2 -0
  20. package/dist/host/opencli-window.js +8 -0
  21. package/dist/host/opencli.js +2 -0
  22. package/dist/host.d.ts +2 -0
  23. package/dist/host.js +2 -0
  24. package/dist/i18n/en.js +3 -0
  25. package/dist/i18n/index.d.ts +6 -3
  26. package/dist/i18n/zh.d.ts +5 -2
  27. package/dist/i18n/zh.js +5 -2
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +2 -0
  30. package/package.json +1 -1
  31. package/src/components/CardHead.test.tsx +81 -0
  32. package/src/components/CardHead.tsx +4 -3
  33. package/src/components/Field.css +16 -0
  34. package/src/components/Field.test.tsx +27 -0
  35. package/src/components/Field.tsx +19 -0
  36. package/src/components/Link.css +22 -0
  37. package/src/components/Link.test.tsx +37 -0
  38. package/src/components/Link.tsx +26 -0
  39. package/src/components/LongTaskRow.css +0 -15
  40. package/src/components/LongTaskRow.tsx +3 -4
  41. package/src/components/TextField.css +5 -0
  42. package/src/host/__tests__/browser-find.test.ts +319 -0
  43. package/src/host/__tests__/browser-read.test.ts +197 -0
  44. package/src/host/browser-find.ts +311 -0
  45. package/src/host/browser-read.ts +308 -0
  46. package/src/host/http.ts +8 -1
  47. package/src/host/opencli-runtime.ts +13 -0
  48. package/src/host/opencli-window.ts +11 -0
  49. package/src/host/opencli.ts +2 -0
  50. package/src/host.ts +2 -0
  51. package/src/i18n/en.ts +3 -0
  52. package/src/i18n/zh.ts +5 -2
  53. package/src/index.ts +2 -0
  54. package/dist/components/StateDot.d.ts +0 -5
  55. package/dist/components/StateDot.js +0 -10
  56. package/dist/host/__tests__/fakes.d.ts +0 -41
  57. package/dist/host/__tests__/fakes.js +0 -76
  58. package/dist/host/__tests__/preflight-fixtures.d.ts +0 -19
  59. package/dist/host/__tests__/preflight-fixtures.js +0 -47
  60. package/dist/host/context-inject.d.ts +0 -24
  61. package/dist/host/context-inject.js +0 -74
  62. package/dist/host/events.d.ts +0 -9
  63. package/dist/host/events.js +0 -70
  64. package/dist/host/mount-units.d.ts +0 -52
  65. package/dist/host/mount-units.js +0 -186
  66. package/dist/host/preflight.d.ts +0 -58
  67. package/dist/host/preflight.js +0 -233
  68. package/dist/host/probe-cache.d.ts +0 -6
  69. package/dist/host/probe-cache.js +0 -19
  70. package/dist/host/probe-libs.d.ts +0 -45
  71. package/dist/host/probe-libs.js +0 -61
  72. package/dist/host/probe-units.d.ts +0 -17
  73. package/dist/host/probe-units.js +0 -102
  74. package/dist/host/probe-verdict.d.ts +0 -7
  75. package/dist/host/probe-verdict.js +0 -143
  76. package/dist/host/tool-scope.d.ts +0 -32
  77. package/dist/host/tool-scope.js +0 -84
  78. package/dist/host/unit-readiness.d.ts +0 -7
  79. package/dist/host/unit-readiness.js +0 -5
  80. package/dist/host/unit-registry.d.ts +0 -9
  81. package/dist/host/unit-registry.js +0 -33
  82. package/dist/host/version-range.d.ts +0 -2
  83. package/dist/host/version-range.js +0 -73
@@ -1,74 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { encodeRef, parseMarkers } from '@dsh-workbench/shared';
3
- export const CONTEXT_SOURCE_KIND = 'workbench';
4
- export function collectContextRefs(messages) {
5
- const seen = new Set();
6
- const refs = [];
7
- for (const message of messages) {
8
- if (message.source?.kind !== 'user')
9
- continue;
10
- for (const block of message.content ?? []) {
11
- if (block.type !== 'text' || typeof block.text !== 'string')
12
- continue;
13
- for (const ref of parseMarkers(block.text)) {
14
- const key = encodeRef(ref);
15
- if (seen.has(key))
16
- continue;
17
- seen.add(key);
18
- refs.push(ref);
19
- }
20
- }
21
- }
22
- return refs;
23
- }
24
- export function buildContextMessage(text, summary) {
25
- return {
26
- role: 'user',
27
- id: randomUUID(),
28
- content: [{ type: 'text', text }],
29
- source: { kind: CONTEXT_SOURCE_KIND, form: 'notice', summary },
30
- };
31
- }
32
- export function createContextInjector(options) {
33
- const done = new WeakMap();
34
- return {
35
- async inject(messages, agent) {
36
- const refs = collectContextRefs(messages);
37
- if (refs.length === 0)
38
- return undefined;
39
- const key = typeof agent === 'object' && agent !== null ? agent : undefined;
40
- const seen = key === undefined ? undefined : (done.get(key) ?? new Set());
41
- if (key !== undefined && seen !== undefined)
42
- done.set(key, seen);
43
- const fresh = [];
44
- for (const ref of refs) {
45
- const encoded = encodeRef(ref);
46
- if (seen?.has(encoded) === true)
47
- continue;
48
- seen?.add(encoded);
49
- fresh.push(ref);
50
- }
51
- if (fresh.length === 0)
52
- return undefined;
53
- const texts = [];
54
- for (const ref of fresh) {
55
- const render = options.renderers.get(ref.kind);
56
- if (render === undefined)
57
- continue;
58
- let text;
59
- try {
60
- text = await render(ref);
61
- }
62
- catch (error) {
63
- options.logger?.warn?.(`[dsh-workbench] 渲染对话引用失败:${String(error)}`);
64
- text = `工作台面板引用了一条内容(${encodeRef(ref)}),但当前渲染不出来(项目未选中或数据源不可用)。`;
65
- }
66
- if (text !== '')
67
- texts.push(text);
68
- }
69
- if (texts.length === 0)
70
- return undefined;
71
- return buildContextMessage(texts.join('\n\n'), `工作台引用:${fresh.length} 条`);
72
- },
73
- };
74
- }
@@ -1,9 +0,0 @@
1
- import type { DshHostContext, DshRequest, DshResponse } from '@dsh-workbench/shared';
2
- import type { FactLog } from './facts';
3
- export interface FactStream {
4
- handler(req: DshRequest, res: DshResponse): void;
5
- closeAll(): void;
6
- size(): number;
7
- }
8
- export declare function createFactStream(log: FactLog): FactStream;
9
- export declare function registerFactStream(ctx: DshHostContext, log: FactLog): () => void;
@@ -1,70 +0,0 @@
1
- import { EVENTS_PATH } from '@dsh-workbench/shared';
2
- const HEARTBEAT_MS = 25_000;
3
- function frame(payload) {
4
- return `data: ${JSON.stringify(payload)}\n\n`;
5
- }
6
- export function createFactStream(log) {
7
- const connections = new Set();
8
- const cleanups = new Map();
9
- const drop = (res) => {
10
- cleanups.get(res)?.();
11
- cleanups.delete(res);
12
- connections.delete(res);
13
- };
14
- return {
15
- size: () => connections.size,
16
- closeAll() {
17
- for (const res of [...connections]) {
18
- drop(res);
19
- res.end?.();
20
- }
21
- },
22
- handler(req, res) {
23
- if (req.method !== undefined && req.method !== 'GET') {
24
- res.statusCode = 405;
25
- res.end();
26
- return;
27
- }
28
- const url = req.url ?? '/';
29
- const cut = url.indexOf('?');
30
- const since = Number(new URLSearchParams(cut === -1 ? '' : url.slice(cut + 1)).get('since') ?? 0) || 0;
31
- const opening = log.since(since);
32
- if (typeof res.write !== 'function') {
33
- res.statusCode = 200;
34
- res.setHeader('content-type', 'application/json; charset=utf-8');
35
- res.end(JSON.stringify({ ok: true, ...opening }));
36
- return;
37
- }
38
- const headers = {
39
- 'content-type': 'text/event-stream; charset=utf-8',
40
- 'cache-control': 'no-store, no-transform',
41
- connection: 'keep-alive',
42
- };
43
- if (typeof res.writeHead === 'function')
44
- res.writeHead(200, headers);
45
- else {
46
- res.statusCode = 200;
47
- for (const [name, value] of Object.entries(headers))
48
- res.setHeader(name, value);
49
- }
50
- res.write(': connected\n\n');
51
- res.write(frame({ type: 'sync', ...opening }));
52
- connections.add(res);
53
- const timer = setInterval(() => res.write?.(': ping\n\n'), HEARTBEAT_MS);
54
- const unsubscribe = log.subscribe((change) => res.write?.(frame({ type: 'bump', ...change })));
55
- cleanups.set(res, () => {
56
- clearInterval(timer);
57
- unsubscribe();
58
- });
59
- res.on?.('close', () => drop(res));
60
- },
61
- };
62
- }
63
- export function registerFactStream(ctx, log) {
64
- const stream = createFactStream(log);
65
- const unregister = ctx.webServer.register({ kind: 'exact', path: EVENTS_PATH, handler: stream.handler });
66
- return () => {
67
- stream.closeAll();
68
- unregister();
69
- };
70
- }
@@ -1,52 +0,0 @@
1
- import type { DshHostContext } from '@dsh-workbench/shared';
2
- import type { UnitManifest } from '@dsh-workbench/shared';
3
- import { type RouteTable } from './http';
4
- import type { ContextRenderer, UnitHostFace, UnitMountDeps, UnitMountResult, UnitCall } from './unit-face';
5
- import { type UnitReadiness } from './unit-readiness';
6
- export interface MountedUnit {
7
- readonly face: UnitHostFace;
8
- readonly result: UnitMountResult;
9
- readonly readiness: UnitReadiness;
10
- }
11
- export interface UnitsPlan {
12
- readonly mounted: readonly MountedUnit[];
13
- readonly routes: RouteTable;
14
- readonly gate: UnitMountResult['gate'];
15
- readonly prefs: ReadonlyArray<{
16
- readonly resource: string;
17
- readonly unit: string;
18
- handle(payload: unknown): unknown;
19
- }>;
20
- readonly actions: ReadonlyArray<{
21
- readonly resource: string;
22
- readonly unit: string;
23
- handle(payload: unknown): unknown;
24
- }>;
25
- readonly provision: UnitMountResult['provision'];
26
- readonly contextRenderers: ReadonlyMap<string, ContextRenderer>;
27
- readonly owners: ReadonlyMap<string, string>;
28
- readonly routesOfUnit: ReadonlyMap<string, readonly string[]>;
29
- readonly factsOf: ReadonlyMap<string, (call: UnitCall) => readonly string[] | undefined>;
30
- readonly skipped: ReadonlyArray<{
31
- readonly id: string;
32
- readonly missing: readonly string[];
33
- }>;
34
- readonly warmReads: () => readonly (readonly string[])[];
35
- readonly disposeLongTasks: () => void;
36
- }
37
- export declare function mountUnits(faces: readonly UnitHostFace[], deps: {
38
- ctx: DshHostContext;
39
- logger?: {
40
- info?(m: string): void;
41
- warn?(m: string): void;
42
- } | undefined;
43
- manifests: () => readonly UnitManifest[];
44
- opencliCommand?: string;
45
- probe?: UnitMountDeps['probe'];
46
- store?: UnitMountDeps['store'];
47
- values?: UnitMountDeps['values'];
48
- longTasks?: {
49
- readonly scope: string;
50
- readonly bump: (facts: readonly string[]) => void;
51
- } | undefined;
52
- }): UnitsPlan;
@@ -1,186 +0,0 @@
1
- import { runsRouteOf } from '@dsh-workbench/shared';
2
- import { param } from './http';
3
- import { createLongTaskHost } from './long-task';
4
- import { unitReadiness } from './unit-readiness';
5
- import { createWorkspaceStore } from './workspace-store';
6
- function withRunsRoute(result, unit) {
7
- const runs = result.longTasks;
8
- if (runs === undefined)
9
- return result;
10
- return {
11
- ...result,
12
- routes: {
13
- ...result.routes,
14
- [runsRouteOf(unit)]: (search) => {
15
- const path = (param(search, 'path') ?? '').trim();
16
- return { ok: true, runs: path === '' ? [] : runs.current(path) };
17
- },
18
- },
19
- };
20
- }
21
- function collectRoutes(mounted) {
22
- const routes = {};
23
- const owner = new Map();
24
- const routesOfUnit = new Map();
25
- for (const item of mounted) {
26
- const unit = item.face.manifest.id;
27
- for (const [key, handler] of Object.entries(item.result.routes)) {
28
- if (key !== unit && !key.startsWith(`${unit}/`)) {
29
- throw new Error(`路由名要住在自己那一格的命名空间里(${unit} 或 ${unit}/…):${key} 不属于 ${unit} —— ` +
30
- `装 / 升 / 卸时点名不到它,那个模块的数据会停在旧值`);
31
- }
32
- const previous = owner.get(key);
33
- if (previous !== undefined) {
34
- throw new Error(`路由名冲突:${key} 由套件 ${previous} 与 ${unit} 同时声明`);
35
- }
36
- owner.set(key, unit);
37
- routes[key] = handler;
38
- const own = routesOfUnit.get(unit);
39
- if (own === undefined)
40
- routesOfUnit.set(unit, [key]);
41
- else
42
- own.push(key);
43
- }
44
- }
45
- return { routes, owners: owner, routesOfUnit };
46
- }
47
- function pickGate(mounted) {
48
- const providers = mounted.filter((item) => item.result.gate !== undefined);
49
- if (providers.length > 1) {
50
- throw new Error(`启停闸门只能有一个提供者,现在是:${providers.map((item) => item.face.manifest.id).join('、')}`);
51
- }
52
- return providers[0]?.result.gate;
53
- }
54
- function pickProvision(mounted) {
55
- const providers = mounted.filter((item) => item.result.provision !== undefined);
56
- if (providers.length > 1) {
57
- throw new Error(`机器供给只能有一个提供者,现在是:${providers.map((item) => item.face.manifest.id).join('、')}`);
58
- }
59
- return providers[0]?.result.provision;
60
- }
61
- function collectPrefs(mounted) {
62
- const owner = new Map();
63
- const prefs = [];
64
- for (const item of mounted) {
65
- const entry = item.result.prefs;
66
- if (entry === undefined)
67
- continue;
68
- const previous = owner.get(entry.resource);
69
- if (previous !== undefined) {
70
- throw new Error(`偏好资源名冲突:${entry.resource} 由套件 ${previous} 与 ${item.face.manifest.id} 同时声明`);
71
- }
72
- owner.set(entry.resource, item.face.manifest.id);
73
- prefs.push({ ...entry, unit: item.face.manifest.id });
74
- }
75
- return prefs;
76
- }
77
- function collectActions(mounted) {
78
- const owner = new Map();
79
- const actions = [];
80
- for (const item of mounted) {
81
- for (const entry of item.result.actions ?? []) {
82
- const previous = owner.get(entry.resource);
83
- if (previous !== undefined) {
84
- throw new Error(`动作资源名冲突:${entry.resource} 由套件 ${previous} 与 ${item.face.manifest.id} 同时声明`);
85
- }
86
- owner.set(entry.resource, item.face.manifest.id);
87
- actions.push({ ...entry, unit: item.face.manifest.id });
88
- }
89
- }
90
- return actions;
91
- }
92
- function collectWarmReads(mounted) {
93
- const declarations = mounted
94
- .map((item) => item.result.warmReads)
95
- .filter((declare) => declare !== undefined);
96
- return () => {
97
- const seen = new Set();
98
- const reads = [];
99
- for (const read of declarations.flatMap((declare) => declare())) {
100
- const key = read.join(' ');
101
- if (seen.has(key))
102
- continue;
103
- seen.add(key);
104
- reads.push(read);
105
- }
106
- return reads;
107
- };
108
- }
109
- function collectContextRenderers(mounted) {
110
- const table = new Map();
111
- const owner = new Map();
112
- for (const item of mounted) {
113
- const context = item.result.context;
114
- if (context === undefined)
115
- continue;
116
- for (const kind of context.kinds) {
117
- const previous = owner.get(kind);
118
- if (previous !== undefined) {
119
- throw new Error(`对话引用的 kind 冲突:${kind} 由套件 ${previous} 与 ${item.face.manifest.id} 同时认领`);
120
- }
121
- owner.set(kind, item.face.manifest.id);
122
- table.set(kind, (ref) => context.render(ref));
123
- }
124
- }
125
- return table;
126
- }
127
- export function mountUnits(faces, deps) {
128
- const store = deps.store ?? createWorkspaceStore({ root: null });
129
- const mounted = [];
130
- const skipped = [];
131
- const longTaskDisposers = [];
132
- for (const face of faces) {
133
- const readiness = unitReadiness(face.manifest, (dep) => deps.ctx.get(dep));
134
- if (!readiness.canMount) {
135
- skipped.push({ id: face.manifest.id, missing: readiness.missingHard });
136
- continue;
137
- }
138
- const unit = face.manifest.id;
139
- const longTasks = deps.longTasks === undefined
140
- ? undefined
141
- : createLongTaskHost({ scope: deps.longTasks.scope, unit, bump: deps.longTasks.bump });
142
- if (longTasks !== undefined)
143
- longTaskDisposers.push(longTasks.dispose);
144
- const result = face.mount({
145
- ctx: deps.ctx,
146
- logger: deps.logger,
147
- manifests: deps.manifests,
148
- ...(deps.opencliCommand === undefined ? {} : { opencliCommand: deps.opencliCommand }),
149
- ...(deps.probe === undefined ? {} : { probe: deps.probe }),
150
- ...(deps.values === undefined ? {} : { values: deps.values }),
151
- ...(longTasks === undefined ? {} : { longTasks: longTasks.host }),
152
- store,
153
- });
154
- mounted.push({ face, readiness, result: withRunsRoute(result, unit) });
155
- }
156
- const collected = collectRoutes(mounted);
157
- const prefs = collectPrefs(mounted);
158
- const actions = collectActions(mounted);
159
- const owners = new Map(collected.owners);
160
- for (const entry of [...prefs, ...actions])
161
- owners.set(entry.resource, entry.unit);
162
- const factsOf = new Map();
163
- for (const item of mounted) {
164
- const declare = item.result.factsOf;
165
- if (declare !== undefined)
166
- factsOf.set(item.face.manifest.id, declare);
167
- }
168
- return {
169
- mounted,
170
- routes: collected.routes,
171
- owners,
172
- routesOfUnit: collected.routesOfUnit,
173
- factsOf,
174
- gate: pickGate(mounted),
175
- prefs,
176
- actions,
177
- provision: pickProvision(mounted),
178
- contextRenderers: collectContextRenderers(mounted),
179
- skipped,
180
- warmReads: collectWarmReads(mounted),
181
- disposeLongTasks: () => {
182
- for (const dispose of longTaskDisposers.splice(0))
183
- dispose();
184
- },
185
- };
186
- }
@@ -1,58 +0,0 @@
1
- import type { DshShell } from '@dsh-workbench/shared';
2
- export type PreflightStepId = 'opencli' | 'bridge' | 'warm';
3
- export type PreflightStepStatus = 'pending' | 'running' | 'ok' | 'warn' | 'failed';
4
- export interface PreflightStep {
5
- readonly id: PreflightStepId;
6
- readonly status: PreflightStepStatus;
7
- readonly detail?: string;
8
- readonly action?: string;
9
- readonly command?: string;
10
- }
11
- export type PreflightFailure = 'permission' | 'network' | 'missing' | 'unknown';
12
- export declare function classifyFailure(text: string): PreflightFailure;
13
- export type PreflightGuidance = 'install' | 'path' | 'shell';
14
- export type PreflightBridgeIssue = 'daemon' | 'extension' | 'profile' | 'stale' | 'unknown';
15
- export declare function readBridgeReport(stdout: string): {
16
- readonly ok: boolean;
17
- readonly issues: readonly PreflightBridgeIssue[];
18
- readonly detail: string;
19
- };
20
- export interface PreflightSnapshot {
21
- readonly phase: 'idle' | 'checking' | 'installing' | 'ready' | 'failed';
22
- readonly steps: readonly PreflightStep[];
23
- readonly at: number;
24
- readonly error?: string;
25
- readonly failure?: PreflightFailure;
26
- readonly guidance?: PreflightGuidance;
27
- readonly bridgeIssues?: readonly PreflightBridgeIssue[];
28
- }
29
- export interface Preflight {
30
- run(options?: {
31
- force?: boolean;
32
- }): Promise<PreflightSnapshot>;
33
- snapshot(): PreflightSnapshot;
34
- }
35
- export declare const OPENCLI_INSTALL_COMMAND: string;
36
- export interface BridgeVerdict {
37
- readonly ok: boolean;
38
- readonly detail: string;
39
- readonly issues: readonly PreflightBridgeIssue[];
40
- readonly command?: string | undefined;
41
- }
42
- export declare function canWarm(bridge: {
43
- ok: boolean;
44
- issues: readonly PreflightBridgeIssue[];
45
- }): boolean;
46
- export declare function createPreflight(options: {
47
- shell: DshShell;
48
- command?: string;
49
- installCommand?: string;
50
- logger?: {
51
- warn?(message: string): void;
52
- } | undefined;
53
- install?: (() => Promise<{
54
- ok: boolean;
55
- detail: string;
56
- }>) | undefined;
57
- warmReads?: (() => readonly (readonly string[])[]) | undefined;
58
- }): Preflight;
@@ -1,233 +0,0 @@
1
- import { INSTALL_TIMEOUT_MS, OPENCLI_TIMEOUT_MS, WARM_TIMEOUT_MS } from '@dsh-workbench/shared';
2
- import { tailLines } from '@dsh-workbench/shared';
3
- import { opencliCommandLine } from './opencli';
4
- import { isolatedInstallCommand } from './opencli-runtime';
5
- import { runShell } from './shell';
6
- export function classifyFailure(text) {
7
- const lower = text.toLowerCase();
8
- if (/eacces|eperm|permission denied|operation not permitted/.test(lower))
9
- return 'permission';
10
- if (/enotfound|etimedout|econnrefused|econnreset|network|proxy|fetch failed/.test(lower))
11
- return 'network';
12
- if (/command not found|not found|no such file/.test(lower))
13
- return 'missing';
14
- return 'unknown';
15
- }
16
- export function readBridgeReport(stdout) {
17
- const text = String(stdout ?? '');
18
- const ok = /^\[OK\] Daemon:/m.test(text) && /^\[OK\] Extension:/m.test(text) && /^\[OK\] Connectivity:/m.test(text);
19
- if (ok) {
20
- const good = text.split('\n').find((line) => line.trim() === 'Everything looks good!');
21
- return { ok: true, issues: [], detail: good?.trim() ?? tailLines(text, 1) };
22
- }
23
- const found = new Set();
24
- if (!/^\[OK\] Daemon:/m.test(text))
25
- found.add('daemon');
26
- if (!/^\[OK\] Extension:/m.test(text))
27
- found.add('extension');
28
- if (/Multiple Chrome profiles are connected/i.test(text))
29
- found.add('profile');
30
- if (/Default browser profile is stale|Selected browser profile is not connected/i.test(text)) {
31
- found.add('stale');
32
- }
33
- if (found.has('profile') || found.has('stale'))
34
- found.delete('extension');
35
- if (found.size === 0)
36
- found.add('unknown');
37
- const order = ['profile', 'stale', 'daemon', 'extension', 'unknown'];
38
- return { ok: false, issues: order.filter((issue) => found.has(issue)), detail: issuesSection(text) };
39
- }
40
- function issuesSection(text) {
41
- const lines = text.split('\n');
42
- const start = lines.findIndex((line) => /^Issues:/.test(line.trim()));
43
- if (start < 0)
44
- return tailLines(text, 6);
45
- return lines.slice(start).join('\n').trim();
46
- }
47
- function bridgeFixCommand(command, issues) {
48
- if (issues.includes('profile') || issues.includes('stale'))
49
- return `${command} profile list`;
50
- if (issues.includes('daemon') || issues.includes('extension'))
51
- return `${command} daemon restart`;
52
- return undefined;
53
- }
54
- export const OPENCLI_INSTALL_COMMAND = isolatedInstallCommand();
55
- const WARMABLE_BRIDGE_ISSUES = ['daemon', 'stale'];
56
- export function canWarm(bridge) {
57
- return bridge.ok || bridge.issues.every((issue) => WARMABLE_BRIDGE_ISSUES.includes(issue));
58
- }
59
- function step(id) {
60
- return { id, status: 'pending' };
61
- }
62
- export function createPreflight(options) {
63
- const { shell, command = 'opencli', logger } = options;
64
- const installCommand = options.installCommand ?? OPENCLI_INSTALL_COMMAND;
65
- const warmReads = () => options.warmReads?.() ?? [];
66
- const steps = () => [
67
- step('opencli'),
68
- step('bridge'),
69
- ...(warmReads().length === 0 ? [] : [step('warm')]),
70
- ];
71
- let current = { phase: 'idle', steps: steps(), at: Date.now() };
72
- let running = null;
73
- let latest = null;
74
- let rerun = false;
75
- function set(next) {
76
- current = { ...current, ...next, at: Date.now() };
77
- return current;
78
- }
79
- function patchStep(id, patch) {
80
- return set({ steps: current.steps.map((item) => (item.id === id ? { ...item, ...patch } : item)) });
81
- }
82
- async function exec(commandLine, timeoutMs) {
83
- try {
84
- const result = await runShell(shell, commandLine, { timeoutMs });
85
- if (result.timedOut) {
86
- return { kind: 'error', detail: `超时(${String(timeoutMs)} ms):${commandLine}` };
87
- }
88
- if (result.exitCode !== 0) {
89
- return { kind: 'nonzero', detail: tailLines(result.stderr || result.stdout, 4) };
90
- }
91
- return { kind: 'ok', stdout: result.stdout };
92
- }
93
- catch (error) {
94
- return { kind: 'error', detail: String(error) };
95
- }
96
- }
97
- async function probeVersion() {
98
- const result = await exec(`${command} --version`, OPENCLI_TIMEOUT_MS);
99
- if (result.kind === 'ok')
100
- return { ok: true, missing: false, detail: result.stdout.trim().split('\n')[0] ?? '' };
101
- return { ok: false, missing: result.kind === 'nonzero', detail: result.detail };
102
- }
103
- async function probeBridge() {
104
- const result = await exec(`${command} doctor`, OPENCLI_TIMEOUT_MS);
105
- if (result.kind !== 'ok')
106
- return { ok: false, detail: result.detail, issues: ['unknown'] };
107
- const report = readBridgeReport(result.stdout);
108
- if (report.ok)
109
- return report;
110
- return { ...report, command: bridgeFixCommand(command, report.issues) };
111
- }
112
- async function installOpencli() {
113
- if (options.install !== undefined)
114
- return options.install();
115
- const result = await exec(installCommand, INSTALL_TIMEOUT_MS);
116
- if (result.kind !== 'ok')
117
- return { ok: false, detail: result.detail };
118
- return { ok: true, detail: tailLines(result.stdout, 1) };
119
- }
120
- async function warmSites(bridge) {
121
- const reads = warmReads();
122
- if (reads.length === 0)
123
- return bridge;
124
- if (!canWarm(bridge)) {
125
- patchStep('warm', { status: 'warn', detail: '' });
126
- return bridge;
127
- }
128
- patchStep('warm', {
129
- status: 'running',
130
- action: `${command} <套件自己声明的那条读命令> --site-session persistent -f json`,
131
- });
132
- const results = await Promise.all(reads.map((read) => exec(opencliCommandLine(command, read), WARM_TIMEOUT_MS)));
133
- const failed = reads.filter((_, index) => results[index]?.kind !== 'ok');
134
- patchStep('warm', {
135
- status: failed.length === 0 ? 'ok' : 'warn',
136
- detail: failed.length === 0 ? String(reads.length) : failed.map((read) => read.join(' ')).join(' '),
137
- action: undefined,
138
- });
139
- if (bridge.ok)
140
- return bridge;
141
- const again = await probeBridge();
142
- patchStep('bridge', {
143
- status: again.ok ? 'ok' : 'warn',
144
- detail: again.detail,
145
- action: undefined,
146
- command: again.command,
147
- });
148
- return again;
149
- }
150
- async function doRun() {
151
- set({ phase: 'checking', error: undefined, failure: undefined, steps: steps() });
152
- patchStep('opencli', { status: 'running', action: `${command} --version` });
153
- let version = await probeVersion();
154
- if (!version.ok && !version.missing) {
155
- patchStep('opencli', { status: 'failed', detail: version.detail, action: undefined });
156
- return set({
157
- phase: 'failed',
158
- error: version.detail,
159
- failure: classifyFailure(version.detail),
160
- guidance: 'shell',
161
- });
162
- }
163
- if (!version.ok) {
164
- set({ phase: 'installing' });
165
- patchStep('opencli', { status: 'running', action: installCommand, command: installCommand });
166
- const installed = await installOpencli();
167
- if (!installed.ok) {
168
- patchStep('opencli', {
169
- status: 'failed',
170
- detail: installed.detail,
171
- command: installCommand,
172
- });
173
- return set({
174
- phase: 'failed',
175
- error: installed.detail,
176
- failure: classifyFailure(installed.detail),
177
- guidance: 'install',
178
- });
179
- }
180
- patchStep('opencli', { status: 'running', action: `${command} --version` });
181
- version = await probeVersion();
182
- if (!version.ok) {
183
- patchStep('opencli', { status: 'failed', detail: version.detail, command: installCommand });
184
- return set({
185
- phase: 'failed',
186
- error: version.detail,
187
- failure: classifyFailure(version.detail),
188
- guidance: 'path',
189
- });
190
- }
191
- }
192
- patchStep('opencli', { status: 'ok', detail: version.detail, action: undefined });
193
- patchStep('bridge', { status: 'running', action: `${command} doctor` });
194
- const bridge = await probeBridge();
195
- const healable = !bridge.ok && warmReads().length > 0 && canWarm(bridge);
196
- if (!healable) {
197
- patchStep('bridge', {
198
- status: bridge.ok ? 'ok' : 'warn',
199
- detail: bridge.detail,
200
- action: undefined,
201
- ...(bridge.command === undefined ? {} : { command: bridge.command }),
202
- });
203
- }
204
- const settled = await warmSites(bridge);
205
- logger?.warn?.(`[dsh-workbench] 环境体检:${current.steps.map((item) => `${item.id}=${item.status}`).join(' ')}`);
206
- return set({ phase: 'ready', ...(settled.ok ? {} : { bridgeIssues: settled.issues }) });
207
- }
208
- async function start(runOptions = {}) {
209
- if (running !== null) {
210
- if (runOptions.force === true)
211
- rerun = true;
212
- return running;
213
- }
214
- if (runOptions.force !== true && latest !== null)
215
- return latest;
216
- const inflight = doRun();
217
- latest = inflight;
218
- running = inflight;
219
- await inflight.catch(() => undefined);
220
- running = null;
221
- if (rerun) {
222
- rerun = false;
223
- return start({ force: true });
224
- }
225
- return inflight;
226
- }
227
- return {
228
- run: start,
229
- snapshot() {
230
- return current;
231
- },
232
- };
233
- }