@danceiny/gotry 0.0.1-rc.9 → 0.2.0-rc.28

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