gz-laya-pilot 0.1.2 → 0.1.3
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/NOTICE.md +29 -29
- package/README.md +102 -98
- package/dist/assertions.d.ts +1 -1
- package/dist/assertions.js +4 -9
- package/dist/assertions.js.map +1 -1
- package/dist/replay.js +18 -2
- package/dist/replay.js.map +1 -1
- package/dist/request-assertions.d.ts +6 -0
- package/dist/request-assertions.js +86 -0
- package/dist/request-assertions.js.map +1 -0
- package/dist/schema.d.ts +6 -0
- package/dist/schema.js +42 -0
- package/dist/schema.js.map +1 -1
- package/package.json +57 -57
- package/src/agent/bridge.ts +180 -180
- package/src/agent/report.ts +139 -139
- package/src/agent/run.ts +136 -136
- package/src/agent/schema.ts +38 -38
- package/src/agent/worker.ts +114 -114
- package/src/assertions.ts +4 -10
- package/src/browser.ts +20 -20
- package/src/cli.ts +5 -5
- package/src/decision.ts +85 -85
- package/src/index.ts +10 -10
- package/src/planner.ts +28 -28
- package/src/readiness.ts +92 -92
- package/src/replay.ts +24 -7
- package/src/request-assertions.ts +83 -0
- package/src/schema.ts +46 -0
- package/src/targets.ts +61 -61
- package/vendor/.gitattributes +5 -5
package/src/agent/worker.ts
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
|
-
import { fileURLToPath } from 'node:url';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { spawn } from 'node:child_process';
|
|
4
|
-
import type { AgentOptions } from './run.js';
|
|
5
|
-
import type { UpstreamReport } from './report.js';
|
|
6
|
-
|
|
7
|
-
const root = fileURLToPath(new URL('../../vendor/laya-pilot/', import.meta.url));
|
|
8
|
-
let started = false,
|
|
9
|
-
cancelled = false;
|
|
10
|
-
process.on('disconnect', () => {
|
|
11
|
-
cancelled = true;
|
|
12
|
-
});
|
|
13
|
-
process.on('message', async (message: { type: string; options?: AgentOptions }) => {
|
|
14
|
-
if (message.type === 'stop') {
|
|
15
|
-
cancelled = true;
|
|
16
|
-
return;
|
|
17
|
-
}
|
|
18
|
-
if (started || !message.options) return;
|
|
19
|
-
started = true;
|
|
20
|
-
const options = message.options;
|
|
21
|
-
const timer = setInterval(() => {
|
|
22
|
-
if (cancelled && process.listenerCount('SIGTERM')) process.emit('SIGTERM');
|
|
23
|
-
}, 200);
|
|
24
|
-
try {
|
|
25
|
-
// Import exact vendored upstream source; the npm facade owns configuration, not workflow logic.
|
|
26
|
-
const upstream = (await import(
|
|
27
|
-
new URL('../../vendor/laya-pilot/lib/workflow.mjs', import.meta.url).href
|
|
28
|
-
)) as {
|
|
29
|
-
validateWorkflow: (file: unknown) => { moduleUrl: string };
|
|
30
|
-
runWorkflow: (
|
|
31
|
-
config: Record<string, unknown>,
|
|
32
|
-
mode: string,
|
|
33
|
-
secret: () => Promise<string>,
|
|
34
|
-
root: string,
|
|
35
|
-
) => Promise<UpstreamReport>;
|
|
36
|
-
};
|
|
37
|
-
if (cancelled) throw Error('任务已取消');
|
|
38
|
-
if (options.workbook) {
|
|
39
|
-
const workbook = await new Promise<unknown>((resolve, reject) => {
|
|
40
|
-
const child = spawn(options.python, [path.join(root, 'lib/workflow_excel.py'), 'read'], {
|
|
41
|
-
windowsHide: true,
|
|
42
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
43
|
-
timeout: 60000,
|
|
44
|
-
});
|
|
45
|
-
let output = '',
|
|
46
|
-
error = '';
|
|
47
|
-
child.stdout.on('data', (chunk) => {
|
|
48
|
-
output += chunk;
|
|
49
|
-
});
|
|
50
|
-
child.stderr.on('data', (chunk) => {
|
|
51
|
-
error = (error + chunk).slice(-1000);
|
|
52
|
-
});
|
|
53
|
-
child.on('error', reject);
|
|
54
|
-
child.stdin.on('error', reject);
|
|
55
|
-
child.once('close', (code) => {
|
|
56
|
-
if (code) reject(Error(error));
|
|
57
|
-
else {
|
|
58
|
-
try {
|
|
59
|
-
resolve(JSON.parse(output));
|
|
60
|
-
} catch {
|
|
61
|
-
reject(Error('Excel 元数据无效'));
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
child.stdin.end(JSON.stringify({ path: options.workbook }));
|
|
66
|
-
});
|
|
67
|
-
const saved = upstream.validateWorkflow(workbook);
|
|
68
|
-
const target = new URL(options.url);
|
|
69
|
-
target.search = '';
|
|
70
|
-
target.hash = '';
|
|
71
|
-
if (new URL(saved.moduleUrl).href !== target.href)
|
|
72
|
-
throw Error('Excel 入口与宿主授权地址不一致');
|
|
73
|
-
}
|
|
74
|
-
const summary = await upstream.runWorkflow(
|
|
75
|
-
{
|
|
76
|
-
url: options.url,
|
|
77
|
-
out: options.outputDir,
|
|
78
|
-
caseFile: options.workbook ?? path.join(options.outputDir, 'cases.xlsx'),
|
|
79
|
-
python: options.python,
|
|
80
|
-
model: options.model,
|
|
81
|
-
provider: 'local',
|
|
82
|
-
browserProvider: 'playwright',
|
|
83
|
-
browserChannel: options.channel ?? 'chrome',
|
|
84
|
-
headless: !options.headed,
|
|
85
|
-
readOnly: !options.allowWrite,
|
|
86
|
-
allowWrite: options.allowWrite === true,
|
|
87
|
-
authState: options.authState ?? '',
|
|
88
|
-
authCheck: options.authCheck ?? '',
|
|
89
|
-
manualLogin: options.manualLogin ?? false,
|
|
90
|
-
pageTimeout: 18000,
|
|
91
|
-
assertTimeout: 4000,
|
|
92
|
-
delay: 180,
|
|
93
|
-
maxSteps: 100,
|
|
94
|
-
minProbability: 0.68,
|
|
95
|
-
minMargin: 0.18,
|
|
96
|
-
data: {},
|
|
97
|
-
cases: [],
|
|
98
|
-
},
|
|
99
|
-
options.workbook ? 'execute' : 'generate',
|
|
100
|
-
async () => {
|
|
101
|
-
throw Error('请在宿主配置登录态或使用手动登录');
|
|
102
|
-
},
|
|
103
|
-
root,
|
|
104
|
-
);
|
|
105
|
-
process.exitCode = summary.exitCode ?? 1;
|
|
106
|
-
} catch (error) {
|
|
107
|
-
if (process.connected)
|
|
108
|
-
process.send?.({ error: error instanceof Error ? error.message : String(error) });
|
|
109
|
-
process.exitCode = 1;
|
|
110
|
-
} finally {
|
|
111
|
-
clearInterval(timer);
|
|
112
|
-
process.disconnect?.();
|
|
113
|
-
}
|
|
114
|
-
});
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import type { AgentOptions } from './run.js';
|
|
5
|
+
import type { UpstreamReport } from './report.js';
|
|
6
|
+
|
|
7
|
+
const root = fileURLToPath(new URL('../../vendor/laya-pilot/', import.meta.url));
|
|
8
|
+
let started = false,
|
|
9
|
+
cancelled = false;
|
|
10
|
+
process.on('disconnect', () => {
|
|
11
|
+
cancelled = true;
|
|
12
|
+
});
|
|
13
|
+
process.on('message', async (message: { type: string; options?: AgentOptions }) => {
|
|
14
|
+
if (message.type === 'stop') {
|
|
15
|
+
cancelled = true;
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (started || !message.options) return;
|
|
19
|
+
started = true;
|
|
20
|
+
const options = message.options;
|
|
21
|
+
const timer = setInterval(() => {
|
|
22
|
+
if (cancelled && process.listenerCount('SIGTERM')) process.emit('SIGTERM');
|
|
23
|
+
}, 200);
|
|
24
|
+
try {
|
|
25
|
+
// Import exact vendored upstream source; the npm facade owns configuration, not workflow logic.
|
|
26
|
+
const upstream = (await import(
|
|
27
|
+
new URL('../../vendor/laya-pilot/lib/workflow.mjs', import.meta.url).href
|
|
28
|
+
)) as {
|
|
29
|
+
validateWorkflow: (file: unknown) => { moduleUrl: string };
|
|
30
|
+
runWorkflow: (
|
|
31
|
+
config: Record<string, unknown>,
|
|
32
|
+
mode: string,
|
|
33
|
+
secret: () => Promise<string>,
|
|
34
|
+
root: string,
|
|
35
|
+
) => Promise<UpstreamReport>;
|
|
36
|
+
};
|
|
37
|
+
if (cancelled) throw Error('任务已取消');
|
|
38
|
+
if (options.workbook) {
|
|
39
|
+
const workbook = await new Promise<unknown>((resolve, reject) => {
|
|
40
|
+
const child = spawn(options.python, [path.join(root, 'lib/workflow_excel.py'), 'read'], {
|
|
41
|
+
windowsHide: true,
|
|
42
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
43
|
+
timeout: 60000,
|
|
44
|
+
});
|
|
45
|
+
let output = '',
|
|
46
|
+
error = '';
|
|
47
|
+
child.stdout.on('data', (chunk) => {
|
|
48
|
+
output += chunk;
|
|
49
|
+
});
|
|
50
|
+
child.stderr.on('data', (chunk) => {
|
|
51
|
+
error = (error + chunk).slice(-1000);
|
|
52
|
+
});
|
|
53
|
+
child.on('error', reject);
|
|
54
|
+
child.stdin.on('error', reject);
|
|
55
|
+
child.once('close', (code) => {
|
|
56
|
+
if (code) reject(Error(error));
|
|
57
|
+
else {
|
|
58
|
+
try {
|
|
59
|
+
resolve(JSON.parse(output));
|
|
60
|
+
} catch {
|
|
61
|
+
reject(Error('Excel 元数据无效'));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
child.stdin.end(JSON.stringify({ path: options.workbook }));
|
|
66
|
+
});
|
|
67
|
+
const saved = upstream.validateWorkflow(workbook);
|
|
68
|
+
const target = new URL(options.url);
|
|
69
|
+
target.search = '';
|
|
70
|
+
target.hash = '';
|
|
71
|
+
if (new URL(saved.moduleUrl).href !== target.href)
|
|
72
|
+
throw Error('Excel 入口与宿主授权地址不一致');
|
|
73
|
+
}
|
|
74
|
+
const summary = await upstream.runWorkflow(
|
|
75
|
+
{
|
|
76
|
+
url: options.url,
|
|
77
|
+
out: options.outputDir,
|
|
78
|
+
caseFile: options.workbook ?? path.join(options.outputDir, 'cases.xlsx'),
|
|
79
|
+
python: options.python,
|
|
80
|
+
model: options.model,
|
|
81
|
+
provider: 'local',
|
|
82
|
+
browserProvider: 'playwright',
|
|
83
|
+
browserChannel: options.channel ?? 'chrome',
|
|
84
|
+
headless: !options.headed,
|
|
85
|
+
readOnly: !options.allowWrite,
|
|
86
|
+
allowWrite: options.allowWrite === true,
|
|
87
|
+
authState: options.authState ?? '',
|
|
88
|
+
authCheck: options.authCheck ?? '',
|
|
89
|
+
manualLogin: options.manualLogin ?? false,
|
|
90
|
+
pageTimeout: 18000,
|
|
91
|
+
assertTimeout: 4000,
|
|
92
|
+
delay: 180,
|
|
93
|
+
maxSteps: 100,
|
|
94
|
+
minProbability: 0.68,
|
|
95
|
+
minMargin: 0.18,
|
|
96
|
+
data: {},
|
|
97
|
+
cases: [],
|
|
98
|
+
},
|
|
99
|
+
options.workbook ? 'execute' : 'generate',
|
|
100
|
+
async () => {
|
|
101
|
+
throw Error('请在宿主配置登录态或使用手动登录');
|
|
102
|
+
},
|
|
103
|
+
root,
|
|
104
|
+
);
|
|
105
|
+
process.exitCode = summary.exitCode ?? 1;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (process.connected)
|
|
108
|
+
process.send?.({ error: error instanceof Error ? error.message : String(error) });
|
|
109
|
+
process.exitCode = 1;
|
|
110
|
+
} finally {
|
|
111
|
+
clearInterval(timer);
|
|
112
|
+
process.disconnect?.();
|
|
113
|
+
}
|
|
114
|
+
});
|
package/src/assertions.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Page } from 'playwright';
|
|
2
|
-
import type
|
|
2
|
+
import { assertionOperators, isRequestAssertion, type Assertion, type AssertionResult } from './schema.js';
|
|
3
3
|
// Declarative browser assertions. Native CSS only; imported cases never execute scripts.
|
|
4
4
|
export async function runAssertion(
|
|
5
5
|
page: Page,
|
|
@@ -7,18 +7,12 @@ export async function runAssertion(
|
|
|
7
7
|
step: number,
|
|
8
8
|
isStopped = () => false,
|
|
9
9
|
): Promise<AssertionResult> {
|
|
10
|
+
if (isRequestAssertion(assertion.source))
|
|
11
|
+
throw Error('接口断言需通过 runCase 在前一操作之前开始观察');
|
|
10
12
|
const started = Date.now();
|
|
11
13
|
let actual = '尚未采样';
|
|
12
14
|
let passed = false;
|
|
13
15
|
let stableSince;
|
|
14
|
-
const names = {
|
|
15
|
-
contains: '包含',
|
|
16
|
-
'not-contains': '不包含',
|
|
17
|
-
equals: '等于',
|
|
18
|
-
'not-equals': '不等于',
|
|
19
|
-
visible: '可见',
|
|
20
|
-
hidden: '不可见或不存在',
|
|
21
|
-
};
|
|
22
16
|
while (Date.now() - started < assertion.timeout) {
|
|
23
17
|
if (isStopped()) throw Error('已停止');
|
|
24
18
|
const sample = await page.evaluate((a) => {
|
|
@@ -109,7 +103,7 @@ export async function runAssertion(
|
|
|
109
103
|
step,
|
|
110
104
|
name: assertion.name,
|
|
111
105
|
passed,
|
|
112
|
-
expected: `${
|
|
106
|
+
expected: `${assertionOperators[assertion.operator]}${assertion.expected === undefined ? '' : ` ${assertion.expected === '' ? '空字符串' : assertion.expected}`}`,
|
|
113
107
|
actual: actual === 'visible' ? '可见' : actual === 'hidden' ? '不可见或不存在' : actual,
|
|
114
108
|
duration: Date.now() - started,
|
|
115
109
|
};
|
package/src/browser.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
// Adapted from anthonyli/laya-pilot lib/browser-provider.mjs (MIT).
|
|
2
|
-
import { chromium, type LaunchOptions, type BrowserContextOptions } from 'playwright';
|
|
3
|
-
export async function openBrowser(
|
|
4
|
-
options: { launch?: LaunchOptions; context?: BrowserContextOptions } = {},
|
|
5
|
-
) {
|
|
6
|
-
const browser = await chromium.launch(options.launch);
|
|
7
|
-
try {
|
|
8
|
-
const context = await browser.newContext({
|
|
9
|
-
viewport: { width: 1500, height: 980 },
|
|
10
|
-
locale: 'zh-CN',
|
|
11
|
-
...options.context,
|
|
12
|
-
});
|
|
13
|
-
const page = await context.newPage();
|
|
14
|
-
page.setDefaultTimeout(10000);
|
|
15
|
-
return { browser, context, page };
|
|
16
|
-
} catch (error) {
|
|
17
|
-
await browser.close();
|
|
18
|
-
throw error;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
1
|
+
// Adapted from anthonyli/laya-pilot lib/browser-provider.mjs (MIT).
|
|
2
|
+
import { chromium, type LaunchOptions, type BrowserContextOptions } from 'playwright';
|
|
3
|
+
export async function openBrowser(
|
|
4
|
+
options: { launch?: LaunchOptions; context?: BrowserContextOptions } = {},
|
|
5
|
+
) {
|
|
6
|
+
const browser = await chromium.launch(options.launch);
|
|
7
|
+
try {
|
|
8
|
+
const context = await browser.newContext({
|
|
9
|
+
viewport: { width: 1500, height: 980 },
|
|
10
|
+
locale: 'zh-CN',
|
|
11
|
+
...options.context,
|
|
12
|
+
});
|
|
13
|
+
const page = await context.newPage();
|
|
14
|
+
page.setDefaultTimeout(10000);
|
|
15
|
+
return { browser, context, page };
|
|
16
|
+
} catch (error) {
|
|
17
|
+
await browser.close();
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Preserve all upstream CLI modes and workbook behavior; use UTF-8 for Windows Python IPC.
|
|
3
|
-
process.env.PYTHONIOENCODING = 'utf-8';
|
|
4
|
-
process.env.PYTHONUTF8 = '1';
|
|
5
|
-
await import(new URL('../vendor/laya-pilot/runner.mjs', import.meta.url).href);
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Preserve all upstream CLI modes and workbook behavior; use UTF-8 for Windows Python IPC.
|
|
3
|
+
process.env.PYTHONIOENCODING = 'utf-8';
|
|
4
|
+
process.env.PYTHONUTF8 = '1';
|
|
5
|
+
await import(new URL('../vendor/laya-pilot/runner.mjs', import.meta.url).href);
|
package/src/decision.ts
CHANGED
|
@@ -1,85 +1,85 @@
|
|
|
1
|
-
// Functional port of anthonyli/laya-pilot lib/model.mjs (MIT).
|
|
2
|
-
export interface Decision {
|
|
3
|
-
choice: string;
|
|
4
|
-
probabilities: Record<string, number>;
|
|
5
|
-
confidence: number | null;
|
|
6
|
-
}
|
|
7
|
-
export type Decide = (state: string, criteria: Record<string, string>) => Promise<Decision>;
|
|
8
|
-
export function decodeDecision(body: unknown, criteria: Record<string, string>): Decision {
|
|
9
|
-
const envelope = body as { choices?: { message?: { content?: string } }[] };
|
|
10
|
-
let result: Decision;
|
|
11
|
-
try {
|
|
12
|
-
result = JSON.parse(envelope.choices![0].message!.content!).result.answers.scenario;
|
|
13
|
-
} catch {
|
|
14
|
-
throw Error('模型没有返回有效的 Laya 决策 JSON');
|
|
15
|
-
}
|
|
16
|
-
const keys = Object.keys(criteria);
|
|
17
|
-
if (
|
|
18
|
-
!result ||
|
|
19
|
-
!Object.hasOwn(criteria, result.choice) ||
|
|
20
|
-
!result.probabilities ||
|
|
21
|
-
Object.keys(result.probabilities).length !== keys.length ||
|
|
22
|
-
keys.some(
|
|
23
|
-
(key) =>
|
|
24
|
-
!Number.isFinite(result.probabilities[key]) ||
|
|
25
|
-
result.probabilities[key] < 0 ||
|
|
26
|
-
result.probabilities[key] > 1,
|
|
27
|
-
)
|
|
28
|
-
)
|
|
29
|
-
throw Error('模型返回了候选集合之外的选择或无效概率');
|
|
30
|
-
if (
|
|
31
|
-
Math.abs(keys.reduce((sum, key) => sum + result.probabilities[key], 0) - 1) > 0.02 ||
|
|
32
|
-
keys.some((key) => result.probabilities[key] > result.probabilities[result.choice])
|
|
33
|
-
)
|
|
34
|
-
throw Error('模型概率与选择不一致');
|
|
35
|
-
return {
|
|
36
|
-
choice: result.choice,
|
|
37
|
-
probabilities: result.probabilities,
|
|
38
|
-
confidence: Number.isFinite(result.confidence) ? result.confidence : null,
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
export function createApiDecision(options: {
|
|
42
|
-
base: string;
|
|
43
|
-
model: string;
|
|
44
|
-
key: string;
|
|
45
|
-
timeout?: number;
|
|
46
|
-
fetchImpl?: typeof fetch;
|
|
47
|
-
}): Decide {
|
|
48
|
-
const url = new URL(options.base);
|
|
49
|
-
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
|
|
50
|
-
throw Error('API 地址必须是无凭据及查询参数的 HTTPS 地址');
|
|
51
|
-
if (!options.key.trim()) throw Error('缺少模型 API 密钥');
|
|
52
|
-
return async (state, criteria) => {
|
|
53
|
-
const response = await (options.fetchImpl ?? fetch)(
|
|
54
|
-
url.href.replace(/\/$/, '') + '/chat/completions',
|
|
55
|
-
{
|
|
56
|
-
method: 'POST',
|
|
57
|
-
redirect: 'error',
|
|
58
|
-
signal: AbortSignal.timeout(options.timeout ?? 30000),
|
|
59
|
-
headers: { Authorization: `Bearer ${options.key}`, 'Content-Type': 'application/json' },
|
|
60
|
-
body: JSON.stringify({
|
|
61
|
-
model: options.model,
|
|
62
|
-
stream: false,
|
|
63
|
-
messages: [
|
|
64
|
-
{
|
|
65
|
-
role: 'system',
|
|
66
|
-
content:
|
|
67
|
-
'你是浏览器测试决策器。只返回 JSON:{"result":{"answers":{"scenario":{"choice":"候选原文","probabilities":{"每个候选":0.0},"confidence":0.0}}}}。choice 必须属于 criteria,概率覆盖全部候选且和为1,所选概率最大。证据不足选择停止,不编造确定性。',
|
|
68
|
-
},
|
|
69
|
-
{
|
|
70
|
-
role: 'user',
|
|
71
|
-
content: JSON.stringify({
|
|
72
|
-
state,
|
|
73
|
-
questions: {
|
|
74
|
-
scenario: { type: 'choice', instructions: '用户请求对应哪个操作?', criteria },
|
|
75
|
-
},
|
|
76
|
-
}),
|
|
77
|
-
},
|
|
78
|
-
],
|
|
79
|
-
}),
|
|
80
|
-
},
|
|
81
|
-
);
|
|
82
|
-
if (!response.ok) throw Error(`模型 API 返回 HTTP ${response.status}`);
|
|
83
|
-
return decodeDecision(await response.json(), criteria);
|
|
84
|
-
};
|
|
85
|
-
}
|
|
1
|
+
// Functional port of anthonyli/laya-pilot lib/model.mjs (MIT).
|
|
2
|
+
export interface Decision {
|
|
3
|
+
choice: string;
|
|
4
|
+
probabilities: Record<string, number>;
|
|
5
|
+
confidence: number | null;
|
|
6
|
+
}
|
|
7
|
+
export type Decide = (state: string, criteria: Record<string, string>) => Promise<Decision>;
|
|
8
|
+
export function decodeDecision(body: unknown, criteria: Record<string, string>): Decision {
|
|
9
|
+
const envelope = body as { choices?: { message?: { content?: string } }[] };
|
|
10
|
+
let result: Decision;
|
|
11
|
+
try {
|
|
12
|
+
result = JSON.parse(envelope.choices![0].message!.content!).result.answers.scenario;
|
|
13
|
+
} catch {
|
|
14
|
+
throw Error('模型没有返回有效的 Laya 决策 JSON');
|
|
15
|
+
}
|
|
16
|
+
const keys = Object.keys(criteria);
|
|
17
|
+
if (
|
|
18
|
+
!result ||
|
|
19
|
+
!Object.hasOwn(criteria, result.choice) ||
|
|
20
|
+
!result.probabilities ||
|
|
21
|
+
Object.keys(result.probabilities).length !== keys.length ||
|
|
22
|
+
keys.some(
|
|
23
|
+
(key) =>
|
|
24
|
+
!Number.isFinite(result.probabilities[key]) ||
|
|
25
|
+
result.probabilities[key] < 0 ||
|
|
26
|
+
result.probabilities[key] > 1,
|
|
27
|
+
)
|
|
28
|
+
)
|
|
29
|
+
throw Error('模型返回了候选集合之外的选择或无效概率');
|
|
30
|
+
if (
|
|
31
|
+
Math.abs(keys.reduce((sum, key) => sum + result.probabilities[key], 0) - 1) > 0.02 ||
|
|
32
|
+
keys.some((key) => result.probabilities[key] > result.probabilities[result.choice])
|
|
33
|
+
)
|
|
34
|
+
throw Error('模型概率与选择不一致');
|
|
35
|
+
return {
|
|
36
|
+
choice: result.choice,
|
|
37
|
+
probabilities: result.probabilities,
|
|
38
|
+
confidence: Number.isFinite(result.confidence) ? result.confidence : null,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function createApiDecision(options: {
|
|
42
|
+
base: string;
|
|
43
|
+
model: string;
|
|
44
|
+
key: string;
|
|
45
|
+
timeout?: number;
|
|
46
|
+
fetchImpl?: typeof fetch;
|
|
47
|
+
}): Decide {
|
|
48
|
+
const url = new URL(options.base);
|
|
49
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
|
|
50
|
+
throw Error('API 地址必须是无凭据及查询参数的 HTTPS 地址');
|
|
51
|
+
if (!options.key.trim()) throw Error('缺少模型 API 密钥');
|
|
52
|
+
return async (state, criteria) => {
|
|
53
|
+
const response = await (options.fetchImpl ?? fetch)(
|
|
54
|
+
url.href.replace(/\/$/, '') + '/chat/completions',
|
|
55
|
+
{
|
|
56
|
+
method: 'POST',
|
|
57
|
+
redirect: 'error',
|
|
58
|
+
signal: AbortSignal.timeout(options.timeout ?? 30000),
|
|
59
|
+
headers: { Authorization: `Bearer ${options.key}`, 'Content-Type': 'application/json' },
|
|
60
|
+
body: JSON.stringify({
|
|
61
|
+
model: options.model,
|
|
62
|
+
stream: false,
|
|
63
|
+
messages: [
|
|
64
|
+
{
|
|
65
|
+
role: 'system',
|
|
66
|
+
content:
|
|
67
|
+
'你是浏览器测试决策器。只返回 JSON:{"result":{"answers":{"scenario":{"choice":"候选原文","probabilities":{"每个候选":0.0},"confidence":0.0}}}}。choice 必须属于 criteria,概率覆盖全部候选且和为1,所选概率最大。证据不足选择停止,不编造确定性。',
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
role: 'user',
|
|
71
|
+
content: JSON.stringify({
|
|
72
|
+
state,
|
|
73
|
+
questions: {
|
|
74
|
+
scenario: { type: 'choice', instructions: '用户请求对应哪个操作?', criteria },
|
|
75
|
+
},
|
|
76
|
+
}),
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
}),
|
|
80
|
+
},
|
|
81
|
+
);
|
|
82
|
+
if (!response.ok) throw Error(`模型 API 返回 HTTP ${response.status}`);
|
|
83
|
+
return decodeDecision(await response.json(), criteria);
|
|
84
|
+
};
|
|
85
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export * from './schema.js';
|
|
2
|
-
export { runCase, type ReplayOptions } from './replay.js';
|
|
3
|
-
export { runAssertion } from './assertions.js';
|
|
4
|
-
export { openBrowser } from './browser.js';
|
|
5
|
-
export { waitForReady } from './readiness.js';
|
|
6
|
-
export { createApiDecision, decodeDecision, type Decision, type Decide } from './decision.js';
|
|
7
|
-
export { chooseStep } from './planner.js';
|
|
8
|
-
export { runAgent, type AgentOptions } from './agent/run.js';
|
|
9
|
-
export { createAgentBridge, type AgentBridgeOptions, type AgentBridgeTarget } from './agent/bridge.js';
|
|
10
|
-
export type { AgentStatus, AgentCapabilities } from './agent/schema.js';
|
|
1
|
+
export * from './schema.js';
|
|
2
|
+
export { runCase, type ReplayOptions } from './replay.js';
|
|
3
|
+
export { runAssertion } from './assertions.js';
|
|
4
|
+
export { openBrowser } from './browser.js';
|
|
5
|
+
export { waitForReady } from './readiness.js';
|
|
6
|
+
export { createApiDecision, decodeDecision, type Decision, type Decide } from './decision.js';
|
|
7
|
+
export { chooseStep } from './planner.js';
|
|
8
|
+
export { runAgent, type AgentOptions } from './agent/run.js';
|
|
9
|
+
export { createAgentBridge, type AgentBridgeOptions, type AgentBridgeTarget } from './agent/bridge.js';
|
|
10
|
+
export type { AgentStatus, AgentCapabilities } from './agent/schema.js';
|
package/src/planner.ts
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import type { Decide } from './decision.js';
|
|
2
|
-
import type { Step } from './schema.js';
|
|
3
|
-
|
|
4
|
-
/** A model selects from observed, host-provided candidates. It never generates executable code. */
|
|
5
|
-
export async function chooseStep(
|
|
6
|
-
instruction: string,
|
|
7
|
-
candidates: { description: string; step: Step }[],
|
|
8
|
-
decide: Decide,
|
|
9
|
-
): Promise<Step | null> {
|
|
10
|
-
if (candidates.length < 1 || candidates.length > 7)
|
|
11
|
-
throw Error('每次提供 1–7 个可观察的候选操作');
|
|
12
|
-
const criteria = Object.fromEntries(
|
|
13
|
-
candidates.map((candidate, index) => [String(index), candidate.description]),
|
|
14
|
-
);
|
|
15
|
-
criteria.stop = '无法判断,停止并由用户确认';
|
|
16
|
-
const result = await decide(instruction, criteria);
|
|
17
|
-
if (result.choice === 'stop') return null;
|
|
18
|
-
const index = Number(result.choice);
|
|
19
|
-
if (!Number.isInteger(index) || !Object.hasOwn(criteria, result.choice) || !candidates[index])
|
|
20
|
-
throw Error('模型选择不属于候选集');
|
|
21
|
-
const probabilities = Object.values(result.probabilities).sort((a, b) => b - a);
|
|
22
|
-
if (
|
|
23
|
-
(result.probabilities[result.choice] ?? 0) < 0.7 ||
|
|
24
|
-
probabilities[0] - (probabilities[1] ?? 0) < 0.15
|
|
25
|
-
)
|
|
26
|
-
return null;
|
|
27
|
-
return structuredClone(candidates[index].step);
|
|
28
|
-
}
|
|
1
|
+
import type { Decide } from './decision.js';
|
|
2
|
+
import type { Step } from './schema.js';
|
|
3
|
+
|
|
4
|
+
/** A model selects from observed, host-provided candidates. It never generates executable code. */
|
|
5
|
+
export async function chooseStep(
|
|
6
|
+
instruction: string,
|
|
7
|
+
candidates: { description: string; step: Step }[],
|
|
8
|
+
decide: Decide,
|
|
9
|
+
): Promise<Step | null> {
|
|
10
|
+
if (candidates.length < 1 || candidates.length > 7)
|
|
11
|
+
throw Error('每次提供 1–7 个可观察的候选操作');
|
|
12
|
+
const criteria = Object.fromEntries(
|
|
13
|
+
candidates.map((candidate, index) => [String(index), candidate.description]),
|
|
14
|
+
);
|
|
15
|
+
criteria.stop = '无法判断,停止并由用户确认';
|
|
16
|
+
const result = await decide(instruction, criteria);
|
|
17
|
+
if (result.choice === 'stop') return null;
|
|
18
|
+
const index = Number(result.choice);
|
|
19
|
+
if (!Number.isInteger(index) || !Object.hasOwn(criteria, result.choice) || !candidates[index])
|
|
20
|
+
throw Error('模型选择不属于候选集');
|
|
21
|
+
const probabilities = Object.values(result.probabilities).sort((a, b) => b - a);
|
|
22
|
+
if (
|
|
23
|
+
(result.probabilities[result.choice] ?? 0) < 0.7 ||
|
|
24
|
+
probabilities[0] - (probabilities[1] ?? 0) < 0.15
|
|
25
|
+
)
|
|
26
|
+
return null;
|
|
27
|
+
return structuredClone(candidates[index].step);
|
|
28
|
+
}
|