@dsh-workbench/adapter-runtime 1.4.0-beta.0 → 1.4.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.
@@ -2,5 +2,5 @@
2
2
  "name": "workbench",
3
3
  "version": "0.2.0",
4
4
  "description": "DSH 工作台的公共通道:用浏览器登录态在 Node 侧发请求",
5
- "opencli": ">=2.0.0 <3.0.0"
5
+ "opencli": ">=1.8.0 <3.0.0"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencli-plugin-workbench",
3
- "version": "1.4.0-beta.0",
3
+ "version": "1.4.0-beta.1",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "description": "DSH 工作台的公共通道:带浏览器登录态的 Node 侧 fetch,只服务 cookie / cookieValue 两种凭据来源",
@@ -1,8 +1,9 @@
1
- import { now, parseJsonLoose } from '@dsh-workbench/shared/host';
1
+ import { now } from '@dsh-workbench/shared/host';
2
2
  import { BROWSER_READ_SESSION } from './browser-read.js';
3
3
  import { backgroundLine, OPENCLI_WINDOW_ENV } from '../cli/index.js';
4
4
  import { noWrite } from '@dsh-workbench/shared/host';
5
5
  import { asRecord, textOf } from './page-value.js';
6
+ import { opencliResultOf } from '../cli/opencli-wire.js';
6
7
  const DEFAULT_TIMEOUT_MS = 25000;
7
8
  const DEFAULT_SETTLE_MS = 2500;
8
9
  const URL_TIMEOUT_MS = 8000;
@@ -43,7 +44,7 @@ export function entriesOf(value) {
43
44
  return entries;
44
45
  }
45
46
  export function reasonOf(stdout, stderr) {
46
- const parsed = asRecord(parseJsonLoose(stdout));
47
+ const parsed = asRecord(opencliResultOf(stdout));
47
48
  const error = parsed === undefined ? undefined : asRecord(parsed['error']);
48
49
  const message = error === undefined ? '' : textOf(error['message']);
49
50
  if (message !== '')
@@ -56,7 +57,7 @@ export function reasonOf(stdout, stderr) {
56
57
  return (lines[lines.length - 1] ?? '').slice(-200);
57
58
  }
58
59
  function hintOf(stdout) {
59
- const parsed = asRecord(parseJsonLoose(stdout));
60
+ const parsed = asRecord(opencliResultOf(stdout));
60
61
  const error = parsed === undefined ? undefined : asRecord(parsed['error']);
61
62
  const hint = error === undefined ? '' : textOf(error['hint']);
62
63
  return hint === '' ? undefined : hint;
@@ -77,7 +78,7 @@ export function urlOf(stdout) {
77
78
  const first = (lines[0] ?? '').replace(/^url:\s*/i, '').trim();
78
79
  const bare = first.replace(/^["']+|["']+$/g, '');
79
80
  if (bare.startsWith('{')) {
80
- const parsed = asRecord(parseJsonLoose(bare));
81
+ const parsed = asRecord(opencliResultOf(bare));
81
82
  const url = parsed === undefined ? '' : textOf(parsed['url']);
82
83
  if (url !== '')
83
84
  return url;
@@ -136,7 +137,7 @@ async function findOnce(seam, command, session, css, limit, textMax, timeoutMs)
136
137
  ...(hintOf(result.stdout) === undefined ? {} : { hint: hintOf(result.stdout) }),
137
138
  };
138
139
  }
139
- const entries = entriesOf(parseJsonLoose(result.stdout));
140
+ const entries = entriesOf(opencliResultOf(result.stdout));
140
141
  return { kind: 'ok', entries, stdout: result.stdout };
141
142
  }
142
143
  async function openOnce(seam, command, session, url, timeoutMs) {
@@ -1,9 +1,10 @@
1
- import { now, parseJsonLoose } from '@dsh-workbench/shared/host';
1
+ import { now } from '@dsh-workbench/shared/host';
2
2
  import { tailLines } from '@dsh-workbench/shared/host';
3
3
  import { backgroundLine, OPENCLI_WINDOW_ENV } from '../cli/index.js';
4
4
  import { noWrite } from '@dsh-workbench/shared/host';
5
5
  import { asRecord, textOf } from './page-value.js';
6
6
  import { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION } from '@dsh-workbench/shared/host';
7
+ import { opencliResultOf } from '../cli/opencli-wire.js';
7
8
  export { BROWSER_READ_SESSION, BROWSER_RECORD_SESSION, BROWSER_SCREEN_SESSION };
8
9
  const DEFAULT_TIMEOUT_MS = 25000;
9
10
  const DEFAULT_RETRY_MS = 1200;
@@ -77,7 +78,7 @@ async function shellRun(seam, command, argv, timeoutMs, platform, signal) {
77
78
  if (signal?.aborted === true)
78
79
  return { kind: 'aborted', detail: '已停止', stderr: '' };
79
80
  const result = await seam.run({
80
- command: backgroundLine(command, argv, platform),
81
+ command: backgroundLine(command, argv, { platform }),
81
82
  intent: noWrite(),
82
83
  retry: 'safe',
83
84
  timeoutMs,
@@ -140,7 +141,7 @@ async function evalOnce(seam, command, session, script, timeoutMs, retryMs, retr
140
141
  },
141
142
  };
142
143
  }
143
- const value = parseJsonLoose(attempt.stdout);
144
+ const value = opencliResultOf(attempt.stdout);
144
145
  if (value === undefined) {
145
146
  return {
146
147
  kind: 'failure',
@@ -1,6 +1,8 @@
1
+ export * from './opencli-session.js';
1
2
  export * from './opencli-window.js';
2
3
  export * from './opencli-types.js';
3
4
  export * from './opencli-runtime.js';
4
5
  export * from './opencli.js';
5
6
  export * from './opencli-report.js';
6
7
  export * from './command.js';
8
+ export * from './opencli-wire.js';
package/dist/cli/index.js CHANGED
@@ -1,6 +1,8 @@
1
+ export * from './opencli-session.js';
1
2
  export * from './opencli-window.js';
2
3
  export * from './opencli-types.js';
3
4
  export * from './opencli-runtime.js';
4
5
  export * from './opencli.js';
5
6
  export * from './opencli-report.js';
6
7
  export * from './command.js';
8
+ export * from './opencli-wire.js';
@@ -1,6 +1,7 @@
1
1
  import { type PluginPeerProblem } from './plugin-peers.js';
2
2
  export interface OpencliVersionReport {
3
3
  readonly pin: string;
4
+ readonly range: string;
4
5
  readonly cli?: string;
5
6
  readonly channel?: string;
6
7
  readonly peer: string;
@@ -1,6 +1,6 @@
1
1
  import { fileURLToPath } from 'node:url';
2
2
  import { join } from 'node:path';
3
- import { OPENCLI_PIN, OPENCLI_PIN_ENV, checkVersionRange, runtimePinOf } from '@dsh-workbench/shared/host';
3
+ import { OPENCLI_PIN, OPENCLI_PIN_ENV, OPENCLI_SUPPORTED_RANGE, checkVersionRange, runtimePinOf, } from '@dsh-workbench/shared/host';
4
4
  import { toolchainOpencliDir, vendorPluginsDir } from '../foundation/paths.js';
5
5
  import { pluginPeerProblems } from './plugin-peers.js';
6
6
  import { jsonAt as jsonOf, textOf } from './json-file.js';
@@ -16,18 +16,21 @@ export function opencliVersionReport() {
16
16
  const cli = textOf(jsonOf(join(toolchainOpencliDir(), 'package.json'))?.['version']);
17
17
  const channel = textOf(jsonOf(join(opencliChannelDir(), 'opencli-plugin.json'))?.['version']);
18
18
  const peer = opencliPeerRange();
19
- const peerProblems = pluginPeerProblems(pin);
19
+ const peerProblems = pluginPeerProblems(cli ?? pin);
20
20
  return {
21
21
  pin,
22
+ range: OPENCLI_SUPPORTED_RANGE,
22
23
  ...(cli === undefined ? {} : { cli }),
23
24
  ...(channel === undefined ? {} : { channel }),
24
25
  peer,
25
26
  peerProblems,
26
- compatible: checkVersionRange(peer, pin) !== 'unsatisfied' && peerProblems.length === 0,
27
+ compatible: checkVersionRange(OPENCLI_SUPPORTED_RANGE, cli ?? pin) !== 'unsatisfied' &&
28
+ checkVersionRange(peer, cli ?? pin) !== 'unsatisfied' &&
29
+ peerProblems.length === 0,
27
30
  };
28
31
  }
29
32
  export function opencliHandshakeOk(report) {
30
- return report.compatible && report.cli === report.pin;
33
+ return report.compatible && report.cli !== undefined;
31
34
  }
32
35
  export function opencliHandshakeNote(report) {
33
36
  if (report.peerProblems.length > 0) {
@@ -48,10 +51,10 @@ export function opencliHandshakeNote(report) {
48
51
  en: `the runtime does not have ${report.pin} yet — restart dsh; if it persists, reinstall the workbench`,
49
52
  };
50
53
  }
51
- if (report.cli !== report.pin) {
54
+ if (checkVersionRange(report.range, report.cli) === 'unsatisfied') {
52
55
  return {
53
- zh: `装的是 ${report.cli},这个版本要 ${report.pin} —— 重启一次 dsh;还不行就重装工作台`,
54
- en: `installed ${report.cli} but this build needs ${report.pin} — restart dsh; if it persists, reinstall the workbench`,
56
+ zh: `装的是 ${report.cli},这段只认 ${report.range} —— 重启一次 dsh;还不行就重装工作台`,
57
+ en: `installed ${report.cli} but this build accepts ${report.range} — restart dsh; if it persists, reinstall the workbench`,
55
58
  };
56
59
  }
57
60
  return undefined;
@@ -76,7 +79,7 @@ export function opencliHandshakeText(report) {
76
79
  }
77
80
  if (report.cli === undefined)
78
81
  return `隔离运行时里还没有 ${report.pin}`;
79
- if (report.cli !== report.pin)
80
- return `已装 ${report.cli},本版固定 ${report.pin}`;
81
- return `${report.pin} · 通道插件 ${report.channel ?? '未装'}`;
82
+ if (checkVersionRange(report.range, report.cli) === 'unsatisfied')
83
+ return `已装 ${report.cli},这段认 ${report.range}`;
84
+ return `${report.cli} · 通道插件 ${report.channel ?? '未装'}`;
82
85
  }
@@ -13,6 +13,7 @@ export declare function opencliReadiness(): {
13
13
  readonly detail: string;
14
14
  };
15
15
  export declare function isOpencliReadyAt(projectDir: string): boolean;
16
+ export declare function installedOpencliVersion(): string | undefined;
16
17
  export declare function isOpencliReady(): boolean;
17
18
  export declare function opencliBuiltAt(projectDir: string): string | undefined;
18
19
  export declare function cliCatalogPath(): string;
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { DEFAULT_NPM_REGISTRY, OPENCLI_CATALOG_ENV, OPENCLI_PIN, OPENCLI_PIN_ENV, OPENCLI_REGISTRY_ENV, runtimePinOf, } from '@dsh-workbench/shared/host';
3
+ import { DEFAULT_NPM_REGISTRY, OPENCLI_CATALOG_ENV, OPENCLI_PIN, OPENCLI_PIN_ENV, OPENCLI_SUPPORTED_RANGE, OPENCLI_REGISTRY_ENV, checkVersionRange, runtimePinOf, } from '@dsh-workbench/shared/host';
4
4
  import { quoteShellArg } from '@dsh-workbench/shared/host';
5
5
  import { isolatedRoot, libsPrefix, storeDirFor, toolchainOpencliDir } from '../foundation/paths.js';
6
6
  import { OPENCLI_NPM_PACKAGE } from '../foundation/paths.js';
@@ -44,10 +44,10 @@ export function opencliReadinessAt(projectDir) {
44
44
  return { ready: false, detail: '隔离副本缺 dist/src/main.js' };
45
45
  }
46
46
  const version = packageVersionOf(join(dir, 'package.json'));
47
- if (version !== runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)) {
48
- return { ready: false, detail: `隔离副本是 ${version ?? '读不到的版本'},要 ${runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV)}` };
47
+ if (version === undefined || checkVersionRange(OPENCLI_SUPPORTED_RANGE, version) === 'unsatisfied') {
48
+ return { ready: false, detail: `隔离副本是 ${version ?? '读不到的版本'},这段认 ${OPENCLI_SUPPORTED_RANGE}` };
49
49
  }
50
- return { ready: true, detail: runtimePinOf(OPENCLI_PIN, OPENCLI_PIN_ENV) };
50
+ return { ready: true, detail: version };
51
51
  }
52
52
  export function opencliReadiness() {
53
53
  return opencliReadinessAt(toolchainDir());
@@ -55,6 +55,9 @@ export function opencliReadiness() {
55
55
  export function isOpencliReadyAt(projectDir) {
56
56
  return opencliReadinessAt(projectDir).ready;
57
57
  }
58
+ export function installedOpencliVersion() {
59
+ return packageVersionOf(join(opencliPackageDir(toolchainDir()), 'package.json'));
60
+ }
58
61
  export function isOpencliReady() {
59
62
  return isOpencliReadyAt(toolchainDir());
60
63
  }
@@ -0,0 +1,4 @@
1
+ export type SessionDialect = 'flag' | 'positional';
2
+ export declare function sessionArgv(argv: readonly string[], dialect?: SessionDialect): readonly string[];
3
+ export declare function sessionDialectOf(version: string | undefined): SessionDialect;
4
+ export declare function tabArgv(argv: readonly string[], dialect?: SessionDialect): readonly string[];
@@ -0,0 +1,24 @@
1
+ export function sessionArgv(argv, dialect = 'flag') {
2
+ if (argv[0] !== 'browser')
3
+ return argv;
4
+ const session = argv[1];
5
+ if (session === undefined || session === '' || session.startsWith('-'))
6
+ return argv;
7
+ if (dialect === 'positional')
8
+ return argv;
9
+ return ['browser', '--session', session, ...argv.slice(2)];
10
+ }
11
+ export function sessionDialectOf(version) {
12
+ if (version === undefined)
13
+ return 'flag';
14
+ const major = Number.parseInt(version.trim().split('.')[0] ?? '', 10);
15
+ return Number.isFinite(major) && major < 2 ? 'positional' : 'flag';
16
+ }
17
+ export function tabArgv(argv, dialect = 'flag') {
18
+ if (dialect !== 'positional')
19
+ return argv;
20
+ const at = argv.indexOf('--tab');
21
+ if (at < 0)
22
+ return argv;
23
+ return [...argv.slice(0, at), ...argv.slice(at + 2)];
24
+ }
@@ -1,3 +1,8 @@
1
+ import { type SessionDialect } from './opencli-session.js';
1
2
  export declare const OPENCLI_WINDOW_ENV: Readonly<Record<string, string>>;
2
3
  export declare const OPENCLI_SITE_SESSION_ENV: Readonly<Record<string, string>>;
3
- export declare function backgroundLine(command: string, argv: readonly string[], platform?: NodeJS.Platform): string;
4
+ export interface BackgroundLineOptions {
5
+ readonly platform?: NodeJS.Platform;
6
+ readonly dialect?: SessionDialect;
7
+ }
8
+ export declare function backgroundLine(command: string, argv: readonly string[], options?: BackgroundLineOptions): string;
@@ -1,8 +1,13 @@
1
- import { quoteShellArgFor, sessionArgv } from '@dsh-workbench/shared/host';
1
+ import { quoteShellArgFor } from '@dsh-workbench/shared/host';
2
+ import { sessionArgv, tabArgv } from './opencli-session.js';
2
3
  export const OPENCLI_WINDOW_ENV = { OPENCLI_WINDOW: 'background' };
3
4
  export const OPENCLI_SITE_SESSION_ENV = {
4
5
  OPENCLI_SITE_SESSION: 'persistent',
5
6
  };
6
- export function backgroundLine(command, argv, platform = process.platform) {
7
- return [quoteShellArgFor(command, platform), ...sessionArgv(argv).map((arg) => quoteShellArgFor(arg, platform))].join(' ');
7
+ export function backgroundLine(command, argv, options = {}) {
8
+ const platform = options.platform ?? process.platform;
9
+ return [
10
+ quoteShellArgFor(command, platform),
11
+ ...tabArgv(sessionArgv(argv, options.dialect ?? 'flag'), options.dialect ?? 'flag').map((arg) => quoteShellArgFor(arg, platform)),
12
+ ].join(' ');
8
13
  }
@@ -0,0 +1,13 @@
1
+ import type { BrowserCaptureRow } from '@dsh-workbench/shared/host';
2
+ export declare function opencliJsonOf(raw: string): unknown;
3
+ export declare function opencliResultOf(raw: string): unknown;
4
+ export interface OpencliErrorEnvelope {
5
+ readonly code: string;
6
+ readonly message: string;
7
+ readonly help?: string;
8
+ readonly detail?: string;
9
+ readonly exitCode?: number;
10
+ }
11
+ export declare function opencliErrorOf(raw: string): OpencliErrorEnvelope | undefined;
12
+ export declare function opencliBrowserCaptureOf(text: string): readonly BrowserCaptureRow[];
13
+ export declare function opencliCaptureLinesOf(rows: readonly BrowserCaptureRow[]): string;
@@ -0,0 +1,206 @@
1
+ import { epochOf } from '@dsh-workbench/shared/host';
2
+ function objectOf(value) {
3
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
4
+ }
5
+ export function opencliJsonOf(raw) {
6
+ const trimmed = raw.trim();
7
+ if (trimmed === '')
8
+ return undefined;
9
+ try {
10
+ return JSON.parse(trimmed);
11
+ }
12
+ catch { }
13
+ const open = trimmed.search(/[{[]/);
14
+ if (open === -1)
15
+ return undefined;
16
+ const close = trimmed[open] === '[' ? trimmed.lastIndexOf(']') : trimmed.lastIndexOf('}');
17
+ if (close <= open)
18
+ return undefined;
19
+ try {
20
+ return JSON.parse(trimmed.slice(open, close + 1));
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ export function opencliResultOf(raw) {
27
+ const parsed = opencliJsonOf(raw);
28
+ if (parsed === undefined)
29
+ return undefined;
30
+ const box = objectOf(parsed);
31
+ if (typeof box['ok'] !== 'boolean')
32
+ return parsed;
33
+ if (!box['ok']) {
34
+ const error = objectOf(box['error']);
35
+ return Object.keys(error).length === 0 ? parsed : error;
36
+ }
37
+ if (!('data' in box))
38
+ return parsed;
39
+ const data = box['data'];
40
+ if (typeof data !== 'string')
41
+ return data;
42
+ const inner = opencliJsonOf(data);
43
+ return inner === undefined ? data : inner;
44
+ }
45
+ const ERROR_FIELDS = ['code', 'message', 'hint', 'help', 'details', 'expected', 'actual', 'available', 'available_keys', 'candidates', 'matches_n', 'download', 'outcome', 'cause', 'exitCode', 'trace'];
46
+ function extrasOf(error) {
47
+ const extra = {};
48
+ for (const key of ERROR_FIELDS) {
49
+ if (key === 'code' || key === 'message' || key === 'hint' || key === 'help')
50
+ continue;
51
+ if (key === 'exitCode')
52
+ continue;
53
+ const value = error[key];
54
+ if (value === undefined)
55
+ continue;
56
+ extra[key] = value;
57
+ }
58
+ if (Object.keys(extra).length === 0)
59
+ return '';
60
+ try {
61
+ const text = JSON.stringify(extra);
62
+ return text.length > 1200 ? `${text.slice(0, 1200)}…` : text;
63
+ }
64
+ catch {
65
+ return '';
66
+ }
67
+ }
68
+ export function opencliErrorOf(raw) {
69
+ const parsed = opencliJsonOf(raw);
70
+ if (parsed === undefined)
71
+ return undefined;
72
+ const box = objectOf(parsed);
73
+ const error = objectOf(typeof box['ok'] === 'boolean' ? box['error'] : box);
74
+ const code = typeof error['code'] === 'string' ? error['code'] : '';
75
+ const message = typeof error['message'] === 'string' ? error['message'] : '';
76
+ if (code === '' && message === '')
77
+ return undefined;
78
+ const hint = error['hint'] ?? error['help'];
79
+ const detail = extrasOf(error);
80
+ const exitCode = typeof error['exitCode'] === 'number' ? error['exitCode'] : undefined;
81
+ return {
82
+ code: code === '' ? 'cli-command-failed' : code,
83
+ message: message === '' ? code : message,
84
+ ...(typeof hint === 'string' && hint !== '' ? { help: hint } : {}),
85
+ ...(detail === '' ? {} : { detail }),
86
+ ...(exitCode === undefined ? {} : { exitCode }),
87
+ };
88
+ }
89
+ function numberOf(value) {
90
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
91
+ }
92
+ function textOf(value) {
93
+ if (typeof value === 'string')
94
+ return value;
95
+ if (typeof value === 'number' || typeof value === 'boolean')
96
+ return String(value);
97
+ if (typeof value === 'object' && value !== null) {
98
+ try {
99
+ return JSON.stringify(value);
100
+ }
101
+ catch {
102
+ return '';
103
+ }
104
+ }
105
+ return '';
106
+ }
107
+ function rowOf(value) {
108
+ const row = objectOf(value);
109
+ const url = row['url'];
110
+ const method = row['method'];
111
+ if (typeof url !== 'string' || url === '')
112
+ return null;
113
+ if (typeof method !== 'string' || method === '')
114
+ return null;
115
+ return {
116
+ key: typeof row['key'] === 'string' ? row['key'] : '',
117
+ at: numberOf(row['at']),
118
+ method: method.toUpperCase(),
119
+ url,
120
+ status: numberOf(row['status']),
121
+ ct: typeof row['ct'] === 'string' ? row['ct'] : '',
122
+ size: numberOf(row['size']),
123
+ request: typeof row['request'] === 'string' ? row['request'] : '',
124
+ response: typeof row['response'] === 'string' ? row['response'] : '',
125
+ requestFullSize: numberOf(row['requestFullSize']),
126
+ responseFullSize: numberOf(row['responseFullSize']),
127
+ requestSizeExact: row['requestSizeExact'] === true,
128
+ responseSizeExact: row['responseSizeExact'] === true,
129
+ headers: typeof row['headers'] === 'string' ? row['headers'] : '',
130
+ };
131
+ }
132
+ function capturedOf(value, lineAt) {
133
+ const row = objectOf(value);
134
+ const request = objectOf(row['request']);
135
+ const requestBody = textOf(request['body']);
136
+ const responseBody = textOf(row['body']);
137
+ const requestFull = numberOf(request['body_full_size']);
138
+ const responseFull = numberOf(row['body_full_size']);
139
+ const stamp = typeof row['timestamp'] === 'string' ? epochOf(row['timestamp']) : Number.NaN;
140
+ return rowOf({
141
+ key: row['key'],
142
+ at: Number.isFinite(stamp) ? stamp : lineAt,
143
+ method: row['method'],
144
+ url: row['url'],
145
+ status: row['status'],
146
+ ct: row['ct'],
147
+ size: row['size'],
148
+ request: requestBody,
149
+ response: responseBody,
150
+ requestFullSize: requestFull || requestBody.length,
151
+ responseFullSize: responseFull || responseBody.length,
152
+ requestSizeExact: requestFull > 0,
153
+ responseSizeExact: responseFull > 0,
154
+ headers: Object.keys(objectOf(request['headers'])).length === 0 ? '' : textOf(request['headers']),
155
+ });
156
+ }
157
+ function lineOf(raw) {
158
+ const trimmed = raw.trim();
159
+ if (trimmed === '')
160
+ return null;
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(trimmed);
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
169
+ return null;
170
+ const box = parsed;
171
+ const data = box['data'];
172
+ if (typeof box['ok'] === 'boolean' && typeof data === 'object' && data !== null && !Array.isArray(data)) {
173
+ return data;
174
+ }
175
+ return box;
176
+ }
177
+ export function opencliBrowserCaptureOf(text) {
178
+ const out = [];
179
+ for (const line of text.split('\n')) {
180
+ const row = lineOf(line);
181
+ if (row === null)
182
+ continue;
183
+ const lineAt = typeof row['captured_at'] === 'string' ? epochOf(row['captured_at']) : Number.NaN;
184
+ const inside = row['entries'];
185
+ if (Array.isArray(inside)) {
186
+ for (const one of inside) {
187
+ const mapped = capturedOf(one, lineAt);
188
+ if (mapped !== null)
189
+ out.push(mapped);
190
+ }
191
+ continue;
192
+ }
193
+ const own = rowOf(row);
194
+ if (own !== null && own.at > 0) {
195
+ out.push(own);
196
+ continue;
197
+ }
198
+ const mapped = capturedOf(row, lineAt);
199
+ if (mapped !== null)
200
+ out.push(mapped);
201
+ }
202
+ return out;
203
+ }
204
+ export function opencliCaptureLinesOf(rows) {
205
+ return rows.map((one) => JSON.stringify(one)).join('\n');
206
+ }
@@ -1,5 +1,6 @@
1
1
  import { OPENCLI_MAX_CONCURRENT, OPENCLI_TIMEOUT_MS, now } from '@dsh-workbench/shared/host';
2
2
  import { parseJsonLoose } from '@dsh-workbench/shared/host';
3
+ import { opencliErrorOf, opencliResultOf } from './opencli-wire.js';
3
4
  import { productWrite, quoteShellArgFor, tailLines } from '@dsh-workbench/shared/host';
4
5
  import { helpUrlOf, parseCliErrorEnvelope } from '@dsh-workbench/shared/host';
5
6
  import { OPENCLI_WINDOW_ENV } from './opencli-window.js';
@@ -70,18 +71,23 @@ export function createOpencli(options) {
70
71
  throw new WorkbenchDataError('cli-timeout', `opencli 超过 ${Math.round(timeoutMs / 1000)} 秒没有返回`, { hint: 'opencli 的本地 daemon 没回应(或浏览器扩展没连上),重试一次通常就好。' });
71
72
  }
72
73
  if (result.exitCode !== 0) {
73
- const detail = tailLines(result.stderr || result.stdout, 6);
74
- const envelope = parseCliErrorEnvelope(result.stderr) ?? parseCliErrorEnvelope(result.stdout);
74
+ const envelope = opencliErrorOf(result.stderr) ??
75
+ opencliErrorOf(result.stdout) ??
76
+ parseCliErrorEnvelope(result.stderr) ??
77
+ parseCliErrorEnvelope(result.stdout);
78
+ const detail = envelope !== undefined && 'detail' in envelope && typeof envelope.detail === 'string' && envelope.detail !== ''
79
+ ? envelope.detail
80
+ : tailLines(result.stderr || result.stdout, 6);
75
81
  const url = envelope === undefined ? undefined : helpUrlOf(envelope);
76
- if (envelope?.code === 'AUTH_REQUIRED') {
77
- throw new WorkbenchDataError('auth-required', envelope.message, {
78
- detail,
79
- ...(url === undefined ? {} : { helpUrl: url }),
80
- });
81
- }
82
- if (envelope !== undefined && FORBIDDEN_CODES.has(envelope.code)) {
83
- throw new WorkbenchDataError('permission-denied', envelope.message, {
82
+ const blocked = envelope?.code === 'AUTH_REQUIRED'
83
+ ? 'auth-required'
84
+ : envelope !== undefined && FORBIDDEN_CODES.has(envelope.code)
85
+ ? 'permission-denied'
86
+ : undefined;
87
+ if (envelope !== undefined && blocked !== undefined) {
88
+ throw new WorkbenchDataError(blocked, envelope.message, {
84
89
  detail,
90
+ ...(envelope.help === undefined ? {} : { hint: envelope.help }),
85
91
  ...(url === undefined ? {} : { helpUrl: url }),
86
92
  });
87
93
  }
@@ -96,7 +102,7 @@ export function createOpencli(options) {
96
102
  hint: '多半是插件里没有这条命令(版本旧就会缺),也可能是命令自己失败了:先确认命令存在,再更新插件重试。',
97
103
  });
98
104
  }
99
- const parsed = parseJsonLoose(result.stdout);
105
+ const parsed = opencliResultOf(result.stdout) ?? parseJsonLoose(result.stdout);
100
106
  if (parsed === undefined) {
101
107
  throw new WorkbenchDataError('cli-bad-output', 'opencli 输出不是 JSON', {
102
108
  detail: tailLines(result.stdout, 4),
@@ -1,4 +1,5 @@
1
1
  import { BROWSER_READ_SESSIONS, BROWSER_SESSION_IDLE_MS, callsProblemOf, noWrite, now, planProblemOf, planResultsOf, recipeProblemOf, scriptOf, scriptOfMany, scriptOfPlan, allSame, } from '@dsh-workbench/shared/host';
2
+ import { opencliResultOf } from '../cli/opencli-wire.js';
2
3
  import { browserRead } from '../browser/index.js';
3
4
  import { attachOf } from './attachment.js';
4
5
  import { readHttp } from './http.js';
@@ -142,13 +143,9 @@ export function createDataReader(options = {}) {
142
143
  return failure('timeout', `通道读超时(${call.timeoutMs}ms)`);
143
144
  if (result.exitCode !== 0)
144
145
  return undefined;
145
- let parsed;
146
- try {
147
- parsed = JSON.parse(result.stdout);
148
- }
149
- catch {
146
+ const parsed = opencliResultOf(result.stdout);
147
+ if (parsed === undefined)
150
148
  return undefined;
151
- }
152
149
  const box = asRecord(parsed);
153
150
  if (box === undefined)
154
151
  return undefined;
@@ -66,11 +66,15 @@ function lineStoreDir(text) {
66
66
  const value = unquote(line.slice('storeDir:'.length).trim());
67
67
  return value === '' ? undefined : value;
68
68
  }
69
+ function storeRootOf(value) {
70
+ return value.replace(/[\\/]v\d+$/u, '');
71
+ }
69
72
  export function storeDirFor(projectDir, read = readTextFile) {
70
73
  const text = read(join(projectDir, 'node_modules', '.modules.yaml'));
71
74
  if (text === undefined)
72
75
  return pnpmStoreDir();
73
- return jsonStoreDir(text) ?? lineStoreDir(text) ?? pnpmStoreDir();
76
+ const recorded = jsonStoreDir(text) ?? lineStoreDir(text);
77
+ return recorded === undefined ? pnpmStoreDir() : storeRootOf(recorded);
74
78
  }
75
79
  export function toolchainOpencliDir() {
76
80
  return join(isolatedRoot(), 'toolchain', 'node_modules', ...OPENCLI_NPM_PACKAGE.split('/'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-workbench/adapter-runtime",
3
- "version": "1.4.0-beta.0",
3
+ "version": "1.4.0-beta.1",
4
4
  "description": "Opencli, browser and data runtime adapters.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,7 +18,7 @@
18
18
  ],
19
19
  "dependencies": {
20
20
  "execa": "^10.2.0",
21
- "@dsh-workbench/shared": "1.4.0-beta.0"
21
+ "@dsh-workbench/shared": "1.4.0-beta.1"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/node": "^24.19.0",