dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,864 +1,863 @@
1
- #!/usr/bin/env node
2
- /**
3
- * EVALUATION ONLY — drive one bound conversation through the public Session
4
- * remote for work order B. Never imported by runtime code.
5
- *
6
- * Public request shape (verified against the host source on 2026-11-01):
7
- *
8
- * packages/api/session-controller/src/types.ts
9
- * interface SessionPromptRequest {
10
- * requestId: SessionRequestId
11
- * sessionId: SessionId
12
- * mode: 'queue' | 'steer'
13
- * content: readonly PromptContentPart[] // {type:'text', text}
14
- * clientTimeZone?: string // 'UTC' or a valid IANA name
15
- * }
16
- *
17
- * packages/api/session-controller/src/index.ts
18
- * @Remote('prompt') prompt(request, signal) -> { accepted: true }
19
- *
20
- * Transport rule
21
- * --------------
22
- * The generated client calls this unary method through the Connection RPC
23
- * carrier; its documented wire form is (docs/api-gateway.md):
24
- *
25
- * POST <base>/api/session/prompt
26
- * {
27
- * "type": "client-request",
28
- * "rpcId": "<connection correlation id>",
29
- * "method": "session/prompt",
30
- * "payload": { "args": { "request": <SessionPromptRequest> } }
31
- * }
32
- * ->
33
- * { "type": "server-response", "rpcId": "<same>", "result": { "ok": true, "value": { "accepted": true } } }
34
- *
35
- * There is no stream-carrier form for this method: the API Gateway rejects a
36
- * unary method opened through /api/remote.mux with gateway/signature-invalid.
37
- *
38
- * Work order B forbids silently calling the shared /api route. Therefore this
39
- * script deliberately REFUSES to send anything unless --allow-api-route is
40
- * passed together with --base. Without that explicit opt-in it prints the exact
41
- * requests as a manual fallback and exits non-zero (code 3). This is not a
42
- * missing feature; it is the rule.
43
- *
44
- * Authentication assumption: the Host's /api route is behind its persistent
45
- * browser authentication (connection.admit() returns 401 without a valid
46
- * cookie). If the target Host enforces it, pass --cookie-file with the single
47
- * Cookie header value copied from the authenticated browser session. This
48
- * harness never prints or stores that value, and it sends no other credentials.
49
- * A non-loopback --base would additionally need the Host's trustedHosts setup;
50
- * the harness warns but does not bypass it.
51
- *
52
- * Completion is observed from the public persisted session log
53
- * (<DSH_HOME>/sessions/<project>/<sessionId>/session.v4.jsonl.zstd), the same
54
- * artifact docs/host-api.md §6.8 describes. No private endpoint and no plugin
55
- * RPC is called. A turn counts as done only when a turn/end for this prompt
56
- * reports reason.kind === 'completed'.
57
- *
58
- * Usage:
59
- * node scripts/drive-session.mjs --session <id> --turns 50 \
60
- * --base http://127.0.0.1:<host-gateway-port> --allow-api-route \
61
- * --requests-out ./requests.jsonl
62
- * node scripts/drive-session.mjs --session <id> --turns 5 --dry-run
63
- *
64
- * Exit codes:
65
- * 0 all requested turns completed
66
- * 1 a turn or the transport failed (the first failure stops the run)
67
- * 2 usage error
68
- * 3 manual fallback: nothing was sent (no approved transport)
69
- * 4 preflight failure: the session log needed to observe turn/end is absent
70
- */
71
- import crypto from 'node:crypto'
72
- import fs from 'node:fs'
73
- import os from 'node:os'
74
- import path from 'node:path'
75
- import zlib from 'node:zlib'
76
- import { pathToFileURL } from 'node:url'
77
-
78
- const EXIT_OK = 0
79
- const EXIT_FAILED = 1
80
- const EXIT_USAGE = 2
81
- const EXIT_MANUAL = 3
82
- const EXIT_PREFLIGHT = 4
83
-
84
- const DEFAULT_TURNS = 50
85
- const DEFAULT_TIMEOUT_MS = 180_000
86
- const DEFAULT_POLL_MS = 400
87
-
88
- /**
89
- * Neutral prompts used only when neither --prompt nor --text-file is supplied.
90
- * They contain no user data and are cycled to reach --turns.
91
- */
92
- const DEFAULT_PROMPTS = Object.freeze([
93
- '今天有点累,随便聊聊吧。',
94
- '你还记得我昨天提到的那件事吗?',
95
- '帮我把今天要做的事理一理。',
96
- '我们上次说到哪儿了?',
97
- '明天有什么安排吗?',
98
- '我想起一个很久以前的小事。',
99
- '给我讲讲你最近在忙什么。',
100
- '如果要去一个陌生的城市,你会先做什么?',
101
- '今天天气怎么样?凭记忆回答就好。',
102
- '晚安,明天见。',
103
- ])
104
-
105
- const USAGE = `EVALUATION ONLY — drive one conversation through the public Session prompt remote.
106
-
107
- Usage:
108
- node scripts/drive-session.mjs --session <id> [options] [--prompt <text> ...]
109
-
110
- Required:
111
- --session <id> Target SessionId (the conversation must already be
112
- bound to the test library).
113
-
114
- Transport:
115
- --base <url> Host gateway base, e.g. http://127.0.0.1:3000
116
- (the Host's own port, not the mock LLM port).
117
- --allow-api-route Explicitly permit the documented public Connection RPC
118
- carrier POST <base>/api/session/prompt. Without this
119
- flag and --base, nothing is sent: the script prints a
120
- manual fallback and exits 3 (work order B rule).
121
- --cookie-file <p> File holding one Cookie header value for /api. The
122
- Host browser-authenticates /api, so a real Host
123
- usually returns 401 without it. The value is never
124
- printed or stored by this script.
125
-
126
- Turns:
127
- --turns <n> Number of prompts. Default: ${DEFAULT_TURNS}.
128
- --prompt <text> One prompt; repeatable. Positional text after options
129
- is also accepted as prompts.
130
- --text-file <p> .json array of strings / {text|prompt|content} objects,
131
- or one prompt per non-empty line. Optional: without it
132
- the built-in neutral prompts are cycled.
133
- --interval-ms <n> Wait between completed turns. Default: 0.
134
- --timeout-ms <n> Per-turn send + completion budget. Default: ${DEFAULT_TIMEOUT_MS}.
135
- --poll-ms <n> Session-log poll interval. Default: ${DEFAULT_POLL_MS}.
136
- --client-time-zone <iana> IANA name sent as clientTimeZone. Default: system zone.
137
-
138
- Observation:
139
- --session-log <p> Exact session log path (skips discovery).
140
- --dsh-home <p> DSH home used for discovery. Default: $DSH_HOME or ~/.dsh.
141
-
142
- Output:
143
- --requests-out <p> Write the exact request objects as JSONL before sending.
144
- This file contains the prompt text; delete it after use
145
- and do not commit it.
146
- --dry-run Print the requests and exit 0 without sending.
147
- -h, --help Show this text.
148
-
149
- Public request sent for every turn:
150
- sessionController.prompt({
151
- requestId: '<unique per turn>',
152
- sessionId: '<--session>',
153
- mode: 'queue',
154
- content: [{ type: 'text', text: '<prompt>' }],
155
- clientTimeZone: '<IANA>'
156
- })
157
-
158
- The run stops on the first failure. A timeout or a non-completed turn/end is a
159
- failure and is not counted as a valid turn. No /api call is made without
160
- --allow-api-route.
161
- `
162
-
163
- function failUsage(message) {
164
- console.error('drive-session: ' + message + '\n')
165
- console.error(USAGE)
166
- return EXIT_USAGE
167
- }
168
-
169
- function parseArgs(argv) {
170
- const options = {
171
- base: null,
172
- session: null,
173
- turns: DEFAULT_TURNS,
174
- intervalMs: 0,
175
- timeoutMs: DEFAULT_TIMEOUT_MS,
176
- pollMs: DEFAULT_POLL_MS,
177
- textFile: null,
178
- prompts: [],
179
- clientTimeZone: null,
180
- sessionLog: null,
181
- dshHome: null,
182
- requestsOut: null,
183
- cookieFile: null,
184
- allowApiRoute: false,
185
- dryRun: false,
186
- help: false,
187
- }
188
- const take = (index, name) => {
189
- const value = argv[index]
190
- if (value === undefined || value.startsWith('--')) throw new Error(name + ' requires a value')
191
- return value
192
- }
193
- for (let i = 0; i < argv.length; i += 1) {
194
- const token = argv[i]
195
- if (token === '-h') {
196
- options.help = true
197
- continue
198
- }
199
- if (!token.startsWith('--')) {
200
- options.prompts.push(token)
201
- continue
202
- }
203
- const eq = token.indexOf('=')
204
- const name = eq === -1 ? token : token.slice(0, eq)
205
- const inline = eq === -1 ? null : token.slice(eq + 1)
206
- switch (name) {
207
- case '--help':
208
- options.help = true
209
- break
210
- case '--base':
211
- options.base = inline ?? take(++i, '--base')
212
- break
213
- case '--session':
214
- options.session = inline ?? take(++i, '--session')
215
- break
216
- case '--turns':
217
- options.turns = positiveInt(inline ?? take(++i, '--turns'), '--turns')
218
- break
219
- case '--interval-ms':
220
- options.intervalMs = nonNegativeInt(inline ?? take(++i, '--interval-ms'), '--interval-ms')
221
- break
222
- case '--timeout-ms':
223
- options.timeoutMs = positiveInt(inline ?? take(++i, '--timeout-ms'), '--timeout-ms')
224
- break
225
- case '--poll-ms':
226
- options.pollMs = positiveInt(inline ?? take(++i, '--poll-ms'), '--poll-ms')
227
- break
228
- case '--text-file':
229
- options.textFile = inline ?? take(++i, '--text-file')
230
- break
231
- case '--prompt':
232
- options.prompts.push(inline ?? take(++i, '--prompt'))
233
- break
234
- case '--client-time-zone':
235
- options.clientTimeZone = inline ?? take(++i, '--client-time-zone')
236
- break
237
- case '--session-log':
238
- options.sessionLog = inline ?? take(++i, '--session-log')
239
- break
240
- case '--dsh-home':
241
- options.dshHome = inline ?? take(++i, '--dsh-home')
242
- break
243
- case '--requests-out':
244
- options.requestsOut = inline ?? take(++i, '--requests-out')
245
- break
246
- case '--cookie-file':
247
- options.cookieFile = inline ?? take(++i, '--cookie-file')
248
- break
249
- case '--allow-api-route':
250
- if (inline !== null) throw new Error('--allow-api-route does not take a value')
251
- options.allowApiRoute = true
252
- break
253
- case '--dry-run':
254
- if (inline !== null) throw new Error('--dry-run does not take a value')
255
- options.dryRun = true
256
- break
257
- default:
258
- throw new Error('unknown option: ' + token)
259
- }
260
- }
261
- return options
262
- }
263
-
264
- function positiveInt(value, name) {
265
- const number = Number(value)
266
- if (!Number.isSafeInteger(number) || number <= 0) throw new Error(name + ' must be a positive integer')
267
- return number
268
- }
269
-
270
- function nonNegativeInt(value, name) {
271
- const number = Number(value)
272
- if (!Number.isSafeInteger(number) || number < 0) throw new Error(name + ' must be a non-negative integer')
273
- return number
274
- }
275
-
276
- function defaultClientTimeZone() {
277
- try {
278
- const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
279
- return typeof zone === 'string' && zone ? zone : 'UTC'
280
- } catch {
281
- return 'UTC'
282
- }
283
- }
284
-
285
- function readTextFilePrompts(file) {
286
- const raw = fs.readFileSync(file, 'utf8')
287
- if (path.extname(file).toLowerCase() === '.json') {
288
- let value
289
- try { value = JSON.parse(raw) } catch (error) { throw new Error('--text-file is not valid JSON: ' + error.message) }
290
- if (!Array.isArray(value)) throw new Error('--text-file JSON must be an array')
291
- const prompts = value.map((item, index) => textOfPromptItem(item, index)).filter(Boolean)
292
- if (prompts.length === 0) throw new Error('--text-file JSON array contains no prompts')
293
- return prompts
294
- }
295
- const prompts = raw.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith('#'))
296
- if (prompts.length === 0) throw new Error('--text-file contains no non-empty lines')
297
- return prompts
298
- }
299
-
300
- function textOfPromptItem(item, index) {
301
- if (typeof item === 'string') return item.trim()
302
- if (!item || typeof item !== 'object') throw new Error('--text-file item ' + (index + 1) + ' is not a string or object')
303
- const candidate = item.text ?? item.prompt ?? item.content
304
- if (typeof candidate === 'string') return candidate.trim()
305
- if (Array.isArray(candidate)) {
306
- const text = candidate
307
- .map((part) => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : ''))
308
- .filter(Boolean)
309
- .join('\n')
310
- .trim()
311
- if (text) return text
312
- }
313
- throw new Error('--text-file item ' + (index + 1) + ' has no text/prompt/content string')
314
- }
315
-
316
- function resolvePrompts(options) {
317
- const prompts = [...options.prompts]
318
- if (options.textFile) prompts.push(...readTextFilePrompts(options.textFile))
319
- const list = prompts.length > 0 ? prompts.map((text) => String(text).trim()).filter(Boolean) : [...DEFAULT_PROMPTS]
320
- if (list.length === 0) throw new Error('no prompts resolved')
321
- return list
322
- }
323
-
324
- function buildRequests({ sessionId, turns, prompts, clientTimeZone }) {
325
- const runId = 'memu-eval-' + new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)
326
- + '-' + crypto.randomBytes(2).toString('hex')
327
- const requests = []
328
- for (let turn = 1; turn <= turns; turn += 1) {
329
- const text = prompts[(turn - 1) % prompts.length]
330
- // One identity, generated once: the log matcher and the wire request must
331
- // agree, and a retried request must not reuse it.
332
- const requestId = runId + '-' + String(turn).padStart(3, '0') + '-' + crypto.randomBytes(2).toString('hex')
333
- requests.push({
334
- turn,
335
- requestId,
336
- request: {
337
- requestId,
338
- sessionId,
339
- mode: 'queue',
340
- content: [{ type: 'text', text }],
341
- clientTimeZone,
342
- },
343
- })
344
- }
345
- return requests
346
- }
347
-
348
- function writeRequests(file, requests) {
349
- fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
350
- const body = requests.map((item) => JSON.stringify({ turn: item.turn, requestId: item.requestId, request: item.request })).join('\n') + '\n'
351
- fs.writeFileSync(file, body, 'utf8')
352
- }
353
-
354
- function printManualFallback({ reason, requests, requestsOut }) {
355
- const sample = requests[0]?.request
356
- console.error('MANUAL FALLBACK — nothing was sent.')
357
- console.error('')
358
- console.error('Reason: ' + reason)
359
- console.error('')
360
- console.error('This harness only calls the public remote below, and it will not touch the')
361
- console.error('shared /api route on its own:')
362
- console.error('')
363
- console.error(' sessionController.prompt({')
364
- console.error(' requestId, sessionId, mode: \'queue\',')
365
- console.error(' content: [{ type: \'text\', text }], clientTimeZone')
366
- console.error(' })')
367
- console.error('')
368
- console.error('Deliver each request with an approved client that can call that remote, then')
369
- console.error('read the mock-llm JSONL log with:')
370
- console.error('')
371
- console.error(' node scripts/mock-llm.mjs --report <mock-llm.jsonl> > mock-llm-report-YYYY-MM-DD.md')
372
- console.error('')
373
- console.error('If you explicitly accept the documented public Connection RPC carrier, re-run with:')
374
- console.error('')
375
- console.error(' --base <host gateway> --allow-api-route')
376
- console.error('')
377
- console.error('That carrier is POST <base>/api/session/prompt with a client-request envelope;')
378
- console.error('it is the same public remote the official browser client uses, not a private')
379
- console.error('endpoint. Without the opt-in flag this driver refuses to POST /api.')
380
- console.error('The Host browser-authenticates /api: add --cookie-file <path> (one Cookie')
381
- console.error('header value) if the carrier answers 401/403.')
382
- if (requestsOut) console.error('')
383
- if (requestsOut) console.error('All ' + requests.length + ' request objects were written to ' + path.resolve(requestsOut) + '.')
384
- else if (requests.length > 5) console.error('Rerun with --requests-out <path> to write all ' + requests.length + ' request objects as JSONL.')
385
- console.error('')
386
- if (!requestsOut && requests.length <= 5) {
387
- for (const item of requests) {
388
- console.error('turn ' + item.turn + ':')
389
- console.error(JSON.stringify(item.request, null, 2))
390
- }
391
- } else {
392
- console.error('First request (' + requests.length + ' total):')
393
- console.error(JSON.stringify(sample, null, 2))
394
- }
395
- }
396
-
397
- /**
398
- * Encode one Session id as the persistence layer does (host format.ts
399
- * encodeSegment). Kept local so the harness imports no host or plugin code.
400
- */
401
- function encodeSegment(raw) {
402
- let out = ''
403
- for (let i = 0; i < raw.length; i += 1) {
404
- const ch = String.fromCharCode(raw.charCodeAt(i))
405
- if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
406
- else out += '~' + raw.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0')
407
- }
408
- return out
409
- }
410
-
411
- const LOG_SUFFIXES = ['session.v4.jsonl.zstd', 'session.v4.jsonl', 'session.jsonl.zstd', 'session.jsonl']
412
-
413
- function locateSessionLog({ explicit, dshHome, sessionId }) {
414
- if (explicit) {
415
- const resolved = path.resolve(explicit)
416
- return fs.existsSync(resolved) ? resolved : null
417
- }
418
- const root = path.join(dshHome, 'sessions')
419
- let projects
420
- try { projects = fs.readdirSync(root, { withFileTypes: true }) } catch { return null }
421
- const encoded = encodeSegment(sessionId)
422
- for (const project of projects) {
423
- if (!project.isDirectory()) continue
424
- for (const dirName of [sessionId, encoded]) {
425
- const dir = path.join(root, project.name, dirName)
426
- for (const suffix of LOG_SUFFIXES) {
427
- const candidate = path.join(dir, suffix)
428
- if (fs.existsSync(candidate)) return candidate
429
- }
430
- }
431
- }
432
- return null
433
- }
434
-
435
- const ZSTD_MAGIC = 0xFD2FB528
436
-
437
- /**
438
- * Locate complete Zstandard frames in a concatenated log.
439
- *
440
- * Mirrors the structural scan in the host's session-persistence-jsonl package
441
- * (src/zstd.ts) because Node's one-shot decompressor stops after the first
442
- * frame and this harness must not import host packages. The final frame may be
443
- * torn while the host is writing; it is left for the next poll.
444
- */
445
- function scanZstdFrames(buffer) {
446
- const frames = []
447
- let offset = 0
448
- while (offset < buffer.length) {
449
- const start = offset
450
- if (buffer.length - offset < 4) return { frames, tornStart: start }
451
- if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error('corrupt session log: bad zstd magic at byte ' + offset)
452
- offset += 4
453
- if (offset === buffer.length) return { frames, tornStart: start }
454
- const descriptor = buffer.readUInt8(offset)
455
- offset += 1
456
- if ((descriptor & 0x18) !== 0) throw new Error('corrupt session log: reserved frame-header bit')
457
- const contentSizeFlag = descriptor >>> 6
458
- const singleSegment = (descriptor & 0x20) !== 0
459
- const checksum = (descriptor & 0x04) !== 0
460
- const dictionaryFlag = descriptor & 0x03
461
- const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
462
- const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
463
- const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
464
- if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
465
- offset += remainingHeaderBytes
466
- for (;;) {
467
- if (buffer.length - offset < 3) return { frames, tornStart: start }
468
- const blockHeader = buffer.readUIntLE(offset, 3)
469
- offset += 3
470
- const lastBlock = (blockHeader & 1) !== 0
471
- const blockType = (blockHeader >>> 1) & 0x03
472
- const blockSize = blockHeader >>> 3
473
- if (blockType === 0x03) throw new Error('corrupt session log: reserved block type')
474
- const payloadBytes = blockType === 0x01 ? 1 : blockSize
475
- if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
476
- offset += payloadBytes
477
- if (lastBlock) break
478
- }
479
- if (checksum) {
480
- if (buffer.length - offset < 4) return { frames, tornStart: start }
481
- offset += 4
482
- }
483
- frames.push({ start, end: offset })
484
- }
485
- return { frames }
486
- }
487
-
488
- function readSessionEvents(file) {
489
- const raw = fs.readFileSync(file)
490
- let text
491
- if (file.endsWith('.zstd')) {
492
- const { frames } = scanZstdFrames(raw)
493
- const parts = []
494
- for (const frame of frames) {
495
- try {
496
- parts.push(zlib.zstdDecompressSync(raw.subarray(frame.start, frame.end)))
497
- } catch (error) {
498
- throw new Error('cannot decompress session log frame at byte ' + frame.start + ': ' + error.message)
499
- }
500
- }
501
- text = Buffer.concat(parts).toString('utf8')
502
- } else {
503
- text = raw.toString('utf8')
504
- }
505
- const events = []
506
- for (const line of text.split(/\r?\n/)) {
507
- if (!line.trim()) continue
508
- try {
509
- const value = JSON.parse(line)
510
- if (value && typeof value === 'object') events.push(value)
511
- } catch {
512
- // The host appends complete JSON lines; a torn line is retried next poll.
513
- }
514
- }
515
- return events
516
- }
517
-
518
- /**
519
- * Index of the durable user/message that claims this requestId.
520
- *
521
- * The inbox `agent/inbox/spliced` event proves admission but not that a turn
522
- * consumed the prompt, so it is deliberately not used as the anchor. A
523
- * `user/message` appears inside the turn that actually claims the prompt, which
524
- * is what lets the wait below pair it with the right turn/end.
525
- */
526
- function promptClaimIndex(events, requestId) {
527
- for (let i = events.length - 1; i >= 0; i -= 1) {
528
- const event = events[i]
529
- if (event?.type === 'user/message' && event?.data?.source?.rpcId === requestId) return i
530
- }
531
- return -1
532
- }
533
-
534
- /** Whether the host durably admitted this requestId (before a turn claims it). */
535
- function promptAdmitted(events, requestId) {
536
- return events.some((event) => event?.type === 'agent/inbox/spliced'
537
- && Array.isArray(event?.data?.inserted)
538
- && event.data.inserted.some((item) => item?.source?.rpcId === requestId))
539
- }
540
-
541
- /** Turn number of the `turn/start` that encloses one claimed user message. */
542
- function enclosingTurn(events, claimIndex) {
543
- for (let i = claimIndex - 1; i >= 0; i -= 1) {
544
- const event = events[i]
545
- if (event?.type === 'turn/start') {
546
- const turn = Number(event?.data?.turn)
547
- return Number.isSafeInteger(turn) ? turn : null
548
- }
549
- if (event?.type === 'turn/end') return null
550
- }
551
- return null
552
- }
553
-
554
- /**
555
- * Read the public session log until the prompt's own turn/end appears.
556
- *
557
- * A queued prompt may be claimed in the middle of an existing long turn, so the
558
- * enclosing turn is read from the log instead of assuming a fresh turn starts.
559
- * Only `reason.kind === 'completed'` counts as success.
560
- *
561
- * @returns {{state:'completed'|'failed'|'timeout', reason:string, waitedMs:number}}
562
- */
563
- async function waitForTurn({ logPath, requestId, timeoutMs, pollMs }) {
564
- const started = Date.now()
565
- const deadline = started + timeoutMs
566
- let admitted = false
567
- let lastReadError = null
568
- while (Date.now() < deadline) {
569
- try {
570
- const events = readSessionEvents(logPath)
571
- if (!admitted && promptAdmitted(events, requestId)) admitted = true
572
- const claim = promptClaimIndex(events, requestId)
573
- if (claim >= 0) {
574
- const turn = enclosingTurn(events, claim)
575
- for (let i = claim + 1; i < events.length; i += 1) {
576
- const event = events[i]
577
- if (event?.type !== 'turn/end') continue
578
- const endedTurn = Number(event?.data?.turn)
579
- if (turn !== null && Number.isSafeInteger(endedTurn) && endedTurn !== turn) {
580
- return {
581
- state: 'failed',
582
- reason: 'turn/end turn=' + endedTurn + ' does not match the claiming turn=' + turn,
583
- waitedMs: Date.now() - started,
584
- }
585
- }
586
- const reason = event?.data?.reason?.kind
587
- if (reason === 'completed') {
588
- return { state: 'completed', reason: 'completed', waitedMs: Date.now() - started }
589
- }
590
- return {
591
- state: 'failed',
592
- reason: 'turn/end reason=' + String(reason || 'unknown'),
593
- waitedMs: Date.now() - started,
594
- }
595
- }
596
- }
597
- lastReadError = null
598
- } catch (error) {
599
- lastReadError = error?.message || String(error)
600
- }
601
- await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))))
602
- }
603
- if (lastReadError) {
604
- return { state: 'timeout', reason: 'cannot read session log: ' + lastReadError, waitedMs: timeoutMs }
605
- }
606
- return {
607
- state: 'timeout',
608
- reason: admitted ? 'prompt was admitted but no turn claimed it before the deadline' : 'prompt not observed in the session log',
609
- waitedMs: timeoutMs,
610
- }
611
- }
612
-
613
- function joinUrl(base, suffix) {
614
- return String(base).replace(/\/+$/, '') + suffix
615
- }
616
-
617
- /**
618
- * The Connection RPC carrier wraps each Remote method parameter by **name**, so a
619
- * single-argument remote must go out as `{ args: { request: <SessionPromptRequest> } }`.
620
- * Sending the request fields directly is rejected before the host ever sees them
621
- * (`gateway/arguments-invalid: missing "request"`) — which is what this file did until it
622
- * actually met a real host.
623
- */
624
- export function buildPromptEnvelope(request, rpcId = crypto.randomUUID()) {
625
- return {
626
- type: 'client-request',
627
- rpcId,
628
- method: 'session/prompt',
629
- payload: { args: { request } },
630
- }
631
- }
632
-
633
- async function sendPrompt({ base, request, timeoutMs, cookie }) {
634
- const url = joinUrl(base, '/api/session/prompt')
635
- const envelope = buildPromptEnvelope(request)
636
- const headers = { 'content-type': 'application/json' }
637
- if (cookie) headers.cookie = cookie
638
- let response
639
- try {
640
- response = await fetch(url, {
641
- method: 'POST',
642
- headers,
643
- body: JSON.stringify(envelope),
644
- signal: AbortSignal.timeout(Math.min(timeoutMs, 2_147_483_647)),
645
- })
646
- } catch (error) {
647
- throw new Error('transport failure for ' + url + ': ' + (error?.message || error))
648
- }
649
- const text = await response.text()
650
- if (!response.ok) {
651
- const hint = response.status === 401 || response.status === 403
652
- ? ' (the Host authenticates /api; pass --cookie-file with the browser session cookie)'
653
- : ''
654
- throw new Error('HTTP ' + response.status + ' from ' + url + hint + ': ' + text.slice(0, 240))
655
- }
656
- let body
657
- try {
658
- body = JSON.parse(text)
659
- } catch {
660
- throw new Error('response is not JSON (expected a Connection RPC envelope)')
661
- }
662
- if (!body || body.type !== 'server-response' || body.rpcId !== envelope.rpcId) {
663
- throw new Error('response is not the matching Connection RPC envelope')
664
- }
665
- if (!body.result || body.result.ok !== true) {
666
- const failure = body.result?.error || {}
667
- throw new Error('session/prompt rejected: ' + String(failure.code || 'unknown') + ': ' + String(failure.message || 'no message'))
668
- }
669
- if (body.result.value?.accepted !== true) {
670
- throw new Error('session/prompt did not return { accepted: true }')
671
- }
672
- return { rpcId: envelope.rpcId }
673
- }
674
-
675
- function isLoopbackHost(hostname) {
676
- return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1'
677
- }
678
-
679
- async function main(argv = process.argv.slice(2)) {
680
- let options
681
- try {
682
- options = parseArgs(argv)
683
- } catch (error) {
684
- return failUsage(error.message)
685
- }
686
- if (options.help) {
687
- process.stdout.write(USAGE)
688
- return EXIT_OK
689
- }
690
- if (!options.session || !String(options.session).trim()) {
691
- return failUsage('--session is required')
692
- }
693
- if (options.base) {
694
- let parsed
695
- try { parsed = new URL(options.base) } catch { return failUsage('--base is not a valid URL') }
696
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return failUsage('--base must be http(s)')
697
- if (!isLoopbackHost(parsed.hostname)) {
698
- console.error('drive-session: warning: --base is not loopback (' + parsed.hostname + '); the harness sends no credentials, so an authenticated host will reject it')
699
- }
700
- }
701
-
702
- const clientTimeZone = options.clientTimeZone || defaultClientTimeZone()
703
- let prompts
704
- try {
705
- prompts = resolvePrompts(options)
706
- } catch (error) {
707
- return failUsage(error.message)
708
- }
709
- const requests = buildRequests({
710
- sessionId: String(options.session).trim(),
711
- turns: options.turns,
712
- prompts,
713
- clientTimeZone,
714
- })
715
-
716
- let cookie = null
717
- if (options.cookieFile) {
718
- try {
719
- cookie = fs.readFileSync(options.cookieFile, 'utf8').trim()
720
- } catch (error) {
721
- return failUsage('cannot read --cookie-file: ' + error.message)
722
- }
723
- if (!cookie || /[\r\n]/.test(cookie)) {
724
- return failUsage('--cookie-file must contain exactly one Cookie header value (no line breaks)')
725
- }
726
- }
727
-
728
- if (options.requestsOut) {
729
- try { writeRequests(options.requestsOut, requests) } catch (error) {
730
- console.error('drive-session: cannot write --requests-out: ' + error.message)
731
- return EXIT_FAILED
732
- }
733
- }
734
-
735
- if (options.dryRun) {
736
- for (const item of requests) {
737
- process.stdout.write(JSON.stringify({ turn: item.turn, request: item.request }) + '\n')
738
- }
739
- console.log('drive-session: dry run — ' + requests.length + ' request(s) generated, nothing sent')
740
- return EXIT_OK
741
- }
742
-
743
- if (!options.allowApiRoute) {
744
- printManualFallback({
745
- reason: 'no approved public-remote carrier. Work order B forbids silently POSTing /api.',
746
- requests,
747
- requestsOut: options.requestsOut,
748
- })
749
- return EXIT_MANUAL
750
- }
751
- if (!options.base) {
752
- printManualFallback({
753
- reason: '--allow-api-route needs --base <host gateway>; there is nowhere to send the public remote.',
754
- requests,
755
- requestsOut: options.requestsOut,
756
- })
757
- return EXIT_MANUAL
758
- }
759
-
760
- const dshHome = options.dshHome || process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
761
- const sessionLog = locateSessionLog({
762
- explicit: options.sessionLog,
763
- dshHome,
764
- sessionId: String(options.session).trim(),
765
- })
766
- if (!sessionLog) {
767
- console.error('drive-session: preflight failed — no session log for ' + options.session)
768
- console.error(' looked under: ' + path.join(dshHome, 'sessions'))
769
- console.error(' Pass --session-log <path> with the exact session.v4.jsonl.zstd file,')
770
- console.error(' or --dsh-home <path> if DSH_HOME is not ' + dshHome + '.')
771
- console.error(' Nothing was sent: without the public session log a turn cannot be observed as completed.')
772
- return EXIT_PREFLIGHT
773
- }
774
- try {
775
- readSessionEvents(sessionLog)
776
- } catch (error) {
777
- console.error('drive-session: preflight failed — cannot read ' + sessionLog + ': ' + error.message)
778
- console.error(' Nothing was sent.')
779
- return EXIT_PREFLIGHT
780
- }
781
-
782
- console.log('drive-session: ' + requests.length + ' turn(s) → session ' + options.session)
783
- console.log(' base: ' + joinUrl(options.base, '/api/session/prompt') + ' (explicit --allow-api-route)')
784
- console.log(' session log: ' + sessionLog)
785
- console.log(' clientTimeZone: ' + clientTimeZone)
786
- console.log(' cookie: ' + (cookie ? 'supplied via --cookie-file (not printed)' : 'none (a Host with browser auth will answer 401)'))
787
- if (options.requestsOut) console.log(' requests: ' + path.resolve(options.requestsOut))
788
-
789
- const started = Date.now()
790
- let completed = 0
791
- let failed = 0
792
- let lastFailure = null
793
- for (const item of requests) {
794
- const turnStarted = Date.now()
795
- try {
796
- await sendPrompt({ base: options.base, request: item.request, timeoutMs: options.timeoutMs, cookie })
797
- } catch (error) {
798
- failed += 1
799
- lastFailure = { turn: item.turn, stage: 'send', reason: error.message }
800
- console.error('turn ' + item.turn + '/' + requests.length + ' SEND FAILED: ' + error.message)
801
- break
802
- }
803
- // One per-turn budget: admission time is charged against completion time.
804
- const remaining = Math.max(1_000, options.timeoutMs - (Date.now() - turnStarted))
805
- const waited = await waitForTurn({
806
- logPath: sessionLog,
807
- requestId: item.request.requestId,
808
- timeoutMs: remaining,
809
- pollMs: options.pollMs,
810
- })
811
- if (waited.state !== 'completed') {
812
- failed += 1
813
- lastFailure = { turn: item.turn, stage: 'wait', reason: waited.state + ': ' + waited.reason }
814
- console.error('turn ' + item.turn + '/' + requests.length + ' WAIT FAILED: ' + waited.state + ' (' + waited.reason + ')')
815
- break
816
- }
817
- completed += 1
818
- const elapsed = Date.now() - turnStarted
819
- console.log('turn ' + item.turn + '/' + requests.length + ' completed in ' + elapsed + 'ms (requestId ' + item.request.requestId + ')')
820
- if (options.intervalMs > 0 && item.turn < requests.length) {
821
- await new Promise((resolve) => setTimeout(resolve, options.intervalMs))
822
- }
823
- }
824
-
825
- const totalMs = Date.now() - started
826
- console.log('')
827
- console.log('summary: sent+completed=' + completed + ' failed=' + failed + ' requested=' + requests.length + ' elapsed=' + totalMs + 'ms')
828
- if (lastFailure) {
829
- console.log('first failure: turn ' + lastFailure.turn + ' (' + lastFailure.stage + ') ' + lastFailure.reason)
830
- return EXIT_FAILED
831
- }
832
- if (completed !== requests.length) {
833
- console.log('run stopped before every requested turn completed')
834
- return EXIT_FAILED
835
- }
836
- console.log('all requested turns completed')
837
- return EXIT_OK
838
- }
839
-
840
- const invokedDirectly = process.argv[1]
841
- ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
842
- : false
843
- if (invokedDirectly) {
844
- main().then((code) => { process.exitCode = typeof code === 'number' ? code : EXIT_FAILED }).catch((error) => {
845
- console.error('drive-session: ' + (error?.stack || error))
846
- process.exitCode = EXIT_FAILED
847
- })
848
- }
849
-
850
- export {
851
- DEFAULT_PROMPTS,
852
- buildRequests,
853
- encodeSegment,
854
- enclosingTurn,
855
- locateSessionLog,
856
- parseArgs,
857
- promptAdmitted,
858
- promptClaimIndex,
859
- readSessionEvents,
860
- scanZstdFrames,
861
- sendPrompt,
862
- textOfPromptItem,
863
- waitForTurn,
864
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EVALUATION ONLY — drive one bound conversation through the public Session
4
+ * remote. This diagnostic script is not imported by runtime code.
5
+ *
6
+ * Public request shape (verified against the host source on 2026-11-01):
7
+ *
8
+ * packages/api/session-controller/src/types.ts
9
+ * interface SessionPromptRequest {
10
+ * requestId: SessionRequestId
11
+ * sessionId: SessionId
12
+ * mode: 'queue' | 'steer'
13
+ * content: readonly PromptContentPart[] // {type:'text', text}
14
+ * clientTimeZone?: string // 'UTC' or a valid IANA name
15
+ * }
16
+ *
17
+ * packages/api/session-controller/src/index.ts
18
+ * @Remote('prompt') prompt(request, signal) -> { accepted: true }
19
+ *
20
+ * Transport rule
21
+ * --------------
22
+ * The generated client calls this unary method through the Connection RPC
23
+ * carrier; its documented wire form is (docs/api-gateway.md):
24
+ *
25
+ * POST <base>/api/session/prompt
26
+ * {
27
+ * "type": "client-request",
28
+ * "rpcId": "<connection correlation id>",
29
+ * "method": "session/prompt",
30
+ * "payload": { "args": { "request": <SessionPromptRequest> } }
31
+ * }
32
+ * ->
33
+ * { "type": "server-response", "rpcId": "<same>", "result": { "ok": true, "value": { "accepted": true } } }
34
+ *
35
+ * There is no stream-carrier form for this method: the API Gateway rejects a
36
+ * unary method opened through /api/remote.mux with gateway/signature-invalid.
37
+ *
38
+ * Work order B forbids silently calling the shared /api route. Therefore this
39
+ * script deliberately REFUSES to send anything unless --allow-api-route is
40
+ * passed together with --base. Without that explicit opt-in it prints the exact
41
+ * requests as a manual fallback and exits non-zero (code 3). This is not a
42
+ * missing feature; it is the rule.
43
+ *
44
+ * Authentication assumption: the Host's /api route is behind its persistent
45
+ * browser authentication (connection.admit() returns 401 without a valid
46
+ * cookie). If the target Host enforces it, pass --cookie-file with the single
47
+ * Cookie header value copied from the authenticated browser session. This
48
+ * harness never prints or stores that value, and it sends no other credentials.
49
+ * A non-loopback --base would additionally need the Host's trustedHosts setup;
50
+ * the harness warns but does not bypass it.
51
+ *
52
+ * Completion is observed from the public persisted session log
53
+ * (<DSH_HOME>/sessions/<project>/<sessionId>/session.v4.jsonl.zstd), the same
54
+ * artifact docs/host-api.md §6.8 describes. No private endpoint and no plugin
55
+ * RPC is called. A turn counts as done only when a turn/end for this prompt
56
+ * reports reason.kind === 'completed'.
57
+ *
58
+ * Usage:
59
+ * node scripts/drive-session.mjs --session <id> --turns 50 \
60
+ * --base http://127.0.0.1:<host-gateway-port> --allow-api-route \
61
+ * --requests-out ./requests.jsonl
62
+ * node scripts/drive-session.mjs --session <id> --turns 5 --dry-run
63
+ *
64
+ * Exit codes:
65
+ * 0 all requested turns completed
66
+ * 1 a turn or the transport failed (the first failure stops the run)
67
+ * 2 usage error
68
+ * 3 manual fallback: nothing was sent (no approved transport)
69
+ * 4 preflight failure: the session log needed to observe turn/end is absent
70
+ */
71
+ import crypto from 'node:crypto'
72
+ import fs from 'node:fs'
73
+ import os from 'node:os'
74
+ import path from 'node:path'
75
+ import zlib from 'node:zlib'
76
+ import { pathToFileURL } from 'node:url'
77
+
78
+ const EXIT_OK = 0
79
+ const EXIT_FAILED = 1
80
+ const EXIT_USAGE = 2
81
+ const EXIT_MANUAL = 3
82
+ const EXIT_PREFLIGHT = 4
83
+
84
+ const DEFAULT_TURNS = 50
85
+ const DEFAULT_TIMEOUT_MS = 180_000
86
+ const DEFAULT_POLL_MS = 400
87
+
88
+ /**
89
+ * Neutral prompts used only when neither --prompt nor --text-file is supplied.
90
+ * They contain no user data and are cycled to reach --turns.
91
+ */
92
+ const DEFAULT_PROMPTS = Object.freeze([
93
+ '今天有点累,随便聊聊吧。',
94
+ '你还记得我昨天提到的那件事吗?',
95
+ '帮我把今天要做的事理一理。',
96
+ '我们上次说到哪儿了?',
97
+ '明天有什么安排吗?',
98
+ '我想起一个很久以前的小事。',
99
+ '给我讲讲你最近在忙什么。',
100
+ '如果要去一个陌生的城市,你会先做什么?',
101
+ '今天天气怎么样?凭记忆回答就好。',
102
+ '晚安,明天见。',
103
+ ])
104
+
105
+ const USAGE = `EVALUATION ONLY — drive one conversation through the public Session prompt remote.
106
+
107
+ Usage:
108
+ node scripts/drive-session.mjs --session <id> [options] [--prompt <text> ...]
109
+
110
+ Required:
111
+ --session <id> Target SessionId (the conversation must already be
112
+ bound to the test library).
113
+
114
+ Transport:
115
+ --base <url> Host gateway base, e.g. http://127.0.0.1:3000
116
+ (the Host's own port, not the mock LLM port).
117
+ --allow-api-route Explicitly permit the documented public Connection RPC
118
+ carrier POST <base>/api/session/prompt. Without this
119
+ flag and --base, nothing is sent: the script prints a
120
+ manual fallback and exits 3.
121
+ --cookie-file <p> File holding one Cookie header value for /api. The
122
+ Host browser-authenticates /api, so a real Host
123
+ usually returns 401 without it. The value is never
124
+ printed or stored by this script.
125
+
126
+ Turns:
127
+ --turns <n> Number of prompts. Default: ${DEFAULT_TURNS}.
128
+ --prompt <text> One prompt; repeatable. Positional text after options
129
+ is also accepted as prompts.
130
+ --text-file <p> .json array of strings / {text|prompt|content} objects,
131
+ or one prompt per non-empty line. Optional: without it
132
+ the built-in neutral prompts are cycled.
133
+ --interval-ms <n> Wait between completed turns. Default: 0.
134
+ --timeout-ms <n> Per-turn send + completion budget. Default: ${DEFAULT_TIMEOUT_MS}.
135
+ --poll-ms <n> Session-log poll interval. Default: ${DEFAULT_POLL_MS}.
136
+ --client-time-zone <iana> IANA name sent as clientTimeZone. Default: system zone.
137
+
138
+ Observation:
139
+ --session-log <p> Exact session log path (skips discovery).
140
+ --dsh-home <p> DSH home used for discovery. Default: $DSH_HOME or ~/.dsh.
141
+
142
+ Output:
143
+ --requests-out <p> Write the exact request objects as JSONL before sending.
144
+ This file contains the prompt text; delete it after use
145
+ and do not commit it.
146
+ --dry-run Print the requests and exit 0 without sending.
147
+ -h, --help Show this text.
148
+
149
+ Public request sent for every turn:
150
+ sessionController.prompt({
151
+ requestId: '<unique per turn>',
152
+ sessionId: '<--session>',
153
+ mode: 'queue',
154
+ content: [{ type: 'text', text: '<prompt>' }],
155
+ clientTimeZone: '<IANA>'
156
+ })
157
+
158
+ The run stops on the first failure. A timeout or a non-completed turn/end is a
159
+ failure and is not counted as a valid turn. No /api call is made without
160
+ --allow-api-route.
161
+ `
162
+
163
+ function failUsage(message) {
164
+ console.error('drive-session: ' + message + '\n')
165
+ console.error(USAGE)
166
+ return EXIT_USAGE
167
+ }
168
+
169
+ function parseArgs(argv) {
170
+ const options = {
171
+ base: null,
172
+ session: null,
173
+ turns: DEFAULT_TURNS,
174
+ intervalMs: 0,
175
+ timeoutMs: DEFAULT_TIMEOUT_MS,
176
+ pollMs: DEFAULT_POLL_MS,
177
+ textFile: null,
178
+ prompts: [],
179
+ clientTimeZone: null,
180
+ sessionLog: null,
181
+ dshHome: null,
182
+ requestsOut: null,
183
+ cookieFile: null,
184
+ allowApiRoute: false,
185
+ dryRun: false,
186
+ help: false,
187
+ }
188
+ const take = (index, name) => {
189
+ const value = argv[index]
190
+ if (value === undefined || value.startsWith('--')) throw new Error(name + ' requires a value')
191
+ return value
192
+ }
193
+ for (let i = 0; i < argv.length; i += 1) {
194
+ const token = argv[i]
195
+ if (token === '-h') {
196
+ options.help = true
197
+ continue
198
+ }
199
+ if (!token.startsWith('--')) {
200
+ options.prompts.push(token)
201
+ continue
202
+ }
203
+ const eq = token.indexOf('=')
204
+ const name = eq === -1 ? token : token.slice(0, eq)
205
+ const inline = eq === -1 ? null : token.slice(eq + 1)
206
+ switch (name) {
207
+ case '--help':
208
+ options.help = true
209
+ break
210
+ case '--base':
211
+ options.base = inline ?? take(++i, '--base')
212
+ break
213
+ case '--session':
214
+ options.session = inline ?? take(++i, '--session')
215
+ break
216
+ case '--turns':
217
+ options.turns = positiveInt(inline ?? take(++i, '--turns'), '--turns')
218
+ break
219
+ case '--interval-ms':
220
+ options.intervalMs = nonNegativeInt(inline ?? take(++i, '--interval-ms'), '--interval-ms')
221
+ break
222
+ case '--timeout-ms':
223
+ options.timeoutMs = positiveInt(inline ?? take(++i, '--timeout-ms'), '--timeout-ms')
224
+ break
225
+ case '--poll-ms':
226
+ options.pollMs = positiveInt(inline ?? take(++i, '--poll-ms'), '--poll-ms')
227
+ break
228
+ case '--text-file':
229
+ options.textFile = inline ?? take(++i, '--text-file')
230
+ break
231
+ case '--prompt':
232
+ options.prompts.push(inline ?? take(++i, '--prompt'))
233
+ break
234
+ case '--client-time-zone':
235
+ options.clientTimeZone = inline ?? take(++i, '--client-time-zone')
236
+ break
237
+ case '--session-log':
238
+ options.sessionLog = inline ?? take(++i, '--session-log')
239
+ break
240
+ case '--dsh-home':
241
+ options.dshHome = inline ?? take(++i, '--dsh-home')
242
+ break
243
+ case '--requests-out':
244
+ options.requestsOut = inline ?? take(++i, '--requests-out')
245
+ break
246
+ case '--cookie-file':
247
+ options.cookieFile = inline ?? take(++i, '--cookie-file')
248
+ break
249
+ case '--allow-api-route':
250
+ if (inline !== null) throw new Error('--allow-api-route does not take a value')
251
+ options.allowApiRoute = true
252
+ break
253
+ case '--dry-run':
254
+ if (inline !== null) throw new Error('--dry-run does not take a value')
255
+ options.dryRun = true
256
+ break
257
+ default:
258
+ throw new Error('unknown option: ' + token)
259
+ }
260
+ }
261
+ return options
262
+ }
263
+
264
+ function positiveInt(value, name) {
265
+ const number = Number(value)
266
+ if (!Number.isSafeInteger(number) || number <= 0) throw new Error(name + ' must be a positive integer')
267
+ return number
268
+ }
269
+
270
+ function nonNegativeInt(value, name) {
271
+ const number = Number(value)
272
+ if (!Number.isSafeInteger(number) || number < 0) throw new Error(name + ' must be a non-negative integer')
273
+ return number
274
+ }
275
+
276
+ function defaultClientTimeZone() {
277
+ try {
278
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
279
+ return typeof zone === 'string' && zone ? zone : 'UTC'
280
+ } catch {
281
+ return 'UTC'
282
+ }
283
+ }
284
+
285
+ function readTextFilePrompts(file) {
286
+ const raw = fs.readFileSync(file, 'utf8')
287
+ if (path.extname(file).toLowerCase() === '.json') {
288
+ let value
289
+ try { value = JSON.parse(raw) } catch (error) { throw new Error('--text-file is not valid JSON: ' + error.message) }
290
+ if (!Array.isArray(value)) throw new Error('--text-file JSON must be an array')
291
+ const prompts = value.map((item, index) => textOfPromptItem(item, index)).filter(Boolean)
292
+ if (prompts.length === 0) throw new Error('--text-file JSON array contains no prompts')
293
+ return prompts
294
+ }
295
+ const prompts = raw.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith('#'))
296
+ if (prompts.length === 0) throw new Error('--text-file contains no non-empty lines')
297
+ return prompts
298
+ }
299
+
300
+ function textOfPromptItem(item, index) {
301
+ if (typeof item === 'string') return item.trim()
302
+ if (!item || typeof item !== 'object') throw new Error('--text-file item ' + (index + 1) + ' is not a string or object')
303
+ const candidate = item.text ?? item.prompt ?? item.content
304
+ if (typeof candidate === 'string') return candidate.trim()
305
+ if (Array.isArray(candidate)) {
306
+ const text = candidate
307
+ .map((part) => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : ''))
308
+ .filter(Boolean)
309
+ .join('\n')
310
+ .trim()
311
+ if (text) return text
312
+ }
313
+ throw new Error('--text-file item ' + (index + 1) + ' has no text/prompt/content string')
314
+ }
315
+
316
+ function resolvePrompts(options) {
317
+ const prompts = [...options.prompts]
318
+ if (options.textFile) prompts.push(...readTextFilePrompts(options.textFile))
319
+ const list = prompts.length > 0 ? prompts.map((text) => String(text).trim()).filter(Boolean) : [...DEFAULT_PROMPTS]
320
+ if (list.length === 0) throw new Error('no prompts resolved')
321
+ return list
322
+ }
323
+
324
+ function buildRequests({ sessionId, turns, prompts, clientTimeZone }) {
325
+ const runId = 'memu-eval-' + new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)
326
+ + '-' + crypto.randomBytes(2).toString('hex')
327
+ const requests = []
328
+ for (let turn = 1; turn <= turns; turn += 1) {
329
+ const text = prompts[(turn - 1) % prompts.length]
330
+ // One identity, generated once: the log matcher and the wire request must
331
+ // agree, and a retried request must not reuse it.
332
+ const requestId = runId + '-' + String(turn).padStart(3, '0') + '-' + crypto.randomBytes(2).toString('hex')
333
+ requests.push({
334
+ turn,
335
+ requestId,
336
+ request: {
337
+ requestId,
338
+ sessionId,
339
+ mode: 'queue',
340
+ content: [{ type: 'text', text }],
341
+ clientTimeZone,
342
+ },
343
+ })
344
+ }
345
+ return requests
346
+ }
347
+
348
+ function writeRequests(file, requests) {
349
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
350
+ const body = requests.map((item) => JSON.stringify({ turn: item.turn, requestId: item.requestId, request: item.request })).join('\n') + '\n'
351
+ fs.writeFileSync(file, body, 'utf8')
352
+ }
353
+
354
+ function printManualFallback({ reason, requests, requestsOut }) {
355
+ const sample = requests[0]?.request
356
+ console.error('MANUAL FALLBACK — nothing was sent.')
357
+ console.error('')
358
+ console.error('Reason: ' + reason)
359
+ console.error('')
360
+ console.error('This harness only calls the public remote below, and it will not touch the')
361
+ console.error('shared /api route on its own:')
362
+ console.error('')
363
+ console.error(' sessionController.prompt({')
364
+ console.error(' requestId, sessionId, mode: \'queue\',')
365
+ console.error(' content: [{ type: \'text\', text }], clientTimeZone')
366
+ console.error(' })')
367
+ console.error('')
368
+ console.error('Deliver each request with an approved client that can call that remote, then')
369
+ console.error('read the mock-llm JSONL log with:')
370
+ console.error('')
371
+ console.error(' node scripts/mock-llm.mjs --report <mock-llm.jsonl> > mock-llm-report-YYYY-MM-DD.md')
372
+ console.error('')
373
+ console.error('If you explicitly accept the documented public Connection RPC carrier, re-run with:')
374
+ console.error('')
375
+ console.error(' --base <host gateway> --allow-api-route')
376
+ console.error('')
377
+ console.error('That carrier is POST <base>/api/session/prompt with a client-request envelope;')
378
+ console.error('it is the same public remote the official browser client uses, not a private')
379
+ console.error('endpoint. Without the opt-in flag this driver refuses to POST /api.')
380
+ console.error('The Host browser-authenticates /api: add --cookie-file <path> (one Cookie')
381
+ console.error('header value) if the carrier answers 401/403.')
382
+ if (requestsOut) console.error('')
383
+ if (requestsOut) console.error('All ' + requests.length + ' request objects were written to ' + path.resolve(requestsOut) + '.')
384
+ else if (requests.length > 5) console.error('Rerun with --requests-out <path> to write all ' + requests.length + ' request objects as JSONL.')
385
+ console.error('')
386
+ if (!requestsOut && requests.length <= 5) {
387
+ for (const item of requests) {
388
+ console.error('turn ' + item.turn + ':')
389
+ console.error(JSON.stringify(item.request, null, 2))
390
+ }
391
+ } else {
392
+ console.error('First request (' + requests.length + ' total):')
393
+ console.error(JSON.stringify(sample, null, 2))
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Encode one Session id as the persistence layer does (host format.ts
399
+ * encodeSegment). Kept local so the harness imports no host or plugin code.
400
+ */
401
+ function encodeSegment(raw) {
402
+ let out = ''
403
+ for (let i = 0; i < raw.length; i += 1) {
404
+ const ch = String.fromCharCode(raw.charCodeAt(i))
405
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
406
+ else out += '~' + raw.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0')
407
+ }
408
+ return out
409
+ }
410
+
411
+ const LOG_SUFFIXES = ['session.v4.jsonl.zstd', 'session.v4.jsonl', 'session.jsonl.zstd', 'session.jsonl']
412
+
413
+ function locateSessionLog({ explicit, dshHome, sessionId }) {
414
+ if (explicit) {
415
+ const resolved = path.resolve(explicit)
416
+ return fs.existsSync(resolved) ? resolved : null
417
+ }
418
+ const root = path.join(dshHome, 'sessions')
419
+ let projects
420
+ try { projects = fs.readdirSync(root, { withFileTypes: true }) } catch { return null }
421
+ const encoded = encodeSegment(sessionId)
422
+ for (const project of projects) {
423
+ if (!project.isDirectory()) continue
424
+ for (const dirName of [sessionId, encoded]) {
425
+ const dir = path.join(root, project.name, dirName)
426
+ for (const suffix of LOG_SUFFIXES) {
427
+ const candidate = path.join(dir, suffix)
428
+ if (fs.existsSync(candidate)) return candidate
429
+ }
430
+ }
431
+ }
432
+ return null
433
+ }
434
+
435
+ const ZSTD_MAGIC = 0xFD2FB528
436
+
437
+ /**
438
+ * Locate complete Zstandard frames in a concatenated log.
439
+ *
440
+ * Mirrors the structural scan in the host's session-persistence-jsonl package
441
+ * (src/zstd.ts) because Node's one-shot decompressor stops after the first
442
+ * frame and this harness must not import host packages. The final frame may be
443
+ * torn while the host is writing; it is left for the next poll.
444
+ */
445
+ function scanZstdFrames(buffer) {
446
+ const frames = []
447
+ let offset = 0
448
+ while (offset < buffer.length) {
449
+ const start = offset
450
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
451
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error('corrupt session log: bad zstd magic at byte ' + offset)
452
+ offset += 4
453
+ if (offset === buffer.length) return { frames, tornStart: start }
454
+ const descriptor = buffer.readUInt8(offset)
455
+ offset += 1
456
+ if ((descriptor & 0x18) !== 0) throw new Error('corrupt session log: reserved frame-header bit')
457
+ const contentSizeFlag = descriptor >>> 6
458
+ const singleSegment = (descriptor & 0x20) !== 0
459
+ const checksum = (descriptor & 0x04) !== 0
460
+ const dictionaryFlag = descriptor & 0x03
461
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
462
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
463
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
464
+ if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
465
+ offset += remainingHeaderBytes
466
+ for (;;) {
467
+ if (buffer.length - offset < 3) return { frames, tornStart: start }
468
+ const blockHeader = buffer.readUIntLE(offset, 3)
469
+ offset += 3
470
+ const lastBlock = (blockHeader & 1) !== 0
471
+ const blockType = (blockHeader >>> 1) & 0x03
472
+ const blockSize = blockHeader >>> 3
473
+ if (blockType === 0x03) throw new Error('corrupt session log: reserved block type')
474
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
475
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
476
+ offset += payloadBytes
477
+ if (lastBlock) break
478
+ }
479
+ if (checksum) {
480
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
481
+ offset += 4
482
+ }
483
+ frames.push({ start, end: offset })
484
+ }
485
+ return { frames }
486
+ }
487
+
488
+ function readSessionEvents(file) {
489
+ const raw = fs.readFileSync(file)
490
+ let text
491
+ if (file.endsWith('.zstd')) {
492
+ const { frames } = scanZstdFrames(raw)
493
+ const parts = []
494
+ for (const frame of frames) {
495
+ try {
496
+ parts.push(zlib.zstdDecompressSync(raw.subarray(frame.start, frame.end)))
497
+ } catch (error) {
498
+ throw new Error('cannot decompress session log frame at byte ' + frame.start + ': ' + error.message)
499
+ }
500
+ }
501
+ text = Buffer.concat(parts).toString('utf8')
502
+ } else {
503
+ text = raw.toString('utf8')
504
+ }
505
+ const events = []
506
+ for (const line of text.split(/\r?\n/)) {
507
+ if (!line.trim()) continue
508
+ try {
509
+ const value = JSON.parse(line)
510
+ if (value && typeof value === 'object') events.push(value)
511
+ } catch {
512
+ // The host appends complete JSON lines; a torn line is retried next poll.
513
+ }
514
+ }
515
+ return events
516
+ }
517
+
518
+ /**
519
+ * Index of the durable user/message that claims this requestId.
520
+ *
521
+ * The inbox `agent/inbox/spliced` event proves admission but not that a turn
522
+ * consumed the prompt, so it is deliberately not used as the anchor. A
523
+ * `user/message` appears inside the turn that actually claims the prompt, which
524
+ * is what lets the wait below pair it with the right turn/end.
525
+ */
526
+ function promptClaimIndex(events, requestId) {
527
+ for (let i = events.length - 1; i >= 0; i -= 1) {
528
+ const event = events[i]
529
+ if (event?.type === 'user/message' && event?.data?.source?.rpcId === requestId) return i
530
+ }
531
+ return -1
532
+ }
533
+
534
+ /** Whether the host durably admitted this requestId (before a turn claims it). */
535
+ function promptAdmitted(events, requestId) {
536
+ return events.some((event) => event?.type === 'agent/inbox/spliced'
537
+ && Array.isArray(event?.data?.inserted)
538
+ && event.data.inserted.some((item) => item?.source?.rpcId === requestId))
539
+ }
540
+
541
+ /** Turn number of the `turn/start` that encloses one claimed user message. */
542
+ function enclosingTurn(events, claimIndex) {
543
+ for (let i = claimIndex - 1; i >= 0; i -= 1) {
544
+ const event = events[i]
545
+ if (event?.type === 'turn/start') {
546
+ const turn = Number(event?.data?.turn)
547
+ return Number.isSafeInteger(turn) ? turn : null
548
+ }
549
+ if (event?.type === 'turn/end') return null
550
+ }
551
+ return null
552
+ }
553
+
554
+ /**
555
+ * Read the public session log until the prompt's own turn/end appears.
556
+ *
557
+ * A queued prompt may be claimed in the middle of an existing long turn, so the
558
+ * enclosing turn is read from the log instead of assuming a fresh turn starts.
559
+ * Only `reason.kind === 'completed'` counts as success.
560
+ *
561
+ * @returns {{state:'completed'|'failed'|'timeout', reason:string, waitedMs:number}}
562
+ */
563
+ async function waitForTurn({ logPath, requestId, timeoutMs, pollMs }) {
564
+ const started = Date.now()
565
+ const deadline = started + timeoutMs
566
+ let admitted = false
567
+ let lastReadError = null
568
+ while (Date.now() < deadline) {
569
+ try {
570
+ const events = readSessionEvents(logPath)
571
+ if (!admitted && promptAdmitted(events, requestId)) admitted = true
572
+ const claim = promptClaimIndex(events, requestId)
573
+ if (claim >= 0) {
574
+ const turn = enclosingTurn(events, claim)
575
+ for (let i = claim + 1; i < events.length; i += 1) {
576
+ const event = events[i]
577
+ if (event?.type !== 'turn/end') continue
578
+ const endedTurn = Number(event?.data?.turn)
579
+ if (turn !== null && Number.isSafeInteger(endedTurn) && endedTurn !== turn) {
580
+ return {
581
+ state: 'failed',
582
+ reason: 'turn/end turn=' + endedTurn + ' does not match the claiming turn=' + turn,
583
+ waitedMs: Date.now() - started,
584
+ }
585
+ }
586
+ const reason = event?.data?.reason?.kind
587
+ if (reason === 'completed') {
588
+ return { state: 'completed', reason: 'completed', waitedMs: Date.now() - started }
589
+ }
590
+ return {
591
+ state: 'failed',
592
+ reason: 'turn/end reason=' + String(reason || 'unknown'),
593
+ waitedMs: Date.now() - started,
594
+ }
595
+ }
596
+ }
597
+ lastReadError = null
598
+ } catch (error) {
599
+ lastReadError = error?.message || String(error)
600
+ }
601
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))))
602
+ }
603
+ if (lastReadError) {
604
+ return { state: 'timeout', reason: 'cannot read session log: ' + lastReadError, waitedMs: timeoutMs }
605
+ }
606
+ return {
607
+ state: 'timeout',
608
+ reason: admitted ? 'prompt was admitted but no turn claimed it before the deadline' : 'prompt not observed in the session log',
609
+ waitedMs: timeoutMs,
610
+ }
611
+ }
612
+
613
+ function joinUrl(base, suffix) {
614
+ return String(base).replace(/\/+$/, '') + suffix
615
+ }
616
+
617
+ /**
618
+ * The Connection RPC carrier wraps each Remote method parameter by **name**, so a
619
+ * single-argument remote must go out as `{ args: { request: <SessionPromptRequest> } }`.
620
+ * Sending request fields without the named wrapper is rejected by the carrier
621
+ * with `gateway/arguments-invalid: missing "request"`.
622
+ */
623
+ export function buildPromptEnvelope(request, rpcId = crypto.randomUUID()) {
624
+ return {
625
+ type: 'client-request',
626
+ rpcId,
627
+ method: 'session/prompt',
628
+ payload: { args: { request } },
629
+ }
630
+ }
631
+
632
+ async function sendPrompt({ base, request, timeoutMs, cookie }) {
633
+ const url = joinUrl(base, '/api/session/prompt')
634
+ const envelope = buildPromptEnvelope(request)
635
+ const headers = { 'content-type': 'application/json' }
636
+ if (cookie) headers.cookie = cookie
637
+ let response
638
+ try {
639
+ response = await fetch(url, {
640
+ method: 'POST',
641
+ headers,
642
+ body: JSON.stringify(envelope),
643
+ signal: AbortSignal.timeout(Math.min(timeoutMs, 2_147_483_647)),
644
+ })
645
+ } catch (error) {
646
+ throw new Error('transport failure for ' + url + ': ' + (error?.message || error))
647
+ }
648
+ const text = await response.text()
649
+ if (!response.ok) {
650
+ const hint = response.status === 401 || response.status === 403
651
+ ? ' (the Host authenticates /api; pass --cookie-file with the browser session cookie)'
652
+ : ''
653
+ throw new Error('HTTP ' + response.status + ' from ' + url + hint + ': ' + text.slice(0, 240))
654
+ }
655
+ let body
656
+ try {
657
+ body = JSON.parse(text)
658
+ } catch {
659
+ throw new Error('response is not JSON (expected a Connection RPC envelope)')
660
+ }
661
+ if (!body || body.type !== 'server-response' || body.rpcId !== envelope.rpcId) {
662
+ throw new Error('response is not the matching Connection RPC envelope')
663
+ }
664
+ if (!body.result || body.result.ok !== true) {
665
+ const failure = body.result?.error || {}
666
+ throw new Error('session/prompt rejected: ' + String(failure.code || 'unknown') + ': ' + String(failure.message || 'no message'))
667
+ }
668
+ if (body.result.value?.accepted !== true) {
669
+ throw new Error('session/prompt did not return { accepted: true }')
670
+ }
671
+ return { rpcId: envelope.rpcId }
672
+ }
673
+
674
+ function isLoopbackHost(hostname) {
675
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1'
676
+ }
677
+
678
+ async function main(argv = process.argv.slice(2)) {
679
+ let options
680
+ try {
681
+ options = parseArgs(argv)
682
+ } catch (error) {
683
+ return failUsage(error.message)
684
+ }
685
+ if (options.help) {
686
+ process.stdout.write(USAGE)
687
+ return EXIT_OK
688
+ }
689
+ if (!options.session || !String(options.session).trim()) {
690
+ return failUsage('--session is required')
691
+ }
692
+ if (options.base) {
693
+ let parsed
694
+ try { parsed = new URL(options.base) } catch { return failUsage('--base is not a valid URL') }
695
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return failUsage('--base must be http(s)')
696
+ if (!isLoopbackHost(parsed.hostname)) {
697
+ console.error('drive-session: warning: --base is not loopback (' + parsed.hostname + '); the harness sends no credentials, so an authenticated host will reject it')
698
+ }
699
+ }
700
+
701
+ const clientTimeZone = options.clientTimeZone || defaultClientTimeZone()
702
+ let prompts
703
+ try {
704
+ prompts = resolvePrompts(options)
705
+ } catch (error) {
706
+ return failUsage(error.message)
707
+ }
708
+ const requests = buildRequests({
709
+ sessionId: String(options.session).trim(),
710
+ turns: options.turns,
711
+ prompts,
712
+ clientTimeZone,
713
+ })
714
+
715
+ let cookie = null
716
+ if (options.cookieFile) {
717
+ try {
718
+ cookie = fs.readFileSync(options.cookieFile, 'utf8').trim()
719
+ } catch (error) {
720
+ return failUsage('cannot read --cookie-file: ' + error.message)
721
+ }
722
+ if (!cookie || /[\r\n]/.test(cookie)) {
723
+ return failUsage('--cookie-file must contain exactly one Cookie header value (no line breaks)')
724
+ }
725
+ }
726
+
727
+ if (options.requestsOut) {
728
+ try { writeRequests(options.requestsOut, requests) } catch (error) {
729
+ console.error('drive-session: cannot write --requests-out: ' + error.message)
730
+ return EXIT_FAILED
731
+ }
732
+ }
733
+
734
+ if (options.dryRun) {
735
+ for (const item of requests) {
736
+ process.stdout.write(JSON.stringify({ turn: item.turn, request: item.request }) + '\n')
737
+ }
738
+ console.log('drive-session: dry run — ' + requests.length + ' request(s) generated, nothing sent')
739
+ return EXIT_OK
740
+ }
741
+
742
+ if (!options.allowApiRoute) {
743
+ printManualFallback({
744
+ reason: 'no approved public-remote carrier. Work order B forbids silently POSTing /api.',
745
+ requests,
746
+ requestsOut: options.requestsOut,
747
+ })
748
+ return EXIT_MANUAL
749
+ }
750
+ if (!options.base) {
751
+ printManualFallback({
752
+ reason: '--allow-api-route needs --base <host gateway>; there is nowhere to send the public remote.',
753
+ requests,
754
+ requestsOut: options.requestsOut,
755
+ })
756
+ return EXIT_MANUAL
757
+ }
758
+
759
+ const dshHome = options.dshHome || process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
760
+ const sessionLog = locateSessionLog({
761
+ explicit: options.sessionLog,
762
+ dshHome,
763
+ sessionId: String(options.session).trim(),
764
+ })
765
+ if (!sessionLog) {
766
+ console.error('drive-session: preflight failed — no session log for ' + options.session)
767
+ console.error(' looked under: ' + path.join(dshHome, 'sessions'))
768
+ console.error(' Pass --session-log <path> with the exact session.v4.jsonl.zstd file,')
769
+ console.error(' or --dsh-home <path> if DSH_HOME is not ' + dshHome + '.')
770
+ console.error(' Nothing was sent: without the public session log a turn cannot be observed as completed.')
771
+ return EXIT_PREFLIGHT
772
+ }
773
+ try {
774
+ readSessionEvents(sessionLog)
775
+ } catch (error) {
776
+ console.error('drive-session: preflight failed — cannot read ' + sessionLog + ': ' + error.message)
777
+ console.error(' Nothing was sent.')
778
+ return EXIT_PREFLIGHT
779
+ }
780
+
781
+ console.log('drive-session: ' + requests.length + ' turn(s) → session ' + options.session)
782
+ console.log(' base: ' + joinUrl(options.base, '/api/session/prompt') + ' (explicit --allow-api-route)')
783
+ console.log(' session log: ' + sessionLog)
784
+ console.log(' clientTimeZone: ' + clientTimeZone)
785
+ console.log(' cookie: ' + (cookie ? 'supplied via --cookie-file (not printed)' : 'none (a Host with browser auth will answer 401)'))
786
+ if (options.requestsOut) console.log(' requests: ' + path.resolve(options.requestsOut))
787
+
788
+ const started = Date.now()
789
+ let completed = 0
790
+ let failed = 0
791
+ let lastFailure = null
792
+ for (const item of requests) {
793
+ const turnStarted = Date.now()
794
+ try {
795
+ await sendPrompt({ base: options.base, request: item.request, timeoutMs: options.timeoutMs, cookie })
796
+ } catch (error) {
797
+ failed += 1
798
+ lastFailure = { turn: item.turn, stage: 'send', reason: error.message }
799
+ console.error('turn ' + item.turn + '/' + requests.length + ' SEND FAILED: ' + error.message)
800
+ break
801
+ }
802
+ // One per-turn budget: admission time is charged against completion time.
803
+ const remaining = Math.max(1_000, options.timeoutMs - (Date.now() - turnStarted))
804
+ const waited = await waitForTurn({
805
+ logPath: sessionLog,
806
+ requestId: item.request.requestId,
807
+ timeoutMs: remaining,
808
+ pollMs: options.pollMs,
809
+ })
810
+ if (waited.state !== 'completed') {
811
+ failed += 1
812
+ lastFailure = { turn: item.turn, stage: 'wait', reason: waited.state + ': ' + waited.reason }
813
+ console.error('turn ' + item.turn + '/' + requests.length + ' WAIT FAILED: ' + waited.state + ' (' + waited.reason + ')')
814
+ break
815
+ }
816
+ completed += 1
817
+ const elapsed = Date.now() - turnStarted
818
+ console.log('turn ' + item.turn + '/' + requests.length + ' completed in ' + elapsed + 'ms (requestId ' + item.request.requestId + ')')
819
+ if (options.intervalMs > 0 && item.turn < requests.length) {
820
+ await new Promise((resolve) => setTimeout(resolve, options.intervalMs))
821
+ }
822
+ }
823
+
824
+ const totalMs = Date.now() - started
825
+ console.log('')
826
+ console.log('summary: sent+completed=' + completed + ' failed=' + failed + ' requested=' + requests.length + ' elapsed=' + totalMs + 'ms')
827
+ if (lastFailure) {
828
+ console.log('first failure: turn ' + lastFailure.turn + ' (' + lastFailure.stage + ') ' + lastFailure.reason)
829
+ return EXIT_FAILED
830
+ }
831
+ if (completed !== requests.length) {
832
+ console.log('run stopped before every requested turn completed')
833
+ return EXIT_FAILED
834
+ }
835
+ console.log('all requested turns completed')
836
+ return EXIT_OK
837
+ }
838
+
839
+ const invokedDirectly = process.argv[1]
840
+ ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
841
+ : false
842
+ if (invokedDirectly) {
843
+ main().then((code) => { process.exitCode = typeof code === 'number' ? code : EXIT_FAILED }).catch((error) => {
844
+ console.error('drive-session: ' + (error?.stack || error))
845
+ process.exitCode = EXIT_FAILED
846
+ })
847
+ }
848
+
849
+ export {
850
+ DEFAULT_PROMPTS,
851
+ buildRequests,
852
+ encodeSegment,
853
+ enclosingTurn,
854
+ locateSessionLog,
855
+ parseArgs,
856
+ promptAdmitted,
857
+ promptClaimIndex,
858
+ readSessionEvents,
859
+ scanZstdFrames,
860
+ sendPrompt,
861
+ textOfPromptItem,
862
+ waitForTurn,
863
+ }