@dsh-workbench/adapter-runtime 0.0.0-stage → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +36 -2
- package/channel/core.js +237 -0
- package/channel/fetch.js +14 -0
- package/channel/opencli-plugin.json +6 -0
- package/channel/package.json +10 -0
- package/channel/send.js +27 -0
- package/dist/browser/browser-find.d.ts +38 -0
- package/dist/browser/browser-find.js +242 -0
- package/dist/browser/browser-read.d.ts +27 -0
- package/dist/browser/browser-read.js +242 -0
- package/dist/browser/index.d.ts +2 -0
- package/dist/browser/index.js +2 -0
- package/dist/cli/command.d.ts +16 -0
- package/dist/cli/command.js +30 -0
- package/dist/cli/index.d.ts +5 -0
- package/dist/cli/index.js +5 -0
- package/dist/cli/opencli-runtime.d.ts +17 -0
- package/dist/cli/opencli-runtime.js +44 -0
- package/dist/cli/opencli-types.d.ts +12 -0
- package/dist/cli/opencli-types.js +1 -0
- package/dist/cli/opencli-window.d.ts +2 -0
- package/dist/cli/opencli-window.js +2 -0
- package/dist/cli/opencli.d.ts +13 -0
- package/dist/cli/opencli.js +136 -0
- package/dist/command/index.d.ts +7 -0
- package/dist/command/index.js +71 -0
- package/dist/data/channel.d.ts +19 -0
- package/dist/data/channel.js +121 -0
- package/dist/data/index.d.ts +10 -0
- package/dist/data/index.js +359 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +36 -0
- package/dist/git/index.d.ts +9 -0
- package/dist/git/index.js +60 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/libs/index.d.ts +6 -0
- package/dist/libs/index.js +46 -0
- package/package.json +32 -3
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { parseJsonLoose } from '@dsh-workbench/shared/host';
|
|
2
|
+
import { tailLines } from '@dsh-workbench/shared/host';
|
|
3
|
+
import { backgroundLine } from '../cli/index.js';
|
|
4
|
+
import { runShell } from '@dsh-workbench/shared/host';
|
|
5
|
+
import { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION } from '@dsh-workbench/shared/host';
|
|
6
|
+
export { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION };
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 25000;
|
|
8
|
+
const DEFAULT_RETRY_MS = 1200;
|
|
9
|
+
const DEFAULT_SETTLE_MS = 900;
|
|
10
|
+
const AUTH_CODES = new Set([
|
|
11
|
+
'NOT_LOGGED_IN',
|
|
12
|
+
'NOT_LOGIN',
|
|
13
|
+
'AUTH_FAILED',
|
|
14
|
+
'AUTH_REQUIRED',
|
|
15
|
+
'UNAUTHENTICATED',
|
|
16
|
+
'UNAUTHORIZED',
|
|
17
|
+
'TOKEN_EXPIRED',
|
|
18
|
+
]);
|
|
19
|
+
const PERMISSION_CODES = new Set(['FORBIDDEN', 'PERMISSION_DENIED', 'NO_PERMISSION', 'EACCES']);
|
|
20
|
+
function asRecord(value) {
|
|
21
|
+
return typeof value === 'object' && value !== null ? value : undefined;
|
|
22
|
+
}
|
|
23
|
+
function textOf(value) {
|
|
24
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
25
|
+
}
|
|
26
|
+
function codeOf(page) {
|
|
27
|
+
const record = asRecord(page);
|
|
28
|
+
return record === undefined ? '' : textOf(record['code']);
|
|
29
|
+
}
|
|
30
|
+
function messageOf(page) {
|
|
31
|
+
const record = asRecord(page);
|
|
32
|
+
return record === undefined ? '' : textOf(record['message']);
|
|
33
|
+
}
|
|
34
|
+
function hintOf(page) {
|
|
35
|
+
const record = asRecord(page);
|
|
36
|
+
const hint = record === undefined ? '' : textOf(record['hint']);
|
|
37
|
+
return hint === '' ? undefined : hint;
|
|
38
|
+
}
|
|
39
|
+
function pageFailed(page) {
|
|
40
|
+
const record = asRecord(page);
|
|
41
|
+
return record !== undefined && record['ok'] === false;
|
|
42
|
+
}
|
|
43
|
+
function blockerFor(code) {
|
|
44
|
+
const normalized = code.trim().toUpperCase().replace(/-/g, '_');
|
|
45
|
+
if (normalized === '')
|
|
46
|
+
return undefined;
|
|
47
|
+
const matches = (set) => [...set].some((one) => normalized === one || normalized.endsWith(`_${one}`));
|
|
48
|
+
if (matches(PERMISSION_CODES))
|
|
49
|
+
return 'permission-denied';
|
|
50
|
+
if (matches(AUTH_CODES) || normalized.includes('UNAUTH'))
|
|
51
|
+
return 'auth-required';
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
function sleep(ms) {
|
|
55
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
56
|
+
}
|
|
57
|
+
async function shellRun(shell, command, argv, timeoutMs) {
|
|
58
|
+
const result = await runShell(shell, backgroundLine(command, argv), { timeoutMs });
|
|
59
|
+
if (result.timedOut) {
|
|
60
|
+
return { kind: 'timeout', detail: `没在 ${Math.round(timeoutMs / 1000)} 秒内返回`, stderr: result.stderr };
|
|
61
|
+
}
|
|
62
|
+
if (result.exitCode !== 0) {
|
|
63
|
+
return { kind: 'failed', detail: tailLines(result.stderr || result.stdout, 4), stderr: result.stderr };
|
|
64
|
+
}
|
|
65
|
+
return { kind: 'ok', stdout: result.stdout };
|
|
66
|
+
}
|
|
67
|
+
async function evalOnce(shell, command, session, script, timeoutMs, retryMs) {
|
|
68
|
+
const run = async () => {
|
|
69
|
+
let attempt;
|
|
70
|
+
try {
|
|
71
|
+
attempt = await shellRun(shell, command, ['browser', session, 'eval', script, '--window', 'background'], timeoutMs);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
return {
|
|
75
|
+
kind: 'failure',
|
|
76
|
+
result: {
|
|
77
|
+
ok: false,
|
|
78
|
+
code: 'cli-exec-failed',
|
|
79
|
+
message: '读不了:后台服务起不来',
|
|
80
|
+
hint: '确认后台服务能跑起来,再重试',
|
|
81
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
if (attempt.kind === 'timeout') {
|
|
86
|
+
return {
|
|
87
|
+
kind: 'failure',
|
|
88
|
+
result: {
|
|
89
|
+
ok: false,
|
|
90
|
+
code: 'cli-timeout',
|
|
91
|
+
message: '这次没读到(等超时了)',
|
|
92
|
+
hint: '稍后重试',
|
|
93
|
+
detail: attempt.detail,
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (attempt.kind === 'failed') {
|
|
98
|
+
const normalized = attempt.stderr.trim().toUpperCase().replace(/-/g, '_');
|
|
99
|
+
const forbidden = [...PERMISSION_CODES].some((one) => normalized.includes(one));
|
|
100
|
+
return {
|
|
101
|
+
kind: 'failure',
|
|
102
|
+
result: {
|
|
103
|
+
ok: false,
|
|
104
|
+
code: forbidden ? 'permission-denied' : 'cli-exec-failed',
|
|
105
|
+
message: forbidden ? '没有权限在这台机器上读' : '读不了(命令失败)',
|
|
106
|
+
hint: forbidden ? '换一个有权限的账号,或让用户开权限' : '把下面这段原始输出看一眼再重试',
|
|
107
|
+
detail: attempt.detail,
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const value = parseJsonLoose(attempt.stdout);
|
|
112
|
+
if (value === undefined) {
|
|
113
|
+
return {
|
|
114
|
+
kind: 'failure',
|
|
115
|
+
result: {
|
|
116
|
+
ok: false,
|
|
117
|
+
code: 'cli-exec-failed',
|
|
118
|
+
message: '读到的格式不对',
|
|
119
|
+
hint: '让 agent 检查一下这条读',
|
|
120
|
+
detail: tailLines(attempt.stdout, 4),
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return { kind: 'value', value };
|
|
125
|
+
};
|
|
126
|
+
const first = await run();
|
|
127
|
+
if (first.kind === 'value')
|
|
128
|
+
return first;
|
|
129
|
+
if (first.result.code !== 'cli-exec-failed')
|
|
130
|
+
return first;
|
|
131
|
+
await sleep(retryMs);
|
|
132
|
+
return run();
|
|
133
|
+
}
|
|
134
|
+
async function openOnce(shell, command, session, url, timeoutMs) {
|
|
135
|
+
let attempt;
|
|
136
|
+
try {
|
|
137
|
+
attempt = await shellRun(shell, command, ['browser', session, 'open', url, '--window', 'background'], timeoutMs);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
code: 'cli-exec-failed',
|
|
143
|
+
message: '打不开那个页面',
|
|
144
|
+
hint: '确认后台服务能跑起来,再重试',
|
|
145
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
146
|
+
helpUrl: url,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (attempt.kind === 'ok')
|
|
150
|
+
return undefined;
|
|
151
|
+
return {
|
|
152
|
+
ok: false,
|
|
153
|
+
code: attempt.kind === 'timeout' ? 'cli-timeout' : 'cli-exec-failed',
|
|
154
|
+
message: '打不开那个页面',
|
|
155
|
+
hint: '在浏览器里手动打开一次,然后重试',
|
|
156
|
+
detail: attempt.detail,
|
|
157
|
+
helpUrl: url,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
export async function browserRead(options) {
|
|
161
|
+
const { shell, script, url, loginUrl, open = true } = options;
|
|
162
|
+
const command = options.command ?? 'opencli';
|
|
163
|
+
const session = options.session ?? BROWSER_READ_SESSION;
|
|
164
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
165
|
+
const retryMs = options.retryMs ?? DEFAULT_RETRY_MS;
|
|
166
|
+
const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
|
|
167
|
+
const at = Date.now();
|
|
168
|
+
const first = await evalOnce(shell, command, session, script, timeoutMs, retryMs);
|
|
169
|
+
if (first.kind === 'failure')
|
|
170
|
+
return { ...first.result, at };
|
|
171
|
+
let page = first.value;
|
|
172
|
+
if (codeOf(page) === 'not-on-site') {
|
|
173
|
+
if (!open || url === undefined) {
|
|
174
|
+
return {
|
|
175
|
+
ok: false,
|
|
176
|
+
code: 'cli-exec-failed',
|
|
177
|
+
at,
|
|
178
|
+
message: '没停在那套系统上',
|
|
179
|
+
hint: '先在那个浏览器里把它打开,再读一次',
|
|
180
|
+
detail: JSON.stringify(page),
|
|
181
|
+
...(url === undefined ? {} : { helpUrl: url }),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const opened = await openOnce(shell, command, session, url, timeoutMs);
|
|
185
|
+
if (opened !== undefined)
|
|
186
|
+
return { ...opened, at };
|
|
187
|
+
await sleep(settleMs);
|
|
188
|
+
const second = await evalOnce(shell, command, session, script, timeoutMs, retryMs);
|
|
189
|
+
if (second.kind === 'failure')
|
|
190
|
+
return { ...second.result, at };
|
|
191
|
+
page = second.value;
|
|
192
|
+
if (codeOf(page) === 'not-on-site') {
|
|
193
|
+
return {
|
|
194
|
+
ok: false,
|
|
195
|
+
code: 'cli-exec-failed',
|
|
196
|
+
at,
|
|
197
|
+
message: '打开了页面、又读了一遍,仍然不在那套系统上',
|
|
198
|
+
hint: '确认这个地址就是那套系统(或者它跳到了别的域)',
|
|
199
|
+
detail: JSON.stringify(page),
|
|
200
|
+
helpUrl: url,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (!pageFailed(page))
|
|
205
|
+
return { ok: true, code: 'ok', at, value: page, message: '读到了' };
|
|
206
|
+
const pageCode = codeOf(page) || 'read-failed';
|
|
207
|
+
const message = messageOf(page) || `读不到(${pageCode})`;
|
|
208
|
+
const blocker = blockerFor(pageCode);
|
|
209
|
+
if (blocker === 'auth-required') {
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
code: blocker,
|
|
213
|
+
at,
|
|
214
|
+
pageCode,
|
|
215
|
+
message,
|
|
216
|
+
hint: '去登录一次,再重试',
|
|
217
|
+
detail: JSON.stringify(page),
|
|
218
|
+
...(loginUrl === undefined && url === undefined ? {} : { helpUrl: loginUrl ?? url }),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
if (blocker === 'permission-denied') {
|
|
222
|
+
return {
|
|
223
|
+
ok: false,
|
|
224
|
+
code: blocker,
|
|
225
|
+
at,
|
|
226
|
+
pageCode,
|
|
227
|
+
message,
|
|
228
|
+
hint: '这个账号没有权限',
|
|
229
|
+
detail: JSON.stringify(page),
|
|
230
|
+
...(loginUrl === undefined && url === undefined ? {} : { helpUrl: loginUrl ?? url }),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
ok: false,
|
|
235
|
+
code: pageCode,
|
|
236
|
+
at,
|
|
237
|
+
pageCode,
|
|
238
|
+
message,
|
|
239
|
+
detail: JSON.stringify(page),
|
|
240
|
+
...(hintOf(page) === undefined ? {} : { hint: hintOf(page) }),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type OpencliSource = 'env' | 'isolated' | 'path';
|
|
2
|
+
export interface HostContextLike {
|
|
3
|
+
get<T = unknown>(name: string): T | undefined;
|
|
4
|
+
}
|
|
5
|
+
export interface OpencliResolution {
|
|
6
|
+
readonly command: string;
|
|
7
|
+
readonly source: OpencliSource;
|
|
8
|
+
readonly isolated: string | null;
|
|
9
|
+
}
|
|
10
|
+
export declare const OPENCLI_PATH_FALLBACK = "opencli";
|
|
11
|
+
export declare function isolatedOpencliPathOf(ctx: HostContextLike): string | null;
|
|
12
|
+
export declare function opencliCommandOf(ctx: HostContextLike): OpencliResolution;
|
|
13
|
+
export * from './opencli.js';
|
|
14
|
+
export * from './opencli-runtime.js';
|
|
15
|
+
export * from './opencli-window.js';
|
|
16
|
+
export * from './opencli-types.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export const OPENCLI_PATH_FALLBACK = 'opencli';
|
|
4
|
+
function binName(platform = process.platform) {
|
|
5
|
+
return platform === 'win32' ? 'opencli.cmd' : 'opencli';
|
|
6
|
+
}
|
|
7
|
+
export function isolatedOpencliPathOf(ctx) {
|
|
8
|
+
const homePath = ctx.get('dshHomePath');
|
|
9
|
+
if (typeof homePath !== 'function')
|
|
10
|
+
return null;
|
|
11
|
+
try {
|
|
12
|
+
return join(homePath('workbench/opencli/bin'), binName());
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function opencliCommandOf(ctx) {
|
|
19
|
+
const isolated = isolatedOpencliPathOf(ctx);
|
|
20
|
+
const fromEnv = process.env.DSH_WORKBENCH_OPENCLI;
|
|
21
|
+
if (fromEnv !== undefined && fromEnv !== '')
|
|
22
|
+
return { command: fromEnv, source: 'env', isolated };
|
|
23
|
+
if (isolated !== null && existsSync(isolated))
|
|
24
|
+
return { command: isolated, source: 'isolated', isolated };
|
|
25
|
+
return { command: OPENCLI_PATH_FALLBACK, source: 'path', isolated };
|
|
26
|
+
}
|
|
27
|
+
export * from './opencli.js';
|
|
28
|
+
export * from './opencli-runtime.js';
|
|
29
|
+
export * from './opencli-window.js';
|
|
30
|
+
export * from './opencli-types.js';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const OPENCLI_NPM_PACKAGE = "@jackwener/opencli";
|
|
2
|
+
export declare function toolchainDir(): string;
|
|
3
|
+
export declare function toolchainOpencliDir(): string;
|
|
4
|
+
export declare const OPENCLI_CATALOG_ENV = "DSH_WB_OPENCLI_CATALOG";
|
|
5
|
+
export declare function cliCatalogPath(): string;
|
|
6
|
+
export declare function vendorPeerLink(): {
|
|
7
|
+
readonly dir: string;
|
|
8
|
+
readonly parent: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function npmCacheDir(): string;
|
|
11
|
+
export declare function isolatedCommand(): string;
|
|
12
|
+
export { libsPrefix } from '@dsh-workbench/shared/host';
|
|
13
|
+
export { libInstallCommand } from '@dsh-workbench/shared/host';
|
|
14
|
+
export declare function libDir(name: string): string;
|
|
15
|
+
export declare function isolatedInstallCommand(): string;
|
|
16
|
+
export declare function isolatedPnpmInstallCommand(pnpmCjs: string): string;
|
|
17
|
+
export { isolatedHome, isolatedRoot, vendorPluginsDir, vendorPrefix } from '@dsh-workbench/shared/host';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { OPENCLI_PIN } from '@dsh-workbench/shared/host';
|
|
2
|
+
import { quoteShellArg } from '@dsh-workbench/shared/host';
|
|
3
|
+
import { isolatedRoot, libsPrefix, vendorPrefix } from '@dsh-workbench/shared/host';
|
|
4
|
+
export const OPENCLI_NPM_PACKAGE = '@jackwener/opencli';
|
|
5
|
+
export function toolchainDir() {
|
|
6
|
+
return `${isolatedRoot()}/toolchain`;
|
|
7
|
+
}
|
|
8
|
+
export function toolchainOpencliDir() {
|
|
9
|
+
return `${toolchainDir()}/node_modules/${OPENCLI_NPM_PACKAGE}`;
|
|
10
|
+
}
|
|
11
|
+
export const OPENCLI_CATALOG_ENV = 'DSH_WB_OPENCLI_CATALOG';
|
|
12
|
+
export function cliCatalogPath() {
|
|
13
|
+
const override = process.env[OPENCLI_CATALOG_ENV]?.trim();
|
|
14
|
+
return override === undefined || override === ''
|
|
15
|
+
? `${toolchainOpencliDir()}/cli-manifest.json`
|
|
16
|
+
: override;
|
|
17
|
+
}
|
|
18
|
+
export function vendorPeerLink() {
|
|
19
|
+
const base = `${vendorPrefix()}/node_modules`;
|
|
20
|
+
const [scope] = OPENCLI_NPM_PACKAGE.split('/');
|
|
21
|
+
return { dir: `${base}/${OPENCLI_NPM_PACKAGE}`, parent: `${base}/${scope}` };
|
|
22
|
+
}
|
|
23
|
+
export function npmCacheDir() {
|
|
24
|
+
return `${isolatedRoot()}/npm-cache`;
|
|
25
|
+
}
|
|
26
|
+
export function isolatedCommand() {
|
|
27
|
+
const name = process.platform === 'win32' ? 'opencli.cmd' : 'opencli';
|
|
28
|
+
return `${isolatedRoot()}/bin/${name}`;
|
|
29
|
+
}
|
|
30
|
+
export { libsPrefix } from '@dsh-workbench/shared/host';
|
|
31
|
+
export { libInstallCommand } from '@dsh-workbench/shared/host';
|
|
32
|
+
export function libDir(name) {
|
|
33
|
+
return `${libsPrefix()}/node_modules/${name}`;
|
|
34
|
+
}
|
|
35
|
+
export function isolatedInstallCommand() {
|
|
36
|
+
return `npm i --prefix ${quoteShellArg(toolchainDir())} ${OPENCLI_NPM_PACKAGE}@${OPENCLI_PIN} --cache ${quoteShellArg(npmCacheDir())}`;
|
|
37
|
+
}
|
|
38
|
+
export function isolatedPnpmInstallCommand(pnpmCjs) {
|
|
39
|
+
const store = `${isolatedRoot()}/pnpm-store`;
|
|
40
|
+
return (`node ${quoteShellArg(pnpmCjs)} add --dir ${quoteShellArg(toolchainDir())} ` +
|
|
41
|
+
`${OPENCLI_NPM_PACKAGE}@${OPENCLI_PIN} --store-dir ${quoteShellArg(store)} ` +
|
|
42
|
+
`--allow-build=${OPENCLI_NPM_PACKAGE}`);
|
|
43
|
+
}
|
|
44
|
+
export { isolatedHome, isolatedRoot, vendorPluginsDir, vendorPrefix } from '@dsh-workbench/shared/host';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface OpencliResult {
|
|
2
|
+
readonly value: unknown;
|
|
3
|
+
readonly at: number;
|
|
4
|
+
}
|
|
5
|
+
export type OpencliSession = 'persistent' | 'ephemeral' | 'none';
|
|
6
|
+
export interface Opencli {
|
|
7
|
+
json(args: readonly string[], options?: {
|
|
8
|
+
key?: string;
|
|
9
|
+
workdir?: string;
|
|
10
|
+
session?: OpencliSession;
|
|
11
|
+
}): Promise<OpencliResult>;
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DshShell } from '@dsh-workbench/shared';
|
|
2
|
+
import type { Opencli, OpencliSession } from './opencli-types.js';
|
|
3
|
+
export declare function opencliCommandLine(command: string, argv: readonly string[], session?: OpencliSession): string;
|
|
4
|
+
export declare function createOpencli(options: {
|
|
5
|
+
shell: DshShell;
|
|
6
|
+
plugin: string;
|
|
7
|
+
logger?: {
|
|
8
|
+
warn?(message: string): void;
|
|
9
|
+
} | undefined;
|
|
10
|
+
command?: string;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
maxConcurrent?: number;
|
|
13
|
+
}): Opencli;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { OPENCLI_MAX_CONCURRENT, OPENCLI_TIMEOUT_MS } from '@dsh-workbench/shared/host';
|
|
2
|
+
import { parseJsonLoose } from '@dsh-workbench/shared/host';
|
|
3
|
+
import { quoteShellArg, tailLines } from '@dsh-workbench/shared/host';
|
|
4
|
+
import { helpUrlOf, parseCliErrorEnvelope } from '@dsh-workbench/shared/host';
|
|
5
|
+
import { backgroundPrefix } from './opencli-window.js';
|
|
6
|
+
import { runShell } from '@dsh-workbench/shared/host';
|
|
7
|
+
import { WorkbenchDataError } from '@dsh-workbench/shared/host';
|
|
8
|
+
const FORBIDDEN_CODES = new Set(['FORBIDDEN', 'PERMISSION_DENIED']);
|
|
9
|
+
const SITE_SESSION_ARGS = ['--site-session', 'persistent'];
|
|
10
|
+
export function opencliCommandLine(command, argv, session = 'persistent') {
|
|
11
|
+
return [
|
|
12
|
+
...backgroundPrefix(),
|
|
13
|
+
quoteShellArg(command),
|
|
14
|
+
...argv.map(quoteShellArg),
|
|
15
|
+
...(session === 'persistent' ? SITE_SESSION_ARGS : []),
|
|
16
|
+
'-f',
|
|
17
|
+
'json',
|
|
18
|
+
].join(' ');
|
|
19
|
+
}
|
|
20
|
+
export function createOpencli(options) {
|
|
21
|
+
const { shell, plugin, logger, command = 'opencli', timeoutMs = OPENCLI_TIMEOUT_MS, maxConcurrent = OPENCLI_MAX_CONCURRENT, } = options;
|
|
22
|
+
const inflight = new Map();
|
|
23
|
+
const MAX_CONCURRENT = maxConcurrent;
|
|
24
|
+
let running = 0;
|
|
25
|
+
const waiting = [];
|
|
26
|
+
async function acquire() {
|
|
27
|
+
if (running < MAX_CONCURRENT) {
|
|
28
|
+
running += 1;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
await new Promise((resolve) => waiting.push(resolve));
|
|
32
|
+
}
|
|
33
|
+
function release() {
|
|
34
|
+
const next = waiting.shift();
|
|
35
|
+
if (next === undefined)
|
|
36
|
+
running -= 1;
|
|
37
|
+
else
|
|
38
|
+
next();
|
|
39
|
+
}
|
|
40
|
+
async function runLimited(task) {
|
|
41
|
+
await acquire();
|
|
42
|
+
try {
|
|
43
|
+
return await task();
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
release();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function call(commandLine, workdir) {
|
|
50
|
+
let result;
|
|
51
|
+
try {
|
|
52
|
+
result = await runShell(shell, commandLine, {
|
|
53
|
+
...(workdir === undefined ? {} : { workdir }),
|
|
54
|
+
timeoutMs,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
throw new WorkbenchDataError('cli-exec-failed', `执行 opencli 失败:${String(error)}`, {
|
|
59
|
+
hint: '确认 opencli 已安装且在 PATH 里(which opencli)。',
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (result.timedOut) {
|
|
63
|
+
throw new WorkbenchDataError('cli-timeout', `opencli 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回`, { hint: '无头浏览器可能没起来,重试一次通常就好。' });
|
|
64
|
+
}
|
|
65
|
+
if (result.exitCode !== 0) {
|
|
66
|
+
const detail = tailLines(result.stderr || result.stdout, 6);
|
|
67
|
+
const envelope = parseCliErrorEnvelope(result.stderr) ?? parseCliErrorEnvelope(result.stdout);
|
|
68
|
+
const url = envelope === undefined ? undefined : helpUrlOf(envelope);
|
|
69
|
+
if (envelope?.code === 'AUTH_REQUIRED') {
|
|
70
|
+
throw new WorkbenchDataError('auth-required', envelope.message, {
|
|
71
|
+
detail,
|
|
72
|
+
...(url === undefined ? {} : { helpUrl: url }),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (envelope !== undefined && FORBIDDEN_CODES.has(envelope.code)) {
|
|
76
|
+
throw new WorkbenchDataError('permission-denied', envelope.message, {
|
|
77
|
+
detail,
|
|
78
|
+
...(url === undefined ? {} : { helpUrl: url }),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (envelope !== undefined) {
|
|
82
|
+
throw new WorkbenchDataError('cli-command-failed', `${envelope.code}:${envelope.message}`, {
|
|
83
|
+
detail,
|
|
84
|
+
...(envelope.help === undefined ? {} : { hint: envelope.help }),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
throw new WorkbenchDataError('cli-unclassified', `opencli 这条命令没跑通(退出码 ${result.exitCode}),而且没有结构化错误码`, {
|
|
88
|
+
detail,
|
|
89
|
+
hint: '多半是插件里没有这条命令(版本旧就会缺),也可能是命令自己失败了:先确认命令存在,再更新插件重试。',
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
const parsed = parseJsonLoose(result.stdout);
|
|
93
|
+
if (parsed === undefined) {
|
|
94
|
+
throw new WorkbenchDataError('cli-bad-output', 'opencli 输出不是 JSON', {
|
|
95
|
+
detail: tailLines(result.stdout, 4),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return parsed;
|
|
99
|
+
}
|
|
100
|
+
async function json(args, callOptions = {}) {
|
|
101
|
+
const { key, workdir } = callOptions;
|
|
102
|
+
const session = callOptions.session ?? 'persistent';
|
|
103
|
+
const callKey = key ?? args.map((arg) => String(arg)).join(' ');
|
|
104
|
+
const pending = inflight.get(callKey);
|
|
105
|
+
if (pending !== undefined)
|
|
106
|
+
return pending;
|
|
107
|
+
const commandLine = opencliCommandLine(command, [plugin, ...args], session);
|
|
108
|
+
const once = async () => {
|
|
109
|
+
const value = await call(commandLine, workdir);
|
|
110
|
+
return { value, at: Date.now() };
|
|
111
|
+
};
|
|
112
|
+
const task = runLimited(async () => {
|
|
113
|
+
try {
|
|
114
|
+
return await once();
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (!(error instanceof WorkbenchDataError) || error.code !== 'auth-required')
|
|
118
|
+
throw error;
|
|
119
|
+
return await once();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
inflight.set(callKey, task);
|
|
123
|
+
try {
|
|
124
|
+
return await task;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
128
|
+
logger?.warn?.(`[dsh-workbench] opencli 调用失败:${message}`);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
inflight.delete(callKey);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { json };
|
|
136
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { DshShell } from '@dsh-workbench/shared';
|
|
2
|
+
import type { CommandReader } from '@dsh-workbench/shared';
|
|
3
|
+
export interface CommandReaderOptions {
|
|
4
|
+
readonly shell: DshShell;
|
|
5
|
+
readonly tmpRoot?: string | undefined;
|
|
6
|
+
}
|
|
7
|
+
export declare function createCommandReader(options: CommandReaderOptions): CommandReader;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { quoteShellArg, runShell } from '@dsh-workbench/shared/host';
|
|
5
|
+
function quoteAll(argv) {
|
|
6
|
+
return argv.map((arg) => quoteShellArg(arg)).join(' ');
|
|
7
|
+
}
|
|
8
|
+
function writeFiles(request, tmpRoot) {
|
|
9
|
+
if (request.files === undefined || request.files.length === 0)
|
|
10
|
+
return undefined;
|
|
11
|
+
const dir = mkdtempSync(join(tmpRoot, 'dsh-wb-command-'));
|
|
12
|
+
const paths = request.files.map((file, index) => {
|
|
13
|
+
const suffix = file.suffix === undefined || file.suffix === '' ? '' : `.${file.suffix}`;
|
|
14
|
+
const path = join(dir, `file-${String(index)}${suffix}`);
|
|
15
|
+
writeFileSync(path, file.content, 'utf8');
|
|
16
|
+
return path;
|
|
17
|
+
});
|
|
18
|
+
return { dir, paths };
|
|
19
|
+
}
|
|
20
|
+
export function createCommandReader(options) {
|
|
21
|
+
const { shell } = options;
|
|
22
|
+
const tmpRoot = options.tmpRoot ?? tmpdir();
|
|
23
|
+
return {
|
|
24
|
+
async run(request) {
|
|
25
|
+
let temp;
|
|
26
|
+
try {
|
|
27
|
+
temp = writeFiles(request, tmpRoot);
|
|
28
|
+
const argv = [...request.argv];
|
|
29
|
+
if (temp !== undefined && request.appendFileArgs !== undefined) {
|
|
30
|
+
for (const path of temp.paths)
|
|
31
|
+
argv.push(request.appendFileArgs, path);
|
|
32
|
+
}
|
|
33
|
+
const result = await runShell(shell, quoteAll(argv), {
|
|
34
|
+
...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }),
|
|
35
|
+
...(request.cwd === undefined ? {} : { workdir: request.cwd }),
|
|
36
|
+
});
|
|
37
|
+
const filePaths = temp?.paths ?? [];
|
|
38
|
+
if (result.timedOut) {
|
|
39
|
+
return {
|
|
40
|
+
stdout: result.stdout,
|
|
41
|
+
stderr: result.stderr,
|
|
42
|
+
exitCode: result.exitCode ?? -1,
|
|
43
|
+
timedOut: true,
|
|
44
|
+
filePaths,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
stdout: result.stdout,
|
|
49
|
+
stderr: result.stderr,
|
|
50
|
+
exitCode: result.exitCode ?? -1,
|
|
51
|
+
timedOut: false,
|
|
52
|
+
filePaths,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
return {
|
|
57
|
+
stdout: '',
|
|
58
|
+
stderr: String(error),
|
|
59
|
+
exitCode: -1,
|
|
60
|
+
timedOut: false,
|
|
61
|
+
filePaths: temp?.paths ?? [],
|
|
62
|
+
error: String(error),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
if (temp !== undefined)
|
|
67
|
+
rmSync(temp.dir, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DshShell } from '@dsh-workbench/shared';
|
|
2
|
+
import type { CallOverrides, RequestRecipe } from '@dsh-workbench/shared/host';
|
|
3
|
+
export declare const CHANNEL_DIR: string;
|
|
4
|
+
export type ChannelState = 'unknown' | 'ready' | 'unavailable';
|
|
5
|
+
export interface ChannelCall {
|
|
6
|
+
readonly argv: readonly string[];
|
|
7
|
+
readonly timeoutMs: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function channelUrlOf(recipe: RequestRecipe, overrides: CallOverrides): string;
|
|
10
|
+
export declare function wireBodyOf(recipe: RequestRecipe, overrides: CallOverrides): {
|
|
11
|
+
readonly contentType: 'json' | 'form';
|
|
12
|
+
readonly body: string | undefined;
|
|
13
|
+
};
|
|
14
|
+
export declare function channelCallOf(recipe: RequestRecipe, overrides: CallOverrides, command: string): ChannelCall | undefined;
|
|
15
|
+
export declare function channelAlreadyInstalled(): boolean;
|
|
16
|
+
export declare function ensureChannel(shell: DshShell, command: string, state: {
|
|
17
|
+
value: ChannelState;
|
|
18
|
+
}, ready?: () => boolean): Promise<boolean>;
|
|
19
|
+
export declare function channelCommandLine(call: ChannelCall): string;
|