@danceiny/gotry 0.0.1-rc.11 → 0.0.1-rc.12
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/README.md +19 -7
- package/cordis.gotry-patch.yml +14 -7
- package/dist/capabilities/flyai.js +135 -30
- package/dist/capabilities/hbcli.js +14 -2
- package/dist/capabilities/session/benchmark.js +252 -0
- package/dist/capabilities/session/transport.js +14 -9
- package/dist/capabilities/session-consent.js +82 -0
- package/dist/capabilities/session-login.js +103 -0
- package/dist/capabilities/session-search.js +5 -3
- package/dist/capabilities/weather.js +72 -17
- package/dist/scripts/agent-reach-wrapper-tests.js +4 -0
- package/dist/scripts/async-collect.js +33 -5
- package/dist/scripts/hbcli-tests.js +25 -4
- package/dist/scripts/ledger-tests.js +134 -4
- package/dist/scripts/memory-value-report.js +379 -0
- package/dist/scripts/product-metrics.js +569 -0
- package/dist/scripts/session-benchmark.js +261 -0
- package/dist/scripts/session-login.js +28 -0
- package/dist/scripts/session-tests.js +260 -23
- package/dist/scripts/smoke.js +112 -14
- package/dist/scripts/weather-tests.js +8 -1
- package/dist/src/index.js +124 -5
- package/dist/src/loop.js +65 -14
- package/dist/src/state-ledger.js +30 -4
- package/package.json +4 -2
- package/ts/capabilities/flyai.ts +177 -22
- package/ts/capabilities/hbcli.ts +16 -4
- package/ts/capabilities/session/benchmark.ts +273 -0
- package/ts/capabilities/session/transport.ts +19 -8
- package/ts/capabilities/session-consent.ts +127 -0
- package/ts/capabilities/session-login.ts +130 -0
- package/ts/capabilities/session-search.ts +11 -4
- package/ts/capabilities/weather.ts +84 -19
- package/ts/scripts/async-collect.ts +48 -7
- package/ts/src/index.ts +107 -11
- package/ts/src/loop.ts +85 -12
- package/ts/src/state-ledger.ts +48 -4
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export const ACCOUNT_TOOLS = {
|
|
2
|
+
gotry_session_search: 'ctrip-flight'
|
|
3
|
+
};
|
|
4
|
+
const SITE_LABEL = {
|
|
5
|
+
'ctrip-flight': '携程机票'
|
|
6
|
+
};
|
|
7
|
+
function reasonFor(toolName, site) {
|
|
8
|
+
return `${toolName} 将使用你本人已登录的浏览器会话做「${SITE_LABEL[site] ?? site}」只读检索` + '(ReadGuard 物理只读:写请求网络层中止,agent 永不碰凭证与验证码);本次批准在你本会话内有效';
|
|
9
|
+
}
|
|
10
|
+
export function createConsentGate(opts) {
|
|
11
|
+
const store = opts.store ?? new WeakMap();
|
|
12
|
+
const approvalOf = opts.approval ?? (()=>undefined);
|
|
13
|
+
return async (exec, next)=>{
|
|
14
|
+
const site = exec.name && ACCOUNT_TOOLS[exec.name];
|
|
15
|
+
if (!site) return next();
|
|
16
|
+
if ((opts.access() ?? 'ask') === 'off') {
|
|
17
|
+
return {
|
|
18
|
+
kind: 'deny',
|
|
19
|
+
reason: `${exec.name} 已被配置关闭(sessionAccess=off);需要账号会话检索时由用户开启`
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const state = exec.agent && store.get(exec.agent) || undefined;
|
|
23
|
+
if (state?.denied.has(site)) {
|
|
24
|
+
return {
|
|
25
|
+
kind: 'deny',
|
|
26
|
+
reason: `你在本会话已拒绝过「${SITE_LABEL[site] ?? site}」的账号会话检索——本会话不再请求授权,请改走其他工具推进`
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
if (state?.granted.has(site) || opts.access() === 'allow' && exec.agent) return next();
|
|
30
|
+
const approval = opts.approval?.();
|
|
31
|
+
if (!approval || !exec.agent) return {
|
|
32
|
+
kind: 'ask',
|
|
33
|
+
reason: reasonFor(exec.name ?? '', site)
|
|
34
|
+
};
|
|
35
|
+
let outcome;
|
|
36
|
+
try {
|
|
37
|
+
outcome = await approval.request({
|
|
38
|
+
agent: exec.agent,
|
|
39
|
+
toolName: exec.name ?? '',
|
|
40
|
+
callId: exec.callId,
|
|
41
|
+
reason: reasonFor(exec.name ?? '', site)
|
|
42
|
+
});
|
|
43
|
+
} catch {
|
|
44
|
+
outcome = 'unavailable';
|
|
45
|
+
}
|
|
46
|
+
if (outcome === 'allowed-once') {
|
|
47
|
+
remember(store, exec.agent, site, 'grant');
|
|
48
|
+
return next();
|
|
49
|
+
}
|
|
50
|
+
if (outcome === 'rejected' || outcome === 'cancelled') {
|
|
51
|
+
remember(store, exec.agent, site, 'deny');
|
|
52
|
+
return {
|
|
53
|
+
kind: 'deny',
|
|
54
|
+
reason: `你拒绝了 ${exec.name} 的账号会话授权(本会话内生效);不再重复请求,请改走其他工具推进`
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
kind: 'deny',
|
|
59
|
+
reason: `${exec.name} 需要你授权,但当前没有可用的审批通道(headless 一问一答无审批界面;请在 web 会话中使用账号会话检索)`
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function remember(store, agent, site, mode) {
|
|
64
|
+
const prev = store.get(agent) ?? {
|
|
65
|
+
granted: new Set(),
|
|
66
|
+
denied: new Set()
|
|
67
|
+
};
|
|
68
|
+
if (mode === 'grant') prev.granted.add(site);
|
|
69
|
+
else prev.denied.add(site);
|
|
70
|
+
store.set(agent, prev);
|
|
71
|
+
}
|
|
72
|
+
export function approvalFromContext(ctx) {
|
|
73
|
+
return ()=>{
|
|
74
|
+
const get = ctx.get;
|
|
75
|
+
if (typeof get !== 'function') return undefined;
|
|
76
|
+
const approval = get.call(ctx, 'approval');
|
|
77
|
+
return approval && typeof approval.request === 'function' ? approval : undefined;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
//# sourceURL=/Users/bytedance/work/gotry/ts/capabilities/session-consent.ts
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { openSession } from './session/transport.js';
|
|
2
|
+
export const LOGIN_TARGETS = {
|
|
3
|
+
'ctrip-flight': {
|
|
4
|
+
domain: 'ctrip.com',
|
|
5
|
+
names: [
|
|
6
|
+
'cticket',
|
|
7
|
+
'uid',
|
|
8
|
+
'uname',
|
|
9
|
+
'passport'
|
|
10
|
+
],
|
|
11
|
+
label: '携程机票',
|
|
12
|
+
entryUrl: 'https://flights.ctrip.com/'
|
|
13
|
+
},
|
|
14
|
+
'meituan-hotel': {
|
|
15
|
+
domain: 'meituan.com',
|
|
16
|
+
names: [
|
|
17
|
+
'lt',
|
|
18
|
+
'u',
|
|
19
|
+
'token',
|
|
20
|
+
'n'
|
|
21
|
+
],
|
|
22
|
+
label: '美团酒店',
|
|
23
|
+
entryUrl: 'https://hotel.meituan.com/'
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
function err(site, verdict, error, started, ts) {
|
|
27
|
+
return {
|
|
28
|
+
ok: false,
|
|
29
|
+
via: 'session-login-error',
|
|
30
|
+
evidence: `[会话:login-error@${ts}] ${error.slice(0, 200)}`,
|
|
31
|
+
latencyMs: Date.now() - started,
|
|
32
|
+
verdict,
|
|
33
|
+
site,
|
|
34
|
+
error: error.slice(0, 200)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export async function pollTicketNames(browser, target) {
|
|
38
|
+
const cookies = await browser.cookies().catch(()=>[]);
|
|
39
|
+
if (!Array.isArray(cookies)) return [];
|
|
40
|
+
return cookies.filter((c)=>(c.domain ?? '').includes(target.domain) && c.name != null && target.names.includes(c.name)).map((c)=>c.name);
|
|
41
|
+
}
|
|
42
|
+
export async function sessionLogin(q = {}) {
|
|
43
|
+
const started = Date.now();
|
|
44
|
+
const ts = new Date().toISOString();
|
|
45
|
+
const site = q.site ?? 'ctrip-flight';
|
|
46
|
+
const target = LOGIN_TARGETS[site];
|
|
47
|
+
if (!target) {
|
|
48
|
+
return err(site, 'error', `未知站点 ${site}(可选 ${Object.keys(LOGIN_TARGETS).join('/')})`, started, ts);
|
|
49
|
+
}
|
|
50
|
+
const t = await openSession({
|
|
51
|
+
mode: 'cdp',
|
|
52
|
+
guard: false
|
|
53
|
+
});
|
|
54
|
+
if (!t.ok) {
|
|
55
|
+
const needsAttach = /chrome:\/\/inspect|DevToolsActivePort|cdp attach 失败/.test(t.summary);
|
|
56
|
+
return err(site, needsAttach ? 'needs-attach' : 'error', needsAttach ? `${t.summary};开启方法:你的 Chrome 打开 chrome://inspect/#remote-debugging → 打开开关(Chrome 144+,一次性),开启后直接再说一声即可` : t.summary, started, ts);
|
|
57
|
+
}
|
|
58
|
+
const evidenceTag = `[会话:${site}-login@${ts}]`;
|
|
59
|
+
try {
|
|
60
|
+
try {
|
|
61
|
+
await t.page.goto(target.entryUrl, {
|
|
62
|
+
waitUntil: 'domcontentloaded',
|
|
63
|
+
timeout: 30_000
|
|
64
|
+
});
|
|
65
|
+
} catch {}
|
|
66
|
+
const waitMs = Math.min(Math.max(q.waitMs ?? 90_000, 0), 300_000);
|
|
67
|
+
const pollMs = Math.min(Math.max(q.pollMs ?? 3_000, 500), 10_000);
|
|
68
|
+
const deadline = Date.now() + waitMs;
|
|
69
|
+
let tickets = [];
|
|
70
|
+
while(Date.now() < deadline){
|
|
71
|
+
await new Promise((resolve)=>setTimeout(resolve, pollMs));
|
|
72
|
+
tickets = await pollTicketNames(t.browser, target);
|
|
73
|
+
if (tickets.length > 0) break;
|
|
74
|
+
}
|
|
75
|
+
await t.close();
|
|
76
|
+
if (tickets.length > 0) {
|
|
77
|
+
return {
|
|
78
|
+
ok: true,
|
|
79
|
+
via: 'session-login',
|
|
80
|
+
latencyMs: Date.now() - started,
|
|
81
|
+
verdict: 'logged-in',
|
|
82
|
+
site,
|
|
83
|
+
tickets,
|
|
84
|
+
evidence: `${evidenceTag} 票据 cookie 已检出 [${tickets.join(', ')}](只读名字;登录在你自己的浏览器里完成,gotry 全程未接触任何密码/验证码/cookie 值)`
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
ok: true,
|
|
89
|
+
via: 'session-login',
|
|
90
|
+
latencyMs: Date.now() - started,
|
|
91
|
+
verdict: 'pending',
|
|
92
|
+
site,
|
|
93
|
+
tickets: [],
|
|
94
|
+
evidence: `${evidenceTag} 登录入口已在你的 Chrome 打开(${target.label});在标签页里正常登录完成后再说一声「继续查」即可——gotry 只检查"是否已登录",永不收集你的账号信息`
|
|
95
|
+
};
|
|
96
|
+
} catch (e) {
|
|
97
|
+
await t.close().catch(()=>{});
|
|
98
|
+
return err(site, 'error', e instanceof Error ? e.message : String(e), started, ts);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
//# sourceURL=/Users/bytedance/work/gotry/ts/capabilities/session-login.ts
|
|
@@ -6,6 +6,9 @@ export function __resetRateLimiterForTest() {
|
|
|
6
6
|
lastCallAt.clear();
|
|
7
7
|
}
|
|
8
8
|
const CHALLENGE_RE = /验证|滑块|captcha|verify/i;
|
|
9
|
+
export function classifyTransportFailure(summary, cdpMode) {
|
|
10
|
+
return cdpMode && /日常 Chrome 未开调试端口|cdp attach 失败/.test(summary) ? 'needs-attach' : 'error';
|
|
11
|
+
}
|
|
9
12
|
export async function sessionFlightSearch(q) {
|
|
10
13
|
const started = Date.now();
|
|
11
14
|
const ts = new Date().toISOString();
|
|
@@ -34,8 +37,7 @@ export async function sessionFlightSearch(q) {
|
|
|
34
37
|
mode: q.profileDir ? 'persistent' : 'cdp'
|
|
35
38
|
});
|
|
36
39
|
if (!t.ok) {
|
|
37
|
-
|
|
38
|
-
return err('error', t.summary);
|
|
40
|
+
return err(classifyTransportFailure(t.summary, q.profileDir === undefined), t.summary);
|
|
39
41
|
}
|
|
40
42
|
try {
|
|
41
43
|
const loggedIn = async ()=>{
|
|
@@ -43,7 +45,7 @@ export async function sessionFlightSearch(q) {
|
|
|
43
45
|
return cookies.some((c)=>c.domain.includes(SITE_DOMAIN.replace(/^\./, '')) && LOGIN_COOKIE_NAMES.includes(c.name));
|
|
44
46
|
};
|
|
45
47
|
if (!await loggedIn() && !q.allowAnonymous) {
|
|
46
|
-
return err('needs-login', '
|
|
48
|
+
return err('needs-login', '未检出你本人登录态——调用 gotry_session_login 为用户打开携程登录入口(登录在携程官网完成;gotry 永不经手密码/验证码/cookie 值)');
|
|
47
49
|
}
|
|
48
50
|
let settled = false;
|
|
49
51
|
let body = '';
|
|
@@ -32,14 +32,15 @@ const WMO_ZH = {
|
|
|
32
32
|
export function wmoLabel(code) {
|
|
33
33
|
return WMO_ZH[code] ?? `天气码${code}`;
|
|
34
34
|
}
|
|
35
|
-
async function fetchJson(url, timeoutMs) {
|
|
35
|
+
async function fetchJson(url, timeoutMs, headers = {}) {
|
|
36
36
|
const ctrl = new AbortController();
|
|
37
37
|
const timer = setTimeout(()=>ctrl.abort(), timeoutMs);
|
|
38
38
|
try {
|
|
39
39
|
const res = await fetch(url, {
|
|
40
40
|
signal: ctrl.signal,
|
|
41
41
|
headers: {
|
|
42
|
-
Accept: 'application/json'
|
|
42
|
+
Accept: 'application/json',
|
|
43
|
+
...headers
|
|
43
44
|
}
|
|
44
45
|
});
|
|
45
46
|
if (!res.ok) return {
|
|
@@ -59,33 +60,87 @@ async function fetchJson(url, timeoutMs) {
|
|
|
59
60
|
clearTimeout(timer);
|
|
60
61
|
}
|
|
61
62
|
}
|
|
63
|
+
const NOMINATIM_BASE = 'https://nominatim.openstreetmap.org/search';
|
|
64
|
+
const MAJOR_FEATURE = /^(PPLC|PPLA|PPLB|PPLX)/;
|
|
65
|
+
function stripHits(hits) {
|
|
66
|
+
return hits.map(({ name, latitude, longitude, country, admin1 })=>({
|
|
67
|
+
...country ? {
|
|
68
|
+
country
|
|
69
|
+
} : {},
|
|
70
|
+
...admin1 ? {
|
|
71
|
+
admin1
|
|
72
|
+
} : {},
|
|
73
|
+
name,
|
|
74
|
+
latitude,
|
|
75
|
+
longitude
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
62
78
|
export async function geocodePlace(name, opts = {}) {
|
|
63
79
|
const ts = new Date().toISOString();
|
|
64
80
|
const count = opts.count ?? 5;
|
|
65
|
-
const
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
ok: false,
|
|
70
|
-
evidence: `[实时API:open-meteo-geo@error@${ts}]`,
|
|
71
|
-
results: [],
|
|
72
|
-
error: r.error
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
const results = (r.data?.results ?? []).map((item)=>{
|
|
81
|
+
const query = name.trim();
|
|
82
|
+
const omUrl = `${GEOCODE_BASE}?name=${encodeURIComponent(query)}&count=${count}&language=zh&format=json`;
|
|
83
|
+
const r = await fetchJson(omUrl, opts.timeoutMs ?? 15_000);
|
|
84
|
+
const omResults = r.ok ? (r.data?.results ?? []).map((item)=>{
|
|
76
85
|
const it = item;
|
|
77
86
|
return {
|
|
78
87
|
name: String(it['name'] ?? ''),
|
|
79
88
|
latitude: Number(it['latitude']),
|
|
80
89
|
longitude: Number(it['longitude']),
|
|
81
90
|
country: it['country'] ? String(it['country']) : undefined,
|
|
82
|
-
admin1: it['admin1'] ? String(it['admin1']) : undefined
|
|
91
|
+
admin1: it['admin1'] ? String(it['admin1']) : undefined,
|
|
92
|
+
population: Number(it['population'] ?? 0) || 0,
|
|
93
|
+
featureCode: String(it['feature_code'] ?? '')
|
|
94
|
+
};
|
|
95
|
+
}).filter((h)=>h.name && Number.isFinite(h.latitude) && Number.isFinite(h.longitude)) : [];
|
|
96
|
+
omResults.sort((a, b)=>b.population - a.population || Number(MAJOR_FEATURE.test(b.featureCode)) - Number(MAJOR_FEATURE.test(a.featureCode)));
|
|
97
|
+
const top = omResults[0];
|
|
98
|
+
if (top && (top.population > 0 || MAJOR_FEATURE.test(top.featureCode))) {
|
|
99
|
+
return {
|
|
100
|
+
ok: true,
|
|
101
|
+
evidence: `[实时API:open-meteo-geo@${ts}]`,
|
|
102
|
+
via: 'open-meteo',
|
|
103
|
+
results: stripHits(omResults)
|
|
83
104
|
};
|
|
105
|
+
}
|
|
106
|
+
const nomTs = new Date().toISOString();
|
|
107
|
+
const nomUrl = `${NOMINATIM_BASE}?q=${encodeURIComponent(query)}&format=jsonv2&limit=${count}&accept-language=zh&addressdetails=1`;
|
|
108
|
+
const nom = await fetchJson(nomUrl, opts.timeoutMs ?? 15_000, {
|
|
109
|
+
'User-Agent': 'gotry-travel-agent/0.1 (+https://github.com/Danceiny/gotry)'
|
|
84
110
|
});
|
|
111
|
+
const nomResults = nom.ok ? (nom.data ?? []).map((item)=>{
|
|
112
|
+
const it = item;
|
|
113
|
+
const addr = it['address'] ?? {};
|
|
114
|
+
return {
|
|
115
|
+
name: String(it['name'] ?? ''),
|
|
116
|
+
latitude: Number(it['lat']),
|
|
117
|
+
longitude: Number(it['lon']),
|
|
118
|
+
country: addr['country'],
|
|
119
|
+
admin1: addr['province'] ?? addr['state'] ?? addr['county']
|
|
120
|
+
};
|
|
121
|
+
}).filter((h)=>h.name && Number.isFinite(h.latitude) && Number.isFinite(h.longitude)) : [];
|
|
122
|
+
if (nomResults.length) {
|
|
123
|
+
const omNote = r.ok ? `open-meteo ${omResults.length} 条弱命中(无人口/行政级,不足采信)` : `open-meteo 失败:${r.error ?? 'HTTP error'}`;
|
|
124
|
+
return {
|
|
125
|
+
ok: true,
|
|
126
|
+
evidence: `[实时API:nominatim@${nomTs}](兜底层: ${omNote})`,
|
|
127
|
+
via: 'nominatim',
|
|
128
|
+
results: nomResults
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (omResults.length) {
|
|
132
|
+
return {
|
|
133
|
+
ok: true,
|
|
134
|
+
evidence: `[实时API:open-meteo-geo@${ts}]`,
|
|
135
|
+
via: 'open-meteo',
|
|
136
|
+
results: stripHits(omResults)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
85
139
|
return {
|
|
86
|
-
ok:
|
|
87
|
-
evidence: `[实时API:open-meteo-geo@${ts}]`,
|
|
88
|
-
results
|
|
140
|
+
ok: false,
|
|
141
|
+
evidence: `[实时API:open-meteo-geo@error@${ts}];[实时API:nominatim@error@${nomTs}]`,
|
|
142
|
+
results: [],
|
|
143
|
+
error: r.ok ? `双源无结果:${nom.error ?? 'nominatim empty'}` : r.error
|
|
89
144
|
};
|
|
90
145
|
}
|
|
91
146
|
export async function getForecast(point, opts = {}) {
|
|
@@ -2,6 +2,10 @@ import assert from 'node:assert/strict';
|
|
|
2
2
|
import { reach, reachStatus } from '../capabilities/agent-reach.js';
|
|
3
3
|
{
|
|
4
4
|
const st = await reachStatus(90_000);
|
|
5
|
+
if (!st.ok) {
|
|
6
|
+
console.log(`SKIP: agent-reach doctor 未就绪(未安装/needs-setup),7 断言整体跳过 — via=${st.via} output=${String(st.output).slice(0, 120)}`);
|
|
7
|
+
process.exit(0);
|
|
8
|
+
}
|
|
5
9
|
assert.equal(st.ok, true);
|
|
6
10
|
assert.equal(st.via, 'agent-reach-cli');
|
|
7
11
|
assert.ok(st.output.length > 50, 'doctor 输出非空(上游原样)');
|
|
@@ -1,7 +1,30 @@
|
|
|
1
1
|
import { appendFileSync } from 'node:fs';
|
|
2
|
-
import { collectDeepPlanning, loadAsyncTicket, makeJournaledSolvePort, settleAsyncTicket } from '../src/loop.js';
|
|
2
|
+
import { ASYNC_TERMINAL_SCHEMA, collectDeepPlanning, loadAsyncTicket, makeJournaledSolvePort, settleAsyncTicket } from '../src/loop.js';
|
|
3
3
|
import { solveUnified } from '../src/unified.js';
|
|
4
4
|
import { openLedgerIfExists } from '../src/state-ledger.js';
|
|
5
|
+
function isTerminalOutcome(value) {
|
|
6
|
+
return value?.['schema'] === ASYNC_TERMINAL_SCHEMA && (value['status'] === 'succeeded' || value['status'] === 'failed') && typeof value['passed'] === 'number' && value['total'] === 4 && Array.isArray(value['failed_checks']);
|
|
7
|
+
}
|
|
8
|
+
function legacyTerminalOutcome(ticket, status, deliverable) {
|
|
9
|
+
const succeeded = status === 'settled' && deliverable.includes('不失望四条:4/4 ✅');
|
|
10
|
+
return {
|
|
11
|
+
schema: ASYNC_TERMINAL_SCHEMA,
|
|
12
|
+
ticket_id: ticket,
|
|
13
|
+
status: succeeded ? 'succeeded' : 'failed',
|
|
14
|
+
passed: succeeded ? 4 : 0,
|
|
15
|
+
total: 4,
|
|
16
|
+
checks: {
|
|
17
|
+
legacy_human_marker_only: succeeded
|
|
18
|
+
},
|
|
19
|
+
failed_checks: succeeded ? [] : [
|
|
20
|
+
'legacy_unstructured_terminal'
|
|
21
|
+
]
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function emitTerminal(outcome) {
|
|
25
|
+
console.log(JSON.stringify(outcome));
|
|
26
|
+
process.exit(outcome.status === 'succeeded' ? 0 : 2);
|
|
27
|
+
}
|
|
5
28
|
const ticketId = process.argv[2];
|
|
6
29
|
const stateRoot = process.argv[3] ?? '.';
|
|
7
30
|
if (!ticketId) {
|
|
@@ -15,9 +38,12 @@ if (!loaded) {
|
|
|
15
38
|
}
|
|
16
39
|
const ledger = openLedgerIfExists(stateRoot);
|
|
17
40
|
const run = ledger?.getWorkflowRun(ticketId);
|
|
18
|
-
if (run?.status === 'settled' && run.deliverable) {
|
|
41
|
+
if ((run?.status === 'settled' || run?.status === 'failed') && run.deliverable) {
|
|
42
|
+
const storedOutcome = ledger?.getWorkflowTerminalOutcome(ticketId) ?? null;
|
|
43
|
+
const outcome = isTerminalOutcome(storedOutcome) ? storedOutcome : legacyTerminalOutcome(ticketId, run.status, run.deliverable);
|
|
44
|
+
await settleAsyncTicket(ticketId, run.deliverable, stateRoot, outcome);
|
|
19
45
|
console.log(`工单 ${ticketId} 已交付(账本终态,复诵不重算):\n\n${run.deliverable}`);
|
|
20
|
-
|
|
46
|
+
emitTerminal(outcome);
|
|
21
47
|
}
|
|
22
48
|
if (!ledger) {
|
|
23
49
|
console.error(`工单 ${ticketId}:stateRoot(${stateRoot})无账本——持久化先于回收,不应发生`);
|
|
@@ -29,9 +55,11 @@ const solve = makeJournaledSolvePort(ledger, ticketId, solveUnified, {
|
|
|
29
55
|
if (f) appendFileSync(f, 'solve\n');
|
|
30
56
|
}
|
|
31
57
|
});
|
|
32
|
-
const { reply } = await collectDeepPlanning(loaded.state, loaded.ticket, solve);
|
|
33
|
-
const out = await settleAsyncTicket(ticketId, reply, stateRoot);
|
|
58
|
+
const { reply, outcome } = await collectDeepPlanning(loaded.state, loaded.ticket, solve);
|
|
59
|
+
const out = await settleAsyncTicket(ticketId, reply, stateRoot, outcome);
|
|
34
60
|
console.log(`交付物已落盘:${out}\n\n${reply}`);
|
|
61
|
+
console.log(JSON.stringify(outcome));
|
|
62
|
+
process.exitCode = outcome.status === 'succeeded' ? 0 : 2;
|
|
35
63
|
|
|
36
64
|
|
|
37
65
|
//# sourceURL=/Users/bytedance/work/gotry/ts/scripts/async-collect.ts
|
|
@@ -62,7 +62,12 @@ await writeFile(fallback, JSON.stringify({
|
|
|
62
62
|
meta: 'fake',
|
|
63
63
|
stays: [
|
|
64
64
|
{
|
|
65
|
-
id: 's1'
|
|
65
|
+
id: 's1',
|
|
66
|
+
note: '普吉岛 workation 两周(13 晚)'
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: 's2',
|
|
70
|
+
note: '曼谷周末(2 晚)'
|
|
66
71
|
}
|
|
67
72
|
]
|
|
68
73
|
}));
|
|
@@ -83,19 +88,35 @@ await writeFile(fallback, JSON.stringify({
|
|
|
83
88
|
}
|
|
84
89
|
console.log('5. v0.3.0 旗标(--destination-name/--room-occupancies)对齐 OK');
|
|
85
90
|
}const r4 = await searchHotels({
|
|
86
|
-
destination: '
|
|
91
|
+
destination: '普吉岛'
|
|
87
92
|
}, {
|
|
88
93
|
hbcliBin: failBin2,
|
|
89
94
|
fallbackPath: fallback
|
|
90
95
|
});
|
|
91
96
|
assert.equal(r4.via, 'hbcli-error', 'searchHotels: fails to hbcli → fallback');
|
|
92
97
|
assert.equal(r4.summary.includes('降级到静态包'), true, 'summary 指明降级');
|
|
93
|
-
assert.
|
|
98
|
+
assert.deepEqual(r4.hotels, {
|
|
99
|
+
stays: [
|
|
100
|
+
{
|
|
101
|
+
id: 's1',
|
|
102
|
+
note: '普吉岛 workation 两周(13 晚)'
|
|
103
|
+
}
|
|
104
|
+
]
|
|
105
|
+
}, 'hotels 只含目的地命中的住宿块');
|
|
106
|
+
assert.equal(r4.summary.includes('命中 1 个住宿块'), true, 'summary 指明命中块数');
|
|
107
|
+
const r5 = await searchHotels({
|
|
108
|
+
destination: '巴黎'
|
|
109
|
+
}, {
|
|
110
|
+
hbcliBin: failBin2,
|
|
111
|
+
fallbackPath: fallback
|
|
112
|
+
});
|
|
113
|
+
assert.equal(r5.hotels ?? null, null, '无目的地命中时 hotels 为 null(不整包倾倒)');
|
|
114
|
+
assert.match(r5.summary, /无「巴黎」住宿数据/, 'summary 明示静态包无该目的地');
|
|
94
115
|
await rm(tmp, {
|
|
95
116
|
recursive: true,
|
|
96
117
|
force: true
|
|
97
118
|
});
|
|
98
|
-
console.log('HBCLI TESTS:
|
|
119
|
+
console.log('HBCLI TESTS: 6/6 OK (happy / error / no-binary / fallback-filter / fallback-no-match / v0.3.0 旗标回归)');
|
|
99
120
|
|
|
100
121
|
|
|
101
122
|
//# sourceURL=/Users/bytedance/work/gotry/ts/scripts/hbcli-tests.ts
|
|
@@ -3,7 +3,9 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync
|
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { persistAsyncTicket } from '../src/loop.js';
|
|
6
7
|
import { ensureLedger, openLedgerIfExists } from '../src/state-ledger.js';
|
|
8
|
+
import { parseFlightPackToSpec } from '../src/unified.js';
|
|
7
9
|
let pass = 0;
|
|
8
10
|
let fail = 0;
|
|
9
11
|
function assert(cond, msg) {
|
|
@@ -15,6 +17,17 @@ function assert(cond, msg) {
|
|
|
15
17
|
console.error(` FAIL - ${msg}`);
|
|
16
18
|
}
|
|
17
19
|
}
|
|
20
|
+
function terminalOutcomeOf(stdout) {
|
|
21
|
+
const line = stdout.trim().split('\n').filter(Boolean).at(-1);
|
|
22
|
+
if (!line) return null;
|
|
23
|
+
try {
|
|
24
|
+
const value = JSON.parse(line);
|
|
25
|
+
if (value.schema !== 'gotry_async_terminal.v1' || typeof value.ticket_id !== 'string' || value.status !== 'succeeded' && value.status !== 'failed' || typeof value.passed !== 'number' || typeof value.total !== 'number' || typeof value.checks !== 'object' || !Array.isArray(value.failed_checks)) return null;
|
|
26
|
+
return value;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
18
31
|
const root = mkdtempSync(join(tmpdir(), 'gotry-ledger-'));
|
|
19
32
|
const ledger = ensureLedger(root);
|
|
20
33
|
const r1 = ledger.appendMotivationPatch({
|
|
@@ -276,11 +289,16 @@ const resume = spawnSync('npx', [
|
|
|
276
289
|
GOTRY_SOLVE_COUNT_FILE: countFile
|
|
277
290
|
}
|
|
278
291
|
});
|
|
279
|
-
|
|
292
|
+
const failedOutcome = terminalOutcomeOf(resume.stdout ?? '');
|
|
293
|
+
assert(resume.status === 2, `非4/4 恢复进程 exit 2(实际 ${resume.status}:${(resume.stderr ?? '').slice(0, 300)})`);
|
|
294
|
+
assert(failedOutcome?.status === 'failed' && failedOutcome.ticket_id === 'dp-crash1' && failedOutcome.passed < failedOutcome.total && failedOutcome.failed_checks.length > 0, '非4/4 输出 gotry_async_terminal.v1/failed 与失败项');
|
|
280
295
|
const count2 = readFileSync(countFile, 'utf-8').split('\n').filter(Boolean).length;
|
|
281
296
|
assert(count2 === 1, '恢复时 done 步骤零重算(exactly-once:求解计数仍 1,不重复花钱)');
|
|
282
|
-
|
|
283
|
-
assert(
|
|
297
|
+
const failedDeliverablePath = join(wroot, 'gotry-state', 'async', 'dp-crash1.deliverable.md');
|
|
298
|
+
assert(existsSync(failedDeliverablePath), '交付物视图已落盘(.deliverable.md)');
|
|
299
|
+
const failedLedger = openLedgerIfExists(wroot);
|
|
300
|
+
assert(failedLedger?.getWorkflowRun('dp-crash1')?.status === 'failed', '非4/4 账本终态 failed');
|
|
301
|
+
assert(JSON.stringify(failedLedger?.getWorkflowTerminalOutcome('dp-crash1')) === JSON.stringify(failedOutcome), '非4/4 结构化终态随 async.failed 事件落账');
|
|
284
302
|
const replay = spawnSync('npx', [
|
|
285
303
|
'tsx',
|
|
286
304
|
'scripts/async-collect.ts',
|
|
@@ -293,9 +311,117 @@ const replay = spawnSync('npx', [
|
|
|
293
311
|
GOTRY_SOLVE_COUNT_FILE: countFile
|
|
294
312
|
}
|
|
295
313
|
});
|
|
296
|
-
assert(replay.status ===
|
|
314
|
+
assert(replay.status === 2 && JSON.stringify(terminalOutcomeOf(replay.stdout ?? '')) === JSON.stringify(failedOutcome), 'failed 终态复诵保持 exit 2 与同一结构化结果');
|
|
297
315
|
const count3 = readFileSync(countFile, 'utf-8').split('\n').filter(Boolean).length;
|
|
298
316
|
assert(count3 === 1, '终态复诵零重算');
|
|
317
|
+
const failedDeliverable = readFileSync(failedDeliverablePath, 'utf-8');
|
|
318
|
+
rmSync(failedDeliverablePath);
|
|
319
|
+
const replayAfterMissingView = spawnSync('npx', [
|
|
320
|
+
'tsx',
|
|
321
|
+
'scripts/async-collect.ts',
|
|
322
|
+
'dp-crash1',
|
|
323
|
+
wroot
|
|
324
|
+
], {
|
|
325
|
+
encoding: 'utf-8',
|
|
326
|
+
env: {
|
|
327
|
+
...process.env,
|
|
328
|
+
GOTRY_SOLVE_COUNT_FILE: countFile
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
assert(replayAfterMissingView.status === 2 && JSON.stringify(terminalOutcomeOf(replayAfterMissingView.stdout ?? '')) === JSON.stringify(failedOutcome), 'failed 终态缺失视图时仍复诵同一 exit 2 与结构化结果');
|
|
332
|
+
assert(existsSync(failedDeliverablePath) && readFileSync(failedDeliverablePath, 'utf-8') === failedDeliverable, 'failed 终态复诵重建缺失 .deliverable.md 视图');
|
|
333
|
+
const countAfterViewRepair = readFileSync(countFile, 'utf-8').split('\n').filter(Boolean).length;
|
|
334
|
+
assert(countAfterViewRepair === 1, '终态视图修复零重算');
|
|
335
|
+
const tickRoot = mkdtempSync(join(tmpdir(), 'gotry-wf-tick-failed-'));
|
|
336
|
+
const tickTicket = {
|
|
337
|
+
id: 'dp-tick-failed1',
|
|
338
|
+
objective: 'state-cli 非4/4 机器终态回归',
|
|
339
|
+
requestedAt: new Date().toISOString(),
|
|
340
|
+
etaLabel: '秒级'
|
|
341
|
+
};
|
|
342
|
+
const tickState = {
|
|
343
|
+
calendar: {
|
|
344
|
+
year: 2026,
|
|
345
|
+
assertedWeekdays: {}
|
|
346
|
+
},
|
|
347
|
+
profile: {},
|
|
348
|
+
gates: [],
|
|
349
|
+
wishes: []
|
|
350
|
+
};
|
|
351
|
+
await persistAsyncTicket(tickTicket, tickState, tickRoot);
|
|
352
|
+
const tick = spawnSync('npx', [
|
|
353
|
+
'tsx',
|
|
354
|
+
'scripts/state-cli.ts',
|
|
355
|
+
'tick',
|
|
356
|
+
tickRoot
|
|
357
|
+
], {
|
|
358
|
+
encoding: 'utf-8'
|
|
359
|
+
});
|
|
360
|
+
assert(tick.status === 0, `state-cli tick 完成回收(实际 ${tick.status}:${(tick.stderr ?? '').slice(0, 200)})`);
|
|
361
|
+
const tickLedger = openLedgerIfExists(tickRoot);
|
|
362
|
+
const tickOutcome = tickLedger?.getWorkflowTerminalOutcome(tickTicket.id);
|
|
363
|
+
assert(tickLedger?.getWorkflowRun(tickTicket.id)?.status === 'failed' && tickOutcome?.schema === 'gotry_async_terminal.v1' && tickOutcome.status === 'failed' && tickOutcome.passed === 0 && tickOutcome.failed_checks.length === 4, 'state-cli tick 未透传 outcome 时仍从权威账本恢复非4/4 failed 终态');
|
|
364
|
+
const tickReplay = spawnSync('npx', [
|
|
365
|
+
'tsx',
|
|
366
|
+
'scripts/async-collect.ts',
|
|
367
|
+
tickTicket.id,
|
|
368
|
+
tickRoot
|
|
369
|
+
], {
|
|
370
|
+
encoding: 'utf-8'
|
|
371
|
+
});
|
|
372
|
+
assert(tickReplay.status === 2 && JSON.stringify(terminalOutcomeOf(tickReplay.stdout ?? '')) === JSON.stringify(tickOutcome), 'state-cli 写入的 failed 终态可由 collector 幂等复诵为同一 outcome/exit 2');
|
|
373
|
+
const successRoot = mkdtempSync(join(tmpdir(), 'gotry-wf-success-'));
|
|
374
|
+
const successCountFile = join(successRoot, 'solve-count.txt');
|
|
375
|
+
writeFileSync(successCountFile, '');
|
|
376
|
+
const successTicket = {
|
|
377
|
+
id: 'dp-success1',
|
|
378
|
+
objective: '4/4 机器终态回归',
|
|
379
|
+
requestedAt: new Date().toISOString(),
|
|
380
|
+
etaLabel: '秒级'
|
|
381
|
+
};
|
|
382
|
+
const successSpec = parseFlightPackToSpec(JSON.parse(readFileSync(join('..', 'data', 'flights_2026.json'), 'utf-8')));
|
|
383
|
+
successSpec.budgetCny = 9000;
|
|
384
|
+
const successState = {
|
|
385
|
+
calendar: {
|
|
386
|
+
year: 2026,
|
|
387
|
+
assertedWeekdays: {}
|
|
388
|
+
},
|
|
389
|
+
profile: {},
|
|
390
|
+
gates: [],
|
|
391
|
+
wishes: [],
|
|
392
|
+
spec: successSpec
|
|
393
|
+
};
|
|
394
|
+
await persistAsyncTicket(successTicket, successState, successRoot);
|
|
395
|
+
const success = spawnSync('npx', [
|
|
396
|
+
'tsx',
|
|
397
|
+
'scripts/async-collect.ts',
|
|
398
|
+
successTicket.id,
|
|
399
|
+
successRoot
|
|
400
|
+
], {
|
|
401
|
+
encoding: 'utf-8',
|
|
402
|
+
env: {
|
|
403
|
+
...process.env,
|
|
404
|
+
GOTRY_SOLVE_COUNT_FILE: successCountFile
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
const successOutcome = terminalOutcomeOf(success.stdout ?? '');
|
|
408
|
+
assert(success.status === 0 && successOutcome?.status === 'succeeded' && successOutcome.ticket_id === successTicket.id && successOutcome.passed === 4 && successOutcome.total === 4 && successOutcome.failed_checks.length === 0, `4/4 输出 gotry_async_terminal.v1/succeeded 且 exit 0(实际 ${success.status})`);
|
|
409
|
+
const successLedger = openLedgerIfExists(successRoot);
|
|
410
|
+
assert(successLedger?.getWorkflowRun(successTicket.id)?.status === 'settled' && successLedger.getWorkflowTerminalOutcome(successTicket.id)?.['status'] === 'succeeded', '4/4 账本终态 settled 且结构化结果随 async.settled 落账');
|
|
411
|
+
const successReplay = spawnSync('npx', [
|
|
412
|
+
'tsx',
|
|
413
|
+
'scripts/async-collect.ts',
|
|
414
|
+
successTicket.id,
|
|
415
|
+
successRoot
|
|
416
|
+
], {
|
|
417
|
+
encoding: 'utf-8',
|
|
418
|
+
env: {
|
|
419
|
+
...process.env,
|
|
420
|
+
GOTRY_SOLVE_COUNT_FILE: successCountFile
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
const successCount = readFileSync(successCountFile, 'utf-8').split('\n').filter(Boolean).length;
|
|
424
|
+
assert(successReplay.status === 0 && successCount === 1 && JSON.stringify(terminalOutcomeOf(successReplay.stdout ?? '')) === JSON.stringify(successOutcome), 'succeeded 终态复诵保持 exit 0、同一结构化结果且零重算');
|
|
299
425
|
const pw1 = ledger.requestPendingWrite({
|
|
300
426
|
idemKey: 'booking:demo-1',
|
|
301
427
|
seam: 'flight-order-confirm',
|
|
@@ -358,6 +484,10 @@ rmSync(wroot, {
|
|
|
358
484
|
recursive: true,
|
|
359
485
|
force: true
|
|
360
486
|
});
|
|
487
|
+
rmSync(successRoot, {
|
|
488
|
+
recursive: true,
|
|
489
|
+
force: true
|
|
490
|
+
});
|
|
361
491
|
console.log(`\nLEDGER TESTS: ${pass} ok, ${fail} fail`);
|
|
362
492
|
if (fail > 0) process.exit(1);
|
|
363
493
|
|