@wenathlan/devthink 2.0.15 → 2.0.19

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 (444) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/{dist/bridge.d.ts → bridge.d.ts} +1 -1
  3. package/bridge.d.ts.map +1 -0
  4. package/bridge.js +1877 -0
  5. package/bun.d.ts.map +1 -0
  6. package/bun.js +52329 -0
  7. package/caps/background.json +712 -0
  8. package/caps/cli.json +360 -0
  9. package/caps/library.json +3611 -0
  10. package/caps/mcp.json +126 -0
  11. package/caps/pagebridge.json +377 -0
  12. package/caps/popup.json +51 -0
  13. package/caps/sidepanel.json +522 -0
  14. package/checksums.txt +142 -0
  15. package/cli.d.ts.map +1 -0
  16. package/{dist/cli.js → cli.js} +2 -2
  17. package/companion.d.ts.map +1 -0
  18. package/companion.js +389 -0
  19. package/crossbrowser.d.ts.map +1 -0
  20. package/crossbrowser.js +1191 -0
  21. package/dashdone.d.ts.map +1 -0
  22. package/dashdone.js +368 -0
  23. package/deno.d.ts.map +1 -0
  24. package/deno.js +52325 -0
  25. package/devthink.umd.js +52346 -0
  26. package/fixtures/bun.ts +7 -0
  27. package/fixtures/cjs.js +6 -0
  28. package/fixtures/deno.ts +6 -0
  29. package/fixtures/example-org-pagestate.json +22 -0
  30. package/fixtures/importers/automa-workflow.json +18 -0
  31. package/fixtures/importers/selenium-side.json +20 -0
  32. package/fixtures/importers/tabular-plan.csv +7 -0
  33. package/fixtures/importers/uivision-macro.json +10 -0
  34. package/fixtures/importers/v1-plan.json +13 -0
  35. package/fixtures/mcp-client.mjs +14 -0
  36. package/fixtures/pages/checkout.html +192 -0
  37. package/fixtures/pages/dashboard.html +110 -0
  38. package/fixtures/pages/feed.html +113 -0
  39. package/fixtures/pages/product-grid.html +150 -0
  40. package/fixtures/plans/form-inventory-plan.json +11 -0
  41. package/fixtures/plans/release-notes-plan.json +11 -0
  42. package/fixtures/recipes/agentscompete.json +11 -0
  43. package/fixtures/recipes/agentsforms.json +11 -0
  44. package/fixtures/recipes/agentsmonitor.json +11 -0
  45. package/fixtures/recipes/agentsreview.json +29 -0
  46. package/fixtures/recipes/agentswarm.json +11 -0
  47. package/fixtures/recipes/fillcalendar.json +12 -0
  48. package/fixtures/recipes/fillcheckout.json +13 -0
  49. package/fixtures/recipes/filldependentdropdowns.json +12 -0
  50. package/fixtures/recipes/fillfromcsv.json +13 -0
  51. package/fixtures/recipes/fillloginform.json +12 -0
  52. package/fixtures/recipes/fillmultistepwizard.json +13 -0
  53. package/fixtures/recipes/fillregistration.json +12 -0
  54. package/fixtures/recipes/fillsearchfilters.json +12 -0
  55. package/fixtures/recipes/filltypeahead.json +11 -0
  56. package/fixtures/recipes/monitoralerts.json +12 -0
  57. package/fixtures/recipes/monitoravailability.json +11 -0
  58. package/fixtures/recipes/monitornetworkquiet.json +12 -0
  59. package/fixtures/recipes/monitorpagechanges.json +11 -0
  60. package/fixtures/recipes/monitorpricechange.json +11 -0
  61. package/fixtures/recipes/monitorschedule.json +12 -0
  62. package/fixtures/recipes/scrapedynamicprices.json +13 -0
  63. package/fixtures/recipes/scrapeimagegallery.json +12 -0
  64. package/fixtures/recipes/scrapeinfinitefeed.json +13 -0
  65. package/fixtures/recipes/scrapenestedlists.json +12 -0
  66. package/fixtures/recipes/scrapeproductgrid.json +12 -0
  67. package/fixtures/recipes/scrapereviews.json +12 -0
  68. package/fixtures/recipes/scrapesearchresults.json +12 -0
  69. package/fixtures/recipes/scrapetablepagination.json +12 -0
  70. package/fixtures/recipes/testaccessibility.json +34 -0
  71. package/fixtures/recipes/testconsoleerrors.json +12 -0
  72. package/fixtures/recipes/testdeeplinks.json +12 -0
  73. package/fixtures/recipes/testformvalidation.json +13 -0
  74. package/fixtures/recipes/testlayoutshift.json +12 -0
  75. package/fixtures/recipes/testlinkcheck.json +12 -0
  76. package/fixtures/recipes/testloadtiming.json +12 -0
  77. package/fixtures/recipes/testvisualdiff.json +12 -0
  78. package/fixtures/workflows/changelog-digest-workflow.json +13 -0
  79. package/fixtures/workflows/form-survey-workflow.json +13 -0
  80. package/gallery.json +706 -0
  81. package/hardening.d.ts.map +1 -0
  82. package/hardening.js +188 -0
  83. package/headless.d.ts.map +1 -0
  84. package/headless.js +11522 -0
  85. package/http.d.ts.map +1 -0
  86. package/http.js +2165 -0
  87. package/index.cjs +54682 -0
  88. package/index.d.ts.map +1 -0
  89. package/index.js +52310 -0
  90. package/index.neutral.js +46343 -0
  91. package/{web/manifest.json → manifest.json} +1 -1
  92. package/mcp.d.ts.map +1 -0
  93. package/mcp.js +20515 -0
  94. package/memory.d.ts.map +1 -0
  95. package/{memory.ts → memory.js} +2310 -3834
  96. package/nativehost.template.json +10 -0
  97. package/node.cjs +54686 -0
  98. package/node.d.ts.map +1 -0
  99. package/pack.d.ts.map +1 -0
  100. package/pack.js +805 -0
  101. package/package.json +83 -176
  102. package/policy.d.ts.map +1 -0
  103. package/{policy.ts → policy.js} +4679 -5073
  104. package/progress.d.ts.map +1 -0
  105. package/progress.js +645 -0
  106. package/protocol.d.ts.map +1 -0
  107. package/protocol.js +8334 -0
  108. package/schemas/audit.schema.json +226 -0
  109. package/schemas/capability.schema.json +113 -0
  110. package/schemas/envelope.schema.json +162 -0
  111. package/schemas/memory.schema.json +51 -0
  112. package/schemas/observation.schema.json +113 -0
  113. package/schemas/plan.schema.json +208 -0
  114. package/schemas/progress.schema.json +126 -0
  115. package/schemas/proposal.schema.json +68 -0
  116. package/schemas/session.schema.json +82 -0
  117. package/schemas/tool.schema.json +94 -0
  118. package/server.d.ts.map +1 -0
  119. package/server.js +28877 -0
  120. package/umd-example.html +18 -0
  121. package/umd.d.ts.map +1 -0
  122. package/accounts.ts +0 -2087
  123. package/agent.ts +0 -2331
  124. package/antigravity.ts +0 -2139
  125. package/apifreeze.ts +0 -4146
  126. package/auth.ts +0 -642
  127. package/background.ts +0 -16837
  128. package/bridge.ts +0 -2080
  129. package/build.ts +0 -54
  130. package/bun.ts +0 -26
  131. package/capture.ts +0 -1614
  132. package/checksecrets.ts +0 -72
  133. package/cjs.ts +0 -9
  134. package/cli.ts +0 -3500
  135. package/commands.ts +0 -1101
  136. package/companion.ts +0 -450
  137. package/compatibility.ts +0 -37
  138. package/config.ts +0 -3137
  139. package/constants.ts +0 -943
  140. package/core.ts +0 -1473
  141. package/crossbrowser.ts +0 -1359
  142. package/dashdone.ts +0 -605
  143. package/data.ts +0 -943
  144. package/database.ts +0 -133
  145. package/debug.ts +0 -850
  146. package/deno.ts +0 -27
  147. package/devthink.ts +0 -707
  148. package/dist/accounts.d.ts +0 -409
  149. package/dist/agent.d.ts +0 -837
  150. package/dist/antigravity.d.ts +0 -380
  151. package/dist/apifreeze.d.ts +0 -113
  152. package/dist/auth.d.ts +0 -224
  153. package/dist/capture.d.ts +0 -595
  154. package/dist/cjs.d.ts +0 -6
  155. package/dist/commands.d.ts +0 -310
  156. package/dist/compatibility.d.ts +0 -17
  157. package/dist/config.d.ts +0 -1853
  158. package/dist/constants.d.ts +0 -637
  159. package/dist/core.d.ts +0 -361
  160. package/dist/data.d.ts +0 -330
  161. package/dist/database.d.ts +0 -24
  162. package/dist/debug.d.ts +0 -270
  163. package/dist/engine.d.ts +0 -74
  164. package/dist/environments.d.ts +0 -244
  165. package/dist/evidence.d.ts +0 -277
  166. package/dist/export.d.ts +0 -311
  167. package/dist/fingerprint.d.ts +0 -594
  168. package/dist/flow.d.ts +0 -300
  169. package/dist/gates.d.ts +0 -103
  170. package/dist/identity.d.ts +0 -51
  171. package/dist/ids.d.ts +0 -7
  172. package/dist/llm.d.ts +0 -652
  173. package/dist/models.d.ts +0 -1807
  174. package/dist/net.d.ts +0 -325
  175. package/dist/neutral.d.ts +0 -41
  176. package/dist/oauth.d.ts +0 -703
  177. package/dist/page.d.ts +0 -1166
  178. package/dist/perf.d.ts +0 -481
  179. package/dist/plan.d.ts +0 -134
  180. package/dist/project.d.ts +0 -395
  181. package/dist/providers.d.ts +0 -37
  182. package/dist/quota.d.ts +0 -453
  183. package/dist/recovery.d.ts +0 -621
  184. package/dist/request.d.ts +0 -1492
  185. package/dist/run.d.ts +0 -779
  186. package/dist/runtime.d.ts +0 -212
  187. package/dist/search.d.ts +0 -375
  188. package/dist/security.d.ts +0 -534
  189. package/dist/serve.d.ts +0 -136
  190. package/dist/session.d.ts +0 -296
  191. package/dist/storage.d.ts +0 -53
  192. package/dist/streaming.d.ts +0 -1119
  193. package/dist/swarm.d.ts +0 -328
  194. package/dist/tools.d.ts +0 -170
  195. package/dist/types.d.ts +0 -8357
  196. package/dist/utils.d.ts +0 -82
  197. package/dist/version.d.ts +0 -7
  198. package/dist/versionregistry.d.ts +0 -406
  199. package/dist/views.d.ts +0 -579
  200. package/dist/workbenchsession.d.ts +0 -69
  201. package/dist/workflow.d.ts +0 -649
  202. package/docs/readme.md +0 -92
  203. package/docs/schemas/antigravity.json +0 -192
  204. package/engine.ts +0 -1524
  205. package/environments.ts +0 -1005
  206. package/evidence.ts +0 -643
  207. package/export.ts +0 -889
  208. package/fingerprint.ts +0 -1458
  209. package/flow.ts +0 -1190
  210. package/gates.ts +0 -307
  211. package/gateway.ts +0 -34
  212. package/hardening.ts +0 -191
  213. package/headless.ts +0 -369
  214. package/http.ts +0 -2110
  215. package/identity.ts +0 -246
  216. package/ids.ts +0 -26
  217. package/index.ts +0 -369
  218. package/llm.ts +0 -2682
  219. package/mcp.ts +0 -1835
  220. package/models.ts +0 -3805
  221. package/modes.ts +0 -43
  222. package/net.ts +0 -1214
  223. package/neutral.ts +0 -362
  224. package/node.ts +0 -26
  225. package/oauth.ts +0 -2216
  226. package/offscreen.ts +0 -170
  227. package/pack.ts +0 -956
  228. package/page.ts +0 -7824
  229. package/pagebridge.ts +0 -1116
  230. package/perf.ts +0 -957
  231. package/plan.ts +0 -672
  232. package/plugin.ts +0 -76
  233. package/prisma.config.ts +0 -27
  234. package/progress.ts +0 -1308
  235. package/project.ts +0 -1291
  236. package/protocol.ts +0 -4187
  237. package/providers.ts +0 -246
  238. package/quota.ts +0 -1887
  239. package/recovery.ts +0 -2433
  240. package/request.ts +0 -4482
  241. package/run.ts +0 -2135
  242. package/runtime.ts +0 -526
  243. package/search.ts +0 -1760
  244. package/security.ts +0 -1673
  245. package/serve.ts +0 -419
  246. package/server.ts +0 -5538
  247. package/session.ts +0 -1162
  248. package/storage.ts +0 -182
  249. package/streaming.ts +0 -4101
  250. package/swarm.ts +0 -884
  251. package/sync.ts +0 -56
  252. package/tests/agentcert.test.ts +0 -128
  253. package/tests/agentfleet.test.ts +0 -214
  254. package/tests/agentreview.test.ts +0 -241
  255. package/tests/agentstream.test.ts +0 -335
  256. package/tests/agentwork.test.ts +0 -356
  257. package/tests/apifreeze.test.ts +0 -290
  258. package/tests/apimap.test.ts +0 -112
  259. package/tests/approvalgate.test.ts +0 -175
  260. package/tests/artifactmanifest.test.ts +0 -204
  261. package/tests/attentionfeed.test.ts +0 -163
  262. package/tests/backgroundruns.test.ts +0 -100
  263. package/tests/batchscheduling.test.ts +0 -131
  264. package/tests/blackboard.test.ts +0 -238
  265. package/tests/bridge.test.ts +0 -1088
  266. package/tests/browsercoverage.test.ts +0 -134
  267. package/tests/browserpolyfills.test.ts +0 -124
  268. package/tests/build.mjs +0 -1260
  269. package/tests/clientauth.test.ts +0 -223
  270. package/tests/clitools.test.ts +0 -578
  271. package/tests/confirmgates.test.ts +0 -190
  272. package/tests/containerpack.test.ts +0 -143
  273. package/tests/controlflow.test.ts +0 -2120
  274. package/tests/coordination.test.ts +0 -345
  275. package/tests/copyscreen.test.ts +0 -139
  276. package/tests/core.test.ts +0 -417
  277. package/tests/costcert.test.ts +0 -95
  278. package/tests/crossbrowser.test.ts +0 -115
  279. package/tests/cspaudit.test.ts +0 -79
  280. package/tests/dashdone.test.ts +0 -615
  281. package/tests/datagrid.test.ts +0 -137
  282. package/tests/doccheck.test.ts +0 -107
  283. package/tests/dombatch.test.ts +0 -109
  284. package/tests/emulation.test.ts +0 -282
  285. package/tests/environments.test.ts +0 -259
  286. package/tests/evidenceviews.test.ts +0 -88
  287. package/tests/exporttools.test.ts +0 -185
  288. package/tests/firefoxprep.test.ts +0 -134
  289. package/tests/flowlibrary.test.ts +0 -242
  290. package/tests/flowrun.test.ts +0 -303
  291. package/tests/forensics.test.ts +0 -439
  292. package/tests/gateway.test.ts +0 -939
  293. package/tests/headlesslib.test.ts +0 -171
  294. package/tests/httpstream.test.ts +0 -277
  295. package/tests/immutablelog.test.ts +0 -157
  296. package/tests/inboundguard.test.ts +0 -177
  297. package/tests/lazyload.test.ts +0 -72
  298. package/tests/librarymodes.test.ts +0 -623
  299. package/tests/llm.test.ts +0 -696
  300. package/tests/manifest.test.ts +0 -226
  301. package/tests/maskinputs.test.ts +0 -150
  302. package/tests/matrixverify.test.ts +0 -111
  303. package/tests/mavenpack.test.ts +0 -75
  304. package/tests/mcpserver.test.ts +0 -704
  305. package/tests/memory.test.ts +0 -4155
  306. package/tests/memorycare.test.ts +0 -230
  307. package/tests/migrateplan.test.ts +0 -349
  308. package/tests/minimization.test.ts +0 -414
  309. package/tests/modelroute.test.ts +0 -112
  310. package/tests/multiagent.test.ts +0 -440
  311. package/tests/nativebridge.test.ts +0 -807
  312. package/tests/navigation.test.ts +0 -284
  313. package/tests/nugetpack.test.ts +0 -83
  314. package/tests/orchestration.test.ts +0 -449
  315. package/tests/originpolicy.test.ts +0 -405
  316. package/tests/outputcompare.test.ts +0 -97
  317. package/tests/package.test.ts +0 -91
  318. package/tests/pagebridge.test.ts +0 -5909
  319. package/tests/pentest.test.ts +0 -75
  320. package/tests/perfrecords.test.ts +0 -257
  321. package/tests/permdiff.test.ts +0 -85
  322. package/tests/phishguard.test.ts +0 -128
  323. package/tests/pickerviews.test.ts +0 -155
  324. package/tests/pipelines.test.ts +0 -381
  325. package/tests/planlint.test.ts +0 -240
  326. package/tests/planreview.test.ts +0 -383
  327. package/tests/platformtargets.test.ts +0 -56
  328. package/tests/policy.test.ts +0 -8284
  329. package/tests/portability.test.ts +0 -96
  330. package/tests/progress.test.ts +0 -1036
  331. package/tests/promptlibrary.test.ts +0 -116
  332. package/tests/protocol.test.ts +0 -4793
  333. package/tests/publishingpipeline.test.ts +0 -314
  334. package/tests/quickactions.test.ts +0 -164
  335. package/tests/readiness.test.ts +0 -78
  336. package/tests/recipes.test.ts +0 -163
  337. package/tests/redactshots.test.ts +0 -216
  338. package/tests/registernvidiakeys.ts +0 -51
  339. package/tests/relayserve.test.ts +0 -304
  340. package/tests/releasenotes.test.ts +0 -276
  341. package/tests/resilience.test.ts +0 -467
  342. package/tests/resourceaware.test.ts +0 -187
  343. package/tests/runbudget.test.ts +0 -125
  344. package/tests/runhistory.test.ts +0 -299
  345. package/tests/runreplay.test.ts +0 -113
  346. package/tests/runresume.test.ts +0 -184
  347. package/tests/runstate.test.ts +0 -288
  348. package/tests/runtimeadapters.test.ts +0 -251
  349. package/tests/safariskeleton.test.ts +0 -115
  350. package/tests/sandboxframe.test.ts +0 -196
  351. package/tests/sbom.test.ts +0 -105
  352. package/tests/secretvault.test.ts +0 -188
  353. package/tests/selcache.test.ts +0 -111
  354. package/tests/sessioninterface.test.ts +0 -791
  355. package/tests/sessions.test.ts +0 -591
  356. package/tests/siteprefs.test.ts +0 -228
  357. package/tests/snapshotdelta.test.ts +0 -165
  358. package/tests/statusviews.test.ts +0 -237
  359. package/tests/stepmeter.test.ts +0 -200
  360. package/tests/streamparse.test.ts +0 -163
  361. package/tests/stylepruning.test.ts +0 -90
  362. package/tests/surfaces.test.ts +0 -282
  363. package/tests/sweep.test.ts +0 -78
  364. package/tests/syncbridge.test.ts +0 -164
  365. package/tests/taskqueue.test.ts +0 -206
  366. package/tests/toolcalls.test.ts +0 -336
  367. package/tests/toolcatalog.test.ts +0 -201
  368. package/tests/torture-agent.test.ts +0 -706
  369. package/tests/torture-auth.test.ts +0 -461
  370. package/tests/torture-commands.test.ts +0 -895
  371. package/tests/torture-data.test.ts +0 -923
  372. package/tests/torture-environments.test.ts +0 -285
  373. package/tests/torture-export.test.ts +0 -263
  374. package/tests/torture-http.test.ts +0 -1379
  375. package/tests/torture-llm.test.ts +0 -808
  376. package/tests/torture-memory.test.ts +0 -1084
  377. package/tests/torture-plan.test.ts +0 -829
  378. package/tests/torture-run.test.ts +0 -626
  379. package/tests/torture-session.test.ts +0 -928
  380. package/tests/torture-swarm.test.ts +0 -1245
  381. package/tests/torture-tools.test.ts +0 -964
  382. package/tests/torture-workflow.test.ts +0 -2354
  383. package/tests/tourviews.test.ts +0 -52
  384. package/tests/transparency.test.ts +0 -147
  385. package/tests/trigger.test.ts +0 -941
  386. package/tests/v1sunset.test.ts +0 -428
  387. package/tests/virtlist.test.ts +0 -94
  388. package/tests/vision.test.ts +0 -540
  389. package/tests/vsixpack.test.ts +0 -145
  390. package/tests/webapi.test.ts +0 -523
  391. package/tests/workflow.test.ts +0 -1785
  392. package/tests/workfloweditor.test.ts +0 -759
  393. package/tests/xpipack.test.ts +0 -128
  394. package/tools.ts +0 -734
  395. package/types.ts +0 -9908
  396. package/umd.ts +0 -9
  397. package/utils.ts +0 -249
  398. package/version.ts +0 -8
  399. package/versionregistry.ts +0 -1310
  400. package/views.ts +0 -2153
  401. package/vitest.config.ts +0 -12
  402. package/web/App.tsx +0 -78
  403. package/web/README.md +0 -47
  404. package/web/capacitor.config.ts +0 -46
  405. package/web/const.ts +0 -19
  406. package/web/control.shell.tsx +0 -66
  407. package/web/dashboardpage.ts +0 -554
  408. package/web/db.ts +0 -493
  409. package/web/design.html +0 -541
  410. package/web/gatewayview/Gateway.tsx +0 -345
  411. package/web/gatewayview/config.ts +0 -1042
  412. package/web/gatewayview/definition.ts +0 -174
  413. package/web/icons.ts +0 -15
  414. package/web/optionspage.ts +0 -691
  415. package/web/popup.ts +0 -1651
  416. package/web/schema.prisma +0 -176
  417. package/web/sidepanel.ts +0 -7941
  418. package/web/sitemanifest.json +0 -13
  419. package/web/terminal-ui.tsx +0 -622
  420. package/web/transparencypage.ts +0 -541
  421. package/web/vite.config.ts +0 -39
  422. package/web/workspace.ts +0 -23
  423. package/workbenchmemory.ts +0 -104
  424. package/workbenchsession.ts +0 -304
  425. package/workflow.ts +0 -4495
  426. /package/{dist/bun.d.ts → bun.d.ts} +0 -0
  427. /package/{dist/cli.d.ts → cli.d.ts} +0 -0
  428. /package/{dist/companion.d.ts → companion.d.ts} +0 -0
  429. /package/{dist/crossbrowser.d.ts → crossbrowser.d.ts} +0 -0
  430. /package/{dist/dashdone.d.ts → dashdone.d.ts} +0 -0
  431. /package/{dist/deno.d.ts → deno.d.ts} +0 -0
  432. /package/{dist/hardening.d.ts → hardening.d.ts} +0 -0
  433. /package/{dist/headless.d.ts → headless.d.ts} +0 -0
  434. /package/{dist/http.d.ts → http.d.ts} +0 -0
  435. /package/{dist/index.d.ts → index.d.ts} +0 -0
  436. /package/{dist/mcp.d.ts → mcp.d.ts} +0 -0
  437. /package/{dist/memory.d.ts → memory.d.ts} +0 -0
  438. /package/{dist/node.d.ts → node.d.ts} +0 -0
  439. /package/{dist/pack.d.ts → pack.d.ts} +0 -0
  440. /package/{dist/policy.d.ts → policy.d.ts} +0 -0
  441. /package/{dist/progress.d.ts → progress.d.ts} +0 -0
  442. /package/{dist/protocol.d.ts → protocol.d.ts} +0 -0
  443. /package/{dist/server.d.ts → server.d.ts} +0 -0
  444. /package/{dist/umd.d.ts → umd.d.ts} +0 -0
package/http.js ADDED
@@ -0,0 +1,2165 @@
1
+ /*! devthink 2.0.19 — consent-first browser agent library — GPL-3.0-only — https://github.com/wenathlan/devthink */
2
+
3
+ // version.ts
4
+ var packageversion = "2.0.19";
5
+ var protocolmajor = 2;
6
+
7
+ // types.ts
8
+ var protocolversion = packageversion;
9
+ var protocolmajorversion = protocolmajor;
10
+ var pinnedprotocolversion = Object.freeze({ protocolversion, protocolmajor: protocolmajorversion });
11
+ var actionkindids = Object.freeze([
12
+ "observe",
13
+ "inspect",
14
+ "extract",
15
+ "wait",
16
+ "waitfor",
17
+ "waittext",
18
+ "readattribute",
19
+ "readstyle",
20
+ "readgeometry",
21
+ "readvalue",
22
+ "readtext",
23
+ "readhtml",
24
+ "countelements",
25
+ "readtable",
26
+ "readlinks",
27
+ "readimages",
28
+ "readmeta",
29
+ "readforms",
30
+ "readstorage",
31
+ "highlight",
32
+ "tablist",
33
+ "windowlist",
34
+ "tabsnapshot",
35
+ "focus",
36
+ "scroll",
37
+ "hover",
38
+ "clickdeep",
39
+ "rightclick",
40
+ "doubleclick",
41
+ "scrollpage",
42
+ "scrollby",
43
+ "scrollend",
44
+ "scrolltop",
45
+ "fullscreen",
46
+ "zoomset",
47
+ "click",
48
+ "type",
49
+ "navigate",
50
+ "select",
51
+ "presskey",
52
+ "drag",
53
+ "drop",
54
+ "upload",
55
+ "clear",
56
+ "check",
57
+ "uncheck",
58
+ "toggle",
59
+ "submit",
60
+ "reload",
61
+ "back",
62
+ "forward",
63
+ "writestorage",
64
+ "setattribute",
65
+ "removeattribute",
66
+ "evaluate",
67
+ "tabcreate",
68
+ "tabactivate",
69
+ "tabclose",
70
+ "tabreload",
71
+ "windowcreate",
72
+ "windowclose",
73
+ "windowresize",
74
+ "downloadfile",
75
+ "movepointer",
76
+ "clickpoint",
77
+ "shiftclick",
78
+ "clicktext",
79
+ "clickaria",
80
+ "clickname",
81
+ "resolvexpath",
82
+ "typetime",
83
+ "appendtext",
84
+ "setvalue",
85
+ "typeedit",
86
+ "keyhold",
87
+ "keyrelease",
88
+ "submitsearch",
89
+ "selectmulti",
90
+ "chooseradio",
91
+ "setslider",
92
+ "setdate",
93
+ "setcolor",
94
+ "expanddetails",
95
+ "dismissdialog",
96
+ "pierceshadow",
97
+ "enterframe",
98
+ "retryaction",
99
+ "mapclicks",
100
+ "verifyvisible",
101
+ "verifyenabled",
102
+ "a11ytree",
103
+ "readvisible",
104
+ "readertree",
105
+ "detectlists",
106
+ "detecttables",
107
+ "readjson",
108
+ "watchmutate",
109
+ "waitquiet",
110
+ "watchbanner",
111
+ "detectinfinitescroll",
112
+ "detectvirtual",
113
+ "detectlazy",
114
+ "readscrollpos",
115
+ "readlang",
116
+ "readoutline",
117
+ "countpages",
118
+ "listshadow",
119
+ "listframes",
120
+ "classifypage",
121
+ "fingerprintsection",
122
+ "diffsnapshots",
123
+ "readselection",
124
+ "watchfocus",
125
+ "detectsticky",
126
+ "detectscrolllock",
127
+ "readopengraph",
128
+ "detectlanguage",
129
+ "deriveselector",
130
+ "openlink",
131
+ "openprivate",
132
+ "reloadcache",
133
+ "stopnav",
134
+ "waitload",
135
+ "waiturl",
136
+ "followlink",
137
+ "spanav",
138
+ "spawait",
139
+ "rewritequery",
140
+ "setfragment",
141
+ "navlist",
142
+ "navprofile",
143
+ "detecthttp",
144
+ "readredirects",
145
+ "readfinalurl",
146
+ "handleauth",
147
+ "printpdf",
148
+ "prefetch",
149
+ "preconnect",
150
+ "deeplink",
151
+ "reopentab",
152
+ "trailaudit",
153
+ "pausenav",
154
+ "navintent",
155
+ "navrate",
156
+ "openclipboard",
157
+ "checksafe",
158
+ "batchopen",
159
+ "querytabs",
160
+ "duplicatetab",
161
+ "closepattern",
162
+ "pintab",
163
+ "mutetab",
164
+ "movetab",
165
+ "movetabwindow",
166
+ "grouptabs",
167
+ "colorgroup",
168
+ "collapsegroup",
169
+ "discardtab",
170
+ "reloadtabs",
171
+ "zoomin",
172
+ "zoomout",
173
+ "watchtab",
174
+ "switchtab",
175
+ "maximizewindow",
176
+ "minimizewindow",
177
+ "restorewindow",
178
+ "focuswindow",
179
+ "scratchwindow",
180
+ "incognitowindow",
181
+ "restoretab",
182
+ "savelayout",
183
+ "restorelayout",
184
+ "findclones",
185
+ "searchtabs",
186
+ "badgetab",
187
+ "attachmeta",
188
+ "listaudio",
189
+ "reopenrun",
190
+ "snapshotsession",
191
+ "fillform",
192
+ "filllabel",
193
+ "fillplaceholder",
194
+ "detectfields",
195
+ "generatevalues",
196
+ "saveprofiles",
197
+ "asksubmit",
198
+ "submitform",
199
+ "readerrors",
200
+ "retryform",
201
+ "runwizard",
202
+ "selectchain",
203
+ "picktypeahead",
204
+ "pickdate",
205
+ "attachfile",
206
+ "handoffcaptcha",
207
+ "fillcard",
208
+ "fillcode",
209
+ "consentpassword",
210
+ "skiphoneypot",
211
+ "detectlogin",
212
+ "detecttemplate",
213
+ "scrapetable",
214
+ "exportcsv",
215
+ "exportjson",
216
+ "exportexcel",
217
+ "copytable",
218
+ "pushsheets",
219
+ "importcsv",
220
+ "looprows",
221
+ "transformvalues",
222
+ "deduperows",
223
+ "paginateextract",
224
+ "mergepages",
225
+ "stamplerows",
226
+ "previewgrid",
227
+ "streamdisk",
228
+ "resumeextract",
229
+ "logprovenance",
230
+ "batchdownload",
231
+ "pausedownload",
232
+ "resumedownload",
233
+ "verifydownload",
234
+ "interceptmime",
235
+ "exportnetlog",
236
+ "readclipboard",
237
+ "writeclipboard",
238
+ "copyscreen",
239
+ "quarantinedownload",
240
+ "scanvirus",
241
+ "namecaptures",
242
+ "cleanupartifacts",
243
+ "shotview",
244
+ "shotfullpage",
245
+ "shotelement",
246
+ "shotregion",
247
+ "contactsheet",
248
+ "capturepdf",
249
+ "recordscreen",
250
+ "captureaudio",
251
+ "captureframe",
252
+ "downloadimages",
253
+ "shotcanvas",
254
+ "probestream",
255
+ "readmedia",
256
+ "readassets",
257
+ "timelapse",
258
+ "convertimage",
259
+ "makethumbs",
260
+ "fetchurl",
261
+ "parsejson",
262
+ "parsehtml",
263
+ "callrest",
264
+ "callgraphql",
265
+ "opensocket",
266
+ "sendmessage",
267
+ "waitmessage",
268
+ "watchrequests",
269
+ "readheaders",
270
+ "capturebodies",
271
+ "subscribesse",
272
+ "longpoll",
273
+ "mapapi",
274
+ "extractapi",
275
+ "blockrequest",
276
+ "mockresponse",
277
+ "rewriteheaders",
278
+ "setcookies",
279
+ "readcookies",
280
+ "clearcookies",
281
+ "authflow",
282
+ "saveapikey",
283
+ "routeproxy",
284
+ "postform",
285
+ "postfiles",
286
+ "watchconsole",
287
+ "watcherrors",
288
+ "watchtasks",
289
+ "attachcdp",
290
+ "detachcdp",
291
+ "cdpcmd",
292
+ "watchcdp",
293
+ "setbreakpoint",
294
+ "stepcode",
295
+ "watchexpr",
296
+ "overridescript",
297
+ "measureflow",
298
+ "heapshot",
299
+ "trackmemory",
300
+ "profilecpu",
301
+ "watchshifts",
302
+ "traceload",
303
+ "annotatetrace",
304
+ "replaytrace",
305
+ "capturesourcemaps",
306
+ "emulatedevice",
307
+ "emulatenetwork",
308
+ "emulatelocate",
309
+ "setuseragent",
310
+ "overridepermission",
311
+ "blackboxscripts",
312
+ "persiststate",
313
+ "capturesession",
314
+ "restoresession",
315
+ "namedsessions",
316
+ "diffsessions",
317
+ "searchsessions",
318
+ "exportsessions",
319
+ "importsessions",
320
+ "composeworkflow",
321
+ "savetemplate",
322
+ "runworkflow",
323
+ "dryrun",
324
+ "delay",
325
+ "waitelement",
326
+ "compute",
327
+ "extractvars",
328
+ "listruns",
329
+ "condition",
330
+ "branch",
331
+ "loop",
332
+ "repeatuntil",
333
+ "whileloop",
334
+ "foreach",
335
+ "parallel",
336
+ "trycatch",
337
+ "visitrule",
338
+ "urlrule",
339
+ "menurule",
340
+ "keyrule",
341
+ "buttonrule",
342
+ "cronrule",
343
+ "intervalrule",
344
+ "urllistrule",
345
+ "webhookrule",
346
+ "eventrule"
347
+ ]);
348
+ var servercontractversion = 1;
349
+
350
+ // net.ts
351
+ function pathstep(current, segment) {
352
+ if (Array.isArray(current) && /^\d+$/.test(segment)) return current[Number.parseInt(segment, 10)];
353
+ if (current && typeof current === "object" && !Array.isArray(current))
354
+ return current[segment];
355
+ return void 0;
356
+ }
357
+ function parsessetext(text) {
358
+ const separator = text.lastIndexOf("\n\n");
359
+ const complete = separator === -1 ? "" : text.slice(0, separator + 2);
360
+ const rest = separator === -1 ? text : text.slice(separator + 2);
361
+ const events = [];
362
+ for (const block of complete.split(/\n\n/)) {
363
+ const id = [];
364
+ const names = [];
365
+ const data = [];
366
+ let retry;
367
+ for (const line of block.split("\n")) {
368
+ if (line === "" || line.startsWith(":")) continue;
369
+ const colon = line.indexOf(":");
370
+ const field = colon === -1 ? line : line.slice(0, colon);
371
+ let value = colon === -1 ? "" : line.slice(colon + 1);
372
+ if (value.startsWith(" ")) value = value.slice(1);
373
+ if (field === "id" && value !== "") id.push(value);
374
+ if (field === "event" && value !== "") names.push(value);
375
+ if (field === "data") data.push(value);
376
+ if (field === "retry" && /^\d+$/.test(value)) retry = Number.parseInt(value, 10);
377
+ }
378
+ if (id.length === 0 && names.length === 0 && data.length === 0) continue;
379
+ events.push({
380
+ ...id.length > 0 ? { id: id[id.length - 1] } : {},
381
+ ...names.length > 0 ? { event: names[names.length - 1] } : {},
382
+ data: data.join("\n"),
383
+ ...retry !== void 0 ? { retry } : {}
384
+ });
385
+ }
386
+ return { events, rest };
387
+ }
388
+ function sserequestheaders(record) {
389
+ return {
390
+ accept: "text/event-stream",
391
+ ...record.lasteventid !== void 0 && record.lasteventid !== "" ? { "last-event-id": record.lasteventid } : {}
392
+ };
393
+ }
394
+ function cursorfrom(response, field) {
395
+ let current = response;
396
+ for (const segment of field.split(".")) {
397
+ const next = pathstep(current, segment);
398
+ if (next === void 0) return void 0;
399
+ current = next;
400
+ }
401
+ return current === void 0 || current === null ? void 0 : String(current);
402
+ }
403
+ function pollurl(cursor, value) {
404
+ if (cursor.param === void 0 || value === void 0) {
405
+ return {
406
+ url: cursor.url,
407
+ ...value !== void 0 ? { body: JSON.stringify({ [cursor.cursorfield]: value }) } : {}
408
+ };
409
+ }
410
+ const url = new URL(cursor.url);
411
+ url.searchParams.set(cursor.param, value);
412
+ return { url: url.toString() };
413
+ }
414
+ function polldecision(input) {
415
+ if (input.cancelled?.() === true) return { continue: false, reason: "The long poll loop was cancelled." };
416
+ if (input.expiresat !== void 0 && input.now >= input.expiresat)
417
+ return { continue: false, reason: "The long poll loop stopped at the reviewed plan expiry." };
418
+ const stopvalue = cursorfrom(input.response, input.cursor.stop.field);
419
+ if (stopvalue !== void 0 && stopvalue === input.cursor.stop.equals)
420
+ return { continue: false, reason: `The stop condition matched ${input.cursor.stop.field} ${stopvalue}.` };
421
+ if (input.cursor.maxpolls !== void 0 && input.polls + 1 >= input.cursor.maxpolls)
422
+ return {
423
+ continue: false,
424
+ reason: `The long poll loop reached the reviewed poll ceiling of ${input.cursor.maxpolls}.`
425
+ };
426
+ const value = cursorfrom(input.response, input.cursor.cursorfield);
427
+ const next = pollurl(input.cursor, value);
428
+ return {
429
+ continue: true,
430
+ reason: "The long poll loop continues.",
431
+ ...value !== void 0 ? { cursor: value } : {},
432
+ next: { ...next, wait: input.cursor.interval }
433
+ };
434
+ }
435
+ function retryafterof(status, headers) {
436
+ if (status !== 429 && status !== 503) return void 0;
437
+ for (const key of Object.keys(headers)) {
438
+ if (key.toLowerCase() !== "retry-after") continue;
439
+ const raw = headers[key];
440
+ if (raw === void 0) continue;
441
+ const value = raw.trim();
442
+ const seconds = Number(value);
443
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
444
+ const date = Date.parse(value);
445
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
446
+ return void 0;
447
+ }
448
+ return void 0;
449
+ }
450
+
451
+ // auth.ts
452
+ var tokenhashprefix = "sha256:";
453
+ var authrefusedmessage = "The remote frame failed its authentication handshake.";
454
+ async function tokenhashof(raw) {
455
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw));
456
+ return tokenhashprefix + [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
457
+ }
458
+ async function verifytoken(input) {
459
+ const hash = await tokenhashof(input.raw);
460
+ const match = input.tokens.find((candidate) => candidate.hash === hash);
461
+ if (match === void 0) return { reason: authrefusedmessage };
462
+ if (match.revokedat !== void 0) return { reason: authrefusedmessage };
463
+ if (input.now >= match.expiresat) return { reason: authrefusedmessage };
464
+ return { token: match };
465
+ }
466
+ function checkallowlist(input) {
467
+ const entry = input.entries.find((candidate) => candidate.fingerprint === input.fingerprint);
468
+ if (entry === void 0)
469
+ return {
470
+ allowed: false,
471
+ reason: `The client fingerprint ${input.fingerprint} is not on the allowlist and is refused.`
472
+ };
473
+ if (input.namespace !== void 0 && !entry.namespaces.includes(input.namespace))
474
+ return { allowed: false, reason: `The allowlist entry ${entry.displayname} grants no ${input.namespace} tools.` };
475
+ return { allowed: true };
476
+ }
477
+ function scopecheck(token, namespace) {
478
+ if (namespace === void 0)
479
+ return { allowed: false, fast: true, reason: "The tool call names no reviewed namespace." };
480
+ if (token === void 0) return { allowed: false, reason: "The tool call carries no verified session token." };
481
+ if (!token.scopes.includes(namespace))
482
+ return { allowed: false, reason: `The session token grants no ${namespace} tools.` };
483
+ return { allowed: true };
484
+ }
485
+ function tlsstateof(tls) {
486
+ return {
487
+ mode: tls.mode,
488
+ certificaterequired: tls.mode === "required" || tls.certificatefingerprint !== void 0,
489
+ verified: tls.verifiedat !== void 0
490
+ };
491
+ }
492
+ function urlencodeform(fields) {
493
+ return fields.map((field) => `${formencode(field.name)}=${formencode(field.value)}`).join("&");
494
+ }
495
+ function formencode(value) {
496
+ const bytes = [...new TextEncoder().encode(value)];
497
+ return bytes.map(
498
+ (byte) => byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || byte >= 48 && byte <= 57 || byte === 45 || byte === 95 || byte === 46 || byte === 126 ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`
499
+ ).join("");
500
+ }
501
+
502
+ // bridge.ts
503
+ var serveroperations = ["sessioncreate", "sessionjoin", "eventpost", "eventstream"];
504
+ var servereventtypes = ["chat", "planproposal", "planreview", "progress"];
505
+ function contractcapabilities(version = servercontractversion) {
506
+ return {
507
+ version,
508
+ operations: [...serveroperations],
509
+ events: [...servereventtypes],
510
+ heartbeat: true,
511
+ multiplex: true
512
+ };
513
+ }
514
+ function composeenvelope(input) {
515
+ const opid = input.opid.trim();
516
+ if (opid === "")
517
+ throw new Error("The envelope carries its stable operation id; an empty id never correlates a reply.");
518
+ if (!serveroperations.includes(input.op))
519
+ throw new Error(`The envelope operation ${input.op} sits outside the servercontract operations.`);
520
+ if (!Number.isFinite(input.at)) throw new Error("The envelope carries its timestamp.");
521
+ return {
522
+ version: input.version ?? servercontractversion,
523
+ op: input.op,
524
+ opid,
525
+ at: input.at,
526
+ ...input.sessionid !== void 0 && input.sessionid.trim() !== "" ? { sessionid: input.sessionid.trim() } : {},
527
+ ...input.token !== void 0 && input.token.trim() !== "" ? { token: input.token.trim() } : {},
528
+ ...input.body !== void 0 ? { body: input.body } : {}
529
+ };
530
+ }
531
+ function parseenvelope(value) {
532
+ if (!value || typeof value !== "object" || Array.isArray(value))
533
+ throw new Error("The servercontract envelope must be a json object.");
534
+ const entry = value;
535
+ if (!Number.isInteger(entry.version) || entry.version < 1)
536
+ throw new Error("The envelope version must be a positive whole number.");
537
+ if (typeof entry.op !== "string" || !serveroperations.includes(entry.op))
538
+ throw new Error(`The envelope operation ${String(entry.op)} sits outside the servercontract operations.`);
539
+ if (typeof entry.opid !== "string" || entry.opid.trim() === "")
540
+ throw new Error("The envelope operation id must be a non-empty string.");
541
+ if (entry.sessionid !== void 0 && (typeof entry.sessionid !== "string" || entry.sessionid.trim() === ""))
542
+ throw new Error("The envelope session id must be a non-empty string when present.");
543
+ if (entry.token !== void 0 && (typeof entry.token !== "string" || entry.token.trim() === ""))
544
+ throw new Error("The envelope frame token must be a non-empty string when present.");
545
+ if (!Number.isFinite(entry.at)) throw new Error("The envelope timestamp must be a finite number.");
546
+ if (entry.body !== void 0 && (!entry.body || typeof entry.body !== "object" || Array.isArray(entry.body)))
547
+ throw new Error("The envelope body must be a json object when present.");
548
+ return {
549
+ version: entry.version,
550
+ op: entry.op,
551
+ opid: entry.opid.trim(),
552
+ at: entry.at,
553
+ ...entry.sessionid !== void 0 ? { sessionid: entry.sessionid.trim() } : {},
554
+ ...entry.token !== void 0 ? { token: entry.token.trim() } : {},
555
+ ...entry.body !== void 0 ? { body: entry.body } : {}
556
+ };
557
+ }
558
+ function parsewireframe(text) {
559
+ let parsed;
560
+ try {
561
+ parsed = JSON.parse(text);
562
+ } catch {
563
+ throw new Error("The wire frame must be json text.");
564
+ }
565
+ return parseenvelope(parsed);
566
+ }
567
+
568
+ // tools.ts
569
+ var toolnamespaces = ["browser", "workflow", "memory", "system"];
570
+ function namespaceof(name) {
571
+ const head = name.split(".")[0];
572
+ return toolnamespaces.includes(head) ? head : void 0;
573
+ }
574
+
575
+ // serve.ts
576
+ function encodemessage(message) {
577
+ return Array.isArray(message) ? JSON.stringify(message) : serializeframe(message);
578
+ }
579
+ function decodemessage(raw) {
580
+ let parsed;
581
+ try {
582
+ parsed = JSON.parse(raw);
583
+ } catch {
584
+ return { error: rpcerrorof("parse", "The wire message does not parse as json.") };
585
+ }
586
+ if (Array.isArray(parsed)) {
587
+ if (parsed.length === 0) return { error: rpcerrorof("params", "A batch message carries at least one frame.") };
588
+ const frames = [];
589
+ for (const entry of parsed) {
590
+ try {
591
+ frames.push(parseframe(JSON.stringify(entry)));
592
+ } catch {
593
+ return { error: rpcerrorof("parse", "Every batch member must be a json rpc frame.") };
594
+ }
595
+ }
596
+ return { message: frames };
597
+ }
598
+ try {
599
+ const frame = parseframe(raw);
600
+ return { message: frame };
601
+ } catch {
602
+ return { error: rpcerrorof("parse", "The wire message must be one json rpc frame or one batch of frames.") };
603
+ }
604
+ }
605
+ function framesof(message) {
606
+ return Array.isArray(message) ? message : [message];
607
+ }
608
+ function isnotification(frame) {
609
+ return frame.id === void 0;
610
+ }
611
+
612
+ // mcp.ts
613
+ var localhostbind = "127.0.0.1";
614
+ function rpcerrorof(code, message, data) {
615
+ return { code, message, ...data !== void 0 ? { data } : {} };
616
+ }
617
+ function unwraphttppost(value) {
618
+ if (value && typeof value === "object" && !Array.isArray(value)) {
619
+ const candidate = value;
620
+ if (candidate.transport === "http" && candidate.frame && typeof candidate.frame === "object" && !Array.isArray(candidate.frame))
621
+ return candidate.frame;
622
+ }
623
+ return value;
624
+ }
625
+ function parseframe(raw) {
626
+ const parsed = unwraphttppost(JSON.parse(raw));
627
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
628
+ throw new Error("A json rpc frame must be an object.");
629
+ return parsed;
630
+ }
631
+ function serializeframe(frame) {
632
+ return JSON.stringify(frame);
633
+ }
634
+ function bindlocalhost(config) {
635
+ const bind = config.bind !== void 0 && config.bind.trim() !== "" ? config.bind.trim() : localhostbind;
636
+ return { bind, port: config.port, localhost: bind === localhostbind || bind === "localhost" || bind === "::1" };
637
+ }
638
+
639
+ // http.ts
640
+ var httpkinds = ["fetchurl", "parsejson", "parsehtml", "callrest", "callgraphql"];
641
+ var redirectstatuses = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
642
+ var bodilessmethods = /* @__PURE__ */ new Set(["GET", "HEAD"]);
643
+ function statusclassof(status) {
644
+ if (status >= 100 && status < 200) return "informational";
645
+ if (status >= 200 && status < 300) return "success";
646
+ if (status >= 300 && status < 400) return "redirect";
647
+ if (status >= 400 && status < 500) return "clienterror";
648
+ if (status >= 500 && status < 600) return "servererror";
649
+ return "unknown";
650
+ }
651
+ function templateurl(template, values) {
652
+ return template.replace(
653
+ /\{([a-z0-9_]+)\}/gi,
654
+ (whole, name) => values[name] === void 0 ? whole : String(values[name])
655
+ );
656
+ }
657
+ function fetchrequestof(value) {
658
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
659
+ const options = value;
660
+ if (typeof options.url !== "string" || !options.url.trim()) return void 0;
661
+ const request = { url: options.url.trim() };
662
+ if (typeof options.method === "string" && options.method.trim()) request.method = options.method.trim().toUpperCase();
663
+ if (options.headers && typeof options.headers === "object" && !Array.isArray(options.headers)) {
664
+ const headers = {};
665
+ for (const [name, headervalue] of Object.entries(options.headers)) {
666
+ if (typeof headervalue === "string") headers[name] = headervalue;
667
+ }
668
+ request.headers = headers;
669
+ }
670
+ if (typeof options.body === "string") request.body = options.body;
671
+ if (options.mode === "cors" || options.mode === "no-cors" || options.mode === "same-origin")
672
+ request.mode = options.mode;
673
+ return request;
674
+ }
675
+ function fetchoptionsof(value) {
676
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
677
+ const options = value;
678
+ const normalized = {};
679
+ if (typeof options.timeout === "number" && Number.isFinite(options.timeout)) normalized.timeout = options.timeout;
680
+ if (typeof options.retries === "number" && Number.isFinite(options.retries)) normalized.retries = options.retries;
681
+ if (typeof options.backoff === "number" && Number.isFinite(options.backoff)) normalized.backoff = options.backoff;
682
+ if (typeof options.follow === "number" && Number.isFinite(options.follow)) normalized.follow = options.follow;
683
+ return normalized;
684
+ }
685
+ function streamwindowof(value) {
686
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
687
+ const options = value;
688
+ const window = {};
689
+ if (typeof options.budget === "number" && Number.isFinite(options.budget)) window.budget = options.budget;
690
+ return window;
691
+ }
692
+ function jsonpathrulesof(value) {
693
+ if (!Array.isArray(value)) return [];
694
+ const rules = [];
695
+ for (const item of value) {
696
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
697
+ const entry = item;
698
+ if (typeof entry.name !== "string" || !entry.name.trim()) continue;
699
+ if (typeof entry.path !== "string" || !entry.path.trim()) continue;
700
+ const rule = { name: entry.name.trim(), path: entry.path.trim() };
701
+ if (entry.kind === "text" || entry.kind === "number" || entry.kind === "boolean" || entry.kind === "json")
702
+ rule.kind = entry.kind;
703
+ if (entry.default !== void 0) rule.default = entry.default;
704
+ rules.push(rule);
705
+ }
706
+ return rules;
707
+ }
708
+ function htmlqueriesof(value) {
709
+ if (!Array.isArray(value)) return [];
710
+ const queries = [];
711
+ for (const item of value) {
712
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
713
+ const entry = item;
714
+ if (typeof entry.selector !== "string" || !entry.selector.trim()) continue;
715
+ const query = { selector: entry.selector.trim() };
716
+ if (typeof entry.attribute === "string" && entry.attribute.trim()) query.attribute = entry.attribute.trim();
717
+ if (entry.multi === true) query.multi = true;
718
+ queries.push(query);
719
+ }
720
+ return queries;
721
+ }
722
+ function graphqlrequestof(value) {
723
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
724
+ const options = value;
725
+ if (typeof options.query !== "string" || !options.query.trim()) return void 0;
726
+ if (options.operationkind !== "query" && options.operationkind !== "mutation") return void 0;
727
+ const request = { query: options.query, operationkind: options.operationkind };
728
+ if (options.variables && typeof options.variables === "object" && !Array.isArray(options.variables))
729
+ request.variables = options.variables;
730
+ if (typeof options.operationname === "string" && options.operationname.trim())
731
+ request.operationname = options.operationname.trim();
732
+ return request;
733
+ }
734
+ var realsleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, Math.max(0, milliseconds)));
735
+ async function sendfetch(input) {
736
+ const options = input.options ?? {};
737
+ const sleep = input.sleep ?? realsleep;
738
+ const now = input.now ?? Date.now;
739
+ const attempts = Math.max(1, Math.floor(options.retries ?? 0) + 1);
740
+ const backoff = options.backoff ?? 0;
741
+ const follow = options.follow ?? Number.POSITIVE_INFINITY;
742
+ let url = input.request.url;
743
+ let method = (input.request.method ?? "GET").toUpperCase();
744
+ let retries = 0;
745
+ let redirects = 0;
746
+ let lastreason = "";
747
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
748
+ let hops = 0;
749
+ const startedat = now();
750
+ let response;
751
+ try {
752
+ const init = {
753
+ method,
754
+ headers: { ...input.request.headers ?? {} },
755
+ ...input.request.body !== void 0 && !bodilessmethods.has(method) ? { body: input.request.body } : {},
756
+ ...input.request.mode !== void 0 ? { mode: input.request.mode } : {},
757
+ redirect: follow <= 0 ? "error" : "follow"
758
+ };
759
+ const sent = input.transport(url, init);
760
+ if (options.timeout !== void 0 && Number.isFinite(options.timeout) && options.timeout >= 0) {
761
+ let timedout = false;
762
+ response = await Promise.race([
763
+ sent,
764
+ sleep(options.timeout).then(() => {
765
+ timedout = true;
766
+ return void 0;
767
+ })
768
+ ]).then(
769
+ (value) => value ?? (timedout ? (() => {
770
+ throw new Error(`The request timed out after ${options.timeout} milliseconds.`);
771
+ })() : value)
772
+ );
773
+ } else {
774
+ response = await sent;
775
+ }
776
+ while (response !== void 0 && redirectstatuses.has(response.status) && typeof response.location === "string" && response.location) {
777
+ hops += 1;
778
+ if (hops > follow) throw new Error(`The redirect chain exceeded the reviewed follow limit of ${follow}.`);
779
+ url = new URL(response.location, url).toString();
780
+ if (method === "POST" && [301, 302, 303].includes(response.status)) method = "GET";
781
+ const hopinit = { ...init, method };
782
+ if (bodilessmethods.has(method))
783
+ delete hopinit.body;
784
+ response = await input.transport(url, hopinit);
785
+ }
786
+ redirects = hops;
787
+ } catch (error) {
788
+ lastreason = error instanceof Error ? error.message : String(error);
789
+ response = void 0;
790
+ }
791
+ if (response !== void 0) {
792
+ const body = response.body;
793
+ return {
794
+ url,
795
+ status: response.status,
796
+ statusclass: statusclassof(response.status),
797
+ headernames: Object.keys(response.headers),
798
+ body,
799
+ bytes: body.length,
800
+ duration: now() - startedat,
801
+ retries,
802
+ redirects
803
+ };
804
+ }
805
+ if (attempt < attempts) {
806
+ const wait = backoff * attempt;
807
+ if (wait > 0) await sleep(wait);
808
+ input.onretry?.(attempt, wait, lastreason);
809
+ retries = attempt;
810
+ }
811
+ }
812
+ throw new Error(
813
+ `The request failed after ${attempts} attempt${attempts === 1 ? "" : "s"} with ${retries} retr${retries === 1 ? "y" : "ies"}: ${lastreason}`
814
+ );
815
+ }
816
+ async function readstream(input) {
817
+ const pull = typeof input.chunks === "function" ? input.chunks : /* @__PURE__ */ ((source) => {
818
+ let index = 0;
819
+ return async () => source[index++];
820
+ })(input.chunks);
821
+ let count = 0;
822
+ let total = 0;
823
+ for (; ; ) {
824
+ if (input.window.abort?.() === true)
825
+ return { chunks: count, bytes: total, aborted: true, reason: "The reviewed abort flag stopped the stream." };
826
+ const chunk = await pull();
827
+ if (chunk === void 0) return { chunks: count, bytes: total, aborted: false };
828
+ const next = total + chunk.length;
829
+ if (input.window.budget !== void 0 && next > input.window.budget)
830
+ return {
831
+ chunks: count,
832
+ bytes: total,
833
+ aborted: true,
834
+ reason: `The stream aborted at ${next} bytes past the reviewed byte budget of ${input.window.budget}.`
835
+ };
836
+ total = next;
837
+ count += 1;
838
+ input.window.onchunk?.(chunk, total);
839
+ }
840
+ }
841
+ function pathstep2(current, segment) {
842
+ if (Array.isArray(current) && /^\d+$/.test(segment)) return current[Number.parseInt(segment, 10)];
843
+ if (current && typeof current === "object" && !Array.isArray(current))
844
+ return current[segment];
845
+ return void 0;
846
+ }
847
+ function coerce(value, kind, fallback) {
848
+ if (value === void 0 || value === null) return { value: fallback, missing: true };
849
+ if (kind === "text") return { value: String(value), missing: false };
850
+ if (kind === "number") {
851
+ const numeric = typeof value === "number" ? value : Number(value);
852
+ return Number.isFinite(numeric) ? { value: numeric, missing: false } : { value: fallback, missing: true };
853
+ }
854
+ if (kind === "boolean") return { value: value === true || value === "true", missing: false };
855
+ return { value, missing: false };
856
+ }
857
+ function readpath(parsed, rules) {
858
+ const fields = [];
859
+ for (const rule of rules) {
860
+ const kind = rule.kind ?? "text";
861
+ let current = parsed;
862
+ let missing = false;
863
+ for (const segment of rule.path.split(".")) {
864
+ const next = pathstep2(current, segment);
865
+ if (next === void 0) {
866
+ missing = true;
867
+ break;
868
+ }
869
+ current = next;
870
+ }
871
+ if (missing)
872
+ fields.push({
873
+ name: rule.name,
874
+ path: rule.path,
875
+ kind,
876
+ ...rule.default !== void 0 ? { value: rule.default } : {},
877
+ missing: true
878
+ });
879
+ else {
880
+ const resolved = coerce(current, kind, rule.default);
881
+ fields.push({
882
+ name: rule.name,
883
+ path: rule.path,
884
+ kind,
885
+ ...resolved.value !== void 0 ? { value: resolved.value } : {},
886
+ ...resolved.missing ? { missing: true } : {}
887
+ });
888
+ }
889
+ }
890
+ return fields;
891
+ }
892
+ function defaultparse() {
893
+ const parser = globalThis.DOMParser;
894
+ if (!parser) throw new Error("parsehtml needs a domparser seam outside the page context.");
895
+ return (markup) => {
896
+ const document = new parser().parseFromString(markup, "text/html");
897
+ return {
898
+ query: (selector) => Array.from(document.querySelectorAll(selector)).map((element) => ({
899
+ text: element.textContent ?? "",
900
+ attributes: Object.fromEntries(
901
+ Array.from(element.attributes).map((attribute) => [attribute.name, attribute.value])
902
+ )
903
+ }))
904
+ };
905
+ };
906
+ }
907
+ function parsehtmlbody(input) {
908
+ const parse = input.parse ?? defaultparse();
909
+ const document = parse(input.body);
910
+ return input.queries.map((query) => {
911
+ const matches = document.query(query.selector);
912
+ const chosen = query.multi === true ? matches : matches.slice(0, 1);
913
+ const values = chosen.map(
914
+ (match) => query.attribute !== void 0 ? match.attributes[query.attribute] ?? "" : match.text
915
+ );
916
+ return {
917
+ selector: query.selector,
918
+ ...query.attribute !== void 0 ? { attribute: query.attribute } : {},
919
+ multi: query.multi === true,
920
+ count: matches.length,
921
+ values
922
+ };
923
+ });
924
+ }
925
+ function payloadvalid(payload, schema) {
926
+ if (!schema)
927
+ return { ok: false, errors: ["The typed endpoint call needs a reviewed payload schema before it runs."] };
928
+ const errors = [];
929
+ for (const field of schema.fields) {
930
+ const value = payload[field.name];
931
+ if (value === void 0 || value === null) {
932
+ if (field.required === true) errors.push(`The required field ${field.name} of kind ${field.kind} is missing.`);
933
+ continue;
934
+ }
935
+ if (field.kind === "string" && typeof value !== "string") errors.push(`The field ${field.name} must be a string.`);
936
+ if (field.kind === "number" && (typeof value !== "number" || !Number.isFinite(value)))
937
+ errors.push(`The field ${field.name} must be a finite number.`);
938
+ if (field.kind === "boolean" && typeof value !== "boolean")
939
+ errors.push(`The field ${field.name} must be a boolean.`);
940
+ }
941
+ return { ok: errors.length === 0, errors };
942
+ }
943
+ function payloadwithdefaults(payload, schema) {
944
+ if (!schema) return payload;
945
+ const merged = { ...payload };
946
+ for (const field of schema.fields) {
947
+ if (merged[field.name] === void 0 && field.default !== void 0) merged[field.name] = field.default;
948
+ }
949
+ return merged;
950
+ }
951
+ function errorsof(body) {
952
+ try {
953
+ const parsed = JSON.parse(body);
954
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [body];
955
+ const record = parsed;
956
+ for (const key of ["errors", "messages", "error", "message"]) {
957
+ const value = record[key];
958
+ if (Array.isArray(value))
959
+ return value.map(
960
+ (item) => typeof item === "string" ? item : item && typeof item === "object" && typeof item.message === "string" ? item.message : String(item)
961
+ );
962
+ if (typeof value === "string") return [value];
963
+ }
964
+ return [body];
965
+ } catch {
966
+ return [body];
967
+ }
968
+ }
969
+ async function callrest(input) {
970
+ const check = payloadvalid(input.payload, input.endpoint.schema);
971
+ if (!check.ok) throw new Error(check.errors.join(" "));
972
+ const payload = payloadwithdefaults(input.payload, input.endpoint.schema);
973
+ const url = templateurl(input.endpoint.url, payload);
974
+ const method = input.endpoint.method.toUpperCase();
975
+ const request = {
976
+ url,
977
+ method,
978
+ ...input.endpoint.headers !== void 0 ? { headers: input.endpoint.headers } : {},
979
+ ...bodilessmethods.has(method) ? {} : { body: JSON.stringify(payload) }
980
+ };
981
+ const transport = await sendfetch({
982
+ request,
983
+ ...input.options !== void 0 ? { options: input.options } : {},
984
+ transport: input.transport,
985
+ ...input.sleep !== void 0 ? { sleep: input.sleep } : {},
986
+ ...input.onretry !== void 0 ? { onretry: input.onretry } : {},
987
+ ...input.now !== void 0 ? { now: input.now } : {}
988
+ });
989
+ const ok = input.success !== void 0 ? input.success.includes(transport.status) : transport.statusclass === "success";
990
+ return { transport, url, payload, ok, errors: ok ? [] : errorsof(transport.body) };
991
+ }
992
+ function graphqlopenvelope(request) {
993
+ return JSON.stringify({
994
+ query: request.query,
995
+ ...request.variables !== void 0 ? { variables: request.variables } : {},
996
+ ...request.operationname !== void 0 ? { operationName: request.operationname } : {}
997
+ });
998
+ }
999
+ function unwrapgraphql(value) {
1000
+ if (!value || typeof value !== "object" || Array.isArray(value))
1001
+ return { errors: ["The graphql response is not a json object."] };
1002
+ const record = value;
1003
+ const errors = Array.isArray(record.errors) ? record.errors.map(
1004
+ (item) => typeof item === "string" ? item : item && typeof item === "object" && typeof item.message === "string" ? item.message : String(item)
1005
+ ) : [];
1006
+ return { ...record.data !== void 0 ? { data: record.data } : {}, errors };
1007
+ }
1008
+ async function callgraphql(input) {
1009
+ const request = {
1010
+ url: input.endpoint.url,
1011
+ method: "POST",
1012
+ ...input.endpoint.headers !== void 0 ? { headers: input.endpoint.headers } : {},
1013
+ body: graphqlopenvelope(input.request)
1014
+ };
1015
+ const transport = await sendfetch({
1016
+ request,
1017
+ ...input.options !== void 0 ? { options: input.options } : {},
1018
+ transport: input.transport,
1019
+ ...input.sleep !== void 0 ? { sleep: input.sleep } : {},
1020
+ ...input.onretry !== void 0 ? { onretry: input.onretry } : {},
1021
+ ...input.now !== void 0 ? { now: input.now } : {}
1022
+ });
1023
+ try {
1024
+ const unwrapped = unwrapgraphql(JSON.parse(transport.body));
1025
+ return { transport, ...unwrapped.data !== void 0 ? { data: unwrapped.data } : {}, errors: unwrapped.errors };
1026
+ } catch {
1027
+ return { transport, errors: [transport.body] };
1028
+ }
1029
+ }
1030
+ function httpendpoint(config) {
1031
+ const binding = bindlocalhost(config);
1032
+ const path = config.httpstream?.endpoint !== void 0 && config.httpstream.endpoint.trim() !== "" ? config.httpstream.endpoint.trim() : "/mcp";
1033
+ return {
1034
+ kind: "http",
1035
+ endpoint: `http://${binding.bind}:${binding.port}${path}`,
1036
+ bind: binding.bind,
1037
+ port: binding.port,
1038
+ localhost: binding.localhost,
1039
+ path
1040
+ };
1041
+ }
1042
+ function tlsdecision(input) {
1043
+ return starttls({
1044
+ config: input.config,
1045
+ ...input.presented !== void 0 ? { presented: input.presented } : {},
1046
+ now: input.now
1047
+ });
1048
+ }
1049
+ async function postauth(input) {
1050
+ if (input.local) return {};
1051
+ if (input.fingerprint === void 0 || input.fingerprint.trim() === "")
1052
+ return {
1053
+ error: {
1054
+ code: "consentrefused",
1055
+ message: "A non localhost connection must complete the auth handshake before any frame routes.",
1056
+ retryhint: "none"
1057
+ }
1058
+ };
1059
+ const pipeline = await httpframepipeline({
1060
+ config: input.config,
1061
+ tokens: input.tokens,
1062
+ ...input.rawtoken !== void 0 ? { rawtoken: input.rawtoken } : {},
1063
+ allowlist: [],
1064
+ fingerprint: input.fingerprint,
1065
+ ...input.toolname !== void 0 ? { toolname: input.toolname } : {},
1066
+ now: input.now
1067
+ });
1068
+ if (pipeline.error !== void 0)
1069
+ return { error: { code: pipeline.error.code, message: pipeline.error.message, retryhint: "none" } };
1070
+ return pipeline.token !== void 0 ? { token: pipeline.token } : {};
1071
+ }
1072
+ function parsepost(body) {
1073
+ try {
1074
+ const parsed = JSON.parse(body);
1075
+ if (Array.isArray(parsed)) {
1076
+ if (parsed.length === 0)
1077
+ return {
1078
+ error: { code: "parse", message: "The posted body does not parse as one json rpc message." }
1079
+ };
1080
+ const frames = [];
1081
+ for (const entry of parsed) frames.push(parseframe(JSON.stringify(entry)));
1082
+ return { message: frames };
1083
+ }
1084
+ return { message: parseframe(body) };
1085
+ } catch {
1086
+ return { error: { code: "parse", message: "The posted body does not parse as one json rpc message." } };
1087
+ }
1088
+ }
1089
+ function httpanswer(frame) {
1090
+ return `${encodemessage(frame)}
1091
+ `;
1092
+ }
1093
+ function sseframe(input) {
1094
+ return `id: ${input.id}
1095
+ event: ${input.event}
1096
+ data: ${JSON.stringify(input.frame)}
1097
+
1098
+ `;
1099
+ }
1100
+ function streampathof(config) {
1101
+ const binding = bindlocalhost(config);
1102
+ const path = config.httpstream?.streampath !== void 0 && config.httpstream.streampath.trim() !== "" ? config.httpstream.streampath.trim() : "/mcp/stream";
1103
+ return { path, bind: binding.bind, port: binding.port, localhost: binding.localhost };
1104
+ }
1105
+ function routepath(config, path) {
1106
+ const endpoint = httpendpoint(config).path;
1107
+ const stream = streampathof(config).path;
1108
+ if (path === endpoint) return "endpoint";
1109
+ if (path === stream) return "stream";
1110
+ return void 0;
1111
+ }
1112
+ var documentedbind = localhostbind;
1113
+ var defaultheartbeatms = 3e4;
1114
+ var defaultidlewindowms = 9e4;
1115
+ function defaulthttpstream() {
1116
+ return {
1117
+ endpoint: "/mcp",
1118
+ streampath: "/mcp/stream",
1119
+ tls: { mode: "off" },
1120
+ heartbeatms: defaultheartbeatms,
1121
+ idlewindowms: defaultidlewindowms
1122
+ };
1123
+ }
1124
+ function openstreamchannel(input) {
1125
+ return {
1126
+ id: input.id ?? `channel-${randomchannelid()}`,
1127
+ clientid: input.clientid,
1128
+ openedat: input.now,
1129
+ lastbeatat: input.now
1130
+ };
1131
+ }
1132
+ function randomchannelid() {
1133
+ return crypto.randomUUID();
1134
+ }
1135
+ function heartbeat(input) {
1136
+ return input.channels.map(
1137
+ (channel) => channel.clientid === input.clientid && channel.closedat === void 0 ? { ...channel, lastbeatat: input.now } : channel
1138
+ );
1139
+ }
1140
+ function channellive(channel, now, idlewindow) {
1141
+ if (channel.closedat !== void 0) return false;
1142
+ return now - channel.lastbeatat < (idlewindow ?? defaultidlewindowms);
1143
+ }
1144
+ function closeidlechannels(input) {
1145
+ return input.channels.map(
1146
+ (channel) => channel.closedat === void 0 && !channellive(channel, input.now, input.idlewindow) ? { ...channel, closedat: input.now } : channel
1147
+ );
1148
+ }
1149
+ function starttls(input) {
1150
+ if (input.config.mode === "off") return { tls: false, verified: false };
1151
+ if (input.config.mode === "required" && input.presented?.fingerprint === void 0)
1152
+ return {
1153
+ tls: false,
1154
+ verified: false,
1155
+ reason: "The remote transport requires tls and the peer presented no certificate."
1156
+ };
1157
+ if (input.config.certificatefingerprint !== void 0 && input.presented?.fingerprint !== input.config.certificatefingerprint)
1158
+ return {
1159
+ tls: false,
1160
+ verified: false,
1161
+ reason: "The peer certificate does not match the user configured fingerprint and the remote traffic is refused."
1162
+ };
1163
+ return { tls: true, verified: true };
1164
+ }
1165
+ function enforcemaxclients(input) {
1166
+ if (input.maxclients === void 0) return { allowed: true };
1167
+ if (!Number.isFinite(input.maxclients))
1168
+ return {
1169
+ allowed: false,
1170
+ reason: `The user configured maximum of ${input.maxclients} remote clients is invalid and the connection is refused.`
1171
+ };
1172
+ const connected = input.clients.filter((client) => client.disconnectedat === void 0).length;
1173
+ if (connected >= input.maxclients)
1174
+ return {
1175
+ allowed: false,
1176
+ reason: `The user configured maximum of ${input.maxclients} remote clients is reached and the connection is refused.`
1177
+ };
1178
+ return { allowed: true };
1179
+ }
1180
+ function listremotestatus(input) {
1181
+ const stream = input.config.httpstream ?? defaulthttpstream();
1182
+ const remote = input.config.remoteaccess;
1183
+ const idlewindow = stream.idlewindowms;
1184
+ const open = input.channels.filter((channel) => channellive(channel, input.now, idlewindow));
1185
+ return {
1186
+ endpoint: remote?.endpoint ?? stream.endpoint,
1187
+ tls: tlsstateof(remote?.tls ?? stream.tls),
1188
+ clients: input.clients.filter((client) => client.disconnectedat === void 0).length,
1189
+ paired: input.clients.filter((client) => client.paired && client.disconnectedat === void 0).length,
1190
+ channelsopen: open.length,
1191
+ channelsdead: input.channels.length - open.length,
1192
+ tokenslive: input.tokens.filter((token) => token.revokedat === void 0 && input.now < token.expiresat).length
1193
+ };
1194
+ }
1195
+ async function httpframepipeline(input) {
1196
+ const stream = input.config.httpstream ?? defaulthttpstream();
1197
+ const tls = starttls({
1198
+ config: input.config.remoteaccess?.tls ?? stream.tls,
1199
+ ...input.presented !== void 0 ? { presented: input.presented } : {},
1200
+ now: input.now
1201
+ });
1202
+ if (tls.reason !== void 0) return { error: rpcerrorof("consentrefused", tls.reason) };
1203
+ if (input.rawtoken === void 0) return { error: rpcerrorof("consentrefused", authrefusedmessage) };
1204
+ const verified = await verifytoken({ tokens: input.tokens, raw: input.rawtoken, now: input.now });
1205
+ if (verified.token === void 0)
1206
+ return { error: rpcerrorof("consentrefused", verified.reason ?? authrefusedmessage) };
1207
+ const namespace = input.toolname !== void 0 ? namespaceof(input.toolname) : void 0;
1208
+ const listed = checkallowlist({
1209
+ entries: input.allowlist,
1210
+ fingerprint: input.fingerprint,
1211
+ ...namespace !== void 0 ? { namespace } : {}
1212
+ });
1213
+ if (!listed.allowed)
1214
+ return { error: rpcerrorof("consentrefused", listed.reason ?? "The allowlist refused the client.") };
1215
+ const scoped = scopecheck(verified.token, namespace);
1216
+ if (!scoped.allowed)
1217
+ return {
1218
+ error: rpcerrorof(
1219
+ scoped.fast === true ? "params" : "consentrefused",
1220
+ scoped.reason ?? "The tool call stayed outside the granted scopes."
1221
+ )
1222
+ };
1223
+ return { token: verified.token };
1224
+ }
1225
+ function newrelayserverstate() {
1226
+ return { sessions: [], pairings: [], connections: [], tokens: [], issued: 0 };
1227
+ }
1228
+ function relayconnectionopen(state, connectionid, now) {
1229
+ if (connectionid.trim() === "")
1230
+ throw new Error("The relay names every connection; an empty connection id never registers.");
1231
+ if (state.connections.some((connection) => connection.id === connectionid)) return state;
1232
+ return {
1233
+ ...state,
1234
+ connections: [...state.connections, { id: connectionid, role: "", sessionid: "", tokenhash: "", lastframeat: now }]
1235
+ };
1236
+ }
1237
+ function relayconnectionclose(state, connectionid) {
1238
+ return {
1239
+ ...state,
1240
+ connections: state.connections.filter((connection) => connection.id !== connectionid),
1241
+ tokens: state.tokens.filter((record) => record.connectionid !== connectionid)
1242
+ };
1243
+ }
1244
+ function relaylivetokens(session) {
1245
+ return session.tokenhashes.filter((hash) => !session.revoked.includes(hash));
1246
+ }
1247
+ function relayframeof(envelope) {
1248
+ return JSON.stringify(composeenvelope({ ...envelope, version: envelope.version ?? servercontractversion }));
1249
+ }
1250
+ function relayserverframe(input) {
1251
+ const idof = input.idof ?? (() => {
1252
+ const next = input.state.issued + 1;
1253
+ return `${next}`;
1254
+ });
1255
+ const hashof = input.hashof ?? ((token) => token);
1256
+ const connection = input.state.connections.find((entry) => entry.id === input.connectionid);
1257
+ if (connection === void 0) return { state: input.state, replies: [], routed: [] };
1258
+ let envelope;
1259
+ try {
1260
+ envelope = parsewireframe(input.frame);
1261
+ } catch {
1262
+ return {
1263
+ state: input.state,
1264
+ replies: [
1265
+ relayframeof({
1266
+ op: "eventpost",
1267
+ opid: "op-relay-parse",
1268
+ at: input.now,
1269
+ body: { error: "The frame does not parse as a servercontract envelope." }
1270
+ })
1271
+ ],
1272
+ routed: []
1273
+ };
1274
+ }
1275
+ const touched = { ...connection, lastframeat: input.now };
1276
+ const base = {
1277
+ ...input.state,
1278
+ connections: input.state.connections.map((entry) => entry.id === touched.id ? touched : entry),
1279
+ issued: input.state.issued + 1
1280
+ };
1281
+ if (envelope.op === "sessioncreate") {
1282
+ const body = envelope.body ?? {};
1283
+ if (body.role !== "extension") {
1284
+ return {
1285
+ state: base,
1286
+ replies: [
1287
+ relayframeof({
1288
+ op: "sessioncreate",
1289
+ opid: envelope.opid,
1290
+ at: input.now,
1291
+ body: { error: "The sessioncreate operation serves the extension member only." }
1292
+ })
1293
+ ],
1294
+ routed: []
1295
+ };
1296
+ }
1297
+ const sessionid = `session-${idof()}`;
1298
+ const token = `token-${idof()}`;
1299
+ const tokenhash2 = hashof(token);
1300
+ const session2 = {
1301
+ id: sessionid,
1302
+ extension: touched.id,
1303
+ site: void 0,
1304
+ events: [],
1305
+ tokenhashes: [tokenhash2],
1306
+ revoked: []
1307
+ };
1308
+ let pairings = base.pairings;
1309
+ const pairingcode = typeof body.pairingcode === "string" ? body.pairingcode.trim() : "";
1310
+ if (pairingcode !== "")
1311
+ pairings = [...pairings, { code: pairingcode, sessionid, expiresat: input.now + 3e5, used: false }];
1312
+ const memberid = typeof body.memberid === "string" ? body.memberid : "";
1313
+ const reply = relayframeof({
1314
+ op: "sessioncreate",
1315
+ opid: envelope.opid,
1316
+ sessionid,
1317
+ token,
1318
+ at: input.now,
1319
+ body: {
1320
+ sessionid,
1321
+ token,
1322
+ capabilities: contractcapabilities(),
1323
+ members: [{ role: "extension", id: memberid, joinedat: input.now }]
1324
+ }
1325
+ });
1326
+ return {
1327
+ state: {
1328
+ ...base,
1329
+ sessions: [...base.sessions, session2],
1330
+ pairings,
1331
+ connections: base.connections.map(
1332
+ (entry) => entry.id === touched.id ? { ...entry, role: "extension", sessionid, tokenhash: tokenhash2 } : entry
1333
+ ),
1334
+ tokens: [
1335
+ ...base.tokens.filter((record) => record.connectionid !== touched.id),
1336
+ { connectionid: touched.id, token }
1337
+ ]
1338
+ },
1339
+ replies: [reply],
1340
+ routed: []
1341
+ };
1342
+ }
1343
+ if (envelope.op === "sessionjoin") {
1344
+ const body = envelope.body ?? {};
1345
+ const pairingcode = typeof body.pairingcode === "string" ? body.pairingcode.trim() : "";
1346
+ if (pairingcode !== "" && body.role === "site") {
1347
+ const pairing = base.pairings.find(
1348
+ (entry) => entry.code === pairingcode && !entry.used && input.now < entry.expiresat
1349
+ );
1350
+ const session3 = pairing === void 0 ? void 0 : base.sessions.find((entry) => entry.id === pairing.sessionid);
1351
+ if (pairing === void 0 || session3 === void 0) {
1352
+ return {
1353
+ state: base,
1354
+ replies: [
1355
+ relayframeof({
1356
+ op: "sessionjoin",
1357
+ opid: envelope.opid,
1358
+ at: input.now,
1359
+ body: { error: "The pairing code matches no pending session of this relay." }
1360
+ })
1361
+ ],
1362
+ routed: []
1363
+ };
1364
+ }
1365
+ if (session3.site !== void 0) {
1366
+ return {
1367
+ state: base,
1368
+ replies: [
1369
+ relayframeof({
1370
+ op: "sessionjoin",
1371
+ opid: envelope.opid,
1372
+ at: input.now,
1373
+ body: { error: "The relay session holds at most one site member." }
1374
+ })
1375
+ ],
1376
+ routed: []
1377
+ };
1378
+ }
1379
+ const token2 = `token-${idof()}`;
1380
+ const tokenhash3 = hashof(token2);
1381
+ const reply2 = relayframeof({
1382
+ op: "sessionjoin",
1383
+ opid: envelope.opid,
1384
+ sessionid: session3.id,
1385
+ token: token2,
1386
+ at: input.now,
1387
+ body: { sessionid: session3.id, token: token2, capabilities: contractcapabilities() }
1388
+ });
1389
+ return {
1390
+ state: {
1391
+ ...base,
1392
+ sessions: base.sessions.map(
1393
+ (entry) => entry.id === session3.id ? { ...entry, site: touched.id, tokenhashes: [...entry.tokenhashes, tokenhash3] } : entry
1394
+ ),
1395
+ pairings: base.pairings.map((entry) => entry.code === pairingcode ? { ...entry, used: true } : entry),
1396
+ connections: base.connections.map(
1397
+ (entry) => entry.id === touched.id ? { ...entry, role: "site", sessionid: session3.id, tokenhash: tokenhash3 } : entry
1398
+ ),
1399
+ tokens: [
1400
+ ...base.tokens.filter((record) => record.connectionid !== touched.id),
1401
+ { connectionid: touched.id, token: token2 }
1402
+ ]
1403
+ },
1404
+ replies: [reply2],
1405
+ routed: []
1406
+ };
1407
+ }
1408
+ const session2 = base.sessions.find((entry) => entry.id === envelope.sessionid);
1409
+ const tokenhash2 = typeof envelope.token === "string" ? hashof(envelope.token) : "";
1410
+ if (session2 === void 0 || tokenhash2 === "" || !relaylivetokens(session2).includes(tokenhash2)) {
1411
+ return {
1412
+ state: base,
1413
+ replies: [
1414
+ relayframeof({
1415
+ op: "sessionjoin",
1416
+ opid: envelope.opid,
1417
+ at: input.now,
1418
+ body: { error: "The sessionjoin frame failed the token authentication." }
1419
+ })
1420
+ ],
1421
+ routed: []
1422
+ };
1423
+ }
1424
+ const token = `token-${idof()}`;
1425
+ const nexttokenhash = hashof(token);
1426
+ const role = body.role === "extension" || body.role === "site" ? body.role : touched.role;
1427
+ const reply = relayframeof({
1428
+ op: "sessionjoin",
1429
+ opid: envelope.opid,
1430
+ sessionid: session2.id,
1431
+ token,
1432
+ at: input.now,
1433
+ body: { sessionid: session2.id, token, capabilities: contractcapabilities(), rotated: true }
1434
+ });
1435
+ return {
1436
+ state: {
1437
+ ...base,
1438
+ sessions: base.sessions.map(
1439
+ (entry) => entry.id === session2.id ? {
1440
+ ...entry,
1441
+ tokenhashes: [...entry.tokenhashes, nexttokenhash],
1442
+ revoked: [...entry.revoked, tokenhash2],
1443
+ ...role === "extension" ? { extension: touched.id } : role === "site" ? { site: touched.id } : {}
1444
+ } : entry
1445
+ ),
1446
+ connections: base.connections.map(
1447
+ (entry) => entry.id === touched.id ? { ...entry, role: role === "" ? entry.role : role, sessionid: session2.id, tokenhash: nexttokenhash } : entry
1448
+ ),
1449
+ tokens: [
1450
+ ...base.tokens.filter((record) => record.connectionid !== touched.id),
1451
+ { connectionid: touched.id, token }
1452
+ ]
1453
+ },
1454
+ replies: [reply],
1455
+ routed: []
1456
+ };
1457
+ }
1458
+ const session = base.sessions.find((entry) => entry.id === envelope.sessionid);
1459
+ const tokenhash = typeof envelope.token === "string" ? hashof(envelope.token) : "";
1460
+ if (session === void 0 || tokenhash === "" || !relaylivetokens(session).includes(tokenhash)) {
1461
+ return {
1462
+ state: base,
1463
+ replies: [
1464
+ relayframeof({
1465
+ op: envelope.op,
1466
+ opid: envelope.opid,
1467
+ at: input.now,
1468
+ body: { error: "The frame failed the token authentication of its session." }
1469
+ })
1470
+ ],
1471
+ routed: []
1472
+ };
1473
+ }
1474
+ if (envelope.op === "eventstream") {
1475
+ const streams = Array.isArray(envelope.body?.streams) ? envelope.body?.streams : [];
1476
+ const reply = relayframeof({
1477
+ op: "eventstream",
1478
+ opid: envelope.opid,
1479
+ sessionid: session.id,
1480
+ ...envelope.token !== void 0 ? { token: envelope.token } : {},
1481
+ at: input.now,
1482
+ body: { streams, subscribed: true }
1483
+ });
1484
+ return { state: base, replies: [reply], routed: [] };
1485
+ }
1486
+ if (envelope.op === "eventpost") {
1487
+ const kind = typeof envelope.body?.kind === "string" ? envelope.body.kind : "";
1488
+ const stream = typeof envelope.body?.stream === "string" ? envelope.body.stream : "";
1489
+ const event = { opid: envelope.opid, kind, stream, at: input.now };
1490
+ const routed = [session.extension, session.site].filter((id) => id !== void 0 && id !== touched.id).map((memberid) => {
1491
+ const membertoken = base.tokens.find((record) => record.connectionid === memberid)?.token ?? "";
1492
+ return {
1493
+ connectionid: memberid,
1494
+ frame: relayframeof({
1495
+ op: "eventpost",
1496
+ opid: envelope.opid,
1497
+ sessionid: session.id,
1498
+ token: membertoken,
1499
+ at: input.now,
1500
+ body: envelope.body ?? {}
1501
+ })
1502
+ };
1503
+ });
1504
+ const reply = relayframeof({
1505
+ op: "eventpost",
1506
+ opid: envelope.opid,
1507
+ sessionid: session.id,
1508
+ ...envelope.token !== void 0 ? { token: envelope.token } : {},
1509
+ at: input.now,
1510
+ body: { accepted: true }
1511
+ });
1512
+ return {
1513
+ state: {
1514
+ ...base,
1515
+ sessions: base.sessions.map(
1516
+ (entry) => entry.id === session.id ? { ...entry, events: [...entry.events, event] } : entry
1517
+ )
1518
+ },
1519
+ replies: [reply],
1520
+ routed
1521
+ };
1522
+ }
1523
+ return {
1524
+ state: base,
1525
+ replies: [
1526
+ relayframeof({
1527
+ op: envelope.op,
1528
+ opid: envelope.opid,
1529
+ at: input.now,
1530
+ body: { error: "The operation sits outside the servercontract." }
1531
+ })
1532
+ ],
1533
+ routed: []
1534
+ };
1535
+ }
1536
+ function relayidleconnections(state, now, idlewindow) {
1537
+ if (idlewindow === void 0 || !Number.isFinite(idlewindow) || idlewindow <= 0) return [];
1538
+ return state.connections.filter((connection) => now - connection.lastframeat >= idlewindow).map((connection) => connection.id);
1539
+ }
1540
+ function relaypendingpairings(state, now) {
1541
+ return state.pairings.filter((pairing) => !pairing.used && now < pairing.expiresat).map((pairing) => pairing.code);
1542
+ }
1543
+ function splitlines(buffer) {
1544
+ if (!buffer.includes("\n")) return { lines: [], rest: buffer };
1545
+ const parts = buffer.split("\n");
1546
+ const rest = parts.pop() ?? "";
1547
+ const lines = parts.map((line) => line.trim()).filter((line) => line !== "");
1548
+ return { lines, rest };
1549
+ }
1550
+ function stdiotransport(now) {
1551
+ return { kind: "stdio", endpoint: "stdio://devthink", startedat: now, received: 0, sent: 0 };
1552
+ }
1553
+ function createlinepump(input) {
1554
+ let buffer = "";
1555
+ let record = stdiotransport(input.now);
1556
+ const feed = async (chunk) => {
1557
+ buffer = `${buffer}${chunk}`;
1558
+ for (; ; ) {
1559
+ const newline = buffer.indexOf("\n");
1560
+ if (newline < 0) return;
1561
+ const line = buffer.slice(0, newline).trim();
1562
+ buffer = buffer.slice(newline + 1);
1563
+ if (line === "") continue;
1564
+ record = { ...record, received: record.received + 1, lastframeat: input.now };
1565
+ const decoded = decodemessage(line);
1566
+ if (decoded.error !== void 0) {
1567
+ input.write(`${JSON.stringify({ jsonrpc: "2.0", id: null, error: decoded.error })}
1568
+ `);
1569
+ record = { ...record, sent: record.sent + 1 };
1570
+ continue;
1571
+ }
1572
+ const frames = framesof(decoded.message);
1573
+ const answers = [];
1574
+ for (const frame of frames) {
1575
+ if (isnotification(frame)) continue;
1576
+ try {
1577
+ const answer = await input.handle(frame);
1578
+ if (answer !== void 0) answers.push(answer);
1579
+ } catch (error) {
1580
+ answers.push({
1581
+ jsonrpc: "2.0",
1582
+ id: frame.id ?? null,
1583
+ error: { code: "internal", message: error instanceof Error ? error.message : String(error) }
1584
+ });
1585
+ }
1586
+ }
1587
+ for (const answer of answers) {
1588
+ input.write(`${encodemessage(answer)}
1589
+ `);
1590
+ record = { ...record, sent: record.sent + 1 };
1591
+ }
1592
+ }
1593
+ };
1594
+ return {
1595
+ feed,
1596
+ record: () => record,
1597
+ close: (now) => {
1598
+ record = { ...record, closedat: now };
1599
+ return record;
1600
+ }
1601
+ };
1602
+ }
1603
+ async function subevents(input) {
1604
+ const now = input.now ?? Date.now;
1605
+ let current = { ...input.record, state: "open" };
1606
+ const events = [];
1607
+ let buffer = "";
1608
+ let error;
1609
+ const lifetimeelapsed = () => current.lifetime !== void 0 && now() - current.openedat >= current.lifetime;
1610
+ try {
1611
+ const opened = await input.open(current.url, sserequestheaders(current));
1612
+ if (!opened.ok) {
1613
+ return {
1614
+ record: {
1615
+ ...current,
1616
+ state: "failed",
1617
+ closedat: now(),
1618
+ ...opened.error !== void 0 ? { error: opened.error } : {}
1619
+ },
1620
+ events,
1621
+ error: opened.error ?? `The event stream channel refused the subscription with status ${opened.status}.`
1622
+ };
1623
+ }
1624
+ for (; ; ) {
1625
+ if (input.cancelled?.() === true) break;
1626
+ if (lifetimeelapsed()) break;
1627
+ const chunk = await opened.read();
1628
+ if (chunk.done) break;
1629
+ buffer += chunk.text ?? "";
1630
+ const parsed = parsessetext(buffer);
1631
+ buffer = parsed.rest;
1632
+ for (const event of parsed.events) {
1633
+ const names = event.event !== void 0 && !current.names.includes(event.event) ? [...current.names, event.event] : current.names;
1634
+ current = {
1635
+ ...current,
1636
+ events: current.events + 1,
1637
+ names,
1638
+ ...event.id !== void 0 ? { lasteventid: event.id } : {}
1639
+ };
1640
+ events.push(event);
1641
+ }
1642
+ }
1643
+ } catch (failure) {
1644
+ if (input.cancelled?.() !== true && !lifetimeelapsed())
1645
+ error = failure instanceof Error ? failure.message : String(failure);
1646
+ }
1647
+ const state = error !== void 0 ? "failed" : "closed";
1648
+ const closed = { ...current, state, closedat: now() };
1649
+ return { record: closed, events, ...error !== void 0 ? { error } : {} };
1650
+ }
1651
+ function longpollrequestof(value) {
1652
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1653
+ const entry = value;
1654
+ if (typeof entry.url !== "string" || !entry.url.trim()) return void 0;
1655
+ const request = { url: entry.url.trim() };
1656
+ if (typeof entry.timeout === "number" && Number.isFinite(entry.timeout) && entry.timeout > 0)
1657
+ request.timeout = entry.timeout;
1658
+ if (typeof entry.cursor === "string" && entry.cursor.trim()) request.cursor = entry.cursor.trim();
1659
+ return request;
1660
+ }
1661
+ async function longpoll(input) {
1662
+ const now = input.now ?? Date.now;
1663
+ const sleep = input.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, Math.max(0, milliseconds))));
1664
+ const exchanges = [];
1665
+ let polls = 0;
1666
+ let retries = 0;
1667
+ let reason = "The long poll loop stopped.";
1668
+ let cursorvalue = input.request.cursor;
1669
+ let next = pollurl(input.cursor, cursorvalue);
1670
+ let error;
1671
+ for (; ; ) {
1672
+ if (input.cancelled?.() === true) {
1673
+ reason = "The long poll loop was cancelled.";
1674
+ break;
1675
+ }
1676
+ if (input.expiresat !== void 0 && now() >= input.expiresat) {
1677
+ reason = "The long poll loop stopped at the reviewed plan expiry.";
1678
+ break;
1679
+ }
1680
+ let response;
1681
+ try {
1682
+ response = await input.fetchpoll(next.url, next.body);
1683
+ } catch (failure) {
1684
+ if (input.cancelled?.() === true) {
1685
+ reason = "The long poll loop was cancelled.";
1686
+ break;
1687
+ }
1688
+ error = failure instanceof Error ? failure.message : String(failure);
1689
+ reason = `The long poll request failed: ${error}`;
1690
+ break;
1691
+ }
1692
+ if (response.timeout === true && input.request.timeout !== void 0) {
1693
+ retries += 1;
1694
+ exchanges.push({ url: next.url, status: response.status, body: response.body, timeout: true });
1695
+ if (input.backoff !== void 0 && input.backoff > 0) await sleep(input.backoff);
1696
+ continue;
1697
+ }
1698
+ polls += 1;
1699
+ exchanges.push({ url: next.url, status: response.status, body: response.body, timeout: false });
1700
+ let parsed;
1701
+ try {
1702
+ parsed = JSON.parse(response.body);
1703
+ } catch {
1704
+ parsed = void 0;
1705
+ }
1706
+ const decision = polldecision({
1707
+ cursor: input.cursor,
1708
+ polls: polls - 1,
1709
+ response: parsed,
1710
+ cancelled: () => input.cancelled?.() === true,
1711
+ ...input.expiresat !== void 0 ? { expiresat: input.expiresat } : {},
1712
+ now: now()
1713
+ });
1714
+ if (!decision.continue) {
1715
+ reason = decision.reason;
1716
+ break;
1717
+ }
1718
+ cursorvalue = decision.cursor;
1719
+ const following = decision.next ?? { url: next.url, wait: input.cursor.interval };
1720
+ await sleep(following.wait);
1721
+ next = { url: following.url, ...following.body !== void 0 ? { body: following.body } : {} };
1722
+ }
1723
+ return {
1724
+ polls,
1725
+ retries,
1726
+ reason,
1727
+ ...cursorvalue !== void 0 ? { cursor: cursorvalue } : {},
1728
+ exchanges,
1729
+ ...error !== void 0 ? { error } : {}
1730
+ };
1731
+ }
1732
+ function graphqlsubscriptionof(value) {
1733
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1734
+ const entry = value;
1735
+ if (typeof entry.query !== "string" || !entry.query.trim()) return void 0;
1736
+ if (typeof entry.channel !== "string" || !entry.channel.trim()) return void 0;
1737
+ const variables = {};
1738
+ if (entry.variables !== void 0) {
1739
+ if (!entry.variables || typeof entry.variables !== "object" || Array.isArray(entry.variables)) return void 0;
1740
+ for (const [name, item] of Object.entries(entry.variables)) {
1741
+ if (typeof item !== "string") return void 0;
1742
+ variables[name] = item;
1743
+ }
1744
+ }
1745
+ return {
1746
+ query: entry.query.trim(),
1747
+ ...Object.keys(variables).length > 0 ? { variables } : {},
1748
+ channel: entry.channel.trim()
1749
+ };
1750
+ }
1751
+ function parsegraphqlmessage(payload) {
1752
+ let parsed;
1753
+ try {
1754
+ parsed = JSON.parse(payload);
1755
+ } catch {
1756
+ return { kind: "error", errors: ["The graphql subscription message does not parse as json."] };
1757
+ }
1758
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1759
+ return { kind: "error", errors: ["The graphql subscription message is not an object."] };
1760
+ const entry = parsed;
1761
+ const id = typeof entry.id === "string" && entry.id.trim() !== "" ? entry.id.trim() : void 0;
1762
+ if (entry.type === "complete" || entry.type === "stop")
1763
+ return { kind: "complete", ...id !== void 0 ? { id } : {} };
1764
+ if (entry.type === "error") {
1765
+ const raw = entry.payload;
1766
+ const messages = Array.isArray(raw) ? raw.map(
1767
+ (item) => item instanceof Error ? item.message : typeof item === "object" && item !== null && "message" in item ? String(item.message) : String(item)
1768
+ ) : raw !== void 0 ? [String(raw)] : ["The graphql subscription reported an error without a message."];
1769
+ return { kind: "error", ...id !== void 0 ? { id } : {}, errors: messages };
1770
+ }
1771
+ if (entry.type === "next" || entry.type === "data")
1772
+ return { kind: "next", ...id !== void 0 ? { id } : {}, payload: entry.payload };
1773
+ return {
1774
+ kind: "error",
1775
+ errors: [`The graphql subscription message carries the unknown type ${String(entry.type)}.`]
1776
+ };
1777
+ }
1778
+ function graphqlsubscribeframe(subscription, operationid) {
1779
+ return JSON.stringify({
1780
+ id: operationid,
1781
+ type: "subscribe",
1782
+ payload: {
1783
+ query: subscription.query,
1784
+ ...subscription.variables !== void 0 ? { variables: subscription.variables } : {}
1785
+ }
1786
+ });
1787
+ }
1788
+ function graphqlsub(input) {
1789
+ const results = [];
1790
+ const errors = [];
1791
+ let completed = false;
1792
+ for (const message of input.messages) {
1793
+ const parsed = parsegraphqlmessage(message);
1794
+ if (parsed.kind === "next")
1795
+ results.push({ ...parsed.id !== void 0 ? { id: parsed.id } : {}, data: parsed.payload });
1796
+ if (parsed.kind === "error") errors.push(...parsed.errors ?? ["The graphql subscription reported an error."]);
1797
+ if (parsed.kind === "complete") completed = true;
1798
+ }
1799
+ return { results, errors, completed };
1800
+ }
1801
+ function granted(url, grants) {
1802
+ let origin = "";
1803
+ try {
1804
+ origin = new URL(url).origin;
1805
+ } catch {
1806
+ return false;
1807
+ }
1808
+ return grants.some((pattern) => {
1809
+ try {
1810
+ return origin === new URL(pattern).origin;
1811
+ } catch {
1812
+ return false;
1813
+ }
1814
+ });
1815
+ }
1816
+ function formpost(input) {
1817
+ if (!granted(input.payload.url, input.grants))
1818
+ return {
1819
+ ok: false,
1820
+ refusal: `The form post to ${input.payload.url} targets an origin outside the session grants; the transport never widens the grants.`
1821
+ };
1822
+ return {
1823
+ ok: true,
1824
+ url: input.payload.url,
1825
+ method: "POST",
1826
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1827
+ body: urlencodeform(input.payload.fields)
1828
+ };
1829
+ }
1830
+ function multipartfieldheader(field) {
1831
+ return `--BOUNDARY\r
1832
+ content-disposition: form-data; name="${field.name}"; filename="${field.filename}"\r
1833
+ content-type: ${field.contenttype}\r
1834
+ \r
1835
+ `;
1836
+ }
1837
+ function multipartpost(input) {
1838
+ if (!granted(input.payload.url, input.grants))
1839
+ return {
1840
+ ok: false,
1841
+ refusal: `The multipart upload to ${input.payload.url} targets an origin outside the session grants; the transport never widens the grants.`
1842
+ };
1843
+ if (input.payload.files.some((file) => file.reviewed !== true))
1844
+ return {
1845
+ ok: false,
1846
+ refusal: "Every file of a multipart upload carries its explicit reviewed flag before the payload encodes."
1847
+ };
1848
+ const boundary = input.payload.boundary ?? `----devthink${Math.random().toString(16).slice(2)}${Date.now().toString(16)}`;
1849
+ const chunks = [];
1850
+ for (const field of input.payload.fields)
1851
+ chunks.push(`--${boundary}\r
1852
+ content-disposition: form-data; name="${field.name}"\r
1853
+ \r
1854
+ ${field.value}\r
1855
+ `);
1856
+ for (const file of input.payload.files)
1857
+ chunks.push(
1858
+ multipartfieldheader({ name: file.name, filename: file.filename, contenttype: file.mime }).replaceAll(
1859
+ "BOUNDARY",
1860
+ boundary
1861
+ ) + `${file.content}\r
1862
+ `
1863
+ );
1864
+ chunks.push(`--${boundary}--\r
1865
+ `);
1866
+ const bytes = chunks.reduce((total, chunk) => total + chunk.length, 0);
1867
+ let sent = 0;
1868
+ for (const [index, chunk] of chunks.entries()) {
1869
+ sent += chunk.length;
1870
+ input.onprogress?.({ chunk: index + 1, chunks: chunks.length, sent, total: bytes });
1871
+ }
1872
+ return {
1873
+ ok: true,
1874
+ url: input.payload.url,
1875
+ method: "POST",
1876
+ headers: { "content-type": `multipart/form-data; boundary=${boundary}` },
1877
+ chunks,
1878
+ boundary,
1879
+ bytes
1880
+ };
1881
+ }
1882
+ function correlateids(input) {
1883
+ let origin = "";
1884
+ try {
1885
+ origin = new URL(input.url).origin;
1886
+ } catch {
1887
+ origin = "";
1888
+ }
1889
+ const index = input.context.requests.length + 1;
1890
+ const requestid = `req-${index}`;
1891
+ const request = {
1892
+ requestid,
1893
+ correlationid: `${input.context.runid}-${index}`,
1894
+ stepid: input.stepid,
1895
+ url: input.url,
1896
+ origin,
1897
+ method: input.method,
1898
+ at: input.now
1899
+ };
1900
+ return { context: { runid: input.context.runid, requests: [...input.context.requests, request] }, requestid };
1901
+ }
1902
+ function joincorrelation(input) {
1903
+ const request = input.context.requests.find((entry) => entry.requestid === input.requestid);
1904
+ if (!request)
1905
+ throw new Error(
1906
+ `The correlation map of the run carries no request ${input.requestid}; the response joins only its own request.`
1907
+ );
1908
+ const joined = {
1909
+ ...request,
1910
+ ...input.responseid !== void 0 ? { responseid: input.responseid } : {},
1911
+ status: input.status
1912
+ };
1913
+ return {
1914
+ runid: input.context.runid,
1915
+ requests: input.context.requests.map((entry) => entry.requestid === input.requestid ? joined : entry)
1916
+ };
1917
+ }
1918
+ function correlationexport(context) {
1919
+ const map = context.requests.map((request) => ({
1920
+ requestid: request.requestid,
1921
+ correlationid: request.correlationid,
1922
+ stepid: request.stepid,
1923
+ url: request.url,
1924
+ origin: request.origin,
1925
+ method: request.method,
1926
+ paired: request.responseid !== void 0,
1927
+ ...request.status !== void 0 ? { status: request.status } : {},
1928
+ at: request.at
1929
+ }));
1930
+ return { runid: context.runid, requests: map.length, pairs: map.filter((entry) => entry.paired).length, map };
1931
+ }
1932
+ function ratelimitdirectiveof(headers, origin, status, now) {
1933
+ const pick = (name) => {
1934
+ for (const key of Object.keys(headers)) {
1935
+ if (key.toLowerCase() !== name) continue;
1936
+ const value = Number(headers[key]);
1937
+ if (Number.isFinite(value) && value >= 0) return value;
1938
+ }
1939
+ return void 0;
1940
+ };
1941
+ const remaining = pick("x-ratelimit-remaining");
1942
+ const reset = pick("x-ratelimit-reset");
1943
+ const retryafter = retryafterof(status, headers);
1944
+ if (remaining === void 0 && reset === void 0 && retryafter === void 0) return void 0;
1945
+ let resetat = now;
1946
+ if (reset !== void 0) resetat = reset > Math.floor(now / 1e3) ? reset * 1e3 : now + reset * 1e3;
1947
+ if (retryafter !== void 0) resetat = Math.max(resetat, now + retryafter);
1948
+ return {
1949
+ origin,
1950
+ scope: origin,
1951
+ ...remaining !== void 0 ? { remaining } : {},
1952
+ resetat,
1953
+ ...retryafter !== void 0 ? { retryafter } : {},
1954
+ at: now
1955
+ };
1956
+ }
1957
+ function ratelimitwaitof(directives, origin, now) {
1958
+ const scoped = directives.filter((directive) => directive.origin === origin);
1959
+ let newest;
1960
+ for (const directive of scoped) if (newest === void 0 || directive.at > newest.at) newest = directive;
1961
+ if (newest === void 0) return { waitms: 0 };
1962
+ return { waitms: Math.max(0, newest.resetat - now), ...newest !== void 0 ? { directive: newest } : {} };
1963
+ }
1964
+ async function ratelimitrespect(input) {
1965
+ const now = input.now ?? Date.now;
1966
+ const sleep = input.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, Math.max(0, milliseconds))));
1967
+ const resolved = ratelimitwaitof(input.directives, input.origin, now());
1968
+ if (resolved.waitms > 0) await sleep(resolved.waitms);
1969
+ return resolved;
1970
+ }
1971
+ function bodyhashof(body) {
1972
+ let hash = 5381;
1973
+ for (let index = 0; index < body.length; index += 1) hash = (hash * 33 ^ body.charCodeAt(index)) & 2147483647;
1974
+ return hash.toString(36);
1975
+ }
1976
+ function cachekeyof(input) {
1977
+ return `${input.runid}:${input.method}:${input.url}:${bodyhashof(input.body)}`;
1978
+ }
1979
+ function cacheexpiryof(headers, now, retention) {
1980
+ let candidates = [];
1981
+ for (const key of Object.keys(headers)) {
1982
+ const lowered = key.toLowerCase();
1983
+ const value = headers[key];
1984
+ if (lowered === "cache-control") {
1985
+ const match = /max-age\s*=\s*(\d+)/i.exec(value ?? "");
1986
+ if (match !== null) candidates.push(now + Number.parseInt(match[1] ?? "0", 10) * 1e3);
1987
+ }
1988
+ if (lowered === "expires") {
1989
+ const date = Date.parse(value ?? "");
1990
+ if (Number.isFinite(date)) candidates.push(date);
1991
+ }
1992
+ }
1993
+ if (retention !== void 0 && Number.isFinite(retention) && retention > 0) candidates.push(now + retention);
1994
+ const valid = candidates.filter((candidate) => Number.isFinite(candidate) && candidate > now);
1995
+ return valid.length > 0 ? Math.min(...valid) : void 0;
1996
+ }
1997
+ function readmethod(method) {
1998
+ const upper = method.toUpperCase();
1999
+ return upper === "GET" || upper === "HEAD";
2000
+ }
2001
+ function cacheresponse(input) {
2002
+ if (!readmethod(input.method))
2003
+ return {
2004
+ entries: input.entries,
2005
+ refusal: `The ${input.method} response of ${input.url} follows a mutation verb and never caches.`
2006
+ };
2007
+ if (input.credentials === true)
2008
+ return {
2009
+ entries: input.entries,
2010
+ refusal: `The response of ${input.url} carries credentials and the cache refuses it.`
2011
+ };
2012
+ if (input.mutatedat !== void 0 && input.mutatedat > 0) {
2013
+ return {
2014
+ entries: input.entries.filter((entry2) => !(entry2.runid === input.runid && sameorigin(entry2, input.url))),
2015
+ refusal: `A mutation landed on the origin of ${input.url}; the responses that follow a mutation never cache and the invalidated entries drop.`
2016
+ };
2017
+ }
2018
+ const key = cachekeyof({ runid: input.runid, url: input.url, method: input.method, body: input.body });
2019
+ const expiry = cacheexpiryof(input.headers, input.now, input.retention);
2020
+ const entry = {
2021
+ key,
2022
+ runid: input.runid,
2023
+ url: input.url,
2024
+ method: input.method.toUpperCase(),
2025
+ body: input.body,
2026
+ headers: input.headers,
2027
+ status: input.status,
2028
+ ...expiry !== void 0 ? { expiry } : {},
2029
+ hits: 0,
2030
+ at: input.now
2031
+ };
2032
+ const entries = [entry, ...input.entries.filter((candidate) => candidate.key !== key)];
2033
+ return { entries, entry };
2034
+ }
2035
+ function cacheserv(input) {
2036
+ if (!readmethod(input.method)) return { entries: input.entries };
2037
+ const key = cachekeyof({ runid: input.runid, url: input.url, method: input.method, body: input.body });
2038
+ const found = input.entries.find((entry) => entry.key === key);
2039
+ if (found === void 0) return { entries: input.entries };
2040
+ if (input.mutatedat !== void 0 && found.at < input.mutatedat) {
2041
+ return { entries: input.entries.filter((entry) => entry.key !== key), expired: found };
2042
+ }
2043
+ if (found.expiry !== void 0 && input.now >= found.expiry) {
2044
+ return { entries: input.entries.filter((entry) => entry.key !== key), expired: found };
2045
+ }
2046
+ const served = { ...found, hits: found.hits + 1 };
2047
+ return { entries: input.entries.map((entry) => entry.key === key ? served : entry), entry: served };
2048
+ }
2049
+ function cachecleanup(entries, now) {
2050
+ const kept = [];
2051
+ const expired = [];
2052
+ for (const entry of entries) {
2053
+ if (entry.expiry !== void 0 && now >= entry.expiry) expired.push(entry);
2054
+ else kept.push(entry);
2055
+ }
2056
+ return { kept, expired };
2057
+ }
2058
+ function apicallrecordof(input) {
2059
+ let origin = "";
2060
+ let endpoint = "";
2061
+ try {
2062
+ const parsed = new URL(input.url);
2063
+ origin = parsed.origin;
2064
+ endpoint = `${parsed.pathname}${parsed.search}`;
2065
+ } catch {
2066
+ origin = "";
2067
+ endpoint = input.url;
2068
+ }
2069
+ return {
2070
+ id: input.id,
2071
+ runid: input.runid,
2072
+ stepid: input.stepid,
2073
+ url: input.url,
2074
+ origin,
2075
+ endpoint,
2076
+ method: input.method,
2077
+ status: input.status,
2078
+ ...input.mime !== void 0 && input.mime !== "" ? { mime: input.mime } : {},
2079
+ at: input.at
2080
+ };
2081
+ }
2082
+ function sameorigin(entry, url) {
2083
+ try {
2084
+ return new URL(entry.url).origin === new URL(url).origin;
2085
+ } catch {
2086
+ return false;
2087
+ }
2088
+ }
2089
+ export {
2090
+ apicallrecordof,
2091
+ bodyhashof,
2092
+ cachecleanup,
2093
+ cacheexpiryof,
2094
+ cachekeyof,
2095
+ cacheresponse,
2096
+ cacheserv,
2097
+ callgraphql,
2098
+ callrest,
2099
+ channellive,
2100
+ closeidlechannels,
2101
+ correlateids,
2102
+ correlationexport,
2103
+ createlinepump,
2104
+ defaultheartbeatms,
2105
+ defaulthttpstream,
2106
+ defaultidlewindowms,
2107
+ documentedbind,
2108
+ enforcemaxclients,
2109
+ fetchoptionsof,
2110
+ fetchrequestof,
2111
+ formpost,
2112
+ graphqlopenvelope,
2113
+ graphqlrequestof,
2114
+ graphqlsub,
2115
+ graphqlsubscribeframe,
2116
+ graphqlsubscriptionof,
2117
+ heartbeat,
2118
+ htmlqueriesof,
2119
+ httpanswer,
2120
+ httpendpoint,
2121
+ httpframepipeline,
2122
+ httpkinds,
2123
+ joincorrelation,
2124
+ jsonpathrulesof,
2125
+ listremotestatus,
2126
+ longpoll,
2127
+ longpollrequestof,
2128
+ multipartfieldheader,
2129
+ multipartpost,
2130
+ newrelayserverstate,
2131
+ openstreamchannel,
2132
+ parsegraphqlmessage,
2133
+ parsehtmlbody,
2134
+ parsepost,
2135
+ payloadvalid,
2136
+ payloadwithdefaults,
2137
+ postauth,
2138
+ ratelimitdirectiveof,
2139
+ ratelimitrespect,
2140
+ ratelimitwaitof,
2141
+ readmethod,
2142
+ readpath,
2143
+ readstream,
2144
+ relayconnectionclose,
2145
+ relayconnectionopen,
2146
+ relayframeof,
2147
+ relayidleconnections,
2148
+ relaylivetokens,
2149
+ relaypendingpairings,
2150
+ relayserverframe,
2151
+ routepath,
2152
+ sendfetch,
2153
+ splitlines,
2154
+ sseframe,
2155
+ starttls,
2156
+ statusclassof,
2157
+ stdiotransport,
2158
+ streampathof,
2159
+ streamwindowof,
2160
+ subevents,
2161
+ templateurl,
2162
+ tlsdecision,
2163
+ unwrapgraphql
2164
+ };
2165
+ //# sourceMappingURL=http.js.map