@danceiny/gotry 0.0.1-rc.8 → 0.2.0-rc.27

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 (506) hide show
  1. package/README.md +172 -217
  2. package/README.zh-CN.md +222 -0
  3. package/bin/gotry-backend.js +53 -0
  4. package/bin/gotry-booking-copilot.js +53 -0
  5. package/bin/gotry-bootstrap.js +1744 -0
  6. package/bin/gotry-inner.js +733 -83
  7. package/bin/gotry-process-liveness.d.ts +27 -0
  8. package/bin/gotry-process-liveness.js +97 -0
  9. package/bin/gotry-runtime-resolution.d.ts +27 -0
  10. package/bin/gotry-runtime-resolution.js +49 -0
  11. package/bin/gotry.js +1 -1
  12. package/client/client.js +203 -0
  13. package/cordis.gotry-patch.yml +80 -49
  14. package/data/airline-airports.json +39 -0
  15. package/data/stations-12306-verify.json +524 -0
  16. package/dist/capabilities/agent-reach-deep.js +45 -122
  17. package/dist/capabilities/agent-reach.js +101 -146
  18. package/dist/capabilities/anything.js +135 -94
  19. package/dist/capabilities/artifacts.js +370 -0
  20. package/dist/capabilities/channel-health.js +131 -0
  21. package/dist/capabilities/channel-registry.js +256 -0
  22. package/dist/capabilities/doctor.js +546 -0
  23. package/dist/capabilities/effect.js +394 -0
  24. package/dist/capabilities/external-event.js +149 -0
  25. package/dist/capabilities/fact-log.js +55 -0
  26. package/dist/capabilities/flyai-config.js +337 -0
  27. package/dist/capabilities/flyai.js +968 -0
  28. package/dist/capabilities/fx-contract.js +293 -0
  29. package/dist/capabilities/geo-atlas.js +246 -0
  30. package/dist/capabilities/ground-transfer.js +509 -0
  31. package/dist/capabilities/hbcli.js +260 -123
  32. package/dist/capabilities/hotelbyte-transaction.js +194 -0
  33. package/dist/capabilities/incident-log.js +131 -61
  34. package/dist/capabilities/itinerary-artifact.js +190 -0
  35. package/dist/capabilities/itinerary-deck-artifact.js +194 -0
  36. package/dist/capabilities/itinerary-deck-export.js +339 -0
  37. package/dist/capabilities/lavish-local.js +924 -0
  38. package/dist/capabilities/model-override.js +38 -0
  39. package/dist/capabilities/opensky.js +54 -43
  40. package/dist/capabilities/resilience.js +191 -0
  41. package/dist/capabilities/session/action-cache.js +126 -0
  42. package/dist/capabilities/session/adapters/ctrip-flight.js +141 -0
  43. package/dist/capabilities/session/adapters/ctrip-hotel.js +222 -0
  44. package/dist/capabilities/session/adapters/dida-portal.js +274 -0
  45. package/dist/capabilities/session/adapters/meituan-local.js +54 -0
  46. package/dist/capabilities/session/adapters/rail-12306.js +342 -0
  47. package/dist/capabilities/session/benchmark.js +189 -0
  48. package/dist/capabilities/session/bridge-ledger.js +224 -0
  49. package/dist/capabilities/session/extension-bridge.js +636 -0
  50. package/dist/capabilities/session/extension-channel.js +109 -0
  51. package/dist/capabilities/session/extension-distribution.js +230 -0
  52. package/dist/capabilities/session/extract.js +50 -0
  53. package/dist/capabilities/session/golden-score.js +114 -0
  54. package/dist/capabilities/session/health-watch.js +215 -0
  55. package/dist/capabilities/session/read-guard.js +107 -0
  56. package/dist/capabilities/session/static-flight-golden.js +150 -0
  57. package/dist/capabilities/session/transport.js +109 -0
  58. package/dist/capabilities/session/wizard.js +117 -0
  59. package/dist/capabilities/session-consent.js +178 -0
  60. package/dist/capabilities/session-login.js +170 -0
  61. package/dist/capabilities/session-search.js +686 -0
  62. package/dist/capabilities/spawn-bounded.js +203 -0
  63. package/dist/capabilities/sponsor-plugin.js +341 -0
  64. package/dist/capabilities/visa-policy.js +140 -0
  65. package/dist/capabilities/weather.js +243 -138
  66. package/dist/data/session-golden-20.json +25 -0
  67. package/dist/data/sf-golden-manifest.json +103 -0
  68. package/dist/data/sf-static-routes.json +91 -0
  69. package/dist/scripts/action-cache-tests.js +72 -0
  70. package/dist/scripts/agent-planning-turn-deadline-e2e.js +242 -0
  71. package/dist/scripts/agent-planning-turn-deadline-tests.js +185 -0
  72. package/dist/scripts/agent-reach-deep-tests.js +30 -40
  73. package/dist/scripts/agent-reach-error-tests.js +354 -0
  74. package/dist/scripts/agent-reach-tests.js +26 -18
  75. package/dist/scripts/agent-reach-wrapper-tests.js +50 -50
  76. package/dist/scripts/anything-tests.js +116 -60
  77. package/dist/scripts/artifact-client-contract-tests.js +220 -0
  78. package/dist/scripts/artifacts-capability-tests.js +727 -0
  79. package/dist/scripts/async-collect.js +68 -10
  80. package/dist/scripts/benchmark-environment-bridge-e2e.js +741 -0
  81. package/dist/scripts/benchmark-environment-bridge-tests.js +1452 -0
  82. package/dist/scripts/booking-copilot-availability-ledger-binding-tests.js +126 -0
  83. package/dist/scripts/booking-copilot-availability-policy-tests.js +265 -0
  84. package/dist/scripts/booking-copilot-bin-proof-tests.js +66 -0
  85. package/dist/scripts/booking-copilot-cleanup-proof-helper.js +76 -0
  86. package/dist/scripts/booking-copilot-crossrepo-fixture-server.js +144 -0
  87. package/dist/scripts/booking-copilot-dsh-core-proof-tests.js +424 -0
  88. package/dist/scripts/booking-copilot-dsh-planner-proof-tests.js +2839 -0
  89. package/dist/scripts/booking-copilot-dsh-plugin-proof-tests.js +309 -0
  90. package/dist/scripts/booking-copilot-dsh-readiness-proof.js +238 -0
  91. package/dist/scripts/booking-copilot-dsh-warmer-proof.js +123 -0
  92. package/dist/scripts/booking-copilot-event-sequence-concurrency-proof-tests.js +156 -0
  93. package/dist/scripts/booking-copilot-gap-code-contract-proof-tests.js +70 -0
  94. package/dist/scripts/booking-copilot-intent-proof-tests.js +422 -0
  95. package/dist/scripts/booking-copilot-operation-ledger-concurrency-proof-tests.js +184 -0
  96. package/dist/scripts/booking-copilot-planner-live-probe.js +95 -0
  97. package/dist/scripts/booking-copilot-proof-runtime.js +42 -0
  98. package/dist/scripts/booking-copilot-receipt-ledger-concurrency-proof-tests.js +210 -0
  99. package/dist/scripts/booking-copilot-runtime-proof-tests.js +2349 -0
  100. package/dist/scripts/booking-copilot-server-proof-tests.js +784 -0
  101. package/dist/scripts/booking-copilot-startup-proof-tests.js +94 -0
  102. package/dist/scripts/booking-executor-tests.js +80 -0
  103. package/dist/scripts/booking-recovery-chain-tests.js +182 -0
  104. package/dist/scripts/booking-saga-tests.js +125 -0
  105. package/dist/scripts/booking-surface-contract-proof-tests.js +212 -0
  106. package/dist/scripts/bootstrap-tests.js +1479 -0
  107. package/dist/scripts/bridge-events-tests.js +239 -0
  108. package/dist/scripts/bridge-ledger-tests.js +428 -0
  109. package/dist/scripts/build-changelog.js +238 -0
  110. package/dist/scripts/build-metrics-report.js +331 -0
  111. package/dist/scripts/changelog-tests.js +118 -0
  112. package/dist/scripts/channel-probe-tests.js +103 -0
  113. package/dist/scripts/channel-probe.js +169 -0
  114. package/dist/scripts/channel-registry-tests.js +208 -0
  115. package/dist/scripts/companion-tests.js +67 -0
  116. package/dist/scripts/dida-cookie-probe.js +87 -0
  117. package/dist/scripts/dida-runner-stop-tests.js +311 -0
  118. package/dist/scripts/dida-sw-probe.js +114 -0
  119. package/dist/scripts/diff-test.js +17 -12
  120. package/dist/scripts/doctor-tests.js +564 -0
  121. package/dist/scripts/dsh-artifact-e2e.js +279 -0
  122. package/dist/scripts/dsh-artifact-web-e2e.js +675 -0
  123. package/dist/scripts/dsh-http-proxy-sse-proof.js +90 -0
  124. package/dist/scripts/dsh-runtime-closure-tests.js +182 -0
  125. package/dist/scripts/dsh-runtime-closure.js +162 -0
  126. package/dist/scripts/dsh-session-v3-migration-proof.js +109 -0
  127. package/dist/scripts/dsh-subprocess-local-proof.js +150 -0
  128. package/dist/scripts/dsh-target-closure-proof.js +178 -0
  129. package/dist/scripts/effect-tests.js +539 -0
  130. package/dist/scripts/engine-run.js +1 -3
  131. package/dist/scripts/engine-tests.js +16 -10
  132. package/dist/scripts/evaluation-cadence-tests.js +174 -0
  133. package/dist/scripts/evaluation-contract-tests.js +268 -0
  134. package/dist/scripts/extension-distribution-cli.js +39 -0
  135. package/dist/scripts/extension-distribution-tests.js +443 -0
  136. package/dist/scripts/extension-tests.js +988 -0
  137. package/dist/scripts/external-event-tests.js +350 -0
  138. package/dist/scripts/fact-gate-tests.js +869 -0
  139. package/dist/scripts/fixtures/extension-bridge-unref-child.mjs +21 -0
  140. package/dist/scripts/flight-hotel-anchor-363-registered-e2e.js +169 -0
  141. package/dist/scripts/flight-malformed-tests.js +159 -0
  142. package/dist/scripts/flyai-setup-tests.js +228 -0
  143. package/dist/scripts/flyai-setup-tool-tests.js +54 -0
  144. package/dist/scripts/flyai-tests.js +692 -0
  145. package/dist/scripts/flyai-tool-registration-contract-tests.js +91 -0
  146. package/dist/scripts/fx-contract-tests.js +201 -0
  147. package/dist/scripts/g5-guard-tests.js +131 -0
  148. package/dist/scripts/g5-guard.js +189 -0
  149. package/dist/scripts/gen-lunar-anchors.js +106 -0
  150. package/dist/scripts/geo-atlas-tests.js +283 -0
  151. package/dist/scripts/gotry-backend-kernel-tests.js +206 -0
  152. package/dist/scripts/gotry-try-demo-tests.js +79 -0
  153. package/dist/scripts/gotry-try-demo.js +49 -0
  154. package/dist/scripts/ground-transfer-tests.js +956 -0
  155. package/dist/scripts/hbcli-e2e-tests.js +159 -0
  156. package/dist/scripts/hbcli-live-optin-tests.js +96 -0
  157. package/dist/scripts/hbcli-release-contract-tests.js +122 -0
  158. package/dist/scripts/hbcli-tests.js +121 -69
  159. package/dist/scripts/health-watch-cli.js +73 -0
  160. package/dist/scripts/hotel-date-gate-tests.js +496 -0
  161. package/dist/scripts/hotelbyte-reconcile-tests.js +141 -0
  162. package/dist/scripts/hotelbyte-spawn-e2e-tests.js +373 -0
  163. package/dist/scripts/i18n-tests.js +41 -0
  164. package/dist/scripts/incident-tests.js +281 -87
  165. package/dist/scripts/issue-194-job-id-guard-tests.js +106 -0
  166. package/dist/scripts/issue-233-cancel-refund-commission-tests.js +392 -0
  167. package/dist/scripts/issue-271-liveness-tests.js +569 -0
  168. package/dist/scripts/issue-289-model-retry-real-tests.js +296 -0
  169. package/dist/scripts/issue-289-model-retry-tests.js +441 -0
  170. package/dist/scripts/issue-289-web-retry-e2e.js +630 -0
  171. package/dist/scripts/issue-338-home-city-e2e.js +577 -0
  172. package/dist/scripts/issue343-real-entry-e2e.js +160 -0
  173. package/dist/scripts/issue436-persisted-routing-e2e.js +247 -0
  174. package/dist/scripts/itinerary-artifact-tests.js +368 -0
  175. package/dist/scripts/itinerary-deck-artifact-tests.js +416 -0
  176. package/dist/scripts/itinerary-deck-export-tests.js +552 -0
  177. package/dist/scripts/itinerary-deck-tests.js +435 -0
  178. package/dist/scripts/itinerary-html-tests.js +426 -0
  179. package/dist/scripts/journey-tests.js +22 -27
  180. package/dist/scripts/kernel-manifest-evidence.js +109 -0
  181. package/dist/scripts/kernel-manifest-gate.js +126 -0
  182. package/dist/scripts/kernel-manifest-tests.js +212 -0
  183. package/dist/scripts/kernel-manifest-trace-entry.js +7 -0
  184. package/dist/scripts/kernel-manifest-trace-hook.mjs +28 -0
  185. package/dist/scripts/kernel-manifest.js +369 -0
  186. package/dist/scripts/lavish-local-tests.js +1226 -0
  187. package/dist/scripts/lavish-product-tools-tests.js +537 -0
  188. package/dist/scripts/ledger-repair-apply-tests.js +316 -0
  189. package/dist/scripts/ledger-repair-plan-tests.js +375 -0
  190. package/dist/scripts/ledger-tests.js +480 -0
  191. package/dist/scripts/ledger-workflow-crash.js +32 -0
  192. package/dist/scripts/managed-dsh-cleanup-diagnostic-proof.js +184 -0
  193. package/dist/scripts/managed-dsh-close-failure-proof.js +172 -0
  194. package/dist/scripts/managed-dsh-run-port-proof.js +153 -0
  195. package/dist/scripts/managed-dsh-terminal-proof.js +252 -0
  196. package/dist/scripts/map-tools-vendor-package-proof.js +365 -0
  197. package/dist/scripts/memory-capture-tests.js +242 -61
  198. package/dist/scripts/memory-decay-tests.js +49 -0
  199. package/dist/scripts/memory-lifecycle-tests.js +657 -0
  200. package/dist/scripts/memory-lifecycle.js +196 -0
  201. package/dist/scripts/memory-metrics.js +29 -31
  202. package/dist/scripts/memory-value-report.js +631 -0
  203. package/dist/scripts/memory-value-tests.js +328 -0
  204. package/dist/scripts/metrics-report-tests.js +151 -0
  205. package/dist/scripts/model-override-e2e.js +137 -0
  206. package/dist/scripts/nightly-evidence-tests.js +161 -0
  207. package/dist/scripts/nightly-evidence.js +286 -0
  208. package/dist/scripts/nudge-digest.js +43 -42
  209. package/dist/scripts/observability-tests.js +381 -0
  210. package/dist/scripts/onboarding-tests.js +161 -0
  211. package/dist/scripts/opensky-check.js +18 -13
  212. package/dist/scripts/opensky-tests.js +28 -28
  213. package/dist/scripts/persona-surface-guard-tests.js +49 -0
  214. package/dist/scripts/pnpm-dsh-closure-proof.js +17 -0
  215. package/dist/scripts/policy-anchor-359-registered-e2e.js +214 -0
  216. package/dist/scripts/price-drift-tests.js +340 -0
  217. package/dist/scripts/price-drift-watch.js +447 -0
  218. package/dist/scripts/probe-poi-tests.js +53 -45
  219. package/dist/scripts/product-metrics.js +483 -0
  220. package/dist/scripts/publish-preverify.js +110 -0
  221. package/dist/scripts/realtime-pricing-tests.js +76 -0
  222. package/dist/scripts/recall-tests.js +513 -0
  223. package/dist/scripts/replay-async.js +20 -18
  224. package/dist/scripts/replay-real.js +18 -18
  225. package/dist/scripts/replay.js +52 -82
  226. package/dist/scripts/session-attach-diagnose.js +31 -0
  227. package/dist/scripts/session-attach-poc.js +62 -0
  228. package/dist/scripts/session-benchmark.js +180 -0
  229. package/dist/scripts/session-dida-live-e2e.js +199 -0
  230. package/dist/scripts/session-extract-tests.js +60 -0
  231. package/dist/scripts/session-link-tests.js +478 -0
  232. package/dist/scripts/session-login.js +29 -0
  233. package/dist/scripts/session-tests.js +862 -0
  234. package/dist/scripts/session-zones-tests.js +358 -0
  235. package/dist/scripts/sf-live-benchmark.js +367 -0
  236. package/dist/scripts/sf-live-challenge-stop-tests.js +453 -0
  237. package/dist/scripts/sf-live-cli-tests.js +92 -0
  238. package/dist/scripts/sf-live-options.js +46 -0
  239. package/dist/scripts/sf-manifest-tests.js +30 -0
  240. package/dist/scripts/sf-manifest.js +33 -0
  241. package/dist/scripts/sf-soft-score-tests.js +67 -0
  242. package/dist/scripts/sf-summary-tests.js +324 -0
  243. package/dist/scripts/sf-summary.js +525 -0
  244. package/dist/scripts/share-tests.js +432 -0
  245. package/dist/scripts/skeleton-check.js +16 -14
  246. package/dist/scripts/skeleton-integration-test.js +28 -11
  247. package/dist/scripts/skills-contract-tests.js +51 -46
  248. package/dist/scripts/smoke-session-gate-tests.js +21 -0
  249. package/dist/scripts/smoke.js +703 -219
  250. package/dist/scripts/spawn-bounded-abort-tests.js +241 -0
  251. package/dist/scripts/sponsor-reuse-tests.js +262 -0
  252. package/dist/scripts/state-cli-tests.js +261 -0
  253. package/dist/scripts/state-cli.js +585 -0
  254. package/dist/scripts/state-repair-cli.js +66 -0
  255. package/dist/scripts/state-repair-tests.js +140 -0
  256. package/dist/scripts/static-golden-tests.js +165 -0
  257. package/dist/scripts/time-eval-tests.js +210 -192
  258. package/dist/scripts/travel-timeline-tests.js +59 -0
  259. package/dist/scripts/turn-handoff-collect-tests.js +169 -0
  260. package/dist/scripts/turn-handoff-collect.js +161 -0
  261. package/dist/scripts/turn-policy-tests.js +55 -0
  262. package/dist/scripts/typed-contract-canary.js +176 -0
  263. package/dist/scripts/tz-resolver-sanity.js +50 -0
  264. package/dist/scripts/tz-resolver-tests.js +584 -0
  265. package/dist/scripts/unified-tests.js +23 -19
  266. package/dist/scripts/visa-policy-tests.js +62 -0
  267. package/dist/scripts/weather-tests.js +276 -41
  268. package/dist/scripts/wish-channel-gate-tests.js +54 -0
  269. package/dist/scripts/write-gate-tests.js +522 -0
  270. package/dist/scripts/z3-lifecycle-fault-tests.js +188 -0
  271. package/dist/scripts/z3-lifecycle-tests.js +170 -0
  272. package/dist/scripts/z3-race-repeat-tests.js +39 -0
  273. package/dist/scripts/z3-race-tests.js +41 -0
  274. package/dist/src/artifact-gate.js +829 -0
  275. package/dist/src/backend/kernel.js +91 -0
  276. package/dist/src/backend/modules/booking-copilot.js +92 -0
  277. package/dist/src/backend/modules/booking-executor.js +124 -0
  278. package/dist/src/backend/modules/session-search.js +551 -0
  279. package/dist/src/benchmark-agent-conformance.js +578 -0
  280. package/dist/src/benchmark-environment-bridge.js +515 -0
  281. package/dist/src/benchmark-headless-child-diagnostics.js +166 -0
  282. package/dist/src/benchmark-tool-isolation.js +151 -0
  283. package/dist/src/bookable-facts.js +533 -0
  284. package/dist/src/booking-saga.js +97 -0
  285. package/dist/src/booking-surface/availability-policy.js +697 -0
  286. package/dist/src/booking-surface/booking-intent.js +43 -0
  287. package/dist/src/booking-surface/cancel-refund-commission.js +379 -0
  288. package/dist/src/booking-surface/canonical-schema.js +116 -0
  289. package/dist/src/booking-surface/contracts.js +75 -0
  290. package/dist/src/booking-surface/dsh-planner.js +1854 -0
  291. package/dist/src/booking-surface/dsh-plugin.js +378 -0
  292. package/dist/src/booking-surface/dsh-worker.js +98 -0
  293. package/dist/src/booking-surface/error-codes.js +231 -0
  294. package/dist/src/booking-surface/index.js +9 -0
  295. package/dist/src/booking-surface/managed-dsh-cleanup-diagnostic.js +97 -0
  296. package/dist/src/booking-surface/managed-dsh-run-port.js +244 -0
  297. package/dist/src/booking-surface/profile.js +24 -0
  298. package/dist/src/booking-surface/recovery-chain.js +367 -0
  299. package/dist/src/booking-surface/runtime.js +1968 -0
  300. package/dist/src/booking-surface/server.js +674 -0
  301. package/dist/src/booking-surface/startup.js +168 -0
  302. package/dist/src/booking-surface/validation.js +261 -0
  303. package/dist/src/bridge.js +20 -13
  304. package/dist/src/companions.js +86 -0
  305. package/dist/src/contracts.js +21 -43
  306. package/dist/src/dsh-llm.js +97 -111
  307. package/dist/src/engine.js +276 -193
  308. package/dist/src/evaluation-cadence.js +97 -0
  309. package/dist/src/evaluation-contracts.js +283 -0
  310. package/dist/src/flight-pack-adapter.js +54 -0
  311. package/dist/src/flight-pack-contract.js +2 -0
  312. package/dist/src/flyai-setup-tool.js +70 -0
  313. package/dist/src/gotry-backend.js +125 -0
  314. package/dist/src/hotel-date-gate.js +118 -0
  315. package/dist/src/i18n.js +88 -0
  316. package/dist/src/index.js +2305 -731
  317. package/dist/src/itinerary-deck.js +139 -0
  318. package/dist/src/itinerary-doc-shared.js +661 -0
  319. package/dist/src/itinerary-html.js +131 -0
  320. package/dist/src/journey.js +155 -108
  321. package/dist/src/lavish-tools.js +400 -0
  322. package/dist/src/ledger-repair-apply.js +538 -0
  323. package/dist/src/ledger-repair-plan.js +463 -0
  324. package/dist/src/loop.js +358 -162
  325. package/dist/src/memory-capture.js +180 -32
  326. package/dist/src/memory-decay.js +47 -0
  327. package/dist/src/memory-lifecycle.js +1310 -0
  328. package/dist/src/memory-utility.js +27 -40
  329. package/dist/src/mock-llm.js +36 -61
  330. package/dist/src/model.js +81 -36
  331. package/dist/src/realtime-pricing.js +103 -0
  332. package/dist/src/recall/card.js +74 -0
  333. package/dist/src/recall/evaluator.js +140 -0
  334. package/dist/src/recall/integration.js +17 -0
  335. package/dist/src/recall/tick.js +166 -0
  336. package/dist/src/session-link/plan-it-action.js +48 -0
  337. package/dist/src/session-link/session-link.js +248 -0
  338. package/dist/src/session-zones.js +507 -0
  339. package/dist/src/share/adapters.js +51 -0
  340. package/dist/src/share/share-consent.js +76 -0
  341. package/dist/src/share/share-deck.js +58 -0
  342. package/dist/src/share/share-token.js +146 -0
  343. package/dist/src/slot-spec.js +84 -106
  344. package/dist/src/state-ledger.js +767 -0
  345. package/dist/src/state-repair.js +299 -0
  346. package/dist/src/subagent-job-id-guard.js +58 -0
  347. package/dist/src/time-anchor.js +231 -33
  348. package/dist/src/tool-packet.js +20 -8
  349. package/dist/src/travel-slots.js +58 -35
  350. package/dist/src/travel-timeline.js +59 -0
  351. package/dist/src/turn-deadline.js +287 -0
  352. package/dist/src/turn-policy.js +118 -0
  353. package/dist/src/tz-resolver.js +143 -0
  354. package/dist/src/unified.js +538 -360
  355. package/dist/src/wish-pool.js +42 -12
  356. package/dist/src/write-gate.js +495 -0
  357. package/dist/src/z3-shared.js +284 -0
  358. package/extension/README.md +21 -0
  359. package/extension/README.zh-CN.md +21 -0
  360. package/extension/background.js +463 -0
  361. package/extension/content-bridge.js +270 -0
  362. package/extension/content-main.js +111 -0
  363. package/extension/manifest.json +60 -0
  364. package/package.json +407 -14
  365. package/schemas/booking.intent.schema.json +193 -0
  366. package/schemas/booking.surface.schema.json +2622 -0
  367. package/ts/capabilities/agent-reach-deep.ts +114 -0
  368. package/ts/capabilities/agent-reach.ts +198 -0
  369. package/ts/capabilities/anything.ts +255 -0
  370. package/ts/capabilities/artifacts.ts +428 -0
  371. package/ts/capabilities/fact-log.ts +54 -0
  372. package/ts/capabilities/flyai-config.ts +388 -0
  373. package/ts/capabilities/flyai.ts +1274 -0
  374. package/ts/capabilities/hbcli.ts +253 -71
  375. package/ts/capabilities/incident-log.ts +88 -59
  376. package/ts/capabilities/itinerary-artifact.ts +214 -0
  377. package/ts/capabilities/itinerary-deck-artifact.ts +218 -0
  378. package/ts/capabilities/itinerary-deck-export.ts +378 -0
  379. package/ts/capabilities/opensky.ts +121 -0
  380. package/ts/capabilities/session/action-cache.ts +148 -0
  381. package/ts/capabilities/session/adapters/ctrip-flight.ts +181 -0
  382. package/ts/capabilities/session/adapters/ctrip-hotel.ts +238 -0
  383. package/ts/capabilities/session/adapters/dida-portal.ts +338 -0
  384. package/ts/capabilities/session/adapters/meituan-local.ts +70 -0
  385. package/ts/capabilities/session/adapters/rail-12306.ts +392 -0
  386. package/ts/capabilities/session/benchmark.ts +276 -0
  387. package/ts/capabilities/session/bridge-ledger.ts +333 -0
  388. package/ts/capabilities/session/extension-bridge.ts +794 -0
  389. package/ts/capabilities/session/extension-channel.ts +144 -0
  390. package/ts/capabilities/session/extension-distribution.ts +266 -0
  391. package/ts/capabilities/session/extract.ts +54 -0
  392. package/ts/capabilities/session/golden-score.ts +139 -0
  393. package/ts/capabilities/session/health-watch.ts +264 -0
  394. package/ts/capabilities/session/read-guard.ts +141 -0
  395. package/ts/capabilities/session/static-flight-golden.ts +209 -0
  396. package/ts/capabilities/session/transport.ts +146 -0
  397. package/ts/capabilities/session/wizard.ts +140 -0
  398. package/ts/capabilities/session-consent.ts +211 -0
  399. package/ts/capabilities/session-login.ts +208 -0
  400. package/ts/capabilities/session-search.ts +893 -0
  401. package/ts/capabilities/weather.ts +330 -0
  402. package/ts/dsh-runtime/vendor/README.md +68 -0
  403. package/ts/dsh-runtime/vendor/dsh-map-tools/LICENSE +21 -0
  404. package/ts/dsh-runtime/vendor/dsh-map-tools/README.en.md +405 -0
  405. package/ts/dsh-runtime/vendor/dsh-map-tools/README.md +404 -0
  406. package/ts/dsh-runtime/vendor/dsh-map-tools/client/client.js +1584 -0
  407. package/ts/dsh-runtime/vendor/dsh-map-tools/cordis.patch.yml +5 -0
  408. package/ts/dsh-runtime/vendor/dsh-map-tools/icon.svg +5 -0
  409. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/clients/amap.js +595 -0
  410. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/clients/nominatim.js +63 -0
  411. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/clients/osrm.js +58 -0
  412. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/clients/photon.js +55 -0
  413. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/config-file.js +87 -0
  414. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/config-route.js +131 -0
  415. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/config.js +16 -0
  416. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/geo.js +232 -0
  417. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/index.js +120 -0
  418. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/settings-ns.js +40 -0
  419. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/staticmap-route.js +115 -0
  420. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/tools/geocode.js +127 -0
  421. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/tools/poi.js +84 -0
  422. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/tools/routes.js +267 -0
  423. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/clients/amap.d.ts +90 -0
  424. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/clients/nominatim.d.ts +17 -0
  425. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/clients/osrm.d.ts +15 -0
  426. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/clients/photon.d.ts +22 -0
  427. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/config-file.d.ts +33 -0
  428. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/config-route.d.ts +23 -0
  429. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/config.d.ts +23 -0
  430. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/geo.d.ts +61 -0
  431. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/index.d.ts +18 -0
  432. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/settings-ns.d.ts +14 -0
  433. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/staticmap-route.d.ts +31 -0
  434. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/tools/geocode.d.ts +11 -0
  435. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/tools/poi.d.ts +9 -0
  436. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/tools/routes.d.ts +75 -0
  437. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/types.d.ts +68 -0
  438. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types.js +16 -0
  439. package/ts/dsh-runtime/vendor/dsh-map-tools/package.json +97 -0
  440. package/ts/package.json +296 -3
  441. package/ts/scripts/async-collect.ts +91 -0
  442. package/ts/scripts/map-tools-vendor-package-proof.ts +404 -0
  443. package/ts/scripts/skeleton-check.ts +1 -1
  444. package/ts/scripts/skeleton-integration-test.ts +23 -1
  445. package/ts/scripts/state-cli.ts +568 -0
  446. package/ts/scripts/turn-handoff-collect.ts +178 -0
  447. package/ts/src/artifact-gate.ts +991 -0
  448. package/ts/src/benchmark-agent-conformance.ts +619 -0
  449. package/ts/src/benchmark-environment-bridge.ts +538 -0
  450. package/ts/src/benchmark-headless-child-diagnostics.ts +184 -0
  451. package/ts/src/benchmark-tool-isolation.ts +166 -0
  452. package/ts/src/bookable-facts.ts +837 -0
  453. package/ts/src/booking-saga.ts +133 -0
  454. package/ts/src/booking-surface/availability-policy.ts +522 -0
  455. package/ts/src/booking-surface/booking-intent.ts +86 -0
  456. package/ts/src/booking-surface/cancel-refund-commission.ts +488 -0
  457. package/ts/src/booking-surface/canonical-schema.js +116 -0
  458. package/ts/src/booking-surface/contracts.ts +475 -0
  459. package/ts/src/booking-surface/dsh-planner.ts +1949 -0
  460. package/ts/src/booking-surface/dsh-plugin.js +378 -0
  461. package/ts/src/booking-surface/dsh-worker.ts +110 -0
  462. package/ts/src/booking-surface/error-codes.ts +241 -0
  463. package/ts/src/booking-surface/index.ts +9 -0
  464. package/ts/src/booking-surface/managed-dsh-cleanup-diagnostic.ts +151 -0
  465. package/ts/src/booking-surface/managed-dsh-run-port.ts +273 -0
  466. package/ts/src/booking-surface/profile.ts +42 -0
  467. package/ts/src/booking-surface/recovery-chain.ts +409 -0
  468. package/ts/src/booking-surface/runtime.ts +1793 -0
  469. package/ts/src/booking-surface/server.ts +733 -0
  470. package/ts/src/booking-surface/startup.ts +201 -0
  471. package/ts/src/booking-surface/validation.ts +217 -0
  472. package/ts/src/companions.ts +113 -0
  473. package/ts/src/contracts.ts +13 -3
  474. package/ts/src/dsh-llm.ts +44 -11
  475. package/ts/src/flyai-setup-tool.ts +77 -0
  476. package/ts/src/index.ts +2107 -224
  477. package/ts/src/itinerary-deck.ts +189 -0
  478. package/ts/src/itinerary-doc-shared.ts +741 -0
  479. package/ts/src/itinerary-html.ts +171 -0
  480. package/ts/src/loop.ts +278 -40
  481. package/ts/src/memory-capture.ts +283 -0
  482. package/ts/src/memory-decay.ts +55 -0
  483. package/ts/src/memory-utility.ts +70 -0
  484. package/ts/src/mock-llm.ts +4 -8
  485. package/ts/src/model.ts +88 -2
  486. package/ts/src/recall/card.ts +106 -0
  487. package/ts/src/recall/evaluator.ts +170 -0
  488. package/ts/src/recall/integration.ts +35 -0
  489. package/ts/src/recall/tick.ts +213 -0
  490. package/ts/src/session-link/plan-it-action.ts +78 -0
  491. package/ts/src/session-link/session-link.ts +275 -0
  492. package/ts/src/share/adapters.ts +93 -0
  493. package/ts/src/share/share-consent.ts +105 -0
  494. package/ts/src/share/share-deck.ts +85 -0
  495. package/ts/src/share/share-token.ts +166 -0
  496. package/ts/src/slot-spec.ts +172 -0
  497. package/ts/src/state-ledger.ts +912 -0
  498. package/ts/src/subagent-job-id-guard.ts +72 -0
  499. package/ts/src/time-anchor.ts +338 -0
  500. package/ts/src/tool-packet.ts +32 -0
  501. package/ts/src/travel-slots.ts +219 -0
  502. package/ts/src/travel-timeline.ts +83 -0
  503. package/ts/src/turn-deadline.ts +366 -0
  504. package/ts/src/turn-policy.ts +154 -0
  505. package/ts/src/unified.ts +360 -89
  506. package/ts/src/wish-pool.ts +79 -0
package/ts/src/index.ts CHANGED
@@ -7,39 +7,95 @@
7
7
  * - gotry_wish_pool_add 「下一次出发」清单(憧憬不被拒绝)
8
8
  *
9
9
  * 插件形态遵循 dsh 约定(name/inject/Config/apply + ctx.tools.register(defineTool(...))),
10
- * 对齐已发布 @deepseek-ai/dsh-tools@0.0.1-rc.1 的契约:
10
+ * 对齐 @deepseek-ai/dsh-tools@0.2.0-rc.2 的契约:
11
11
  * render 位于 output 对象内,参数属性是 ValueSchemaSpec(支持 type:'json')。
12
12
  *
13
13
  * @module @gotry/plugin
14
14
  */
15
15
 
16
- import { join } from 'node:path'
17
- import { readFile, writeFile } from 'node:fs/promises'
18
- import { readFileSync } from 'node:fs'
16
+ import { isAbsolute, join } from 'node:path'
17
+
19
18
  import type { Context } from '@deepseek-ai/cordis'
20
19
  import z from '@deepseek-ai/schemastery'
21
- import { defineTool } from '@deepseek-ai/dsh-tools'
22
- import { ensureStateDir, readJson, recordLatency, writeJson } from './bridge.ts'
20
+ import { defineTool, type ToolResult, type ToolRunContext } from '@deepseek-ai/dsh-tools'
21
+ import { ensureStateDir, recordLatency } from './bridge.ts'
23
22
  import { segmentsFromCandidate, solveChoiceSegment } from './unified.ts'
24
23
  import { checkConnectivity } from '../scripts/skeleton-check.ts'
25
24
  import { parseCandidate, parseRequest } from './model.ts'
26
- import { searchHotels as hbcliSearchHotels } from '../capabilities/hbcli.ts'
27
25
  import { installProcessGuards, guardToolExecute } from '../capabilities/incident-log.ts'
28
26
  import { interpretArgs, type GotryObservation } from './tool-packet.ts'
29
- import { appendEvent, projectUtility, type MemoryUtilityEvent } from './memory-utility.ts'
27
+ import { projectUtility } from './memory-utility.ts'
30
28
  import { pickNudgeWish, type WishPoolEntry } from './wish-pool.ts'
31
- import { mergeProfile } from './memory-capture.ts'
32
- import { buildTimeAnchor } from './time-anchor.ts'
33
- import { resolveSlotDate } from './slot-spec.ts'
34
- import { geocodePlace, getForecast, getClimate, wmoLabel } from '../capabilities/weather.ts'
35
- import { verifyFlight } from '../capabilities/opensky.ts'
36
- import { anythingSearch } from '../capabilities/anything.ts'
37
- import { readUrl, reach, reachStatus } from '../capabilities/agent-reach.ts'
38
- import { videoSubtitle, githubSearch } from '../capabilities/agent-reach-deep.ts'
29
+ import { resolveTimelineDate } from './travel-timeline.ts'
30
+ import { ensureLedger, readCompanionsWithFallback, readMotivationWithFallback, readTripsWithFallback, readWishPoolWithFallback } from './state-ledger.ts'
31
+ import { isValidHomeCityPreference, resolveDefaultOrigin, type MergedProfile, type ProfilePatch } from './memory-capture.ts'
32
+ import { applyPlanningWindow } from './loop.ts'
33
+ import { buildTimeAnchor, type PlanningWindow } from './time-anchor.ts'
34
+ import { evaluateHotelStayDates } from './hotel-date-gate.ts'
35
+ import { wmoLabel } from '../capabilities/weather.ts'
36
+ // D-23 收编(issue #115):anything/web/github/video/agent_reach/session_login 六渠道改经
37
+ // 效应注册表(退避/熔断/declined 面统一);能力层直接 import 仅留类型位(reach/reachStatus)
38
+ import { reach, reachStatus } from '../capabilities/agent-reach.ts'
39
+ import { runDoctorChecks, renderDoctorReportMd, runDoctorRepair, createRepairApprovalGate, type DoctorRepairOptions } from '../capabilities/doctor.ts'
40
+ import { EXTENSION_STORE_URL } from '../capabilities/session/extension-bridge.ts'
41
+ import { createConsentGate, approvalFromContext, resolveSessionSearchKind } from '../capabilities/session-consent.ts'
42
+ import { installModelOverride } from '../capabilities/model-override.ts'
43
+ import { listArtifacts, readArtifact } from '../capabilities/artifacts.ts'
44
+ import { generateItineraryArtifact } from '../capabilities/itinerary-artifact.ts'
45
+ import { generateItineraryDeckArtifact } from '../capabilities/itinerary-deck-artifact.ts'
46
+ import { generateItineraryDeckExport } from '../capabilities/itinerary-deck-export.ts'
47
+ import { interpretEffect, declinedObservation, type EffectInterpreter } from '../capabilities/effect.ts'
48
+ import { customerSendCode, customerLogin } from '../capabilities/hbcli.ts'
49
+ import { FLYAI_POI_CATEGORIES, type FlyaiKind, type FlyaiQuery, type FlyaiResult } from '../capabilities/flyai.ts'
50
+ import { createFlyaiSetupTool } from './flyai-setup-tool.ts'
51
+ import { appendFacts, loadFactRegistry } from '../capabilities/fact-log.ts'
52
+ import { factsFromFlyai, factsFromHotel, factsFromSession, factsFromSessionTrain } from './bookable-facts.ts'
53
+ import { hasRecognizedAvailableSeat } from '../capabilities/session/adapters/rail-12306.ts'
54
+ import { gateArtifact, type AirlineAirportMap } from './artifact-gate.ts'
55
+ import { installTurnDeadline, listTurnHandoffTickets } from './turn-deadline.ts'
56
+ import { noteChannelVerdict, recordChannelEvent, readLatestChannelEvents } from '../capabilities/channel-health.ts'
57
+ import { routingAdvice, renderRoutingCard, toolRoutingHeadline, persistedDownChannels, type ChannelIntent } from '../capabilities/channel-registry.ts'
58
+ import { registerBenchmarkEnvironmentBridge, type BenchmarkSubprocessService } from './benchmark-environment-bridge.ts'
59
+ import { installBenchmarkToolIsolation } from './benchmark-tool-isolation.ts'
60
+ import { installBenchmarkAgentConformance } from './benchmark-agent-conformance.ts'
61
+ import { installSubagentJobIdGuard } from './subagent-job-id-guard.ts'
62
+ import { registerLavishTools } from './lavish-tools.ts'
63
+ import {
64
+ createGroundTransferResolver,
65
+ createPublicMapDrivingRouteProvider,
66
+ exposeGroundTransferEvidence,
67
+ resolveGroundTransferPayload,
68
+ type GroundTransferProvider,
69
+ type GroundTransferResolution,
70
+ } from '../capabilities/ground-transfer.ts'
71
+
72
+ /** 航司→机场映射表(issue #46 冲突检测面;data/airline-airports.json,as_of 快照) */
73
+ let airlineAirportMapCache: AirlineAirportMap | null = null
74
+ async function loadAirlineAirportMap(): Promise<AirlineAirportMap | null> {
75
+ if (airlineAirportMapCache) return airlineAirportMapCache
76
+ try {
77
+ const { readFile } = await import('node:fs/promises')
78
+ airlineAirportMapCache = JSON.parse(
79
+ await readFile(join(import.meta.dirname, '..', '..', 'data', 'airline-airports.json'), 'utf-8'),
80
+ ) as AirlineAirportMap
81
+ return airlineAirportMapCache
82
+ } catch {
83
+ return null // 映射缺失不阻塞检索主路径;闸工具侧另行显式报错
84
+ }
85
+ }
39
86
 
40
87
  export const name = 'gotry-tools'
88
+ // The benchmark CLI projection adds a required subprocess loader dependency.
89
+ // Keep the plugin's ordinary mode independent of that opt-in-only service.
41
90
  export const inject = ['tools', 'systemPrompt']
42
91
 
92
+ function sessionCwd(exec: unknown): string | undefined {
93
+ const candidate = exec as { agent?: { session?: { header?: { cwd?: unknown } } } } | null
94
+ return typeof candidate?.agent?.session?.header?.cwd === 'string'
95
+ ? candidate.agent.session.header.cwd
96
+ : undefined
97
+ }
98
+
43
99
  export interface Config {
44
100
  /** 状态根目录(动机画像、wish pool、延迟日志) */
45
101
  stateRoot: string
@@ -47,24 +103,52 @@ export interface Config {
47
103
  timeoutMs: number
48
104
  /** hbcli 二进制路径(hotelbyte-cli;空=禁用实时酒店,回退数据包) */
49
105
  hbcliBin: string
106
+ /** 账号会话检索总闸(RFC 支柱④「用户明示授权+随时可关」):ask=gotry_session_search 每会话每站点首次调用弹审批卡、会话内记住(默认);allow=用户已在配置明示预授权(直接放行);off=总闸关闭,直接拒绝 */
107
+ sessionAccess: string
108
+ /** Owner-local benchmark environment bridge config; empty disables the bridge. */
109
+ benchmarkEnvironmentConfigPath?: string
110
+ /** Trusted absolute path of the installed `lavish-axi@0.1.67` package; empty disables the local Lavish Editor product tools. */
111
+ lavishAxiPackageRoot?: string
50
112
  }
51
113
 
52
114
  export const Config: z<Config> = z.object({
53
115
  stateRoot: z.string().default('.'),
54
116
  timeoutMs: z.number().default(30_000),
55
117
  hbcliBin: z.string().default('hbcli'),
118
+ sessionAccess: z.string().default('ask'),
119
+ benchmarkEnvironmentConfigPath: z.string().default(''),
120
+ lavishAxiPackageRoot: z.string().default(''),
56
121
  })
57
122
 
58
123
  interface FeasibilityResult {
59
124
  answer_md?: string
60
125
  recommended?: string | null
61
126
  verdicts?: Array<Record<string, unknown>>
127
+ ground_transfer?: GroundTransferResolution
128
+ }
129
+
130
+ interface FeasibilityValidationFailure extends Record<string, Json> {
131
+ ok: false
132
+ code: 'invalid_planning_context' | 'planning_window_rejected'
133
+ summary: string
134
+ rejected: Array<{ segmentId: string; optionId: string; date: string }>
62
135
  }
63
136
 
64
137
  interface MotivationProfileInput {
65
138
  weights?: Record<string, number>
66
139
  evidence?: string[]
67
140
  hard?: Record<string, unknown>
141
+ /**
142
+ * 持久化用户常驻城市/默认出发地(issue #338)。
143
+ * - string = 设置默认城市(用户原话指明常驻)
144
+ * - null = 显式清除(审计一行留痕,用于遗忘/迁居)
145
+ * - undefined = 字段未传,保持当前值不动
146
+ * 改值须伴新 evidence(同 weights/hard 的 P0 守卫);evidence 恰好一条且非空时
147
+ * 可省略 homeCityEvidence,多条 evidence 必须显式绑定。
148
+ */
149
+ homeCity?: string | null
150
+ /** homeCity 对应的本次用户原话;仅与 homeCity 一起传入。 */
151
+ homeCityEvidence?: string
68
152
  }
69
153
 
70
154
  interface WishPoolEntryInput {
@@ -81,30 +165,372 @@ interface WishPoolEntryInput {
81
165
  const unwrapQuery = interpretArgs
82
166
 
83
167
  /**
84
- * 动机画像 → persona 紧凑 brief(M4 T1 读回路径):空文件返回 ''(首访),
168
+ * 动机画像 → persona 紧凑 brief(M4 T1 读回路径):空画像返回 ''(首访),
85
169
  * persona 据此决定是否访谈。只读,不猜——画像里没有的字段不编。
170
+ * ADR-15:读经账本(未迁移 root 回退旧文件,只读)。
86
171
  */
87
172
  function renderMotivationBrief(stateRoot: string): string {
88
- try {
89
- const raw = readFileSync(join(stateRoot, 'gotry-state', 'motivation-profile.json'), 'utf-8')
90
- const p = JSON.parse(raw) as { weights?: Record<string, number>; evidence?: string[]; hard?: Record<string, unknown>; updated_at?: string }
91
- const lines: string[] = ['## 用户记忆(跨会话画像;与用户当轮说法冲突时以用户为准,更新经 gotry_motivation_save)']
92
- const weights = Object.entries(p.weights ?? {})
93
- if (weights.length) lines.push(`- 动机权重: ${weights.map(([k, v]) => `${k}=${v}`).join(', ')}(证据 ${p.evidence?.length ?? 0} 条)`)
94
- const hard = Object.entries(p.hard ?? {})
95
- if (hard.length) lines.push(`- 硬约束: ${hard.map(([k, v]) => `${k}=${String(v)}`).join(', ')}`)
96
- lines.push(`- 愿望池: 用 gotry_wish_pool_list 按条件召回(0..1),勿直接堆砌`)
97
- if (p.updated_at) lines.push(`- 更新于: ${p.updated_at}`)
98
- return weights.length || hard.length ? lines.join('\n') : ''
99
- } catch {
100
- return '' // 首访:无画像
173
+ const p = readMotivationWithFallback(stateRoot)
174
+ if (!p) return '' // 首访:无画像
175
+ const lines: string[] = ['## 用户记忆(跨会话画像;与用户当轮说法冲突时以用户为准,更新经 gotry_motivation_save)']
176
+ const weights = Object.entries(p.weights ?? {})
177
+ if (weights.length) lines.push(`- 动机权重: ${weights.map(([k, v]) => `${k}=${v}`).join(', ')}(证据 ${p.evidence?.length ?? 0} 条)`)
178
+ const hard = Object.entries(p.hard ?? {})
179
+ if (hard.length) lines.push(`- 硬约束: ${hard.map(([k, v]) => `${k}=${String(v)}`).join(', ')}`)
180
+ // 持久默认城市(issue #338):生产 brief 复用纯 resolver 的 precedence
181
+ // 契约;这里仍只负责读回渲染,不把 resolver 接入 feasibility/evaluate。
182
+ const profile = p as MergedProfile
183
+ const homeResolution = resolveDefaultOrigin(undefined, profile)
184
+ const homePref = profile.homeCityPreference
185
+ const typedPreferenceIsValid = isValidHomeCityPreference(profile)
186
+ const hasHomeCityData = Object.prototype.hasOwnProperty.call(profile, 'homeCity')
187
+ || Object.prototype.hasOwnProperty.call(profile, 'homeCityPreference')
188
+ if (homeResolution.source === 'home_default' && homeResolution.origin && typedPreferenceIsValid && homePref) {
189
+ const evidence = homeResolution.homeCityEvidence?.[0] ?? ''
190
+ lines.push(`- 常驻城市: ${homeResolution.origin}(原话证据:${evidence};记录于 ${homePref.updated_at})——本轮未指明出发地时作为软默认;本轮显式出发地优先;不进可行性硬约束,不删候选`)
191
+ } else if (typedPreferenceIsValid && homePref?.value === null) {
192
+ lines.push(`- 常驻城市: 已显式清除(原话证据:${homePref.evidence};记录于 ${homePref.updated_at})——已无持久软默认;每次行程必须由用户明确出发地,不猜测`)
193
+ } else if (hasHomeCityData) {
194
+ lines.push('- 常驻城市: 无可验证的持久默认——本轮请明确出发地;不从旧画像或全局 evidence 猜测')
195
+ }
196
+ // 旅行时间线(memory-design P1):去过的地方不再主动推荐,除非用户点名
197
+ const trips = readTimelineTrips(stateRoot)
198
+ if (trips.length) {
199
+ lines.push(`- 去过: ${trips.map(t => `${t.destination}(${t.start.slice(0, 7)})`).join('、')}——去过的地方不再主动推荐,除非用户点名`)
200
+ }
201
+ // 同行人档案(memory-design P2):约束只进排序与行程结构建议,永不硬过滤
202
+ const companions = readCompanions(stateRoot)
203
+ if (companions.length) {
204
+ lines.push(`- 同行人: ${companions.map(c => `${c.label}(${c.brief})`).join('、')}——约束进结构与排序建议,不硬过滤;引用时带当初的原话依据`)
205
+ }
206
+ lines.push(`- 愿望池: 用 gotry_wish_pool_list 按条件召回(0..1),勿直接堆砌`)
207
+ if (p.updated_at) lines.push(`- 更新于: ${p.updated_at}`)
208
+ return weights.length || hard.length || hasHomeCityData ? lines.join('\n') : ''
209
+ }
210
+
211
+ /**
212
+ * 时间线摘要(brief 用):最近 3 次行程(目的地+年月);账本优先,未迁移回退文件 */
213
+ /** 同行人摘要(brief 用):label + 约束串 */
214
+ function readCompanions(stateRoot: string): Array<{ label: string; brief: string }> {
215
+ return readCompanionsWithFallback(stateRoot)
216
+ .map(c => {
217
+ const bits = [c.constraints.mobility, ...(c.constraints.health ?? []), ...(c.constraints.prefs ?? [])].filter(Boolean)
218
+ return { label: c.label, brief: bits.join('/') }
219
+ })
220
+ }
221
+
222
+ function readTimelineTrips(stateRoot: string): Array<{ destination: string; start: string }> {
223
+ return readTripsWithFallback(stateRoot)
224
+ .map(t => ({ destination: t.destination, start: t.start }))
225
+ .sort((a, b) => (a.start < b.start ? 1 : -1))
226
+ .slice(0, 3)
227
+ }
228
+
229
+ const FLYAI_TOOL_KINDS = ['flight', 'train', 'hotel', 'poi', 'keyword', 'ai', 'marriott-hotel', 'marriott-package'] as const
230
+
231
+ function isFlyaiKind(value: unknown): value is FlyaiKind {
232
+ return typeof value === 'string' && (FLYAI_TOOL_KINDS as readonly string[]).includes(value)
233
+ }
234
+
235
+ type FlyaiToolArgs = Record<string, unknown>
236
+
237
+ function textArg(args: FlyaiToolArgs, ...names: string[]): string | undefined {
238
+ for (const name of names) {
239
+ const value = args[name]
240
+ if (value !== undefined) return typeof value === 'string' ? value : undefined
241
+ }
242
+ return undefined
243
+ }
244
+
245
+ function numberArg(args: FlyaiToolArgs, ...names: string[]): number | undefined {
246
+ for (const name of names) {
247
+ const value = args[name]
248
+ if (value !== undefined) return typeof value === 'number' ? value : undefined
249
+ }
250
+ return undefined
251
+ }
252
+
253
+ function putText(target: FlyaiQuery, key: keyof FlyaiQuery, args: FlyaiToolArgs, ...names: string[]): void {
254
+ const value = textArg(args, ...names)
255
+ if (value !== undefined) (target as unknown as Record<string, unknown>)[key] = value
256
+ }
257
+
258
+ function putNumber(target: FlyaiQuery, key: keyof FlyaiQuery, args: FlyaiToolArgs, ...names: string[]): void {
259
+ const value = numberArg(args, ...names)
260
+ if (value !== undefined) (target as unknown as Record<string, unknown>)[key] = value
261
+ }
262
+
263
+ function flyaiToolQuery(args: FlyaiToolArgs, signal?: AbortSignal): { query?: FlyaiQuery; error?: string } {
264
+ if (!isFlyaiKind(args.kind)) {
265
+ return { error: `kind 必须是 ${FLYAI_TOOL_KINDS.join('/')},未知值不会按 flight 处理` }
266
+ }
267
+ const kind = args.kind
268
+ const query: FlyaiQuery = { kind }
269
+ putText(query, 'origin', args, 'from', 'origin')
270
+ putText(query, 'destination', args, 'to', 'destination')
271
+ putText(query, 'depDate', args, 'date', 'depDate')
272
+ putText(query, 'depDateStart', args, 'dateStart', 'depDateStart')
273
+ putText(query, 'depDateEnd', args, 'dateEnd', 'depDateEnd')
274
+ putText(query, 'backDate', args, 'backDate')
275
+ putNumber(query, 'journeyType', args, 'journeyType')
276
+ putText(query, 'seatClassName', args, 'seatClassName')
277
+ putText(query, 'transportNo', args, 'transportNo')
278
+ putText(query, 'transferCity', args, 'transferCity')
279
+ putNumber(query, 'depHourStart', args, 'depHourStart')
280
+ putNumber(query, 'depHourEnd', args, 'depHourEnd')
281
+ putNumber(query, 'arrHourStart', args, 'arrHourStart')
282
+ putNumber(query, 'arrHourEnd', args, 'arrHourEnd')
283
+ putNumber(query, 'totalDurationHour', args, 'totalDurationHour')
284
+ putNumber(query, 'maxPrice', args, 'maxPrice')
285
+ putText(query, 'sortType', args, 'sortType')
286
+
287
+ putText(query, 'destName', args, 'destName', 'to')
288
+ putText(query, 'checkInDate', args, 'checkIn', 'checkInDate')
289
+ putText(query, 'checkOutDate', args, 'checkOut', 'checkOutDate')
290
+ putText(query, 'keyWords', args, 'keyWords')
291
+ putText(query, 'poiName', args, 'poiName')
292
+ putText(query, 'hotelTypes', args, 'hotelTypes')
293
+ putText(query, 'sort', args, 'sort')
294
+ putText(query, 'hotelStars', args, 'hotelStars')
295
+ putText(query, 'hotelBedTypes', args, 'hotelBedTypes')
296
+ putText(query, 'cityName', args, 'cityName', 'to')
297
+ putNumber(query, 'poiLevel', args, 'poiLevel')
298
+ putText(query, 'keyword', args, 'keyword')
299
+ putText(query, 'category', args, 'category')
300
+ putText(query, 'query', args, 'query')
301
+ putText(query, 'hotelBrands', args, 'hotelBrands')
302
+ putText(query, 'hotelName', args, 'hotelName')
303
+ putText(query, 'provinceOrCity', args, 'provinceOrCity')
304
+ putNumber(query, 'timeoutMs', args, 'timeoutMs')
305
+ if (signal) query.signal = signal
306
+
307
+ const isCalendarDate = (value: string): boolean => {
308
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
309
+ const date = new Date(`${value}T00:00:00.000Z`)
310
+ const [year, month, day] = value.split('-').map(Number)
311
+ return Number.isFinite(date.valueOf())
312
+ && date.getUTCFullYear() === year
313
+ && date.getUTCMonth() + 1 === month
314
+ && date.getUTCDate() === day
315
+ }
316
+ const dateError = (label: string, value: string): string | undefined =>
317
+ isCalendarDate(value) ? undefined : `${label} 必须是有效的 YYYY-MM-DD 日历日期`
318
+
319
+ if (kind === 'flight' || kind === 'train') {
320
+ // Official 1.0.16 requires only --origin; omitting destination/date is a
321
+ // supported exploration query and must reach the upstream command.
322
+ if (!query.origin?.trim()) return { error: `kind=${kind} 需要 from/origin(中文城市名或机场)` }
323
+ const hasExact = Boolean(query.depDate)
324
+ const hasStart = Boolean(query.depDateStart)
325
+ const hasEnd = Boolean(query.depDateEnd)
326
+ if (hasStart !== hasEnd) return { error: 'dateStart/depDateStart 与 dateEnd/depDateEnd 必须成对' }
327
+ if (hasExact && (hasStart || hasEnd)) return { error: 'date 与日期范围不能同时传入,请选择 exact-date 或 range 查询' }
328
+ for (const [label, value] of [
329
+ ['date', query.depDate],
330
+ ['dateStart', query.depDateStart],
331
+ ['dateEnd', query.depDateEnd],
332
+ ['backDate', query.backDate],
333
+ ] as const) {
334
+ if (value) {
335
+ const error = dateError(label, value)
336
+ if (error) return { error }
337
+ }
338
+ }
339
+ if (query.depDateStart && query.depDateEnd && query.depDateStart > query.depDateEnd) {
340
+ return { error: 'dateStart 不能晚于 dateEnd' }
341
+ }
342
+ if (query.depDate && query.backDate && query.backDate < query.depDate) {
343
+ return { error: 'backDate 不能早于 date' }
344
+ }
345
+ if (query.sortType && !/^[1-8]$/.test(query.sortType.trim())) {
346
+ return { error: 'flight/train 的 sortType 只接受 1–8' }
347
+ }
348
+ }
349
+ if (kind === 'hotel' || kind === 'marriott-hotel') {
350
+ if (!query.destName?.trim()) return { error: `kind=${kind} 需要 to/destName(目的地)` }
351
+ const hasIn = Boolean(query.checkInDate)
352
+ const hasOut = Boolean(query.checkOutDate)
353
+ if (hasIn !== hasOut) return { error: 'checkIn/checkOut 必须成对' }
354
+ for (const [label, value] of [['checkIn', query.checkInDate], ['checkOut', query.checkOutDate]] as const) {
355
+ if (value) {
356
+ const error = dateError(label, value)
357
+ if (error) return { error }
358
+ }
359
+ }
360
+ if (query.checkInDate && query.checkOutDate && query.checkOutDate <= query.checkInDate) {
361
+ return { error: 'checkOut 必须晚于 checkIn' }
362
+ }
363
+ if (kind === 'marriott-hotel') {
364
+ // The official Marriott command has one keyword field covering hotel
365
+ // name/brand; it does not accept generic hotel-types/hotel-stars or
366
+ // the non-existent hotel-brands/hotel-name flags.
367
+ if (query.hotelTypes?.trim() || query.hotelStars?.trim()) {
368
+ return { error: 'marriott-hotel 不支持 hotelTypes/hotelStars;请使用 hotelBrands/hotelName' }
369
+ }
370
+ const marriottKeywords = [query.keyWords, query.hotelBrands, query.hotelName]
371
+ .map(value => value?.trim())
372
+ .filter((value): value is string => Boolean(value))
373
+ query.keyWords = marriottKeywords.length ? marriottKeywords.join(' ') : undefined
374
+ delete query.hotelBrands
375
+ delete query.hotelName
376
+ }
377
+ }
378
+ if (kind === 'poi' && !query.cityName?.trim()) return { error: 'kind=poi 需要 cityName(景点所在城市)' }
379
+ if ((kind === 'keyword' || kind === 'ai') && !query.query?.trim()) return { error: `kind=${kind} 需要 query` }
380
+ if (kind === 'marriott-package' && ![query.keyword, query.hotelName, query.provinceOrCity].some(value => value?.trim())) return { error: 'kind=marriott-package 需要 keyword/hotelName/provinceOrCity 至少一项' }
381
+ return { query }
382
+ }
383
+
384
+ function flyaiToolSummary(query: FlyaiQuery, result: FlyaiResult): string {
385
+ const label = query.kind === 'flight' ? '机票' : query.kind === 'train' ? '火车票' : query.kind === 'hotel' || query.kind === 'marriott-hotel' ? '酒店' : query.kind
386
+ if (result.verdict === 'miss') return `${label}查询完成,官方通道返回 0 条。${result.evidence}`
387
+ if (result.verdict !== 'hit') return `${label}查询未完成:${result.error ?? result.verdict}。${result.setup ? `\n${result.setup}` : ''}\n${result.evidence}`
388
+ const price = (raw: string | undefined, numeric: number | undefined): string => raw?.trim() || (numeric !== undefined && numeric > 0 ? `¥${numeric}` : '价格待询')
389
+ const lines: string[] = []
390
+ if (query.kind === 'flight' || query.kind === 'train') {
391
+ for (const option of (result.options ?? []).slice(0, 8)) {
392
+ const route = option.nonstop === false ? '中转' : option.nonstop === true ? '直达' : '路线待确认'
393
+ const services = option.segments?.map(segment => segment.no).join('→') || option.no
394
+ lines.push(`${route} ${services} ${option.name} ${option.depDateTime.slice(0, 16)}→${option.arrDateTime.slice(0, 16)} ${price(option.priceRaw, option.price)}${option.jumpUrl ? ` · ${option.jumpUrl}` : ''}`)
395
+ }
396
+ } else if (query.kind === 'hotel' || query.kind === 'marriott-hotel') {
397
+ for (const option of (result.hotels ?? []).slice(0, 8)) {
398
+ lines.push(`${option.name} ${price(option.priceRaw, option.price)}${option.score ? ` · ${option.score}` : ''}${option.jumpUrl ? ` · ${option.jumpUrl}` : ''}`)
399
+ }
400
+ } else if (query.kind === 'poi') {
401
+ for (const option of (result.pois ?? []).slice(0, 8)) lines.push(`${option.name}${option.address ? ` · ${option.address}` : ''}${option.jumpUrl ? ` · ${option.jumpUrl}` : ''}`)
402
+ } else if (query.kind === 'keyword') {
403
+ for (const option of (result.keywords ?? []).slice(0, 8)) lines.push(`${option.title}${option.price ? ` · ${option.price}` : ''}${option.jumpUrl ? ` · ${option.jumpUrl}` : ''}`)
404
+ } else if (query.kind === 'marriott-package') {
405
+ for (const option of (result.packages ?? []).slice(0, 8)) lines.push(`${option.name}${option.price ? ` · ${option.price}` : ''}${option.detailUrl ? ` · ${option.detailUrl}` : ''}`)
406
+ } else if (query.kind === 'ai') {
407
+ lines.push(`上游 ai-search data 已原样保留(${JSON.stringify(result.aiData).slice(0, 500)})`)
101
408
  }
409
+ return `${label}官方只读查询命中 ${lines.length} 条:\n${lines.join('\n')}\n${result.evidence}`
410
+ }
411
+
412
+ function flyaiRoutingIntent(kind: FlyaiKind): ChannelIntent | undefined {
413
+ if (kind === 'flight') return 'search-flight'
414
+ if (kind === 'train') return 'search-train'
415
+ if (kind === 'hotel' || kind === 'marriott-hotel') return 'search-hotel'
416
+ return undefined
102
417
  }
103
418
 
104
419
  type Json = string | number | boolean | null | Json[] | { [k: string]: Json }
105
420
  type JsonObject = { [k: string]: Json }
106
421
 
107
- export function apply(ctx: Context, config: Config): void {
422
+ /** Benchmark 治理面钉死预算(Round 9,#100/#102):官方任务形态(如 ChinaTravel
423
+ * 单查询 300s)超出内置 60/120s;预算仍必须「按 run 钉死」保证可复现——允许
424
+ * owner 经 env 按次显式设定,缺省维持既有值,非法值启动即抛。 */
425
+ function benchmarkPinnedPolicy(): { softMs: number; hardMs: number; exit: 'converge' } {
426
+ const parse = (name: string, fallback: number): number => {
427
+ const raw = process.env[name]
428
+ if (raw === undefined || raw === '') return fallback
429
+ const value = Number.parseInt(raw, 10)
430
+ if (!Number.isSafeInteger(value) || value <= 0) {
431
+ throw new Error(`invalid ${name}: ${JSON.stringify(raw)} (expected a positive safe integer)`)
432
+ }
433
+ return value
434
+ }
435
+ const softMs = parse('GOTRY_BENCHMARK_SOFT_MS', 60_000)
436
+ const hardMs = parse('GOTRY_BENCHMARK_HARD_MS', 120_000)
437
+ if (hardMs <= softMs) throw new Error(`GOTRY_BENCHMARK_HARD_MS (${hardMs}) must exceed GOTRY_BENCHMARK_SOFT_MS (${softMs})`)
438
+ return { softMs, hardMs, exit: 'converge' }
439
+ }
440
+
441
+ /** 把 hotel-date-gate.message 里的模型转手措辞(请告诉用户 / 请告诉 gotry /
442
+ * 请向用户确认)归一为直接对用户措辞(请补充 / 请提供)。仅做这一类短语的字面
443
+ * 替换,日期示例等可行动细节保留不动;只服务 hotel_search input_required 卡
444
+ * 单点,不动 date-gate 契约、不动其它 presentResult 路径。 */
445
+ function normalizeHotelGateHandoff(message: unknown): string {
446
+ const raw = String(message ?? '')
447
+ if (!raw) return ''
448
+ return raw
449
+ .replace(/请告诉\s*(?:用户|gotry)\s*/g, '请补充 ')
450
+ .replace(/请向用户确认/g, '请提供')
451
+ }
452
+
453
+ export interface ApplyTestSeams {
454
+ doctor?: {
455
+ check?: typeof runDoctorChecks
456
+ repair?: DoctorRepairOptions
457
+ }
458
+ /** Isolated test-only effect interpreter; production keeps interpretEffect. */
459
+ effect?: typeof interpretEffect
460
+ /** Test-only clock injection; production derives the reference date from Date. */
461
+ clock?: () => Date
462
+ /** Isolated public map-tool result seam; production uses nested dsh dispatch. */
463
+ groundTransfer?: { provider?: GroundTransferProvider }
464
+ }
465
+
466
+ function parseFeasibilityPlanning(raw: unknown, anchor: ReturnType<typeof buildTimeAnchor>): PlanningWindow | null {
467
+ if (raw === undefined) return null
468
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('planning must be an object')
469
+ const planning = raw as Record<string, unknown>
470
+ const intent = planning['intent']
471
+ const requestedYear = planning['requested_year']
472
+ if (intent !== 'future' && intent !== 'historical') {
473
+ throw new Error('planning.intent must be future or historical')
474
+ }
475
+ if (!Number.isInteger(requestedYear) || Number(requestedYear) < 1_000 || Number(requestedYear) > 9_999) {
476
+ throw new Error('planning.requested_year must be a four-digit integer')
477
+ }
478
+ // referenceDate is always the host clock; the payload cannot supply a stale now.
479
+ return { intent, requestedYear: Number(requestedYear), referenceDate: anchor.today }
480
+ }
481
+
482
+ function feasibilityValidationFailure(
483
+ code: FeasibilityValidationFailure['code'],
484
+ summary: string,
485
+ rejected?: FeasibilityValidationFailure['rejected'],
486
+ ): FeasibilityValidationFailure {
487
+ return { ok: false, code, summary, rejected: rejected ?? [] }
488
+ }
489
+
490
+ export function apply(ctx: Context, config: Config, seams: ApplyTestSeams = {}): void {
491
+ const clock = seams.clock ?? (() => new Date())
492
+ const runFlyaiEffect = (seams.effect ?? interpretEffect) as unknown as (fx: {
493
+ effect: 'FLYAI_SEARCH'
494
+ params: FlyaiQuery
495
+ signal?: AbortSignal
496
+ }) => Promise<{ result: FlyaiResult | null; trace: Parameters<typeof declinedObservation>[1] }>
497
+ const groundTransferResolver = createGroundTransferResolver({
498
+ provider: seams.groundTransfer?.provider ?? createPublicMapDrivingRouteProvider(ctx),
499
+ clock,
500
+ })
501
+ const rawBenchmarkEnvironmentConfigPath = config.benchmarkEnvironmentConfigPath ?? ''
502
+ // ADR-24 v2:产品路径装「路由 + wall-clock 双出口」——用户主观时间是唯一
503
+ // 预算,复杂度决定出口结构(converge/handoff)。benchmark opt-in 钉死
504
+ // 固定 policy 保证评测可复现,不走路由。GOTRY_HANDOFF_CHILD=1 是收集器
505
+ // 派生的后台规划会话:唯一出口 converge + 长 leash——前台转后台,后台
506
+ // 必须产出最终交付物,不得再次 handoff(否则无限递归)。
507
+ const handoffChild = process.env.GOTRY_HANDOFF_CHILD === '1'
508
+ installTurnDeadline(ctx, handoffChild
509
+ ? { fixedPolicy: { softMs: 300_000, hardMs: 900_000, exit: 'converge' } }
510
+ : rawBenchmarkEnvironmentConfigPath.trim()
511
+ ? { fixedPolicy: benchmarkPinnedPolicy() }
512
+ : { stateRoot: process.env.GOTRY_TURN_HANDOFF_ROOT ?? config.stateRoot ?? '.' })
513
+ if (rawBenchmarkEnvironmentConfigPath.trim()) {
514
+ // Benchmark mode is a deliberately minimal kernel: only the model
515
+ // override and the environment bridge are installed besides the pinned
516
+ // turn-deadline policy above. In particular, product prompt variables,
517
+ // process/consent guards, and guarded product tools must not be
518
+ // observable on this path.
519
+ installModelOverride(ctx as unknown as Parameters<typeof installModelOverride>[0])
520
+ const getService = (ctx as unknown as { get?: (name: string, fallback?: unknown) => unknown }).get
521
+ const directSubprocess = (typeof getService === 'function'
522
+ ? getService.call(ctx, 'subprocess')
523
+ : undefined) as BenchmarkSubprocessService | undefined
524
+ const projection = registerBenchmarkEnvironmentBridge(
525
+ rawBenchmarkEnvironmentConfigPath,
526
+ tool => ctx.tools.register(tool),
527
+ directSubprocess,
528
+ )
529
+ installBenchmarkToolIsolation(ctx)
530
+ installBenchmarkAgentConformance(ctx, projection)
531
+ return
532
+ }
533
+
108
534
  // 时间感知:注册动态变量,persona 里用 {{current_date}} 引用。
109
535
  // 每次 assemble 时取系统时钟——LLM 始终知道「今天是几号」。
110
536
  const sp = (ctx as unknown as Record<string, unknown>)['systemPrompt'] as {
@@ -125,12 +551,79 @@ export function apply(ctx: Context, config: Config): void {
125
551
  // 渲染成紧凑 brief 注入 persona;为空 = 首访。与当轮说法冲突时以用户为准。
126
552
  sp?.variable?.('motivation_brief', () => renderMotivationBrief(config.stateRoot ?? '.'))
127
553
 
554
+ // 通道路由卡(通道注册表生成,docs/design/tool-orchestration-design.md §2.1/D-8):
555
+ // persona 检索条款只留行为契约,机/火/酒通道顺位与额度口径查卡——prose 教义
556
+ // 变查表教义,注册表加通道卡片自动一致。
557
+ sp?.variable?.('channel_routing_card', () => renderRoutingCard())
558
+
559
+ // 通道健康面接线(issue #107/#108):检索通道 verdict → 会话状态标记 +
560
+ // down/cooldown 事件落持久面(doctor CLI 进程消费)。落盘失败不阻塞检索。
561
+ const noteChannel = async (channel: string, verdict: string): Promise<void> => {
562
+ const ev = noteChannelVerdict(channel, verdict)
563
+ if (ev) await recordChannelEvent(config.stateRoot ?? '.', ev)
564
+ }
565
+ /**
566
+ * verdict≠hit 时在平铺 envelope 上追加 routing 建议(§3.3:失败现场教学)。
567
+ * 健康态两源并集(issue #436):进程内会话态 + 本 stateRoot 持久健康面
568
+ * (channel-probe / 外部本地生产者 append 的 channel-health.jsonl)。持久面在
569
+ * **工具结果边界**读入并投影为 down 集合(IO 只在此层,注册表保持纯函数);
570
+ * 读不到/坏行/未来时间戳=不排除——坏输入不能凭空压制通道,与会话态失联同纪律。
571
+ * 持久面只会加排除项:它写的 'ok' 恢复事件不能解除本会话刚发生的失败。
572
+ */
573
+ const routingField = async (intent: ChannelIntent, excludeChannel: string) => {
574
+ let persistedDown: ReadonlySet<string> | undefined
575
+ try {
576
+ // 同一个捕获时钟贯穿读者与投影:坏时间戳行在 latest-wins 覆盖前就被读者丢弃,
577
+ // 否则一条未来/缺时间戳的新行会顶掉更早的有效 down,把通道错误判回可用。
578
+ const now = Date.now()
579
+ persistedDown = persistedDownChannels(
580
+ await readLatestChannelEvents(config.stateRoot ?? '.', { now, requireValidTimestamp: true }),
581
+ now,
582
+ )
583
+ } catch { /* 健康面缺席=不启用持久排除,建议表退回会话态口径 */ }
584
+ return { routing: routingAdvice(intent, { excludeChannel, ...(persistedDown ? { persistedDownChannels: persistedDown } : {}) }) }
585
+ }
586
+
128
587
  // D-NEW 进程护栏(Z3 WASM crash 教训):dsh 0.1.1-rc.1 缺 uncaughtException
129
588
  // handler,插件异常穿透即杀进程。我们在 gotry 侧挂护栏:同步 fsync 写事故证据
130
589
  // (gotry-state/incidents.jsonl),handler 自身不再抛,不阻塞后续控制流。
131
590
  // 不调 process.exit——让 dsh/上级容器决定生死,我们只留现场。
132
591
  installProcessGuards(config.stateRoot ?? '.', { uncaughtException: 'gotry-tools', unhandledRejection: 'gotry-tools' })
133
592
 
593
+ // 账号会话授权闸(RFC 支柱④「用户明示授权 + 站点白名单 + 随时可关」进代码;v2 每会话一次):
594
+ // 会话面工具动用用户本人登录态,**每会话每站点首次调用**弹 dsh 原生审批卡——
595
+ // allowed-once 记入会话 granted 集,后续同站调用免弹;用户拒绝 = 本会话吊销
596
+ // (denied 集,不再弹卡也不再执行——拒绝是裁决,不反复骚扰);无审批通道
597
+ // (headless 无用户在场)一律 fail-closed 拒绝。sessionAccess: ask(默认)|allow|off。
598
+ // v1 教训(2026-08-29 founder 实测「每次都要弹,经常无法点击」):逐调用弹卡 = 骚扰,
599
+ // 会话态收归 capabilities/session-consent.ts。防御:极简宿主/mock ctx 无事件总线时跳过。
600
+ // issue #194 A-轨道 guard 先注册;生产 Cordis 的 prepend 保证它在授权闸
601
+ // 前运行,smoke 的轻量事件采集器也继续把授权闸作为最后一个观察项。
602
+ installSubagentJobIdGuard(ctx)
603
+ const ctxOn = (ctx as unknown as { on?: unknown }).on
604
+ if (typeof ctxOn === 'function') {
605
+ const gate = createConsentGate({
606
+ access: () => config.sessionAccess ?? 'ask',
607
+ approval: approvalFromContext(ctx),
608
+ })
609
+ // site 绑定(#308):dsh pre-execute 实际派发的 arguments 原样进入 gate;
610
+ // gate 与 execute 共用 resolveSessionSearchKind/interpretArgs,因此 wrapped
611
+ // query.*、缺省 flight、unknown/malformed 的选择与授权和效应路径保持一致。
612
+ ctx.on('tools/pre-execute', gate)
613
+ }
614
+
615
+ // issue #284 修复闸:gotry_doctor.action='repair' 走同一审批缝(scope-keyed,
616
+ // WeakMap<agent>)——同 agent + 同 scope 复用批准,不同 scope 重问,rejected/cancelled
617
+ // = 本会话吊销,unavailable 通道不记。同口径 session-consent,不增新持久面。
618
+ // 注册早于 gotry_doctor(下方),保证工具面闭包捕获当前会话的闸实例。
619
+ const repairApprovalGate = createRepairApprovalGate({
620
+ approval: approvalFromContext(ctx),
621
+ })
622
+
623
+ // LLM_MODEL → dsh 会话面模型覆盖(issue #77;机制与分层见
624
+ // capabilities/model-override.ts 头注)。GOTRY_LLM_MODEL 未设时零行为变化。
625
+ installModelOverride(ctx as unknown as Parameters<typeof installModelOverride>[0])
626
+
134
627
  // D-NEW 收尾:全部工具 execute 统一异常隔离——单个工具抛错/拒绝不再沿 cordis
135
628
  // 传到 dsh 主循环,降级为结构化错误返回给 LLM + incident 落盘(incident-log.ts)。
136
629
  const registerGuarded = (tool: ReturnType<typeof defineTool>): void => {
@@ -141,6 +634,22 @@ export function apply(ctx: Context, config: Config): void {
141
634
  ctx.tools.register(t as unknown as ReturnType<typeof defineTool>)
142
635
  }
143
636
 
637
+ // Issue #443: register the five local editor tools only from trusted host
638
+ // configuration. Tool arguments cannot select process or filesystem authority.
639
+ registerLavishTools({
640
+ ctx,
641
+ register: registerGuarded,
642
+ getConfig: () => ({ lavishAxiPackageRoot: config.lavishAxiPackageRoot ?? '' }),
643
+ })
644
+
645
+ // 工具描述首行生成(issue #113,L1):检索工具描述统一前置注册表生成的
646
+ // 「服务意图 × 通道顺位」卡——模型选工具时(读描述)与失败后(读 routing)
647
+ // 两个决策点拿到同一张表;注册表加行,描述自动一致。非检索工具原样返回。
648
+ const routed = (tool: string, desc: string): string => {
649
+ const head = toolRoutingHeadline(tool)
650
+ return head ? `${head}\n${desc}` : desc
651
+ }
652
+
144
653
  registerGuarded(defineTool({
145
654
  name: 'gotry_feasibility_check',
146
655
  description:
@@ -151,11 +660,100 @@ export function apply(ctx: Context, config: Config): void {
151
660
  + 'structure { request: { motivation weights, hard constraints, window, budget, home hubs }, candidates: [ { id, label, services, transfers, stay, minDays } ] }. '
152
661
  + 'Returns per-candidate verdicts, unsat cores with minimal-modification suggestions, '
153
662
  + 'a wish-pool entry for infeasible aspirations, and a ready-to-show markdown answer.',
663
+ // D-30 第五刀(issue #112):payload json blob → 结构化对象(request/candidates 模型可见,
664
+ // 嵌套形状权威在 unified 引擎契约,工具面不越层强约束)
154
665
  parameters: {
155
666
  payload: {
156
- type: 'json',
667
+ type: 'object',
668
+ additionalProperties: false,
157
669
  required: true,
158
- description: 'The full engine payload: { request, candidates }.',
670
+ properties: {
671
+ request: { type: 'object', additionalProperties: true, required: true, description: '引擎请求:{ motivation weights, hard constraints, window, budget, home hubs }' },
672
+ candidates: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true, description: '候选列表:[{ id, label, date?, services, transfers, stay, minDays }]' },
673
+ planning: {
674
+ type: 'object', additionalProperties: false,
675
+ description: '可选显式规划上下文;dated 候选省略时默认按宿主时钟作 future 下界过滤,指定 future 年份再加年末上界,historical 仅用于明确历史/回测查询;完全 dateless 输入保持旧可行性计算',
676
+ properties: {
677
+ intent: { type: 'string', enum: ['future', 'historical'], required: true },
678
+ requested_year: { type: 'integer', required: true, description: '用户明确请求的四位年份,不传宿主当前年份' },
679
+ },
680
+ },
681
+ ground_transfer: {
682
+ type: 'object',
683
+ additionalProperties: false,
684
+ description: '可选显式地面接驳覆盖:仅 destination 位置、显式经纬度和 mode=driving;路线同时绑定抵达方向(A→B)与返程方向(B→A),两方向分别请求/缓存/降级,价格仍来自静态包;缓存 TTL 由能力层固定',
685
+ properties: {
686
+ candidate_id: { type: 'string', description: '要绑定的候选 id;不会按相似度推断' },
687
+ transfer_index: { type: 'integer', description: 'dest_transfers 的零基位置;不会按 mode 推断' },
688
+ position: { type: 'string', description: '当前切片固定为 destination' },
689
+ mode: { type: 'string', description: '当前只接受 driving;其它/缺省模式显式回退静态分钟' },
690
+ origin: {
691
+ type: 'object',
692
+ additionalProperties: false,
693
+ description: '旧版单对坐标:等同于 outbound.origin(能力层自动把返程方向设为其互换)',
694
+ properties: {
695
+ longitude: { type: 'number' },
696
+ latitude: { type: 'number' },
697
+ },
698
+ },
699
+ destination: {
700
+ type: 'object',
701
+ additionalProperties: false,
702
+ description: '旧版单对坐标:等同于 outbound.destination',
703
+ properties: {
704
+ longitude: { type: 'number' },
705
+ latitude: { type: 'number' },
706
+ },
707
+ },
708
+ outbound: {
709
+ type: 'object',
710
+ additionalProperties: false,
711
+ description: '显式抵达方向坐标对(A→B):不指定时回退 origin/destination',
712
+ properties: {
713
+ origin: {
714
+ type: 'object',
715
+ additionalProperties: false,
716
+ properties: {
717
+ longitude: { type: 'number' },
718
+ latitude: { type: 'number' },
719
+ },
720
+ },
721
+ destination: {
722
+ type: 'object',
723
+ additionalProperties: false,
724
+ properties: {
725
+ longitude: { type: 'number' },
726
+ latitude: { type: 'number' },
727
+ },
728
+ },
729
+ },
730
+ },
731
+ return: {
732
+ type: 'object',
733
+ additionalProperties: false,
734
+ description: '显式返程方向坐标对(B→A):不指定时回退 outbound 互换',
735
+ properties: {
736
+ origin: {
737
+ type: 'object',
738
+ additionalProperties: false,
739
+ properties: {
740
+ longitude: { type: 'number' },
741
+ latitude: { type: 'number' },
742
+ },
743
+ },
744
+ destination: {
745
+ type: 'object',
746
+ additionalProperties: false,
747
+ properties: {
748
+ longitude: { type: 'number' },
749
+ latitude: { type: 'number' },
750
+ },
751
+ },
752
+ },
753
+ },
754
+ },
755
+ },
756
+ },
159
757
  },
160
758
  },
161
759
  output: {
@@ -170,10 +768,38 @@ export function apply(ctx: Context, config: Config): void {
170
768
  // 路径——候选形态枚举求解,~6ms/次)。unified 内部有 try-catch 护栏覆盖 wasm 异常。
171
769
  const started = Date.now()
172
770
  const payload = args.payload as Record<string, unknown>
771
+ const anchor = buildTimeAnchor(clock())
772
+ let planning: PlanningWindow | null
773
+ try {
774
+ planning = parseFeasibilityPlanning(payload['planning'], anchor)
775
+ } catch (error) {
776
+ const summary = error instanceof Error ? error.message : 'planning context is invalid'
777
+ return feasibilityValidationFailure('invalid_planning_context', summary)
778
+ }
173
779
  const req = parseRequest(payload['request'] as Record<string, unknown>)
174
780
  const cands = (payload['candidates'] as Record<string, unknown>[]).map(parseCandidate)
175
- const spec = segmentsFromCandidate(req, cands)
176
- const result = solveChoiceSegment(spec, req) as Record<string, unknown>
781
+ const execution = _exec && typeof _exec === 'object' ? _exec as ToolRunContext : undefined
782
+ let solverCandidates = cands
783
+ let groundTransferEvidence: GroundTransferResolution | undefined
784
+ if (payload['ground_transfer'] !== undefined) {
785
+ const prepared = await resolveGroundTransferPayload(
786
+ payload['ground_transfer'],
787
+ cands,
788
+ groundTransferResolver,
789
+ { signal: execution?.signal, execution },
790
+ )
791
+ solverCandidates = prepared.candidates
792
+ groundTransferEvidence = prepared.resolution
793
+ }
794
+ const spec = segmentsFromCandidate(req, solverCandidates)
795
+ const planningCheck = applyPlanningWindow(spec, planning, anchor, { defaultDatedFuture: true })
796
+ if (planningCheck.error) {
797
+ return feasibilityValidationFailure('planning_window_rejected', planningCheck.error, planningCheck.rejected)
798
+ }
799
+ const solved = solveChoiceSegment(planningCheck.spec, req) as Record<string, unknown>
800
+ const result = groundTransferEvidence
801
+ ? exposeGroundTransferEvidence(solved, groundTransferEvidence)
802
+ : solved
177
803
  const dir = await ensureStateDir(config.stateRoot)
178
804
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, 'feasibility_check:in-process-unified').catch(() => {})
179
805
  return { ok: true, ...result, latency_ms: Date.now() - started, via: 'in-process-unified' }
@@ -208,11 +834,32 @@ export function apply(ctx: Context, config: Config): void {
208
834
  + 'never the principal/sponsor distinction. MERGE semantics (T1): call again with just the NEW '
209
835
  + 'facts learned this turn (weights delta optional but MUST bring fresh evidence; evidence = user quotes); '
210
836
  + 'existing history is never deleted. Requires evidence on every call (P0 anti-fabrication rule).',
837
+ // D-30 第五刀(issue #112):profile blob → 结构化闭合对象;evidence(P0 反伪造红线)进嵌套
838
+ // schema 由宿主权闸——无证据的保存请求入口即被结构化拒绝(ToolFailure 形状)
839
+ // issue #338:homeCity 字段(string=设置,null=显式清除,undefined=不动);单条非空
840
+ // evidence 可省略 binding,多条 evidence 必须显式 homeCityEvidence。
841
+ // dsh 参数 schema 仅支持单值 type,string|null 用 oneOf 表达。
211
842
  parameters: {
212
843
  profile: {
213
- type: 'json',
844
+ type: 'object',
845
+ additionalProperties: false,
214
846
  required: true,
215
- description: '{ weights: {escape_rest: 0.7, ...}, evidence: [user quotes...], hard: {wake_not_before, min_arrival_energy_pct} }',
847
+ properties: {
848
+ weights: { type: 'object', additionalProperties: true, description: '动机权重增量,如 { escape_rest: 0.7 }(可选,权重变更须伴新证据)' },
849
+ evidence: { type: 'array', items: { type: 'string' }, required: true, description: '本轮新事实的用户原话数组(P0:必带)' },
850
+ hard: { type: 'object', additionalProperties: true, description: '硬约束:{ wake_not_before, min_arrival_energy_pct }(可选)' },
851
+ homeCity: {
852
+ oneOf: [
853
+ { type: 'string', description: '设置持久常驻城市/默认出发地(用户原话指明常驻),如 "上海"' },
854
+ { type: 'null', description: '显式清除常驻城市(用于遗忘/迁居)' },
855
+ ],
856
+ description: '持久常驻城市/默认出发地(string=设置,null=显式清除);改值须伴新 evidence(P0);恰一条非空可省略 binding,多条须显式;不删候选/不压当轮 origin',
857
+ },
858
+ homeCityEvidence: {
859
+ type: 'string',
860
+ description: 'homeCity 对应的 exact 用户原话;显式传入时必须逐字出现在本次 profile.evidence 中且为新证据(同值同绑定重复调用例外为幂等);evidence 恰好一条非空时可省略并绑定该条,多条时必须显式传入',
861
+ },
862
+ },
216
863
  },
217
864
  },
218
865
  output: {
@@ -220,29 +867,52 @@ export function apply(ctx: Context, config: Config): void {
220
867
  schema: { type: 'json' },
221
868
  render: (_args, value) => [{ type: 'text', text: `动机画像已保存:${String((value as { path?: string }).path ?? '')}` }],
222
869
  },
223
- async execute(args: { profile: unknown }, _exec: unknown) {
870
+ async execute(args, _exec: unknown) {
224
871
  // T1 接线:本工具是增量补丁语义(契约 18——模型每轮把对话新事实带进来),
225
872
  // 经 mergeProfile 守门合并进既有画像(追加不删史/幂等/权重变更须伴新证据),
226
873
  // 不再整档覆盖。首次调用(无档案)= 全量建立。
227
- const incoming = (args.profile ?? {}) as { weights?: Record<string, number>; evidence?: string[]; hard?: Record<string, unknown> }
874
+ // ADR-15:守门+事件+投影在账本单事务内完成,evidence 红线拒绝即回滚,账本无痕。
875
+ // issue #338:homeCity 同走 mergeProfile 守门(null=显式清除)。单条非空
876
+ // evidence 可提供省略的 unambiguous binding;多条 evidence 不按数组位置推断。
877
+ const incoming = (args.profile ?? {}) as { weights?: Record<string, number>; evidence?: string[]; hard?: Record<string, unknown>; homeCity?: string | null; homeCityEvidence?: string }
228
878
  if (!incoming.evidence?.length) {
229
879
  throw new Error('refusing to save a motivation profile without evidence (P0 anti-fabrication rule)')
230
880
  }
231
- const dir = await ensureStateDir(config.stateRoot)
232
- const path = join(dir, 'motivation-profile.json')
233
- let existing: { weights?: Record<string, number>; evidence?: string[]; hard?: Record<string, unknown> } | null = null
234
- try {
235
- existing = await readJson<typeof existing>(path, null)
236
- } catch { /* 首次保存:无档案 */ }
237
- const merged = mergeProfile(existing, { weights: incoming.weights, evidence: incoming.evidence, hard: incoming.hard })
238
- if (!merged) {
239
- // 幂等:补丁与现有画像完全一致,不落盘
240
- const currentJson = JSON.parse(JSON.stringify({ ...(existing ?? {}), updated_at: new Date().toISOString() })) as JsonObject
241
- return { ok: true, saved: false, path, profile: currentJson, summary: '无新内容(幂等跳过)' }
242
- }
243
- const saved = JSON.parse(JSON.stringify({ ...merged, updated_at: new Date().toISOString() })) as JsonObject
244
- await writeJson(path, saved)
245
- return { ok: true, saved: true, path, profile: saved, summary: '画像已合并落盘' }
881
+ // issue #338:trim 后空白拒绝(零事件落账)。空白字符串「无值」≠
882
+ // 「显式清除」——后者是 null,前者是没有声明。不擅自解释,显式拒收。
883
+ if (typeof incoming.homeCity === 'string' && incoming.homeCity.trim().length === 0) {
884
+ throw new Error('gotry_motivation_save.homeCity 是空白字符串,既不是声明也不是清除;请明确传城市名或 null')
885
+ }
886
+ let boundHomeCityEvidence: string | undefined
887
+ if (incoming.homeCity !== undefined) {
888
+ if (incoming.homeCityEvidence !== undefined) {
889
+ if (typeof incoming.homeCityEvidence !== 'string' || incoming.homeCityEvidence.trim().length === 0) {
890
+ throw new Error('gotry_motivation_save.homeCityEvidence 为空白;homeCity 必须绑定本次 evidence 中的一条 exact 用户原话')
891
+ }
892
+ if (!incoming.evidence.some(e => e === incoming.homeCityEvidence)) {
893
+ throw new Error('gotry_motivation_save.homeCityEvidence 必须逐字匹配本次 profile.evidence 中的一条用户原话')
894
+ }
895
+ boundHomeCityEvidence = incoming.homeCityEvidence
896
+ } else if (incoming.evidence.length === 1 && typeof incoming.evidence[0] === 'string' && incoming.evidence[0].trim().length > 0) {
897
+ boundHomeCityEvidence = incoming.evidence[0]
898
+ } else {
899
+ throw new Error('gotry_motivation_save.homeCityEvidence 缺失或有歧义;evidence 恰好一条非空时可省略,多条 evidence 必须显式绑定 exact 用户原话')
900
+ }
901
+ } else if (incoming.homeCityEvidence !== undefined) {
902
+ throw new Error('gotry_motivation_save.homeCityEvidence 只能与 homeCity 一起传入')
903
+ }
904
+ const ledger = ensureLedger(config.stateRoot)
905
+ const res = ledger.appendMotivationPatch({
906
+ weights: incoming.weights,
907
+ evidence: incoming.evidence,
908
+ hard: incoming.hard,
909
+ homeCity: incoming.homeCity,
910
+ homeCityEvidence: boundHomeCityEvidence,
911
+ } as ProfilePatch)
912
+ const profileJson = JSON.parse(JSON.stringify(res.profile)) as JsonObject
913
+ return res.saved
914
+ ? { ok: true, saved: true, path: ledger.dbPath, profile: profileJson, summary: '画像已合并入账本(单事务)' }
915
+ : { ok: true, saved: false, path: ledger.dbPath, profile: profileJson, summary: '无新内容(幂等跳过)' }
246
916
  },
247
917
  presentCall: args => ({ card: 'generic', title: '保存动机画像', kind: 'edit', rawInput: args.profile }),
248
918
  }))
@@ -258,7 +928,7 @@ export function apply(ctx: Context, config: Config): void {
258
928
  entry: {
259
929
  type: 'json',
260
930
  required: true,
261
- description: '{ name, reason?, conditions: { days, budget_cny, best_months }, muted?: boolean }',
931
+ description: '{ name, reason?, conditions: { days, budget_cny, best_months, channels? }, muted?: boolean }',
262
932
  },
263
933
  },
264
934
  output: {
@@ -271,30 +941,11 @@ export function apply(ctx: Context, config: Config): void {
271
941
  },
272
942
  async execute(args: { entry: unknown }, _exec: unknown) {
273
943
  const entry = (args.entry ?? {}) as WishPoolEntryInput & { muted?: boolean }
274
- if (!entry.name || !entry.conditions) {
275
- throw new Error('wish pool entry requires name and conditions (fulfilment conditions are the whole point)')
276
- }
277
- const dir = await ensureStateDir(config.stateRoot)
278
- const path = join(dir, 'wish-pool.json')
279
- const pool = (await readJson(path, [])) as Array<Record<string, unknown>>
280
- // 同名憧憬幂等更新(刷新理由与成行条件),不重复落盘;wish_id 稳定(存量补签)
281
- const existing = pool.findIndex(e => e['name'] === entry.name)
282
- if (existing >= 0) {
283
- const prev = pool[existing] ?? {}
284
- pool[existing] = {
285
- ...prev,
286
- wish_id: prev['wish_id'] ?? `w${Date.now().toString(36)}`,
287
- reason: entry.reason ?? prev['reason'],
288
- conditions: entry.conditions,
289
- ...(entry.muted !== undefined ? { muted: entry.muted } : {}),
290
- }
291
- await writeJson(path, pool)
292
- return { ok: true, added: false, wish_id: String(pool[existing]?.['wish_id']), total: pool.length, path }
293
- }
294
- const created = { wish_id: `w${Date.now().toString(36)}`, reason: '', ...entry, added_at: new Date().toISOString() }
295
- pool.push(created)
296
- await writeJson(path, pool)
297
- return { ok: true, added: true, wish_id: created.wish_id, total: pool.length, path }
944
+ // 同名憧憬幂等更新(刷新理由与成行条件),不重复入池;wish_id 语义派生自名称,稳定可重放。
945
+ // ADR-15:conditions 红线在账本事务内校验拒绝。
946
+ const ledger = ensureLedger(config.stateRoot)
947
+ const r = ledger.appendWish({ name: entry.name, reason: entry.reason, conditions: entry.conditions, muted: entry.muted })
948
+ return { ok: true, added: r.added, wish_id: r.wish_id, total: r.total, path: ledger.dbPath }
298
949
  },
299
950
  presentCall: args => ({ card: 'generic', title: '加入「下一次出发」清单', kind: 'edit', rawInput: args.entry }),
300
951
  }))
@@ -305,58 +956,68 @@ export function apply(ctx: Context, config: Config): void {
305
956
  'Surface AT MOST ONE "next departure" wish whose fulfilment conditions match the user\'s current window '
306
957
  + '(0..1 rule: never more than one nudge per turn, never push when nothing matches — 憧憬不被拒绝,也不被硬推). '
307
958
  + 'Muted wishes never surface. Surfacing records a recalled event in the memory-utility sidecar. '
959
+ + 'A wish whose conditions.channels names a channel that is currently down (out-of-band health facts) is vetoed for this recall — 不推当下走不通的憧憬. '
308
960
  + 'action="confirm-outcome" records the user-confirmed real-world outcome (attribution helpful/harmful/neutral) — '
309
961
  + 'ONLY pass attribution the user explicitly stated; the agent must never self-attribute usefulness.',
962
+ // D-30 第四刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层
310
963
  parameters: {
311
- query: {
312
- type: 'json',
313
- required: true,
314
- description: '{ action?: "recall"|"confirm-outcome", days?: number, budgetCny?: number, month?: number, wishId?: string, attribution?: "helpful"|"harmful"|"neutral", detail?: string }',
315
- },
964
+ action: { type: 'string', description: 'recall(默认,召回下一次出发建议)或 confirm-outcome(确认某条建议成/不成)' },
965
+ days: { type: 'integer', description: '回看天数窗(recall)' },
966
+ budgetCny: { type: 'number', description: '预算上限(recall 过滤)' },
967
+ month: { type: 'integer', description: '出行月份 1-12(recall)' },
968
+ wishId: { type: 'string', description: 'confirm-outcome 目标愿望 id' },
969
+ attribution: { type: 'string', enum: ['helpful', 'harmful', 'neutral'], description: 'confirm-outcome 归因' },
970
+ detail: { type: 'string', description: '一句话细节(用户原话)' },
971
+ tripStart: { type: 'string', description: '确认成行时挂时间线的行程起始日' },
316
972
  },
317
973
  output: {
318
974
  schema: { type: 'json' },
319
975
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }],
320
976
  },
321
- async execute(args: { query: unknown }, _exec: unknown) {
322
- const q = unwrapQuery<{ action?: string; days?: number; budgetCny?: number; month?: number; wishId?: string; attribution?: 'helpful' | 'harmful' | 'neutral'; detail?: string }>(args, 'action')
323
- const dir = await ensureStateDir(config.stateRoot)
324
- const pool = (await readJson(join(dir, 'wish-pool.json'), [])) as Array<Record<string, unknown>>
325
- const sidecarPath = join(dir, 'memory-utility.jsonl')
326
- const loadSidecar = async (): Promise<MemoryUtilityEvent[]> => {
327
- try {
328
- const raw = await readFile(sidecarPath, 'utf-8')
329
- return raw.split('\n').filter(Boolean).map(l => JSON.parse(l) as MemoryUtilityEvent)
330
- } catch { return [] } // fail-open:sidecar 缺失/损坏不阻塞召回
331
- }
332
- const saveSidecar = async (events: MemoryUtilityEvent[]) => {
333
- await writeFile(sidecarPath, events.map(e => JSON.stringify(e)).join('\n') + '\n', 'utf-8')
334
- }
977
+ async execute(args, _exec: unknown) {
978
+ const q = unwrapQuery<{ action?: string; days?: number; budgetCny?: number; month?: number; wishId?: string; attribution?: 'helpful' | 'harmful' | 'neutral'; detail?: string; tripStart?: string }>(args, 'action')
979
+ const ledger = ensureLedger(config.stateRoot)
335
980
  const now = new Date().toISOString()
336
981
  if (q.action === 'confirm-outcome') {
337
982
  if (!q.wishId || !q.attribution) {
338
983
  return { ok: false, summary: 'confirm-outcome 需要 wishId + attribution(helpful|harmful|neutral)' } as never
339
984
  }
340
- const events = await loadSidecar()
341
- const { events: next, appended } = appendEvent(events, {
342
- wish_id: q.wishId, kind: 'verified_outcome', ts: now,
343
- ctx: 'gotry_wish_pool_list.confirm', detail: q.detail, attribution: q.attribution,
344
- })
345
- if (appended) await saveSidecar(next)
346
- return { ok: true, recorded: appended, wish_id: q.wishId, status: q.attribution } as never
985
+ // 成行确认 = 效用事件 + 可选时间线行程,账本单事务(ADR-15:原两文件写在崩溃时分叉)
986
+ let tripInput: { destination: string; start: string; end?: string; companions?: string[]; source: 'wish-confirmed'; evidence: string } | undefined
987
+ const wish = ledger.readWishPool().find(e => String(e.wish_id) === q.wishId) as { name?: unknown } | undefined
988
+ if (q.tripStart && wish?.name) {
989
+ const anchor = buildTimeAnchor(new Date())
990
+ const start = resolveTimelineDate(q.tripStart, anchor) ?? (/^\d{4}-\d{2}-\d{2}$/.test(q.tripStart) ? q.tripStart : undefined)
991
+ if (start) {
992
+ tripInput = {
993
+ destination: String(wish.name), start, companions: undefined,
994
+ source: 'wish-confirmed', evidence: `wish ${q.wishId} confirm-outcome(${q.attribution})`,
995
+ }
996
+ }
997
+ }
998
+ const r = ledger.confirmOutcome({ wishId: q.wishId, attribution: q.attribution, detail: q.detail, trip: tripInput })
999
+ return { ok: true, recorded: r.recorded, wish_id: q.wishId, status: q.attribution, ...(r.trip ? { trip: r.trip } : {}) } as never
347
1000
  }
348
- // recall:0..1 条件匹配(判定归 wish-pool 纯函数),muted 永不召回,无命中不硬推
349
- const candidates = pool.filter(e => !e['muted'] && typeof e['wish_id'] === 'string')
1001
+ // recall:0..1 条件匹配(判定归 wish-pool 纯函数),muted 永不召回,无命中不硬推;
1002
+ // 通道否证(接缝第 2 段):持久健康面里处于 down 的通道集合进 context——
1003
+ // conditions.channels 命名依赖通道的愿望在被否证时不当场推荐(读不到健康面=不启用)。
1004
+ const pool = ledger.readWishPool()
1005
+ const candidates = pool.filter(e => !e.muted && typeof e.wish_id === 'string')
350
1006
  const month = q.month ?? new Date().getMonth() + 1
351
- const match = pickNudgeWish(candidates as WishPoolEntry[], { days: q.days, budgetCny: q.budgetCny, month })
1007
+ let channelDown: ReadonlySet<string> | undefined
1008
+ try {
1009
+ const latest = await readLatestChannelEvents(config.stateRoot)
1010
+ const down = new Set<string>()
1011
+ for (const [ch, ev] of latest) if (ev.state === 'down') down.add(ch)
1012
+ channelDown = down
1013
+ } catch { /* 健康面缺席=不启用否证,召回行为与旧版一致 */ }
1014
+ const match = pickNudgeWish(candidates as WishPoolEntry[], { days: q.days, budgetCny: q.budgetCny, month, channelDown })
352
1015
  if (!match) {
353
1016
  return { ok: true, suggestion: null, summary: `无可成行的憧憬匹配当前窗口(${candidates.length} 条在册,0..1 纪律:不硬推)` } as never
354
1017
  }
355
- const events = await loadSidecar()
356
- const { events: next, appended } = appendEvent(events, {
1018
+ const { events: next } = ledger.appendUtilityEvent({
357
1019
  wish_id: match.wishId, kind: 'recalled', ts: now, ctx: 'gotry_wish_pool_list.recall',
358
1020
  })
359
- if (appended) await saveSidecar(next)
360
1021
  const utility = projectUtility(next)[match.wishId]
361
1022
  return {
362
1023
  ok: true,
@@ -365,51 +1026,203 @@ export function apply(ctx: Context, config: Config): void {
365
1026
  summary: `「下一次出发」候选(0..1):${String(match.entry['name'])}——成行条件 ${JSON.stringify(match.entry['conditions'])},本次窗口命中 ${match.score}/3 项(${match.hits.join('+')});效用状态 ${utility?.status ?? 'unknown'}`,
366
1027
  } as never
367
1028
  },
368
- presentCall: args => ({ card: 'generic', title: '「下一次出发」召回', kind: 'search', rawInput: args.query }),
1029
+ presentCall: args => ({ card: 'generic', title: '「下一次出发」召回', kind: 'search', rawInput: args }),
369
1030
  }))
370
1031
 
1032
+ // ADR-24 v2 复访交付面:用户回问「行程规划好了吗」时,模型用这个只读工具
1033
+ // 查后台工单状态;settled 附交付物摘录(完整内容在工单同目录
1034
+ // .deliverable.md)。工单由 scripts/turn-handoff-collect.ts 收集结算。
371
1035
  registerGuarded(defineTool({
372
- name: 'gotry_hotel_search',
1036
+ name: 'gotry_turn_handoff_list',
373
1037
  description:
374
- 'Search hotels via hotelbyte-cli (real-time when hbcli credentials exist, falls back to the static pack with explicit evidence tagging). '
375
- + 'Input: destination city name + optional dates/occupancy. Dates accept verbatim natural expressions (下周五 / 8.20 / 下周五+3) — '
376
- + 'the code layer resolves them against the time anchor; unresolved expressions degrade to an undated search with an explicit '
377
- + 'date_notes entry instead of guessing. Output: hotel list with evidence chain ([realtime-API:hbcli] + fetch timestamp, '
378
- + 'or [static-pack:estimate]) per the L4 invariant.',
1038
+ 'List background deep-planning handoff tickets (read-only). Call this whenever the user asks about '
1039
+ + 'a previously handed-off plan («规划好了吗» / «上次那个行程»): open = still being worked in the '
1040
+ + 'background (ETA ' + '约 1 小时' + '), settled = deliverable ready (excerpt included, full text in the '
1041
+ + 'ticket\'s .deliverable.md), failed = honest failure note. Never fabricate a deliverable that is not here.',
1042
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层(同 session 刀法)
379
1043
  parameters: {
380
- query: {
381
- type: 'json',
1044
+ ticketId: { type: 'string', description: '只看这一单,如 th-...(缺省列全部)' },
1045
+ },
1046
+ output: {
1047
+ schema: { type: 'json' },
1048
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }],
1049
+ },
1050
+ async execute(args, _exec: unknown) {
1051
+ const q = interpretArgs<{ ticketId?: string }>(args)
1052
+ const root = process.env.GOTRY_TURN_HANDOFF_ROOT ?? config.stateRoot ?? '.'
1053
+ const all = await listTurnHandoffTickets(root)
1054
+ const tickets = (q.ticketId ? all.filter(t => t.id === q.ticketId) : all).slice(0, 10)
1055
+ if (tickets.length === 0) {
1056
+ return {
1057
+ ok: true, count: 0,
1058
+ summary: q.ticketId
1059
+ ? `没有 id 为 ${q.ticketId} 的后台规划工单(可能已被清理或记错 id)`
1060
+ : '当前没有后台深度规划工单(无挂起、无历史)',
1061
+ } as never
1062
+ }
1063
+ const lines = tickets.map(t => {
1064
+ const head = `[${t.status}] ${t.id} ${t.objective.slice(0, 40)}`
1065
+ if (t.status === 'open') return `${head}——后台规划中,ETA ${t.etaLabel}`
1066
+ if (t.status === 'failed') return `${head}——失败:${t.error ?? '未知原因'}(请重新发起规划)`
1067
+ return `${head}——已交付,摘要:${(t.deliverableExcerpt ?? '').slice(0, 120).replace(/\n/g, ' ')}`
1068
+ })
1069
+ return {
1070
+ ok: true, count: tickets.length, tickets,
1071
+ summary: `后台规划工单 ${tickets.length} 张:\n${lines.join('\n')}`,
1072
+ } as never
1073
+ },
1074
+ presentCall: args => ({ card: 'generic', title: '后台规划工单查询', kind: 'search', rawInput: args }),
1075
+ }))
1076
+
1077
+ registerGuarded(defineTool({
1078
+ name: 'gotry_companion_save',
1079
+ description:
1080
+ 'Save/update a travel companion profile (memory-design M5 layer): constraints that shape itinerary STRUCTURE and ranking — '
1081
+ + 'never a hard filter (「爸爸65轻度高血压」→ 不排高海拔/控制步行量;「晕车」→ 优先火车/备提示). '
1082
+ + 'evidence MUST be the user\'s verbatim words (append-only, traceable). '
1083
+ + 'NEGATIVE LIST: passport/ID/phone numbers are rejected on sight — such fields never enter storage.',
1084
+ // D-30 第五刀(issue #112):companion blob → 结构化闭合对象;label/evidence required 由宿主权闸
1085
+ // (evidence append-only 溯源 P0;additionalProperties:false 与负面清单同向——护照/证件号类
1086
+ // 杂散字段入口即拒)
1087
+ parameters: {
1088
+ companion: {
1089
+ type: 'object',
1090
+ additionalProperties: false,
382
1091
  required: true,
383
- description: '{ destination: "<目的地城市>", checkIn?: "YYYY-MM-DD 或自然表达(下周五/8.20)", checkOut?: 同上, occupancy?: { adults: 2 } }',
1092
+ properties: {
1093
+ label: { type: 'string', required: true, description: '称呼,如 爸爸' },
1094
+ constraints: { type: 'object', additionalProperties: true, description: '{ mobility?: "步行≤4h", health?: ["轻度高血压"], prefs?: ["怕吵"] }' },
1095
+ evidence: { type: 'string', required: true, description: '用户原话(append-only 可溯源,P0)' },
1096
+ },
384
1097
  },
385
1098
  },
1099
+ output: {
1100
+ schema: { type: 'json' },
1101
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }],
1102
+ },
1103
+ async execute(args: { companion: unknown }, _exec: unknown) {
1104
+ const c = (args.companion ?? {}) as { label?: string; constraints?: { mobility?: string; health?: string[]; prefs?: string[] }; evidence?: string }
1105
+ if (!c.evidence) return { ok: false, summary: 'evidence 必填(用户原话,溯源 P0)' } as never
1106
+ // ADR-15:负面清单守卫(upsertCompanion)在账本事务内执行,拒收即回滚
1107
+ const ledger = ensureLedger(config.stateRoot)
1108
+ const res = ledger.appendCompanion({
1109
+ label: String(c.label ?? ''),
1110
+ constraints: { mobility: c.constraints?.mobility, health: c.constraints?.health, prefs: c.constraints?.prefs },
1111
+ evidence: c.evidence,
1112
+ })
1113
+ if (!res.appended && res.reason) return { ok: false, summary: res.reason } as never
1114
+ return { ok: true, appended: res.appended, companion_id: res.companionId, total: res.total, summary: res.appended ? `同行人已保存:${res.companionId}` : `无新内容(幂等跳过):${res.companionId}` } as never
1115
+ },
1116
+ presentCall: args => ({ card: 'generic', title: '保存同行人', kind: 'edit', rawInput: args.companion }),
1117
+ }))
1118
+
1119
+ registerGuarded(defineTool({
1120
+ name: 'gotry_trip_log',
1121
+ description:
1122
+ 'Record a PAST trip into the travel timeline (memory-design M4 layer). Use when the user mentions a trip they already took '
1123
+ + '(「去年国庆去了大理」) — dates resolve via the time anchor (词表外日期会拒绝,请用户给绝对日期), evidence MUST be the user\'s verbatim words. '
1124
+ + 'Append-only and idempotent (same destination+start+source = same trip); overlapping same-destination trips are rejected for human adjudication. '
1125
+ + 'Past trips power origin resolution and 「去过不再推」 ranking — never a hard filter.',
1126
+ // D-30 第四刀(issue #112):平铺 typed;destination/evidence required → 宿主权入口拒缺参
1127
+ // (evidence 是 P0 溯源红线,进 schema 由宿主权闸,不再依赖 execute 散文报错)
1128
+ parameters: {
1129
+ destination: { type: 'string', required: true, description: '目的地,如 大理' },
1130
+ start: { type: 'string', required: true, description: '行程起始:YYYY-MM-DD 或绝对日期表达(解析不了 execute 结构化报错不猜)' },
1131
+ end: { type: 'string', description: '行程结束,形态同 start(可选)' },
1132
+ companions: { type: 'array', items: { type: 'string' }, description: '同行人,如 ["爸爸"]' },
1133
+ evidence: { type: 'string', required: true, description: '用户原话(溯源 P0 红线)' },
1134
+ },
1135
+ output: {
1136
+ schema: { type: 'json' },
1137
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }],
1138
+ },
1139
+ async execute(args, _exec: unknown) {
1140
+ const q = args
1141
+ if (!q.destination) return { ok: false, summary: 'destination 必填' } as never
1142
+ if (!q.evidence) return { ok: false, summary: 'evidence 必填(用户原话,溯源 P0)' } as never
1143
+ const anchor = buildTimeAnchor(new Date())
1144
+ const start = resolveTimelineDate(q.start ?? '', anchor) ?? (/^\d{4}-\d{2}-\d{2}$/.test(q.start ?? '') ? q.start : undefined)
1145
+ if (!start) return { ok: false, summary: `start 无法解析为绝对日期(${q.start ?? '缺'})——请向用户要具体日期,不猜` } as never
1146
+ const end = q.end ? (resolveTimelineDate(q.end, anchor) ?? (/^\d{4}-\d{2}-\d{2}$/.test(q.end) ? q.end : undefined)) : undefined
1147
+ // ADR-15:appendTrip 守门(必填/绝对日期/重叠冲突即停)在账本事务内执行
1148
+ const ledger = ensureLedger(config.stateRoot)
1149
+ const res = ledger.appendTripEvent({
1150
+ destination: q.destination.trim(), start, end, companions: q.companions,
1151
+ source: 'user-verbatim', evidence: q.evidence,
1152
+ })
1153
+ if (!res.appended && res.reason) return { ok: false, summary: res.reason } as never
1154
+ return { ok: true, appended: res.appended, trip_id: res.tripId, total: res.total, summary: res.appended ? `已入时间线:${q.destination} @ ${start}` : `已存在(幂等跳过):${res.tripId}` } as never
1155
+ },
1156
+ presentCall: args => ({ card: 'generic', title: '记录旅行', kind: 'edit', rawInput: args }),
1157
+ }))
1158
+
1159
+ registerGuarded(defineTool({
1160
+ name: 'gotry_hotel_search',
1161
+ description: routed('gotry_hotel_search',
1162
+ 'Search hotels via hotelbyte-cli (real-time when hbcli credentials exist, falls back to the static pack with explicit evidence tagging). '
1163
+ + 'Input: destination city name + optional dates/adults. Dates accept verbatim natural expressions (下周五 / 8.20 / 下周五+3) — '
1164
+ + 'the code layer resolves them against the time anchor. **Dates are required for a supplier search** (issue #283): missing, blank, '
1165
+ + 'single-side, unresolvable, or checkOut ≤ checkIn returns an actionable input_required result WITHOUT spawning the vendor CLI; '
1166
+ + 'only after a complete valid stay window is fixed do we forward to hbcli. '
1167
+ + 'Output: hotel list with evidence chain ([realtime-API:hbcli] + fetch timestamp, '
1168
+ + 'or [static-pack:estimate]) per the L4 invariant. Independent read-only: safe to issue in the same step as other independent searches; '
1169
+ + 'the host abort signal is forwarded to the spawned process tree.'),
1170
+ // 并发安全(issue #519):只读检索,execute 不写共享会话态(延迟/事实落盘 append-only 且失败不阻塞),
1171
+ // 私有进程组接收宿主 signal;取消有界返回,未知组外后代不冒充已回收。
1172
+ isConcurrencySafe: () => true,
1173
+ // D-30 第二刀(issue #112):query blob → 平铺 typed 契约(同 flyai 刀法)。
1174
+ parameters: {
1175
+ destination: { type: 'string', required: true, description: '目的地城市,如 大理' },
1176
+ // issue #283 闸:日期字段对模型面仍是契约必填(required 标在 description,schema 不强制,
1177
+ // 让 gate 产出更可行动的错误——dsh schema 拒绝信息太泛)
1178
+ checkIn: { type: 'string', description: '入住日:YYYY-MM-DD 或自然表达(下周五/8.20/下周五+3);REQUIRED——缺失/空白/无法解析由 date-gate 返回 input_required,不查' },
1179
+ checkOut: { type: 'string', description: 'checkOut 退房日:YYYY-MM-DD 或自然表达,形态同 checkIn;REQUIRED——必须晚于入住日,否则不查' },
1180
+ adults: { type: 'integer', description: '成人数(顶层字段,默认 2)' },
1181
+ },
386
1182
  output: {
387
1183
  schema: { type: 'json' },
388
1184
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 400)) }],
389
1185
  },
390
- async execute(args: { query: unknown }, _exec: unknown) {
391
- const q = unwrapQuery<{ destination?: string; checkIn?: string; checkOut?: string; adults?: number }>(args, 'destination')
1186
+ async execute(args, _exec) {
1187
+ const q = args
392
1188
  if (!q.destination) throw new Error('gotry_hotel_search requires destination')
393
1189
  const started = Date.now()
1190
+ const execSignal = (_exec as { signal?: AbortSignal } | undefined)?.signal
394
1191
  const fallbackPath = join(import.meta.dirname, '..', '..', 'data', 'hotels_2026.json')
395
- // D-10 切片 B:日期槽位接受逐字自然表达(下周五/8.20/+N),代码层换算(slot-spec);
396
- // unresolved 不猜——降级为无日期搜索并显式记 note,由模型向用户追问
397
- const anchor = buildTimeAnchor(new Date())
398
- const dateNotes: string[] = []
399
- const resolveDate = (expr?: string): string | undefined => {
400
- if (!expr) return undefined
401
- const r = resolveSlotDate(expr, anchor)
402
- if (!r.date) {
403
- dateNotes.push(`日期未解析:${r.raw}——请向用户确认具体日期`)
404
- return undefined
405
- }
406
- if (r.raw !== r.date) dateNotes.push(`slot-resolved: ${r.raw} → ${r.date}`)
407
- return r.date
1192
+ // issue #283 闸:完整、有效且退房晚于入住才能派发 hbcli;失败直接返回
1193
+ // input_required,不发供应商命令,不把当前窗口查询当所需日期结果。
1194
+ // 复用既有 time-anchor/slot-spec:词表内自然表达 → 绝对日期;
1195
+ // 词表外 → unresolved,闸失败,不再走「无日期降级」伪装默认窗口价。
1196
+ const gate = evaluateHotelStayDates(q.checkIn, q.checkOut)
1197
+ if (!gate.ok) {
1198
+ // 闸失败:不调用 interpretEffect,不调 hbcli;延迟日志不写(no spawn)。
1199
+ // summary 用「需要 X 信息才能查询酒店」开头的可行动句式,presentResult 直接
1200
+ // 渲成「酒店:<dest> 缺日期」行动卡(替代旧版「无结果」空卡)。
1201
+ const summary = `需要补充${(gate.missing ?? []).map(m => m === 'checkIn' ? '入住日' : '退房日').join('和')}才能查询酒店「${q.destination ?? ''}」:${gate.message}`
1202
+ return {
1203
+ ok: false,
1204
+ verdict: gate.verdict,
1205
+ reason: gate.reason,
1206
+ missing: gate.missing,
1207
+ raw: gate.raw,
1208
+ destination: q.destination,
1209
+ message: gate.message,
1210
+ summary,
1211
+ evidence: gate.evidence,
1212
+ latency_ms: Date.now() - started,
1213
+ } as never
408
1214
  }
409
- const resp = await hbcliSearchHotels(
410
- { destination: q.destination, checkIn: resolveDate(q.checkIn), checkOut: resolveDate(q.checkOut), adults: q.adults },
411
- { hbcliBin: config.hbcliBin, timeoutMs: config.timeoutMs, fallbackPath },
412
- )
1215
+ // 闸通过:绝对日期已就位;slot 解析过程产生的原话 → 绝对日期 注记回显
1216
+ // (工具层 date_notes 与既有 D-10 切片 B 形态兼容)
1217
+ const dateNotes = [...gate.notes]
1218
+ // 效应解译层(ADR-18):渠道选择/韧性(重试/熔断)在解译器,result 原样透传——
1219
+ // 断路拒绝时返回平铺失败面(不发起查询,不伪装成 miss)
1220
+ const itp = await interpretEffect({
1221
+ effect: 'HBCLI_HOTEL_SEARCH',
1222
+ params: { destination: q.destination, checkIn: gate.checkIn, checkOut: gate.checkOut, adults: q.adults, hbcliBin: config.hbcliBin, timeoutMs: config.timeoutMs, fallbackPath, signal: execSignal },
1223
+ })
1224
+ if (!itp.result) return declinedObservation('HBCLI_HOTEL_SEARCH', itp.trace)
1225
+ const resp = itp.result
413
1226
  const dir = await ensureStateDir(config.stateRoot)
414
1227
  const isLive = resp.via === 'hbcli-realtime'
415
1228
  const evidence = isLive ? resp.evidence : '[静态包:估算]'
@@ -427,18 +1240,127 @@ export function apply(ctx: Context, config: Config): void {
427
1240
  } as never
428
1241
  return JSON.parse(JSON.stringify(payload)) as never
429
1242
  },
430
- presentCall: args => ({ card: 'generic', title: `酒店搜索:${String((args.query as { destination?: string })?.destination ?? '')}`, kind: 'search', rawInput: args.query }),
1243
+ presentCall: args => ({ card: 'generic', title: `酒店搜索:${args.destination ?? ''}`, kind: 'search', rawInput: args }),
431
1244
  presentResult: (_args, value) => {
432
- const r = value as { hotels?: unknown[]; via?: string; destination?: string; summary?: string }
433
- const n = Array.isArray(r.hotels) ? r.hotels.length : 0
1245
+ // 闸失败:渲染为「input_required」行动卡,引导模型向用户追问日期;
1246
+ // 不再退化为「无结果」空卡——闸拒绝的可行动语义必须显式进 UI。
1247
+ // UI 面禁用内部工程词(check_in_blank / 闸拒绝 / ISO 字符串),只露「入住日/退房日」
1248
+ // 与具体日期示例供模型追问。
1249
+ const r = value as { hotels?: unknown; via?: string; destination?: string; summary?: string; verdict?: string; reason?: string; missing?: string[]; message?: string }
1250
+ if (r.verdict === 'input_required') {
1251
+ const missingLabels = (r.missing ?? []).map(m => m === 'checkIn' ? '入住日' : '退房日')
1252
+ const fieldText = missingLabels.length ? missingLabels.join('和') : '入住日和退房日'
1253
+ const dateHint = !missingLabels.length || missingLabels.length === 2
1254
+ ? '例如 2026-09-18 / 2026-09-20'
1255
+ : missingLabels[0] === '入住日' ? '例如 2026-09-18' : '例如 2026-09-20'
1256
+ return {
1257
+ card: 'generic',
1258
+ title: `酒店:${r.destination ?? ''} 需要${fieldText}`,
1259
+ // P2 措辞修正:直接对用户说话的句式,不再绕一道「请告诉.../请向用户确认」转给模型;
1260
+ // gate.message 里残留的字段指引也归一为直接对用户措辞,保留日期示例等可行动细节。
1261
+ content: [{ type: 'text', text: `请补充 ${fieldText}(${dateHint})后再次查询。\n${normalizeHotelGateHandoff(r.message)}` }],
1262
+ }
1263
+ }
1264
+ const h = r.hotels
1265
+ const liveCount = Array.isArray(h) ? h.length : 0
1266
+ // 静态包是 {meta, stays} 对象而非数组(issue #24:此前计数恒 0 → UI 显示「无结果」)
1267
+ const stays = !Array.isArray(h) && h && typeof h === 'object' ? (h as { stays?: unknown[] }).stays : undefined
1268
+ const staticCount = Array.isArray(stays) ? stays.length : 0
1269
+ const tag = r.via === 'hbcli-realtime'
1270
+ ? (liveCount ? `实时 ${liveCount} 家` : '实时')
1271
+ : staticCount ? `静态包 ${staticCount} 块` : (liveCount ? `${liveCount} 家` : '无结果')
434
1272
  return {
435
1273
  card: 'generic',
436
- title: `酒店:${r.destination ?? ''} ${n ? `${n} 家(${r.via === 'hbcli-realtime' ? '实时' : '静态包'})` : '无结果'}`,
1274
+ title: `酒店:${r.destination ?? ''} ${tag}`,
437
1275
  content: [{ type: 'text', text: String(r.summary ?? '') }],
438
1276
  }
439
1277
  },
440
1278
  }))
441
1279
 
1280
+ // ---- hotelbyte 客户认证面(hbcli auth customer-*;新邮箱即注册,无需密码)----
1281
+ // 两步流:send_code(外发邮件,须用户明示同意)→ 用户从收件箱报码 → login。
1282
+ // 刻意不走 interpretEffect 效应层:发码/验码非幂等(超时重试会重复发信/浪费
1283
+ // 一次性验证码),直调能力层 fail-fast;凭据写 hbcli customer 档(CLI 侧最低
1284
+ // 优先级,不劫持既有 portal/API-key 凭据),token 值不进 gotry 会话/日志。
1285
+
1286
+ registerGuarded(defineTool({
1287
+ name: 'gotry_hotel_auth_send_code',
1288
+ description:
1289
+ 'Send an email verification code to the user for HotelByte customer login (step 1 of 2). '
1290
+ + '**Only call after the user explicitly agreed to login/register with that email** — this sends a real email and the backend rate-limits sends. '
1291
+ + 'Step 2 is gotry_hotel_auth_login with the code the user reads from their inbox (never guess or fabricate the code). '
1292
+ + 'Requires hbcli with auth support (npm staicli ≥ 0.0.4); on older versions it fails with unknown-command via the error surface.',
1293
+ parameters: {
1294
+ email: { type: 'string', required: true, description: '用户邮箱(验证码发送目标,须用户自己提供)' },
1295
+ },
1296
+ output: {
1297
+ schema: { type: 'json' },
1298
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 400)) }],
1299
+ },
1300
+ async execute(args, _exec) {
1301
+ const q = args as { email?: string }
1302
+ const email = String(q.email ?? '').trim()
1303
+ if (!email || !email.includes('@')) {
1304
+ return { ok: false, summary: `需要有效邮箱才能发送验证码(收到:${email || '空'})——请向用户要邮箱,不猜` } as never
1305
+ }
1306
+ const started = Date.now()
1307
+ const r = await customerSendCode(email, { hbcliBin: config.hbcliBin, timeoutMs: config.timeoutMs })
1308
+ return JSON.parse(JSON.stringify({
1309
+ ok: r.via === 'hbcli-realtime',
1310
+ summary: r.summary,
1311
+ evidence: r.evidence,
1312
+ via: r.via,
1313
+ detail: r.result,
1314
+ latency_ms: Date.now() - started,
1315
+ })) as never
1316
+ },
1317
+ presentCall: args => ({ card: 'generic', title: `发送验证码:${(args as { email?: string }).email ?? ''}`, kind: 'execute', rawInput: args }),
1318
+ }))
1319
+
1320
+ registerGuarded(defineTool({
1321
+ name: 'gotry_hotel_auth_login',
1322
+ description:
1323
+ 'Complete HotelByte customer login with email + code (step 2 of 2; pairs with gotry_hotel_auth_send_code). '
1324
+ + 'The code comes from the user\'s inbox — never guess. A NEW email is auto-registered (no password needed): verified email = account. '
1325
+ + 'On success the credential is stored in hbcli\'s customer profile (lowest precedence — existing portal/API-key credentials are NOT hijacked), '
1326
+ + 'and subsequent hotel search/rates run realtime under that identity. Optional attributionToken (from an advisor share link) binds the user '
1327
+ + 'to that advisor. Login failure consumes the one-shot code: re-send a new code before retrying.',
1328
+ parameters: {
1329
+ email: { type: 'string', required: true, description: '用户邮箱(与发送验证码时一致)' },
1330
+ code: { type: 'string', required: true, description: '用户从邮箱收到的验证码(一次性凭据;失败即作废,需重新发码)' },
1331
+ attributionToken: { type: 'string', description: '顾问归因令牌(顾问分享链接携带;可选,绑定后该客户计入顾问客户簿)' },
1332
+ },
1333
+ output: {
1334
+ schema: { type: 'json' },
1335
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 400)) }],
1336
+ },
1337
+ async execute(args, _exec) {
1338
+ const q = args as { email?: string; code?: string; attributionToken?: string }
1339
+ const email = String(q.email ?? '').trim()
1340
+ const code = String(q.code ?? '').trim()
1341
+ if (!email || !email.includes('@')) {
1342
+ return { ok: false, summary: `需要有效邮箱才能登录(收到:${email || '空'})——请向用户确认邮箱` } as never
1343
+ }
1344
+ if (!code) {
1345
+ return { ok: false, summary: '需要邮箱验证码才能登录——请让用户从收件箱查收并报码(先 gotry_hotel_auth_send_code)' } as never
1346
+ }
1347
+ const started = Date.now()
1348
+ const r = await customerLogin(
1349
+ { email, code, attributionToken: q.attributionToken ? String(q.attributionToken) : undefined },
1350
+ { hbcliBin: config.hbcliBin, timeoutMs: config.timeoutMs },
1351
+ )
1352
+ return JSON.parse(JSON.stringify({
1353
+ ok: r.via === 'hbcli-realtime' && (r.result as { status?: string } | null)?.status === 'logged_in',
1354
+ summary: r.summary,
1355
+ evidence: r.evidence,
1356
+ via: r.via,
1357
+ detail: r.result,
1358
+ latency_ms: Date.now() - started,
1359
+ })) as never
1360
+ },
1361
+ presentCall: args => ({ card: 'generic', title: `客户登录:${(args as { email?: string }).email ?? ''}`, kind: 'execute', rawInput: args }),
1362
+ }))
1363
+
442
1364
  registerGuarded(defineTool({
443
1365
  name: 'gotry_skeleton_check',
444
1366
  description:
@@ -466,30 +1388,34 @@ export function apply(ctx: Context, config: Config): void {
466
1388
 
467
1389
  registerGuarded(defineTool({
468
1390
  name: 'gotry_weather_check',
469
- description:
1391
+ description: routed('gotry_weather_check',
470
1392
  'Check weather for a destination: forecast (≤16 days) or historical climate (seasonality baseline). '
471
1393
  + 'Free Open-Meteo API, no key required. Input: place name (Chinese ok) or lat/lng. '
472
1394
  + 'Returns daily temp range, precipitation probability, weather code — with evidence chain tagging '
473
- + '[实时API:open-meteo@ts]. Use to ground seasonal advice in real data instead of LLM guessing.',
1395
+ + '[实时API:open-meteo@ts]. Use to ground seasonal advice in real data instead of LLM guessing.'),
474
1396
  parameters: {
475
- query: {
476
- type: 'json',
477
- required: true,
478
- description: '{ place: "<城市名>", month?: 8, mode?: "forecast"|"climate", days?: 7 }',
479
- },
1397
+ // D-30 第二刀(issue #112):query blob → 平铺 typed 契约(同 flyai 刀法)。
1398
+ place: { type: 'string', description: '城市名(中文可),如 大理;与 lat/lng 二选一,都没给 execute 结构化报错' },
1399
+ lat: { type: 'number', description: '纬度(与 lng 成对;给了则跳过地理编码)' },
1400
+ lng: { type: 'number', description: '经度(与 lat 成对)' },
1401
+ month: { type: 'integer', description: '气候基线月份 1-12(mode=climate 或给了 month 未指 mode 时用)' },
1402
+ mode: { type: 'string', enum: ['forecast', 'climate'], description: '默认 forecast' },
1403
+ days: { type: 'integer', description: '预报天数(≤16,默认 7)' },
480
1404
  },
481
1405
  output: {
482
1406
  schema: { type: 'json' },
483
1407
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 600)) }],
484
1408
  },
485
- async execute(args: { query: unknown }, _exec: unknown) {
486
- const q = unwrapQuery<{ place?: string; lat?: number; lng?: number; month?: number; mode?: string; days?: number }>(args, 'place')
1409
+ async execute(args, _exec) {
1410
+ const q = args
487
1411
  const started = Date.now()
488
1412
  let lat: number | undefined = q.lat, lng: number | undefined = q.lng
489
1413
  let placeLabel = q.place ?? `${q.lat},${q.lng}`
490
1414
  if (lat === undefined || lng === undefined) {
491
1415
  if (!q.place) throw new Error('gotry_weather_check requires place name or lat/lng')
492
- const geo = await geocodePlace(q.place)
1416
+ const geoItp = await interpretEffect({ effect: 'WEATHER_GEOCODE', params: { name: q.place } })
1417
+ if (!geoItp.result) return declinedObservation('WEATHER_GEOCODE', geoItp.trace)
1418
+ const geo = geoItp.result
493
1419
  if (!geo.ok || geo.results.length === 0) {
494
1420
  return JSON.parse(JSON.stringify({ ok: false, summary: `地点「${q.place}」地理编码失败:${geo.error ?? '无结果'}`, evidence: geo.evidence })) as Record<string, never>
495
1421
  }
@@ -498,9 +1424,11 @@ export function apply(ctx: Context, config: Config): void {
498
1424
  placeLabel = `${hit.name}(${hit.admin1 ?? hit.country ?? ''})`
499
1425
  }
500
1426
  const isClimate = q.mode === 'climate' || (q.month !== undefined && q.mode !== 'forecast')
501
- const r = isClimate
502
- ? await getClimate({ latitude: lat, longitude: lng }, q.month ?? new Date().getMonth() + 1)
503
- : await getForecast({ latitude: lat, longitude: lng }, { days: q.days })
1427
+ const wxItp = isClimate
1428
+ ? await interpretEffect({ effect: 'WEATHER_CLIMATE', params: { latitude: lat, longitude: lng, month: q.month ?? new Date().getMonth() + 1 } })
1429
+ : await interpretEffect({ effect: 'WEATHER_FORECAST', params: { latitude: lat, longitude: lng, days: q.days } })
1430
+ if (!wxItp.result) return declinedObservation(isClimate ? 'WEATHER_CLIMATE' : 'WEATHER_FORECAST', wxItp.trace)
1431
+ const r = wxItp.result
504
1432
  const dir = await ensureStateDir(config.stateRoot)
505
1433
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, `weather:${r.via}`).catch(() => {})
506
1434
  const dailyLines = (r.daily ?? []).slice(0, 7).map(d =>
@@ -514,10 +1442,10 @@ export function apply(ctx: Context, config: Config): void {
514
1442
  latency_ms: Date.now() - started,
515
1443
  })) as Record<string, never>
516
1444
  },
517
- presentCall: args => ({ card: 'generic', title: `天气:${String((args.query as { place?: string })?.place ?? '')}`, kind: 'fetch', rawInput: args.query }),
1445
+ presentCall: args => ({ card: 'generic', title: `天气:${args.place ?? `${args.lat ?? ''},${args.lng ?? ''}`}`, kind: 'fetch', rawInput: args }),
518
1446
  presentResult: (args, value) => {
519
1447
  const r = value as { summary?: string }
520
- const place = String((args.query as { place?: string })?.place ?? '')
1448
+ const place = String(args.place ?? '')
521
1449
  const failed = String(r.summary ?? '').includes('降级') || String(r.summary ?? '').includes('unavailable')
522
1450
  return {
523
1451
  card: 'generic',
@@ -529,7 +1457,7 @@ export function apply(ctx: Context, config: Config): void {
529
1457
 
530
1458
  registerGuarded(defineTool({
531
1459
  name: 'gotry_flight_verify',
532
- description:
1460
+ description: routed('gotry_flight_verify',
533
1461
  'Verify whether a flight callsign is currently observable on the OpenSky ADS-B network. '
534
1462
  + 'Free anonymous API (~400 credits/day, 4 req/s burst). Three-valued semantics: '
535
1463
  + 'observed = strong positive (the aircraft is currently being broadcast); '
@@ -537,25 +1465,26 @@ export function apply(ctx: Context, config: Config): void {
537
1465
  + 'a missing signal does NOT disprove the flight); '
538
1466
  + 'unavailable = API failure, gracefully degraded. '
539
1467
  + 'Use to ground "is this flight actually flying right now?" in real data, complementing '
540
- + 'the OpenFlights skeleton (historical connectivity) and the static flight pack (planned schedule).',
1468
+ + 'the OpenFlights skeleton (historical connectivity) and the static flight pack (planned schedule).'),
1469
+ // D-30 第四刀(issue #112):平铺 typed;callsign required → 宿主权即拒
541
1470
  parameters: {
542
- query: {
543
- type: 'json',
544
- required: true,
545
- description: '{ callsign: "EK329", airport?: "OMDB", timeoutMs?: 10000 }',
546
- },
1471
+ callsign: { type: 'string', required: true, description: '航班呼号,如 EK329' },
1472
+ airport: { type: 'string', description: '预期机场 IATA,如 OMDB(观测命中时展示)' },
1473
+ timeoutMs: { type: 'integer', description: '超时毫秒,默认 10000' },
547
1474
  },
548
1475
  output: {
549
1476
  schema: { type: 'json' },
550
1477
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 500)) }],
551
1478
  },
552
- async execute(args: { query: unknown }, _exec: unknown) {
553
- const q = unwrapQuery<{ callsign: string; airport?: string; timeoutMs?: number }>(args, 'callsign')
1479
+ async execute(args, _exec: unknown) {
1480
+ const q = args
554
1481
  const started = Date.now()
555
1482
  if (!q.callsign) {
556
1483
  return JSON.parse(JSON.stringify({ verdict: 'unavailable', evidence: '[校验不可用:无 callsign]', summary: 'callsign 必填' })) as Record<string, never>
557
1484
  }
558
- const r = await verifyFlight({ callsign: q.callsign, airport: q.airport, timeoutMs: q.timeoutMs })
1485
+ const itp = await interpretEffect({ effect: 'OPENSKY_FLIGHT_VERIFY', params: { callsign: q.callsign, airport: q.airport, timeoutMs: q.timeoutMs } })
1486
+ if (!itp.result) return declinedObservation('OPENSKY_FLIGHT_VERIFY', itp.trace)
1487
+ const r = itp.result
559
1488
  const dir = await ensureStateDir(config.stateRoot)
560
1489
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, `flight_verify:${r.via}`).catch(() => {})
561
1490
  const summary = r.verdict === 'observed'
@@ -570,42 +1499,395 @@ export function apply(ctx: Context, config: Config): void {
570
1499
  latency_ms: Date.now() - started,
571
1500
  })) as Record<string, never>
572
1501
  },
573
- presentCall: args => ({ card: 'generic', title: `飞行校验:${String((args.query as { callsign?: string })?.callsign ?? '')}`, kind: 'fetch', rawInput: args.query }),
1502
+ presentCall: args => ({ card: 'generic', title: `飞行校验:${args.callsign ?? ''}`, kind: 'fetch', rawInput: args }),
574
1503
  }))
575
1504
 
576
1505
  registerGuarded(defineTool({
577
- name: 'gotry_anything_search',
1506
+ name: 'gotry_flyai_search',
1507
+ description: routed('gotry_flyai_search',
1508
+ 'Live travel search through the Fliggy official FlyAI channel (read-only, no key; booking/comparison happens by the HUMAN on the jumpUrl page). '
1509
+ + 'kind="flight"|"train": from/origin is required; to/destination and date/dateStart+dateEnd are optional for official exploration, and exact-date results split 直达/中转. '
1510
+ + 'kind="hotel"|"marriott-hotel": to/destName=目的地中文, checkIn/checkOut (YYYY-MM-DD,成对可选——未定档期可不填先摸底). '
1511
+ + 'kind="poi": cityName=城市; kind="keyword"|"ai": query; kind="marriott-package": keyword. '
1512
+ + 'Hotel prices may be masked upstream (priceRaw like "¥7xx"): always present the mask as a range, and let the human open jumpUrl for the real price. '
1513
+ + 'Evidence [实时API:flyai@ts]. verdict=needs-setup (anonymous trial quota exhausted, upstream 429) is a CONFIG issue, not a search failure: surface the setup hint once, do NOT retry this tool this session — switch to gotry_session_search or web search. '
1514
+ + 'Errors (rate-limit Sentinel / invalid dates) degrade as structured errors with the upstream message — surface them, never guess.'),
1515
+ // D-30 第一刀(issue #112):query json blob → 平铺 typed 契约。内部 cliBin、
1516
+ // cliPrefixArgs、credentials、endpoint 不进入模型可见 schema;from/to/date 与
1517
+ // checkIn/checkOut 保留为兼容别名,adapter 的完整公共筛选面在同一平铺入口透传。
1518
+ parameters: {
1519
+ kind: { type: 'string', enum: [...FLYAI_TOOL_KINDS], required: true, description: '检索类型:flight/train/hotel/poi/keyword/ai/marriott-hotel/marriott-package' },
1520
+ from: { type: 'string', description: '兼容字段:机/火出发城市;等价于 origin' },
1521
+ to: { type: 'string', description: '兼容字段:机/火到达城市或酒店目的地;等价于 destination/destName' },
1522
+ date: { type: 'string', description: '兼容字段:机/火 exact-date YYYY-MM-DD;等价于 depDate' },
1523
+ origin: { type: 'string', description: '机/火出发城市或机场' },
1524
+ destination: { type: 'string', description: '机/火到达城市或机场' },
1525
+ depDate: { type: 'string', description: '机/火 exact-date YYYY-MM-DD' },
1526
+ dateStart: { type: 'string', description: '机/火日期范围起点 YYYY-MM-DD,与 dateEnd 成对' },
1527
+ dateEnd: { type: 'string', description: '机/火日期范围终点 YYYY-MM-DD,与 dateStart 成对' },
1528
+ depDateStart: { type: 'string', description: '机/火日期范围起点 YYYY-MM-DD' },
1529
+ depDateEnd: { type: 'string', description: '机/火日期范围终点 YYYY-MM-DD' },
1530
+ backDate: { type: 'string', description: '机票返程日期 YYYY-MM-DD' },
1531
+ journeyType: { type: 'integer', enum: [1, 2], description: '机票 1=直达,2=中转' },
1532
+ seatClassName: { type: 'string', description: '机/火舱位或坐席,逗号分隔' },
1533
+ transportNo: { type: 'string', description: '航班号或车次,逗号分隔' },
1534
+ transferCity: { type: 'string', description: '中转城市,逗号分隔' },
1535
+ depHourStart: { type: 'integer', description: '出发时段起点 0–23' },
1536
+ depHourEnd: { type: 'integer', description: '出发时段终点 0–23' },
1537
+ arrHourStart: { type: 'integer', description: '到达时段起点 0–23' },
1538
+ arrHourEnd: { type: 'integer', description: '到达时段终点 0–23' },
1539
+ totalDurationHour: { type: 'number', description: '机票总时长上限(小时)' },
1540
+ maxPrice: { type: 'number', description: '最高价格(CNY)' },
1541
+ sortType: { type: 'string', description: '机/火排序或万豪套餐 price_asc/price_desc' },
1542
+ destName: { type: 'string', description: '酒店/万豪酒店目的地' },
1543
+ checkIn: { type: 'string', description: '兼容字段:酒店入住日期 YYYY-MM-DD' },
1544
+ checkOut: { type: 'string', description: '兼容字段:酒店退房日期 YYYY-MM-DD' },
1545
+ checkInDate: { type: 'string', description: '酒店入住日期 YYYY-MM-DD' },
1546
+ checkOutDate: { type: 'string', description: '酒店退房日期 YYYY-MM-DD' },
1547
+ keyWords: { type: 'string', description: '酒店关键词;hotel/marriott-hotel 均支持' },
1548
+ poiName: { type: 'string', description: '酒店周边景点名' },
1549
+ hotelTypes: { type: 'string', description: '酒店类型,逗号分隔;仅 kind=hotel' },
1550
+ sort: { type: 'string', enum: ['distance_asc', 'rate_desc', 'price_asc', 'price_desc', 'no_rank'], description: '酒店排序' },
1551
+ hotelStars: { type: 'string', description: '酒店星级,1–5 逗号分隔;仅 kind=hotel' },
1552
+ hotelBedTypes: { type: 'string', description: '床型,逗号分隔' },
1553
+ cityName: { type: 'string', description: '景点所在城市;kind=poi 必填' },
1554
+ poiLevel: { type: 'integer', description: '景点等级 1–5' },
1555
+ keyword: { type: 'string', description: '景点关键词或万豪套餐单维度关键词' },
1556
+ category: { type: 'string', enum: [...FLYAI_POI_CATEGORIES], description: '景点官方闭集类别' },
1557
+ query: { type: 'string', description: 'keyword/ai 的查询词' },
1558
+ hotelBrands: { type: 'string', description: 'kind=marriott-hotel 的品牌关键词(与 hotelName 合并为官方 --key-words)' },
1559
+ hotelName: { type: 'string', description: '万豪酒店名;marriott-hotel 合并为 --key-words,marriott-package 使用 --hotel-name' },
1560
+ provinceOrCity: { type: 'string', description: '万豪套餐的省份或城市;与 keyword/hotelName 至少填写一项' },
1561
+ timeoutMs: { type: 'integer', description: '本次查询本地超时毫秒' },
1562
+ },
1563
+ output: { schema: { type: 'json' }, render: (_a, v) => [{ type: 'text', text: JSON.stringify({ ...(v as Record<string, unknown>), raw: undefined }) }] },
1564
+ async execute(args, exec) {
1565
+ const raw = args as unknown as FlyaiToolArgs
1566
+ const signal = (exec as { signal?: AbortSignal } | null | undefined)?.signal
1567
+ const built = flyaiToolQuery(raw, signal)
1568
+ if (built.error || !built.query) {
1569
+ return JSON.parse(JSON.stringify({ ok: false, verdict: 'error', summary: `未发起 FlyAI 查询:${built.error ?? '参数无效'}`, evidence: '[校验:gotry_flyai_search] rejected' })) as Record<string, never>
1570
+ }
1571
+ const q = built.query
1572
+ const todayYmd = new Date().toISOString().slice(0, 10)
1573
+ if ((q.kind === 'flight' || q.kind === 'train') && q.depDate && /^\d{4}-\d{2}-\d{2}$/.test(q.depDate) && q.depDate < todayYmd) {
1574
+ return JSON.parse(JSON.stringify({ ok: false, verdict: 'error', kind: q.kind, summary: `未发起查询:日期 ${q.depDate} 已是过去(今天 ${todayYmd})。`, evidence: '[校验:gotry_flyai_search] past exact date' })) as Record<string, never>
1575
+ }
1576
+ if ((q.kind === 'hotel' || q.kind === 'marriott-hotel') && q.checkInDate && q.checkOutDate
1577
+ && /^\d{4}-\d{2}-\d{2}$/.test(q.checkInDate) && /^\d{4}-\d{2}-\d{2}$/.test(q.checkOutDate)
1578
+ && (q.checkInDate < todayYmd || q.checkOutDate <= q.checkInDate)) {
1579
+ return JSON.parse(JSON.stringify({ ok: false, verdict: 'error', kind: q.kind, summary: `未发起查询:入住 ${q.checkInDate} / 退房 ${q.checkOutDate} 不是未来合法区间。`, evidence: '[校验:gotry_flyai_search] invalid stay dates' })) as Record<string, never>
1580
+ }
1581
+
1582
+ const itp = await runFlyaiEffect({ effect: 'FLYAI_SEARCH', params: q, signal })
1583
+ if (!itp.result) return declinedObservation('FLYAI_SEARCH', itp.trace)
1584
+ const r = itp.result as FlyaiResult
1585
+ await noteChannel('flyai', r.verdict)
1586
+ const fetchedAt = new Date().toISOString()
1587
+ if ((q.kind === 'flight' || q.kind === 'train') && q.origin && q.destination && q.depDate && !q.depDateStart && !q.depDateEnd) {
1588
+ const avMap = await loadAirlineAirportMap()
1589
+ await appendFacts(config.stateRoot ?? '.', factsFromFlyai({ kind: q.kind, origin: q.origin, destination: q.destination, date: q.depDate }, r, fetchedAt, avMap?.city_alias))
1590
+ } else if ((q.kind === 'hotel' || q.kind === 'marriott-hotel') && q.destName && q.checkInDate && q.checkOutDate) {
1591
+ await appendFacts(config.stateRoot ?? '.', factsFromHotel({
1592
+ source: q.kind === 'hotel' ? 'flyai-hotel' : 'flyai-marriott-hotel',
1593
+ destination: q.destName, checkIn: q.checkInDate, checkOut: q.checkOutDate,
1594
+ verdict: r.verdict, options: r.hotels?.length ?? 0, evidence: r.evidence, fetchedAt,
1595
+ }))
1596
+ }
1597
+ const intent = flyaiRoutingIntent(q.kind)
1598
+ const routing = r.verdict !== 'hit' && intent ? await routingField(intent, 'flyai') : {}
1599
+ return JSON.parse(JSON.stringify({ ...r, summary: flyaiToolSummary(q, r), ...routing })) as Record<string, never>
1600
+ },
1601
+ presentCall: args => ({ card: 'generic', title: `官方检索:${args.kind}`, kind: 'fetch', rawInput: args }),
1602
+ presentResult: (args, value) => {
1603
+ const isHotel = args.kind === 'hotel'
1604
+ const r = value as { ok?: boolean; options?: unknown[]; hotels?: unknown[] }
1605
+ const n = Math.max((r.options ?? []).length, (r.hotels ?? []).length)
1606
+ return { card: 'generic', title: `${isHotel ? '飞猪酒店' : '飞猪检索'}:${r.ok && n > 0 ? `${n} 条` : '降级'}`, content: [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }] }
1607
+ },
1608
+ }))
1609
+
1610
+ registerGuarded(createFlyaiSetupTool((seams.effect ?? interpretEffect) as unknown as EffectInterpreter, config.stateRoot))
1611
+
1612
+ registerGuarded(defineTool({
1613
+ name: 'gotry_session_login',
578
1614
  description:
1615
+ 'Productized login bootstrap for the account session channel (call this when gotry_session_search returns needs-login — the user never needs a terminal). ' + 'AUTO-DETECTION FIRST: it reads ticket-cookie NAMES before anything else — if the user already logged in (on the external site) it confirms instantly WITHOUT opening any page. '
1616
+ + 'OPENS the site login entry in the USER\'S OWN Chrome (foreground tab, left open for the user) and waits for the user to finish logging in on the external site. '
1617
+ + 'GoTry NEVER collects, stores, or transmits credentials: no passwords, no SMS codes, no cookie values — it only checks the boolean fact "already logged in" (reads cookie NAMES only, zero values). '
1618
+ + 'Transport: the GoTry Session Bridge browser extension (one-time install, ZERO Chrome system dialogs). '
1619
+ + `verdict logged-in (tickets detected) | pending (login tab opened, user not done yet — offer to re-check later) | needs-extension (one-time extension install: the verdict surfaces the Chrome Web Store installUrl as a clickable link for dsh UI to render — installation is a browser concern, not gotry's). `
1620
+ + 'Evidence [会话:<site>-login@ts].',
1621
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层
1622
+ parameters: {
1623
+ waitSeconds: { type: 'integer', description: '等待用户完成登录的上限秒数,默认 90,至多 300;不传用默认' },
1624
+ },
1625
+ output: { schema: { type: 'json' }, render: (_a, v) => [{ type: 'text', text: String((v as { evidence?: string }).evidence ?? JSON.stringify(v).slice(0, 600)) }] },
1626
+ async execute(args, _exec: unknown) {
1627
+ const q = unwrapQuery<{ waitSeconds?: number }>(args, 'waitSeconds')
1628
+ // D-23 收编(issue #115):登录引导入效应注册表(SESSION_LOGIN,浏览器族永不重试不熔断)
1629
+ const itpL = await interpretEffect({ effect: 'SESSION_LOGIN', params: { waitSeconds: q?.waitSeconds } })
1630
+ if (!itpL.result) return declinedObservation('SESSION_LOGIN', itpL.trace)
1631
+ const r = itpL.result
1632
+ const summary = r.verdict === 'logged-in'
1633
+ ? `${r.site} 登录完成确认(票据 cookie 名已检出,只读名字)。说明:登录是在携程官网、用你自己的浏览器完成的——gotry 全程未接触任何密码/验证码/cookie 值。现在可以继续会话检索了。${r.evidence}`
1634
+ : r.verdict === 'pending'
1635
+ ? `登录入口已在你的 Chrome 打开;请在弹出的标签页里正常登录携程(登录由你在官网完成,不属于 gotry)。完成后说一声"继续",我再确认。gotry 只检查"是否已登录",永不收集你的账号信息。${r.evidence}`
1636
+ : r.verdict === 'needs-extension'
1637
+ ? `需要一次性安装 GoTry Session Bridge 浏览器扩展:这是浏览器的事,gotry 不弹面板不开剪贴板——请直接在 Chrome 应用商店一键装(add-to-chrome 自动更新)。storeUrl=${EXTENSION_STORE_URL}. 装好即生效,装完后告诉我「重试」即可。${r.evidence}`
1638
+ : r.verdict === 'needs-attach'
1639
+ ? `cdp 车道需要一次性开启你 Chrome 的远程调试开关:在你的 Chrome 地址栏打开 chrome://inspect/#remote-debugging 并打开开关,然后说一声"重试"(默认走扩展车道,无需此步)。${r.evidence}`
1640
+ : `登录引导未完成:${r.error ?? '未知原因'} ${r.evidence}`
1641
+ return JSON.parse(JSON.stringify({ ...r, summary })) as Record<string, never>
1642
+ },
1643
+ presentCall: _args => ({ card: 'generic', title: '登录携程(用你自己的浏览器,不在 gotry 输入)', kind: 'fetch', rawInput: {} }),
1644
+ presentResult: (_args, value) => {
1645
+ const r = value as { verdict?: string; tickets?: string[]; installUrl?: string }
1646
+ const needsExt = r.verdict === 'needs-extension'
1647
+ const label = r.verdict === 'logged-in'
1648
+ ? `已登录(${(r.tickets ?? []).length} 票据)`
1649
+ : r.verdict === 'pending'
1650
+ ? '等待你在携程页面完成登录'
1651
+ : needsExt
1652
+ ? '🧩 需装 GoTry Session Bridge 扩展(浏览器商店一键装,自动更新)'
1653
+ : r.verdict ?? '降级'
1654
+ const content: Array<{ type: 'text'; text: string }> = [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }]
1655
+ // needs-extension:把商店 URL 渲成可点链接(浏览器自己当安装器,gotry 不插手)
1656
+ // dsh presentResult 若支持 actions 字段,URL 可被原生渲染;否则 content 里也保留文本兜底
1657
+ if (needsExt && r.installUrl) content.push({ type: 'text', text: `安装链接:${r.installUrl}` })
1658
+ return { card: 'generic', title: `账号登录:${label}`, content }
1659
+ },
1660
+ }))
1661
+
1662
+ registerGuarded(defineTool({
1663
+ name: 'gotry_session_search',
1664
+ description: routed('gotry_session_search',
1665
+ 'Search on the USER\'S OWN browser session (Ctrip kind="flight"(default)/"hotel"; 12306 kind="train" — public query face, no login needed). '
1666
+ + 'Consent gate: the FIRST call in a session asks the user via the runtime approval card; once granted it holds for the session, a refusal revokes it for the session (no repeat prompting). '
1667
+ + 'Transport: GoTry Session Bridge browser extension (one-time install) — the agent side never talks to Chrome debugging, ZERO system dialogs; read-only by construction (the extension never issues requests; it only passively forwards the site\'s own search responses; agent NEVER touches credentials/captcha; on captcha it stops and returns challenged). '
1668
+ + 'kind="flight": from/to 中文城市名 + date YYYY-MM-DD — sniffs the site search API for structured options. Evidence [会话:ctrip-flight@ts]. '
1669
+ + 'kind="hotel": to=目的地中文, cityId? = the numeric city= in a hotels.ctrip.com list URL (web-search it when the destination is outside the built-in city table), checkIn?/checkOut? (YYYY-MM-DD), adults?; hotel prices are the user\'s real logged-in prices. Evidence [会话:ctrip-hotel@ts]. '
1670
+ + 'kind="dida": Dida supplier-portal realtime hotel rates on the employee\'s own logged-in session (hotel-be portal integration line) — no from/to needed; the portal find page\'s own requests are sniffed passively. Rates carry ratePlanId/referenceNo for the server-side booking chain. Evidence [会话:dida-portal@ts]. '
1671
+ + 'kind="train": from/to/date(YYYY-MM-DD) + fromStationTelecode?/toStationTelecode? (three-letter codes in the kyfw query URL, for cities outside the built-in table) — 12306 left-ticket query (public face): train codes, times, durations, seat availability; the list API carries NO prices (prices live on the 12306 page). Evidence [会话:train-12306@ts]. '
1672
+ + 'verdict needs-login = call gotry_session_login (opens the Ctrip login entry in the user\'s own foreground tab — no terminal, no credentials through GoTry); '
1673
+ + `needs-extension = one-time browser-extension install (Chrome Web Store one-click, installUrl is also surfaced as a clickable link in the verdict field for dsh UI to render) — the DEFAULT transport; cdp (chrome://inspect remote debugging) is a diagnostic fallback only via GOTRY_SESSION_TRANSPORT=cdp. `
1674
+ + 'Rate-limited (≥30s between same-site calls; a challenged/timeout verdict means STOP — never retry, fall back to other tools).'),
1675
+ // D-30 第二刀(issue #112):query blob → 平铺 typed 契约(逐字段 schema 模型可见)。
1676
+ // 与 flyai 刀的差异:本工具三意图无公共 required 字段(kind 缺省=flight),根 schema 是
1677
+ // 隐式开放对象,宿主权无法用 required 拒 legacy blob——故保留 interpretArgs 容忍层
1678
+ // (docs/design/tool-orchestration-design.md §4③「interpretArgs 留作旧形态容忍层」),blob 调用在
1679
+ // execute 内归一后走原条件闸,结构化报错不崩。flyai 因 kind required 仍在宿主权即拒。
1680
+ parameters: {
1681
+ kind: { type: 'string', enum: ['flight', 'hotel', 'train', 'dida'], description: '默认 flight 机票;hotel 携程酒店(用户登录态真实价);train 12306 余票(公开面);dida 供应商门户实时价(员工登录态)' },
1682
+ from: { type: 'string', description: '出发城市中文(词表内),如 上海——kind=flight|train 必填' },
1683
+ to: { type: 'string', description: '到达城市中文——kind=flight|train 必填;kind=hotel 时为目的地(必填)' },
1684
+ date: { type: 'string', description: '出发日期 YYYY-MM-DD——kind=flight|train 必填,须为今天或未来' },
1685
+ cityId: { type: 'integer', description: '携程酒店 city= 数字,仅 kind=hotel;目的地码表外时 web 搜 hotels.ctrip.com list URL 取 city=' },
1686
+ checkIn: { type: 'string', description: '入住日 YYYY-MM-DD,仅 kind=hotel 可选' },
1687
+ checkOut: { type: 'string', description: '退房日 YYYY-MM-DD,仅 kind=hotel 可选' },
1688
+ adults: { type: 'integer', description: '成人数,仅 kind=hotel 可选' },
1689
+ fromStationTelecode: { type: 'string', description: '出发站三位电报码,仅 kind=train;城市码表外时填(kyfw 查询页 URL 里)' },
1690
+ toStationTelecode: { type: 'string', description: '到达站三位电报码,仅 kind=train,同上' },
1691
+ },
1692
+ output: { schema: { type: 'json' }, render: (_a, v) => [{ type: 'text', text: String((v as { summary?: string }).summary ?? JSON.stringify(v).slice(0, 600)) }] },
1693
+ async execute(args, _exec) {
1694
+ const selectedKind = resolveSessionSearchKind(args)
1695
+ if (!selectedKind.ok) return { ok: false, summary: selectedKind.reason } as const
1696
+ const q = { ...unwrapQuery<{ kind?: string; from?: string; to?: string; date?: string; cityId?: number | string; checkIn?: string; checkOut?: string; adults?: number; fromStationTelecode?: string; toStationTelecode?: string }>(args), kind: selectedKind.kind }
1697
+ const runSessionEffect = seams.effect ?? interpretEffect
1698
+ // ---- Dida 供应商门户(2026-09-09 实装;hotel-be portal integration 迁移线)----
1699
+ if (q.kind === 'dida') {
1700
+ const itpD = await runSessionEffect({
1701
+ effect: 'SESSION_DIDA_SEARCH',
1702
+ params: {
1703
+ auditPath: join(config.stateRoot ?? '.', 'gotry-state', 'session-incidents.jsonl'),
1704
+ },
1705
+ })
1706
+ if (!itpD.result) return declinedObservation('SESSION_DIDA_SEARCH', itpD.trace)
1707
+ const rD = itpD.result
1708
+ await noteChannel('session:dida-portal', rD.verdict)
1709
+ const topD = (rD.rates ?? []).slice(0, 8).map(x => `${x.hotelName ?? x.hotelId ?? '?'} ${x.roomName ?? ''} ${x.ratePlanId ?? ''} ${x.currency ?? ''}${x.price} 库存${x.inventory ?? '?'}${x.referenceNo ? ` ref=${x.referenceNo.slice(0, 12)}…` : ''}`)
1710
+ const summaryD = rD.verdict === 'hit'
1711
+ ? `Dida 门户实时价(员工本人登录态,被动嗅探)前 ${topD.length} 条(预订由服务端适配器凭 referenceNo 续链,gotry 不碰下单):\n${topD.join('\n')}\n${rD.evidence}`
1712
+ : rD.verdict === 'cooldown'
1713
+ ? `会话检索节律闸冷却中(两次会话检索需 ≥30s 间隔)——稍候重试或先用其他工具推进。${rD.evidence}`
1714
+ : rD.verdict === 'needs-login'
1715
+ ? `${rD.error ?? ''} ${rD.evidence}`
1716
+ : `Dida 门户会话检索未取回(${rD.verdict}):${rD.error ?? ''} ${rD.evidence}`
1717
+ return JSON.parse(JSON.stringify({
1718
+ ...rD, summary: summaryD,
1719
+ ...(rD.verdict !== 'hit' ? await routingField('search-hotel', 'session:dida-portal') : {}),
1720
+ })) as Record<string, never>
1721
+ }
1722
+ // ---- 会话酒店(2026-09-03 实装;2026-09-02 迪拜 session:用户要携程找酒店,会话面却只有机票)----
1723
+ // ---- 会话火车(2026-09-03 实装;12306 公开查询面,无登录闸)----
1724
+ if (q.kind === 'train') {
1725
+ if (!q.from || !q.to || !q.date) {
1726
+ return { ok: false, summary: 'kind=train 需要 from/to(中文城市/车站名)与 date(YYYY-MM-DD);城市电报码表外带 fromStationTelecode/toStationTelecode(kyfw 查询页 URL 里的三位码)' } as const
1727
+ }
1728
+ const nowT = new Date()
1729
+ const todayT = `${nowT.getFullYear()}-${String(nowT.getMonth() + 1).padStart(2, '0')}-${String(nowT.getDate()).padStart(2, '0')}`
1730
+ if (q.date < todayT) {
1731
+ return JSON.parse(JSON.stringify({
1732
+ ok: false, verdict: 'error',
1733
+ summary: `未发起查询:日期 ${q.date} 已是过去(今天 ${todayT}),过去不存在在售火车票。向用户确认日期后再查。`,
1734
+ })) as Record<string, never>
1735
+ }
1736
+ const itpT = await runSessionEffect({
1737
+ effect: 'SESSION_TRAIN_SEARCH',
1738
+ params: {
1739
+ from: q.from, to: q.to, date: q.date,
1740
+ fromStationTelecode: q.fromStationTelecode, toStationTelecode: q.toStationTelecode,
1741
+ auditPath: join(config.stateRoot ?? '.', 'gotry-state', 'session-incidents.jsonl'),
1742
+ },
1743
+ })
1744
+ if (!itpT.result) return declinedObservation('SESSION_TRAIN_SEARCH', itpT.trace)
1745
+ const rT = itpT.result
1746
+ await noteChannel('session:12306-train', rT.verdict)
1747
+ // #355:only the invocation-produced binding may enter the fact log;
1748
+ // malformed/transport/challenge states remain no-fact, and Y alone is
1749
+ // not rendered as bookable without a recognized available seat token.
1750
+ await appendFacts(config.stateRoot ?? '.', factsFromSessionTrain({ from: q.from, to: q.to, date: q.date }, rT, clock()))
1751
+ const topT = (rT.trains ?? []).slice(0, 10).map(t => `${t.trainCode} ${t.depTime}→${t.arrTime} 历时${Math.round(t.durationMin / 60 * 10) / 10}h ${t.canWebBuy === 'Y' && hasRecognizedAvailableSeat(t) ? '可订' : '余票待确认'}${Object.entries(t.seats).filter(([, v]) => v && v !== '--' && v !== '无').slice(0, 3).map(([k, v]) => `${k}:${v}`).join(' ')}`)
1752
+ const summaryT = rT.verdict === 'hit'
1753
+ ? `${q.from}→${q.to} ${q.date} 余票(12306 公开查询面,${(rT.trains ?? []).length} 趟)前 ${topT.length} 条(列表接口不含票价,票价以 12306 落地页为准):\n${topT.join('\n')}\n${rT.evidence}`
1754
+ : rT.verdict === 'cooldown'
1755
+ ? `会话火车检索节律闸冷却中(两次会话检索需 ≥30s 间隔)——稍候重试或先用其他工具推进。${rT.evidence}`
1756
+ : `会话火车检索未取回(${rT.verdict}):${rT.error ?? ''} ${rT.evidence}`
1757
+ return JSON.parse(JSON.stringify({
1758
+ ...rT, summary: summaryT,
1759
+ ...(rT.verdict !== 'hit' ? await routingField('search-train', 'session:12306-train') : {}),
1760
+ })) as Record<string, never>
1761
+ }
1762
+ if (q.kind === 'hotel') {
1763
+ if (!q.to) {
1764
+ return { ok: false, summary: 'kind=hotel 需要 to(目的地中文;城市码表外带 cityId=携程酒店 list 页 URL 里的 city= 数字)' } as const
1765
+ }
1766
+ const itp = await runSessionEffect({
1767
+ effect: 'SESSION_HOTEL_SEARCH',
1768
+ params: {
1769
+ to: q.to, cityId: q.cityId, checkIn: q.checkIn, checkOut: q.checkOut, adults: q.adults,
1770
+ auditPath: join(config.stateRoot ?? '.', 'gotry-state', 'session-incidents.jsonl'),
1771
+ },
1772
+ })
1773
+ if (!itp.result) return declinedObservation('SESSION_HOTEL_SEARCH', itp.trace)
1774
+ const r = itp.result
1775
+ await noteChannel('session:ctrip-hotel', r.verdict)
1776
+ // D-26(issue #118):exact-date 会话酒店 hit/miss 落账(摸底无档期不落;cooldown 是节律闸非结论,不落)
1777
+ if (r.verdict === 'hit' || r.verdict === 'miss') {
1778
+ await appendFacts(config.stateRoot ?? '.', factsFromHotel({
1779
+ source: 'session:ctrip-hotel', destination: q.to ?? '', checkIn: q.checkIn, checkOut: q.checkOut,
1780
+ verdict: r.verdict, options: r.hotels?.length ?? 0, evidence: r.evidence, fetchedAt: new Date().toISOString(),
1781
+ }))
1782
+ }
1783
+ const top = (r.hotels ?? []).slice(0, 8).map(h => `${h.name}${h.star ? `(${h.star}星)` : ''} ${h.priceRaw ?? (h.price > 0 ? `¥${h.price}` : '价待询')}${h.score ? ` 评分${h.score}` : ''}`)
1784
+ const summary = r.verdict === 'hit'
1785
+ ? `${q.to} 酒店(携程,用户本人登录态,真实价)前 ${top.length} 家(预订以 jumpUrl 落地页为准):\n${top.join('\n')}\n${r.evidence}`
1786
+ : r.verdict === 'cooldown'
1787
+ ? `会话酒店检索节律闸冷却中(两次会话检索需 ≥30s 间隔)——稍候重试或先用其他工具推进。${r.evidence}`
1788
+ : `会话酒店检索未取回(${r.verdict}):${r.error ?? ''} ${r.evidence}`
1789
+ return JSON.parse(JSON.stringify({
1790
+ ...r, summary,
1791
+ ...(r.verdict !== 'hit' ? await routingField('search-hotel', 'session:ctrip-hotel') : {}),
1792
+ })) as Record<string, never>
1793
+ }
1794
+ if (!q.from || !q.to || !q.date) {
1795
+ return { ok: false, summary: '需要 from/to(中文城市名,词表内)与 date(YYYY-MM-DD);酒店/火车检索分别用 kind=hotel / kind=train' } as const
1796
+ }
1797
+ // 效应解译层(ADR-18):SESSION 通道策略=永不重试/不熔断,节律闸在渠道内;
1798
+ // 解译器只做分发与证据拼装,verdict 语义(risk 型 needs-login/challenged)原样透传
1799
+ const itp = await runSessionEffect({
1800
+ effect: 'SESSION_FLIGHT_SEARCH',
1801
+ params: {
1802
+ from: q.from, to: q.to, date: q.date,
1803
+ // ADR-15 收尾:ReadGuard 审计在生产工具路径同样落盘(此前仅测试传隔离 stateRoot 才有 JSONL)
1804
+ auditPath: join(config.stateRoot ?? '.', 'gotry-state', 'session-incidents.jsonl'),
1805
+ },
1806
+ })
1807
+ if (!itp.result) return declinedObservation('SESSION_FLIGHT_SEARCH', itp.trace)
1808
+ const r = itp.result
1809
+ await noteChannel('session:ctrip-flight', r.verdict)
1810
+ // issue #46 事实落账(ADR-19):会话面 exact-date 结论同样进事实注册表(独立 source 并列标注)
1811
+ const avMapS = await loadAirlineAirportMap()
1812
+ await appendFacts(config.stateRoot ?? '.', factsFromSession({ origin: q.from, destination: q.to, date: q.date }, r, new Date().toISOString(), avMapS?.city_alias))
1813
+ const top = (r.options ?? []).slice(0, 8).map(o => `${o.flightNo} ${o.airline} ${o.depDateTime.slice(11, 16)}→${o.arrDateTime.slice(11, 16)} ¥${o.price}`)
1814
+ const summary = r.verdict === 'hit'
1815
+ ? `${q.from}→${q.to} ${q.date} 会话检索(携程,用户本人登录态)前 ${top.length} 条:\n${top.join('\n')}\n${r.evidence}`
1816
+ : `会话检索未取回(${r.verdict}):${r.error ?? ''} ${r.evidence}`
1817
+ return JSON.parse(JSON.stringify({
1818
+ ...r, summary,
1819
+ ...(r.verdict !== 'hit' ? await routingField('search-flight', 'session:ctrip-flight') : {}),
1820
+ })) as Record<string, never>
1821
+ },
1822
+ presentCall: args => {
1823
+ const selected = resolveSessionSearchKind(args)
1824
+ const kind = selected.ok ? selected.kind : undefined
1825
+ const raw = args as { to?: unknown; from?: unknown }
1826
+ const callTitle = kind === 'hotel' ? `会话酒店:${raw.to ?? ''}` : kind === 'train' ? `会话火车:${raw.from ?? ''}` : kind === 'dida' ? '会话酒店:Dida 门户实时价' : `会话检索:${raw.from ?? ''}`
1827
+ return { card: 'generic', title: callTitle, kind: 'fetch', rawInput: args }
1828
+ },
1829
+ presentResult: (args, value) => {
1830
+ const selected = resolveSessionSearchKind(args)
1831
+ const kind = selected.ok ? selected.kind : undefined
1832
+ const r = value as { verdict?: string; options?: unknown[]; hotels?: unknown[]; installUrl?: string }
1833
+ const isHotel = kind === 'hotel'
1834
+ const n = Math.max((r.options ?? []).length, (r.hotels ?? []).length)
1835
+ const needsExt = r.verdict === 'needs-extension'
1836
+ const label = r.verdict === 'hit'
1837
+ ? `会话 ${n} 条`
1838
+ : r.verdict === 'needs-login'
1839
+ ? '需登录'
1840
+ : needsExt
1841
+ ? '🧩 需装 GoTry Session Bridge 扩展(浏览器商店一键装,自动更新)'
1842
+ : r.verdict ?? '降级'
1843
+ const content: Array<{ type: 'text'; text: string }> = [{ type: 'text', text: String((value as { summary?: string }).summary ?? '') }]
1844
+ if (needsExt && r.installUrl) content.push({ type: 'text', text: `安装链接:${r.installUrl}` })
1845
+ const face = kind === 'hotel' ? '会话酒店' : kind === 'train' ? '会话火车' : kind === 'dida' ? '会话酒店:Dida' : '会话检索'
1846
+ return { card: 'generic', title: `${face}:${label}`, content }
1847
+ },
1848
+ }))
1849
+
1850
+ registerGuarded(defineTool({
1851
+ name: 'gotry_anything_search',
1852
+ description: routed('gotry_anything_search',
579
1853
  'Travel-domain search via hotel-byte CLI → hotel-be Anything (cities/hotels/destinations) — NOT general web search; for general internet facts use gotry_agent_reach. ' +
580
1854
  'Mixed destinations (cities / metropolitan areas / high-level regions) + hotels in one call. ' +
581
1855
  'Returns candidates with type, name, optional coordinates and hotel-id. ' +
582
1856
  'Three-valued semantics: hit = ≥1 candidate; miss = 0 candidates (try synonyms or contentType=city/hotel); ' +
583
1857
  'unavailable = hbcli failed (degraded, never blocks). ' +
584
1858
  'Use as the first stop when the user mentions a place/city/hotel name and you need to ground it in real catalog data ' +
585
- '(OpenFlights skeleton tells you connectivity; Anything tells you what EXISTS at a city/region).',
1859
+ '(OpenFlights skeleton tells you connectivity; Anything tells you what EXISTS at a city/region). Independent read-only: safe in the same step as other independent searches; host abort is forwarded to the process tree.'),
1860
+ // 并发安全(issue #519):同 hotel_search,只读 + append-only 延迟日志 + 宿主取消信号。
1861
+ isConcurrencySafe: () => true,
1862
+ // D-30 第四刀(issue #112):平铺 typed;keyword required → 宿主权即拒
586
1863
  parameters: {
587
- query: {
588
- type: 'json',
589
- required: true,
590
- description: '{ keyword: "<搜索关键词>", contentType?: "city"|"hotel", parentDestinationId?: "?", timeoutMs?: 12000 }',
591
- },
1864
+ keyword: { type: 'string', required: true, description: '搜索关键词' },
1865
+ contentType: { type: 'string', enum: ['city', 'hotel'], description: '内容类型(缺省由上游推断)' },
1866
+ parentDestinationId: { type: 'string', description: '父目的地 id(上游形态)' },
1867
+ timeoutMs: { type: 'integer', description: '超时毫秒,默认 12000' },
592
1868
  },
593
1869
  output: {
594
1870
  schema: { type: 'json' },
595
1871
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
596
1872
  },
597
- async execute(args: { query: unknown }, _exec: unknown) {
598
- const q = unwrapQuery<{ keyword: string; contentType?: 'city' | 'hotel'; parentDestinationId?: string | number; timeoutMs?: number }>(args, 'keyword')
1873
+ async execute(args, _exec: unknown) {
1874
+ const q = args
1875
+ const rawQuery = String(q.keyword ?? '')
599
1876
  const started = Date.now()
1877
+ const execSignal = (_exec as { signal?: AbortSignal } | undefined)?.signal
600
1878
  if (!q.keyword) {
601
1879
  return JSON.parse(JSON.stringify({ ok: false, verdict: 'error', summary: 'keyword 必填', evidence: '[hbcli-anything@error] empty' })) as Record<string, never>
602
1880
  }
603
- const r = await anythingSearch(q)
1881
+ // hbcliBin 直通 config(缺省 'hbcli',能力层按已知安装位回退)——issue #195 教训:
1882
+ // 此前 params 只透 q,config.hbcliBin 永远到不了能力层
1883
+ const itpA = await interpretEffect({ effect: 'ANYTHING_SEARCH', params: { ...q, hbcliBin: config.hbcliBin, signal: execSignal } })
1884
+ if (!itpA.result) return declinedObservation('ANYTHING_SEARCH', itpA.trace)
1885
+ const r = itpA.result
604
1886
  const dir = await ensureStateDir(config.stateRoot)
605
1887
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, `anything:${r.via}`).catch(() => {})
606
1888
  const top5 = (r.hits ?? []).slice(0, 5)
607
1889
  const summary = r.verdict === 'hit'
608
- ? `${q.keyword} → hit (${r.hits?.length ?? 0} 候选项)\n${top5.map((h, i) => ` ${i + 1}. [${h.type}] ${h.name}${h.latitude !== undefined && h.longitude !== undefined ? ` @ (${h.latitude.toFixed(3)},${h.longitude.toFixed(3)})` : ''}`).join('\n')}\n${r.evidence}`
1890
+ ? `${q.keyword} → hit (${r.hits?.length ?? 0} 候选项)\n${top5.map((h, i) => ` ${i + 1}. [${h.type}] ${h.name}${h.star ? ` ${h.star}★` : ''}${h.latitude !== undefined && h.longitude !== undefined ? ` @ (${h.latitude.toFixed(3)},${h.longitude.toFixed(3)})` : ''}${h.hotelId ? ` hotelId=${h.hotelId}` : h.destinationId ? ` destinationId=${h.destinationId}` : ''}`).join('\n')}\n${r.evidence}`
609
1891
  : r.verdict === 'miss'
610
1892
  ? `${q.keyword} → miss (酒店-be 一切正常但无候选)\n${r.evidence}`
611
1893
  : `${q.keyword} → unavailable (${r.error})\n${r.evidence}`
@@ -616,7 +1898,7 @@ export function apply(ctx: Context, config: Config): void {
616
1898
  latency_ms: Date.now() - started,
617
1899
  })) as Record<string, never>
618
1900
  },
619
- presentCall: args => ({ card: 'generic', title: `Anything search:${String((args.query as { keyword?: string })?.keyword ?? '')}`, kind: 'search', rawInput: args.query }),
1901
+ presentCall: args => ({ card: 'generic', title: `Anything search:${args.keyword ?? ''}`, kind: 'search', rawInput: args }),
620
1902
  presentResult: (_args, value) => {
621
1903
  const r = value as { hits?: unknown[]; total_candidates?: number; verdict?: string; keyword?: string; summary?: string }
622
1904
  const n = Array.isArray(r.hits) ? r.hits.length : (r.total_candidates ?? 0)
@@ -630,30 +1912,30 @@ export function apply(ctx: Context, config: Config): void {
630
1912
 
631
1913
  registerGuarded(defineTool({
632
1914
  name: 'gotry_web_search',
633
- description:
1915
+ description: routed('gotry_web_search',
634
1916
  'Read any public URL as markdown (Jina Reader, free, no key). ' +
635
1917
  'Use as the "last mile" web reader when hotel-be Anything or gotry tools lack the answer. ' +
636
1918
  'NOT a general-purpose search engine — only fetches a URL you already know. ' +
637
1919
  'Three-valued: ok / error(非法 URL/超时)/not-reachable(r.jina.ai 不可用).' +
638
- 'Contract with gotry capabilities/anything.ts: 同构(L4 证据链 + 降级不阻塞 + 三值)。',
1920
+ 'Contract with gotry capabilities/anything.ts: 同构(L4 证据链 + 降级不阻塞 + 三值)。'),
1921
+ // D-30 第四刀(issue #112):平铺 typed;url required → 宿主权即拒(字符串 blob 形态退役)
639
1922
  parameters: {
640
- query: {
641
- type: 'json',
642
- required: true,
643
- description: '{ url: "https://example.com", timeoutMs?: 20000 }',
644
- },
1923
+ url: { type: 'string', required: true, description: '完整 URL,https://…' },
1924
+ timeoutMs: { type: 'integer', description: '超时毫秒,默认 20000' },
645
1925
  },
646
1926
  output: {
647
1927
  schema: { type: 'json' },
648
1928
  render: (_args, value) => [{ type: 'text', text: String((value as { content?: string }).content?.slice(0, 800) ?? JSON.stringify(value).slice(0, 800)) }],
649
1929
  },
650
- async execute(args: { query: unknown }, _exec: unknown) {
651
- const q = unwrapQuery<{ url?: string; timeoutMs?: number }>(args, 'url')
1930
+ async execute(args, _exec: unknown) {
1931
+ const q = args
652
1932
  const started = Date.now()
653
1933
  if (!q.url) {
654
1934
  return JSON.parse(JSON.stringify({ ok: false, summary: 'url 必填', evidence: '[agent-reach:error] empty url' })) as Record<string, never>
655
1935
  }
656
- const r = await readUrl({ url: q.url, timeoutMs: q.timeoutMs })
1936
+ const itpW = await interpretEffect({ effect: 'WEB_READ', params: { url: q.url, timeoutMs: q.timeoutMs } })
1937
+ if (!itpW.result) return declinedObservation('WEB_READ', itpW.trace)
1938
+ const r = itpW.result
657
1939
  const dir = await ensureStateDir(config.stateRoot)
658
1940
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, `agent-reach:${r.via}`).catch(() => {})
659
1941
  const summary = r.ok
@@ -665,7 +1947,7 @@ export function apply(ctx: Context, config: Config): void {
665
1947
  latency_ms: Date.now() - started,
666
1948
  })) as Record<string, never>
667
1949
  },
668
- presentCall: args => ({ card: 'generic', title: `读网页:${String((args.query as { url?: string })?.url ?? '')}`, kind: 'fetch', rawInput: args.query }),
1950
+ presentCall: args => ({ card: 'generic', title: `读网页:${args.url ?? ''}`, kind: 'fetch', rawInput: args }),
669
1951
  }))
670
1952
 
671
1953
  registerGuarded(defineTool({
@@ -675,23 +1957,23 @@ export function apply(ctx: Context, config: Config): void {
675
1957
  'If yt-dlp is installed on this machine, returns the subtitle text (vtt, zh-Hans/zh/en preference). ' +
676
1958
  'If NOT installed, degrades gracefully with install instructions — never blocks. ' +
677
1959
  'Evidence chain: [agent-reach:yt-dlp@ts] / [@not-installed@ts].',
1960
+ // D-30 第四刀(issue #112):平铺 typed;url required → 宿主权即拒
678
1961
  parameters: {
679
- query: {
680
- type: 'json',
681
- required: true,
682
- description: '{ url: "https://www.youtube.com/watch?v=...", lang?: "zh-Hans,zh,en" }',
683
- },
1962
+ url: { type: 'string', required: true, description: '视频页 URL(youtube 等)' },
1963
+ lang: { type: 'string', description: '字幕语言优先级,如 zh-Hans,zh,en' },
684
1964
  },
685
1965
  output: {
686
1966
  schema: { type: 'json' },
687
1967
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 600)) }],
688
1968
  },
689
- async execute(args: { query: unknown }, _exec: unknown) {
690
- const q = unwrapQuery<{ url?: string; lang?: string }>(args, 'url')
1969
+ async execute(args, _exec: unknown) {
1970
+ const q = args
691
1971
  if (!q.url) {
692
1972
  return JSON.parse(JSON.stringify({ ok: false, summary: 'url 必填' })) as Record<string, never>
693
1973
  }
694
- const r = await videoSubtitle({ url: q.url, lang: q.lang })
1974
+ const itpV = await interpretEffect({ effect: 'VIDEO_SUBTITLE', params: { url: q.url, lang: q.lang } })
1975
+ if (!itpV.result) return declinedObservation('VIDEO_SUBTITLE', itpV.trace)
1976
+ const r = itpV.result
695
1977
  const summary = r.verdict === 'found'
696
1978
  ? `${q.url} 字幕提取成功 (${r.latencyMs}ms)\n${r.evidence}\n---\n${(r.subtitles ?? '').slice(0, 800)}`
697
1979
  : r.verdict === 'not-installed'
@@ -703,7 +1985,7 @@ export function apply(ctx: Context, config: Config): void {
703
1985
  latency_ms: r.latencyMs,
704
1986
  })) as Record<string, never>
705
1987
  },
706
- presentCall: args => ({ card: 'generic', title: `视频字幕:${String((args.query as { url?: string })?.url ?? '')}`, kind: 'fetch', rawInput: args.query }),
1988
+ presentCall: args => ({ card: 'generic', title: `视频字幕:${args.url ?? ''}`, kind: 'fetch', rawInput: args }),
707
1989
  }))
708
1990
 
709
1991
  registerGuarded(defineTool({
@@ -713,23 +1995,23 @@ export function apply(ctx: Context, config: Config): void {
713
1995
  'If gh is installed and authenticated, returns repos with name/description/stars/url. ' +
714
1996
  'If NOT installed, degrades with install instructions — never blocks. ' +
715
1997
  'Evidence chain: [agent-reach:gh@ts] / [@not-installed@ts].',
1998
+ // D-30 第四刀(issue #112):平铺 typed;query required → 宿主权即拒(顶层字段与旧内层同名,形态从对象变字符串)
716
1999
  parameters: {
717
- query: {
718
- type: 'json',
719
- required: true,
720
- description: '{ query: "agent-reach", limit?: 5 }',
721
- },
2000
+ query: { type: 'string', required: true, description: 'GitHub 搜索关键词,如 agent-reach' },
2001
+ limit: { type: 'integer', description: '结果数上限,默认 5' },
722
2002
  },
723
2003
  output: {
724
2004
  schema: { type: 'json' },
725
2005
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 600)) }],
726
2006
  },
727
- async execute(args: { query: unknown }, _exec: unknown) {
728
- const q = unwrapQuery<{ query?: string; limit?: number }>(args, 'query')
2007
+ async execute(args, _exec: unknown) {
2008
+ const q = args
729
2009
  if (!q.query) {
730
2010
  return JSON.parse(JSON.stringify({ ok: false, summary: 'query 必填' })) as Record<string, never>
731
2011
  }
732
- const r = await githubSearch({ query: q.query, limit: q.limit })
2012
+ const itpG = await interpretEffect({ effect: 'GITHUB_SEARCH', params: { query: q.query, limit: q.limit } })
2013
+ if (!itpG.result) return declinedObservation('GITHUB_SEARCH', itpG.trace)
2014
+ const r = itpG.result
733
2015
  const summary = r.verdict === 'found'
734
2016
  ? `${q.query} → ${r.repos?.length ?? 0} repos\n${(r.repos ?? []).map((x, i) => ` ${i + 1}. ${x.name} ★${x.stars ?? '?'} — ${(x.description ?? '').slice(0, 60)}`).join('\n')}\n${r.evidence}`
735
2017
  : r.verdict === 'not-installed'
@@ -741,7 +2023,7 @@ export function apply(ctx: Context, config: Config): void {
741
2023
  latency_ms: r.latencyMs,
742
2024
  })) as Record<string, never>
743
2025
  },
744
- presentCall: args => ({ card: 'generic', title: `GitHub 搜索:${String((args.query as { query?: string })?.query ?? '')}`, kind: 'search', rawInput: args.query }),
2026
+ presentCall: args => ({ card: 'generic', title: `GitHub 搜索:${args.query ?? ''}`, kind: 'search', rawInput: args }),
745
2027
  }))
746
2028
 
747
2029
  registerGuarded(defineTool({
@@ -755,28 +2037,35 @@ export function apply(ctx: Context, config: Config): void {
755
2037
  'Action "status" runs the real `agent-reach doctor` (.venv/bin/agent-reach). ' +
756
2038
  'Channels needing cookies/setup return the upstream check() guidance verbatim — do NOT give up there: hand the user the exact configure command, then offer to re-check. ' +
757
2039
  'Evidence chain: [agent-reach:<channel>.<method>@ts].',
2040
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层。
2041
+ // action 不设 enum:反射桥按 D-4a' 透传上游新增渠道/方法,gotry 零改动(生态开放面)
758
2042
  parameters: {
759
- query: {
760
- type: 'json',
761
- required: true,
762
- description: '{ action: "status" } 或 { action: "reach", channel: "<上游渠道名,如 web/v2ex/xueqiu>", method: "<上游方法名,如 read/get_hot_topics/get_stock_quote>", args?: "<空格分隔参数>" }',
763
- },
2043
+ action: { type: 'string', description: 'status(默认,无 channel 时)或 reach' },
2044
+ channel: { type: 'string', description: '上游渠道名,如 web/v2ex/xueqiu(action=reach 时)' },
2045
+ method: { type: 'string', description: '上游方法名,如 read/get_hot_topics/get_stock_quote' },
2046
+ args: { type: 'string', description: '空格分隔参数' },
2047
+ timeoutMs: { type: 'integer', description: '超时毫秒' },
764
2048
  },
765
2049
  output: {
766
2050
  schema: { type: 'json' },
767
2051
  render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
768
2052
  },
769
- async execute(args: { query: unknown }, _exec: unknown) {
770
- const q = unwrapQuery<{ action?: string; channel?: string; method?: string; args?: string; timeoutMs?: number }>(args, 'channel')
2053
+ async execute(args, _exec: unknown) {
2054
+ const q = unwrapQuery<{ action?: string; channel?: string; method?: string; args?: string; timeoutMs?: number }>(args)
771
2055
  const started = Date.now()
772
2056
  const dir = await ensureStateDir(config.stateRoot)
773
2057
 
2058
+ // D-23 收编(issue #115):status/reach 两分支收敛为单一 AGENT_REACH 效应——
2059
+ // 解译器横切(trace/declined 面)统一,渲染逻辑留在工具层不变
2060
+ const itpAR = await interpretEffect({ effect: 'AGENT_REACH', params: { action: q.action, channel: q.channel, method: q.method, args: q.args, timeoutMs: q.timeoutMs } })
2061
+ if (!itpAR.result) return declinedObservation('AGENT_REACH', itpAR.trace)
2062
+
774
2063
  if (q.action === 'status' || (!q.action && !q.channel)) {
775
- const st = await reachStatus(q.timeoutMs)
2064
+ const st = itpAR.result as Awaited<ReturnType<typeof reachStatus>>
776
2065
  await recordLatency(join(dir, 'bridge-latency.jsonl'), Date.now() - started, 'agent-reach:doctor').catch(() => {})
777
2066
  const summary = st.via === 'agent-reach-cli'
778
2067
  ? `Agent Reach doctor(上游 CLI,原样透传):\n${st.output}\n${st.evidence}`
779
- : `Agent Reach 未装:\n${st.output}\n${st.evidence}`
2068
+ : `Agent Reach 未装配(.venv 缺失)——可选依赖,机/酒/网页社媒读取之外的工具不受影响。\n补装:终端跑 npx @danceiny/gotry doctor --fix;整体依赖状态可调 gotry_doctor 工具查看。\n${st.evidence}`
780
2069
  return JSON.parse(JSON.stringify({
781
2070
  ok: st.ok, via: st.via, output: st.output, evidence: st.evidence, summary,
782
2071
  latency_ms: Date.now() - started,
@@ -786,7 +2075,7 @@ export function apply(ctx: Context, config: Config): void {
786
2075
  if (!q.channel || !q.method) {
787
2076
  return JSON.parse(JSON.stringify({ ok: false, summary: 'channel 与 method 必填(或 action=status);清单可先随便调一次,inventory 会带回上游渠道/方法表' })) as Record<string, never>
788
2077
  }
789
- const r = await reach({ channel: q.channel, method: q.method, args: q.args, timeoutMs: q.timeoutMs })
2078
+ const r = itpAR.result as Awaited<ReturnType<typeof reach>>
790
2079
  // 长结果干净截断:数组按条目边界保留(dsh 工具上限会拦腰断 JSON,模型只能看到半条)
791
2080
  const dataStr = (v: unknown): unknown => {
792
2081
  if (Array.isArray(v)) {
@@ -811,7 +2100,7 @@ export function apply(ctx: Context, config: Config): void {
811
2100
  : r.verdict === 'needs-setup'
812
2101
  ? `${q.channel}.${q.method} → 需配置(上游 check() 原话): ${r.setup ?? ''}\n${r.evidence}`
813
2102
  : r.verdict === 'not-installed'
814
- ? `${q.channel}.${q.method} → 上游未装: ${r.setup ?? ''}\n${r.evidence}`
2103
+ ? `${q.channel}.${q.method} → 上游未装配(可选依赖): ${r.setup ?? ''}\n整体依赖状态可调 gotry_doctor 查看;补装: npx @danceiny/gotry doctor --fix\n${r.evidence}`
815
2104
  : `${q.channel}.${q.method} → ${r.error ?? 'error'}${r.inventory ? `\n上游清单: ${JSON.stringify(r.inventory).slice(0, 1200)}` : ''}\n${r.evidence}`
816
2105
  return JSON.parse(JSON.stringify({
817
2106
  ok: r.ok, channel: r.channel, method: q.method, verdict: r.verdict,
@@ -820,10 +2109,10 @@ export function apply(ctx: Context, config: Config): void {
820
2109
  latency_ms: Date.now() - started,
821
2110
  })) as Record<string, never>
822
2111
  },
823
- presentCall: args => ({ card: 'generic', title: `Agent Reach:${String((args.query as { channel?: string; method?: string })?.channel ?? '')}.${String((args.query as { method?: string })?.method ?? 'status')}`, kind: 'fetch', rawInput: args.query }),
2112
+ presentCall: args => ({ card: 'generic', title: `Agent Reach:${String(args.channel ?? '')}.${String(args.method ?? 'status')}`, kind: 'fetch', rawInput: args }),
824
2113
  presentResult: (args, value) => {
825
2114
  const r = value as { verdict?: string; summary?: string }
826
- const q = (args.query as { channel?: string; method?: string }) ?? {}
2115
+ const q = (args as { channel?: string; method?: string }) ?? {}
827
2116
  const icon = r.verdict === 'found' ? '✅' : r.verdict === 'needs-setup' ? '🔧' : r.verdict === 'not-installed' ? '📦' : '❌'
828
2117
  return {
829
2118
  card: 'generic',
@@ -832,4 +2121,598 @@ export function apply(ctx: Context, config: Config): void {
832
2121
  }
833
2122
  },
834
2123
  }))
2124
+
2125
+ // ---- 依赖体检面(2026-09-02 迪拜 session 复盘:可选依赖未装配时,LLM 需要一个
2126
+ // 统一的状态入口来「显示状态 + 引导补装」,而不是在 not-installed 里各自摸索)----
2127
+
2128
+ registerGuarded(defineTool({
2129
+ name: 'gotry_doctor',
2130
+ description:
2131
+ 'Check optional-dependency health for ALL gotry tools (read-only by default). Coverage: GoTry Session Bridge extension / Agent Reach (.venv) / hbcli (hotel realtime) / FlyAI key + recent trial-quota exhaustion time / dsh-calendar mount state / dsh-better-sidebar / dsh-map-tools / dsh-tool-ask-user. '
2132
+ + 'Call this when ANY gotry tool returns not-installed / needs-setup, when the user asks 「体检/依赖状态/工具为什么不可用」, or BEFORE leaning on a channel for a plan. '
2133
+ + 'Returns per-item status (ok/degraded/missing) with exact fix commands. '
2134
+ + 'Action=diagnose (default): pure read-only — never installs anything, only renders the report. '
2135
+ + 'Action=repair: optional autonomous repair — only attempts items the user named via `items` (stable doctor item ids, e.g. ["agent-reach","sidebar"]); empty/missing items means repair every auto-repairable gap. Items requiring browser-store install / credentials / API key / profile config / package reinstall / Node upgrade are NEVER auto-installed — they are reported as needs-user-action / unavailable and require the user to handle them. '
2136
+ + 'Repair flow is observable: diagnosis → scope-keyed plan (selected auto-repairable items + skipped) → runtime approval card (per agent, per scope; same agent+scope reuses approval, different scope re-asks) → execute installer → recheck → per-item installed/failed with retry command. '
2137
+ + 'Rejected/cancelled = no execution; unavailable approval channel = no execution (clear structured outcome). LLM keys are the dsh host\'s business and are deliberately out of scope. '
2138
+ + 'A markdown report is rendered for the workspace (gotry-state/doctor-report.md) so the sidebar workbench can preview it.',
2139
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层
2140
+ // issue #284 增量:action + items 两参数;默认 diagnose 保持读-only 不变(向后兼容)
2141
+ parameters: {
2142
+ action: { type: 'string', enum: ['diagnose', 'repair'], description: '默认 diagnose;repair 时按 items 范围补装可选依赖,user-action / unavailable 项永不冒充 auto' },
2143
+ items: { type: 'array', items: { type: 'string', enum: ['node', 'extension', 'agent-reach', 'hbcli', 'flyai', 'sidebar', 'llm-key', 'calendar', 'map-tools', 'ask-user'] }, description: 'repair 时的 doctor item id 范围;空 = 全部 auto-repairable' },
2144
+ writeReport: { type: 'boolean', description: '默认 true,把 markdown 报告写进 gotry-state/doctor-report.md(侧栏工作台可预览)' },
2145
+ },
2146
+ output: {
2147
+ schema: { type: 'json' },
2148
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 900)) }],
2149
+ },
2150
+ async execute(args, _exec: unknown) {
2151
+ const q = unwrapQuery<{ action?: 'diagnose' | 'repair'; items?: string[]; writeReport?: boolean }>(args, 'action')
2152
+ const action = q?.action === 'repair' ? 'repair' : 'diagnose'
2153
+ const check = seams.doctor?.check ?? runDoctorChecks
2154
+ const report = await check({ stateRoot: config.stateRoot ?? '.' })
2155
+
2156
+ // repair 时必须把复检后的报告写盘,避免侧栏仍显示修复前状态。
2157
+ let reportPath: string | undefined
2158
+ const writeReport = async (current: typeof report): Promise<void> => {
2159
+ if (q?.writeReport === false) return
2160
+ try {
2161
+ const { writeFile } = await import('node:fs/promises')
2162
+ const dir = await ensureStateDir(config.stateRoot)
2163
+ reportPath = join(dir, 'doctor-report.md')
2164
+ await writeFile(reportPath, renderDoctorReportMd(current), 'utf-8')
2165
+ } catch { reportPath = undefined }
2166
+ }
2167
+ const icon = (s: string) => (s === 'ok' ? '✅' : s === 'degraded' ? '⚠️' : '❌')
2168
+ const reportLines = (current: typeof report) => current.items.map(i => `${icon(i.status)} ${i.label}:${i.detail}${i.fix ? `\n ↳ 修复: ${i.fix}` : ''}`)
2169
+
2170
+ if (action === 'diagnose') {
2171
+ await writeReport(report)
2172
+ const diagSummary = `${report.summary}\n${reportLines(report).join('\n')}${reportPath ? `\n报告已写: ${reportPath}(侧栏工作台可直接预览)` : '\n(报告写盘失败,仅本对话展示)'}`
2173
+ // 读-only 路径:保持向后兼容,模型拿到的 verdict/items 与 issue #284 之前一致
2174
+ return JSON.parse(JSON.stringify({
2175
+ ok: true,
2176
+ action: 'diagnose',
2177
+ verdict: report.ok ? 'all-clear' : 'needs-attention',
2178
+ items: report.items,
2179
+ report_path: reportPath,
2180
+ evidence: `[doctor@${new Date().toISOString()}]`,
2181
+ summary: diagSummary,
2182
+ })) as Record<string, never>
2183
+ }
2184
+
2185
+ // action='repair':从诊断 → 选定 auto-repairable → scope-keyed 审批 → 真执行(走 bootstrap.runOnboardingFix)→ 复检。
2186
+ // 范围过滤:items 非空时只考虑这些 id(未知 id 静默剔除,落 skipped 不冒充 auto)。
2187
+ // runDoctorRepair 内部懒加载 bin/gotry-bootstrap.js,自适应 status→level 适配 + 真实安装器。
2188
+ const requestedItems = Array.isArray(q?.items) && q!.items!.length > 0 ? new Set(q!.items!) : null
2189
+ const scopedReport = requestedItems
2190
+ ? { ...report, items: report.items.filter((i) => requestedItems.has(i.id)) }
2191
+ : report
2192
+ const exec = _exec as { agent?: object; callId?: string; signal?: AbortSignal } | undefined
2193
+ // 生产 repair 让 bootstrap 安装编排复用本工具的同一诊断注册表做终态复检;
2194
+ // fixture 若显式提供 recheck,则保留其隔离实现,再单独取一次工具报告。
2195
+ let recheck: typeof report | undefined
2196
+ const injectedRepair = seams.doctor?.repair
2197
+ const repairOptions: DoctorRepairOptions = {
2198
+ ...injectedRepair,
2199
+ recheck: injectedRepair?.recheck ?? (async () => {
2200
+ recheck = await check({ stateRoot: config.stateRoot ?? '.' })
2201
+ return recheck.items.map((item) => ({
2202
+ label: item.label,
2203
+ level: item.status,
2204
+ detail: item.detail,
2205
+ fix: item.fix,
2206
+ }))
2207
+ }),
2208
+ }
2209
+ const repair = await runDoctorRepair(
2210
+ scopedReport,
2211
+ (scopeKey, reason) => repairApprovalGate.request(exec?.agent, scopeKey, reason, { callId: exec?.callId, signal: exec?.signal }),
2212
+ repairOptions,
2213
+ )
2214
+ if (repair.approval === 'granted' && !recheck) {
2215
+ recheck = await check({ stateRoot: config.stateRoot ?? '.' })
2216
+ }
2217
+ const finalReport = recheck ?? report
2218
+ await writeReport(finalReport)
2219
+ const diagSummary = `${report.summary}\n${reportLines(report).join('\n')}`
2220
+ // 整合诊断 + 修复双视角 summary(模型可分清哪段是体检、哪段是修复)
2221
+ const repairLines: string[] = []
2222
+ for (const r of repair.repairs) {
2223
+ repairLines.push(`${r.status === 'installed' ? '✅' : '❌'} ${r.label}: ${r.reason}${r.nextAction ? ` → ${r.nextAction}` : ''}`)
2224
+ }
2225
+ for (const s of repair.skipped) {
2226
+ repairLines.push(`⏭ ${s.label}: ${s.reason}(bucket=${s.bucket})`)
2227
+ }
2228
+ const recheckSummary = recheck
2229
+ ? `\n\n[recheck] ${recheck.summary}\n${reportLines(recheck).join('\n')}`
2230
+ : ''
2231
+ const reportSummary = reportPath ? `\n报告已写: ${reportPath}(侧栏工作台可直接预览)` : '\n(报告写盘失败,仅本对话展示)'
2232
+ const combinedSummary = `${diagSummary}\n\n[repair] verdict=${repair.verdict}, approval=${repair.approval}, plan=${repair.selected.length} 项 auto / ${repair.skipped.length} 项 skipped\n${repairLines.join('\n')}\n${repair.summary}${recheckSummary}${reportSummary}`
2233
+ return JSON.parse(JSON.stringify({
2234
+ ok: repair.ok,
2235
+ action: 'repair',
2236
+ verdict: repair.verdict,
2237
+ diagnosis: report,
2238
+ recheck,
2239
+ plan: {
2240
+ selected: repair.selected,
2241
+ needs_user_action: repair.skipped.filter((s) => s.bucket === 'user-action').map((s) => ({ id: s.id, label: s.label, reason: s.reason })),
2242
+ unavailable: repair.skipped.filter((s) => s.bucket === 'unavailable').map((s) => ({ id: s.id, label: s.label, reason: s.reason })),
2243
+ scope_key: repair.scopeKey,
2244
+ },
2245
+ approval: repair.approval,
2246
+ repairs: repair.repairs,
2247
+ skipped: repair.skipped,
2248
+ evidence: `[doctor@${new Date().toISOString()}]`,
2249
+ summary: combinedSummary,
2250
+ report_path: reportPath,
2251
+ })) as Record<string, never>
2252
+ },
2253
+ presentCall: args => {
2254
+ const q = unwrapQuery<{ action?: string }>(args, 'action')
2255
+ const a = q?.action === 'repair'
2256
+ return { card: 'generic', title: a ? '🩺 依赖体检+修复(待批准)' : '🩺 依赖体检', kind: 'execute', rawInput: args }
2257
+ },
2258
+ presentResult: (_args, value) => {
2259
+ const r = value as { verdict?: string; summary?: string; action?: string; approval?: string }
2260
+ const deniedLabel = r.approval === 'cancelled'
2261
+ ? '↩️ 已取消'
2262
+ : r.approval === 'unavailable'
2263
+ ? '⚠️ 无审批通道'
2264
+ : '🚫 已拒绝'
2265
+ const title = r.action === 'repair'
2266
+ ? `🩺 修复:${r.verdict === 'repaired' ? '✅ 已就位' : r.verdict === 'partial-repair' ? '⚠️ 部分成功' : r.verdict === 'repair-blocked' ? '❌ 复检未通过' : r.verdict === 'approval-denied' ? deniedLabel : '🔧 无可补装项'}`
2267
+ : `🩺 依赖体检:${r.verdict === 'all-clear' ? '✅ 全部就绪' : '🔧 有项待处理'}`
2268
+ return {
2269
+ card: 'generic',
2270
+ title,
2271
+ content: [{ type: 'text', text: String(r.summary ?? '') }],
2272
+ }
2273
+ },
2274
+ }))
2275
+
2276
+ // ---- 产物面(issue #25):agent 生成的文件可在 dsh 内发现与阅读,不再只是本地文件名 ----
2277
+
2278
+ registerGuarded(defineTool({
2279
+ name: 'gotry_artifacts_list',
2280
+ description:
2281
+ 'List GoTry artifacts — deep-planning deliverables (async runs from the state ledger) plus agent-written markdown/HTML itinerary files ' +
2282
+ 'in the working directory (trip plans as .md, .html or .htm). READ-ONLY discovery. ' +
2283
+ 'Opening a listed .html/.htm goes through the host native HTML preview, which the client labels as an HTML preview because its scripts may run; gotry_artifacts_read is the source-text path. ' +
2284
+ 'Generated itinerary HTML documents (gotry_itinerary_render) land in the same working-directory view. ' +
2285
+ 'Use when the user asks to see/open/revisit a previously generated artifact ' +
2286
+ '(「看看刚才生成的行程」「上次的规划在哪」「打开那个 md/html」) — list first, then read with gotry_artifacts_read. ' +
2287
+ 'Optional `offset` (zero-based nonnegative integer) and `search` (literal, case-insensitive substring over id/title/filename; ' +
2288
+ 'trim then empty = no filter; no regex/glob semantics, body content is never searched) let you page past the default 20 / cap 50 ' +
2289
+ 'to enumerate every eligible artifact and find an older one by name. `total` is the post-filter total; `nextOffset` is present ' +
2290
+ 'only when another page exists; an offset past the end returns an empty page with the known `total` and no `nextOffset`. ' +
2291
+ 'The list is not a stable snapshot across filesystem mutations.',
2292
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;全字段可选 → interpretArgs 容忍层
2293
+ parameters: {
2294
+ limit: { type: 'integer', description: '最多返回条数,默认 20,上限 50' },
2295
+ offset: { type: 'integer', description: '零-based 非负整数,跳过前 N 条;越界返回空页 + 准确 total + 无 nextOffset' },
2296
+ search: { type: 'string', description: '字面大小写无关子串(匹配 id/title/filename);trim 后空 = 不过滤;非正则/非 glob,不搜内容' },
2297
+ },
2298
+ output: {
2299
+ schema: { type: 'json' },
2300
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 600)) }],
2301
+ presentationMeta: (_args, value) => {
2302
+ const r = value as { artifacts?: Array<{ path?: string }>; total?: number; truncated?: boolean; offset?: number; limit?: number }
2303
+ const paths = Array.isArray(r.artifacts)
2304
+ ? r.artifacts.map(a => String(a.path ?? '')).filter(Boolean)
2305
+ : []
2306
+ return {
2307
+ shape: 'paths',
2308
+ paths,
2309
+ truncated: Boolean(r.truncated),
2310
+ total: r.total ?? paths.length,
2311
+ }
2312
+ },
2313
+ },
2314
+ async execute(args, exec: unknown) {
2315
+ const q = unwrapQuery<{ limit?: number; offset?: number; search?: string }>(args, 'limit')
2316
+ let r: Awaited<ReturnType<typeof listArtifacts>>
2317
+ try {
2318
+ r = await listArtifacts({
2319
+ stateRoot: config.stateRoot ?? '.',
2320
+ cwd: sessionCwd(exec),
2321
+ limit: q.limit,
2322
+ offset: q.offset,
2323
+ search: q.search,
2324
+ })
2325
+ } catch (err) {
2326
+ const msg = err instanceof Error ? err.message : String(err)
2327
+ return JSON.parse(JSON.stringify({ ok: false, error: msg, summary: msg, hint: 'limit 必须是有限整数(零/负夹到 1,大值封顶 50);offset 必须是非负安全整数(≤ Number.MAX_SAFE_INTEGER);search 必须是字符串(trim 后空 = 不过滤,非字符串 predictably 拒绝)' })) as Record<string, never>
2328
+ }
2329
+ const lines = r.artifacts.map(a =>
2330
+ `- [${a.source}] ${a.title}${a.status ? `(${a.status})` : ''} — ${a.path}${a.updated ? ` @ ${a.updated.slice(0, 16).replace('T', ' ')}` : ''}`)
2331
+ // Echo the requested offset (post-validation), not the clamped page start,
2332
+ // so a caller that asked for an offset past the end can tell.
2333
+ const requestedOffset = q.offset ?? 0
2334
+ const position = r.artifacts.length > 0
2335
+ ? `${requestedOffset + 1}-${requestedOffset + r.artifacts.length}`
2336
+ : '无'
2337
+ const sizeInfo = `第 ${position}/${r.total} 项(limit=${r.limit})`
2338
+ const searchInfo = r.search ? `,搜索「${r.search}」` : ''
2339
+ const summary = r.artifacts.length
2340
+ ? `在册产物 ${r.artifacts.length}/${r.total} 项${r.truncated ? `(后续页 offset=${r.nextOffset})` : ''}${searchInfo},${sizeInfo}:\n${lines.join('\n')}`
2341
+ : r.total > 0
2342
+ // Beyond the end with a known total — never claim "no artifacts".
2343
+ ? `空页(${requestedOffset + 1} 起越界;总在册 ${r.total} 项,本次 limit=${r.limit})${searchInfo},${sizeInfo}`
2344
+ : `无在册产物(异步深度规划交付与工作目录 md/html 文件都会出现在这里)${searchInfo ? `(搜索「${r.search}」无匹配)` : ''}`
2345
+ return JSON.parse(JSON.stringify({
2346
+ ok: true,
2347
+ artifacts: r.artifacts,
2348
+ total: r.total,
2349
+ truncated: r.truncated,
2350
+ offset: requestedOffset,
2351
+ limit: r.limit,
2352
+ ...(r.nextOffset !== undefined ? { nextOffset: r.nextOffset } : {}),
2353
+ ...(r.search !== undefined ? { search: r.search } : {}),
2354
+ summary,
2355
+ })) as Record<string, never>
2356
+ },
2357
+ // Host presentationMeta remains persisted with the ToolResult for Host-side
2358
+ // consumers; the packaged public Client separately renders the runtime block
2359
+ // for these custom wire names in DSH Web.
2360
+ presentResult: (_args, result: ToolResult) => {
2361
+ if (result.isError || typeof result.meta !== 'object' || result.meta === null || Array.isArray(result.meta)) return undefined
2362
+ const meta = result.meta as { shape?: unknown; paths?: unknown; truncated?: unknown; total?: unknown }
2363
+ if (meta.shape !== 'paths' || !Array.isArray(meta.paths) || !meta.paths.every(p => typeof p === 'string') ||
2364
+ typeof meta.truncated !== 'boolean' || typeof meta.total !== 'number' || !Number.isInteger(meta.total) || meta.total < 0) {
2365
+ return undefined
2366
+ }
2367
+ return {
2368
+ card: 'search' as const,
2369
+ shape: 'paths' as const,
2370
+ title: `产物:${meta.total} 项在册${meta.truncated ? '(已截断)' : ''}`,
2371
+ paths: meta.paths,
2372
+ truncated: meta.truncated,
2373
+ total: meta.total,
2374
+ }
2375
+ },
2376
+ }))
2377
+
2378
+ registerGuarded(defineTool({
2379
+ name: 'gotry_artifacts_read',
2380
+ description:
2381
+ 'Read one GoTry artifact as a line-numbered file view rendered directly in the chat UI. ' +
2382
+ 'Input: the path from gotry_artifacts_list, or a bare async ticket id (e.g. dp-xxxx). ' +
2383
+ 'Optional offset (1-based) / limit window for paging large files. ' +
2384
+ 'READ-ONLY; text artifacts only (md/txt/json/jsonl/csv/log/yaml/html/htm). ' +
2385
+ 'HTML/HTM is returned as source text by this tool only — it does not parse markup, run scripts or inline event handlers, or fetch anything; opening a listed HTML file is a separate action the client labels as an interactive HTML preview.',
2386
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;path required → 宿主权入口拒畸形参数(同 flyai/hotel 刀法)
2387
+ parameters: {
2388
+ path: { type: 'string', required: true, description: 'list 返回的路径或工单 id' },
2389
+ offset: { type: 'integer', description: '起始行号(1 起)' },
2390
+ limit: { type: 'integer', description: '窗口行数,默认 400' },
2391
+ },
2392
+ output: {
2393
+ schema: { type: 'json' },
2394
+ render: (_args, value) => [{ type: 'text', text: String((value as { content?: string }).content ?? JSON.stringify(value).slice(0, 600)) }],
2395
+ presentationMeta: (_args, value) => {
2396
+ const r = value as { path?: string; offset?: number; lines?: Array<{ number: number; text: string }>; totalLines?: number; lang?: string; source?: string; version?: string }
2397
+ return {
2398
+ path: String(r.path ?? ''),
2399
+ offset: r.offset ?? 1,
2400
+ lines: Array.isArray(r.lines) ? r.lines.map(line => ({ number: line.number, text: line.text })) : [],
2401
+ totalLines: r.totalLines ?? 0,
2402
+ ...(r.lang ? { lang: r.lang } : {}),
2403
+ ...(r.source ? { source: r.source } : {}),
2404
+ ...(r.version ? { version: r.version } : {}),
2405
+ }
2406
+ },
2407
+ },
2408
+ async execute(args, exec) {
2409
+ const q = args
2410
+ if (!q.path) throw new Error('gotry_artifacts_read requires path')
2411
+ if (!q.path) return JSON.parse(JSON.stringify({ ok: false, error: 'path 必填(来自 gotry_artifacts_list)' })) as Record<string, never>
2412
+ const r = await readArtifact({ stateRoot: config.stateRoot ?? '.', cwd: sessionCwd(exec), path: q.path, offset: q.offset, limit: q.limit })
2413
+ if (!r.ok) return JSON.parse(JSON.stringify(r)) as Record<string, never>
2414
+ // 身份/来源展示(issue #285 第 1 条「显示身份/来源」):行号视图保留 read 卡的
2415
+ // path/offset/lines/totalLines/lang;fallback content 用 source label 前缀,
2416
+ // 让无法渲染 read 卡的 UI 也能区分「本会话选了哪个产物」,避免把旧摘要当新内容。
2417
+ return JSON.parse(JSON.stringify({
2418
+ ...r,
2419
+ source: r.source,
2420
+ summary: `${r.path}(${r.totalLines} 行)第 ${r.offset}-${r.offset + r.lines.length - 1} 行${r.windowed ? `(共 ${r.totalLines} 行,可翻页)` : ''}`,
2421
+ })) as Record<string, never>
2422
+ },
2423
+ // Keep the standard location payload for Host consumers. The Web client only
2424
+ // renders its built-in keyed tools, so this is not claimed as native custom-card E2E.
2425
+ presentCall: args => ({
2426
+ card: 'generic',
2427
+ title: `读产物:${args.path ?? ''}`,
2428
+ kind: 'read',
2429
+ rawInput: args,
2430
+ ...(args.path ? { locations: [{ path: String(args.path), line: 1 }] } : {}),
2431
+ }),
2432
+ presentResult: (_args, result: ToolResult) => {
2433
+ if (result.isError || typeof result.meta !== 'object' || result.meta === null || Array.isArray(result.meta)) return undefined
2434
+ const meta = result.meta as { path?: unknown; source?: unknown; offset?: unknown; lines?: unknown; totalLines?: unknown; lang?: unknown }
2435
+ if (typeof meta.path !== 'string' || meta.path === '' || typeof meta.offset !== 'number' || !Number.isInteger(meta.offset) || meta.offset < 1 ||
2436
+ !Array.isArray(meta.lines) || !meta.lines.every(line => typeof line === 'object' && line !== null && !Array.isArray(line) &&
2437
+ typeof (line as { number?: unknown }).number === 'number' && Number.isInteger((line as { number: number }).number) &&
2438
+ typeof (line as { text?: unknown }).text === 'string') ||
2439
+ typeof meta.totalLines !== 'number' || !Number.isInteger(meta.totalLines) || meta.totalLines < 0) {
2440
+ return undefined
2441
+ }
2442
+ const source = typeof meta.source === 'string' ? meta.source : 'unknown'
2443
+ const identityLine = `source: ${source} · path: ${meta.path} · ${meta.totalLines} lines`
2444
+ const rawContent = result.content
2445
+ .filter(block => block.type === 'text')
2446
+ .map(block => block.text)
2447
+ .join('\n')
2448
+ return {
2449
+ card: 'read' as const,
2450
+ title: meta.path.split('/').pop() ?? meta.path,
2451
+ path: meta.path,
2452
+ offset: meta.offset,
2453
+ lines: meta.lines as Array<{ number: number; text: string }>,
2454
+ totalLines: meta.totalLines,
2455
+ ...(typeof meta.lang === 'string' ? { lang: meta.lang } : {}),
2456
+ content: [
2457
+ { type: 'text', text: identityLine },
2458
+ { type: 'text', text: rawContent },
2459
+ ],
2460
+ }
2461
+ },
2462
+ }))
2463
+
2464
+ // ---- 行程 HTML 产物生成(issue #442,父 #438):显式行程 + 注册表事实 → 会话工作目录内的新文件 ----
2465
+ // 只新建(独占 O_EXCL,绝不覆盖);事实只从 config.stateRoot 注册表按 id 取,
2466
+ // 不收调用方自带事实对象;空 fact_ids = 明确未核验计划(无整体「已验证」结论)。
2467
+
2468
+ registerGuarded(defineTool({
2469
+ name: 'gotry_itinerary_render',
2470
+ description:
2471
+ 'Generate a local, self-contained HTML itinerary document as a NEW file in the session working directory (never overwrites; '
2472
+ + 'the file can then be listed/read with gotry_artifacts_list / gotry_artifacts_read). '
2473
+ + 'Input: title, the explicit itinerary object { trip_start, trip_end, stays:[{place,check_in,check_out}], '
2474
+ + 'od_segments:[{from,to,date,mode,legs}] } (same shape as gotry_fact_gate itinerary; nights/budget fields are not accepted), '
2475
+ + 'and fact_ids — the ids of already-recorded bookable facts to project as evidence. Facts are loaded ONLY from the session fact '
2476
+ + 'registry (stateRoot bookable-facts log): caller-supplied fact objects are never accepted, and unknown/duplicate/over-limit ids are rejected. '
2477
+ + 'An empty fact_ids array is legitimate and renders an explicitly unverified plan — this document never carries an overall "verified" badge, '
2478
+ + 'only per-fact bookability/tier/source labels. No Markdown-to-facts guessing, no date/night/budget arithmetic, no upstream queries. '
2479
+ + 'Optional basename must match gotry-itinerary-<ASCII token>.html; when omitted a random name is generated. '
2480
+ + 'The result returns the final absolute path.',
2481
+ parameters: {
2482
+ title: { type: 'string', required: true, description: '文档标题(作为页面标题与 h1,原样转义)' },
2483
+ itinerary: { type: 'object', additionalProperties: true, required: true, description: '结构化行程 { trip_start, trip_end, stays:[{place,check_in,check_out}], od_segments:[{from,to,date,mode,legs}] }; 不做夜数/预算/时间运算' },
2484
+ fact_ids: { type: 'array', items: { type: 'string' }, required: true, description: '要投影的事实 id 数组(来自本会话 exact-date 工具结果登记的注册表);必填,空数组 = 明确未核验计划' },
2485
+ basename: { type: 'string', description: '可选文件名,必须形如 gotry-itinerary-<ASCII token>.html;不传则用 crypto 随机名' },
2486
+ },
2487
+ output: {
2488
+ schema: { type: 'json' },
2489
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
2490
+ },
2491
+ async execute(args, exec) {
2492
+ const q = args as { title?: unknown; itinerary?: unknown; fact_ids?: unknown; basename?: unknown }
2493
+ // 写产物不允许猜测落点:宿主必须给出显式绝对会话工作目录,否则 fail closed
2494
+ //(绝不回落 process.cwd()——那会把产物写进 Node 进程的偶然目录)
2495
+ const cwd = sessionCwd(exec)
2496
+ if (typeof cwd !== 'string' || cwd.trim() === '' || !isAbsolute(cwd)) {
2497
+ const error = typeof cwd !== 'string' || cwd.trim() === ''
2498
+ ? '会话工作目录缺失:拒绝在未知目录写产物'
2499
+ : `会话工作目录必须是绝对路径:${cwd}`
2500
+ return JSON.parse(JSON.stringify({
2501
+ ok: false,
2502
+ error,
2503
+ hint: '产物只写到宿主会话的显式绝对工作目录(dsh 会话 header.cwd);本工具不猜测落点',
2504
+ })) as Record<string, never>
2505
+ }
2506
+ const r = await generateItineraryArtifact(
2507
+ { title: q.title, itinerary: q.itinerary, fact_ids: q.fact_ids, basename: q.basename },
2508
+ { stateRoot: config.stateRoot ?? '.', cwd },
2509
+ )
2510
+ const summary = r.ok
2511
+ ? `已生成行程 HTML 产物(未写入任何整体「已验证」结论):${r.path}\n`
2512
+ + `投影事实 ${r.fact_ids.length} 条(全部来自当前注册表),文件 ${r.bytes} 字节。`
2513
+ + `${r.fact_ids.length === 0 ? '本次为空事实列表:文档明确为未核验计划。' : ''}`
2514
+ + '可用 gotry_artifacts_list / gotry_artifacts_read 再次查看。'
2515
+ : `未生成产物(未写入任何文件):${r.error}`
2516
+ + `${r.errors?.length ? `\n${r.errors.slice(0, 8).map(e => `- ${e}`).join('\n')}` : ''}`
2517
+ + `${r.hint ? `\n修正提示:${r.hint}` : ''}`
2518
+ return JSON.parse(JSON.stringify({ ...r, summary })) as Record<string, never>
2519
+ },
2520
+ presentCall: args => ({ card: 'generic', title: `生成行程 HTML:${String(args.title ?? '')}`.slice(0, 80), kind: 'execute', rawInput: args }),
2521
+ presentResult: (_args, value) => {
2522
+ const r = value as { ok?: boolean; path?: string; bytes?: number; error?: string }
2523
+ return {
2524
+ card: 'generic',
2525
+ title: r.ok ? `行程 HTML 已生成:${String(r.path ?? '').split('/').pop() ?? ''}` : '行程 HTML 未生成',
2526
+ content: [{ type: 'text', text: r.ok ? `最终路径:${String(r.path ?? '')}(${r.bytes ?? 0} 字节)` : String(r.error ?? '') }],
2527
+ }
2528
+ },
2529
+ }))
2530
+
2531
+ registerGuarded(defineTool({
2532
+ name: 'gotry_itinerary_deck_render',
2533
+ description:
2534
+ 'Generate a local, self-contained HTML itinerary DECK (slide-form, CSS scroll-snap paging, deterministic slide derivation) as a NEW file in the session working directory (never overwrites; '
2535
+ + 'the file can then be listed/read with gotry_artifacts_list / gotry_artifacts_read). '
2536
+ + 'Input: title, the explicit itinerary object { trip_start, trip_end, stays:[{place,check_in,check_out}], '
2537
+ + 'od_segments:[{from,to,date,mode,legs}] } (same shape as gotry_itinerary_render; nights/budget fields are not accepted), '
2538
+ + 'and fact_ids — the ids of already-recorded bookable facts to project as evidence. Facts are loaded ONLY from the session fact '
2539
+ + 'registry (stateRoot bookable-facts log): caller-supplied fact objects are never accepted, and unknown/duplicate/over-limit ids are rejected. '
2540
+ + 'An empty fact_ids array is legitimate and renders an explicitly unverified plan — this deck never carries an overall "verified" badge, '
2541
+ + 'only per-fact bookability/tier/source labels. No Markdown-to-facts guessing, no date/night/budget arithmetic, no upstream queries. '
2542
+ + 'Optional basename must match gotry-deck-<ASCII token>.html; when omitted a random name is generated. '
2543
+ + 'The result returns the final absolute path.',
2544
+ parameters: {
2545
+ title: { type: 'string', required: true, description: 'deck 标题(作为封面 h1,原样转义)' },
2546
+ itinerary: { type: 'object', additionalProperties: true, required: true, description: '结构化行程 { trip_start, trip_end, stays:[{place,check_in,check_out}], od_segments:[{from,to,date,mode,legs}] }; 不做夜数/预算/时间运算' },
2547
+ fact_ids: { type: 'array', items: { type: 'string' }, required: true, description: '要投影的事实 id 数组(来自本会话 exact-date 工具结果登记的注册表);必填,空数组 = 明确未核验计划' },
2548
+ basename: { type: 'string', description: '可选文件名,必须形如 gotry-deck-<ASCII token>.html;不传则用 crypto 随机名' },
2549
+ },
2550
+ output: {
2551
+ schema: { type: 'json' },
2552
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
2553
+ },
2554
+ async execute(args, exec) {
2555
+ const q = args as { title?: unknown; itinerary?: unknown; fact_ids?: unknown; basename?: unknown }
2556
+ // 写产物不允许猜测落点:宿主必须给出显式绝对会话工作目录,否则 fail closed
2557
+ //(绝不回落 process.cwd()——那会把产物写进 Node 进程的偶然目录)
2558
+ const cwd = sessionCwd(exec)
2559
+ if (typeof cwd !== 'string' || cwd.trim() === '' || !isAbsolute(cwd)) {
2560
+ const error = typeof cwd !== 'string' || cwd.trim() === ''
2561
+ ? '会话工作目录缺失:拒绝在未知目录写产物'
2562
+ : `会话工作目录必须是绝对路径:${cwd}`
2563
+ return JSON.parse(JSON.stringify({
2564
+ ok: false,
2565
+ error,
2566
+ hint: '产物只写到宿主会话的显式绝对工作目录(dsh 会话 header.cwd);本工具不猜测落点',
2567
+ })) as Record<string, never>
2568
+ }
2569
+ const r = await generateItineraryDeckArtifact(
2570
+ { title: q.title, itinerary: q.itinerary, fact_ids: q.fact_ids, basename: q.basename },
2571
+ { stateRoot: config.stateRoot ?? '.', cwd },
2572
+ )
2573
+ const summary = r.ok
2574
+ ? `已生成行程 deck 产物(未写入任何整体「已验证」结论):${r.path}\n`
2575
+ + `投影事实 ${r.fact_ids.length} 条(全部来自当前注册表),文件 ${r.bytes} 字节。`
2576
+ + `${r.fact_ids.length === 0 ? '本次为空事实列表:deck 明确为未核验计划。' : ''}`
2577
+ + '可用 gotry_artifacts_list / gotry_artifacts_read 再次查看。'
2578
+ : `未生成产物(未写入任何文件):${r.error}`
2579
+ + `${r.errors?.length ? `\n${r.errors.slice(0, 8).map(e => `- ${e}`).join('\n')}` : ''}`
2580
+ + `${r.hint ? `\n修正提示:${r.hint}` : ''}`
2581
+ return JSON.parse(JSON.stringify({ ...r, summary })) as Record<string, never>
2582
+ },
2583
+ presentCall: args => ({ card: 'generic', title: `生成行程 deck:${String(args.title ?? '')}`.slice(0, 80), kind: 'execute', rawInput: args }),
2584
+ presentResult: (_args, value) => {
2585
+ const r = value as { ok?: boolean; path?: string; bytes?: number; error?: string }
2586
+ return {
2587
+ card: 'generic',
2588
+ title: r.ok ? `行程 deck 已生成:${String(r.path ?? '').split('/').pop() ?? ''}` : '行程 deck 未生成',
2589
+ content: [{ type: 'text', text: r.ok ? `最终路径:${String(r.path ?? '')}(${r.bytes ?? 0} 字节)` : String(r.error ?? '') }],
2590
+ }
2591
+ },
2592
+ }))
2593
+ registerGuarded(defineTool({
2594
+ name: 'gotry_deck_export',
2595
+ description:
2596
+ 'Export a local, self-contained HTML itinerary DECK as a shareable static bundle (NEW directory contents; never overwrites) into a host-provided target directory. '
2597
+ + 'Writes three files at the target_dir top level, all basename-prefixed so multiple bundles can coexist in the same dir: '
2598
+ + '`<basename>.html` (the rendered deck), `<basename>.manifest.json` (provenance: sha256, bytes, fact counts by kind, source tags, evidence-chain summary, exported_at, optional target_url), '
2599
+ + 'and `<basename>.qr.svg` (real QR matrix — issue #569, encoding the target_url when provided, or a `local bundle; not yet hosted` marker when omitted). '
2600
+ + 'Input: title, the explicit itinerary object { trip_start, trip_end, stays:[{place,check_in,check_out}], od_segments:[{from,to,date,mode,legs}] } (same shape as gotry_itinerary_render; nights/budget fields are not accepted), '
2601
+ + 'fact_ids (loaded ONLY from the session fact registry), optional basename (default = random hex), optional target_url (recorded in manifest, used by QR when slice 3b lands). '
2602
+ + 'target_dir must be an absolute directory path provided by the host (no fallback to process cwd). All three files use O_CREAT|O_EXCL — any pre-existing file at the target slot rejects the call with zero bytes written.',
2603
+ parameters: {
2604
+ title: { type: 'string', required: true, description: 'deck 标题(原样转义)' },
2605
+ itinerary: { type: 'object', additionalProperties: true, required: true, description: '结构化行程 { trip_start, trip_end, stays:[{place,check_in,check_out}], od_segments:[{from,to,date,mode,legs}] }; 不做夜数/预算/时间运算' },
2606
+ fact_ids: { type: 'array', items: { type: 'string' }, required: true, description: '事实 id 数组(来自本会话 exact-date 工具结果登记的注册表)' },
2607
+ basename: { type: 'string', description: '可选 bundle stem,默认随机 hex;决定三件文件名(<basename>.html / manifest.json / qr.svg)' },
2608
+ target_url: { type: 'string', description: '可选:目标托管 URL,写入 manifest;切片 3b QR 编码将引用此字段' },
2609
+ },
2610
+ output: {
2611
+ schema: { type: 'json' },
2612
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
2613
+ },
2614
+ async execute(args, exec) {
2615
+ const q = args as { title?: unknown; itinerary?: unknown; fact_ids?: unknown; basename?: unknown; target_url?: unknown }
2616
+ // 写产物不允许猜测落点:宿主必须给出显式绝对 target_dir,否则 fail closed
2617
+ const targetDir = sessionCwd(exec)
2618
+ if (typeof targetDir !== 'string' || targetDir.trim() === '' || !isAbsolute(targetDir)) {
2619
+ const error = typeof targetDir !== 'string' || targetDir.trim() === ''
2620
+ ? 'target_dir 缺失:拒绝在未知目录写产物'
2621
+ : `target_dir 必须是绝对路径:${targetDir}`
2622
+ return JSON.parse(JSON.stringify({
2623
+ ok: false,
2624
+ error,
2625
+ hint: '产物只写到宿主会话的显式绝对工作目录(dsh 会话 header.cwd);本工具不猜测落点',
2626
+ })) as Record<string, never>
2627
+ }
2628
+ const r = await generateItineraryDeckExport(
2629
+ { title: q.title, itinerary: q.itinerary, fact_ids: q.fact_ids, basename: q.basename, target_url: q.target_url },
2630
+ { stateRoot: config.stateRoot ?? '.', targetDir },
2631
+ )
2632
+ const summary = r.ok
2633
+ ? `已生成 deck 静态导出 bundle(target_dir):${r.target_dir}\n`
2634
+ + `三件文件:html=${r.files.html}\nmanifest=${r.files.manifest}\nqr.svg=${r.files.qr}(真矩阵,#569 切片 3b 落地;target_url 见 manifest.target_url)\n`
2635
+ + `总字节 ${r.bytes},投影事实 ${r.fact_ids.length} 条(全部来自当前注册表)。`
2636
+ + '可直接上传到任意静态托管(Vercel/Netlify/GH Pages)。'
2637
+ : `未生成产物(未写入任何文件):${r.error}`
2638
+ + `${r.errors?.length ? `\n${r.errors.slice(0, 8).map(e => `- ${e}`).join('\n')}` : ''}`
2639
+ + `${r.hint ? `\n修正提示:${r.hint}` : ''}`
2640
+ return JSON.parse(JSON.stringify({ ...r, summary })) as Record<string, never>
2641
+ },
2642
+ presentCall: args => ({ card: 'generic', title: `导出 deck bundle:${String(args.title ?? '')}`.slice(0, 80), kind: 'execute', rawInput: args }),
2643
+ presentResult: (_args, value) => {
2644
+ const r = value as { ok?: boolean; target_dir?: string; files?: { html?: string; manifest?: string; qr?: string }; error?: string }
2645
+ return {
2646
+ card: 'generic',
2647
+ title: r.ok ? `deck bundle 已导出:${String(r.target_dir ?? '')}` : 'deck bundle 未导出',
2648
+ content: [{ type: 'text', text: r.ok ? `三件文件:${r.files?.html ?? ''} / ${r.files?.manifest ?? ''} / ${r.files?.qr ?? ''}` : String(r.error ?? '') }],
2649
+ }
2650
+ },
2651
+ }))
2652
+
2653
+ // ---- 产物事实闸(issue #46,ADR-19):含可下单事实的产物交付前必过 ----
2654
+ // 每个航班号/时刻/机场/价格/政策断言必须回溯到本会话 exact-date 工具结果
2655
+ // (bookable-facts 侧车,query_id 可重放);无法回溯即 blocked——不得宣称「已验证方案」。
2656
+
2657
+ registerGuarded(defineTool({
2658
+ name: 'gotry_fact_gate',
2659
+ description:
2660
+ 'Factuality gate for itinerary artifacts (issue #46): call BEFORE delivering any artifact that contains bookable facts '
2661
+ + '(flight numbers, times, airports, prices, visa/entry policies). Every bookable claim in the markdown is checked against '
2662
+ + 'the session fact registry (exact-date tool results recorded by gotry_flyai_search / gotry_session_search — hit AND miss). '
2663
+ + 'Blocked when: a claimed flight is absent from the exact-date source (never backfill from route pages/history/adjacent dates); '
2664
+ + 'route+date never queried; times contradict the snapshot; carrier→airport mapping conflicts (FD=DMK vs VZ=BKK are NOT interchangeable); '
2665
+ + '「联程」without protected_connection=true; policy claims without 「截至 YYYY-MM-DD」; unconditional ✓ on unverified claims. '
2666
+ + 'Optional itinerary object enables machine invariants (hotel_nights + onboard_nights = total nights, O&D segments vs flight legs, '
2667
+ + 'budget floor ≥ sum of item minimums). verdict=blocked ⇒ fix or downgrade wording — never present as a verified plan.',
2668
+ // D-30 第三刀(issue #112):query blob → 平铺 typed;markdown/path 二选一无公共 required
2669
+ // → interpretArgs 容忍层;itinerary 保 object+additionalProperties:true(嵌套形状归一在闸内,
2670
+ // #118 D-26 渲染原语切片再收紧),给模型「这是对象」的可见信号
2671
+ parameters: {
2672
+ markdown: { type: 'string', description: '产物全文;与 path 二选一' },
2673
+ path: { type: 'string', description: '产物路径(artifacts_list 返回的);与 markdown 二选一' },
2674
+ tripYear: { type: 'integer', description: '行程年份,如 2027(日期归一用)' },
2675
+ itinerary: { type: 'object', additionalProperties: true, description: '结构化行程 { trip_start, trip_end, stays:[{place,check_in,check_out}], onboard_nights, od_segments:[{from,to,date,mode,legs}], budget_items:[{label,min_cny,max_cny}], claimed_floor_cny? }' },
2676
+ },
2677
+ output: {
2678
+ schema: { type: 'json' },
2679
+ render: (_args, value) => [{ type: 'text', text: String((value as { summary?: string }).summary ?? JSON.stringify(value).slice(0, 800)) }],
2680
+ },
2681
+ async execute(args, exec: unknown) {
2682
+ const q = unwrapQuery<{ markdown?: string; path?: string; tripYear?: number; itinerary?: Record<string, unknown> }>(args, 'markdown')
2683
+ const avMap = await loadAirlineAirportMap()
2684
+ if (!avMap) {
2685
+ return JSON.parse(JSON.stringify({ ok: false, summary: '航司机场映射缺失(data/airline-airports.json)——事实闸不可用,fail closed:产物不得宣称已验证' })) as Record<string, never>
2686
+ }
2687
+ let markdown = q.markdown
2688
+ if (!markdown && q.path) {
2689
+ const r = await readArtifact({ stateRoot: config.stateRoot ?? '.', cwd: sessionCwd(exec), path: q.path })
2690
+ if (!r.ok) return JSON.parse(JSON.stringify({ ok: false, summary: `产物读取失败:${String((r as { error?: string }).error ?? '')}` })) as Record<string, never>
2691
+ markdown = r.content
2692
+ }
2693
+ if (!markdown) return JSON.parse(JSON.stringify({ ok: false, summary: '需要 markdown(产物全文)或 path(产物路径)' })) as Record<string, never>
2694
+ const itinerary = q.itinerary as import('./bookable-facts.ts').ItineraryFacts | undefined
2695
+ const registry = await loadFactRegistry(config.stateRoot ?? '.')
2696
+ // 政策复核提醒桥接(issue #359):闸侧 opts.tripStart 与 renderer 同一传入
2697
+ // 才能让合法 `renderPolicyFact(f, tripStart)` 行通过公开闸。已加载的
2698
+ // itinerary.trip_start 是权威源(同次闸同时驱动 itineraryInvariants),不再
2699
+ // 额外要求调用方传 opts.tripStart;空 itinerary/无 trip_start 即无提醒。
2700
+ const tripStart = typeof itinerary?.trip_start === 'string' ? itinerary.trip_start : undefined
2701
+ const report = gateArtifact(markdown, registry, avMap, { trip_year: q.tripYear, itinerary, tripStart })
2702
+ const lines = report.violations.slice(0, 20).map(v => ` L${v.line} [${v.kind}] ${v.detail}`)
2703
+ const summary = report.verdict === 'pass'
2704
+ ? `事实闸 PASS:${report.traceable}/${report.claims_checked} 可下单 claim 全部回溯到 exact-date 工具结果(query_id 可重放)——可宣称「已验证方案」。`
2705
+ : `事实闸 BLOCKED(${report.violations.length} 违例,${report.traceable}/${report.claims_checked} claim 可回溯)——不得宣称「已验证方案」:\n${lines.join('\n')}\n修正路径:逐条改成 exact-date 源返回的事实,或降级为「未确认/当前不可售,到 D-xx 复核」;exact-date miss 的 route+date 不得用历史班期/相邻日期/航线页填充。`
2706
+ return JSON.parse(JSON.stringify({ ok: true, ...report, summary })) as Record<string, never>
2707
+ },
2708
+ presentCall: args => ({ card: 'generic', title: '产物事实闸', kind: 'execute', rawInput: args }),
2709
+ presentResult: (_args, value) => {
2710
+ const r = value as { verdict?: string; violations?: unknown[]; summary?: string }
2711
+ return {
2712
+ card: 'generic',
2713
+ title: `事实闸:${r.verdict === 'pass' ? '✅ pass' : `⛔ blocked(${r.violations?.length ?? '?'})`}`,
2714
+ content: [{ type: 'text', text: String(r.summary ?? '') }],
2715
+ }
2716
+ },
2717
+ }))
835
2718
  }