@danceiny/gotry 0.2.0-rc.31 → 0.2.0-rc.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/bin/gotry-bootstrap.js +63 -53
  4. package/bin/gotry-hbcli-release.d.ts +3 -0
  5. package/bin/gotry-hbcli-release.js +4 -0
  6. package/client/client.js +66 -21
  7. package/dist/capabilities/doctor.js +7 -8
  8. package/dist/capabilities/effect.js +45 -12
  9. package/dist/capabilities/flyai-config.js +12 -10
  10. package/dist/capabilities/flyai.js +87 -56
  11. package/dist/capabilities/hbcli-config.js +156 -0
  12. package/dist/capabilities/hbcli.js +29 -2
  13. package/dist/capabilities/resilience.js +6 -6
  14. package/dist/capabilities/session/adapters/ctrip-flight.js +42 -7
  15. package/dist/capabilities/session/adapters/ctrip-hotel.js +52 -3
  16. package/dist/capabilities/session/ctrip-city.js +186 -0
  17. package/dist/capabilities/session/extension-bridge.js +8 -1
  18. package/dist/capabilities/session/gui-flight.js +737 -0
  19. package/dist/capabilities/session/gui-hotel.js +413 -0
  20. package/dist/capabilities/session-search.js +98 -11
  21. package/dist/scripts/bootstrap-tests.js +23 -6
  22. package/dist/scripts/ctrip-city-tests.js +80 -0
  23. package/dist/scripts/effect-tests.js +602 -504
  24. package/dist/scripts/extension-tests.js +14 -8
  25. package/dist/scripts/flight-malformed-tests.js +1 -1
  26. package/dist/scripts/flyai-setup-tests.js +19 -4
  27. package/dist/scripts/flyai-tests.js +768 -653
  28. package/dist/scripts/gotry-web-api-tests.js +5 -0
  29. package/dist/scripts/gotry-web-client-tests.js +20 -1
  30. package/dist/scripts/gui-flight-live.js +27 -0
  31. package/dist/scripts/hbcli-tests.js +1 -1
  32. package/dist/scripts/hbcli-upgrade-tests.js +107 -0
  33. package/dist/scripts/hbcli-web-setup-tests.js +114 -0
  34. package/dist/scripts/hotel-date-gate-tests.js +1 -1
  35. package/dist/scripts/hotel-result-tests.js +169 -0
  36. package/dist/scripts/issue-271-liveness-tests.js +1 -1
  37. package/dist/scripts/session-tests.js +177 -6
  38. package/dist/src/gotry-web-api.js +64 -2
  39. package/dist/src/index.js +40 -18
  40. package/extension/manifest.json +2 -2
  41. package/package.json +2 -1
  42. package/ts/capabilities/flyai-config.ts +12 -10
  43. package/ts/capabilities/flyai.ts +91 -50
  44. package/ts/capabilities/hbcli-config.ts +128 -0
  45. package/ts/capabilities/hbcli.ts +30 -3
  46. package/ts/capabilities/session/adapters/ctrip-flight.ts +43 -7
  47. package/ts/capabilities/session/adapters/ctrip-hotel.ts +51 -4
  48. package/ts/capabilities/session/ctrip-city.ts +158 -0
  49. package/ts/capabilities/session/extension-bridge.ts +9 -2
  50. package/ts/capabilities/session/gui-flight.ts +792 -0
  51. package/ts/capabilities/session/gui-hotel.ts +451 -0
  52. package/ts/capabilities/session-search.ts +115 -15
  53. package/ts/src/gotry-web-api.ts +51 -2
  54. package/ts/src/index.ts +41 -19
@@ -65,6 +65,24 @@ async function attemptHbcli(bin, args, opts) {
65
65
  }
66
66
  catch { /* 非 JSON 输出,留给调用方处理 */ }
67
67
  }
68
+ // CLI exit status describes the process, not the API verdict. hbcli can exit
69
+ // zero with an API error envelope (for example an unconfigured supplier pool).
70
+ const code = result?.code;
71
+ const invalid = result === null;
72
+ const upstreamFailure = code !== undefined && code !== 0 && code !== '0';
73
+ if (invalid || upstreamFailure) {
74
+ const msg = result?.msg
75
+ ?? result?.message;
76
+ const detail = code === 300010002 || code === '300010002'
77
+ ? '当前账号没有可用供应商;库存查询未完成'
78
+ : typeof msg === 'string' ? msg.slice(0, 200) : 'API request failed';
79
+ return {
80
+ via: 'hbcli-error', exitCode: 0, result: null,
81
+ evidence: `[实时API:hbcli@error@${ts}]`,
82
+ stdout: r.stdout.slice(0, 2000), latencyMs,
83
+ error: invalid ? 'failed to parse hbcli output as JSON' : `hbcli upstream code ${String(code)}: ${detail}`,
84
+ };
85
+ }
68
86
  return {
69
87
  via: 'hbcli-realtime', exitCode: 0, result,
70
88
  evidence: `[实时API:hbcli@${ts}]`,
@@ -138,7 +156,7 @@ export async function searchHotels(query, opts = {}) {
138
156
  hbArgs.push('--check-out', query.checkOut);
139
157
  if (query.adults)
140
158
  hbArgs.push('--room-occupancies', JSON.stringify([{ adultCount: query.adults, childrenAges: [] }]));
141
- const live = await callHbcliJson(hbArgs, opts);
159
+ let live = await callHbcliJson(hbArgs, opts);
142
160
  // 取消立即结束:不读静态包、不产出命中/无结果/估算,也不计上游故障
143
161
  if (opts.signal?.aborted || /abort/i.test(live.error ?? '')) {
144
162
  const ts = new Date().toISOString();
@@ -149,6 +167,15 @@ export async function searchHotels(query, opts = {}) {
149
167
  latencyMs: live.latencyMs, error: `aborted by host signal${cleanupError}`, summary: `酒店「${query.destination}」检索已取消,未产生事实`,
150
168
  };
151
169
  }
170
+ const list = live.result?.list;
171
+ if (live.via === 'hbcli-realtime' && (!Array.isArray(list)
172
+ || list.some(item => item === null || typeof item !== 'object' || Array.isArray(item)))) {
173
+ live = {
174
+ ...live, via: 'hbcli-error', result: null,
175
+ evidence: `[实时API:hbcli@error@${new Date().toISOString()}]`,
176
+ error: 'invalid hotel-list response: expected list array of hotels; inventory not observed',
177
+ };
178
+ }
152
179
  if (live.via === 'hbcli-realtime') {
153
180
  // summary 即模型面(render 只透 summary):必须自带紧凑数据行 + 证据链,
154
181
  // 否则模型只看到「实时返回」占位一句话(issue #195 实锤)。
@@ -247,7 +274,7 @@ export async function checkAvail(query, opts = {}) {
247
274
  * ~/.staicli/credentials.json)——hbcli 侧 customer 档是最低优先级凭据(无
248
275
  * portal/API-key 凭据时才生效),登录不劫持既有凭据。本层不透出 token 值
249
276
  * (CLI 只回 token_saved,凭据留在 CLI 仓内,不进 gotry 会话/日志)。
250
- * auth 命令族要求 hbcli 带 register 支持(npm 0.0.4 起;0.0.3 报 unknown
277
+ * auth 命令族要求 hbcli 带 register 支持(官方原生 0.0.4 起;0.0.3 报 unknown
251
278
  * command,经 hbcli-error 面优雅失败)。
252
279
  */
253
280
  export async function customerSendCode(email, opts = {}) {
@@ -108,7 +108,7 @@ export async function withRetry(fn, policy, onBackoff) {
108
108
  export class CircuitBreaker {
109
109
  o;
110
110
  consecutiveFailures = 0;
111
- openedAt = 0;
111
+ openedAt = null;
112
112
  generation = 0;
113
113
  nextTokenId = 0;
114
114
  probeToken = null;
@@ -122,9 +122,9 @@ export class CircuitBreaker {
122
122
  return (this.o.now ?? Date.now)();
123
123
  }
124
124
  state() {
125
- if (this.openedAt > 0 && this.now() - this.openedAt >= this.o.openMs)
125
+ if (this.openedAt !== null && this.now() - this.openedAt >= this.o.openMs)
126
126
  return 'half-open';
127
- if (this.openedAt > 0)
127
+ if (this.openedAt !== null)
128
128
  return 'open';
129
129
  return 'closed';
130
130
  }
@@ -134,7 +134,7 @@ export class CircuitBreaker {
134
134
  if (s === 'closed')
135
135
  return { allowed: true, state: s, token: this.makeToken(false) };
136
136
  if (s === 'open')
137
- return { allowed: false, state: s };
137
+ return { allowed: false, state: s, retryAfterMs: Math.max(0, Math.min(this.o.openMs, this.o.openMs - (this.now() - this.openedAt))) };
138
138
  // half-open:单探测语义——已有探测在途拒其余并发
139
139
  if (this.probeToken)
140
140
  return { allowed: false, state: s };
@@ -158,7 +158,7 @@ export class CircuitBreaker {
158
158
  if (!this.owns(token))
159
159
  return;
160
160
  this.consecutiveFailures = 0;
161
- this.openedAt = 0;
161
+ this.openedAt = null;
162
162
  if (token?.probe === true || (!token && this.probeToken !== null)) {
163
163
  this.probeToken = null;
164
164
  this.generation += 1;
@@ -171,7 +171,7 @@ export class CircuitBreaker {
171
171
  if (token?.probe === true || (!token && this.probeToken !== null))
172
172
  this.probeToken = null;
173
173
  this.consecutiveFailures += 1;
174
- if (this.openedAt > 0 || this.consecutiveFailures >= this.threshold()) {
174
+ if (this.openedAt !== null || this.consecutiveFailures >= this.threshold()) {
175
175
  this.openedAt = this.now();
176
176
  this.generation += 1;
177
177
  }
@@ -6,23 +6,58 @@
6
6
  * (schema 实测 2026-08-28,见 data-sources.md §8)
7
7
  * 只读:适配器不含任何提交/预订语义;URL 直开即零 DOM 交互。
8
8
  */
9
- /** 城市三字码表(小起步集;词表外 unresolved 逐字保留,不做开放式猜测——ADR-12 同款边界) */
10
- const CITY_CODES = {
9
+ import { resolveCtripFlightCity, cityResolutionHint } from '../ctrip-city.js';
10
+ /**
11
+ * 离线起步缓存;未命中由编排层查询供应商城市数据(ctrip-city.ts),不推断航线覆盖。
12
+ * 码表只做性能优化,不在主链路上(显式码/供应商解析是正路)。
13
+ * 实测校准(2026-10-14):香港=hkg/迪拜=dxb 经 list 页实证——合法组合 HTTP 200 且
14
+ * title 含航线名(「中国香港(HKG)到迪拜(阿联酋)(DXB)机票预订」),非法组合 302 跳
15
+ * international/search(该 200/302 判别式即真数据校准手段)。
16
+ */
17
+ export const CITY_CODES = {
11
18
  上海: 'sha', 北京: 'bjs', 广州: 'can', 深圳: 'szx', 成都: 'ctu', 昆明: 'kmg',
12
19
  大理: 'dlu', 丽江: 'ljg', 西安: 'sia', 杭州: 'hgh', 三亚: 'syx', 厦门: 'xmn',
13
20
  重庆: 'cqg', 青岛: 'taa', 长沙: 'csx', 武汉: 'wuh', 南京: 'nkg', 郑州: 'cgo',
14
21
  贵阳: 'kwe', 桂林: 'kwl', 西双版纳: 'jhg', 香格里拉: 'dig',
22
+ 香港: 'hkg', 迪拜: 'dxb',
15
23
  };
16
- export function buildEntryUrl(from, to, depDate) {
24
+ /** Resolve unknown names against current supplier metadata before inventory navigation. */
25
+ export async function resolveFlightEntryUrl(from, to, depDate, codes = {}, resolve = resolveCtripFlightCity, backDate) {
26
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(depDate))
27
+ return { ok: false, unresolved: [depDate], error: '出发日期需要 YYYY-MM-DD' };
28
+ for (const c of [codes.fromCode, codes.toCode])
29
+ if (c !== undefined && !/^[a-z]{3}$/i.test(c))
30
+ return { ok: false, error: '城市/机场码必须是三个英文字母' };
31
+ const resolveCode = async (name, explicit) => {
32
+ const known = explicit ?? (/^[a-z]{3}$/i.test(name.trim()) ? name.trim() : undefined);
33
+ if (known)
34
+ return { code: known };
35
+ const result = await resolve(name);
36
+ return result.ok ? { code: result.city.code } : { error: cityResolutionHint(name, result) };
37
+ };
38
+ const [origin, destination] = await Promise.all([resolveCode(from, codes.fromCode), resolveCode(to, codes.toCode)]);
39
+ if (!origin.code || !destination.code)
40
+ return { ok: false, unresolved: [!origin.code ? from : '', !destination.code ? to : ''].filter(Boolean), error: [origin.error, destination.error].filter(Boolean).join(';') };
41
+ return buildEntryUrl(from, to, depDate, { fromCode: origin.code, toCode: destination.code }, backDate);
42
+ }
43
+ export function buildEntryUrl(from, to, depDate, codes = {}, backDate) {
17
44
  const unresolved = [];
18
- const fromCode = CITY_CODES[from];
19
- const toCode = CITY_CODES[to];
45
+ // 显式码优先(形状合格才采纳),词表只是缓存——任何城市都可经显式码成行。
46
+ const fromCode = codes.fromCode === undefined ? CITY_CODES[from.trim()] : /^[a-z]{3}$/i.test(codes.fromCode) ? codes.fromCode.toLowerCase() : undefined;
47
+ const toCode = codes.toCode === undefined ? CITY_CODES[to.trim()] : /^[a-z]{3}$/i.test(codes.toCode) ? codes.toCode.toLowerCase() : undefined;
20
48
  if (!fromCode)
21
49
  unresolved.push(from);
22
50
  if (!toCode)
23
51
  unresolved.push(to);
24
- if (unresolved.length > 0 || !/^\d{4}-\d{2}-\d{2}$/.test(depDate)) {
25
- return { ok: false, unresolved: unresolved.length > 0 ? unresolved : [depDate] };
52
+ const badDate = !/^\d{4}-\d{2}-\d{2}$/.test(depDate)
53
+ || (backDate !== undefined && (!/^\d{4}-\d{2}-\d{2}$/.test(backDate) || backDate <= depDate));
54
+ if (unresolved.length > 0 || badDate) {
55
+ return { ok: false, unresolved: unresolved.length > 0 ? unresolved : [badDate ? (backDate !== undefined && backDate <= depDate ? backDate : depDate) : depDate], ...(backDate !== undefined && backDate <= depDate ? { error: `回程(${backDate})须晚于去程(${depDate})` } : {}) };
56
+ }
57
+ // 往返形状(2026-10-14 GUI URL 教师实测定稿):round-{code}0-{code}0?depdate=去_回&cabin=y_s
58
+ // ——此前 roundtrip-{3字码}?depdate&retdate 的猜测形状实测 302,已废弃。
59
+ if (backDate) {
60
+ return { ok: true, url: `https://flights.ctrip.com/online/list/round-${fromCode}0-${toCode}0?depdate=${depDate}_${backDate}&cabin=y_s&adult=1&child=0&infant=0` };
26
61
  }
27
62
  return { ok: true, url: `https://flights.ctrip.com/online/list/oneway-${fromCode}-${toCode}?depdate=${depDate}` };
28
63
  }
@@ -13,10 +13,11 @@
13
13
  * 只读:适配器不含任何提交/预订语义;URL 直开即零 DOM 交互;ReadGuard 对酒店
14
14
  * 页面照常生效(下单/支付面 URL 仍被物理拦截)。
15
15
  */
16
- /** 城市码表(**实测校准 2026-09-03**:每条 id 均经 hotels.ctrip.com list 页
16
+ import { resolveCtripHotelCity, hotelResolutionHint } from '../ctrip-city.js';
17
+ /** 离线兼容缓存(**实测校准 2026-09-03**:每条 id 均经 hotels.ctrip.com list 页
17
18
  * <title> 验证——探测法曾纠出 104=平遥县(传猜成都)等 5 处错猜,表内只收
18
19
  * 验证过的 id;词表外 unresolved 逐字保留,调用方可显式传 cityId 覆盖) */
19
- const HOTEL_CITY_CODES = {
20
+ export const HOTEL_CITY_CODES = {
20
21
  上海: '2', 北京: '1', 广州: '32', 深圳: '30', 成都: '28',
21
22
  杭州: '17', 南京: '12', 苏州: '14', 无锡: '13', 扬州: '15', 镇江: '16',
22
23
  青岛: '7', 厦门: '25', 珠海: '31', 三亚: '43', 海口: '42',
@@ -24,10 +25,22 @@ const HOTEL_CITY_CODES = {
24
25
  贵阳: '38', 拉萨: '41', 乌鲁木齐: '39', 太原: '105', 长春: '158', 南通: '82',
25
26
  敦煌: '11', 舟山: '19', 张家界: '27', 黄山市: '23', 九江: '24', 武夷山: '26',
26
27
  迪拜: '220',
28
+ // Verified against the official list page and its displayed destination/date
29
+ // controls on 2026-10-07; https://hotels.ctrip.com/hotels/list?city=5
30
+ 哈尔滨: '5',
27
31
  };
32
+ export async function resolveHotelEntryUrl(q, resolve = resolveCtripHotelCity) {
33
+ if (q.cityId !== undefined)
34
+ return buildHotelEntryUrl(q);
35
+ const result = await resolve(q.to, q.country);
36
+ if (!result.ok)
37
+ return { ok: false, unresolved: [q.to], error: hotelResolutionHint(q.to, result) };
38
+ return buildHotelEntryUrl({ ...q, cityId: result.city.id });
39
+ }
28
40
  export function buildHotelEntryUrl(q) {
29
41
  const unresolved = [];
30
- const cityId = String(q.cityId ?? '').trim() || HOTEL_CITY_CODES[q.to.trim()];
42
+ const candidate = q.cityId === undefined ? HOTEL_CITY_CODES[q.to.trim()] : String(q.cityId).trim();
43
+ const cityId = candidate && /^[1-9]\d{0,9}$/.test(candidate) ? candidate : undefined;
31
44
  if (!cityId)
32
45
  unresolved.push(q.to);
33
46
  if (unresolved.length > 0) {
@@ -220,3 +233,39 @@ export function parseCtripHotelList(body, opts = {}) {
220
233
  walk(raw, 0, new Set());
221
234
  return out;
222
235
  }
236
+ /** Only an explicit empty hotel array proves a miss; parser failure proves nothing. */
237
+ export function classifyCtripHotelList(body) {
238
+ let raw;
239
+ try {
240
+ raw = JSON.parse(body);
241
+ }
242
+ catch {
243
+ return { shape: 'malformed', hotels: [] };
244
+ }
245
+ const envelope = raw;
246
+ if (envelope?.success === false || envelope?.ok === false
247
+ || (envelope?.code !== undefined && envelope.code !== 0 && envelope.code !== '0')
248
+ || /^(failure|error)$/i.test(String(envelope?.ResponseStatus?.Ack ?? ''))) {
249
+ return { shape: 'unrecognized', hotels: [] };
250
+ }
251
+ const hotels = parseCtripHotelList(body);
252
+ if (hotels.length > 0)
253
+ return { shape: 'parsed', hotels };
254
+ let emptyList = false;
255
+ let unparsedItems = false;
256
+ const inspectHotelLists = (node, depth) => {
257
+ if (depth > 12 || node === null || typeof node !== 'object')
258
+ return;
259
+ for (const [key, value] of Object.entries(node)) {
260
+ if (['hotelList', 'hotelMatchInfos'].includes(key) && Array.isArray(value)) {
261
+ if (value.length === 0)
262
+ emptyList = true;
263
+ else
264
+ unparsedItems = true;
265
+ }
266
+ inspectHotelLists(value, depth + 1);
267
+ }
268
+ };
269
+ inspectHotelLists(raw, 0);
270
+ return { shape: emptyList && !unparsedItems ? 'recognized-empty' : 'unrecognized', hotels: [] };
271
+ }
@@ -0,0 +1,186 @@
1
+ /** Public supplier city metadata, independent of inventory and account sessions. */
2
+ export const CTRIP_CITY_CATALOG_URL = 'https://m.ctrip.com/restapi/soa2/17909/SearchBoxRecommend';
3
+ export const CTRIP_CITY_SUGGEST_URL = 'https://flights.ctrip.com/international/search/api/poi/search';
4
+ export const CTRIP_HOTEL_CITY_URL = 'https://m.ctrip.com/restapi/soa2/34951/getHotelKeywords';
5
+ const normalized = (s) => s.normalize('NFKC').trim().replace(/^中国(?=香港|澳门)/, '').toLowerCase();
6
+ const text = (v) => typeof v === 'string' ? v.trim() : '';
7
+ const code = (v) => /^[a-z]{3}$/i.test(text(v)) ? text(v).toUpperCase() : undefined;
8
+ const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
9
+ export function parseCtripCityCatalog(value) {
10
+ const root = object(value);
11
+ if (object(root.ResponseStatus).Ack !== 'Success' || object(root.responseHead).errorCode !== '0' || !Array.isArray(root.recommendGroupList))
12
+ throw new Error('unrecognized city catalog');
13
+ const records = [];
14
+ let visited = 0;
15
+ const walk = (v, depth = 0) => {
16
+ if (++visited > 20_000 || depth > 12)
17
+ throw new Error('city catalog bounds');
18
+ if (Array.isArray(v)) {
19
+ for (const item of v)
20
+ walk(item, depth + 1);
21
+ return;
22
+ }
23
+ const r = object(v), c = code(r.code), name = text(r.name);
24
+ if (c && name && Number(r.id) > 0) {
25
+ records.push({ name, code: c, aliases: [name, text(r.eName), text(r.nameEn), text(r.namePy), text(r.specName)].filter(Boolean), context: text(r.specName) || undefined, requiresQualification: r.sameSpecCity === 1 });
26
+ if (Array.isArray(r.airportlst))
27
+ for (const item of r.airportlst) {
28
+ const a = object(item), ac = code(a.code), an = text(a.name);
29
+ if (ac && an)
30
+ records.push({ name: an, code: ac, aliases: [an], context: name, airport: true });
31
+ }
32
+ }
33
+ for (const [key, child] of Object.entries(r))
34
+ if (key !== 'airportlst' && child && typeof child === 'object')
35
+ walk(child, depth + 1);
36
+ };
37
+ walk(root.recommendGroupList);
38
+ return records;
39
+ }
40
+ export function parseCtripCitySuggestions(value) {
41
+ const root = object(value);
42
+ if (!Array.isArray(root.Data))
43
+ throw new Error('unrecognized city suggestions');
44
+ const records = [];
45
+ let visited = 0;
46
+ const walk = (items, depth = 0) => {
47
+ if (depth > 5)
48
+ throw new Error('city suggestion bounds');
49
+ for (const value of items) {
50
+ if (++visited > 2_000)
51
+ throw new Error('city suggestion bounds');
52
+ const r = object(value), c = code(r.Code), name = text(r.Name);
53
+ if (c && name && [3, 4, 5].includes(Number(r.Type)))
54
+ records.push({
55
+ name, code: c, aliases: [name, text(r.EName), text(r.NameAlias), text(r.ShortSpell)].filter(Boolean),
56
+ context: [text(r.Country), text(r.Province)].filter(Boolean).join(' / ') || undefined, airport: Number(r.Type) === 3,
57
+ });
58
+ if (Array.isArray(r.Datas))
59
+ walk(r.Datas, depth + 1);
60
+ // Nearby cities must not be substituted for the requested destination.
61
+ }
62
+ };
63
+ walk(root.Data);
64
+ return records;
65
+ }
66
+ export function matchCtripCity(query, records) {
67
+ const input = normalized(query);
68
+ const matches = records.filter(r => r.code.toLowerCase() === input || r.aliases.some(a => normalized(a) === input));
69
+ const unique = [...new Map(matches.map(r => [`${r.code}:${r.context ?? ''}`, r])).values()];
70
+ // A city and its airport may share one code. An explicitly typed code remains exact.
71
+ const codes = new Set(unique.map(r => r.code));
72
+ if (codes.size === 1 && /^[a-z]{3}$/i.test(query.trim()))
73
+ return { ok: true, city: unique[0] };
74
+ if (unique.length === 1 && (!unique[0].requiresQualification || normalized(unique[0].context ?? '') === input))
75
+ return { ok: true, city: unique[0] };
76
+ return { ok: false, reason: unique.length ? 'ambiguous' : 'not-found', candidates: unique.slice(0, 8) };
77
+ }
78
+ async function readMetadata(url, init, fetcher) {
79
+ const response = await fetcher(url, { ...init, signal: AbortSignal.timeout(8_000), redirect: 'error' });
80
+ if (!response.ok || !response.body)
81
+ throw new Error('city metadata unavailable');
82
+ const reader = response.body.getReader(), chunks = [];
83
+ let size = 0;
84
+ try {
85
+ for (;;) {
86
+ const { done, value } = await reader.read();
87
+ if (done)
88
+ break;
89
+ size += value.byteLength;
90
+ if (size > 512_000)
91
+ throw new Error('city metadata bounds');
92
+ chunks.push(value);
93
+ }
94
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
95
+ }
96
+ finally {
97
+ await reader.cancel().catch(() => { });
98
+ }
99
+ }
100
+ let catalog;
101
+ const catalogBody = {
102
+ head: { cver: '3', cid: '', extension: [{ name: 'source', value: 'ONLINE' }, { name: 'sotpGroup', value: 'CTrip' }, { name: 'sotpLocale', value: 'zh-CN' }] },
103
+ locale: 'zh-CN', departureCity: '', dataType: 0,
104
+ };
105
+ export async function resolveCtripFlightCity(query, fetcher = fetch) {
106
+ if (!query.trim() || query.length > 120)
107
+ return { ok: false, reason: 'not-found', candidates: [] };
108
+ if (fetcher === fetch && process.env.GOTRY_SESSION_LIVE === '0')
109
+ return { ok: false, reason: 'unavailable', candidates: [] };
110
+ try {
111
+ const load = () => readMetadata(CTRIP_CITY_CATALOG_URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(catalogBody) }, fetcher).then(parseCtripCityCatalog);
112
+ let records;
113
+ if (fetcher !== fetch)
114
+ records = await load();
115
+ else {
116
+ if (!catalog || Date.now() - catalog.at > 3_600_000)
117
+ catalog = { at: Date.now(), promise: load() };
118
+ try {
119
+ records = await catalog.promise;
120
+ }
121
+ catch {
122
+ catalog = undefined;
123
+ records = [];
124
+ }
125
+ }
126
+ const matched = matchCtripCity(query, records);
127
+ if (matched.ok || matched.reason === 'ambiguous')
128
+ return matched;
129
+ const url = new URL(CTRIP_CITY_SUGGEST_URL);
130
+ url.searchParams.set('key', query.trim().toUpperCase());
131
+ url.searchParams.set('filterAirport', 'false');
132
+ return matchCtripCity(query, parseCtripCitySuggestions(await readMetadata(url.href, {}, fetcher)));
133
+ }
134
+ catch {
135
+ return { ok: false, reason: 'unavailable', candidates: [] };
136
+ }
137
+ }
138
+ export function cityResolutionHint(query, result) {
139
+ if (result.reason === 'ambiguous')
140
+ return `城市「${query}」有多个候选,请确认城市或机场码:${result.candidates.map(c => `${c.name} ${c.code}${c.context ? `(${c.context})` : ''}`).join(';')}`;
141
+ return `unresolved 城市「${query}」:${result.reason === 'unavailable' ? '携程城市解析服务暂不可用' : '供应商城市候选未精确匹配'};请确认城市/机场名称,或提供 fromCityCode/toCityCode。城市解析失败不能证明该航线无库存或不受支持。`;
142
+ }
143
+ export function parseCtripHotelCities(value) {
144
+ const root = object(value), data = object(root.data), keywords = object(data.mainKeywordList).keywords;
145
+ if (object(root.ResponseStatus).Ack !== 'Success' || data.htlSpiderActionErrorCode || !Array.isArray(keywords) || keywords.length > 1_000)
146
+ throw new Error('hotel city metadata unavailable');
147
+ const records = [];
148
+ for (const item of keywords) {
149
+ const r = object(item), k = object(object(r.keyword).keywordContentInfo), region = object(object(r.controlInfo).regionInfo);
150
+ const display = object(region.displayCityModel), basic = object(region.basicCityModel), id = String(basic.cityId ?? '');
151
+ if (k.tripType !== 'CT' || !/^[1-9]\d{0,9}$/.test(id))
152
+ continue;
153
+ if (k.keywordCode !== undefined && String(k.keywordCode) !== id)
154
+ throw new Error('hotel city ID conflict');
155
+ const titles = Array.isArray(k.displayTexts) ? k.displayTexts.map(object).filter(t => t.key === 'MAIN_TITLE').map(t => text(t.value)) : [];
156
+ const name = text(display.cityName) || text(display.destinationName);
157
+ if (!name)
158
+ continue;
159
+ records.push({ id, name, aliases: [name, text(display.destinationName), text(display.destinationNameEN), ...titles].filter(Boolean),
160
+ countries: [text(display.countryName), text(display.countryNameEN)].filter(Boolean),
161
+ context: [text(display.countryName), text(display.provinceName)].filter(Boolean).join(' / ') });
162
+ }
163
+ return records;
164
+ }
165
+ export async function resolveCtripHotelCity(query, country, fetcher = fetch) {
166
+ if (!query.trim() || query.length > 120 || (country?.length ?? 0) > 120)
167
+ return { ok: false, reason: 'not-found', candidates: [] };
168
+ if (fetcher === fetch && process.env.GOTRY_SESSION_LIVE === '0')
169
+ return { ok: false, reason: 'unavailable', candidates: [] };
170
+ try {
171
+ const value = await readMetadata(CTRIP_HOTEL_CITY_URL, { method: 'POST', headers: { 'content-type': 'application/json' },
172
+ body: JSON.stringify({ head: { platform: 'PC', bu: 'HBU', group: 'ctrip', locale: 'zh-CN' }, queryInfo: { keyword: query.trim(), actionType: 'destination' } }) }, fetcher);
173
+ const input = normalized(query);
174
+ const candidates = parseCtripHotelCities(value).filter(c => (!country || c.countries.some(a => normalized(a) === normalized(country))) && c.aliases.some(a => normalized(a) === input));
175
+ const unique = [...new Map(candidates.map(c => [c.id, c])).values()];
176
+ return unique.length === 1 ? { ok: true, city: unique[0] } : { ok: false, reason: unique.length ? 'ambiguous' : 'not-found', candidates: unique.slice(0, 8) };
177
+ }
178
+ catch {
179
+ return { ok: false, reason: 'unavailable', candidates: [] };
180
+ }
181
+ }
182
+ export function hotelResolutionHint(query, result) {
183
+ if (result.reason === 'ambiguous')
184
+ return `城市「${query}」有多个候选,请确认国家或城市:${result.candidates.map(c => `${c.name}(${c.context},cityId=${c.id})`).join(';')}`;
185
+ return `城市「${query}」${result.reason === 'unavailable' ? '的携程酒店城市解析服务暂不可用' : '未精确匹配供应商城市候选'};可提供 country 消歧,或携程酒店 list 页 city= 数字作为 cityId。城市解析失败不能证明目的地不受支持。`;
186
+ }
@@ -513,7 +513,14 @@ export function createBridgeJobQueue(opts = {}) {
513
513
  const settle = armSettle(entry, resolve);
514
514
  entry.resolve = settle;
515
515
  entry.timer = setTimeout(() => {
516
- settle({ ok: false, reason: 'timeout', summary: `扩展未在 ${timeoutMs}ms 内回包(标签页无嗅探命中或扩展已停用)` });
516
+ const stage = entry.claimedOrigin === undefined ? 'queued' : 'claimed';
517
+ const task = full.kind === 'cookie-names' ? '登录态检查' : full.kind === 'search' ? '检索' : '登录页打开';
518
+ settle({
519
+ ok: false, reason: 'timeout', jobKind: full.kind, stage,
520
+ summary: stage === 'queued'
521
+ ? `扩展${task}等待领取超时(${timeoutMs}ms);尚未执行,请检查扩展是否支持当前站点或正在处理其他作业`
522
+ : `扩展${task}已领取但未在 ${timeoutMs}ms 内回传;请检查扩展运行错误与桥连接`,
523
+ });
517
524
  }, timeoutMs);
518
525
  if (!dispatchToParked(entry))
519
526
  queue.push(entry);