@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
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.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/*! @johnhenry/wsh@0.50.0 (MIT): its browser client and in-memory host, bundled into one ES module by scripts/build-wsh-vendor.mjs. Do not edit. */
|
|
2
|
+
var Zl=Object.defineProperty;var ze=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var eu=(t,e)=>{for(var n in e)Zl(t,n,{get:e[n],enumerable:!0})};function Du(t,e=!1){return e?{h:Number(t&wr),l:Number(t>>Na&wr)}:{h:Number(t>>Na&wr)|0,l:Number(t&wr)|0}}function La(t,e=!1){let n=t.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){let{h:o,l:a}=Du(t[i],e);[r[i],s[i]]=[o,a]}return[r,s]}var wr,Na,ka=ze(()=>{wr=BigInt(4294967295),Na=BigInt(32)});function Ls(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Oe(t,e=""){if(typeof t!="number")throw new TypeError(mr(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(mr(e)+"expected integer >= 0, got "+t);return t}function Da(t,e=""){if(typeof t!="boolean")throw new TypeError(mr(e)+"expected boolean, got type="+typeof t);return t}function _e(t,e,n=""){if(Ls(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Oe(e,"length");let r=Ls(t),s=e!==void 0?` of length ${e}`:"",i=r?`length=${t.length}`:`type=${typeof t}`,o=mr(n)+"expected Uint8Array"+s+", got "+i;throw r?new RangeError(o):new TypeError(o)}function ks(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Pa(t,e){_e(t,void 0,"output");let n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function bn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ms(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Uu(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function vu(t){for(let e=0;e<t.length;e++)t[e]=Uu(t[e]);return t}function Ds(t,e,n="opts"){return Ma(t,"defaults"),e!==void 0&&Ma(e,n),Object.assign(Object.create(null),t,e)}function Ps(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Ds({},e,"info");let n=(s,i)=>t(i).update(s).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>t(s),Object.assign(n,e),Object.freeze(n)}function va(t=32){Oe(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var mr,Pu,Ma,Ua,Bt,An,gr=ze(()=>{mr=t=>t?`"${t}" `:"";Pu=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Ma=(t,e)=>{Pu(t,e);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};Ua=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Bt=Ua?t=>t:vu;An=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});function qu(t,e=24){if(!(t instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof t);if(t.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+t.length);if(Oe(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)Ht[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let o=(i+8)%10,a=(i+2)%10,c=Ht[a],l=Ht[a+1],h=Fa(c,l,1)^Ht[o],d=$a(c,l,1)^Ht[o+1];for(let w=0;w<50;w+=10)t[i+w]^=h,t[i+w+1]^=d}let r=t[2],s=t[3];for(let i=0;i<24;i++){let o=Ba[i],a=Fa(r,s,o),c=$a(r,s,o),l=Ka[i];r=t[l],s=t[l+1],t[l]=a,t[l+1]=c}for(let i=0;i<50;i+=10){let o=t[i],a=t[i+1],c=t[i+2],l=t[i+3];t[i]^=~t[i+2]&t[i+4],t[i+1]^=~t[i+3]&t[i+5],t[i+2]^=~t[i+4]&t[i+6],t[i+3]^=~t[i+5]&t[i+7],t[i+4]^=~t[i+6]&t[i+8],t[i+5]^=~t[i+7]&t[i+9],t[i+6]^=~t[i+8]&o,t[i+7]^=~t[i+9]&a,t[i+8]^=~o&c,t[i+9]^=~a&l}t[0]^=Gu[n],t[1]^=Wu[n]}Ms(Ht)}var Fu,Tn,$u,Ku,Bu,Hu,Ka,Ba,Ha,Ga,Gu,Wu,zu,ju,Vu,Yu,Fa,$a,Ht,_r,Wa,za,ja,Va,Ya,br,Us=ze(()=>{ka();gr();Fu=BigInt(0),Tn=BigInt(1),$u=BigInt(2),Ku=BigInt(7),Bu=BigInt(256),Hu=BigInt(113),Ka=[],Ba=[],Ha=[];for(let t=0,e=Tn,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ka.push(2*(5*r+n)),Ba.push((t+1)*(t+2)/2%64);let s=Fu;for(let i=0;i<7;i++)e=(e<<Tn^(e>>Ku)*Hu)%Bu,e&$u&&(s^=Tn<<(Tn<<BigInt(i))-Tn);Ha.push(s)}Ga=La(Ha,!0),Gu=Ga[0],Wu=Ga[1],zu=(t,e,n)=>t<<n|e>>>32-n,ju=(t,e,n)=>e<<n|t>>>32-n,Vu=(t,e,n)=>e<<n-32|t>>>64-n,Yu=(t,e,n)=>t<<n-32|e>>>64-n,Fa=(t,e,n)=>n>32?Vu(t,e,n):zu(t,e,n),$a=(t,e,n)=>n>32?Yu(t,e,n):ju(t,e,n),Ht=new Uint32Array(10);_r=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,n,r,s=!1,i=24){if(Oe(e,"blockLen"),Oe(n,"suffix"),Oe(i,"rounds"),Da(s,"enableXOF"),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.canXOF=s,this.rounds=i,Oe(r,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=bn(this.state)}clone(){return this._cloneInto()}keccak(){Bt(this.state32),qu(this.state32,this.rounds),Bt(this.state32),this.posOut=0,this.pos=0}update(e){ks(this),_e(e);let{blockLen:n,state:r,state32:s}=this,i=e.length,o=n%4===0&&e.byteOffset%4===0,a=n/4,c=o&&i>=n?bn(e):void 0;for(let l=0;l<i;){if(c!==void 0&&this.pos===0&&l%4===0&&i-l>=n){for(let d=0,w=l/4;d<a;d++)s[d]^=c[w+d];l+=n,this.pos=n,this.keccak();continue}let h=Math.min(n-this.pos,i-l);for(let d=0;d<h;d++)r[this.pos++]^=e[l++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,(n&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ks(this,!1),_e(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,i=e.length;s<i;){this.posOut>=r&&this.keccak();let o=Math.min(r-this.posOut,i-s);e.set(n.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return Oe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Pa(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,Ms(this.state)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||=new t(n,r,s,o,i),e.blockLen=n,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},Wa=(t,e,n,r={})=>Ps(()=>new _r(e,t,n),r),za=Wa(6,136,32,An(8)),ja=Wa(6,72,64,An(10)),Va=(t,e,n,r={})=>Ps((s={})=>(s=Ds({},s),new _r(e,t,s.dkLen===void 0?n:s.dkLen,!0)),r),Ya=Va(31,168,16,An(11)),br=Va(31,136,32,An(12))});function vs(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function qa(t,e={},n={},r="object"){vs(t,r),vs(e,"fields"),vs(n,"optFields");function s(o,a,c){let l=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,h=t[o];if(!Object.hasOwn(t,o)&&(c?h!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&h===void 0)return;let d=typeof h;if(d!==a||h===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let i=(o,a)=>Object.entries(o).forEach(([c,l])=>s(c,l,a));i(e,!1),i(n,!0)}var Xa=ze(()=>{});function xn(t,e="n"){if(typeof t!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof t}`);if(!Number.isSafeInteger(t)||t<0||t>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${t}`);return t}function Qa(t){return xn(t,"x"),(t&t-1)===0&&t!==0}function Fs(t,e){if(xn(t),typeof e!="number")throw new TypeError('"bits" expected number, got type='+typeof e);if(!Number.isSafeInteger(e)||e<0||e>32)throw new Error(`expected integer 0 <= bits <= 32, got ${e}`);let n=0;for(let r=0;r<e;r++,t>>>=1)n=n<<1|t&1;return n>>>0}function Za(t){return xn(t),31-Math.clz32(t)}function Ja(t){if(!t||typeof t!="object"||typeof t.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof t);let e=t.length;if(!Qa(e))throw new Error("expected positive power-of-two length, got "+e);let n=Za(e);for(let r=0;r<e;r++){let s=Fs(r,n);if(r<s){let i=t[r];t[r]=t[s],t[s]=i}}return t}var $s,ec=ze(()=>{Xa();$s=(t,e)=>{qa(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:n,roots:r,dit:s,invertButterflies:i=!1,skipStages:o=0,brp:a=!0}=e;xn(n,"coreOpts.N");let c=Za(n);if(!Qa(n))throw new Error("FFT: Polynomial size should be power of two");xn(o,"coreOpts.skipStages");let l=c===0?0:c-1;if(o>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(r.length!==n)throw new Error(`FFT: wrong roots length: expected ${n}, got ${r.length}`);let h=s!==i;return d=>{if(d.length!==n)throw new Error("FFT: wrong Polynomial length");s&&a&&Ja(d);for(let w=0,y=1;w<c-o;w++){let _=s?w+1+o:c-w,E=1<<_,g=E>>1,A=n>>_;for(let I=0;I<n;I+=E)for(let S=0,O=y++;S<g;S++){let N=i?s?n-O:O:S*A,D=I+S,x=I+S+g,m=r[N],L=d[x],G=d[D];if(h){let $=t.mul(L,m);d[D]=t.add(G,$),d[x]=t.sub(G,$)}else i?(d[D]=t.add(L,G),d[x]=t.mul(t.sub(L,G),m)):(d[D]=t.add(G,L),d[x]=t.mul(t.sub(G,L),m))}}return!s&&a&&Ja(d),d}}});function Xu(t,e,n=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let r=0;r<t.length;r++)n(t[r],`${e}[${r}]`);return t}function _t(t,e){if(t=_e(t),e=_e(e),t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Ks(t){return new Uint8Array(_e(t))}function Sn(t,...e){let n=s=>typeof s=="number"?s:s.bytesLen,r=e.reduce((s,i)=>s+n(i),0);return{bytesLen:r,encode:s=>{let i=new Uint8Array(r);for(let o=0,a=0;o<e.length;o++){let c=e[o],l=n(c),h=typeof c=="number"?s[o]:c.encode(s[o]);_e(h,l,t),i.set(h,a),typeof c!="number"&&h.fill(0),a+=l}return i},decode:s=>{_e(s,r,t);let i=[];for(let o of e){let a=n(o),c=s.subarray(0,a);i.push(typeof o=="number"?c:o.decode(c)),s=s.subarray(a)}return i}}}function Tr(t,e){let n=t,r=e*n.bytesLen;return{bytesLen:r,encode:s=>{let i=Xu(s,"u");if(i.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${i.length}. Expected: ${e}`);let o=new Uint8Array(r);for(let a=0,c=0;a<i.length;a++){let l=n.encode(i[a]);o.set(l,c),l.fill(0),c+=l.length}return o},decode:s=>{_e(s,r);let i=[];for(let o=0;o<s.length;o+=n.bytesLen)i.push(n.decode(s.subarray(o,o+n.bytesLen)));return i}}}function ne(...t){for(let e of t)if(Array.isArray(e))for(let n of e)n.fill(0);else e.fill(0)}function Rn(t){if(Oe(t,"bits"),t>32)throw new RangeError('"bits" expected <= 32, got '+t);return t===32?4294967295:~(-1<<t)>>>0}var be,Ar,Bs=ze(()=>{gr();be=_e,Ar=va});var tc,Ju,Hs,nc=ze(()=>{ec();Us();Bs();tc=t=>{let{newPoly:e,N:n,Q:r,F:s,ROOT_OF_UNITY:i,brvBits:o,isKyber:a}=t,c=(S,O=r)=>{let N=S%O|0;return(N>=0?N|0:O+N|0)|0},l=(S,O=r)=>{let N=c(S,O)|0;return(N>O>>1?N-O|0:N)|0};function h(){let S=e(n);for(let O=0;O<n;O++){let N=Fs(O,o),D=BigInt(i)**BigInt(N)%BigInt(r);S[O]=Number(D)|0}return S}let d=h(),w=S=>{throw new Error("not implemented")},y=a?{add:(S,O)=>{let N=S+O|0;return N>=r?N-r|0:N},sub:(S,O)=>{let N=S-O|0;return N<0?N+r|0:N},mul:(S,O)=>c((S|0)*(O|0))|0,inv:w}:{add:(S,O)=>c((S|0)+(O|0))|0,sub:(S,O)=>c((S|0)-(O|0))|0,mul:(S,O)=>c((S|0)*(O|0))|0,inv:w},_={N:n,roots:d,invertButterflies:!0,skipStages:a?1:0,brp:!1},E=$s(y,{dit:!1,..._}),g=$s(y,{dit:!0,..._}),A={encode:S=>E(S),decode:S=>{g(S);for(let O=0;O<S.length;O++)S[O]=c(s*S[O]);return S}};return{mod:c,smod:l,nttZetas:d,NTT:{encode:S=>A.encode(S),decode:S=>A.decode(S)},bitsCoder:(S,O)=>{for(let x=0,m=0;x<n;x++)m+=S,m>32&&Rn(m),m%=8;let N=Rn(S),D=S*(n/8);return{bytesLen:D,encode:x=>{let m=x,L=new Uint8Array(D);for(let G=0,$=0,ee=0,ie=0;G<m.length;G++)for($|=(O.encode(m[G])&N)<<ee,ee+=S;ee>=8;ee-=8,$>>=8)L[ie++]=$&255;return L},decode:x=>{let m=e(n);for(let L=0,G=0,$=0,ee=0;L<x.length;L++)for(G|=x[L]<<$,$+=8;$>=S;$-=S,G>>=S)m[ee++]=O.decode(G&N);return m}}}}},Ju=t=>(e,n)=>{n||(n=t.blockLen);let r=new Uint8Array(e.length+2);r.set(e);let s=e.length,i=new Uint8Array(n),o=t.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(l,h)=>(r[s+0]=l,r[s+1]=h,o.destroy(),o=t.create({}).update(r),a++,()=>(c++,o.xofInto(i))),clean:()=>{o.destroy(),ne(i,r)}}},Hs=Ju(Ya)});var sc={};eu(sc,{PARAMS:()=>Sr,__tests:()=>lh,ml_kem1024:()=>ch,ml_kem512:()=>oh,ml_kem768:()=>ah});function bt(t,e){let n=t,r=e;for(let s=0;s<ue;s++){let i=n[s]+r[s];n[s]=i>=le?i-le:i}}function eh(t,e){let n=t,r=e;for(let s=0;s<ue;s++){let i=n[s]-r[s];n[s]=i<0?i+le:i}}function th(t,e,n,r,s){let i=ce.mod(ce.mod(e*r)*s+t*n),o=ce.mod(t*r+e*n);return{c0:i,c1:o}}function In(t,e){let n=t,r=e;for(let s=0;s<ue/2;s++){let i=ce.nttZetas[64+(s>>1)];s&1&&(i=-i);let{c0:o,c1:a}=th(n[2*s+0],n[2*s+1],r[2*s+0],r[2*s+1],i);n[2*s+0]=o,n[2*s+1]=a}return n}function xr(t){let e=t,n=new Uint16Array(ue);for(let r=0;r<ue;){let s=e();if(s.length%3)throw new Error("SampleNTT: unaligned block");for(let i=0;r<ue&&i+3<=s.length;i+=3){let o=(s[i+0]>>0|s[i+1]<<8)&4095,a=(s[i+1]>>4|s[i+2]<<4)&4095;o<le&&(n[r++]=o),r<ue&&a<le&&(n[r++]=a)}}return n}function Cn(t,e,n,r){return rc(t(r*ue/4,e,n),r)}function rh(t){let e=t,n=nh(e),{HASH256:r,HASH512:s,KDF:i}=e,{secretCoder:o,lengths:a}=n,c=Sn("secretKey",a.secretKey,a.publicKey,32,32),l=32,h=64,d=(y,_)=>{let E=y.subarray(0,384*e.K),g=o.encode(o.decode(Ks(E))),A=_t(g,E);if(ne(g),!A)throw new Error(`ML-KEM.${_}: wrong publicKey modulus`)},w=Object.freeze({...a,seed:64,msg:l,msgRand:l,secretKey:c.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:w,keygen:y=>{let _=y===void 0,E=_?Ar(h):y,g,A;try{be(E,h,"seed");let I=n.keygen(E.subarray(0,32)),S=I.publicKey;g=I.secretKey,A=r(S);let O=c.encode([g,S,A,E.subarray(32)]);return{publicKey:S,secretKey:O}}finally{g!==void 0&&ne(g),A!==void 0&&ne(A),_&&ne(E)}},getPublicKey:y=>{let[_,E,g,A]=c.decode(y);return Uint8Array.from(E)},encapsulate:(y,_)=>{let E=_===void 0,g=E?Ar(l):_,A;try{return be(y,a.publicKey,"publicKey"),be(g,l,"message"),d(y,"encapsulate"),A=s.create().update(g).update(r(y)).digest(),{cipherText:n.encrypt(y,g,A.subarray(32,64)),sharedSecret:A.subarray(0,32)}}finally{A!==void 0&&ne(A.subarray(32)),E&&ne(g)}},decapsulate:(y,_)=>{be(_,c.bytesLen,"secretKey"),be(y,a.cipherText,"cipherText");let E=c.bytesLen-96,g=E+32,A=r(_.subarray(E/2,g));if(!_t(A,_.subarray(g,g+32)))throw new Error("invalid secretKey: hash check failed");let[I,S,O,N]=c.decode(_),D=n.decrypt(y,I),x=s.create().update(D).update(O).digest(),m=x.subarray(0,32),L=n.encrypt(S,D,x.subarray(32,64)),G=_t(y,L),$=i.create({dkLen:32}).update(N).update(y).digest();return ne(D,L,x.subarray(32),G?$:m),G?m:$},prepare:y=>{be(y,a.publicKey,"publicKey"),d(y,"prepare");let _=Ks(y),E=r(_),g=n.prepare(_);return Object.freeze({publicKey:_,encapsulate:A=>{let I=A===void 0,S=I?Ar(l):A,O;try{return be(S,l,"message"),O=s.create().update(S).update(E).digest(),{cipherText:g.encrypt(S,O.subarray(32,64)),sharedSecret:O.subarray(0,32)}}finally{O!==void 0&&ne(O.subarray(32)),I&&ne(S)}},decapsulate:(A,I)=>{be(I,c.bytesLen,"secretKey"),be(A,a.cipherText,"cipherText");let[S,O,N,D]=c.decode(I);if(!_t(O,_)||!_t(N,E))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let x=n.decrypt(A,S),m=s.create().update(x).update(E).digest(),L=m.subarray(0,32),G=g.encrypt(x,m.subarray(32,64)),$=_t(A,G),ee=i.create({dkLen:32}).update(D).update(A).digest();return ne(x,G,m.subarray(32),$?ee:L),$?L:ee},clean:g.clean})}})}function sh(t,e,n){return br.create({dkLen:t}).update(e).update(new Uint8Array([n])).digest()}var ue,le,Qu,Zu,ce,Sr,Gs,Ws,On,rc,nh,ih,zs,oh,ah,ch,lh,ic=ze(()=>{Us();gr();nc();Bs();ue=256,le=3329,Qu=3303,Zu=17,ce=tc({N:ue,Q:le,F:Qu,ROOT_OF_UNITY:Zu,newPoly:t=>new Uint16Array(t),brvBits:7,isKyber:!0}),Sr=Object.freeze({512:Object.freeze({N:ue,Q:le,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:ue,Q:le,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:ue,Q:le,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),Gs=t=>{if(t>=12)return{encode:n=>n,decode:n=>n>=le?n-le:n};let e=2**(t-1);return{encode:n=>((n<<t)+le/2)/le,decode:n=>n*le+e>>>t}},Ws=t=>ce.bitsCoder(t,t===12?{encode:e=>e,decode:e=>e>=le?e-le:e}:{encode:e=>e,decode:e=>e}),On=t=>t===12?Ws(12):ce.bitsCoder(t,Gs(t));rc=(t,e)=>{let n=new Uint16Array(ue),r=bn(t);Bt(r);let s=0;for(let i=0,o=0,a=0,c=0;i<r.length;i++){let l=r[i];for(let h=0;h<32;h++)a+=l&1,l>>=1,s+=1,s===e?(c=a,a=0):s===2*e&&(n[o++]=ce.mod(c-a),a=0,s=0)}if(Bt(r),s)throw new Error(`sampleCBD: leftover bits: ${s}`);return n};nh=t=>{let e=t,{K:n,PRF:r,XOF:s,HASH512:i,ETA1:o,ETA2:a,du:c,dv:l}=e,h=On(1),d=On(l),w=On(c),y=Sn("publicKey",Tr(On(12),n),32),_=Tr(On(12),n),E=Sn("ciphertext",Tr(w,n),d),g=Sn("seed",32,32),A=(I,S,O,N)=>{let D=[];for(let $=0;$<n;$++)D.push(ce.NTT.encode(Cn(r,N,$,o)));let x=new Uint16Array(ue),m=[];for(let $=0;$<n;$++){let ee=Cn(r,N,n+$,a),ie=new Uint16Array(ue);for(let Re=0;Re<n;Re++){let me=S($,Re);bt(ie,In(me,D[Re]))}bt(ee,ce.NTT.decode(ie)),m.push(ee),bt(x,In(I[$],D[$])),ne(ie)}let L=Cn(r,N,2*n,a);bt(L,ce.NTT.decode(x));let G=h.decode(O);return bt(G,L),ne(I,D,x,L),E.encode([m,G])};return{secretCoder:_,lengths:{secretKey:_.bytesLen,publicKey:y.bytesLen,cipherText:E.bytesLen},keygen:I=>{be(I,32,"seed");let S=new Uint8Array(33);S.set(I),S[32]=n;let O=i(S),[N,D]=g.decode(O),x=[],m=[];for(let $=0;$<n;$++)x.push(ce.NTT.encode(Cn(r,D,$,o)));let L=s(N);for(let $=0;$<n;$++){let ee=ce.NTT.encode(Cn(r,D,n+$,o));for(let ie=0;ie<n;ie++){let Re=xr(L.get(ie,$));bt(ee,In(Re,x[ie]))}m.push(ee)}L.clean();let G={publicKey:y.encode([m,N]),secretKey:_.encode(x)};return ne(N,D,x,m,S,O),G},encrypt:(I,S,O)=>{let[N,D]=y.decode(I),x=s(D),m=A(N,(L,G)=>xr(x.get(L,G)),S,O);return x.clean(),m},prepare:I=>{let[S,O]=y.decode(I),N=s(O),D=[];for(let x=0;x<n;x++)for(let m=0;m<n;m++)D.push(xr(N.get(x,m)));return N.clean(),{encrypt:(x,m)=>A(S.map(L=>L.slice()),(L,G)=>D[L*n+G].slice(),x,m),clean:()=>ne(S,D)}},decrypt:(I,S)=>{let[O,N]=E.decode(I),D=_.decode(S),x=new Uint16Array(ue);for(let L=0;L<n;L++)bt(x,In(D[L],ce.NTT.encode(O[L])));eh(N,ce.NTT.decode(x));let m=h.encode(N);return ne(x,D,O,N),m}}};ih={HASH256:za,HASH512:ja,KDF:br,XOF:Hs,PRF:sh},zs=t=>rh({...ih,...t}),oh=zs(Sr[512]),ah=zs(Sr[768]),ch=zs(Sr[1024]),lh=Object.freeze({Compress_d:(t,e)=>{if(e<1||e>11)throw new Error(`Compress_d: expected d in [1..11], got ${e}`);return Gs(e).encode(t)&Rn(e)},Decompress_d:(t,e)=>{if(e<1||e>11)throw new Error(`Decompress_d: expected d in [1..11], got ${e}`);return Gs(e).decode(t)},ByteEncode_d:(t,e)=>{if(e<1||e>12)throw new Error(`ByteEncode_d: expected d in [1..12], got ${e}`);return Ws(e).encode(t)},ByteDecode_d:(t,e)=>{if(e<1||e>12)throw new Error(`ByteDecode_d: expected d in [1..12], got ${e}`);return Ws(e).decode(t)},NTT:t=>ce.NTT.encode(Uint16Array.from(t)),NTT_inv:t=>ce.NTT.decode(Uint16Array.from(t)),MultiplyNTTs:(t,e)=>In(Uint16Array.from(t),Uint16Array.from(e)),SamplePolyCBD:(t,e)=>(be(t,64*e,"B"),rc(t,e)),SampleNTT:t=>{be(t,34,"B");let e=Hs(t.subarray(0,32));try{return xr(e.get(t[32],t[33]))}finally{e.clean()}}})});var tu=new TextEncoder,nu=new TextDecoder;function Ve(t){let e=[];return qn(t,e),Gi(e)}function qn(t,e){if(t==null){e.push(new Uint8Array([246]));return}if(t===!0){e.push(new Uint8Array([245]));return}if(t===!1){e.push(new Uint8Array([244]));return}if(typeof t=="number"){if(Number.isInteger(t)&&!Object.is(t,-0)&&t>=-Ki&&t<Ki)Number.isSafeInteger(t)?e.push(t>=0?ut(0,t):ut(1,-1-t)):e.push(t>=0?Bi(0,BigInt(t)):Bi(1,-1n-BigInt(t)));else{let n=new ArrayBuffer(9),r=new DataView(n);r.setUint8(0,251),r.setFloat64(1,t),e.push(new Uint8Array(n))}return}if(typeof t=="string"){let n=tu.encode(t);e.push(ut(3,n.length)),e.push(n);return}if(t instanceof Uint8Array){e.push(ut(2,t.length)),e.push(t);return}if(ArrayBuffer.isView(t)){let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);e.push(ut(2,n.length)),e.push(n);return}if(Array.isArray(t)){e.push(ut(4,t.length));for(let n of t)qn(n,e);return}if(typeof t=="object"){let n=Object.keys(t);e.push(ut(5,n.length));for(let r of n)qn(r,e),qn(t[r],e);return}throw new Error(`cborEncode: unsupported type ${typeof t}`)}var Ki=2**64;function Bi(t,e){let n=new ArrayBuffer(9),r=new DataView(n);return r.setUint8(0,t<<5|27),r.setBigUint64(1,e),new Uint8Array(n)}function ut(t,e){let n=t<<5;if(e<24)return new Uint8Array([n|e]);if(e<256)return new Uint8Array([n|24,e]);if(e<65536){let i=new Uint8Array(3);return i[0]=n|25,i[1]=e>>8&255,i[2]=e&255,i}if(e<4294967296){let i=new Uint8Array(5);return i[0]=n|26,i[1]=e>>24&255,i[2]=e>>16&255,i[3]=e>>8&255,i[4]=e&255,i}let r=new ArrayBuffer(9),s=new DataView(r);return s.setUint8(0,n|27),s.setUint32(1,Math.floor(e/4294967296)),s.setUint32(5,e>>>0),new Uint8Array(r)}function dt(t){return Ne({data:t,offset:0})}function Ne(t){if(t.offset>=t.data.length)throw new Error("cborDecode: unexpected end");let e=t.data[t.offset++],n=e>>5,r=e&31;switch(n){case 0:return ht(t,r);case 1:{if(r===27){let s=new DataView(t.data.buffer,t.data.byteOffset+t.offset,8);return t.offset+=8,Number(-1n-s.getBigUint64(0))}return-1-ht(t,r)}case 2:{if(r===31)return ru(t);let s=ht(t,r),i=t.data.slice(t.offset,t.offset+s);return t.offset+=s,i}case 3:{if(r===31)return su(t);let s=ht(t,r),i=nu.decode(t.data.subarray(t.offset,t.offset+s));return t.offset+=s,i}case 4:{if(r===31)return iu(t);let s=ht(t,r),i=new Array(s);for(let o=0;o<s;o++)i[o]=Ne(t);return i}case 5:{if(r===31)return ou(t);let s=ht(t,r),i={};for(let o=0;o<s;o++){let a=Ne(t);Hi(i,a,Ne(t))}return i}case 6:return ht(t,r),Ne(t);case 7:{if(r===20)return!1;if(r===21)return!0;if(r===22)return null;if(r===25){let s=t.data[t.offset]<<8|t.data[t.offset+1];return t.offset+=2,au(s)}if(r===26){let s=new DataView(t.data.buffer,t.data.byteOffset+t.offset,4);return t.offset+=4,s.getFloat32(0)}if(r===27){let s=new DataView(t.data.buffer,t.data.byteOffset+t.offset,8);return t.offset+=8,s.getFloat64(0)}return r===31?void 0:r}default:throw new Error(`cborDecode: unknown major type ${n}`)}}function ru(t){let e=[];for(;!Xn(t);){let n=Ne(t);if(!(n instanceof Uint8Array))throw new Error("cborDecode: invalid chunk in indefinite byte string");e.push(n)}return Gi(e)}function su(t){let e="";for(;!Xn(t);){let n=Ne(t);if(typeof n!="string")throw new Error("cborDecode: invalid chunk in indefinite text string");e+=n}return e}function iu(t){let e=[];for(;!Xn(t);)e.push(Ne(t));return e}function ou(t){let e={};for(;!Xn(t);){let n=Ne(t);Hi(e,n,Ne(t))}return e}function Hi(t,e,n){let r=typeof e=="string"?e:String(e);r==="__proto__"?Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0}):t[r]=n}function Xn(t){if(t.offset>=t.data.length)throw new Error("cborDecode: unexpected end in indefinite value");return t.data[t.offset]===255?(t.offset+=1,!0):!1}function ht(t,e){if(e<24)return e;if(e===24)return t.data[t.offset++];if(e===25){let n=t.data[t.offset]<<8|t.data[t.offset+1];return t.offset+=2,n}if(e===26){let n=new DataView(t.data.buffer,t.data.byteOffset+t.offset,4);return t.offset+=4,n.getUint32(0)}if(e===27){let n=new DataView(t.data.buffer,t.data.byteOffset+t.offset,8);t.offset+=8;let r=n.getUint32(0),s=n.getUint32(4);return r*4294967296+s}throw new Error(`cborDecode: invalid additional info ${e}`)}function au(t){let e=t>>15&1,n=t>>10&31,r=t&1023,s;return n===0?s=r===0?0:Math.pow(2,-14)*(r/1024):n===31?s=r===0?1/0:NaN:s=Math.pow(2,n-15)*(1+r/1024),e?-s:s}function Nt(t){let e=Ve(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length),n.set(e,4),n}var cu=16*1024*1024,ft=class extends Error{constructor(e,n){super(`Frame claims length ${e}, which exceeds the maximum of ${n} bytes`),this.name="FrameSizeError",this.len=e,this.maxFrameSize=n}},je=class{#e=new Uint8Array(0);#n;constructor({maxFrameSize:e=cu}={}){this.#n=e}feed(e){this.#e=lu(this.#e,e);let n=[];for(;this.#e.length>=4;){let s=new DataView(this.#e.buffer,this.#e.byteOffset,4).getUint32(0);if(s>this.#n)throw this.#e=new Uint8Array(0),new ft(s,this.#n);if(this.#e.length<4+s)break;let i=this.#e.slice(4,4+s);this.#e=this.#e.slice(4+s),n.push(dt(i))}return n}reset(){this.#e=new Uint8Array(0)}get pending(){return this.#e.length}};function Gi(t){let e=0;for(let s of t)e+=s.length;let n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.length;return n}function lu(t,e){if(t.length===0)return e;let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}var f=Object.freeze({HELLO:1,SERVER_HELLO:2,CHALLENGE:3,AUTH_METHODS:4,AUTH:5,AUTH_OK:6,AUTH_FAIL:7,OPEN:16,OPEN_OK:17,OPEN_FAIL:18,RESIZE:19,SIGNAL:20,EXIT:21,CLOSE:22,SESSION_DATA:23,ERROR:32,PING:33,PONG:34,ATTACH:48,RESUME:49,RENAME:50,IDLE_WARNING:51,SHUTDOWN:52,SNAPSHOT:53,PRESENCE:54,CONTROL_CHANGED:55,METRICS:56,CLIPBOARD:57,RECORDING_EXPORT:58,COMMAND_JOURNAL:59,METRICS_REQUEST:60,SUSPEND_SESSION:61,RESTART_PTY:62,SESSION_LIST_REQUEST:63,MCP_DISCOVER:64,MCP_TOOLS:65,MCP_CALL:66,MCP_RESULT:67,MCP_CANCEL:68,REVERSE_REGISTER:80,REVERSE_LIST:81,REVERSE_PEERS:82,REVERSE_CONNECT:83,REVERSE_ACCEPT:84,REVERSE_REJECT:85,RELAY_FORWARD:86,REVERSE_CLOSE:87,REVERSE_CHALLENGE:88,REVERSE_PROOF:89,SESSION_LIST:95,DETACH:96,DETACH_OK:97,DETACH_FAIL:98,OPEN_UNIX:99,OPEN_ENDPOINT:100,LISTEN_UNIX:101,OPEN_TCP:112,OPEN_UDP:113,RESOLVE_DNS:114,GATEWAY_OK:115,GATEWAY_FAIL:116,GATEWAY_CLOSE:117,INBOUND_OPEN:118,INBOUND_ACCEPT:119,INBOUND_REJECT:120,DNS_RESULT:121,LISTEN_REQUEST:122,LISTEN_OK:123,LISTEN_FAIL:124,LISTEN_CLOSE:125,GATEWAY_DATA:126,GATEWAY_CREDIT:127,GUEST_INVITE:128,GUEST_JOIN:129,GUEST_REVOKE:130,SHARE_SESSION:131,SHARE_REVOKE:132,COMPRESS_BEGIN:133,COMPRESS_ACK:134,RATE_CONTROL:135,RATE_WARNING:136,SESSION_LINK:137,SESSION_UNLINK:138,COPILOT_ATTACH:139,COPILOT_SUGGEST:140,COPILOT_DETACH:141,KEY_EXCHANGE:142,ENCRYPTED_FRAME:143,ECHO_ACK:144,ECHO_STATE:145,TERM_SYNC:146,TERM_DIFF:147,NODE_ANNOUNCE:148,NODE_REDIRECT:149,SESSION_GRANT:150,SESSION_REVOKE:151,FILE_OP:152,FILE_RESULT:153,FILE_CHUNK:154,POLICY_EVAL:155,POLICY_RESULT:156,POLICY_UPDATE:157,TERMINAL_CONFIG:158,AUTHORIZED_KEY_ADD:159,AUTHORIZED_KEY_RESULT:160,SHARE_OFFER:168,SHARE_REQUEST:169,SHARE_REPLY:170,LIST_TARGETS:171,TARGET_LIST:172}),yd=Object.freeze(Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]))),Ed=Object.freeze({PTY:"pty",EXEC:"exec",META:"meta",FILE:"file",TCP:"tcp",UDP:"udp",JOB:"job",RPC:"rpc"}),te=Object.freeze({PUBKEY:"pubkey",PASSWORD:"password"}),ss="wsh-v1";function is({username:t,features:e=[],authMethod:n=te.PUBKEY}={}){return{type:f.HELLO,version:ss,username:t,features:e,auth_method:n}}function Wi({sessionId:t,features:e=[],fingerprints:n=[],hostFingerprint:r}={}){let s={type:f.SERVER_HELLO,session_id:t,features:e,fingerprints:n};return r!==void 0&&(s.host_fingerprint=r),s}function zi({nonce:t,sessionId:e}={}){return{type:f.CHALLENGE,nonce:t,session_id:e}}function pt({method:t,signature:e,publicKey:n,password:r}={}){let s={type:f.AUTH,method:t};return t===te.PUBKEY?(s.signature=e,s.public_key=n):t===te.PASSWORD&&(s.password=r),s}function ji({sessionId:t,token:e,ttl:n}={}){return{type:f.AUTH_OK,session_id:t,token:e,ttl:n}}function Vi({reason:t}={}){return{type:f.AUTH_FAIL,reason:t}}function Yi({kind:t,command:e,cols:n,rows:r,env:s,stdio:i,target:o}={}){let a={type:f.OPEN,kind:t};return e!==void 0&&(a.command=e),n!==void 0&&(a.cols=n),r!==void 0&&(a.rows=r),s!==void 0&&(a.env=s),i!==void 0&&(a.stdio=i),o!==void 0&&(a.target=o),a}function Ye({channelId:t,streamIds:e=[],dataMode:n="stream",capabilities:r=[],sessionId:s,token:i,stderrChannelId:o}={}){let a={type:f.OPEN_OK,channel_id:t,stream_ids:e,data_mode:n,capabilities:r};return s!==void 0&&(a.session_id=s),i!==void 0&&(a.token=i),o!==void 0&&(a.stderr_channel_id=o),a}function re({reason:t}={}){return{type:f.OPEN_FAIL,reason:t}}function qi({channelId:t,cols:e,rows:n}={}){return{type:f.RESIZE,channel_id:t,cols:e,rows:n}}function Xi({channelId:t,signal:e}={}){return{type:f.SIGNAL,channel_id:t,signal:e}}function os({channelId:t,code:e}={}){return{type:f.EXIT,channel_id:t,code:e}}function Lt({channelId:t}={}){return{type:f.CLOSE,channel_id:t}}function yt({channelId:t,data:e}={}){return{type:f.SESSION_DATA,channel_id:t,data:e}}function qe({code:t,message:e}={}){return{type:f.ERROR,code:t,message:e}}function as({id:t}={}){return{type:f.PING,id:t}}function Jn({id:t}={}){return{type:f.PONG,id:t}}function Ji({sessionId:t,token:e,mode:n="control",deviceLabel:r}={}){let s={type:f.ATTACH,session_id:t,mode:n};return e!==void 0&&(s.token=e),r!==void 0&&(s.device_label=r),s}function Qi({sessionId:t,token:e,lastSeq:n}={}){return{type:f.RESUME,session_id:t,token:e,last_seq:n}}function cs({attachments:t}={}){return{type:f.PRESENCE,attachments:t}}function Zi(){return{type:f.METRICS_REQUEST}}function eo({sessionId:t,action:e}={}){return{type:f.SUSPEND_SESSION,session_id:t,action:e}}function to({sessionId:t,command:e}={}){let n={type:f.RESTART_PTY,session_id:t};return e!==void 0&&(n.command=e),n}function no(){return{type:f.SESSION_LIST_REQUEST}}function ro(){return{type:f.MCP_DISCOVER}}function so({tools:t}={}){return{type:f.MCP_TOOLS,tools:t}}function io({tool:t,arguments:e,callId:n}={}){let r={type:f.MCP_CALL,tool:t,arguments:e};return n!==void 0&&(r.call_id=n),r}function ls({result:t,callId:e}={}){let n={type:f.MCP_RESULT,result:t};return e!==void 0&&(n.call_id=e),n}function oo({callId:t}={}){return{type:f.MCP_CANCEL,call_id:t}}function ao({username:t,capabilities:e=[],peerType:n="host",shellBackend:r="pty",supportsAttach:s=!1,supportsReplay:i=!1,supportsEcho:o=!1,supportsTermSync:a=!1,publicKey:c,seq:l,recordSignature:h}={}){return{type:f.REVERSE_REGISTER,username:t,capabilities:e,peer_type:n,shell_backend:r,supports_attach:s,supports_replay:i,supports_echo:o,supports_term_sync:a,public_key:c,seq:l,record_signature:h}}function co(){return{type:f.REVERSE_LIST}}function lo({peers:t}={}){return{type:f.REVERSE_PEERS,peers:t}}function uo({targetFingerprint:t,username:e,fromFingerprint:n,features:r}={}){let s={type:f.REVERSE_CONNECT,target_fingerprint:t,username:e,from_fingerprint:n};return r!==void 0&&(s.features=r),s}function us({targetFingerprint:t,username:e,reason:n}={}){return{type:f.REVERSE_REJECT,target_fingerprint:t,username:e,reason:n}}function ho({fromFingerprint:t,inner:e,toFingerprint:n}={}){let r={type:f.RELAY_FORWARD,from_fingerprint:t,inner:e};return n!==void 0&&(r.to_fingerprint=n),r}function fo({targetFingerprint:t,publicKey:e,username:n,nonce:r,sessionId:s,signature:i,fromFingerprint:o}={}){let a={type:f.REVERSE_PROOF,target_fingerprint:t,public_key:e,username:n,nonce:r,session_id:s,signature:i};return o!==void 0&&(a.from_fingerprint=o),a}function po({sessions:t}={}){return{type:f.SESSION_LIST,sessions:t}}function yo({sessionId:t}={}){return{type:f.DETACH,session_id:t}}function Eo({sessionId:t}={}){return{type:f.DETACH_OK,session_id:t}}function wo({reason:t}={}){return{type:f.DETACH_FAIL,reason:t}}function mo({gatewayId:t,path:e}={}){return{type:f.OPEN_UNIX,gateway_id:t,path:e}}function go({gatewayId:t,name:e,target:n}={}){let r={type:f.OPEN_ENDPOINT,gateway_id:t,name:e};return n!==void 0&&(r.target=n),r}function _o({listenerId:t,path:e,replace:n}={}){let r={type:f.LISTEN_UNIX,listener_id:t,path:e};return n!==void 0&&(r.replace=n),r}function bo({gatewayId:t,host:e,port:n}={}){return{type:f.OPEN_TCP,gateway_id:t,host:e,port:n}}function Ao({gatewayId:t,host:e,port:n}={}){return{type:f.OPEN_UDP,gateway_id:t,host:e,port:n}}function To({gatewayId:t,resolvedAddr:e}={}){let n={type:f.GATEWAY_OK,gateway_id:t};return e!==void 0&&(n.resolved_addr=e),n}function Qn({gatewayId:t,code:e,message:n}={}){return{type:f.GATEWAY_FAIL,gateway_id:t,code:e,message:n}}function Zn({gatewayId:t,reason:e}={}){let n={type:f.GATEWAY_CLOSE,gateway_id:t};return e!==void 0&&(n.reason=e),n}function xo({channelId:t,gatewayId:e}={}){let n={type:f.INBOUND_ACCEPT,channel_id:t};return e!==void 0&&(n.gateway_id=e),n}function hs({channelId:t,reason:e}={}){let n={type:f.INBOUND_REJECT,channel_id:t};return e!==void 0&&(n.reason=e),n}function So({listenerId:t,port:e,bindAddr:n="0.0.0.0"}={}){return{type:f.LISTEN_REQUEST,listener_id:t,port:e,bind_addr:n}}function er({listenerId:t,reason:e}={}){return{type:f.LISTEN_FAIL,listener_id:t,reason:e}}function fs({listenerId:t}={}){return{type:f.LISTEN_CLOSE,listener_id:t}}function tr({gatewayId:t,data:e}={}){return{type:f.GATEWAY_DATA,gateway_id:t,data:e}}function Xe({gatewayId:t,bytes:e}={}){return{type:f.GATEWAY_CREDIT,gateway_id:t,bytes:e}}function Ro({sessionId:t,ttl:e,permissions:n=["read"]}={}){return{type:f.GUEST_INVITE,session_id:t,ttl:e,permissions:n}}function Oo({token:t,deviceLabel:e}={}){let n={type:f.GUEST_JOIN,token:t};return e!==void 0&&(n.device_label=e),n}function Co({token:t,reason:e}={}){let n={type:f.GUEST_REVOKE,token:t};return e!==void 0&&(n.reason=e),n}function Io({sessionId:t,mode:e="read",ttl:n}={}){return{type:f.SHARE_SESSION,session_id:t,mode:e,ttl:n}}function No({shareId:t,reason:e}={}){let n={type:f.SHARE_REVOKE,share_id:t};return e!==void 0&&(n.reason=e),n}function Lo({algorithm:t,level:e=3}={}){return{type:f.COMPRESS_BEGIN,algorithm:t,level:e}}function ko({algorithm:t,accepted:e}={}){return{type:f.COMPRESS_ACK,algorithm:t,accepted:e}}function Mo({sessionId:t,maxBytesPerSec:e,policy:n="pause"}={}){return{type:f.RATE_CONTROL,session_id:t,max_bytes_per_sec:e,policy:n}}function Do({sourceSession:t,targetHost:e,targetPort:n,targetUser:r}={}){let s={type:f.SESSION_LINK,source_session:t,target_host:e,target_port:n};return r!==void 0&&(s.target_user=r),s}function Po({linkId:t,reason:e}={}){let n={type:f.SESSION_UNLINK,link_id:t};return e!==void 0&&(n.reason=e),n}function Uo({sessionId:t,model:e,contextWindow:n}={}){let r={type:f.COPILOT_ATTACH,session_id:t,model:e};return n!==void 0&&(r.context_window=n),r}function vo({sessionId:t,suggestion:e,confidence:n}={}){let r={type:f.COPILOT_SUGGEST,session_id:t,suggestion:e};return n!==void 0&&(r.confidence=n),r}function Fo({sessionId:t,reason:e}={}){let n={type:f.COPILOT_DETACH,session_id:t};return e!==void 0&&(n.reason=e),n}function kt({algorithm:t,publicKey:e,sessionId:n,kemPublicKey:r,kemCiphertext:s,signature:i}={}){let o={type:f.KEY_EXCHANGE,algorithm:t,session_id:n};return e!==void 0&&(o.public_key=e),r!==void 0&&(o.kem_public_key=r),s!==void 0&&(o.kem_ciphertext=s),i!==void 0&&(o.signature=i),o}function Mt({channelId:t,nonce:e,ciphertext:n,sessionId:r}={}){return{type:f.ENCRYPTED_FRAME,channel_id:t,nonce:e,ciphertext:n,session_id:r}}function $o({sessionId:t,principal:e,permissions:n=["read"]}={}){return{type:f.SESSION_GRANT,session_id:t,principal:e,permissions:n}}function Ko({sessionId:t,principal:e,reason:n}={}){let r={type:f.SESSION_REVOKE,session_id:t,principal:e};return n!==void 0&&(r.reason=n),r}function ds({channelId:t,op:e,path:n,offset:r,length:s,target:i}={}){let o={type:f.FILE_OP,channel_id:t,op:e,path:n};return r!==void 0&&(o.offset=r),s!==void 0&&(o.length=s),i!==void 0&&(o.target=i),o}function de({channelId:t,success:e,metadata:n={},entries:r=[],errorMessage:s}={}){let i={type:f.FILE_RESULT,channel_id:t,success:e,metadata:n,entries:r};return s!==void 0&&(i.error_message=s),i}function hn({channelId:t,offset:e,data:n,isFinal:r,totalSize:s}={}){return{type:f.FILE_CHUNK,channel_id:t,offset:e,data:n,is_final:r,total_size:s}}function Bo({requestId:t,action:e,principal:n,context:r={}}={}){return{type:f.POLICY_EVAL,request_id:t,action:e,principal:n,context:r}}function Ho({policyId:t,rules:e,version:n}={}){return{type:f.POLICY_UPDATE,policy_id:t,rules:e,version:n}}function Go({publicKey:t,comment:e}={}){let n={type:f.AUTHORIZED_KEY_ADD,public_key:t};return e!==void 0&&(n.comment=e),n}function Wo({requestId:t,share:e,op:n,path:r,to:s,handle:i,offset:o,length:a,mode:c,flags:l=[],cursor:h,attr:d={},data:w}={}){let y={type:f.SHARE_REQUEST,request_id:t,share:e,op:n,flags:l,attr:d};return r!==void 0&&(y.path=r),s!==void 0&&(y.to=s),i!==void 0&&(y.handle=i),o!==void 0&&(y.offset=o),a!==void 0&&(y.length=a),c!==void 0&&(y.mode=c),h!==void 0&&(y.cursor=h),w!==void 0&&(y.data=w),y}function zo(){return{type:f.LIST_TARGETS}}function jo({targets:t}={}){return{type:f.TARGET_LIST,targets:t}}var uu=new Set([f.OPEN,f.OPEN_OK,f.OPEN_FAIL,f.CLOSE,f.EXIT,f.RESIZE,f.SIGNAL,f.SESSION_DATA,f.GATEWAY_DATA,f.GATEWAY_CREDIT,f.GATEWAY_OK,f.GATEWAY_FAIL,f.GATEWAY_CLOSE,f.MCP_DISCOVER,f.MCP_TOOLS,f.MCP_CALL,f.MCP_RESULT,f.MCP_CANCEL,f.REVERSE_ACCEPT,f.REVERSE_REJECT,f.GUEST_JOIN,f.GUEST_REVOKE,f.COPILOT_ATTACH,f.COPILOT_DETACH,f.FILE_OP,f.FILE_RESULT,f.FILE_CHUNK,f.POLICY_EVAL,f.ECHO_ACK,f.ECHO_STATE,f.TERM_SYNC,f.TERM_DIFF,f.KEY_EXCHANGE,f.ENCRYPTED_FRAME]);function Dt(t){return uu.has(t)}var ps=null;async function Vo(){return ps===null&&(ps=(async()=>{try{return await crypto.subtle.generateKey("Ed25519",!1,["sign","verify"]),!0}catch{return!1}})()),ps}async function ys(t=!1){try{return await crypto.subtle.generateKey("Ed25519",t,["sign","verify"])}catch(e){throw new Error(`wsh requires WebCrypto Ed25519, which this runtime does not implement (Safari 17+, Chrome/Edge 137+, Firefox 130+, Node 20+). Check isEd25519Supported() first and fall back to password auth, or supply a CryptoKeyPair from elsewhere. (${e?.message||e})`,{cause:e})}}async function fn(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}async function Ut(t){let e=await fn(t),n="ssh-ed25519",r=new TextEncoder().encode(n),s=new Uint8Array(4+r.length+4+e.length),i=new DataView(s.buffer),o=0;return i.setUint32(o,r.length),o+=4,s.set(r,o),o+=r.length,i.setUint32(o,e.length),o+=4,s.set(e,o),`${n} ${du(s)}`}async function pe(t){return crypto.subtle.importKey("raw",t,"Ed25519",!0,["verify"])}async function Yo(t,e=!1){return crypto.subtle.importKey("pkcs8",t,"Ed25519",e,["sign"])}async function nr(t,e){let n=await crypto.subtle.sign("Ed25519",t,e);return new Uint8Array(n)}async function Je({keyPair:t,signer:e}={}){if(t&&e)throw new TypeError("pass either keyPair or signer, not both");if(t)return{publicKeyRaw:await fn(t.publicKey),sign:r=>nr(t.privateKey,r)};if(!e)return null;if(typeof e!="object"||typeof e.sign!="function")throw new TypeError("signer must be { publicKey, sign(data) }");let n;if(e.publicKey instanceof Uint8Array?n=e.publicKey:e.publicKey&&typeof e.publicKey=="object"&&e.publicKey.type==="public"&&(n=await fn(e.publicKey)),!n||n.byteLength!==32)throw new TypeError("signer.publicKey must be a raw 32-byte Ed25519 key or a public CryptoKey");return{publicKeyRaw:n,sign:async r=>{let s=await e.sign(r);if(!(s instanceof Uint8Array)||s.byteLength!==64)throw new TypeError("signer.sign() must return a 64-byte Ed25519 signature");return s}}}async function vt(t,e,n,r){let s=await ws(e,n,r);return{signature:await t.sign(s),publicKeyRaw:t.publicKeyRaw}}async function Es(t,e){let n=await ms(e);return{signature:await t.sign(n),publicKeyRaw:t.publicKeyRaw}}async function Le(t,e,n){return crypto.subtle.verify("Ed25519",t,e,n)}function Pt(t){let e=new Uint8Array(4+t.length);return new DataView(e.buffer).setUint32(0,t.length),e.set(t,4),e}async function ws(t,e,{username:n="",channelBinding:r=new Uint8Array(0)}={}){let s=new TextEncoder,i=s.encode(ss+"\0"),o=Pt(s.encode(n)),a=Pt(s.encode(t)),c=i.length+o.length+a.length+e.length+r.length,l=new Uint8Array(c),h=0;l.set(i,h),h+=i.length,l.set(o,h),h+=o.length,l.set(a,h),h+=a.length,l.set(e,h),h+=e.length,l.set(r,h);let d=await crypto.subtle.digest("SHA-256",l);return new Uint8Array(d)}async function rr(t,e,n,r,s){let i=await ws(n,r,s);return Le(t,e,i)}var hu="wsh-peer-record-v1\0";async function ms(t){let e=new TextEncoder,n=e.encode(hu),r=Pt(e.encode(t.username??"")),s=Pt(e.encode(t.peerType??"host")),i=Pt(e.encode(t.shellBackend??"pty")),o=Pt(e.encode((t.capabilities??[]).join(","))),a=new Uint8Array([(t.supportsAttach?1:0)|(t.supportsReplay?2:0)|(t.supportsEcho?4:0)|(t.supportsTermSync?8:0)]),c=new Uint8Array(8);new DataView(c.buffer).setBigUint64(0,BigInt(t.seq));let l=n.length+r.length+s.length+i.length+o.length+a.length+c.length,h=new Uint8Array(l),d=0;h.set(n,d),d+=n.length,h.set(r,d),d+=r.length,h.set(s,d),d+=s.length,h.set(i,d),d+=i.length,h.set(o,d),d+=o.length,h.set(a,d),d+=a.length,h.set(c,d);let w=await crypto.subtle.digest("SHA-256",h);return new Uint8Array(w)}async function gs(t,e,n){let r=await ms(n);return Le(t,e,r)}async function oe(t){let e=await crypto.subtle.digest("SHA-256",t);return fu(new Uint8Array(e))}function _s(){return crypto.getRandomValues(new Uint8Array(32))}function fu(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function du(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function qo(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function dn(t){let e=t.trim().split(/\s+/);if(e.length<2)return null;let[n,r,...s]=e;if(n!=="ssh-ed25519")return null;try{let i=qo(r);return{type:n,data:i,comment:s.join(" ")}}catch{return null}}function pn(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint32(0),r=4+n+4,s=e.getUint32(4+n);return t.slice(r,r+s)}async function As(t,e){for(let n of t)await e(n)}var ir=class{#e=[];#n;#r=!1;constructor(e){this.#n=e}#i=Promise.resolve();push(e){this.#e.push(e),this.#r||(this.#i=this.#t())}get busy(){return this.#r||this.#e.length>0}idle(){return this.#i}clear(){this.#e.length=0}async#t(){if(!this.#r){this.#r=!0;try{for(;this.#e.length>0;){let e=this.#e.shift();await this.#n(e)}}finally{this.#r=!1}}}},Xo="disconnected",Jo="connecting",sr="connected",bs="closed",yn=class{#e=Xo;onControl=null;onStreamOpen=null;onClose=null;onError=null;get state(){return this.#e}onDatagram=null;get supportsDatagrams(){return!1}get maxDatagramSize(){return 0}sendDatagram(e){return!1}tlsExporter(e,n){return null}_setState(e){this.#e=e}async connect(e,n){if(this.#e===sr||this.#e===Jo)throw new Error(`Transport already ${this.#e}`);this.#e=Jo;try{await this._doConnect(e,n),this.#e=sr}catch(r){this.#e=bs;try{await this._doClose()}catch{}throw r}}async close(){if(!(this.#e===bs||this.#e===Xo)){this.#e=bs;try{await this._doClose()}finally{this._emitClose()}}}async sendControl(e){if(this.#e!==sr)throw new Error(`Cannot send: transport is ${this.#e}`);await this._doSendControl(e)}async openStream(){if(this.#e!==sr)throw new Error(`Cannot open stream: transport is ${this.#e}`);return this._doOpenStream()}_emitControl(e){try{this.onControl?.(e)}catch(n){console.error("[wsh:transport] onControl handler error:",n)}}_emitStreamOpen(e){try{this.onStreamOpen?.(e)}catch(n){console.error("[wsh:transport] onStreamOpen handler error:",n)}}_emitClose(){try{this.onClose?.()}catch(e){console.error("[wsh:transport] onClose handler error:",e)}}_emitError(e){try{this.onError?.(e)}catch(n){console.error("[wsh:transport] onError handler error:",n)}}async _doConnect(e,n){throw new Error("_doConnect not implemented")}async _doClose(){throw new Error("_doClose not implemented")}async _doSendControl(e){throw new Error("_doSendControl not implemented")}async _doOpenStream(){throw new Error("_doOpenStream not implemented")}},pu=Object.freeze({"sha-256":32});function Qo(t,e="sha-256"){let n=pu[e],r;if(t instanceof Uint8Array)r=t;else if(ArrayBuffer.isView(t))r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)r=new Uint8Array(t);else if(typeof t=="string")r=yu(t);else throw new TypeError(`serverCertificateHashes value must be a BufferSource or a hex/base64 string, got ${t===null?"null":typeof t}`);if(n!==void 0&&r.length!==n)throw new RangeError(`serverCertificateHashes value for "${e}" must be ${n} bytes, got ${r.length}`);return r}function yu(t){let e=t.trim().replace(/^[^=]{0,64}fingerprint[^=]{0,64}=\s*/i,""),n=e.replace(/[\s:-]/g,"");if(/^[0-9a-fA-F]+$/.test(n)&&n.length%2===0){let o=new Uint8Array(n.length/2);for(let a=0;a<o.length;a++)o[a]=Number.parseInt(n.slice(a*2,a*2+2),16);return o}let r=e.replace(/-/g,"+").replace(/_/g,"/");if(!/^[A-Za-z0-9+/]+={0,2}$/.test(r))throw new TypeError(`serverCertificateHashes value is neither hex nor base64: ${JSON.stringify(t)}`);let s=atob(r),i=new Uint8Array(s.length);for(let o=0;o<s.length;o++)i[o]=s.charCodeAt(o);return i}function Ts(t){if(!t)return;let e=Object.keys(t).filter(r=>t[r]!==void 0);if(e.length===0)return;let n={};for(let r of e)n[r]=t[r];if(n.serverCertificateHashes!==void 0){let r=n.serverCertificateHashes;if(!Array.isArray(r))throw new TypeError("serverCertificateHashes must be an array");if(r.length===0)throw new TypeError("serverCertificateHashes must not be empty -- omit the option entirely to use the normal certificate-authority path");n.serverCertificateHashes=r.map(s=>{if(s===null||typeof s!="object"||Array.isArray(s)||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)return{algorithm:"sha-256",value:Qo(s,"sha-256")};let i=String(s.algorithm??"sha-256").toLowerCase();return{algorithm:i,value:Qo(s.value,i)}})}return n}var or=class extends yn{#e=null;#n=null;#r=new AbortController;#i=new je;#t=1;#s=null;#o=null;#a;constructor(e){super(),this.#a=e}async _doConnect(e,n){this.#r=new AbortController,this.#i.reset(),this.#t=1;let r=Ts((this.#a||n)&&{...this.#a,...n}),s=r?new WebTransport(e,r):new WebTransport(e);this.#e=s,s.closed?.catch?.(()=>{}),await s.ready;let i=await s.createBidirectionalStream();this.#n=i.writable.getWriter(),this.#c=null;try{let o=s.datagrams;o&&o.readable&&(this.#c=(typeof o.createWritable=="function"?o.createWritable():o.writable).getWriter(),this.#u(o.readable))}catch{this.#c=null}this.#s=this.#l(i.readable),this.#o=this.#f(),this.#y(s)}#c=null;get supportsDatagrams(){return this.#c!==null}get maxDatagramSize(){try{return this.#c&&Number(this.#e?.datagrams?.maxDatagramSize)||0}catch{return 0}}sendDatagram(e){let n=this.#c;return!n||this.state!=="connected"||n.desiredSize!==null&&n.desiredSize<=0?!1:(n.write(e).catch(()=>{}),!0)}async#u(e){let n=e.getReader();try{for(;;){let{done:r,value:s}=await n.read();if(r)break;try{this.onDatagram?.(s)}catch(i){console.error("[wsh:transport] onDatagram handler error:",i)}}}catch{}}async _doClose(){this.#c=null,this.#r.abort();try{this.#n?.releaseLock?.()}catch{}try{this.#e?.close()}catch{}await Promise.allSettled([this.#s,this.#o]),this.#e=null,this.#n=null,this.#i.reset()}async _doSendControl(e){let n=Nt(e);await this.#n.write(n)}async _doOpenStream(){let e=await this.#e.createBidirectionalStream(),n=this.#t++;return{readable:e.readable,writable:e.writable,id:n}}async#l(e){let n=e.getReader();try{for(;!this.#r.signal.aborted;){let{done:r,value:s}=await n.read();if(r)break;let i=this.#i.feed(s);await As(i,o=>this._emitControl(o))}}catch(r){this.#r.signal.aborted||(this._emitError(new Error(`Control stream read error: ${r.message}`)),r instanceof ft&&this.close().catch(()=>{}))}finally{n.releaseLock()}}async#f(){let e=this.#e.incomingBidirectionalStreams.getReader();try{for(;!this.#r.signal.aborted;){let{done:n,value:r}=await e.read();if(n)break;let s=this.#t++;this._emitStreamOpen({readable:r.readable,writable:r.writable,id:s})}}catch(n){this.#r.signal.aborted||this._emitError(new Error(`Incoming stream acceptor error: ${n.message}`))}finally{e.releaseLock()}}#y(e){let n=()=>this.#s?.catch(()=>{})??Promise.resolve();e.closed.then(()=>n().then(()=>{this.state!=="closed"&&(this._setState("closed"),this._emitClose())})).catch(r=>n().then(()=>{this.state!=="closed"&&(this._setState("closed"),this._emitError(r),this._emitClose())}))}};var Eu=(1n<<62n)-1n;function K(t){let e=typeof t=="bigint"?t:BigInt(t);if(e<0n)throw new RangeError("varint value must be non-negative");if(e>Eu)throw new RangeError("varint value exceeds the 62-bit QUIC varint range");if(e<=BigInt(63))return new Uint8Array([Number(e)]);if(e<=BigInt(16383)){let r=new Uint8Array(2);return new DataView(r.buffer).setUint16(0,Number(e)|16384),r}if(e<=BigInt(1073741823)){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,Number(e)|2147483648),r}let n=new Uint8Array(8);return new DataView(n.buffer).setBigUint64(0,e|0xc000000000000000n),n}function Y(t,e=0){if(e>=t.byteLength)throw new RangeError("varint: no data at offset");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint8(e),i=1<<(r>>6);if(e+i>t.byteLength)throw new RangeError("varint: truncated");let o;if(i===1)o=r&63;else if(i===2)o=n.getUint16(e)&16383;else if(i===4)o=(n.getUint32(e)&1073741823)>>>0;else{let a=n.getBigUint64(e)&0x3fffffffffffffffn;o=a<=BigInt(Number.MAX_SAFE_INTEGER)?Number(a):a}return{value:o,length:i}}function ae(t){let e=0;for(let s of t)e+=s.byteLength;let n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.byteLength;return n}var W=Object.freeze({PADDING:0,RESET_STREAM:4,STOP_SENDING:5,STREAM:8,MAX_DATA:16,MAX_STREAM_DATA:17,MAX_STREAMS_BIDI:18,MAX_STREAMS_UNI:19,DATA_BLOCKED:20,STREAM_DATA_BLOCKED:21,STREAMS_BLOCKED_BIDI:22,STREAMS_BLOCKED_UNI:23,CONNECTION_CLOSE_TRANSPORT:28,CONNECTION_CLOSE_APPLICATION:29,DATAGRAM:48,RESET_STREAM_AT:36}),Zo=0x3f5153300d0a0d0an,Fe=Object.freeze({NO_ERROR:0,INTERNAL_ERROR:1,FLOW_CONTROL_ERROR:3,STREAM_LIMIT_ERROR:4,STREAM_STATE_ERROR:5,FINAL_SIZE_ERROR:6,FRAME_ENCODING_ERROR:7,TRANSPORT_PARAMETER_ERROR:8,PROTOCOL_VIOLATION:10,APPLICATION_ERROR:12});function ke(t){return ae([K(t.byteLength),t])}var ar=class{#e=new Uint8Array(0);feed(e){let n=new Uint8Array(this.#e.byteLength+e.byteLength);n.set(this.#e,0),n.set(e,this.#e.byteLength),this.#e=n;let r=[];for(;;){let s;try{s=Y(this.#e,0)}catch{break}let i=Number(s.value),o=s.length+i;if(this.#e.byteLength<o)break;r.push(this.#e.slice(s.length,o)),this.#e=this.#e.slice(o)}return r}reset(){this.#e=new Uint8Array(0)}};function ea({streamId:t,errorCode:e,finalSize:n}){return ae([K(W.RESET_STREAM),K(t),K(e),K(n)])}function ta({streamId:t,errorCode:e,finalSize:n,reliableSize:r}){return ae([K(W.RESET_STREAM_AT),K(t),K(e),K(n),K(r)])}function na({streamId:t,errorCode:e}){return ae([K(W.STOP_SENDING),K(t),K(e)])}function cr({streamId:t,offset:e,data:n,fin:r}){let s=6|(r?1:0);return ae([K(W.STREAM|s),K(t),K(e),K(n.byteLength),n])}function ra(t){return ae([K(W.MAX_DATA),K(t)])}function sa({streamId:t,maxStreamData:e}){return ae([K(W.MAX_STREAM_DATA),K(t),K(e)])}function ia({unidirectional:t,maxStreams:e}){return ae([K(t?W.MAX_STREAMS_UNI:W.MAX_STREAMS_BIDI),K(e)])}function oa(t){return ae([K(W.DATA_BLOCKED),K(t)])}function aa({streamId:t,streamDataLimit:e}){return ae([K(W.STREAM_DATA_BLOCKED),K(t),K(e)])}function ca({unidirectional:t,streamLimit:e}){return ae([K(t?W.STREAMS_BLOCKED_UNI:W.STREAMS_BLOCKED_BIDI),K(e)])}var wu=new TextEncoder,mu=new TextDecoder;function xs({application:t=!1,errorCode:e,frameType:n,reason:r=""}){let s=wu.encode(r),i=[K(t?W.CONNECTION_CLOSE_APPLICATION:W.CONNECTION_CLOSE_TRANSPORT),K(e)];return t||i.push(K(n??0)),i.push(K(s.byteLength),s),ae(i)}function la(t){return ae([K(W.DATAGRAM|1),K(t.byteLength),t])}function ua(t){let e=[];for(let[s,i]of Object.entries(ha)){if(t[s]===void 0)continue;let o=K(t[s]);e.push(ae([K(i),K(o.byteLength),o]))}let n=ae(e),r=K(Zo);return ae([r,K(n.byteLength),n])}var ha=Object.freeze({max_idle_timeout:1,initial_max_data:4,initial_max_stream_data_bidi_local:5,initial_max_stream_data_bidi_remote:6,initial_max_stream_data_uni:7,initial_max_streams_bidi:8,initial_max_streams_uni:9,max_datagram_frame_size:32}),gu=Object.freeze(Object.fromEntries(Object.entries(ha).map(([t,e])=>[e,t])));function fa(t){let e=[],n=0;for(;n<t.byteLength;){let r=Y(t,n),s=r.value;if(n+=r.length,s===Zo){let i=Y(t,n);n+=i.length;let o=t.subarray(n,n+Number(i.value));n+=Number(i.value),e.push({frameType:"QX_TRANSPORT_PARAMETERS",params:_u(o)});continue}if(typeof s=="number"&&s>=8&&s<=15){let i=(s&1)!==0,o=(s&2)!==0,a=(s&4)!==0,c=Y(t,n);n+=c.length;let l=0;if(a){let w=Y(t,n);n+=w.length,l=w.value}let h;if(o){let w=Y(t,n);n+=w.length,h=Number(w.value)}else h=t.byteLength-n;let d=t.slice(n,n+h);n+=h,e.push({frameType:"STREAM",streamId:c.value,offset:l,data:d,fin:i});continue}if(s===W.DATAGRAM||s===(W.DATAGRAM|1)){let i=(Number(s)&1)!==0,o;if(i){let c=Y(t,n);n+=c.length,o=Number(c.value)}else o=t.byteLength-n;let a=t.slice(n,n+o);n+=o,e.push({frameType:"DATAGRAM",data:a});continue}switch(s){case W.PADDING:{e.push({frameType:"PADDING"});break}case W.RESET_STREAM:{let i=Y(t,n);n+=i.length;let o=Y(t,n);n+=o.length;let a=Y(t,n);n+=a.length,e.push({frameType:"RESET_STREAM",streamId:i.value,errorCode:o.value,finalSize:a.value});break}case W.RESET_STREAM_AT:{let i=Y(t,n);n+=i.length;let o=Y(t,n);n+=o.length;let a=Y(t,n);n+=a.length;let c=Y(t,n);if(n+=c.length,Number(c.value)>Number(a.value))throw new $e(Fe.FRAME_ENCODING_ERROR,"RESET_STREAM_AT: reliableSize > finalSize");e.push({frameType:"RESET_STREAM_AT",streamId:i.value,errorCode:o.value,finalSize:a.value,reliableSize:c.value});break}case W.STOP_SENDING:{let i=Y(t,n);n+=i.length;let o=Y(t,n);n+=o.length,e.push({frameType:"STOP_SENDING",streamId:i.value,errorCode:o.value});break}case W.MAX_DATA:{let i=Y(t,n);n+=i.length,e.push({frameType:"MAX_DATA",maxData:i.value});break}case W.MAX_STREAM_DATA:{let i=Y(t,n);n+=i.length;let o=Y(t,n);n+=o.length,e.push({frameType:"MAX_STREAM_DATA",streamId:i.value,maxStreamData:o.value});break}case W.MAX_STREAMS_BIDI:case W.MAX_STREAMS_UNI:{let i=Y(t,n);n+=i.length,e.push({frameType:"MAX_STREAMS",unidirectional:s===W.MAX_STREAMS_UNI,maxStreams:i.value});break}case W.DATA_BLOCKED:{let i=Y(t,n);n+=i.length,e.push({frameType:"DATA_BLOCKED",dataLimit:i.value});break}case W.STREAM_DATA_BLOCKED:{let i=Y(t,n);n+=i.length;let o=Y(t,n);n+=o.length,e.push({frameType:"STREAM_DATA_BLOCKED",streamId:i.value,streamDataLimit:o.value});break}case W.STREAMS_BLOCKED_BIDI:case W.STREAMS_BLOCKED_UNI:{let i=Y(t,n);n+=i.length,e.push({frameType:"STREAMS_BLOCKED",unidirectional:s===W.STREAMS_BLOCKED_UNI,streamLimit:i.value});break}case W.CONNECTION_CLOSE_TRANSPORT:case W.CONNECTION_CLOSE_APPLICATION:{let i=s===W.CONNECTION_CLOSE_APPLICATION,o=Y(t,n);n+=o.length;let a;if(!i){let h=Y(t,n);n+=h.length,a=h.value}let c=Y(t,n);n+=c.length;let l=t.slice(n,n+Number(c.value));n+=Number(c.value),e.push({frameType:"CONNECTION_CLOSE",application:i,errorCode:o.value,closeFrameType:a,reason:mu.decode(l)});break}default:throw new $e(Fe.FRAME_ENCODING_ERROR,`unknown/prohibited frame type: 0x${s.toString(16)}`)}}return e}function _u(t){let e={},n=0;for(;n<t.byteLength;){let r=Y(t,n);n+=r.length;let s=Y(t,n);n+=s.length;let i=t.subarray(n,n+Number(s.value));n+=Number(s.value);let o=gu[Number(r.value)];o&&(e[o]=i.byteLength===0?!0:Y(i,0).value)}return e}var $e=class extends Error{constructor(e,n){super(n),this.name="QMuxProtocolError",this.errorCode=e}},lr=Object.freeze({CLIENT:0,SERVER:1});function Ss(t){return(Number(t)&1)===lr.CLIENT}function da(t){return t+4}var ur=Object.freeze({initialMaxData:8*1024*1024,initialMaxStreamData:1024*1024,initialMaxStreamsBidi:100}),Rs=.5,se=Object.freeze({READY:"ready",SEND:"send",RESET_SENT:"reset_sent",DATA_SENT:"data_sent"}),ge=Object.freeze({RECV:"recv",SIZE_KNOWN:"size_known",DATA_RECVD:"data_recvd",RESET_RECVD:"reset_recvd"}),Os=class{id;#e;#n=se.READY;#r=0;#i;#t=[];#s=ge.RECV;#o=0;#a=0;#c;#u;#l=null;#f=null;#y=null;#A=new Map;onData=null;onEnd=null;onReset=null;onDestroy=null;constructor(e,n,{sendWindow:r,recvWindow:s}){this.#e=e,this.id=n,this.#i=r,this.#c=s,this.#u=s}get sendState(){return this.#n}get recvState(){return this.#s}_isFullyClosed(){let e=this.#n===se.DATA_SENT||this.#n===se.RESET_SENT,n=this.#s===ge.DATA_RECVD||this.#s===ge.RESET_RECVD;return e&&n}async write(e){if(this.#n===se.RESET_SENT)throw new Error(`Cannot write to stream ${this.id}: already reset`);if(this.#n===se.DATA_SENT)throw new Error(`Cannot write to stream ${this.id}: already closed (FIN sent)`);if(e.byteLength===0){this.announce();return}this.#n=se.SEND;let n=0;for(;n<e.byteLength;){let r=await this.#h(e.byteLength-n),s=e.subarray(n,n+r);this.#e._sendFrame(cr({streamId:this.id,offset:this.#r,data:s,fin:!1}),s.byteLength),this.#r+=s.byteLength,this.#i-=s.byteLength,n+=s.byteLength}}announce(){this.#n===se.READY&&(this.#n=se.SEND,this.#e._sendFrame(cr({streamId:this.id,offset:this.#r,data:new Uint8Array(0),fin:!1}),0))}async close(){this.#n===se.RESET_SENT||this.#n===se.DATA_SENT||(this.#e._sendFrame(cr({streamId:this.id,offset:this.#r,data:new Uint8Array(0),fin:!0}),0),this.#n=se.DATA_SENT,this.#e._maybeStreamClosed(this.id))}reset(e=Fe.APPLICATION_ERROR,n=0){if(this.#n===se.RESET_SENT||this.#n===se.DATA_SENT)return;let r=this.#r;n>0?this.#e._sendFrame(ta({streamId:this.id,errorCode:e,finalSize:r,reliableSize:Math.min(n,r)}),0):this.#e._sendFrame(ea({streamId:this.id,errorCode:e,finalSize:r}),0),this.#n=se.RESET_SENT,this.#E(new Error(`Stream ${this.id} was reset`)),this.#e._maybeStreamClosed(this.id)}stopSending(e=Fe.APPLICATION_ERROR){this.#e._sendFrame(na({streamId:this.id,errorCode:e}),0)}_destroy(e){if(this.#n!==se.RESET_SENT&&this.#n!==se.DATA_SENT&&(this.#n=se.RESET_SENT),this.#E(e),this.#s!==ge.DATA_RECVD&&this.#s!==ge.RESET_RECVD){this.#s=ge.RESET_RECVD;try{this.onDestroy?.(e)}catch(n){console.error("[qmux] onDestroy handler error:",n)}}}#h(e){let n=Math.min(e,this.#i,this.#e._connSendWindow());return n>0?(this.#e._reserveConnSendWindow(n),Promise.resolve(n)):(this.#i<=0&&this.#e._sendFrame(aa({streamId:this.id,streamDataLimit:this.#r+this.#i}),0),this.#e._connSendWindow()<=0&&this.#e._sendDataBlocked(),new Promise((r,s)=>{this.#t.push({resolve:r,reject:s,requested:e})}))}_grantSendWindow(e){let n=e-this.#r;n<=this.#i||(this.#i=n,this.#g())}_recheckSendWindow(){this.#g()}#g(){for(;this.#t.length>0&&this.#i>0;){let e=this.#t[0],n=Math.min(e.requested,this.#i,this.#e._connSendWindow());if(n<=0)break;this.#t.shift(),this.#e._reserveConnSendWindow(n),e.resolve(n)}}#E(e){for(let n of this.#t.splice(0))n.reject(e)}_receiveStreamData(e,n,r){if(e!==this.#a)throw new $e(Fe.PROTOCOL_VIOLATION,`stream ${this.id}: out-of-order STREAM frame (expected offset ${this.#a}, got ${e})`);if(this.#s===ge.RESET_RECVD)return 0;if(this.#a+=n.byteLength,n.byteLength>0){this.#o+=n.byteLength;try{this.onData?.(n)}catch(s){console.error("[qmux] onData handler error:",s)}this.#w()}if(r){this.#l=this.#a,this.#s=ge.DATA_RECVD;try{this.onEnd?.()}catch(s){console.error("[qmux] onEnd handler error:",s)}this.#e._maybeStreamClosed(this.id)}return n.byteLength}_receiveReset(e,n,r){this.#s===ge.RESET_RECVD||this.#s===ge.DATA_RECVD||(this.#l=n,this.#f=r,this.#y=e,this.#s=ge.SIZE_KNOWN,this.#p())}#p(){if(this.#f!==null&&!(this.#a<this.#f)&&this.#s!==ge.RESET_RECVD){this.#s=ge.RESET_RECVD;try{this.onReset?.(this.#y)}catch(e){console.error("[qmux] onReset handler error:",e)}this.#e._maybeStreamClosed(this.id)}}#w(){if(this.#p(),this.#u-this.#a<=this.#c*(1-Rs)){let n=this.#a+this.#c;this.#u=n,this.#e._sendFrame(sa({streamId:this.id,maxStreamData:n}),0)}}},Ft=class{#e;#n;#r=new ar;#i=new Map;#t;#s=!1;#o=0;#a;#c=-1;#u=0;#l;#f;#y;#A=0;#h;#g=[];#E=0;#p;#w;onStreamOpen=null;onDatagram=null;onClose=null;onError=null;constructor({isClient:e,send:n,initialMaxData:r=ur.initialMaxData,initialMaxStreamData:s=ur.initialMaxStreamData,initialMaxStreamsBidi:i=ur.initialMaxStreamsBidi}){this.#e=e,this.#n=n,this.#a=r,this.#l=r,this.#f=r,this.#w=s,this.#y=i,this.#p=i,this.#t=e?lr.CLIENT:lr.SERVER}sendHandshake(){this.#n(ke(ua({initial_max_data:this.#f,initial_max_stream_data_bidi_local:this.#w,initial_max_stream_data_bidi_remote:this.#w,initial_max_streams_bidi:this.#y})))}async openStream(){this.#h!==void 0&&this.#A>=this.#h&&(this.#n(ke(ca({unidirectional:!1,streamLimit:this.#h}))),await new Promise(n=>this.#g.push(n)));let e=this.#t;return this.#t=da(e),this.#A++,this.#R(e)}#R(e){let n=new Os(this,e,{sendWindow:this.#w,recvWindow:this.#w});return this.#i.set(e,n),n}#C(e){let n=this.#i.get(e);if(n)return n;if(Ss(e)===this.#e)return;let r=Math.floor(e/4)+1;if(r>this.#p)throw new $e(Fe.STREAM_LIMIT_ERROR,`peer referenced stream ${e} beyond the granted MAX_STREAMS limit (${this.#p})`);this.#E=Math.max(this.#E,r),n=this.#R(e);try{this.onStreamOpen?.(n)}catch(s){console.error("[qmux] onStreamOpen handler error:",s)}return n}getStream(e){return this.#i.get(e)}_maybeStreamClosed(e){let n=this.#i.get(e);!n||!n._isFullyClosed()||(this.#i.delete(e),Ss(e)!==this.#e&&this.#p-this.#E<=this.#y*(1-Rs)&&(this.#p=this.#E+this.#y,this.#n(ke(ia({unidirectional:!1,maxStreams:this.#p})))))}sendDatagram(e){this.#n(ke(la(e)))}receiveBytes(e){let n;try{n=this.#r.feed(e)}catch(r){this.#b(r);return}for(let r of n)if(this.#k(r),this.#s)break}#k(e){let n;try{n=fa(e)}catch(r){r instanceof $e&&this.#_(r.errorCode,r.message),this.#b(r);return}for(let r of n)try{this.#I(r)}catch(s){s instanceof $e&&this.#_(s.errorCode,s.message),this.#b(s);return}}#I(e){switch(e.frameType){case"QX_TRANSPORT_PARAMETERS":{e.params.initial_max_data!==void 0&&(this.#a=Number(e.params.initial_max_data)-this.#o),this.#h=e.params.initial_max_streams_bidi!==void 0?Number(e.params.initial_max_streams_bidi):ur.initialMaxStreamsBidi,this.#T();break}case"STREAM":{let n=this.#C(Number(e.streamId));if(!n)break;let r=n._receiveStreamData(Number(e.offset),e.data,e.fin);this.#S(r);break}case"RESET_STREAM":{this.#C(Number(e.streamId))?._receiveReset(Number(e.errorCode),Number(e.finalSize),0);break}case"RESET_STREAM_AT":{this.#C(Number(e.streamId))?._receiveReset(Number(e.errorCode),Number(e.finalSize),Number(e.reliableSize));break}case"STOP_SENDING":{this.#i.get(Number(e.streamId))?.reset(Fe.NO_ERROR,0);break}case"MAX_DATA":{let n=Number(e.maxData)-this.#o;n>this.#a&&(this.#a=n,this.#x());break}case"MAX_STREAM_DATA":{this.#i.get(Number(e.streamId))?._grantSendWindow(Number(e.maxStreamData));break}case"MAX_STREAMS":{e.unidirectional||(this.#h=Number(e.maxStreams),this.#T());break}case"DATA_BLOCKED":case"STREAM_DATA_BLOCKED":case"STREAMS_BLOCKED":break;case"CONNECTION_CLOSE":{this.#s=!0;try{this.onClose?.(e.errorCode,e.reason)}catch(n){console.error("[qmux] onClose handler error:",n)}break}case"DATAGRAM":{try{this.onDatagram?.(e.data)}catch(n){console.error("[qmux] onDatagram handler error:",n)}break}case"PADDING":break;default:break}}close(e=Fe.NO_ERROR,n=""){this.#s||(this.#n(ke(xs({application:!0,errorCode:e,reason:n}))),this.#s=!0)}destroy(e){this.#s=!0;for(let n of this.#i.values())n._destroy(e);this.#i.clear()}#_(e,n){if(!this.#s){try{this.#n(ke(xs({application:!1,errorCode:e,reason:n})))}catch{}this.#s=!0}}#b(e){try{this.onError?.(e)}catch(n){console.error("[qmux] onError handler error:",n)}}#T(){for(;this.#g.length>0&&(this.#h===void 0||this.#A<this.#h);)this.#g.shift()()}#x(){for(let e of this.#i.values())e._recheckSendWindow()}#S(e){if(e<=0)return;if(this.#u+=e,this.#f-this.#u<=this.#l*(1-Rs)){let r=this.#u+this.#l;this.#f=r,this.#n(ke(ra(r)))}}_sendFrame(e,n){this.#n(ke(e)),this.#o+=n}_connSendWindow(){return this.#a}_reserveConnSendWindow(e){this.#a-=e}_sendDataBlocked(){this.#c!==this.#o&&(this.#c=this.#o,this.#n(ke(oa(this.#o+this.#a))))}};var bu=Object.freeze({CONTROL:1,DATA:2,OPEN_STREAM:3,CLOSE_STREAM:4}),hr=class{id;readable;writable;constructor(e){this.id=e.id;let n=null;this.readable=new ReadableStream({pull:r=>{if(n)try{r.error(n)}catch{}},start:r=>{e.onData=s=>{try{r.enqueue(s)}catch{}},e.onEnd=()=>{try{r.close()}catch{}},e.onReset=s=>{try{r.error(new Error(`Stream ${e.id} was reset by peer (error code ${s})`))}catch{}},e.onDestroy=s=>{if(n=s,r.desiredSize===null||r.desiredSize>0)try{r.error(s)}catch{}}},cancel:()=>{e.stopSending()}}),this.writable=new WritableStream({write:async r=>{let s=r instanceof Uint8Array?r:new Uint8Array(r);await e.write(s)},close:async()=>{await e.close()},abort:()=>{e.reset()}})}},Au=1,Me=class extends yn{#e=null;#n=null;#r=null;#i=new je;#t=!1;#s=new ir(e=>this.#a(e));#o;constructor({WebSocket:e}={}){super(),this.#o=e}async _doConnect(e){return this.#i.reset(),this.#t=!1,this.#s.clear(),this.#r=null,new Promise((n,r)=>{let s=e.replace(/^wsh:\/\//,"wss://").replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://"),i=new(this.#o??WebSocket)(s);i.binaryType="arraybuffer",this.#e=i;let o=new Ft({isClient:!0,send:a=>this.#u(a)});this.#n=o,o.onStreamOpen=a=>{let c=new hr(a);this._emitStreamOpen({readable:c.readable,writable:c.writable,id:a.id})},o.onError=a=>this._emitError(a),o.onClose=(a,c)=>{this.#c(a,c||"peer sent CONNECTION_CLOSE")},i.addEventListener("open",async()=>{try{o.sendHandshake();let a=await o.openStream();a.onData=c=>this.#s.push(c),a.onReset=c=>{this._emitError(new Error(`control stream reset by peer (error code ${c})`))},this.#r=a,n()}catch(a){r(a)}},{once:!0}),i.addEventListener("error",()=>{this.state==="connecting"?r(new Error("WebSocket connection failed")):this._emitError(new Error("WebSocket error"))}),i.addEventListener("close",a=>{this.#c(null,`WebSocket closed: ${a.code} ${a.reason}`)}),i.addEventListener("message",a=>{if(typeof a.data=="string"){this._emitError(new Error("Received text WebSocket frame; expected binary"));return}o.receiveBytes(new Uint8Array(a.data))})})}async _doClose(){this.#t=!0;try{this.#n?.close()}catch{}try{this.#n?.destroy(new Error("Transport closed"))}catch{}if(this.#e){try{this.#e.close(1e3,"client close")}catch{}this.#e=null}this.#i.reset()}async _doSendControl(e){if(!this.#r)throw new Error("Control stream is not open");let n=Nt(e);await this.#r.write(n)}async _doOpenStream(){let e=await this.#n.openStream();e.announce();let n=new hr(e);return{readable:n.readable,writable:n.writable,id:e.id}}async#a(e){let n;try{n=this.#i.feed(e)}catch(r){this._emitError(r),r instanceof ft&&this.close().catch(()=>{});return}await As(n,r=>this._emitControl(r))}#c(e,n){if(this.state==="closed")return;let r=new Error(n);this.#n?.destroy(r),this._setState("closed"),this.#t||this._emitError(r),this.#s.busy?this.#s.idle().then(()=>this._emitClose(),()=>this._emitClose()):this._emitClose()}tlsExporter(e,n){try{let r=this.#e?._socket;if(!r||typeof r.exportKeyingMaterial!="function"||r.encrypted!==!0)return null;let s=r.exportKeyingMaterial(n,e);return s&&s.length===n?new Uint8Array(s.buffer,s.byteOffset,s.byteLength).slice():null}catch{return null}}#u(e){if(!this.#e||this.#e.readyState!==Au)throw new Error("WebSocket is not open");this.#e.send(e)}};var Tu=new TextEncoder;function pa(t){return t instanceof Uint8Array?t:Tu.encode(String(t))}var fr=class{#e;#n;#r=null;#i=null;#t=null;#s=null;#o=[];#a=[];#c=!1;constructor(e,n){this.#e=e,this.#n=n}async write(e){await this.#e(yt({channelId:this.#n,data:pa(e)}))}async writeEncrypted({nonce:e,ciphertext:n,sessionId:r}){await this.#e(Mt({channelId:this.#n,nonce:e,ciphertext:n,sessionId:r}))}async read(){return this.#o.length>0?{done:!1,value:this.#o.shift()}:this.#c?{done:!0,value:void 0}:await new Promise((e,n)=>{this.#a.push({resolve:e,reject:n})})}pushData(e){let n=e instanceof Uint8Array?e:pa(e),r=this.#a.shift();if(r){r.resolve({done:!1,value:n});return}this.#o.push(n)}close(){if(!this.#c)for(this.#c=!0;this.#a.length>0;)this.#a.shift()?.resolve({done:!0,value:void 0})}get lastEchoAck(){return this.#r?{...this.#r}:null}get lastEchoState(){return this.#i?{...this.#i}:null}get lastTermSync(){return this.#t?{...this.#t,state_hash:this.#t.state_hash?.slice?.()||this.#t.state_hash}:null}get lastTermDiff(){return this.#s?{...this.#s,patch:this.#s.patch?.slice?.()||this.#s.patch}:null}recordEchoAck(e){return this.#r={channel_id:this.#n,echo_seq:e.echo_seq??0},this.lastEchoAck}recordEchoState(e){return this.#i={channel_id:this.#n,echo_seq:e.echo_seq??0,cursor_x:e.cursor_x??0,cursor_y:e.cursor_y??0,pending:e.pending??0},this.lastEchoState}recordTermSync(e){return this.#t={channel_id:this.#n,frame_seq:e.frame_seq??0,state_hash:e.state_hash?.slice?.()||e.state_hash||new Uint8Array},this.lastTermSync}recordTermDiff(e){return this.#s={channel_id:this.#n,frame_seq:e.frame_seq??0,base_seq:e.base_seq??0,patch:e.patch?.slice?.()||e.patch||new Uint8Array},this.lastTermDiff}};var ya=new TextEncoder;function xu(t){if(!Number.isInteger(t)||t<0)throw new Error(`e2e-frame: counter must be a non-negative integer, got ${t}`);let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!1),e}function Su(t,e){if(!(e instanceof Uint8Array)||e.length!==4)throw new Error("e2e-frame: roleTag must be a 4-byte Uint8Array");let n=new Uint8Array(12);return n.set(xu(t),0),n.set(e,8),n}async function Et(t,e,n,r,s){if(!t||typeof t!="object")throw new Error("e2e-frame: sealFrame requires a CryptoKey");let i=Su(r,n),o=ya.encode(e),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:o},t,s));return{nonce:i,ciphertext:a}}async function wt(t,e,n,{nonce:r,ciphertext:s,expectedRoleTag:i}){if(!t||typeof t!="object")throw new Error("e2e-frame: openFrame requires a CryptoKey");if(!(r instanceof Uint8Array)||r.length!==12)throw new Error("e2e-frame: nonce must be a 12-byte Uint8Array");if(!(i instanceof Uint8Array)||i.length!==4)throw new Error("e2e-frame: openFrame requires expectedRoleTag, a 4-byte Uint8Array");let o=r.subarray(8);for(let l=0;l<4;l+=1)if(o[l]!==i[l])throw new Error("e2e-frame: role tag mismatch -- this frame was sealed by the wrong side of the session");let a=Number(new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,!1));if(a!==n)throw new Error(`e2e-frame: replay/reorder detected -- expected counter ${n}, got ${a}`);let c=ya.encode(e);try{return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:r,additionalData:c},t,s))}catch(l){throw new Error(`e2e-frame: authentication failed while opening frame (${l.message})`)}}var De=Object.freeze({initiator:Uint8Array.from([105,110,105,116]),responder:Uint8Array.from([114,101,115,112])});var mt=4,gt=12,Ru=16,Ou=16*1024,Cu=64*1024,Ea=Cu+Ru,dr=class extends Error{constructor(e){super(e),this.name="StreamTornChunkError"}},En=class extends Error{constructor(e){super(e),this.name="StreamAuthenticationError"}};function ma(t,e){if(!(t instanceof Uint8Array)||t.length!==gt)throw new Error(`stream-frame: nonce must be a ${gt}-byte Uint8Array`);if(!(e instanceof Uint8Array))throw new Error("stream-frame: ciphertext must be a Uint8Array");let n=new Uint8Array(mt+gt+e.length);return new DataView(n.buffer).setUint32(0,e.length,!1),n.set(t,mt),n.set(e,mt+gt),n}var pr=class{#e=new Uint8Array(0);#n=0;#r=0;feed(e){e&&e.length>0&&this.#i(e);let n=[];for(;;){let r=this.#t();if(r===null)break;n.push(r)}return this.#n===this.#r&&(this.#n=0,this.#r=0),n}finish(){let e=this.#r-this.#n;if(e>0)throw new dr(`stream-frame: stream ended with ${e} torn (incomplete) chunk bytes buffered`)}#i(e){let n=this.#r-this.#n,r=n+e.length;if(r>this.#e.length-this.#n){let s=Math.max(r,this.#e.length*2,4096),i=new Uint8Array(s);i.set(this.#e.subarray(this.#n,this.#r),0),this.#e=i,this.#r=n,this.#n=0}this.#e.set(e,this.#r),this.#r+=e.length}#t(){let e=this.#r-this.#n;if(e<mt+gt)return null;let r=new DataView(this.#e.buffer,this.#e.byteOffset+this.#n,mt).getUint32(0,!1);if(r>Ea)throw new dr(`stream-frame: chunk length ${r} exceeds max ${Ea} -- corrupt or malicious framing`);let s=mt+gt+r;if(e<s)return null;let i=this.#n+mt,o=i+gt,a=this.#e.slice(i,o),c=this.#e.slice(o,this.#n+s);return this.#n+=s,{nonce:a,ciphertext:c}}},wa=Object.freeze({pty:Object.freeze({maxBytes:4*1024,maxDelayMs:6}),exec:Object.freeze({maxBytes:Ou,maxDelayMs:30})});function ga(t,e){if(e===!1)return null;let n=wa[t]||wa.exec;if(e&&typeof e=="object"){let r=Number.isFinite(e.maxBytes)&&e.maxBytes>0?e.maxBytes:n.maxBytes,s=Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0?e.maxDelayMs:n.maxDelayMs;return{maxBytes:r,maxDelayMs:s}}return{...n}}var yr=class{#e;#n;#r;#i=[];#t=0;#s=null;#o=Promise.resolve();constructor({maxBytes:e,maxDelayMs:n},r){if(!(e>0))throw new Error("stream-frame: WriteCoalescer requires a positive maxBytes");if(!(n>=0))throw new Error("stream-frame: WriteCoalescer requires a non-negative maxDelayMs");if(typeof r!="function")throw new Error("stream-frame: WriteCoalescer requires an onFlush callback");this.#e=e,this.#n=n,this.#r=r}write(e){return this.#i.push(e),this.#t+=e.length,this.#t>=this.#e?this.flush():(this.#s===null&&(this.#s=setTimeout(()=>{this.#s=null,this.flush().catch(()=>{})},this.#n),typeof this.#s.unref=="function"&&this.#s.unref()),this.#o)}flush(){if(this.#s!==null&&(clearTimeout(this.#s),this.#s=null),this.#i.length===0)return this.#o;let e=Iu(this.#i,this.#t);return this.#i=[],this.#t=0,this.#o=this.#o.then(()=>this.#r(e)),this.#o}};function Iu(t,e){if(t.length===1)return t[0];let n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.length;return n}var Nu="opening",_a="active",Se="closed",Lu=300,ba=new TextEncoder,wn=class{id;kind;channelId;#e=Nu;#n;#r="stream";#i=[];#t;#s;#o=0;#a;#c=null;#u=!1;#l=null;#f=null;#y=null;#A=null;#h=0;#g=0;#E=null;#p=null;#w=null;#R=new AbortController;#C=null;#k=null;#I=null;#_=null;onData=null;onStderr=null;onExit=null;onClose=null;onEchoAck=null;onEchoState=null;onTermSync=null;onTermDiff=null;#b=null;#T=null;#x=null;#S=null;#P=[];#O=null;constructor(e,n,r,s,{dataMode:i="stream",capabilities:o=[],sessionId:a,resumeToken:c,stderrChannelId:l}={}){this.#n=e,this.channelId=n,this.stderrChannelId=Number.isSafeInteger(l)?l:void 0,this.#a=r,this.kind=s,this.id=String(n),this.#r=i==="virtual"?"virtual":"stream",this.#i=Array.isArray(o)?[...o]:[],this.#t=a,this.#s=c}get sessionId(){return this.#t}get resumeToken(){return this.#s}get seq(){return this.#o}_setSeq(e){this.#o=e}get state(){return this.#e}get exitCode(){return this.#k}get dataMode(){return this.#r}get capabilities(){return[...this.#i]}get lastEchoAck(){return this.#b?{...this.#b}:null}get lastEchoState(){return this.#T?{...this.#T}:null}get lastTermSync(){return this.#x?{...this.#x,state_hash:this.#x.state_hash?.slice?.()||this.#x.state_hash}:null}get lastTermDiff(){return this.#S?{...this.#S,patch:this.#S.patch?.slice?.()||this.#S.patch}:null}_bind(e,n){if(this.#r!=="stream")throw new Error("Cannot bind transport streams to a virtual session");if(this.#e===Se)throw new Error("Cannot bind streams to a closed session");this.#w=e,this.#c=n.getWriter(),this.#e=_a,this.#C=this._pumpDataStream()}_activateVirtual(e){if(this.#r!=="virtual")throw new Error("Cannot activate virtual backend for a stream session");if(this.#e===Se)throw new Error("Cannot activate a closed session");this.#l=new fr(e,this.channelId),this.#e=_a}get e2eEnabled(){return this.#f!==null}enableE2E(e,{role:n,coalesce:r}={}){if(!e||typeof e!="object")throw new Error("enableE2E: sharedSecret must be a CryptoKey (see WshClient.initiateE2E)");if(n!=="initiator"&&n!=="responder")throw new Error("enableE2E: opts.role must be 'initiator' or 'responder'");if(!this.#t)throw new Error("enableE2E: session has no server-assigned session_id to bind as AAD -- was OPEN_OK missing session_id?");if(this.#f=e,this.#y=De[n],this.#A=n==="initiator"?De.responder:De.initiator,this.#h=0,this.#g=0,this.#r==="stream"){this.#E=new pr;let s=ga(this.kind,r);this.#p=s?new yr(s,i=>this.#M(i)):null}else this.#E=null,this.#p=null}async#M(e){if(this.#c===null)throw new Error("Session not yet bound \u2014 stdin writer unavailable");let n=this.#h++,{nonce:r,ciphertext:s}=await Et(this.#f,this.#t,this.#y,n,e);await this.#c.write(ma(r,s))}async#N(e){let n;try{n=this.#E.feed(e)}catch(s){return console.error("[wsh:session] stream E2E framing error:",s),null}let r=[];for(let{nonce:s,ciphertext:i}of n){let o=this.#g++;try{let a=await wt(this.#f,this.#t,o,{nonce:s,ciphertext:i,expectedRoleTag:this.#A});r.push(a)}catch(a){return console.error("[wsh:session] stream E2E chunk failed authentication:",new En(a.message)),null}}return r}async write(e){if(this.#e===Se)throw new Error("Cannot write to a closed session");if(this.#r==="virtual"){if(this.#l===null)throw new Error("Session not yet activated \u2014 virtual backend unavailable");if(this.#u)throw new Error("Cannot write to a session whose stdin is closed");if(this.#i.includes("stdin-eof")&&(typeof e=="string"?e.length===0:e.byteLength===0))return;if(this.#f!==null){let r=typeof e=="string"?ba.encode(e):e,s=this.#h++,{nonce:i,ciphertext:o}=await Et(this.#f,this.#t,this.#y,s,r);await this.#l.writeEncrypted({nonce:i,ciphertext:o,sessionId:this.#t});return}await this.#l.write(e);return}if(this.#c===null)throw new Error("Session not yet bound \u2014 stdin writer unavailable");if(this.#u)throw new Error("Cannot write to a session whose stdin is closed");let n=typeof e=="string"?ba.encode(e):e;if(this.#f!==null){this.#p?await this.#p.write(n):await this.#M(n);return}await this.#c.write(n)}async closeStdin(){if(!this.#u&&this.#e!==Se){if(this.#r==="virtual"&&this.#i.includes("stdin-eof")){if(this.#l===null)throw new Error("Session not yet activated \u2014 virtual backend unavailable");if(this.#f!==null)throw new Error("closeStdin() is not supported on an end-to-end encrypted virtual session");this.#u=!0,await this.#l.write(new Uint8Array(0));return}if(this.#r!=="stream")throw new Error(`closeStdin() needs a stream-mode session or a host advertising "exec-pipes"; this session's host carries stdin as control messages, which have no EOF`);if(this.#c===null)throw new Error("Session not yet bound \u2014 stdin writer unavailable");this.#u=!0,this.#p&&await this.#p.flush(),await this.#c.close()}}async read(){if(this.#r==="virtual"){if(this.#l===null){if(this.#e===Se)return null;throw new Error("Session not yet activated \u2014 virtual backend unavailable")}let{done:n,value:r}=await this.#l.read();return n?null:r||new Uint8Array}if(!this.#w)throw new Error("Session not yet bound \u2014 stdout stream unavailable");let e=this.#w.getReader();try{let{done:n,value:r}=await e.read();return n?null:r||new Uint8Array}finally{e.releaseLock()}}async resize(e,n){this.#D("resize"),await this.#n.sendControl(qi({channelId:this.channelId,cols:e,rows:n}))}async signal(e){this.#D("signal"),await this.#n.sendControl(Xi({channelId:this.channelId,signal:e}))}async close(){if(this.#e!==Se){this.#e=Se,this.#R.abort(),this.#U();try{await this.#n.sendControl(Lt({channelId:this.channelId}))}catch{}if(this.#r==="stream"){if(this.#p)try{await this.#p.flush()}catch(e){console.error("[wsh:session] failed to flush coalesced stream E2E writes on close:",e)}try{await this.#c?.close()}catch{}this.#C&&await this.#C.catch(()=>{})}this.#c=null,this.#w=null,this.#L(null),this.#$()}}_handleControlMessage(e){switch(e.type){case f.SESSION_DATA:{if(this.stderrChannelId!==void 0&&e.channel_id===this.stderrChannelId){if(e.data&&e.data.byteLength>0)try{this.onStderr?.(e.data)}catch(n){console.error("[wsh:session] onStderr handler error:",n)}break}if(e.data&&e.data.byteLength>0){this.kind!=="rpc"&&this.#l?.pushData(e.data);try{this.#o+=e.data.byteLength,this.onData?.(e.data)}catch(n){console.error("[wsh:session] onData handler error:",n)}}break}case f.ENCRYPTED_FRAME:{if(this.#f===null){console.error("[wsh:session] received EncryptedFrame but E2E is not enabled on this session \u2014 dropping");break}if(e.session_id!==this.#t){console.error("[wsh:session] EncryptedFrame session_id mismatch \u2014 dropping (possible splice attempt)");break}let n=this.#g++;wt(this.#f,this.#t,n,{nonce:e.nonce,ciphertext:e.ciphertext,expectedRoleTag:this.#A}).then(r=>{this.#l?.pushData(r);try{this.#o+=r.byteLength,this.onData?.(r)}catch(s){console.error("[wsh:session] onData handler error:",s)}}).catch(r=>{console.error("[wsh:session] failed to open EncryptedFrame:",r)});break}case f.FILE_CHUNK:{if(this.#O){let{resolve:n}=this.#O;this.#O=null,n(e)}else this.#P.push(e);break}case f.EXIT:{this.#k=e.code??-1;try{this.onExit?.(this.#k)}catch(n){console.error("[wsh:session] onExit handler error:",n)}break}case f.CLOSE:{this.#U(),this.#v();break}case f.RESIZE:break;case f.ECHO_ACK:this.#b=this.#l?.recordEchoAck(e)||{channel_id:this.channelId,echo_seq:e.echo_seq??0};try{this.onEchoAck?.(this.lastEchoAck)}catch(n){console.error("[wsh:session] onEchoAck handler error:",n)}break;case f.ECHO_STATE:this.#T=this.#l?.recordEchoState(e)||{channel_id:this.channelId,echo_seq:e.echo_seq??0,cursor_x:e.cursor_x??0,cursor_y:e.cursor_y??0,pending:e.pending??0};try{this.onEchoState?.(this.lastEchoState)}catch(n){console.error("[wsh:session] onEchoState handler error:",n)}break;case f.TERM_SYNC:this.#x=this.#l?.recordTermSync(e)||{channel_id:this.channelId,frame_seq:e.frame_seq??0,state_hash:e.state_hash?.slice?.()||e.state_hash||new Uint8Array};try{this.onTermSync?.(this.lastTermSync)}catch(n){console.error("[wsh:session] onTermSync handler error:",n)}break;case f.TERM_DIFF:this.#S=this.#l?.recordTermDiff(e)||{channel_id:this.channelId,frame_seq:e.frame_seq??0,base_seq:e.base_seq??0,patch:e.patch?.slice?.()||e.patch||new Uint8Array};try{this.onTermDiff?.(this.lastTermDiff)}catch(n){console.error("[wsh:session] onTermDiff handler error:",n)}break;default:break}}async _readFileChunk(){return this.#P.length>0?this.#P.shift():this.#e===Se?null:new Promise((e,n)=>{this.#O={resolve:e,reject:n}})}#L(e){if(this.#O){let{resolve:n}=this.#O;this.#O=null,n(e)}}async _pumpDataStream(){if(!this.#w)return;let e=this.#w.getReader();try{for(;!this.#R.signal.aborted;){let{done:n,value:r}=await e.read();if(n){if(this.#f!==null&&this.#E)try{this.#E.finish()}catch(s){console.error("[wsh:session] stream E2E torn chunk at stream end:",s)}break}if(r&&r.byteLength>0)if(this.#f!==null&&this.#E){let s=await this.#N(r);if(s===null){this.#_=new En("wsh: stream authentication failed -- session torn down"),this.#U(),this.#v();return}for(let i of s)try{this.#o+=i.byteLength,this.onData?.(i)}catch(o){console.error("[wsh:session] onData handler error:",o)}}else try{this.#o+=r.byteLength,this.onData?.(r)}catch(s){console.error("[wsh:session] onData handler error:",s)}}}catch(n){this.#R.signal.aborted||console.error("[wsh:session] data stream read error:",n)}finally{e.releaseLock()}this.#e!==Se&&this.#I===null&&(this.#I=setTimeout(()=>{this.#I=null,this.#v()},Lu),this.#I?.unref?.())}#v(){this.#e!==Se&&(this.#e=Se,this.#R.abort(),this.#l?.close(),this.#q(),this.#L(null),this.#$())}#U(){this.#I!==null&&(clearTimeout(this.#I),this.#I=null)}#q(){try{this.#c?.close()?.catch?.(()=>{})}catch{}this.#c=null,this.#w=null,this.#l?.close()}get closeReason(){return this.#_}#$(){try{this.onClose?.(this.#_)}catch(e){console.error("[wsh:session] onClose handler error:",e)}this.onClose=null}#D(e){if(this.#e===Se)throw new Error(`Cannot ${e}: session is closed`)}};var $t="mcp-call-id",mn="mcp-cancel",Cs="stream-announce",gn="exec-pipes",Qe="targets",_n="e2e-session",Er="e2e-session-required";var Ta=new TextEncoder,ku=Ta.encode("wsh-channel-binding-v1\0"),Is="channel-binding:",Mu="channel-binding-required",xa="EXPORTER-wsh-channel-binding",Sa=32,Kt=Object.freeze(["cert-hash","host","tls-exporter"]),Aa=t=>{let e=new Uint8Array(4+t.length);return new DataView(e.buffer).setUint32(0,t.length),e.set(t,4),e};async function Ra(t){let e=[ku];for(let s of Kt){let i=t?.[s];i instanceof Uint8Array&&i.length&&e.push(Aa(Ta.encode(s)),Aa(i))}if(e.length===1)return new Uint8Array(0);let n=new Uint8Array(e.reduce((s,i)=>s+i.length,0)),r=0;for(let s of e)n.set(s,r),r+=s.length;return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}function Ns(t){let e=new Set;for(let n of t??[])typeof n=="string"&&n.startsWith(Is)&&e.add(n.slice(Is.length));return Kt.filter(n=>e.has(n))}function Oa(t,{required:e=!1}={}){return[...t.map(n=>Is+n),...e?[Mu]:[]]}async function Ca(t,e){let n=Ns(t).filter(s=>e?.[s]instanceof Uint8Array&&e[s].length),r={};for(let s of n)r[s]=e[s];return{binding:await Ra(r),kinds:n}}async function Ia(t,{required:e=!1}={}){let n=Kt.filter(o=>t[o]?.length),r=Array.isArray(e)?e:[],s=[],i=[];for(let o=0;o<1<<n.length;o++)i.push(n.filter((a,c)=>o&1<<c));for(let o of i){if(o.length===0&&e||!r.every(c=>o.includes(c)))continue;let a=[{}];for(let c of o)a=a.flatMap(l=>t[c].map(h=>({...l,[c]:h})));for(let c of a)s.push({binding:await Ra(c),kinds:o})}return s}var At={name:"ML-KEM-768"},Or=1184,oc=1088;var uh=64,js=null,Rr=null;async function Vs(){return Rr||(Rr=Promise.resolve().then(()=>(ic(),sc)).catch(t=>{throw Rr=null,new Error(`Hybrid PQ key exchange requires either native WebCrypto ML-KEM-768 support (Node 24.7+, or a browser implementing the experimental draft) or the optional "@noble/post-quantum" package installed as a fallback. (${t.message})`)})),Rr}async function hh(){try{let{publicKey:t,privateKey:e}=await crypto.subtle.generateKey(At,!0,["encapsulateBits","decapsulateBits"]),{ciphertext:n,sharedKey:r}=await crypto.subtle.encapsulateBits(At,t),s=await crypto.subtle.decapsulateBits(At,e,n);return fh(new Uint8Array(r),new Uint8Array(s))}catch{return!1}}function fh(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function dh(){try{let t=globalThis.process?.env?.WSH_MLKEM_BACKEND;return t==="noble"||t==="native"?t:null}catch{return null}}async function Ys(){let t=dh();return t||(js||(js=hh().then(e=>e?"native":"noble")),js)}async function ac(t){return crypto.subtle.importKey("raw-seed",t,At,!1,["decapsulateBits"])}async function ph(t,e){if(e==="native"){let r=await ac(t),s=await crypto.subtle.getPublicKey(r,["encapsulateBits"]);return new Uint8Array(await crypto.subtle.exportKey("raw-public",s))}let{ml_kem768:n}=await Vs();return n.keygen(t).publicKey}async function Cr(){let t=new Uint8Array(uh);crypto.getRandomValues(t);let e=await Ys();return{publicKey:await ph(t,e),secretKeySeed:t}}async function Ir(t){if(t.length!==Or)throw new Error(`ML-KEM-768 public key must be ${Or} bytes, got ${t.length}`);if(await Ys()==="native"){let o=await crypto.subtle.importKey("raw-public",t,At,!1,["encapsulateBits"]),{ciphertext:a,sharedKey:c}=await crypto.subtle.encapsulateBits(At,o);return{ciphertext:new Uint8Array(a),sharedSecret:new Uint8Array(c)}}let{ml_kem768:n}=await Vs(),r=new Uint8Array(32);crypto.getRandomValues(r);let{cipherText:s,sharedSecret:i}=n.encapsulate(t,r);return{ciphertext:s,sharedSecret:i}}async function Nr(t,e){if(e.length!==oc)throw new Error(`ML-KEM-768 ciphertext must be ${oc} bytes, got ${e.length}`);if(await Ys()==="native"){let s=await ac(t),i=await crypto.subtle.decapsulateBits(At,s,e);return new Uint8Array(i)}let{ml_kem768:r}=await Vs();return r.decapsulate(e,r.keygen(t).secretKey)}var cc="X25519",Lr="X25519+ML-KEM-768",lc="e2e",Xs="e2e-sign",yh=new TextEncoder().encode("wsh-e2e-keyexchange-v1\0"),Nn=new TextEncoder,Eh=8,wh=15e3;function Js(t,e){let n=Math.min(t.length,e.length);for(let r=0;r<n;r++)if(t[r]!==e[r])return t[r]-e[r];return t.length-e.length}async function kr(t,e){let n=new Uint8Array(t.length+e.length);n.set(t,0),n.set(e,t.length);let r=await crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveBits"]),s=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:Nn.encode("wsh-hybrid-e2e-v1")},r,256);return new Uint8Array(s)}var Ze=t=>{let e=new Uint8Array(4+t.length);return new DataView(e.buffer).setUint32(0,t.length),e.set(t,4),e};function uc({sessionId:t,algorithm:e,initiatorKey:n,responderKey:r}){let s=[yh,Ze(Nn.encode(t)),Ze(Nn.encode(e)),Ze(n),Ze(r)],i=new Uint8Array(s.reduce((a,c)=>a+c.length,0)),o=0;for(let a of s)i.set(a,o),o+=a.length;return i}var mh=new TextEncoder().encode("wsh-e2e-keyexchange-init-v1\0");function Qs({sessionId:t,algorithm:e,initiatorKey:n,responderIdentity:r}){let s=[mh,Ze(Nn.encode(t)),Ze(Nn.encode(e)),Ze(n),Ze(r)],i=new Uint8Array(s.reduce((a,c)=>a+c.length,0)),o=0;for(let a of s)i.set(a,o),o+=a.length;return i}async function gh(t,e,n){if(!(e instanceof Uint8Array)||e.length!==64)return!1;try{let r=t instanceof Uint8Array?await pe(t):t;return await Le(r,e,Qs(n))}catch{return!1}}async function hc(t,e,n){if(!(e instanceof Uint8Array)||e.length!==64)return!1;try{let r=t instanceof Uint8Array?await pe(t):t;return await Le(r,e,uc(n))}catch{return!1}}var Ln=class{#e;#n;#r=new Map;constructor({signKey:e=null,hybrid:n=!0,identity:r=null,initiator:s=null}={}){this.#e=e,this.#n=n,this.#i=r,this.#t=s}#i;#t;get signs(){return!!this.#e}close(){for(let e of this.#r.values())clearTimeout(e.timer);this.#r.clear()}async respond(e,n){let r=e.session_id;if(typeof r!="string"||!r)throw new Error("KeyExchange without a session_id");return e.public_key===void 0&&e.kem_ciphertext!==void 0?this.#o(e,r):this.#s(e,r,n)}async#s(e,n,r){let s=[],i=async S=>{r?await r(S):s.push(S)},o=e.algorithm;if(o!==cc&&o!==Lr)throw new Error(`unsupported E2E algorithm ${JSON.stringify(o)}`);let a=e.public_key;if(!(a instanceof Uint8Array)||a.length!==32)throw new Error("KeyExchange public_key must be a 32-byte X25519 key");let c=e.kem_public_key,l=o===Lr&&this.#n&&c instanceof Uint8Array&&c.length===Or,h=!1;if(this.#t){if(e.signature!==void 0){if(h=!!this.#i&&await gh(this.#t.publicKey,e.signature,{sessionId:n,algorithm:o,initiatorKey:a,responderIdentity:this.#i}),!h)throw Object.assign(new Error("KeyExchange initiator signature does not verify"),{code:"E2E_INITIATOR_UNAUTHENTICATED"})}else if(this.#t.require)throw Object.assign(new Error("KeyExchange without the initiator signature this host requires"),{code:"E2E_INITIATOR_UNAUTHENTICATED"})}this.#a(n);let d=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"]),w=new Uint8Array(await crypto.subtle.exportKey("raw",d.publicKey)),y=null;if(l)try{y=await Cr()}catch{y=null}let _=!!y,E={algorithm:_?Lr:cc,publicKey:w,sessionId:n,kemPublicKey:y?.publicKey};if(this.#e){let S=uc({sessionId:n,algorithm:o,initiatorKey:a,responderKey:w});E.signature=typeof this.#e.sign=="function"?await this.#e.sign(S):await nr(this.#e,S)}await i(kt(E));let g=await crypto.subtle.importKey("raw",a,{name:"X25519"},!1,[]),A=new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:g},d.privateKey,256));if(!_)return{replies:s,key:await qs(A),sessionId:n,hybrid:!1};if(Js(w,a)<0){let{ciphertext:S,sharedSecret:O}=await Ir(c);return await new Promise(N=>setTimeout(N,0)),await i(kt({algorithm:Lr,sessionId:n,kemCiphertext:S})),{replies:s,key:await qs(await kr(A,O)),sessionId:n,hybrid:!0}}for(;this.#r.size>=Eh;)this.#a(this.#r.keys().next().value);let I=setTimeout(()=>this.#a(n),wh);return I.unref?.(),this.#r.set(n,{sharedBits:A,localKem:y,timer:I}),{replies:s,sessionId:n,hybrid:!0}}async#o(e,n){let r=this.#r.get(n);if(!r)throw new Error("unexpected KeyExchange ciphertext (no hybrid exchange in progress for this session)");this.#a(n);let s=await Nr(r.localKem.secretKeySeed,new Uint8Array(e.kem_ciphertext));return{replies:[],key:await qs(await kr(r.sharedBits,s)),sessionId:n,hybrid:!0}}#a(e){let n=this.#r.get(e);n&&(clearTimeout(n.timer),this.#r.delete(e))}};function qs(t){return crypto.subtle.importKey("raw",t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var Pe="operator-proof",Zs="e2e-sealed",Gt=new TextEncoder,_h=Gt.encode("wsh-reverse-challenge-v1\0"),bh=Gt.encode("wsh-operator-proof-v1\0"),Ah=32,Ke=t=>{let e=new Uint8Array(4+t.length);return new DataView(e.buffer).setUint32(0,t.length),e.set(t,4),e},dc=t=>{let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e},pc=t=>t instanceof Uint8Array&&t.length===32,fc=(t,e=256)=>typeof t=="string"&&t.length>0&&t.length<=e;function Th({peerPublicKey:t,operatorFingerprint:e,nonce:n,sessionId:r}){return dc([_h,Ke(t),Ke(Gt.encode(e)),Ke(n),Ke(Gt.encode(r))])}function xh({peerPublicKey:t,operatorPublicKey:e,username:n,nonce:r,sessionId:s}){return dc([bh,Ke(t),Ke(e),Ke(Gt.encode(n)),Ke(r),Ke(Gt.encode(s))])}async function Sh(t,e,n){if(!pc(t)||!(e instanceof Uint8Array)||e.length!==64)return!1;try{return await Le(await pe(t),e,n)}catch{return!1}}async function yc(t,{target:e,ownFingerprint:n}){let r=o=>Object.assign(new Error(`reverse challenge refused: ${o}`),{code:"REVERSE_CHALLENGE_INVALID"});if(!pc(t.public_key)||!(t.nonce instanceof Uint8Array)||t.nonce.length!==Ah||!fc(t.session_id)||!fc(t.operator_fingerprint))throw r("malformed");let s=await oe(t.public_key);if(typeof e!="string"||!e||!s.startsWith(e))throw r("the key that signed it is not the peer that was asked for");if(t.operator_fingerprint!==n)throw r("the peer saw a different operator fingerprint than this connection's (the relay rewrote it)");if(!await Sh(t.public_key,t.signature,Th({peerPublicKey:t.public_key,operatorFingerprint:t.operator_fingerprint,nonce:t.nonce,sessionId:t.session_id})))throw r("the signature does not verify");return{peerPublicKey:t.public_key,peerFingerprint:s,nonce:t.nonce,sessionId:t.session_id}}async function Ec(t,e,n){let r=await t.sign(xh({peerPublicKey:e.peerPublicKey,operatorPublicKey:t.publicKeyRaw,username:n,nonce:e.nonce,sessionId:e.sessionId}));return{publicKey:t.publicKeyRaw,username:n,nonce:e.nonce,sessionId:e.sessionId,signature:r}}var wc=0,Tt=class{#e;#n;#r;#i;#t;#s=0;#o=0;#a=Promise.resolve();#c=Promise.resolve();constructor({key:e,sessionId:n,role:r,scope:s="bridge"}){if(s!=="bridge"&&s!=="session")throw new TypeError("SealedBridge: scope must be 'bridge' or 'session'");if(this.#n=s,r!=="initiator"&&r!=="responder")throw new TypeError("SealedBridge: role must be 'initiator' or 'responder'");this.#e=e,this.#r=n,this.#i=De[r],this.#t=De[r==="initiator"?"responder":"initiator"]}get sessionId(){return this.#r}isFrame(e){return e?.type===f.ENCRYPTED_FRAME&&e.channel_id===wc&&e.session_id===this.#r}seal(e){let n=this.#s++,r=this.#a.then(async()=>{let{nonce:s,ciphertext:i}=await Et(this.#e,this.#r,this.#i,n,Ve(e));return Mt({channelId:wc,nonce:s,ciphertext:i,sessionId:this.#r})});return this.#a=r.catch(()=>{}),r}open(e){let n=this.#c.then(async()=>{if(!this.isFrame(e))throw new Error("not a frame of this bridge");let r=await wt(this.#e,this.#r,this.#o,{nonce:e.nonce,ciphertext:e.ciphertext,expectedRoleTag:this.#t});this.#o+=1;let s=dt(r);if(!s||typeof s.type!="number"||s.type===f.RELAY_FORWARD||this.#n==="bridge"&&!Dt(s.type))throw new Error("sealed message of a type that may not cross a bridge");return s});return this.#c=n.catch(()=>{}),n}};var et="gateway-credit";var Wt=class{#e;#n;#r;#i=0;#t=[];#s=0;#o=null;#a=[];#c=!1;#u=!1;#l=!1;#f=null;#y=null;#A;#h;constructor(e){this.#e={window:262144,maxQueued:4*1024*1024,credit:!1,writeAfterRemoteClose:!1,graceMs:0,...e},this.#n=this.#e.credit?this.#e.window:1/0,this.#r=this.#e.credit?this.#e.window:1/0,this.#A=new Promise(n=>{this.#h=n})}get id(){return this.#e.id}get closed(){return this.#l}get remoteEnded(){return this.#u}get closedPromise(){return this.#A}get queuedBytes(){return this.#s}receive(e){if(this.#l||this.#u)return;let n=e.byteLength;if(n===0)return;if(this.#e.credit&&(this.#r-=n,this.#r<0))return this.#E("peer exceeded its credit");let r=this.#e.budget;if(this.#s+n>this.#e.maxQueued||r&&r.used+n>r.max)return this.#E("buffer limit exceeded");if(this.#s+=n,r&&(r.used+=n),this.#e.onData){this.#e.onData(e);return}this.#t.push(e),this.#o?.()}grant(e){!this.#e.credit||this.#l||!Number.isFinite(e)||e<=0||(this.#n=Math.min(this.#n+e,Number.MAX_SAFE_INTEGER),this.#p())}remoteClosed(e){if(!(this.#l||this.#u)){this.#u=!0,this.#o?.();try{this.#e.onRemoteClose?.(e)}catch{}if(this.#e.writeAfterRemoteClose||this.#p(),this.#c){this.#t.length===0&&this.#w(e);return}this.#e.graceMs>0&&(clearTimeout(this.#f),this.#f=setTimeout(()=>this.end("grace period over"),this.#e.graceMs),this.#f.unref?.())}}async write(e){let n=0;for(;n<e.byteLength;){this.#g();let r=Math.min(e.byteLength-n,65536);if(this.#e.credit){for(;this.#n<=0;)this.#g(),await new Promise(s=>this.#a.push(s));this.#g(),r=Math.min(r,this.#n),this.#n-=r}await this.#e.sendData(e.subarray(n,n+r)),n+=r}}#g(){if(this.#l||this.#c||this.#u&&!this.#e.writeAfterRemoteClose)throw new Error("gateway connection closed")}consumed(e){if(e<=0)return;let n=Math.min(e,this.#s);if(this.#s-=n,this.#e.budget&&(this.#e.budget.used-=n),this.#e.credit&&!this.#l&&!this.#u&&(this.#i+=n,this.#i>=this.#e.window/2)){let r=this.#i;this.#i=0,this.#r+=r;try{this.#e.sendCredit(r)}catch{}}}end(e){if(!(this.#l||this.#c)){this.#c=!0;try{this.#e.sendClose(e)}catch{}this.#p(),this.#u&&this.#t.length===0?this.#w(e):!this.#u&&this.#e.graceMs>0&&(this.#f=setTimeout(()=>this.destroy("grace period over"),this.#e.graceMs),this.#f.unref?.())}}destroy(e){if(!this.#l){if(!this.#c){this.#c=!0;try{this.#e.sendClose(e)}catch{}}this.#w(e)}}abandon(e){this.#l||(this.#c=!0,this.#w(e))}streams(){if(this.#y)return this.#y;let e=this,n=new ReadableStream({async pull(s){for(;e.#t.length===0&&!e.#u&&!e.#l;)await new Promise(i=>{e.#o=i});if(e.#o=null,e.#t.length){let i=e.#t.shift();s.enqueue(i),e.consumed(i.byteLength);return}s.close(),e.#c&&e.#w()},cancel(s){e.destroy(typeof s=="string"?s:void 0)}},{highWaterMark:0}),r=new WritableStream({write(s){return e.write(s instanceof Uint8Array?s:new Uint8Array(s))},close(){e.end()},abort(s){e.destroy(typeof s=="string"?s:void 0)}});return this.#y={readable:n,writable:r},this.#y}#E(e){this.destroy(e)}#p(){for(let e of this.#a.splice(0))e()}#w(e){if(!this.#l){this.#l=!0,clearTimeout(this.#f),this.#e.budget&&(this.#e.budget.used-=this.#s),this.#s=0,this.#t=[],this.#o?.(),this.#p();try{this.#e.onClose?.(e)}catch{}this.#h(e)}}};var zt="gateway-datagram";function Rh(t,e){let n=new Uint8Array(4+e.byteLength);return new DataView(n.buffer).setUint32(0,t,!1),n.set(e,4),n}function mc(t){return!(t instanceof Uint8Array)||t.byteLength<4?null:{id:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1),payload:t.subarray(4)}}var Oh=128,Mr=class{#e;#n=[];#r=null;#i=!1;#t=null;stats={sent:0,received:0,sentReliable:0,receivedReliable:0,sendDropped:0,receiveDropped:0};constructor(e){this.#e={oversize:"reliable",queueDatagrams:Oh,...e},this.channel=e.channel,this.closed=e.channel.closedPromise,this.closed.then(()=>{this.#i=!0,this.#r?.()})}get transport(){return this.#e.datagrams?"datagram":"stream"}get maxDatagramSize(){return this.#e.datagrams?Math.max(0,this.#e.datagrams.maxSize()-4):65507}async send(e){if(!(e instanceof Uint8Array))throw new TypeError("send: bytes must be a Uint8Array");if(e.byteLength>65507)throw new RangeError(`a UDP payload is at most 65507 bytes (got ${e.byteLength})`);if(this.channel.closed)throw new Error("the UDP flow is closed");let n=this.#e.datagrams;if(n&&e.byteLength<=this.maxDatagramSize){let r=n.send(Rh(this.channel.id,e));return r?this.stats.sent++:this.stats.sendDropped++,r}if(n&&this.#e.oversize==="drop")throw this.stats.sendDropped++,new RangeError(`this payload (${e.byteLength} bytes) does not fit one datagram (${this.maxDatagramSize} bytes) and this flow drops oversize payloads`);return await this.channel.write(e),this.stats.sentReliable++,!0}deliverDatagram(e){this.#s(e,!1)}deliverReliable(e){this.#s(e,!0)}#s(e,n){if(!this.#i){if(this.#n.length>=this.#e.queueDatagrams){this.stats.receiveDropped++,n&&this.channel.consumed(e.byteLength);return}n?this.stats.receivedReliable++:this.stats.received++,this.#n.push({bytes:n?e:e.slice(),reliable:n}),this.#r?.()}}get streams(){if(this.#t)return this.#t;let e=this,n=new ReadableStream({async pull(s){for(;e.#n.length===0&&!e.#i;)await new Promise(o=>{e.#r=o});e.#r=null;let i=e.#n.shift();if(i){s.enqueue(i.bytes),i.reliable&&e.channel.consumed(i.bytes.byteLength);return}s.close()},cancel(){e.destroy()}},{highWaterMark:0}),r=new WritableStream({async write(s){try{await e.send(s instanceof Uint8Array?s:new Uint8Array(s))}catch(i){if(!(i instanceof RangeError))throw i}},close(){e.close()},abort(){e.destroy()}});return this.#t={readable:n,writable:r},this.#t}get readable(){return this.streams.readable}get writable(){return this.streams.writable}close(e){this.channel.destroy(e)}destroy(e){this.channel.destroy(e)}};var Ch=1073741824,Ih=4294967295,ei=3e4,Nh=5e3,Ce=class extends Error{constructor(e,n){super(e),this.name="GatewayError",this.code=n}},Dr=class{#e;#n;#r=Ch;#i=new Map;#t=new Map;#s=new Map;constructor({send:e,hasFeature:n,datagrams:r=()=>null}){this.#e=e,this.#n=n,this.#o=r}#o;#a=new Map;handleDatagram(e){let n=mc(e);n&&this.#a.get(n.id)?.deliverDatagram(n.payload)}#c(){if(this.#r>=Ih)throw new Error("gateway ids exhausted on this connection");return this.#r++}#u(e,n){if(!this.#n(e))throw new Ce(`this host does not support ${n} (it did not advertise "${e}")`,0)}#l(e,{datagram:n=!1,onData:r}={}){let s=new Wt({id:e,credit:this.#n(et),graceMs:Nh,onRemoteClose:n?()=>s.destroy():void 0,onData:r,sendData:i=>this.#e(tr({gatewayId:e,data:i})),sendCredit:i=>Promise.resolve(this.#e(Xe({gatewayId:e,bytes:i}))).catch(()=>{}),sendClose:i=>Promise.resolve(this.#e(Zn({gatewayId:e,reason:i}))).catch(()=>{}),onClose:()=>{this.#i.delete(e),this.#a.delete(e)}});return this.#i.set(e,s),s}#f(e){let n=this.#a.get(e.id);if(n)return n;let{readable:r,writable:s}=e.streams();return{readable:r,writable:s,close:i=>e.end(i),destroy:i=>e.destroy(i),closed:e.closedPromise}}async#y(e,{timeoutMs:n=ei,signal:r}={},s){if(r?.aborted)throw r.reason??new DOMException("aborted","AbortError");let i=this.#c(),o,a=this.#l(i,{...s,onData:s?.udp?h=>o.deliverReliable(h):void 0});s?.udp&&(o=new Mr({id:i,channel:a,...s.udp}),this.#a.set(i,o));let c=new Promise((h,d)=>{let w=setTimeout(()=>{this.#t.delete(i),a.abandon(),d(new Ce("the host did not answer the open request in time",5))},n);w.unref?.(),this.#t.set(i,{channel:a,resolve:h,reject:d,timer:w})}),l=()=>{let h=this.#t.get(i);h&&(this.#t.delete(i),clearTimeout(h.timer),a.destroy(),h.reject(r.reason??new DOMException("aborted","AbortError")))};r?.addEventListener("abort",l,{once:!0});try{await this.#e(e(i))}catch(h){let d=this.#t.get(i);throw d&&(clearTimeout(d.timer),this.#t.delete(i)),a.abandon(),h}try{return await c}finally{r?.removeEventListener("abort",l)}}async openUnix(e,n){if(this.#u("gateway-unix","unix-domain socket forwarding"),typeof e!="string"||!e)throw new TypeError("openUnix: path must be a non-empty string");return this.#y(r=>mo({gatewayId:r,path:e}),n)}async openEndpoint(e,n){if(this.#u("gateway-endpoints","named endpoints"),typeof e!="string"||!e)throw new TypeError("openEndpoint: name must be a non-empty string");let r=n?.target;if(r!==void 0){if(typeof r!="string"||!r)throw new TypeError("openEndpoint: target must be a non-empty string");this.#u("targets","execution targets")}return this.#y(s=>go({gatewayId:s,name:e,target:r}),n)}async openTcp(e,n,r){if(this.#u("gateway","TCP egress"),typeof e!="string"||!e||!Number.isInteger(n))throw new TypeError("openTcp: host and port are required");return this.#y(s=>bo({gatewayId:s,host:e,port:n}),r)}async openUdp(e,n,r){if(this.#u("gateway","UDP egress"),typeof e!="string"||!e||!Number.isInteger(n))throw new TypeError("openUdp: host and port are required");if(r?.oversize!==void 0&&r.oversize!=="reliable"&&r.oversize!=="drop")throw new TypeError('openUdp: oversize must be "reliable" or "drop"');let s=this.#o();return this.#y(i=>Ao({gatewayId:i,host:e,port:n}),r,{datagram:!0,udp:{datagrams:s,oversize:r?.oversize}})}async listenTcp(e,{bindAddr:n,onConnection:r,timeoutMs:s=ei}={}){if(this.#u("gateway","reverse tunnels (ListenRequest)"),!Number.isInteger(e)||e<0||e>65535)throw new TypeError("listenTcp: port must be an integer 0-65535");if(typeof r!="function")throw new TypeError("listenTcp: onConnection is required");let i=this.#c(),o={onConnection:r,path:"",closed:!1,actualPort:0},a=new Promise((c,l)=>{o.resolve=c,o.reject=l,o.timer=setTimeout(()=>{this.#s.delete(i),l(new Ce("the host did not answer the listen request in time",5))},s),o.timer.unref?.()});this.#s.set(i,o);try{await this.#e(So({listenerId:i,port:e,...n===void 0?{}:{bindAddr:n}})),await a}catch(c){throw this.#s.delete(i),c}return{port:o.actualPort,close:async()=>{o.closed||(o.closed=!0,this.#s.delete(i),await this.#e(fs({listenerId:i})).catch(()=>{}))}}}async listenUnix(e,{replace:n,onConnection:r,timeoutMs:s=ei}={}){if(this.#u("gateway-unix","unix-domain socket forwarding"),typeof e!="string"||!e)throw new TypeError("listenUnix: path must be a non-empty string");if(typeof r!="function")throw new TypeError("listenUnix: onConnection is required");let i=this.#c(),o={onConnection:r,path:e,closed:!1},a=new Promise((c,l)=>{o.resolve=c,o.reject=l,o.timer=setTimeout(()=>{this.#s.delete(i),l(new Ce("the host did not answer the listen request in time",5))},s),o.timer.unref?.()});this.#s.set(i,o);try{await this.#e(_o({listenerId:i,path:e,replace:n===!0?!0:void 0})),await a}catch(c){throw this.#s.delete(i),c}return{path:e,close:async()=>{o.closed||(o.closed=!0,this.#s.delete(i),await this.#e(fs({listenerId:i})).catch(()=>{}))}}}handle(e){switch(e.type){case f.GATEWAY_OK:{let n=this.#t.get(e.gateway_id);return n?(this.#t.delete(e.gateway_id),clearTimeout(n.timer),n.resolve(this.#f(n.channel)),!0):this.#i.has(e.gateway_id)}case f.GATEWAY_FAIL:{let n=this.#t.get(e.gateway_id);return n?(this.#t.delete(e.gateway_id),clearTimeout(n.timer),n.channel.abandon(),n.reject(new Ce(e.message||"refused by the host",e.code)),!0):!1}case f.GATEWAY_DATA:{let n=this.#i.get(e.gateway_id);return n?(n.receive(e.data),!0):!1}case f.GATEWAY_CREDIT:{let n=this.#i.get(e.gateway_id);return n?(n.grant(e.bytes),!0):!1}case f.GATEWAY_CLOSE:{let n=this.#i.get(e.gateway_id);if(!n)return!1;let r=this.#t.get(e.gateway_id);return r?(this.#t.delete(e.gateway_id),clearTimeout(r.timer),n.abandon(),r.reject(new Ce("closed by the host",6)),!0):(n.remoteClosed(e.reason),!0)}case f.LISTEN_OK:{let n=this.#s.get(e.listener_id);return n?.resolve?(clearTimeout(n.timer),n.actualPort=e.actual_port,n.resolve(),n.resolve=void 0,!0):!1}case f.LISTEN_FAIL:{let n=this.#s.get(e.listener_id);return n?.reject?(clearTimeout(n.timer),this.#s.delete(e.listener_id),n.reject(new Ce(e.reason||"refused by the host",4)),!0):!1}case f.INBOUND_OPEN:{let n=this.#s.get(e.listener_id);if(!n)return!1;if(n.closed)return this.#e(hs({channelId:e.channel_id,reason:"listener closed"})).catch(()=>{}),!0;let r;try{r=this.#c()}catch{return this.#e(hs({channelId:e.channel_id,reason:"out of ids"})).catch(()=>{}),!0}let s=this.#l(r),i=this.#f(s);return this.#e(xo({channelId:e.channel_id,gatewayId:r})).then(()=>{try{n.onConnection(i,{peer:e.peer_addr,peerPort:e.peer_port})}catch{s.destroy("handler error")}},()=>s.abandon()),!0}default:return!1}}abandonAll(e="connection closed"){for(let n of this.#t.values())clearTimeout(n.timer),n.reject(new Ce(e,6));this.#t.clear();for(let n of this.#s.values())clearTimeout(n.timer),n.reject?.(new Ce(e,6));this.#s.clear();for(let n of[...this.#i.values()])n.abandon(e);this.#i.clear()}};var Pr=t=>(2147483648|t)>>>0,Vt=t=>Number.isInteger(t)&&t>=2147483648?t-2147483648:void 0,jt=class{#e;#n;#r;#i;#t;#s;#o;#a=0;#c=[];#u=!1;constructor({sendData:e,sendCredit:n,onViolation:r=()=>{},window:s=262144,chunkBytes:i=32768}){this.#e=e,this.#n=n,this.#r=r,this.#i=s,this.#t=i,this.#s=s,this.#o=s}get credit(){return this.#s}async write(e){let n=0;for(;n<e.length;){for(;this.#s<=0;){if(this.#u)throw new Error("rpc channel closed");await new Promise(i=>this.#c.push(i))}if(this.#u)throw new Error("rpc channel closed");let r=Math.min(e.length-n,this.#s,this.#t);this.#s-=r;let s=e.subarray(n,n+r);n+=r,await this.#e(s)}}grant(e){if(!(this.#u||!Number.isSafeInteger(e)||e<=0)){this.#s=Math.min(this.#s+e,Number.MAX_SAFE_INTEGER);for(let n of this.#c.splice(0))n()}}receive(e){return this.#u?!1:(this.#o-=e,this.#o<0?(this.#r("the peer sent more rpc data than the credit it was given"),!1):!0)}consumed(e){if(!this.#u&&(this.#a+=e,this.#a>=this.#i/2)){let n=this.#a;this.#a=0,this.#o+=n;try{Promise.resolve(this.#n(n)).catch(()=>{})}catch{}}}close(){this.#u=!0;for(let e of this.#c.splice(0))e()}};var tt="rpc",Xt="rpc-virtual",vr="rpc-protocol:",Dn="rpc-max-message:",He=1024*1024,xt=t=>vr+t,Un=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,j=Object.freeze({PARSE:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL:-32603,UNSUPPORTED_PROTOCOL:-32e3,CANCELLED:-32001,STREAM_LIMIT:-32002,UNAUTHORIZED:-32003});function ni(t=[]){let e=[],n=He,r=!1;for(let s of t)if(typeof s=="string"){if(s===tt)r=!0;else if(s.startsWith(vr))e.push(s.slice(vr.length));else if(s.startsWith(Dn)){let i=Number(s.slice(Dn.length));Number.isSafeInteger(i)&&i>0&&(n=i)}}return{enabled:r,protocols:e,maxMessageBytes:n}}var q=class t extends Error{constructor(e,n,r,s){super(n),this.name="RpcError",this.code=e,r!==void 0&&(this.data=r),this.reason=s??(r&&typeof r=="object"&&typeof r.reason=="string"?r.reason:void 0)}toJSON(){let e={code:this.code,message:this.message};return this.data!==void 0?e.data=this.data:this.reason&&(e.data={reason:this.reason}),e}static fromWire(e){let n=e&&typeof e=="object"?e:{};return new t(Number.isInteger(n.code)?n.code:j.INTERNAL,typeof n.message=="string"?n.message:"rpc error",n.data)}},Pn=(t,e,n)=>new q(j.INVALID_REQUEST,`${t} of ${e} bytes exceeds the ${n} byte rpc message limit`,{reason:"message-too-large"}),Ur=t=>new q(j.CANCELLED,"rpc channel closed",{reason:"channel-closed",detail:t}),Lh=128,ti=class extends Error{},qt=new ti("incomplete");function kn(t,e,n,r){if(r>Lh)throw new q(j.PARSE,"cbor nesting too deep");if(e>=t.length)throw qt;let s=t[e++],i=s>>5,o=s&31;if(o>=28&&o<=30)throw new q(j.PARSE,"malformed cbor (reserved additional info)");let a=o===31,c=0;if(o<24)c=o;else if(o<=27){let l=o===24?1:o===25?2:o===26?4:8;if(e+l>t.length)throw qt;for(let h=0;h<l;h++)c=c*256+t[e+h];e+=l}switch(i){case 0:case 1:if(a)throw new q(j.PARSE,"malformed cbor (indefinite integer)");return e;case 2:case 3:{if(a)for(;;){if(e>=t.length)throw qt;if(t[e]===255)return e+1;if(t[e]>>5!==i||(t[e]&31)===31)throw new q(j.PARSE,"malformed cbor (bad string chunk)");e=kn(t,e,n,r+1)}if(c>n)throw Pn("message",c,n);if(e+c>t.length)throw qt;return e+c}case 4:case 5:{let l=i===5?2:1;if(a)for(;;){if(e>=t.length)throw qt;if(t[e]===255)return e+1;for(let h=0;h<l;h++)e=kn(t,e,n,r+1)}if(c>n)throw Pn("message",c,n);for(let h=0;h<c*l;h++)e=kn(t,e,n,r+1);return e}case 6:if(a)throw new q(j.PARSE,"malformed cbor (indefinite tag)");return kn(t,e,n,r+1);default:if(a)throw new q(j.PARSE,"malformed cbor (unexpected break)");return e}}var Fr=class{#e=new Uint8Array(0);#n;constructor({maxItemBytes:e=He}={}){this.#n=e}get pending(){return this.#e.length}feed(e){if(e.length)if(this.#e.length===0)this.#e=e;else{let s=new Uint8Array(this.#e.length+e.length);s.set(this.#e,0),s.set(e,this.#e.length),this.#e=s}let n=[],r=0;try{for(;r<this.#e.length;){let s;try{s=kn(this.#e,r,this.#n,0)}catch(o){if(o===qt){if(this.#e.length-r>this.#n)throw Pn("message",this.#e.length-r,this.#n);break}throw o}if(s-r>this.#n)throw Pn("message",s-r,this.#n);let i;try{i=dt(this.#e.subarray(r,s))}catch(o){throw new q(j.PARSE,`malformed cbor: ${o.message}`)}n.push(i),r=s}}catch(s){throw this.#e=new Uint8Array(0),s}return this.#e=r===this.#e.length?new Uint8Array(0):this.#e.slice(r),n}};function Mn(t){if(Array.isArray(t))return t.map(e=>e===void 0?null:Mn(e));if(t&&typeof t=="object"&&!ArrayBuffer.isView(t)&&!(t instanceof ArrayBuffer)){let e={};for(let n of Object.keys(t))t[n]!==void 0&&(n==="__proto__"?Object.defineProperty(e,n,{value:Mn(t[n]),writable:!0,enumerable:!0,configurable:!0}):e[n]=Mn(t[n]));return e}return t}var Yt=t=>typeof t=="string"||typeof t=="number"&&Number.isFinite(t),gc=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t),Be=class{#e;#n;#r;#i;#t;#s=1;#o=new Map;#a=new Map;#c=new Map;#u=new Map;#l=null;#f=null;#y;#A=Promise.resolve();#h=!1;#g=null;#E=null;#p=!1;#w=[];#R=0;#C;onClose=null;constructor({write:e,close:n,maxMessageBytes:r=He,timeoutMs:s,maxInflight:i=64,onConsumed:o}={}){if(typeof e!="function")throw new TypeError("RpcChannel: write(bytes) is required");this.#C=typeof o=="function"?o:null,this.#e=e,this.#n=n??(()=>{}),this.#r=r,this.#i=s>0?s:0,this.#t=i,this.#y=new Fr({maxItemBytes:r})}get closed(){return this.#h}get closeReason(){return this.#g}get maxMessageBytes(){return this.#r}get pendingCount(){return this.#o.size}get inflightCount(){return this.#a.size}onRequest(e,n){if(typeof n!="function")throw new TypeError("onRequest: handler must be a function");return this.#c.set(e,n),()=>{this.#c.get(e)===n&&this.#c.delete(e)}}onNotification(e,n){return this.#u.set(e,n),()=>{this.#u.get(e)===n&&this.#u.delete(e)}}setFallbackRequestHandler(e){this.#l=e}setFallbackNotificationHandler(e){this.#f=e}onProgress(e,n){let r=this.#o.get(e);r&&(r.onProgress=n)}hold(){this.#p=!0}release(){this.#p=!1;for(let e of this.#w.splice(0)){if(this.#h)return;this.#T(e)}this.#k(this.#R),this.#R=0}#k(e){if(e>0&&this.#C)try{this.#C(e)}catch{}}request(e,n,{onProgress:r,signal:s,timeoutMs:i,id:o}={}){if(typeof e!="string"||!e)throw new TypeError("request: method must be a non-empty string");if(o!==void 0&&!Yt(o))throw new TypeError("request: id must be a string or number");let a=o??this.#s++,c=new Promise((l,h)=>this.#I(a,e,n,{resolve:l,reject:h,onProgress:r,signal:s,timeoutMs:i}));return c.id=a,c.cancel=l=>this.cancel(a,l),c}#I(e,n,r,{resolve:s,reject:i,onProgress:o,signal:a,timeoutMs:c}){if(this.#h)return i(Ur(this.#g));if(this.#o.has(e))return i(new q(j.INVALID_REQUEST,`request id ${e} is already in flight`));let l={method:n,resolve:s,reject:i,onProgress:o,timer:null,signal:a,onAbort:null},h;try{let w={jsonrpc:"2.0",id:e,method:n};r!==void 0&&(w.params=r),h=this.#M(w)}catch(w){return i(w)}this.#o.set(e,l);let d=c??this.#i;d>0&&(l.timer=setTimeout(()=>this.cancel(e,"timeout",`request "${n}" timed out after ${d} ms`),d)),a&&(a.aborted?queueMicrotask(()=>this.cancel(e,"aborted")):(l.onAbort=()=>this.cancel(e,"aborted"),a.addEventListener("abort",l.onAbort,{once:!0}))),this.#L(h).catch(w=>this.#_(e,y=>y.reject(w instanceof q?w:Ur(w?.message))))}#_(e,n){let r=this.#o.get(e);return r?(this.#o.delete(e),clearTimeout(r.timer),r.onAbort&&r.signal.removeEventListener("abort",r.onAbort),n(r),!0):!1}cancel(e,n="cancelled",r){let s=this.#_(e,i=>i.reject(new q(j.CANCELLED,r??`request "${i.method}" cancelled`,{reason:n})));return s&&!this.#h&&this.notify("$/cancel",{id:e}),s}notify(e,n){if(typeof e!="string"||!e)throw new TypeError("notify: method must be a non-empty string");if(this.#h)return Promise.resolve();let r={jsonrpc:"2.0",method:e};return n!==void 0&&(r.params=n),this.#L(this.#M(r)).catch(()=>{})}async close(e="closed"){if(this.#E)return this.#E;if(!this.#h)return this.#E=(async()=>{let n=this.#A;this.#b(e),await Promise.race([n,new Promise(r=>setTimeout(r,1e3))]);try{await this.#n()}catch{}})(),this.#E}handleClose(e="stream-closed"){this.#b(e)}#b(e){if(this.#h)return;this.#h=!0,this.#g=e;for(let r of[...this.#o.keys()])this.#_(r,s=>s.reject(Ur(e)));for(let r of this.#a.values())r.done=!0,r.ctl.abort(Ur(e));this.#a.clear();let n=this.onClose;this.onClose=null;try{n?.(e)}catch{}}feed(e){if(this.#h)return;let n;try{n=this.#y.feed(e)}catch(r){let s=r instanceof q?r:new q(j.PARSE,String(r?.message??r));this.#N({jsonrpc:"2.0",id:null,error:s.toJSON()}),this.close(s.code===j.PARSE?"parse-error":s.reason??"protocol-error");return}for(let r of n){if(this.#h)return;this.#p?this.#w.push(r):this.#T(r)}this.#p?this.#R+=e.length:this.#k(e.length)}#T(e){if(!gc(e)||e.jsonrpc!=="2.0")return this.#x(e);if(typeof e.method=="string")return e.params!==void 0&&e.params!==null&&typeof e.params!="object"?this.#x(e):e.id===void 0?this.#S(e):Yt(e.id)?this.#P(e):this.#N({jsonrpc:"2.0",id:null,error:{code:j.INVALID_REQUEST,message:"invalid request id"}});if(e.method!==void 0)return this.#x(e);e.id===null||e.id===void 0||!Yt(e.id)||"result"in e=="error"in e||this.#_(e.id,r=>{"error"in e?r.reject(q.fromWire(e.error)):r.resolve(e.result)})}#x(e){let n=gc(e)&&Yt(e.id)?e.id:null;this.#N({jsonrpc:"2.0",id:n,error:{code:j.INVALID_REQUEST,message:"invalid JSON-RPC 2.0 message"}})}#S(e){let n=e.params??void 0;if(e.method==="$/cancel"){let s=n?.id,i=Yt(s)?this.#a.get(s):void 0;if(!i||i.done)return;i.done=!0,this.#a.delete(s),i.ctl.abort(new q(j.CANCELLED,"request cancelled by the caller",{reason:"cancelled"})),this.#N({jsonrpc:"2.0",id:s,error:{code:j.CANCELLED,message:"request cancelled",data:{reason:"cancelled"}}});return}if(e.method==="$/progress"){let s=Yt(n?.id)?this.#o.get(n.id):void 0;if(s?.onProgress)try{s.onProgress(n.chunk)}catch{}return}let r=this.#u.get(e.method);try{r?r(n):this.#f?.(e.method,n)}catch{}}#P(e){let{id:n,method:r}=e,s=e.params??void 0,i=d=>this.#N(d);if(this.#a.has(n))return i({jsonrpc:"2.0",id:n,error:{code:j.INVALID_REQUEST,message:`request id ${n} is already in flight`}});if(this.#a.size>=this.#t)return i({jsonrpc:"2.0",id:n,error:{code:j.STREAM_LIMIT,message:`more than ${this.#t} requests in flight`,data:{reason:"stream-limit"}}});let o=this.#c.get(r),a=this.#l;if(!o&&!a)return i({jsonrpc:"2.0",id:n,error:{code:j.METHOD_NOT_FOUND,message:`method not found: ${r}`}});let c=new AbortController,l={ctl:c,done:!1};this.#a.set(n,l);let h={id:n,method:r,signal:c.signal,channel:this,progress:d=>l.done||this.#h?Promise.resolve():this.#O(n,d)};(async()=>{let d;try{let w=o?await o(s,h):await a(r,s,h);d={jsonrpc:"2.0",id:n,result:w===void 0?null:w}}catch(w){let y=w instanceof q?w:new q(j.INTERNAL,String(w?.message??w));d={jsonrpc:"2.0",id:n,error:y.toJSON()}}if(!l.done){l.done=!0,this.#a.delete(n);try{this.#L(this.#M(d)).catch(()=>{})}catch(w){if(!(w instanceof q))throw w;this.#N({jsonrpc:"2.0",id:n,error:{code:j.INTERNAL,message:w.message,data:{reason:w.reason}}})}}})()}#O(e,n){try{return this.#L(this.#M({jsonrpc:"2.0",method:"$/progress",params:{id:e,chunk:n}}))}catch(r){return Promise.reject(r)}}#M(e){let n=Ve(Mn(e));if(n.length>this.#r)throw Pn("message",n.length,this.#r);return n}#N(e){if(!(this.#h&&e.error?.code!==j.PARSE&&e.error?.code!==j.INVALID_REQUEST))try{this.#L(Ve(Mn(e))).catch(()=>{})}catch{}}#L(e){let n=this.#A.then(()=>this.#e(e));return this.#A=n.catch(()=>{}),n}};var vn="host-key-nonce:",$r="host-key:",Kr="host-key-sig:",kh="wsh-host-key-proof-v1",Mh=new TextEncoder;function Fn(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function _c(t){if(typeof t!="string"||t.length%2||/[^0-9a-f]/i.test(t))throw new Error("invalid hex");let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}var ye=class extends Error{constructor(e,n,r={}){super(n),this.name="HostKeyError",this.code=e,Object.assign(this,r)}};function ri(){return Fn(crypto.getRandomValues(new Uint8Array(16)))}function Br({sessionId:t,clientNonce:e,username:n}){return Mh.encode(`${kh}\0${t}\0${typeof e=="string"?e:Fn(e)}\0${n}`)}function bc(t){for(let e of Array.isArray(t)?t:[])if(typeof e=="string"&&e.startsWith(vn)){let n=e.slice(vn.length);if(/^[0-9a-f]{32,128}$/i.test(n))return n.toLowerCase()}return null}function Ac(t){let e=null,n=null;for(let r of Array.isArray(t)?t:[])if(typeof r=="string")try{r.startsWith(Kr)?n=_c(r.slice(Kr.length)):r.startsWith($r)&&(e=_c(r.slice($r.length)))}catch{}return e||n?{key:e,sig:n}:null}var Dh=Object.freeze({AUTH_FAILED:"AUTH_FAILED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_BAD_SIGNATURE:"AUTH_BAD_SIGNATURE",AUTH_METHOD_DISABLED:"AUTH_METHOD_DISABLED",AUTH_RATE_LIMITED:"AUTH_RATE_LIMITED",AUTH_KEY_EXPIRED:"AUTH_KEY_EXPIRED",AUTH_BINDING_REQUIRED:"AUTH_BINDING_REQUIRED",AUTH_NOT_SEALED:"AUTH_NOT_SEALED",AUTH_BAD_REQUEST:"AUTH_BAD_REQUEST",CONNECTION_FAILED:"CONNECTION_FAILED",HANDSHAKE_TIMEOUT:"HANDSHAKE_TIMEOUT"}),Ph=[["key-expired",/\bexpired\b/i],["binding-required",/channel binding required/i],["not-sealed",/sealed session/i],["rate-limited",/too many (failed )?(auth )?attempts|rate limited/i],["method-disabled",/auth(entication)? (is )?(not enabled|disabled)/i],["bad-signature",/signature (does not verify|verification failed)/i],["unauthorized",/^(key not authorized|authentication failed|invalid password)$/i],["bad-request",/^bad username|^unsupported auth method|^expected (a |an )?(pubkey|password )?auth|^malformed|^missing /i]];function Uh(t){if(typeof t=="string"){for(let[e,n]of Ph)if(n.test(t.trim()))return{code:`AUTH_${e.toUpperCase().replace(/-/g,"_")}`,refusal:e}}return{code:Dh.AUTH_FAILED,refusal:null}}var St=class extends Error{constructor(e,n){super(n??`Authentication failed: ${e}`),this.name="WshAuthError";let{code:r,refusal:s}=Uh(e);this.code=r,this.reason=e,this.refusal=s}},$n=class extends Error{constructor(e,n,r={}){super(n,r.cause===void 0?void 0:{cause:r.cause}),this.name="WshConnectionError",this.code=e,r.attempts&&(this.attempts=r.attempts)}};var Hr=t=>new $n("HANDSHAKE_TIMEOUT",t),si="disconnected",Tc="connecting",xc="connected",Jt="authenticated",nt="closed",Sc=1e4,Z=1e4,vh=new Set(["stat","list","read","write","mkdir","remove","rename"]);function Rc(t,e,n){if(e!==void 0){if(typeof e!="string"||!e)throw new TypeError(`${n}: target must be a non-empty string`);if(!t.hasFeature(Qe))throw new Error(`${n}: this host does not advertise "${Qe}" (execution targets); it would run the request on its own default, or reject the unknown field -- it was not sent`)}}function Ae(t){let e=new DOMException("The operation was aborted","AbortError");return t&&"reason"in t&&t.reason!==void 0&&(e.cause=t.reason),e}function Qt(t,e){for(let[n,r]of Object.entries(e))if(r==null)throw new TypeError(`${t}: "${n}" is required -- the corresponding wire field is not optional, and omitting it produces a message a conformant server will reject`)}var Oc=3e4,Cc=9e4,Fh=6e4,ii=65536;async function $h(t){if(!t.public_key||!t.record_signature||t.seq===void 0||t.seq===null)return!1;try{if(await oe(t.public_key)!==t.fingerprint)return!1;let n=await pe(t.public_key);return await gs(n,t.record_signature,{username:t.username,peerType:t.peer_type,shellBackend:t.shell_backend,capabilities:t.capabilities,supportsAttach:t.supports_attach,supportsReplay:t.supports_replay,supportsEcho:t.supports_echo,supportsTermSync:t.supports_term_sync,seq:t.seq})}catch{return!1}}async function Kh(t){if(t instanceof Uint8Array){if(t.byteLength!==32)throw new TypeError("expectHostKey: a raw key must be 32 bytes");return oe(t)}let e=String(t).trim();if(/^ssh-ed25519\s/.test(e)){let r=dn(e);if(!r)throw new TypeError("expectHostKey: malformed ssh-ed25519 line");return oe(pn(r.data))}let n=e.replace(/^sha256:/i,"").replace(/:/g,"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new TypeError("expectHostKey: expected a 64-char hex fingerprint, a raw key, or an ssh-ed25519 line");return n}var Ic=64*1024;function Bh(t){if(!(typeof t=="string"||t instanceof Uint8Array)&&!(t&&(typeof t.getReader=="function"||typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function")))throw new TypeError("exec: stdin must be a string, Uint8Array, ReadableStream or (async) iterable of those")}function Nc(t){if(t!==!1&&t!=="auto"&&t!==!0)throw new TypeError("connect: sealSession must be false, 'auto' or true")}async function Hh(t,e){let n=async r=>{if(typeof r=="string"&&(r=new TextEncoder().encode(r)),!(r instanceof Uint8Array))throw new TypeError("exec: stdin chunks must be strings or Uint8Arrays");for(let s=0;s<r.byteLength;s+=Ic)await t.write(r.subarray(s,s+Ic))};if(typeof e=="string"||e instanceof Uint8Array)await n(e);else if(typeof e.getReader=="function"){let r=e.getReader();try{for(;;){let{value:s,done:i}=await r.read();if(i)break;await n(s)}}finally{r.releaseLock?.()}}else for await(let r of e)await n(r);await t.closeStdin()}function Gh(t){try{let e=Ts(t)?.serverCertificateHashes;if(e?.length!==1||e[0].algorithm!=="sha-256")return null;let n=e[0].value;return n instanceof Uint8Array?n:new Uint8Array(n)}catch{return null}}var rt=class t{#e=si;#n=null;#r=null;#i=0;#t=null;#s=null;#o=null;#a="";#c=null;#u=null;#l=null;#f=[];#y=null;onHostKey=null;#A;#h=new Map;#g=new Map;#E=[];#p=[];#w=new Set;#R=new Set;#C=0;#k=0;#I=Promise.resolve();#_=new Map;#b=[];#T=null;#x=null;#S=null;#P=0;#O=null;#M=Oc;#N=Cc;constructor({transportFactories:e,pingIntervalMs:n,pongTimeoutMs:r}={}){this.#A=e||{wt:()=>new or,ws:()=>new Me},this.#M=n??Oc,this.#N=r??Cc}onClose=null;onError=null;onDrop=null;#L=0;#v=0;get droppedMessages(){return{plaintext:this.#L,unopened:this.#v}}#U(e){e.reason==="unopenable-bridge-frame"?this.#v++:this.#L++;try{this.onDrop?.(e)}catch{}}onReverseConnect=null;onReverseProof=null;onClipboard=null;onRelayMessage=null;onRateWarning=null;onCopilotSuggest=null;onKeyExchange=null;onGatewayMessage=null;get state(){return this.#e}get sessionId(){return this.#n}get authToken(){return this.#r}get authTtl(){return this.#i}get sessions(){return new Map(this.#h)}get features(){return[...this.#T??this.#b]}get serverFeatures(){return[...this.#b]}get bridgedFeatures(){return this.#T?[...this.#T]:null}get _transport(){return this.#t}hasFeature(e){return(this.#T??this.#b).includes(e)}get hostKey(){return this.#s}get sessionSealed(){return!!this.#l?.bridge}async connect(e,{username:n,keyPair:r,signer:s,password:i,transport:o,webTransport:a,timeout:c=Sc,requireChannelBinding:l=!1,sealSession:h="auto",...d}={}){if(this.#e!==si&&this.#e!==nt)throw new Error(`Client already ${this.#e}`);if(!n)throw new Error("username is required");Nc(h);let w=await Je({keyPair:r,signer:s});if(this.#o=w,this.#a=n,!w&&!i)throw new Error("Either keyPair, signer or password is required for authentication");if(l&&!w)throw new Error("requireChannelBinding needs a key: a password login signs nothing to bind");this.#e=Tc,this.#f=[],this.#y=null,this.#u=null,this.#l=null,this.#c=null,this.#h.clear(),this.#g.clear(),this.#C=0,this.#_.clear(),this.#n=null,this.#r=null,this.#i=0,this.#s=null;try{let y=await this.#oe(e,o,a);this.#t=y,this.#e=xc;let _=w?te.PUBKEY:te.PASSWORD,E=ri();await y.sendControl(is({username:n,authMethod:_,features:[vn+E,et,...y.supportsDatagrams?[zt]:[]]}));let g={...d,url:e,username:n,nonce:E},A=await this.#m([f.SERVER_HELLO,f.CHALLENGE,f.AUTH_FAIL],c,Hr("Auth handshake timed out waiting for server response"));if(A.type===f.AUTH_FAIL)throw new St(A.reason||"unknown");let I=null,S=!1;if(A.type===f.SERVER_HELLO){I=A.session_id,this.#b=A.features||[];let N=_===te.PUBKEY?this.#m([f.CHALLENGE,f.AUTH_OK],c,Hr("Auth handshake timed out waiting for challenge")):null;if(N?.catch(()=>{}),await this.#G(A,g),S=this.#W(h,this.#b,!!w),_===te.PUBKEY){let D=await N;if(D.type===f.AUTH_OK)return this.#n=D.session_id||I,this.#r=D.token||null,this.#i=Number(D.ttl)||0,this.#e=Jt,S&&await this.#z(c),this.#V(),this.#n;let{signature:x,publicKeyRaw:m}=await vt(w,D.session_id,D.nonce,{username:n,channelBinding:await this.#H(this.#b,l)});await y.sendControl(pt({method:te.PUBKEY,signature:x,publicKey:m}))}else await y.sendControl(pt({method:te.PASSWORD,password:i}))}else if(A.type===f.CHALLENGE){if(await this.#G(null,g),S=this.#W(h,[],!!w),_!==te.PUBKEY||!w)throw new Error("Server sent CHALLENGE but no key pair was provided");I=A.session_id;let{signature:N,publicKeyRaw:D}=await vt(w,A.session_id,A.nonce,{username:n,channelBinding:await this.#H([],l)});await y.sendControl(pt({method:te.PUBKEY,signature:N,publicKey:D}))}let O=await this.#m([f.AUTH_OK,f.AUTH_FAIL],c,Hr("Auth handshake timed out waiting for auth result"));if(O.type===f.AUTH_FAIL)throw new St(O.reason||"rejected");return this.#n=O.session_id||I,this.#r=O.token||null,this.#i=Number(O.ttl)||0,this.#e=Jt,S&&await this.#z(c),this.#V(),this.#n}catch(y){throw this.#e=nt,await this.#t?.close().catch(()=>{}),this.#t=null,this.#j(y),y}}async openSession({type:e="pty",command:n,protocol:r,cols:s=80,rows:i=24,env:o,timeout:a=Z,primer:c=!0,attach:l,stdio:h,target:d}={}){if(this.#d("openSession"),Rc(this,d,"openSession"),h!==void 0&&h!=="pty"&&h!=="pipes")throw new TypeError('openSession: stdio must be "pty" or "pipes"');if(h==="pipes"){if(e!=="exec")throw new TypeError('openSession: stdio "pipes" is only for type "exec"');if(!this.hasFeature(gn))throw new Error(`openSession: this host does not advertise "${gn}" (exec on plain pipes with stdin EOF); it runs exec on a PTY, which cannot signal end of input`)}e==="rpc"&&(this.#q(r),n=r);let w=this._nextChannelId();return await this.#t.sendControl(Yi({kind:e,command:n,cols:s,rows:i,env:o,stdio:h==="pipes"?"pipes":void 0,target:d})),new Promise((y,_)=>{let E={mode:"session",kind:e,primer:c,attach:l,requestedChannelId:w,resolve:y,reject:_};E.timer=setTimeout(()=>{let g=this.#p.indexOf(E);g!==-1&&this.#p.splice(g,1),_(new Error("Timed out waiting for session open response"))},a),this.#p.push(E)})}#q(e){if(typeof e!="string"||!Un.test(e))throw new q(j.INVALID_PARAMS,'openSession({ type: "rpc" }) needs a protocol name',void 0,"INVALID_PROTOCOL");if(!this.hasFeature(tt)&&!this.hasFeature(Xt))throw new q(j.UNSUPPORTED_PROTOCOL,`UNSUPPORTED_PROTOCOL: this host does not advertise "${tt}" channels (cannot open "${e}")`,void 0,"UNSUPPORTED_PROTOCOL");if(!this.hasFeature(xt(e)))throw new q(j.UNSUPPORTED_PROTOCOL,`UNSUPPORTED_PROTOCOL: this host does not advertise the "${e}" rpc protocol`,void 0,"UNSUPPORTED_PROTOCOL")}async openRpc(e,{timeoutMs:n,openTimeout:r=Z}={}){this.#d("openRpc");let{maxMessageBytes:s}=ni(this.#T??this.#b),i=!this.hasFeature(tt)&&this.hasFeature(Xt),o=null,a=await this.openSession({type:"rpc",protocol:e,timeout:r,attach:c=>{if(i){let l=new jt({sendData:h=>c.write(h),sendCredit:h=>this.sendRelayControl(Xe({gatewayId:Pr(c.channelId),bytes:h})),onViolation:()=>{o?.close("credit-violation")}});this.#g.set(c.channelId,l),o=new Be({maxMessageBytes:s??He,timeoutMs:n,write:h=>l.write(h),close:async()=>{l.close(),await c.close()},onConsumed:h=>l.consumed(h)}),c.onData=h=>{l.receive(h.length)&&o.feed(h)},c.onClose=h=>{l.close(),this.#g.delete(c.channelId),o.handleClose(h?"stream-error":"channel-closed")};return}o=new Be({maxMessageBytes:s??He,timeoutMs:n,write:l=>c.write(l),close:()=>c.close()}),c.onData=l=>o.feed(l),c.onClose=l=>o.handleClose(l?"stream-error":"channel-closed")}});return o.session=a,o}listSessions(){let e=[];for(let[n,r]of this.#h)e.push({channelId:n,kind:r.kind,state:r.state,sessionId:r.sessionId});return e}getSession(e){if(typeof e=="number")return this.#h.get(e);if(!(typeof e!="string"||!e)){for(let n of this.#h.values())if(n.sessionId===e)return n}}async attachSession(e,{readOnly:n=!1,token:r,timeout:s=Z}={}){this.#d("attachSession");let i=n?"readonly":"control";return this.#$(e,r,Ji({sessionId:e,token:r,mode:i}),s,"attach","Failed to attach")}async#$(e,n,r,s,i,o){let a={sessionId:e,token:n};this.#E.push(a);try{await this.#t.sendControl(r);let c=await this.#m([f.PRESENCE,f.ERROR],s,`Timed out waiting for ${i} response`,l=>l.type===f.ERROR||!Array.isArray(l.attachments)||l.attachments.length===0||l.attachments.some(h=>h?.session_id===e));if(c.type===f.ERROR)throw new Error(`${o}: ${c.message||"rejected"}`);return c}finally{let c=this.#E.indexOf(a);c!==-1&&this.#E.splice(c,1)}}async resumeSession(e,n,{lastSeq:r=0,timeout:s=Z}={}){return this.#d("resumeSession"),this.#$(e,n,Qi({sessionId:e,token:n,lastSeq:r}),s,"resume","Failed to resume")}async detach(e,n=Z){this.#d("detach"),await this.#t.sendControl(yo({sessionId:e}));let r=await this.#m([f.DETACH_OK,f.DETACH_FAIL],n,"Timed out waiting for detach response");if(r.type===f.DETACH_FAIL)throw new Error(`Failed to detach: ${r.reason||"rejected"}`)}async listRemoteSessions(e=Z){return this.#d("listRemoteSessions"),await this.#t.sendControl(no()),(await this.#m([f.SESSION_LIST],e,"Timed out waiting for session list response")).sessions||[]}async grantSessionAccess(e,n,r=["read"]){this.#d("grantSessionAccess"),await this.#t.sendControl($o({sessionId:e,principal:n,permissions:r}))}async revokeSessionAccess(e,n,r){this.#d("revokeSessionAccess"),await this.#t.sendControl(Ko({sessionId:e,principal:n,reason:r}))}async disconnect(){if(this.#e===si||this.#e===nt)return;this.#B(),this.#e=nt,this.#T=null,this.#x?.abandonAll("client disconnected");let e=[];for(let n of this.#h.values())e.push(n.close().catch(()=>{}));await Promise.allSettled(e),this.#h.clear(),this.#g.clear(),this.#t&&(await this.#t.close().catch(()=>{}),this.#t=null),this.#j(new Error("Client disconnected"))}static async exec(e,n,{username:r,keyPair:s,signer:i,password:o,timeout:a=Fh,primer:c=!0,stdin:l,stdio:h,target:d,...w}={}){if(l!==void 0&&Bh(l),h!==void 0&&h!=="pipes"&&h!=="pty")throw new TypeError('exec: stdio must be "pipes" or "pty"');let y=new t,_=[],E=[],g=-1,A=!1;try{await y.connect(e,{username:r,keyPair:s,signer:i,password:o,...w}),A=h==="pipes"||h===void 0&&l!==void 0&&y.hasFeature(gn);let O=await y.openSession({type:"exec",command:n,primer:l===void 0?c:!1,stdio:A?"pipes":void 0,target:d});await new Promise((N,D)=>{let x=setTimeout(()=>{D(new Error(`exec timed out after ${a}ms`))},a);O.onData=m=>{_.push(m)},O.onStderr=m=>{E.push(m)},O.onExit=m=>{g=m},O.onClose=()=>{clearTimeout(x),N()},l!==void 0&&Hh(O,l).catch(m=>{clearTimeout(x),D(m)})})}finally{await y.disconnect().catch(()=>{})}let I=O=>{let N=new Uint8Array(O.reduce((x,m)=>x+m.byteLength,0)),D=0;for(let x of O)N.set(x,D),D+=x.byteLength;return N},S=I(_);return A?{stdout:S,exitCode:g,stderr:I(E)}:{stdout:S,exitCode:g}}async connectReverse(e,{username:n,keyPair:r,signer:s,password:i,webTransport:o,expose:a={},peerType:c="browser-shell",shellBackend:l,supportsAttach:h,supportsReplay:d,supportsEcho:w,supportsTermSync:y,operatorProof:_=!0,...E}={}){let g=await this.connect(e,{username:n,keyPair:r,signer:s,password:i,webTransport:o,...E}),A=[];a.shell&&A.push("shell"),a.exec&&A.push("exec"),a.fs&&A.push("fs"),a.tools&&A.push("tools");let I=await Je({keyPair:r,signer:s});I&&_&&A.push(Pe),this.#o=I,this.#a=n;let S=null;I&&(S=I.publicKeyRaw);let O=l||(a.shell?"virtual-shell":"exec-only"),N={username:n,capabilities:A,peerType:c,shellBackend:O,supportsAttach:h??O!=="exec-only",supportsReplay:d??O!=="exec-only",supportsEcho:w??O==="virtual-shell",supportsTermSync:y??O==="virtual-shell",seq:Date.now()},D;return I&&({signature:D}=await Es(I,N)),await this.#t.sendControl(ao({...N,publicKey:S,recordSignature:D})),g}async listPeers(e=Z){this.#d("listPeers"),await this.#t.sendControl(co());let r=(await this.#m([f.REVERSE_PEERS],e,"Timed out waiting for peer list")).peers||[];return Promise.all(r.map(async s=>({...s,verified:await $h(s)})))}async listTargets(e=Z){if(this.#d("listTargets"),!this.hasFeature(Qe))throw new Error(`listTargets: this host does not advertise "${Qe}" (execution targets)`);return await this.#t.sendControl(zo()),(await this.#m([f.TARGET_LIST],e,"Timed out waiting for the target list")).targets??[]}async reverseConnectTo(e,n=Z){return this.#d("reverseConnectTo"),await this.reverseConnect(e,n)}async reverseConnect(e,n=Z,{proof:r="auto",requirePeerProof:s=!1,sealed:i=!1,peerCapabilities:o}={}){if(this.#d("reverseConnect"),r!=="auto"&&typeof r!="boolean")throw new TypeError("reverseConnect: proof must be 'auto', true or false");let a=this.#b.includes(Pe),c=i===!0?{}:i||null;if((c||s||r===!0)&&!a)throw new Error(`reverseConnect: this relay does not carry operator proof (no "${Pe}" in its features), so ${c?"a sealed bridge":"proof"} is not available -- nothing was sent`);if((c||s||r===!0)&&!this.#o)throw new Error("reverseConnect: proof needs a key login (a password login has nothing to sign with)");let l=this.#t,h=l.sendControl.bind(l),d=null,w=null;c&&(this.#u={sessionId:null,bridge:null},l.sendControl=async g=>{if(!Dt(g.type))return h(g);if(d)return h(await d.seal(g));if(g.type===f.KEY_EXCHANGE&&w&&g.session_id===w.sessionId)return h(g);throw new Error("sealed bridge: nothing is sent over it before the key exists")});let y=()=>{d||(l.sendControl=h,this.#u=null)},_=null,E=null;try{let g=r===!0;if(!g&&r==="auto"&&a&&this.#o){let N=o;if(!Array.isArray(N)){let x=(await this.listPeers(n).catch(()=>[])).filter(m=>m.fingerprint===e||e.length>=8&&String(m.fingerprint??"").startsWith(e));N=x.length===1?x[0].capabilities:[]}if(g=N.includes(Pe),(c||s)&&!g)throw new Error(`reverseConnect: the peer does not advertise "${Pe}" in its registered record (a host older than operator proof, or one that cannot answer a challenge), so ${c?"a sealed bridge":"proof"} is not available -- nothing was sent`)}let A=r!==!1&&a&&!!this.#o&&g,I=this.#o?await oe(this.#o.publicKeyRaw):null,S=this.#m([f.REVERSE_ACCEPT,f.REVERSE_REJECT,f.REVERSE_CHALLENGE],n,"Timed out waiting for reverse-connect response");S.catch(()=>{});let O=uo({targetFingerprint:e,username:"",fromFingerprint:""});if(A&&(O.features=[Pe]),await h(O),_=await S,E=null,_.type===f.REVERSE_CHALLENGE){let N=this.#m([f.REVERSE_ACCEPT,f.REVERSE_REJECT],n,"Timed out waiting for reverse-connect response");N.catch(()=>{});try{E=await yc(_,{target:e,ownFingerprint:I}),await h(fo({targetFingerprint:E.peerFingerprint,...await Ec(this.#o,E,this.#a)}))}catch(D){throw N.catch(()=>{}),D}_=await N}if(_.type===f.REVERSE_ACCEPT){if(s&&!E)throw new Error(`reverseConnect: the peer did not prove its identity (requirePeerProof)${r===!0?`; the relay does not pass the offer to a peer that does not advertise "${Pe}"`:""} -- nothing was sent over the bridge`);if(E&&_.target_fingerprint!==E.peerFingerprint)throw new Error("reverseConnect: the relay named a different peer than the one that signed the challenge");if(c){if(!E)throw new Error("reverseConnect: a sealed bridge needs the peer to answer with a challenge (does it require operator proof support?)");if(!(_.features??[]).includes(Zs))throw new Error(`reverseConnect: the peer does not state "${Zs}", so a sealed bridge is not available -- nothing was sent`)}if(this.trustRelayPeer(E?.peerFingerprint??_.target_fingerprint),c){w={sessionId:E.sessionId},this.#u={sessionId:E.sessionId,bridge:null};let N=c.hybrid===!1?"X25519":"X25519+ML-KEM-768",{sharedSecret:D}=await this.initiateE2E(E.sessionId,N,n,{verifyPeer:E.peerPublicKey,signAs:this.#o,responderIdentity:E.peerPublicKey});d=new Tt({key:D,sessionId:E.sessionId,role:"initiator"}),this.#u={sessionId:E.sessionId,bridge:d}}this.#c=E?{peerFingerprint:E.peerFingerprint,sealed:!!c}:null}else y()}catch(g){throw y(),g}return _.type===f.REVERSE_ACCEPT&&(this.#T=Array.isArray(_.features)&&_.features.every(g=>typeof g=="string")?[..._.features]:null),_}async sendRelayControl(e,{to:n}={}){if(this.#d("sendRelayControl"),n!==void 0){if(typeof n!="string"||!n)throw new TypeError("sendRelayControl: to must be an operator fingerprint");e=ho({fromFingerprint:"",toFingerprint:n,inner:Ve(e)})}await this.#t.sendControl(e)}async sendControl(e){this.#d("sendControl"),await this.#t.sendControl(e)}#D(){return this.#d("gateway"),this.#x??=new Dr({send:e=>this.sendControl(e),hasFeature:e=>this.hasFeature(e),datagrams:()=>{let e=this.#t;return!this.#l&&e?.supportsDatagrams&&this.hasFeature(zt)?{send:n=>e.sendDatagram(n),maxSize:()=>e.maxDatagramSize}:null}})}async openUnix(e,n){return this.#D().openUnix(e,n)}async openEndpoint(e,n){return this.#D().openEndpoint(e,n)}async openTcp(e,n,r){return this.#D().openTcp(e,n,r)}async openUdp(e,n,r){return this.#D().openUdp(e,n,r)}async listenTcp(e,n){return this.#D().listenTcp(e,n)}async listenUnix(e,n){return this.#D().listenUnix(e,n)}async forwardUnix(e){let n="./forward-node.mjs",r;try{r=await import(n)}catch(s){throw new Error(`forwardUnix needs Node (${s?.message??s})`)}return r.forward(this,e)}async openStream(){if(this.#d("openStream"),this.#l)throw new Error("openStream: a sealed session carries no client-opened data streams (their bytes are not frames)");return this.#t.openStream()}addControlListener(e){if(typeof e!="function")throw new TypeError("addControlListener requires a function");this.#R.add(e)}removeControlListener(e){this.#R.delete(e)}trustRelayPeer(e){this.#w.add(e)}untrustRelayPeer(e){this.#w.delete(e)}async upload(e,n,{onProgress:r,signal:s}={}){if(this.#d("upload"),s?.aborted)throw Ae(s);let i=await this.#Q(s,{type:"file",command:`upload:${n}`}),o=()=>{i.close().catch(()=>{})};s?.addEventListener("abort",o,{once:!0});try{return await this.#re(i,e,r,s)}catch(a){throw s?.aborted?Ae(s):a}finally{s?.removeEventListener("abort",o),await i.close().catch(()=>{})}}async#Q(e,n){if(!e)return this.openSession(n);let r=this.openSession(n),s,i=new Promise((o,a)=>{s=()=>a(Ae(e)),e.addEventListener("abort",s,{once:!0})});try{return await Promise.race([r,i])}catch(o){throw r.then(a=>a.close(),()=>{}).catch(()=>{}),o}finally{e.removeEventListener("abort",s)}}async#re(e,n,r,s){let i=n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n,o=i.byteLength,a=0;do{if(s?.aborted)throw Ae(s);let l=Math.min(a+ii,o);await this.#t.sendControl(hn({channelId:e.channelId,offset:a,data:i.subarray(a,l),isFinal:l>=o,totalSize:o})),a=l,r?.(a)}while(a<o);if(s?.aborted)throw Ae(s);let c=await new Promise(l=>{e.onExit=h=>{e.onExit=null,l(h)},e.onClose=()=>l(null),e.state==="closed"&&l(null)});if(c!==0)throw new Error(`Upload failed with exit code ${c??"unknown"}`)}async download(e,{onProgress:n,timeout:r=Z,signal:s}={}){if(this.#d("download"),s?.aborted)throw Ae(s);let i=await this.#Q(s,{type:"file",command:`download:${e}`,timeout:r}),o=()=>{i.close().catch(()=>{})};s?.addEventListener("abort",o,{once:!0});try{let a=null,c=0;for(;;){let l=await i._readFileChunk();if(s?.aborted)throw Ae(s);if(l===null)throw new Error("Download failed: connection closed before the transfer completed (truncated)");if(a===null&&(a=new Uint8Array(l.total_size??0)),a.set(l.data,l.offset),c=l.offset+l.data.byteLength,n?.({received:c,total:a.byteLength}),l.is_final){if(c!==a.byteLength)throw new Error(`Download failed: truncated transfer (received ${c} of ${a.byteLength} bytes)`);return a}}}catch(a){throw s?.aborted?Ae(s):a}finally{s?.removeEventListener("abort",o),await i.close().catch(()=>{})}}async discoverTools(e=Z){return this.#d("discoverTools"),await this.#t.sendControl(ro()),(await this.#m([f.MCP_TOOLS],e,"Timed out waiting for MCP tool discovery response")).tools||[]}async callTool(e,n={},r=3e4){this.#d("callTool"),Qt("callTool",{name:e});let{timeout:s=3e4,signal:i}=typeof r=="number"?{timeout:r}:r??{};if(i?.aborted)throw Ae(i);if(this.hasFeature($t))return this.#X(e,n,s,i);let o=this.#I.then(()=>this.#X(e,n,s,void 0,i),()=>this.#X(e,n,s,void 0,i));if(this.#I=o.then(()=>{},()=>{}),!i)return o;let a,c=new Promise((l,h)=>{a=()=>h(Ae(i)),i.addEventListener("abort",a,{once:!0})});try{return await Promise.race([o,c])}finally{i.removeEventListener("abort",a)}}async#X(e,n,r,s,i){if(i?.aborted)throw Ae(i);let a=this.hasFeature($t)?`mcp-${++this.#k}-${Date.now()}`:void 0;await this.#t.sendControl(io({tool:e,arguments:n,callId:a}));let c=this.#m([f.MCP_RESULT],r,`Timed out waiting for MCP tool result (${e})`,a===void 0?void 0:l=>l.call_id===void 0||l.call_id===a,s);try{return(await c).result}catch(l){throw s?.aborted&&l?.name==="AbortError"&&a!==void 0&&this.hasFeature(mn)&&this.#t.sendControl(oo({callId:a})).catch(()=>{}),l}}async suspendSession(e,n="suspend"){this.#d("suspendSession"),await this.#t.sendControl(eo({sessionId:e,action:n}))}async restartPty(e,n){this.#d("restartPty"),await this.#t.sendControl(to({sessionId:e,command:n}))}async requestMetrics(e=Z){return this.#d("requestMetrics"),await this.#t.sendControl(Zi()),this.#m([f.METRICS],e,"Timed out waiting for metrics")}async inviteGuest(e,n,r=["read"],s=Z){return this.#d("inviteGuest"),Qt("inviteGuest",{sessionId:e,ttl:n}),await this.#t.sendControl(Ro({sessionId:e,ttl:n,permissions:r})),this.#m([f.GUEST_INVITE],s,"Timed out waiting for guest invite confirmation")}async joinAsGuest(e,n,r=Z){return this.#d("joinAsGuest"),await this.#t.sendControl(Oo({token:e,deviceLabel:n})),this.#m([f.PRESENCE,f.AUTH_FAIL],r,"Timed out waiting for guest join response")}async revokeGuest(e,n){this.#d("revokeGuest"),await this.#t.sendControl(Co({token:e,reason:n}))}async shareSession(e,n="read",r,s=Z){return this.#d("shareSession"),Qt("shareSession",{sessionId:e,ttl:r}),await this.#t.sendControl(Io({sessionId:e,mode:n,ttl:r})),this.#m([f.SHARE_SESSION],s,"Timed out waiting for share confirmation")}async revokeShare(e,n){this.#d("revokeShare"),await this.#t.sendControl(No({shareId:e,reason:n}))}async negotiateCompression(e,n=3,r=Z){return this.#d("negotiateCompression"),await this.#t.sendControl(Lo({algorithm:e,level:n})),this.#m([f.COMPRESS_ACK],r,"Timed out waiting for compression acknowledgment")}async setRateControl(e,n,r="pause"){this.#d("setRateControl"),Qt("setRateControl",{sessionId:e,maxBytesPerSec:n}),await this.#t.sendControl(Mo({sessionId:e,maxBytesPerSec:n,policy:r}))}async linkSession(e,n,r,s){this.#d("linkSession"),await this.#t.sendControl(Do({sourceSession:e,targetHost:n,targetPort:r,targetUser:s}))}async unlinkSession(e,n){this.#d("unlinkSession"),await this.#t.sendControl(Po({linkId:e,reason:n}))}async copilotAttach(e,n,r){this.#d("copilotAttach"),Qt("copilotAttach",{sessionId:e,model:n}),await this.#t.sendControl(Uo({sessionId:e,model:n,contextWindow:r}))}async copilotSuggest(e,n,r){this.#d("copilotSuggest"),await this.#t.sendControl(vo({sessionId:e,suggestion:n,confidence:r}))}async copilotDetach(e,n){this.#d("copilotDetach"),await this.#t.sendControl(Fo({sessionId:e,reason:n}))}async initiateE2E(e,n="X25519",r=Z,{verifyPeer:s,signAs:i,responderIdentity:o}={}){this.#d("initiateE2E");let a=n==="X25519+ML-KEM-768",c=this.#m([f.KEY_EXCHANGE],r,"Timed out waiting for peer key exchange");c.catch(()=>{});let l=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"]),h=new Uint8Array(await crypto.subtle.exportKey("raw",l.publicKey)),d=a?await Cr():null,w;if(i){let D=o??(s instanceof Uint8Array?s:null);if(!D)throw new TypeError("initiateE2E: signAs needs responderIdentity (or a raw verifyPeer key)");w=await i.sign(Qs({sessionId:e,algorithm:n,initiatorKey:h,responderIdentity:D}))}await this.#t.sendControl(kt({algorithm:n,publicKey:h,sessionId:e,kemPublicKey:d?.publicKey,signature:w}));let y=await c,_=a&&!!d&&!!y.kem_public_key,E=_&&Js(h,new Uint8Array(y.public_key))<0,g=null;_&&!E&&(g=this.#m([f.KEY_EXCHANGE],r,"Timed out waiting for peer ML-KEM-768 ciphertext"),g.catch(()=>{}));let A=!1;if(s!==void 0){if(!await hc(s,y.signature,{sessionId:e,algorithm:n,initiatorKey:h,responderKey:new Uint8Array(y.public_key??[])}))throw Object.assign(new Error(y.signature===void 0?"initiateE2E: the peer did not sign its key exchange (verifyPeer was given)":"initiateE2E: the peer's key exchange signature does not verify against verifyPeer"),{code:"E2E_PEER_UNAUTHENTICATED"});A=!0}let I=await crypto.subtle.importKey("raw",y.public_key,{name:"X25519"},!1,[]),S=new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:I},l.privateKey,256)),O=S;if(_){let D=new Uint8Array(y.kem_public_key),x;if(E){let{ciphertext:m,sharedSecret:L}=await Ir(D);x=L,await this.#t.sendControl(kt({algorithm:n,sessionId:e,kemCiphertext:m}))}else{let m=await g;x=await Nr(d.secretKeySeed,new Uint8Array(m.kem_ciphertext))}O=await kr(S,x)}return{sharedSecret:await crypto.subtle.importKey("raw",O,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),peerPublicKey:new Uint8Array(y.public_key),hybrid:_,peerAuthenticated:A}}async fileOperation(e,n,r={},s=Z){this.#d("fileOperation"),Rc(this,r.target,"fileOperation");let{target:i}=r;if(i===void 0&&this.preferRpcFiles&&vh.has(e)&&this.hasFeature(xt("wsh-fs"))){let c=null;try{c=await this.#se()}catch{}if(c)return this.#ie(c,e,n,r,s)}let o=this._nextChannelId(),a=c=>c.channel_id===o;if(e==="write"||e==="rename"){let c=e==="write"?"file-write":"file-rename";if(!this.hasFeature(c))throw new Error(`this host does not support file ${e} (no "${c}" feature)`);let l;if(e==="write"){if(l=typeof r.data=="string"?new TextEncoder().encode(r.data):r.data,!(l instanceof Uint8Array))throw new TypeError("fileWrite: data must be a string or Uint8Array")}else{if(typeof r.newPath!="string"||!r.newPath)throw new TypeError("fileRename: newPath is required");l=new TextEncoder().encode(r.newPath)}let h=this.#m([f.FILE_RESULT],s,`Timed out waiting for file ${e} result`,a);h.catch(()=>{}),await this.#t.sendControl(ds({channelId:o,op:e,path:n,offset:e==="write"?r.offset:void 0,length:l.byteLength,target:i}));let d=0;do{let w=Math.min(d+ii,l.byteLength);await this.#t.sendControl(hn({channelId:o,offset:d,data:l.subarray(d,w),isFinal:w>=l.byteLength,totalSize:l.byteLength})),d=w}while(d<l.byteLength);return h}return await this.#t.sendControl(ds({channelId:o,op:e,path:n,offset:r.offset,length:r.length,target:i})),this.#m([f.FILE_RESULT],s,`Timed out waiting for file ${e} result`,a)}preferRpcFiles=!0;#F=null;async#se(){if(this.#F){let n=await this.#F.catch(()=>null);if(n&&!n.closed)return n;this.#F=null}let e=this.openRpc("wsh-fs");this.#F=e;try{return await e}catch(n){throw this.#F===e&&(this.#F=null),n}}async#ie(e,n,r,s,i){let o=this._nextChannelId(),a=(l={},h=[])=>de({channelId:o,success:!0,metadata:l,entries:h}),c=i;try{switch(n){case"stat":return a(await e.request("stat",{path:r},{timeoutMs:c}));case"list":{let l=await e.request("list",{path:r},{timeoutMs:c});return a({path:l.path},l.entries)}case"read":{let l=[],h=await e.request("read",{path:r,offset:s.offset,length:s.length??ii},{timeoutMs:c,onProgress:y=>{y instanceof Uint8Array&&l.push(y)}}),d=new Uint8Array(l.reduce((y,_)=>y+_.byteLength,0)),w=0;for(let y of l)d.set(y,w),w+=y.byteLength;return a({data:d,size:h.size})}case"mkdir":case"remove":return a(await e.request(n,{path:r},{timeoutMs:c}));case"rename":if(typeof s.newPath!="string"||!s.newPath)throw new TypeError("fileRename: newPath is required");return a(await e.request("rename",{path:r,newPath:s.newPath},{timeoutMs:c}));case"write":{let l=typeof s.data=="string"?new TextEncoder().encode(s.data):s.data;if(!(l instanceof Uint8Array))throw new TypeError("fileWrite: data must be a string or Uint8Array");let h=Math.max(256,Math.min(256*1024,e.maxMessageBytes-1024)),d=s.offset===void 0||s.offset===null?void 0:Number(s.offset),w=0;do{let y=Math.min(w+h,l.byteLength),_=l.subarray(w,y);d===void 0?await e.request("upload",{path:r,data:_,offset:w||void 0},{timeoutMs:c}):await e.request("write",{path:r,data:_,offset:d+w},{timeoutMs:c}),w=y}while(w<l.byteLength);return a({written:l.byteLength})}default:throw new Error(`unsupported file op ${n}`)}}catch(l){if(l instanceof q&&l.code!==j.CANCELLED)return de({channelId:o,success:!1,errorMessage:l.message});throw l}}async fileStat(e,n){return this.fileOperation("stat",e,{},n)}async fileList(e,n){return this.fileOperation("list",e,{},n)}async fileRead(e,n,r,s){return this.fileOperation("read",e,{offset:n,length:r},s)}async fileWrite(e,n,r,s){return this.fileOperation("write",e,{data:n,offset:r},s)}async fileMkdir(e,n){return this.fileOperation("mkdir",e,{},n)}async fileRemove(e,n){return this.fileOperation("remove",e,{},n)}async fileRename(e,n,r){return this.fileOperation("rename",e,{newPath:n},r)}async addAuthorizedKey(e,n,r=Z){this.#d("addAuthorizedKey"),await this.#t.sendControl(Go({publicKey:e,comment:n}));let s=await this.#m([f.AUTHORIZED_KEY_RESULT],r,"Timed out waiting for authorized-key-add result");if(!s.success)throw new Error(s.error_message||"key installation refused");return{added:!!s.added}}async evaluatePolicy(e,n,r={},s=Z){this.#d("evaluatePolicy");let i=`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return await this.#t.sendControl(Bo({requestId:i,action:e,principal:n,context:r})),this.#m([f.POLICY_RESULT],s,"Timed out waiting for policy evaluation result")}async updatePolicy(e,n,r){this.#d("updatePolicy"),Qt("updatePolicy",{policyId:e,rules:n,version:r}),await this.#t.sendControl(Ho({policyId:e,rules:n,version:r}))}async#oe(e,n,r){let s=this.#ce(e,n),i=[];for(let o of s){let a=this.#ae(o.kind);try{return await a.connect(o.url,o.kind==="wt"?r:void 0),this.#y=o.kind==="wt"?Gh(r):null,this.#Z(a),a}catch(c){i.push(`${o.kind}: ${c?.message||c}`);try{await a.close()}catch{}}}throw new $n("CONNECTION_FAILED",`Connection failed across transports (${i.join("; ")})`,{attempts:i})}#ae(e){let n=this.#A[e];if(!n)throw new Error(`Unsupported transport: ${e}`);return n()}#ce(e,n){if(n==="wt")return[{kind:"wt",url:e}];if(n==="ws")return[{kind:"ws",url:e}];if(n!=null&&n!=="auto")throw new Error(`Unknown transport hint: ${JSON.stringify(n)} (expected 'wt', 'ws', or 'auto')`);return/^wss?:\/\//i.test(e)?[{kind:"ws",url:e}]:[{kind:"wt",url:e},{kind:"ws",url:e}]}#Z(e){e.onControl=n=>this.#le(n),e.onClose=()=>this.#ue(()=>this.#de()),e.onError=n=>this.#pe(n),e.onDatagram=n=>{this.#l||this.#x?.handleDatagram(n)}}static withTransport(e){let n=new t;return n.#t=e,n}async connectWithTransport(e,n,r){return this.#e=Tc,await e.connect(n),this.#Z(e),this.#t=e,this.#e=xc,this.#fe({...r,url:n})}async#H(e,n){let r=this.#t?.tlsExporter?.(xa,Sa)??null,{binding:s,kinds:i}=await Ca(e,{host:this.#s?.publicKey??null,"cert-hash":this.#y,"tls-exporter":r});if(n){let a=(Array.isArray(n)?n:[]).filter(c=>!i.includes(c));if(i.length===0||a.length){let c=Ns(e);throw new Error(`channel binding required but not available (host offers: ${c.join(", ")||"none"}; bound: ${i.join(", ")||"none"}${a.length?`; missing: ${a.join(", ")}`:""}) -- nothing was signed`)}}return this.#f=i,s}get channelBinding(){return[...this.#f]}async#G(e,n){let{expectHostKey:r,knownHosts:s,trustOnFirstUse:i,nonce:o,username:a}=n,c=!!(r||s),l=e?Ac(e.features):null;if(!l){if(c)throw new ye("HOST_KEY_MISSING","host key required (expectHostKey/knownHosts) but the server presented none; refusing before sending credentials");return}let{key:h,sig:d}=l;if(!h||h.byteLength!==32||!d)throw new ye("HOST_KEY_INVALID","server advertised a malformed host key or no proof of possession");let w=!1,y;try{y=await oe(h),w=await Le(await pe(h),d,Br({sessionId:e.session_id,clientNonce:o,username:a}))}catch{w=!1}if(!w)throw new ye("HOST_KEY_INVALID","host key proof does not verify (not signed over this connection)");if(e.host_fingerprint&&e.host_fingerprint!==y)throw new ye("HOST_KEY_INVALID","ServerHello.host_fingerprint does not match the advertised host key");let _="";try{_=await Ut(await pe(h))}catch{}let E={fingerprint:y,publicKey:h,openssh:_,status:"unpinned"};if(this.#s=E,r){let I=await Kh(r);if(I!==y)throw new ye("HOST_KEY_MISMATCH",`host key mismatch: expected ${I}, host presented ${y}`,{expected:I,actual:y});E.status="pinned"}let g=n.hostLabel;if(s){if(!g)try{g=new URL(n.url).host}catch{g=String(n.url)}let I=s.verifyHost(g,y);if(I.status==="changed")throw new ye("HOST_KEY_MISMATCH",`HOST KEY CHANGED for ${g}: pinned ${I.expected}, host presented ${y} (possible impersonation)`,{expected:I.expected,actual:y});E.status=I.status}let A=n.onHostKey??this.onHostKey;if(typeof A=="function"){let I;try{I=await A({...E})}catch(S){throw new ye("HOST_KEY_REJECTED",`onHostKey threw: ${S?.message??S}`)}if(I===!1)throw new ye("HOST_KEY_REJECTED","host key rejected by onHostKey")}if(s&&E.status==="unknown"){if(!i&&typeof A!="function")throw new ye("HOST_KEY_UNKNOWN",`${g} is not in knownHosts; pass trustOnFirstUse: true (or an onHostKey) to pin it`,{actual:y});s.addHost(g,y)}}#W(e,n,r){if(e===!1||e==="auto"&&!n.includes(Er))return!1;let s=n.includes(_n)?this.#s?.publicKey?r?null:"a sealed session needs a key login (a password login has nothing to sign with)":"the host proved no host key to authenticate the exchange against":`the host does not offer "${_n}" (it needs a host key and a connection without client-opened data streams)`;if(s)throw new Error(`sealed session: ${s} -- nothing was sent`);return!0}async#z(e){let n=this.#n,r=this.#s?.publicKey;if(!n||!r||!this.#o)throw new Error("sealed session: no session id, host key or login key -- nothing was sent");let s=this.#t,i=s.sendControl.bind(s),o=null;this.#l={sessionId:n,bridge:null},s.sendControl=async c=>{if(c.type===f.PING||c.type===f.PONG)return i(c);if(o)return i(await o.seal(c));if(c.type===f.KEY_EXCHANGE&&c.session_id===n)return i(c);throw new Error("sealed session: nothing is sent before the key exists")};let{sharedSecret:a}=await this.initiateE2E(n,"X25519+ML-KEM-768",e,{verifyPeer:r,signAs:this.#o,responderIdentity:r});o=new Tt({key:a,sessionId:n,role:"initiator",scope:"session"}),this.#l={sessionId:n,bridge:o}}#le(e){let n=this.#l;if(!n||e.type===f.PING||e.type===f.PONG){this.#K(e);return}if(n.bridge){if(!n.bridge.isFrame(e)){this.#U({reason:"plaintext-on-sealed-session",messageType:e.type});return}this.#te(n.bridge.open(e).then(r=>{this.#l===n&&this.#K(r)},r=>this.#he(n,r)));return}if(e.type===f.KEY_EXCHANGE&&e.session_id===n.sessionId){this.#K(e);return}this.#U({reason:"plaintext-before-seal",messageType:e.type})}#J=0;#ee=[];#te(e){this.#J++;let n=()=>{if(!(--this.#J>0))for(let r of this.#ee.splice(0))r()};e.then(n,n)}#ue(e){this.#J===0?e():this.#ee.push(e)}#he(e,n){this.#l!==e||this.#e===nt||(this.#l={...e,failed:!0},this.#Y(new Error(`wsh: a sealed frame did not open (${n.message}); the session is closed`)),this.#t?.close().catch(()=>{}))}async#fe({username:e,keyPair:n,signer:r,password:s,timeout:i=Sc,url:o,requireChannelBinding:a=!1,sealSession:c="auto",...l}={}){if(!e)throw new Error("username is required");Nc(c),this.#l=null;let h=await Je({keyPair:n,signer:r});if(this.#o=h,this.#a=e,!h&&!s)throw new Error("Either keyPair, signer or password is required");this.#s=null,this.#f=[],this.#y=null;try{let d=h?te.PUBKEY:te.PASSWORD,w=ri();await this.#t.sendControl(is({username:e,authMethod:d,features:[vn+w,et,...this.#t.supportsDatagrams?[zt]:[]]}));let y={...l,url:o,username:e,nonce:w},_=await this.#m([f.SERVER_HELLO,f.CHALLENGE,f.AUTH_FAIL],i,Hr("Auth handshake timed out"));if(_.type===f.AUTH_FAIL)throw new St(_.reason||"unknown");let E=null,g=!1;if(_.type===f.SERVER_HELLO){E=_.session_id,this.#b=_.features||[];let I=d===te.PUBKEY?this.#m([f.CHALLENGE,f.AUTH_OK],i,"Timed out waiting for challenge"):null;if(I?.catch(()=>{}),await this.#G(_,y),g=this.#W(c,this.#b,!!h),d===te.PUBKEY){let S=await I;if(S.type===f.AUTH_OK)return this.#n=S.session_id||E,this.#r=S.token||null,this.#i=Number(S.ttl)||0,this.#e=Jt,g&&await this.#z(i),this.#V(),this.#n;let{signature:O,publicKeyRaw:N}=await vt(h,S.session_id,S.nonce,{username:e,channelBinding:await this.#H(this.#b,a)});await this.#t.sendControl(pt({method:te.PUBKEY,signature:O,publicKey:N}))}else await this.#t.sendControl(pt({method:te.PASSWORD,password:s}))}else if(_.type===f.CHALLENGE){if(!h)throw new Error("Server sent CHALLENGE but no key pair provided");await this.#G(null,y),g=this.#W(c,[],!0),E=_.session_id;let{signature:I,publicKeyRaw:S}=await vt(h,_.session_id,_.nonce,{username:e,channelBinding:await this.#H([],a)});await this.#t.sendControl(pt({method:te.PUBKEY,signature:I,publicKey:S}))}let A=await this.#m([f.AUTH_OK,f.AUTH_FAIL],i,"Timed out waiting for auth result");if(A.type===f.AUTH_FAIL)throw new St(A.reason||"rejected");return this.#n=A.session_id||E,this.#r=A.token||null,this.#i=Number(A.ttl)||0,this.#e=Jt,g&&await this.#z(i),this.#V(),this.#n}catch(d){throw this.#e=nt,await this.#t?.close().catch(()=>{}),this.#t=null,this.#j(d),d}}#K(e,n){let r=e.type;if(r===f.RELAY_FORWARD){if(!this.#w.has(e.from_fingerprint)){console.warn("[wsh:client] dropping RelayForward from untrusted/unaccepted peer:",e.from_fingerprint);return}let i;try{i=dt(e.inner)}catch(a){console.error("[wsh:client] failed to decode RelayForward inner envelope:",a);return}if(!Dt(i.type)){console.warn("[wsh:client] dropping RelayForward wrapping a non-forwardable type:",i.type);return}let o=this.#u;if(o){if(o.bridge?.isFrame(i)){this.#te(o.bridge.open(i).then(c=>this.#K(c,e.from_fingerprint)).catch(c=>this.#U({reason:"unopenable-bridge-frame",detail:c.message})));return}if(!(!o.bridge&&i.type===f.KEY_EXCHANGE&&i.session_id===o.sessionId)){this.#U({reason:"plaintext-on-sealed-bridge",messageType:i.type});return}}this.#K(i,e.from_fingerprint);return}if(this.#ye(e),r===f.OPEN_OK||r===f.OPEN_FAIL){let i=this.#p.shift();if(!i)return;if(clearTimeout(i.timer),r===f.OPEN_FAIL){i.reject(new Error(`Failed to open session: ${e.reason||"rejected"}`));return}let o=e.channel_id??i.requestedChannelId,a=e.stream_ids??{},c=e.data_mode==="virtual"?"virtual":"stream";if(this.#l&&c!=="virtual"){i.reject(new Error("Failed to open session: the host answered with a data stream, and a sealed session carries none"));return}let l=Array.isArray(e.capabilities)?e.capabilities:[],h=new wn(this.#t,o,a,i.kind,{dataMode:c,capabilities:l,sessionId:e.session_id,resumeToken:e.token,stderrChannelId:e.stderr_channel_id});if(this.#h.set(o,h),h.stderrChannelId!==void 0&&this.#h.set(h.stderrChannelId,h),c==="virtual"){h._activateVirtual(d=>this.sendRelayControl(d)),i.attach?.(h),i.resolve(h);return}this.#t.openStream().then(async d=>{if(h._bind(d.readable,d.writable),i.attach?.(h),i.kind==="exec"&&i.primer&&!this.hasFeature(Cs))try{await h.write(new Uint8Array([0]))}catch(w){i.reject(w);return}i.resolve(h)},d=>i.reject(d));return}if(r===f.PRESENCE&&this.#E.length>0){let i=Array.isArray(e.attachments)?e.attachments.find(o=>o?.channel_id!==void 0&&this.#E.some(a=>a.sessionId===o.session_id)):void 0;if(i){let o=this.#E.find(c=>c.sessionId===i.session_id),a=new wn(this.#t,i.channel_id,{},"pty",{dataMode:"virtual",capabilities:["resize","signal"],sessionId:i.session_id,resumeToken:o.token});a._setSeq(Number.isSafeInteger(i.seq)?i.seq:0),this.#h.set(i.channel_id,a),a._activateVirtual(c=>this.sendRelayControl(c)),Object.defineProperty(e,"session",{value:a,enumerable:!1})}}if(this.#_.has(r)){let i=this.#_.get(r);for(let o=0;o<i.length;o++){if(i[o].match&&!i[o].match(e))continue;let a=i.splice(o,1)[0];i.length===0&&this.#_.delete(r),clearTimeout(a.timer),a.resolve(e);return}}for(let[i,o]of this.#_)if(typeof i=="string"&&i.startsWith("multi:"))for(let a=0;a<o.length;a++){if(!o[a].types?.includes(r)||o[a].match&&!o[a].match(e))continue;let c=o.splice(a,1)[0];o.length===0&&this.#_.delete(i),clearTimeout(c.timer),c.resolve(e);return}if(r===f.GATEWAY_CREDIT&&Vt(e.gateway_id)!==void 0){this.#g.get(Vt(e.gateway_id))?.grant(e.bytes);return}if(r>=112&&r<=127){if(this.#x?.handle(e))return;try{this.onGatewayMessage?.(e)}catch(i){console.error("[wsh:client] onGatewayMessage handler error:",i)}return}let s=e.channel_id;if(s!==void 0&&this.#h.has(s)){let i=this.#h.get(s);i._handleControlMessage(e),r===f.CLOSE&&(this.#h.delete(s),i.stderrChannelId!==void 0&&this.#h.delete(i.stderrChannelId));return}if(this.onRelayMessage&&this._isRelayForwardable(r)){try{this.onRelayMessage(e,n)}catch(i){console.error("[wsh:client] onRelayMessage handler error:",i)}return}switch(r){case f.PING:this.#t?.sendControl(Jn({id:e.id})).catch(()=>{});break;case f.PONG:this.#O=Date.now();break;case f.ERROR:console.error("[wsh:client] Server error:",e.code,e.message),this.#Y(new Error(`Server error ${e.code}: ${e.message}`));break;case f.SHUTDOWN:console.warn("[wsh:client] Server shutdown:",e.reason),this.disconnect().catch(()=>{});break;case f.IDLE_WARNING:this.#t?.sendControl(as({id:++this.#P})).catch(()=>{});break;case f.REVERSE_CLOSE:try{this.onReverseClose?.(e)}catch(i){console.error("[wsh:client] onReverseClose handler error:",i)}break;case f.REVERSE_PROOF:try{this.onReverseProof?.(e)}catch(i){console.error("[wsh:client] onReverseProof handler error:",i)}break;case f.REVERSE_CONNECT:try{this.onReverseConnect?.(e)}catch(i){console.error("[wsh:client] onReverseConnect handler error:",i)}break;case f.CLIPBOARD:if(e.direction==="server_to_client"&&e.data)try{let i=atob(e.data);navigator.clipboard?.writeText(i).catch(()=>{})}catch{}try{this.onClipboard?.(e)}catch(i){console.error("[wsh:client] onClipboard handler error:",i)}break;case f.PRESENCE:case f.CONTROL_CHANGED:case f.METRICS:break;case f.COMPRESS_BEGIN:this.#t?.sendControl(ko({algorithm:e.algorithm,accepted:!1})).catch(()=>{});break;case f.RATE_WARNING:try{this.onRateWarning?.(e)}catch(i){console.error("[wsh:client] onRateWarning handler error:",i)}break;case f.COPILOT_SUGGEST:try{this.onCopilotSuggest?.(e)}catch(i){console.error("[wsh:client] onCopilotSuggest handler error:",i)}break;case f.KEY_EXCHANGE:try{this.onKeyExchange?.(e)}catch(i){console.error("[wsh:client] onKeyExchange handler error:",i)}break;default:break}}#de(){if(this.#e!==nt){this.#e=nt,this.#T=null,this.#x?.abandonAll("transport closed"),this.#B(),this.#j(new Error("Transport closed"));for(let e of this.#h.values())e._handleControlMessage({type:f.CLOSE});this.#h.clear(),this.#g.clear();try{this.onClose?.()}catch(e){console.error("[wsh:client] onClose handler error:",e)}}}#pe(e){this.#Y(e)}#m(e,n,r,s,i){let o=Array.isArray(e)?e:[e];return new Promise((a,c)=>{let l=setTimeout(()=>{this.#ne(w,d),i?.removeEventListener("abort",h),c(r instanceof Error?r:new Error(r))},n),h=()=>{clearTimeout(l),this.#ne(w,d),c(Ae(i))};if(i){if(i.aborted){clearTimeout(l),c(Ae(i));return}i.addEventListener("abort",h,{once:!0})}let d={resolve:y=>{i?.removeEventListener("abort",h),a(y)},reject:y=>{i?.removeEventListener("abort",h),c(y)},timer:l,types:o,match:s},w=o.length===1?o[0]:`multi:${o.join(",")}`;this.#_.has(w)||this.#_.set(w,[]),this.#_.get(w).push(d)})}#ne(e,n){let r=this.#_.get(e);if(!r)return;let s=r.indexOf(n);s!==-1&&r.splice(s,1),r.length===0&&this.#_.delete(e)}#j(e){for(let[,n]of this.#_)for(let r of n)clearTimeout(r.timer),r.reject(e);this.#_.clear();for(let n of this.#p)clearTimeout(n.timer),n.reject(e);this.#p.length=0}#V(){this.#B(),this.#O=Date.now(),this.#S=setInterval(()=>{if(this.#e!==Jt){this.#B();return}if(this.#O!==null&&Date.now()-this.#O>this.#N){let e=Date.now()-this.#O;this.#B(),this.#Y(new Error(`wsh: peer stopped answering keepalive pings ${e}ms ago`));return}this.#t?.sendControl(as({id:++this.#P})).catch(e=>{console.warn("[wsh:client] Failed to send ping:",e.message)})},this.#M),typeof this.#S=="object"&&this.#S.unref&&this.#S.unref()}#B(){this.#S!==null&&(clearInterval(this.#S),this.#S=null)}_isRelayForwardable(e){return Dt(e)}_nextChannelId(){return++this.#C}#d(e){if(this.#e!==Jt)throw new Error(`Cannot ${e}: client is ${this.#e} (expected authenticated)`)}#ye(e){if(this.#R.size!==0)for(let n of[...this.#R])try{n(e)}catch(r){console.error("[wsh:client] control listener error:",r)}}#Y(e){try{this.onError?.(e)}catch(n){console.error("[wsh:client] onError handler error:",n)}}};var Ee=Object.freeze({CONNECTION_REFUSED:1,HOST_UNREACHABLE:2,DNS_FAILED:3,POLICY_DENIED:4,TIMEOUT:5,CLOSED:6,QUEUE_FULL:7}),ey=Object.freeze([Object.freeze({name:"CONNECTION_REFUSED",code:1,meaning:"The destination actively refused the connection (nothing listens there)."}),Object.freeze({name:"HOST_UNREACHABLE",code:2,meaning:"The destination could not be reached on the network (no route, connect failed, socket error)."}),Object.freeze({name:"DNS_FAILED",code:3,meaning:"The name did not resolve, or is not a valid name."}),Object.freeze({name:"POLICY_DENIED",code:4,meaning:"The host refused by policy: the key lacks the capability, the address is not allowed, the endpoint or target does not exist or is not for this caller, or the request was malformed or reused an id."}),Object.freeze({name:"TIMEOUT",code:5,alsoSentAs:Object.freeze(["GATEWAY_DISABLED"]),meaning:"The host did not finish in time. The Rust wsh-server sends this number when its gateway is disabled."}),Object.freeze({name:"CLOSED",code:6,meaning:"The gateway connection was closed before the operation finished."}),Object.freeze({name:"QUEUE_FULL",code:7,meaning:"The host holds too many gateway connections or too much unsent data, and takes no more for now."})]),ty=Object.freeze({UNSUPPORTED:0});var Wh="wsh:known-hosts:v1",oi=class{#e=new Map;getItem(e){return this.#e.has(e)?this.#e.get(e):null}setItem(e,n){this.#e.set(e,n)}removeItem(e){this.#e.delete(e)}};function zh(){return typeof localStorage<"u"&&localStorage?localStorage:new oi}var Gr=class{#e;#n;constructor({storage:e,storageKey:n=Wh}={}){this.#e=e||zh(),this.#n=n}verifyHost(e,n){let r=this.#r();return e in r?r[e]===n?{status:"known"}:{status:"changed",expected:r[e]}:{status:"unknown"}}addHost(e,n){let r=this.#r();r[e]=n,this.#i(r)}removeHost(e){let n=this.#r();return e in n?(delete n[e],this.#i(n),!0):!1}list(){let e=this.#r();return Object.entries(e).map(([n,r])=>({host:n,fingerprint:r}))}#r(){let e=this.#e.getItem(this.#n);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}}#i(e){this.#e.setItem(this.#n,JSON.stringify(e))}};var Wr=class t{sessionId;startTime;entries=[];#e=80;#n=24;constructor(e,{width:n=80,height:r=24}={}){if(!e)throw new Error("sessionId is required");this.sessionId=e,this.startTime=Date.now(),this.entries=[],this.#e=n,this.#n=r}record(e,n){let r=Date.now()-this.startTime;this.entries.push({t:r,type:e,data:n}),e==="resize"&&n&&(n.cols&&(this.#e=n.cols),n.rows&&(this.#n=n.rows))}toJSON(){let e=this.entries.map(({t:n,type:r,data:s})=>{let i=n/1e3,o=jh[r]||r,a;return r==="resize"&&s?a=`${s.cols}x${s.rows}`:r==="exit"&&s?a=String(s.code??0):r==="open"&&s?a=JSON.stringify(s):a=typeof s=="string"?s:JSON.stringify(s),[i,o,a]});return{version:2,width:this.#e,height:this.#n,timestamp:Math.floor(this.startTime/1e3),env:{TERM:"xterm-256color",SHELL:"/bin/bash"},sessionId:this.sessionId,events:e}}static fromJSON(e){let n=typeof e=="string"?JSON.parse(e):e;if(!n.version||n.version<2)throw new Error(`Unsupported recording version: ${n.version}`);let r=new t(n.sessionId||"imported",{width:n.width||80,height:n.height||24});if(r.startTime=(n.timestamp||Math.floor(Date.now()/1e3))*1e3,r.entries=[],Array.isArray(n.events))for(let s of n.events){if(!Array.isArray(s)||s.length<3)continue;let[i,o,a]=s,c=Math.round(i*1e3),l=Vh[o]||o,h;if(l==="resize"&&typeof a=="string"){let d=a.match(/^(\d+)x(\d+)$/);h=d?{cols:parseInt(d[1],10),rows:parseInt(d[2],10)}:a}else if(l==="exit")h={code:parseInt(a,10)||0};else if(l==="open")try{h=JSON.parse(a)}catch{h=a}else h=a;r.entries.push({t:c,type:l,data:h})}return r}get duration(){return this.entries.length===0?0:this.entries[this.entries.length-1].t}get length(){return this.entries.length}},jh={output:"o",input:"i",resize:"r",open:"open",exit:"exit"},Vh={o:"output",i:"input",r:"resize"};function Lc(t){if(!t||typeof t.spawn!="function")throw new TypeError("createWshServer: pty.spawn must be a function (e.g. node-pty's spawn)");return{spawn:t.spawn,shell:t.shell??globalThis.process?.env?.SHELL??"/bin/sh",cwd:t.cwd,env:t.env,term:t.term??"xterm-256color",clientEnv:t.clientEnv}}var Yh=new Set(["string","number","integer","boolean","null","object","array"]),qh=new Set(["$schema","$id","$comment","title","description","default","examples","format","definitions","$defs","deprecated","readOnly","writeOnly"]),Xh=new Set(["type","enum","const","properties","required","additionalProperties","items","minItems","maxItems","uniqueItems","minLength","maxLength","pattern","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","allOf","anyOf","oneOf","not","$ref","minProperties","maxProperties"]),kc=64,Zt=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function Mc(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}function Jh(t,e){let n=Mc(t);return n===e||e==="number"&&n==="integer"}function Kn(t,e){if(t===e)return!0;if(typeof t!=typeof e||t===null||e===null||typeof t!="object"||Array.isArray(t)!==Array.isArray(e))return!1;if(Array.isArray(t))return t.length===e.length&&t.every((s,i)=>Kn(s,e[i]));let n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&n.every(s=>Object.hasOwn(e,s)&&Kn(t[s],e[s]))}function st(t,e="#",n=0){if(n>kc)throw new TypeError(`inputSchema at ${e} is nested too deeply`);if(!(t===!0||t===!1)){if(!Zt(t))throw new TypeError(`inputSchema at ${e} must be an object`);for(let r of Object.keys(t))if(!Xh.has(r)&&!qh.has(r))throw new TypeError(`inputSchema at ${e} uses unsupported keyword "${r}"`);if(t.type!==void 0){let r=Array.isArray(t.type)?t.type:[t.type];for(let s of r)if(!Yh.has(s))throw new TypeError(`inputSchema at ${e} has unknown type ${JSON.stringify(s)}`)}if(t.pattern!==void 0)try{new RegExp(t.pattern,"u")}catch{throw new TypeError(`inputSchema at ${e} has an invalid pattern`)}if(t.required!==void 0&&!(Array.isArray(t.required)&&t.required.every(r=>typeof r=="string")))throw new TypeError(`inputSchema at ${e}: required must be an array of strings`);if(Zt(t.properties))for(let[r,s]of Object.entries(t.properties))st(s,`${e}/properties/${r}`,n+1);else if(t.properties!==void 0)throw new TypeError(`inputSchema at ${e}: properties must be an object`);t.additionalProperties!==void 0&&typeof t.additionalProperties!="boolean"&&st(t.additionalProperties,`${e}/additionalProperties`,n+1),t.items!==void 0&&st(t.items,`${e}/items`,n+1);for(let r of["allOf","anyOf","oneOf"])if(t[r]!==void 0){if(!Array.isArray(t[r]))throw new TypeError(`inputSchema at ${e}: ${r} must be an array`);t[r].forEach((s,i)=>st(s,`${e}/${r}/${i}`,n+1))}t.not!==void 0&&st(t.not,`${e}/not`,n+1);for(let r of["definitions","$defs"])if(Zt(t[r]))for(let[s,i]of Object.entries(t[r]))st(i,`${e}/${r}/${s}`,n+1);if(t.$ref!==void 0&&!(typeof t.$ref=="string"&&t.$ref.startsWith("#")))throw new TypeError(`inputSchema at ${e}: only local "#..." $ref is supported`)}}function Qh(t,e){if(e==="#")return t;if(!e.startsWith("#/"))return;let n=t;for(let r of e.slice(2).split("/")){let s=r.replace(/~1/g,"/").replace(/~0/g,"~");if(!Zt(n)&&!Array.isArray(n)||!Object.hasOwn(n,s))return;n=n[s]}return n}function Dc(t,e){let n=(s,i)=>`${s||"/"}: ${i}`;function r(s,i,o,a){if(a>kc)return n(o,"schema or value nested too deeply");if(s===!0)return null;if(s===!1)return n(o,"no value is allowed here");if(s.$ref!==void 0){let c=Qh(t,s.$ref);if(c===void 0)return n(o,`unresolvable $ref ${s.$ref}`);let l=r(c,i,o,a+1);if(l)return l}if(s.type!==void 0){let c=Array.isArray(s.type)?s.type:[s.type];if(!c.some(l=>Jh(i,l)))return n(o,`expected ${c.join(" | ")}, got ${Mc(i)}`)}if(s.enum!==void 0&&!s.enum.some(c=>Kn(c,i)))return n(o,"not one of the allowed values");if(s.const!==void 0&&!Kn(s.const,i))return n(o,"does not equal the required constant");if(typeof i=="string"){let c=[...i].length;if(s.minLength!==void 0&&c<s.minLength)return n(o,`shorter than ${s.minLength}`);if(s.maxLength!==void 0&&c>s.maxLength)return n(o,`longer than ${s.maxLength}`);if(s.pattern!==void 0&&!new RegExp(s.pattern,"u").test(i))return n(o,"does not match the required pattern")}if(typeof i=="number"){if(!Number.isFinite(i))return n(o,"must be a finite number");if(s.minimum!==void 0&&i<s.minimum)return n(o,`below the minimum ${s.minimum}`);if(s.maximum!==void 0&&i>s.maximum)return n(o,`above the maximum ${s.maximum}`);if(typeof s.exclusiveMinimum=="number"&&i<=s.exclusiveMinimum)return n(o,`must be above ${s.exclusiveMinimum}`);if(typeof s.exclusiveMaximum=="number"&&i>=s.exclusiveMaximum)return n(o,`must be below ${s.exclusiveMaximum}`);if(s.multipleOf!==void 0){let c=i/s.multipleOf;if(Math.abs(c-Math.round(c))>1e-9)return n(o,`not a multiple of ${s.multipleOf}`)}}if(Array.isArray(i)){if(s.minItems!==void 0&&i.length<s.minItems)return n(o,`fewer than ${s.minItems} items`);if(s.maxItems!==void 0&&i.length>s.maxItems)return n(o,`more than ${s.maxItems} items`);if(s.uniqueItems===!0){for(let c=0;c<i.length;c++)for(let l=c+1;l<i.length;l++)if(Kn(i[c],i[l]))return n(o,"items are not unique")}if(s.items!==void 0)for(let c=0;c<i.length;c++){let l=r(s.items,i[c],`${o}/${c}`,a+1);if(l)return l}}if(Zt(i)){let c=Object.keys(i);if(s.minProperties!==void 0&&c.length<s.minProperties)return n(o,`fewer than ${s.minProperties} properties`);if(s.maxProperties!==void 0&&c.length>s.maxProperties)return n(o,`more than ${s.maxProperties} properties`);for(let h of s.required??[])if(!Object.hasOwn(i,h))return n(o,`missing required property "${h}"`);let l=Zt(s.properties)?s.properties:{};for(let h of c)if(Object.hasOwn(l,h)){let d=r(l[h],i[h],`${o}/${h}`,a+1);if(d)return d}else{if(s.additionalProperties===!1)return n(o,`unexpected property "${h}"`);if(s.additionalProperties!==void 0&&s.additionalProperties!==!0){let d=r(s.additionalProperties,i[h],`${o}/${h}`,a+1);if(d)return d}}}for(let c of s.allOf??[]){let l=r(c,i,o,a+1);if(l)return l}if(s.anyOf&&!s.anyOf.some(c=>r(c,i,o,a+1)===null))return n(o,"matches none of the anyOf alternatives");if(s.oneOf){let c=s.oneOf.filter(l=>r(l,i,o,a+1)===null).length;if(c!==1)return n(o,`matches ${c} of the oneOf alternatives, expected exactly 1`)}return s.not!==void 0&&r(s.not,i,o,a+1)===null?n(o,"matches a schema it must not match"):null}return r(t,e,"",0)}var Zh=Object.freeze({type:"object"}),Pc=Object.freeze({maxConcurrent:8,timeoutMs:3e4});function Uc(t,e,n){if(typeof t!="string"||!t)throw new TypeError("createWshServer: every mcp tool needs a name");if(!e||typeof e.call!="function")throw new TypeError(`createWshServer: mcp tool "${t}" needs a call(args, ctx) function`);let r=e.inputSchema??e.parameters??Zh;return st(r,`#(${t})`),{name:t,description:String(e.description??""),inputSchema:r,call:e.call,origin:n}}function vc(t){if(!t||typeof t!="object")throw new TypeError("createWshServer: mcp must be an object");let e=new Map,n=Array.isArray(t.tools)?t.tools.map(c=>[c?.name,c]):Object.entries(t.tools??{});for(let[c,l]of n){if(e.has(c))throw new TypeError(`createWshServer: duplicate mcp tool "${c}"`);e.set(c,Uc(c,l,"local"))}let r=t.client??null;if(r&&(typeof r.listTools!="function"||typeof r.callTool!="function"))throw new TypeError("createWshServer: mcp.client needs listTools() and callTool() (an @modelcontextprotocol/sdk Client)");if(typeof t.authorize<"u"&&typeof t.authorize!="function")throw new TypeError("createWshServer: mcp.authorize must be a function");let s=new Map;async function i(){if(!r)return;let c=new Map,{tools:l=[]}=await r.listTools();for(let h of l)if(!(!h||typeof h.name!="string"||e.has(h.name)))try{c.set(h.name,Uc(h.name,{description:h.description,inputSchema:h.inputSchema,call:(d,w)=>o(h.name,d,w)},"proxy"))}catch{}s=c}async function o(c,l,{signal:h}){let d=await r.callTool({name:c,arguments:l},void 0,{signal:h});if(d?.isError){let w=Array.isArray(d.content)?d.content.filter(y=>y?.type==="text").map(y=>y.text).join(`
|
|
3
|
+
`):"";throw new Error(w||`tool ${c} failed`)}return d?.structuredContent??d?.content??null}let a=async(c,l,h)=>{if(!t.authorize)return!0;try{return await t.authorize(l,{name:c.name,description:c.description,inputSchema:c.inputSchema},h)===!0}catch{return!1}};return{maxConcurrent:t.maxConcurrent>0?t.maxConcurrent:Pc.maxConcurrent,timeoutMs:t.timeoutMs>=0?t.timeoutMs:Pc.timeoutMs,async list(c,l){await i();let h=[];for(let d of[...e.values(),...s.values()])await a(d,c,l)&&h.push({name:d.name,description:d.description,parameters:d.inputSchema});return h},async find(c,l,h){let d=e.get(c)??s.get(c);return!d&&r&&!e.has(c)&&(await i(),d=s.get(c)),d&&await a(d,l,h)?d:null},validate:(c,l)=>Dc(c.inputSchema,l)}}var ef=32,tf=4*1024*1024,nf=32*1024*1024,rf=1024*1024,sf=1e3,$c=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function of(t){let e=t.maxConnections??ef;if(!Number.isInteger(e)||e<1)throw new TypeError("gateway.maxConnections must be a positive integer");let n=t.maxBufferedBytes??tf,r=t.maxClientBufferedBytes??nf;if(!Number.isInteger(n)||n<262144)throw new TypeError(`gateway.maxBufferedBytes must be an integer of at least ${262144}`);if(!Number.isInteger(r)||r<n)throw new TypeError("gateway.maxClientBufferedBytes must be an integer of at least maxBufferedBytes");return{maxConnections:e,maxBufferedBytes:n,maxClientBufferedBytes:r}}function ai(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))throw new TypeError("gateway.endpoints must be an object of { name: handler }");let e=new Map;for(let[n,r]of Object.entries(t)){if(!$c.test(n))throw new TypeError(`gateway.endpoints: ${JSON.stringify(n)} is not a valid endpoint name (letters, digits, ".", "_", "-"; at most 64)`);let s=typeof r=="function"?r:r?.open;if(typeof s!="function")throw new TypeError(`gateway.endpoints[${JSON.stringify(n)}] needs a handler function (duplex, who) => void, or { open, authorize }`);if(r?.authorize!==void 0&&typeof r.authorize!="function")throw new TypeError(`gateway.endpoints[${JSON.stringify(n)}].authorize must be a function (who) => boolean`);e.set(n,{open:s,authorize:r?.authorize??null})}return e.size===0?null:e}function ci(t={}){return{...of(t),tcp:!1,unix:null,endpoints:ai(t.endpoints)}}function Kc(t){let e=[];return(t.tcp||t.reverse)&&e.push("gateway"),e.push(et),t.unix&&e.push("gateway-unix"),(t.endpoints||t.targetEndpoints)&&e.push("gateway-endpoints"),e}function af(t,e,n=()=>{},r={}){let s=new Map,i=new Set,o=!1,a=!1,c={used:0,max:t.maxClientBufferedBytes},l=E=>{try{return Promise.resolve(e(E)).catch(()=>{})}catch{return Promise.resolve()}},h=(E,g,A)=>l(Qn({gatewayId:E,code:g,message:A})),d=()=>s.size+i.size,w=E=>s.has(E)||i.has(E);function y(E,g){return new Wt({id:E,credit:o,maxQueued:t.maxBufferedBytes,budget:c,sendData:A=>l(tr({gatewayId:E,data:A})),sendCredit:A=>l(Xe({gatewayId:E,bytes:A})),sendClose:A=>l(Zn({gatewayId:E,reason:A})),...g,onClose:A=>{s.delete(E),g?.onClose?.(A)}})}async function _(E){let g=E.gateway_id;if(!Number.isInteger(g)||typeof E.name!="string")return h(g,Ee.POLICY_DENIED,"malformed OpenEndpoint");if(w(g))return h(g,Ee.POLICY_DENIED,"gateway_id already in use");let A=t.endpoints;if(E.target!==void 0&&E.target!==null){let m=r.target?await r.target(E.target):{refuse:"this host has no targets"};if(m.refuse)return h(g,Ee.POLICY_DENIED,m.refuse);A=m.endpoints}else if(r.requireTarget?.())return h(g,Ee.POLICY_DENIED,"a target is required");let I=A&&$c.test(E.name)?A.get(E.name):void 0;if(!I)return h(g,Ee.POLICY_DENIED,"no such endpoint");if(d()>=t.maxConnections)return h(g,Ee.QUEUE_FULL,"too many gateway connections");let S=r.who?.()??{username:null,fingerprint:null};i.add(g);try{if(I.authorize&&!await I.authorize(S))return i.delete(g),await h(g,Ee.POLICY_DENIED,"endpoint refused this caller")}catch(m){return i.delete(g),n(`gateway endpoint ${E.name} authorize threw: ${m.message}`),h(g,Ee.POLICY_DENIED,"endpoint refused this caller")}if(i.delete(g),a)return;let O=y(g,{writeAfterRemoteClose:!0,graceMs:sf});s.set(g,{channel:O,sock:null});let{readable:N,writable:D}=O.streams(),x={readable:N,writable:D,who:S,target:E.target??void 0,close:m=>O.end(m),destroy:m=>O.destroy(m),closed:O.closedPromise};try{let m=I.open(x,S);m&&typeof m.then=="function"&&m.then(void 0,L=>{n(`gateway endpoint ${E.name} failed: ${L?.message}`),O.destroy("endpoint error")})}catch(m){return n(`gateway endpoint ${E.name} threw: ${m.message}`),O.abandon(),h(g,Ee.POLICY_DENIED,"endpoint refused the connection")}return n(`gateway: ${g} -> endpoint ${E.name}`),l(To({gatewayId:g}))}return{conns:s,pending:i,budget:c,reply:l,fail:h,active:d,idInUse:w,makeChannel:y,get closed(){return a},setPeerFeatures(E){o=Array.isArray(E)&&E.includes(et)},async handle(E){if(a)return!0;switch(E.type){case f.OPEN_ENDPOINT:return await _(E),!0;case f.GATEWAY_DATA:{let g=s.get(E.gateway_id)?.channel,A=E.data;return g&&A&&A.length<=rf&&g.receive(A),!0}case f.GATEWAY_CREDIT:return o&&Number.isInteger(E.bytes)&&s.get(E.gateway_id)?.channel.grant(E.bytes),!0;case f.GATEWAY_CLOSE:return s.get(E.gateway_id)?.channel.remoteClosed(E.reason),!0;case f.OPEN_TCP:case f.OPEN_UDP:case f.RESOLVE_DNS:return await h(E.gateway_id,Ee.POLICY_DENIED,"only named endpoints are available on this host"),!0;case f.OPEN_UNIX:return await h(E.gateway_id,Ee.POLICY_DENIED,"unix sockets are not available on this host"),!0;case f.LISTEN_REQUEST:case f.LISTEN_UNIX:return await l(er({listenerId:E.listener_id,reason:"listening is not available on this host"})),!0;default:return!1}},close(){a=!0;for(let{channel:E}of[...s.values()])E.abandon("connection closed");s.clear()},get size(){return s.size},get bufferedBytes(){return c.used},get listenerCount(){return 0}}}function Bc(t,e,n,r){return af(t,e,n,r)}var cf=["operate","readWhole","writeWhole","writeAt"];function lf(t,e="fs"){if(!t||typeof t!="object")throw new TypeError(`${e} must be an object of file operations`);if(typeof t.root=="string"&&typeof t.operate!="function")throw new TypeError(`${e}.root names a directory, which needs Node: use @johnhenry/wsh/server, or give ${e} as an object of operations ({ operate, readWhole, writeWhole, writeAt })`);for(let s of cf)if(typeof t[s]!="function")throw new TypeError(`${e}.${s} must be a function`);if(t.openRange!==void 0&&typeof t.openRange!="function")throw new TypeError(`${e}.openRange must be a function`);let n=t.maxFileBytes??67108864;if(!Number.isSafeInteger(n)||n<1)throw new TypeError(`${e}.maxFileBytes must be a positive integer`);let r={maxFileBytes:n,operate:(...s)=>t.operate(...s),readWhole:(...s)=>t.readWhole(...s),writeWhole:(...s)=>t.writeWhole(...s),writeAt:(...s)=>t.writeAt(...s)};return t.openRange&&(r.openRange=(...s)=>t.openRange(...s)),r}function Wc(t,e,n,r="createMemoryHost"){if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError(`${r}: rpc must be an object of { [protocol]: handler }`);if(!(e>=256))throw new TypeError(`${r}: rpcMaxMessageBytes must be at least 256`);if(!Number.isSafeInteger(n)||n<1)throw new TypeError(`${r}: rpcMaxInflight must be a positive integer`);let s=new Map;for(let[i,o]of Object.entries(t))if(!(o===void 0||o===!1||o===null)){if(!Un.test(i))throw new TypeError(`${r}: rpc protocol name ${JSON.stringify(i)} is not allowed (letters, digits, ".", "_", "-")`);if(typeof o!="function")throw new TypeError(`${r}: rpc[${JSON.stringify(i)}] needs a handler function (channel, ctx) => void (the wsh-host / wsh-fs built-ins need Node; use @johnhenry/wsh/server)`);s.set(i,o)}return{protocols:s,maxMessageBytes:e,maxInflight:n}}var li=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Hc=["description","authorize","exec","pty","fs","endpoints"];function uf(t,e){return{maxFileBytes:t.maxFileBytes,operate:(n,r,s={})=>t.operate(n,r,{...s,target:e}),readWhole:(n,r={})=>t.readWhole(n,{...r,target:e}),writeWhole:(n,r,s={})=>t.writeWhole(n,r,{...s,target:e}),writeAt:(n,r,s,i={})=>t.writeAt(n,r,s,{...i,target:e}),...t.openRange?{openRange:(n,r={})=>t.openRange(n,{...r,target:e})}:{}}}function hf(t,e,n,r="host"){if(e!==void 0&&typeof e!="boolean")throw new TypeError(`${r}: requireTarget must be a boolean`);if(t==null){if(e)throw new TypeError(`${r}: requireTarget needs targets`);return{targets:null,requireTarget:!1}}if(typeof t!="object"||Array.isArray(t))throw new TypeError(`${r}: targets must be an object of { name: { exec, pty, fs, endpoints, authorize, description } }`);let s=new Map;for(let[i,o]of Object.entries(t)){if(!li.test(i))throw new TypeError(`${r}: targets: ${JSON.stringify(i)} is not a valid target name (letters, digits, ".", "_", "-"; at most 64)`);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError(`${r}: targets.${i} must be an object`);for(let c of Object.keys(o))if(!Hc.includes(c))throw new TypeError(`${r}: targets.${i}.${c} is not an option of a target (${Hc.join(", ")})`);if(o.authorize!==void 0&&typeof o.authorize!="function")throw new TypeError(`${r}: targets.${i}.authorize must be a function (who, { target, kind }) => boolean`);if(o.description!==void 0&&typeof o.description!="string")throw new TypeError(`${r}: targets.${i}.description must be a string`);let a=n({exec:o.exec,pty:o.pty,fs:o.fs});s.set(i,{name:i,description:o.description,authorize:o.authorize??null,execRunner:a.execRunner,execOptions:a.execOptions,pty:a.pty,files:a.files?uf(a.files,i):null,endpoints:ai(o.endpoints)})}return{targets:s.size?s:null,requireTarget:s.size?!!e:!1}}function zc({exec:t,pty:e,fs:n,mcp:r,targets:s,requireTarget:i}={}){return{...Gc({exec:t,pty:e,fs:n,mcp:r}),...hf(s,i,a=>Gc(a),"host")}}function Gc({exec:t,pty:e,fs:n,mcp:r}={}){let s=null,i={};if(typeof t=="function")s=t;else if(t!=null&&t!==!1){if(typeof t!="object"||typeof t.run!="function")throw new TypeError("exec must be a function run(command, io) or { run }: there is no shell to run `true` with here (use @johnhenry/wsh/server for that)");i=t,s=t.run}return{execRunner:s,execOptions:i,pty:e?Lc(e):null,files:n?lf(n):null,mcp:r?vc(r):null}}async function jc(t,e="hostKey"){t===!0&&(t=await ys(!1));let n=t&&typeof t=="object"&&t.privateKey&&t.publicKey,r=t&&typeof t=="object"&&typeof t.sign=="function"&&t.publicKey;if(!n&&!r)throw new TypeError(`${e} must be true, a CryptoKeyPair, or a signer { publicKey, sign(data) }`);let s=await Je(n?{keyPair:t}:{signer:t});return{publicKey:s.publicKeyRaw,fingerprint:await oe(s.publicKeyRaw),openssh:await Ut(await pe(s.publicKeyRaw)),sign:s.sign}}var vy=8*1024*1024;var Vc="relay-multi-operator";var ff=/^[A-Za-z_][A-Za-z0-9_]*$/;var df=Object.freeze(["TERM","COLORTERM","LANG","LANGUAGE","LC_*"]),Yc=t=>{let e=new Set,n=[];for(let r of t){if(typeof r!="string"||!r)throw new TypeError("clientEnv: list entries must be non-empty strings");r.endsWith("*")?n.push(r.slice(0,-1)):e.add(r)}return r=>e.has(r)||n.some(s=>r.startsWith(s))};function Bn(t){let e;if(t===void 0)e=Yc(df);else if(t===!0)e=()=>!0;else if(t===!1)e=()=>!1;else if(Array.isArray(t))e=Yc(t);else if(typeof t=="function")e=t;else throw new TypeError("clientEnv must be true, false, an array of names or a function (name, value) => boolean");return n=>{let r={};if(!n||typeof n!="object"||Array.isArray(n))return r;let s=0;for(let[i,o]of Object.entries(n)){if(++s>64)break;if(!ff.test(i)||typeof o!="string"||o.length>4096||o.includes("\0"))continue;let a=!1;try{a=e(i,o)===!0}catch{a=!1}a&&(r[i]=o)}return r}}var Ky=Object.freeze(["not-sealed","unauthorized","binding-required","bad-signature","method-disabled","rate-limited","bad-request","seal-failed","busy","proof-required","proof-failed","key-expired","not-permitted"]);function zr(t,e){if(t!=null&&typeof t!="function")throw new TypeError(`${e}: onRefused must be a function`)}function qc(t,e=()=>{}){return typeof t!="function"?()=>{}:(n,r={},s="")=>{let i={};for(let[o,a]of Object.entries(r))a!=null&&a!==""&&(i[o]=a);try{t({reason:n,who:i,detail:String(s)})}catch(o){e(`onRefused threw: ${o?.message??o}`)}}}var Gy=Object.freeze(["unknown-option","bad-syntax","bad-value","duplicate-option","unknown-capability","bad-capability"]),Wy=Object.freeze(["pty-not-permitted","exec-not-permitted","file-transfer-not-permitted","forced-command","max-sessions","mcp-not-permitted","relay-not-permitted","key-admin-not-permitted","capability-missing","key-expired"]),pf=new Set(["no-agent-forwarding","no-X11-forwarding","no-user-rc","no-port-forwarding"]),Xc=new Set(["restrict","no-pty","permit-pty","permit-exec","permit-mcp","permit-file-transfer","permit-relay",...pf]),yf=new Set(["command","max-sessions","capabilities","expires"]),Ef=/^[A-Za-z][A-Za-z0-9_-]*$/,wf=/^[1-9][0-9]{0,8}$/;function tl(){return{pty:!0,exec:!0,mcp:!0,fileTransfer:!0,relay:!0,forcedCommand:null,maxSessions:null,capabilities:null,expires:null}}var we=(t,e)=>({ok:!1,code:t,reason:e}),ui=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,mf=/^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/,gf=/^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/,_f=/^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/,Jc=["get","call","set","on"],bf=new Set(["exec","pty","relay","fs:read","fs:write"]),en=(t,e)=>({ok:!1,code:t,reason:e});function nl(t){return t==="*"?{port:"*"}:!/^[1-9][0-9]{0,4}$/.test(t)||Number(t)>65535?null:{port:Number(t)}}function Af(t){let e,n;if(t.startsWith("[")){let s=t.indexOf("]");if(s<0||t[s+1]!==":"||(e=t.slice(0,s+1),n=t.slice(s+2),!/^\[[0-9A-Fa-f:.]+\]$/.test(e)))return null}else{let s=t.lastIndexOf(":");if(s<0)return null;e=t.slice(0,s),n=t.slice(s+1);let i=e.startsWith("*.")?e.slice(2):e;if(e!=="*"&&!gf.test(i))return null}let r=nl(n);return r?{host:e.toLowerCase(),port:r.port}:null}function hi(t){if(typeof t!="string"||!t.startsWith("/"))return null;let e=t.slice(1).split("/");return e.every(n=>n!==""&&n!=="."&&n!=="..")?e:null}function Tf(t){if(/[\u0000-\u0020\u007f,"'\\]/.test(t))return null;if(t==="/*")return{path:"/",prefix:!0};if(t.endsWith("/*")){let e=t.slice(0,-2);return hi(e)&&!e.includes("*")?{path:e,prefix:!0}:null}return hi(t)&&!t.includes("*")?{path:t,prefix:!1}:null}function xf(t){if(t==="")return en("bad-capability","empty capability");if(/\s/.test(t))return en("bad-capability",`capability ${JSON.stringify(t)} contains whitespace`);let e=r=>en("bad-capability",`capability ${JSON.stringify(t)}: ${r}`);if(bf.has(t))return{ok:!0,cap:{raw:t,kind:t}};if(t.startsWith("gateway:")){let r=t.slice(8);if(r.startsWith("tcp:")||r.startsWith("udp:")){let s=Af(r.slice(4));return s?{ok:!0,cap:{raw:t,kind:r.slice(0,3),host:s.host,port:s.port}}:e("expected gateway:<tcp|udp>:<host>:<port>")}if(r.startsWith("listen:tcp:")){let s=nl(r.slice(11));return s?{ok:!0,cap:{raw:t,kind:"listen-tcp",port:s.port}}:e("expected gateway:listen:tcp:<port>")}return en("unknown-capability",`unknown capability ${JSON.stringify(t)}`)}if(t.startsWith("unix:")){let r=t.startsWith("unix:listen:"),s=Tf(t.slice(r?12:5));return s?{ok:!0,cap:{raw:t,kind:r?"listen-unix":"unix",...s}}:e("expected an absolute path, exact or ending in /*, without . or ..")}let n=(r,s,i,o)=>{let a=t.slice(r.length);return o&&a==="*"||i.test(a)?{ok:!0,cap:{raw:t,kind:s,name:a}}:e(`expected ${r}<name>`)};if(t.startsWith("endpoint:"))return n("endpoint:","endpoint",ui,!0);if(t.startsWith("target:"))return n("target:","target",ui,!0);if(t.startsWith("mcp:"))return n("mcp:","mcp",mf,!0);if(t.startsWith("rpc:"))return n("rpc:","rpc",ui,!1);if(t.startsWith("objects:")){let r=t.slice(8).split(":"),[s,i,...o]=r;return o.length||!(s==="*"||_f.test(s))?e("expected objects:<root>[:<get|call|set|on>]"):i!==void 0&&!Jc.includes(i)?e(`the operation must be one of ${Jc.join(", ")}`):{ok:!0,cap:{raw:t,kind:"objects",name:s,op:i??null}}}return en("unknown-capability",`unknown capability ${JSON.stringify(t)}`)}function fi(t){let e=Array.isArray(t)?t:t===""?[]:String(t).split(","),n=[];for(let r of e){if(typeof r!="string")return en("bad-capability","capabilities must be strings");let s=xf(r);if(!s.ok)return s;n.push(s.cap)}return{ok:!0,capabilities:e.slice(),parsed:n}}var Sf=[31,28,31,30,31,30,31,31,30,31,30,31],Rf=t=>t%4===0&&t%100!==0||t%400===0;function Of(t,e,n){let r=e<=2?t-1:t,s=Math.floor(r/400),i=r-s*400,o=Math.floor((153*(e+(e>2?-3:9))+2)/5)+n-1;return s*146097+i*365+Math.floor(i/4)-Math.floor(i/100)+o-719468}function rl(t){let e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))$/.exec(String(t));if(!e)return null;let[n,r,s,i,o,a]=[e[1],e[2],e[3],e[4],e[5],e[6]].map(Number);if(n<1970||r<1||r>12||s<1||s>(r===2&&Rf(n)?29:Sf[r-1])||i>23||o>59||a>59)return null;let c=0;if(e[7]){let l=Number(e[8]),h=Number(e[9]);if(l>23||h>59)return null;c=(e[7]==="+"?1:-1)*(l*3600+h*60)}return Of(n,r,s)*86400+i*3600+o*60+a-c}function Cf(t){let e=[],n=0,r=t.length;for(;;){let s="";for(;n<r&&t[n]!==","&&t[n]!=="=";){let o=t[n];if(o==='"'||o==="'"||o===" "||o===" ")return we("bad-syntax",`unexpected ${JSON.stringify(o)} in an option name`);s+=o,n++}if(!s)return we("bad-syntax","empty option (a stray comma)");let i=null;if(t[n]==="=")if(n++,t[n]==='"'){n++;let o="",a=!1;for(;n<r;){let c=t[n];if(c==="\\"&&t[n+1]==='"'){o+='"',n+=2;continue}if(c==='"'){a=!0,n++;break}o+=c,n++}if(!a)return we("bad-syntax",`unterminated quote in ${s}=`);if(n<r&&t[n]!==",")return we("bad-syntax",`text after the closing quote of ${s}=`);i=o}else{let o="";for(;n<r&&t[n]!==",";){let a=t[n];if(a==='"'||a==="'"||a==="="||a===" "||a===" ")return we("bad-syntax",`unexpected ${JSON.stringify(a)} in the value of ${s}= (quote the value with double quotes)`);o+=a,n++}i=o}if(e.push([s,i]),n>=r)return{ok:!0,items:e};if(n++,n>=r)return we("bad-syntax","empty option (a trailing comma)")}}function If(t){if(t==null||t==="")return{ok:!0,permissions:tl()};let e=Cf(String(t));if(!e.ok)return e;let n=new Set,r=new Set,s=null,i=null,o=null,a=null;for(let[w,y]of e.items){if(!Ef.test(w)||!(Xc.has(w)||yf.has(w)))return we("unknown-option",`unknown option ${JSON.stringify(w)}`);if(n.has(w))return we("duplicate-option",`option ${w} given twice`);if(n.add(w),Xc.has(w)){if(y!==null)return we("bad-value",`option ${w} takes no value`);r.add(w)}else{if(y===null)return we("bad-value",`option ${w} needs a value`);if(w==="command"){if(!y||/[\u0000-\u001f\u007f]/.test(y))return we("bad-value","command must be a non-empty string without control characters");s=y}else if(w==="capabilities"){let _=fi(y);if(!_.ok)return _;o=_}else if(w==="expires"){if(a=rl(y),a===null)return we("bad-value","expires must be an RFC 3339 timestamp such as 2030-01-01T00:00:00Z")}else{if(!wf.test(y))return we("bad-value","max-sessions must be a positive whole number");i=Number(y)}}}let c=r.has("restrict"),l=w=>c?r.has(w):!0,d={pty:l("permit-pty")&&!r.has("no-pty"),exec:c?r.has("permit-exec")||r.has("permit-pty")||s!==null:!0,mcp:l("permit-mcp"),fileTransfer:l("permit-file-transfer"),relay:l("permit-relay"),forcedCommand:s,maxSessions:i,capabilities:o?o.capabilities:null,expires:a};return Object.defineProperty(d,"_caps",{value:o?o.parsed:null,enumerable:!1}),s!==null&&(d.pty=!1,d.fileTransfer=!1,d.mcp=!1,d.relay=!1,d.exec=!0),{ok:!0,permissions:d}}var sl=t=>t._caps??(Array.isArray(t.capabilities)?fi(t.capabilities).parsed:null),Nf=new Set(["stat","list","read"]);function Qc(t,e){let n=String(e).toLowerCase(),r=n.includes(":")&&!n.startsWith("[")?`[${n}]`:n;return t==="*"?!0:t.startsWith("*.")?r.endsWith(t.slice(1))&&r.length>t.length-1:r===t}var Zc=(t,e)=>t==="*"||t===e;function el(t,e){if(!hi(e))return!1;if(!t.prefix)return e===t.path;let r=t.path==="/"?"":t.path;return e.startsWith(`${r}/`)&&e.length>r.length+1}var Hn=(t,e)=>t.name==="*"||t.name===e;function Lf(t,e){let n=sl(t),r=o=>n.some(a=>a.kind===o),s=(o,a)=>a?null:{code:"capability-missing",capability:o,reason:`missing capability ${o}`},i=()=>e.target===void 0||e.target===null?null:s(`target:${e.target}`,n.some(o=>o.kind==="target"&&Hn(o,e.target)));switch(e.kind){case"open":{let o;if(e.channel==="pty")o=s("pty",r("pty"));else if(e.channel==="exec")o=s("exec",r("exec"));else if(e.channel==="file"){let a=e.direction==="download"?"fs:read":"fs:write";o=s(a,r(a))}else if(e.channel==="rpc"){let a=e.protocol;if(e.authorizesItself===!0)return e.target===void 0||e.target===null?null:i();a==="wsh-fs"?o=s("fs:read",r("fs:read"))??s("fs:write",r("fs:write")):a==="mcp"?o=e.scoped?s("mcp:<tool>",r("mcp")):s("mcp:*",n.some(c=>c.kind==="mcp"&&c.name==="*")):a==="wsh-objects"&&e.scoped?o=s("rpc:wsh-objects",r("objects")||n.some(c=>c.kind==="rpc"&&c.name===a)):o=s(`rpc:${a}`,n.some(c=>c.kind==="rpc"&&c.name===a))}else o=s(e.channel,!1);return o??i()}case"file-op":{let o=Nf.has(e.op)?"fs:read":"fs:write";return s(o,r(o))??i()}case"mcp":return s("mcp:*",r("mcp"));case"mcp-call":case"mcp-tool":return s(`mcp:${e.tool}`,n.some(o=>o.kind==="mcp"&&Hn(o,e.tool)));case"objects":{let o=n.filter(a=>a.kind==="objects");return o.length?s(`objects:${e.root}${e.op==="walk"?"":`:${e.op}`}`,o.some(a=>Hn(a,e.root)&&(e.op==="walk"||a.op===null||a.op===e.op))):s("rpc:wsh-objects",n.some(a=>a.kind==="rpc"&&a.name==="wsh-objects"))}case"relay":return s("relay",r("relay"));case"key-admin":return{code:"key-admin-not-permitted",reason:"installing a key is not permitted for a restricted key"};case"tcp":case"udp":{let o=`gateway:${e.kind}:${e.host}:${e.port}`;return s(o,n.some(a=>a.kind===e.kind&&Qc(a.host,e.host)&&Zc(a.port,e.port)))}case"dns":return s(`gateway:tcp:${e.name}:*`,n.some(o=>o.kind==="tcp"&&Qc(o.host,e.name)));case"listen-tcp":return s(`gateway:listen:tcp:${e.port}`,n.some(o=>o.kind==="listen-tcp"&&Zc(o.port,e.port)));case"unix":return s(`unix:${e.path}`,n.some(o=>o.kind==="unix"&&el(o,e.path)));case"listen-unix":return s(`unix:listen:${e.path}`,n.some(o=>o.kind==="listen-unix"&&el(o,e.path)));case"endpoint":return s(`endpoint:${e.name}`,n.some(o=>o.kind==="endpoint"&&Hn(o,e.name)))??i();case"target":return s(`target:${e.name}`,n.some(o=>o.kind==="target"&&Hn(o,e.name)));default:return s(String(e.kind),!1)}}function jr(t,e,{activeSessions:n=0,now:r}={}){if(t.expires!==null&&t.expires!==void 0&&(r??Math.floor(Date.now()/1e3))>=t.expires)return{code:"key-expired",reason:"this key has expired"};if(e.kind==="login")return null;let s=kf(t,e,n);return s||(sl(t)?Lf(t,e):null)}function kf(t,e,n){let r=(s,i)=>({code:s,reason:i});switch(e.kind){case"open":{let s=e.channel;if(t.forcedCommand!==null&&s!=="exec")return r("forced-command","key is restricted to forced exec command");if(s==="pty"&&!t.pty)return r("pty-not-permitted","PTY not permitted for this key");if(s==="exec"&&!t.exec)return r("exec-not-permitted","exec access not permitted for this key");if(s==="file"&&!t.fileTransfer)return r("file-transfer-not-permitted","file transfer not permitted for this key");if(s==="rpc"){let i=e.protocol;if(i==="wsh-fs"&&!t.fileTransfer)return r("file-transfer-not-permitted","file transfer not permitted for this key");if(i==="mcp"&&!t.mcp)return r("mcp-not-permitted","MCP not permitted for this key");if(i!=="wsh-fs"&&i!=="mcp"&&i!=="wsh-host"&&!(t.pty&&t.exec&&t.mcp&&t.fileTransfer&&t.relay))return r("exec-not-permitted","this protocol is not permitted for a restricted key")}return(s==="pty"||s==="exec")&&t.maxSessions!==null&&n>=t.maxSessions?r("max-sessions",`max sessions for this key reached (${t.maxSessions})`):null}case"file-op":return t.forcedCommand!==null?r("forced-command","key is restricted to forced exec command"):t.fileTransfer?null:r("file-transfer-not-permitted","file transfer not permitted for this key");case"mcp":case"mcp-call":case"mcp-tool":return t.mcp?null:r("mcp-not-permitted","MCP not permitted for this key");case"relay":return t.relay?null:r("relay-not-permitted","relay not permitted for this key");case"tcp":case"udp":case"dns":case"listen-tcp":case"unix":case"listen-unix":case"endpoint":case"target":case"objects":return null;case"key-admin":return t.pty&&t.exec&&t.mcp&&t.fileTransfer&&t.relay&&t.forcedCommand===null?null:r("key-admin-not-permitted","installing a key is not permitted for a restricted key");default:return r("exec-not-permitted",`unknown request ${JSON.stringify(e.kind)}`)}}function il(t){let e=tl(),n=null;if(t.capabilities!==void 0){let r=fi(t.capabilities);if(!r.ok)return r;e.capabilities=r.capabilities,n=r.parsed}if(t.expires!==void 0){let r=null;if(typeof t.expires=="string"?r=rl(t.expires):t.expires instanceof Date&&Number.isFinite(t.expires.getTime())?r=Math.floor(t.expires.getTime()/1e3):typeof t.expires=="number"&&Number.isFinite(t.expires)&&(r=Math.floor(t.expires/1e3)),r===null)return we("bad-value","expires must be an RFC 3339 string, a Date or epoch milliseconds");e.expires=r}return Object.defineProperty(e,"_caps",{value:n,enumerable:!1}),{ok:!0,permissions:e}}var Mf=t=>t===" "||t===" ";function ol(t){let e=String(t).trim();if(!e||e.startsWith("#"))return{skip:"blank or comment"};let n=e,r=null;if(!/^ssh-ed25519[ \t]/.test(e)){let o=!1,a=0;for(;a<e.length;a++){let c=e[a];if(o){if(c==="\\"&&e[a+1]==='"'){a++;continue}c==='"'&&(o=!1)}else if(c==='"')o=!0;else if(Mf(c))break}if(o)return{skip:"unterminated quote in the options"};if(r=e.slice(0,a),n=e.slice(a).trim(),!/^ssh-ed25519[ \t]/.test(n))return{skip:"not an ssh-ed25519 key"}}let s;try{let o=dn(n);if(s=pn(o.data),!(s instanceof Uint8Array)||s.byteLength!==32)return{skip:"malformed key"}}catch{return{skip:"malformed key"}}let i=If(r);return i.ok?{key:s,options:r,permissions:i.permissions}:{refused:{code:i.code,reason:i.reason},key:s,options:r}}var Df=/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;function Pf(t){return t<=31||t>=127&&t<=159||t===8232||t===8233||t===47||t===92}function Uf(t){for(let e=0;e<t.length;e++)if(Pf(t.charCodeAt(e)))return!0;return!1}function Vr(t,e){if(t==null)return Df;let n;try{t instanceof RegExp?n=new RegExp(t.source,t.flags.replace(/[gy]/g,"")):typeof t=="string"&&(n=new RegExp(t))}catch(r){throw new TypeError(`${e}: usernamePattern is not a valid pattern (${r.message})`)}if(!n)throw new TypeError(`${e}: usernamePattern must be a RegExp or a pattern string`);if(n.test(""))throw new TypeError(`${e}: usernamePattern must not match the empty name`);return n}function al(t,e){return typeof e!="string"||e.length===0||e.length>256||Uf(e)||e==="."||e===".."?!1:t.test(e)}var ll="shares",vf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ff=new Set(["ENOENT","EEXIST","ENOTDIR","EISDIR","ENOTEMPTY","EACCES","EPERM","EROFS","EINVAL","EBADF","ELOOP","ENAMETOOLONG","ENOSPC","EMFILE","EBUSY","EAGAIN","EXDEV","EFBIG","ENOTSUP","ESTALE","EIO"]),$f=16,Kf=4096;function Bf(t,e){let n=new Array(e).fill(void 0);return!Array.isArray(t)||t.length!==e?n:t.map(r=>typeof r=="string"&&r.startsWith("/")&&!r.includes("\0")&&new TextEncoder().encode(r).length<=Kf?r:void 0)}var Hf=64,ul=4096,Gf=4*1024*1024,Wf=4096,zf=3e4,jf=64*1024*1024,Vf=2e6,V=class extends Error{constructor(e,n){super(`${e}: ${n}`),this.name="ShareError",this.errno=e,this.code=e,this.wsh=!0}},cl=(t,e,n)=>Math.min(n,Math.max(e,Number.isFinite(t)?Math.trunc(t):e)),Yf=(t,e=200)=>typeof t=="string"?t.replace(/[\u0000-\u001f\u007f]/g," ").slice(0,e):"";function it(t){if(!t||typeof t!="object")throw new V("EIO","the operator sent no attributes");let e=t.type==="file"||t.type==="directory"||t.type==="symlink"?t.type:null;if(!e)throw new V("EIO","the operator sent an unknown file type");let n=r=>Number.isFinite(r)?Number(r):0;return{type:e,size:n(t.size),mode:n(t.mode)&511,mtimeMs:n(t.mtime_ms),atimeMs:n(t.atime_ms),ctimeMs:n(t.ctime_ms),nlink:n(t.nlink),ino:n(t.ino),isFile:()=>e==="file",isDirectory:()=>e==="directory",isSymbolicLink:()=>e==="symlink"}}var qf=(t,e)=>{if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);throw new V("EIO",`the operator sent ${e} that is not bytes`)};function Xf({send:t,log:e=()=>{},timeoutMs:n=zf}){let r=1,s=ul,i=1,o=!1,a=new Map,c=[],l={requests:0,replies:0,errors:0,bytesDown:0,bytesUp:0,timeouts:0};function h(){for(;!o&&a.size<r&&c.length;)d(c.shift())}function d(y){if(y.done)return;let _=i;for(let E=0;a.has(_);E+=1)if(_=_%4294967295+1,E>65535){w(y,new V("EAGAIN","no request id free"));return}i=_%4294967295+1,y.id=_,a.set(_,{job:y,abandoned:!1}),l.requests+=1,y.fields.data&&(l.bytesUp+=y.fields.data.byteLength);try{Promise.resolve(t(Wo({requestId:_,share:y.share,op:y.op,...y.fields}))).catch(()=>{})}catch(E){a.delete(_),w(y,new V("EIO",`could not send: ${E.message}`))}}function w(y,_,E){y.done||(y.done=!0,clearTimeout(y.timer),_?y.reject(_):y.resolve(E))}return{stats:l,get maxBytes(){return s},configure(y){r=y.maxInflight,s=y.maxBytes,h()},call(y,_,E={}){return new Promise((g,A)=>{if(o){A(new V("EIO","the connection to the operator is gone"));return}let I={share:y,op:_,fields:E,resolve:g,reject:A,done:!1,id:0,timer:null};if(c.length>=Wf){A(new V("EAGAIN","too many share requests are waiting"));return}I.timer=setTimeout(()=>{l.timeouts+=1;let S=c.indexOf(I);S>=0&&c.splice(S,1);let O=a.get(I.id);O&&(O.abandoned=!0),w(I,new V("EIO",`the operator did not answer ${_} within ${n} ms`))},n),I.timer.unref?.(),c.push(I),h()})},reply(y){let _=a.get(y.request_id);if(!_)return;a.delete(y.request_id),l.replies+=1;let{job:E,abandoned:g}=_;if(!g)if(y.ok===!0){let A=y.data;if(A instanceof Uint8Array&&(l.bytesDown+=A.byteLength,A.byteLength>s)){l.errors+=1,w(E,new V("EIO","the operator sent more data than it offered")),h();return}w(E,null,y)}else{l.errors+=1;let A=Ff.has(y.errno)?y.errno:"EIO";w(E,new V(A,Yf(y.message)||A))}h()},close(){if(o)return;o=!0;let y=()=>new V("EIO","the connection to the operator is gone");for(let{job:_}of a.values())w(_,y());a.clear();for(let _ of c.splice(0))w(_,y())},get closed(){return o},log:e}}var Gn=class{#e;#n;#r;#i;#t;#s=!1;constructor(e,n,r,s,{inline:i=null,writable:o=!1}={}){this.#e=e,this.#n=n,this.#r=r,this.#i=i,this.#t=o,this.attr=s}async read(e,n){if(this.#s)throw new V("EBADF","the file is closed");if(!(Number.isSafeInteger(e)&&e>=0)||!(Number.isSafeInteger(n)&&n>=0))throw new V("EINVAL","read needs a non-negative offset and length");if(this.#i)return{data:this.#i.subarray(e,e+n),eof:e+n>=this.#i.byteLength};let r=Math.min(n,this.#e.maxBytes),s=await this.#e.call(this.#n,"read",{handle:this.#r,offset:e,length:r});return{data:qf(s.data,"read data"),eof:s.eof===!0}}async write(e,n){if(this.#s)throw new V("EBADF","the file is closed");if(!this.#t)throw new V("EBADF","the file is not open for writing");let r=0;for(;r<n.byteLength;){let s=n.subarray(r,r+this.#e.maxBytes),i=await this.#e.call(this.#n,"write",{handle:this.#r,offset:e+r,data:s}),o=Number(i.written);if(!Number.isSafeInteger(o)||o<0||o>s.byteLength)throw new V("EIO","the operator reported a bad write size");if(r+=o,o===0)break}return r}async setattr(e){if(this.#s)throw new V("EBADF","the file is closed");if(!this.#r)throw new V("EBADF","this file is read-only and complete: use fs.setattr(path, ...)");let n=await this.#e.call(this.#n,"setattr",{handle:this.#r,attr:hl(e)});return it(n.attr)}async truncate(e){return this.setattr({size:e})}async close(){this.#s||(this.#s=!0,this.#r&&await this.#e.call(this.#n,"close",{handle:this.#r}).catch(()=>{}))}};function hl(t={}){let e={};return t.mode!==void 0&&(e.mode=t.mode),t.atimeMs!==void 0&&(e.atime_ms=t.atimeMs),t.mtimeMs!==void 0&&(e.mtime_ms=t.mtimeMs),t.size!==void 0&&(e.size=t.size),e}function Jf(t,e,n,r,s){let i=(l,h)=>t.call(e,l,h),o=l=>{if(typeof l!="string")throw new V("EINVAL","a path must be a string");return l},a=jf,c={name:e,writable:n,get root(){return s},maxFileBytes:a,signal:r,get stats(){return{...t.stats}},async stat(l){return it((await i("stat",{path:o(l)})).attr)},async lstat(l){return it((await i("lstat",{path:o(l)})).attr)},async readlink(l){let h=await i("readlink",{path:o(l)});if(typeof h.target!="string")throw new V("EIO","the operator sent no link target");return h.target},async readdir(l){let h=[],d;for(;;){let w=await i("readdir",{path:o(l),...d!==void 0?{cursor:d}:{}});if(!Array.isArray(w.entries))throw new V("EIO","the operator sent no entries");for(let y of w.entries){if(!y||typeof y.name!="string"||!y.name||y.name.includes("/")||y.name.includes("\0")||y.name==="."||y.name==="..")throw new V("EIO","the operator sent a bad directory entry");let _={name:y.name,...it(y)};typeof y.target=="string"&&(_.target=y.target),h.push(_)}if(h.length>Vf)throw new V("EFBIG","directory has too many entries");if(w.cursor===void 0||w.cursor===null)break;if(typeof w.cursor!="string"||d!==void 0&&w.cursor<=d)throw new V("EIO","the operator's directory cursor did not advance");d=w.cursor}return h},async open(l,h=["read"],{mode:d,inlineBytes:w}={}){let y=[...h],_=y.includes("write")||y.includes("create")||y.includes("trunc"),E=await i("open",{path:o(l),flags:y,...d!==void 0?{mode:d}:{},...w!==void 0?{length:w}:{}}),g=it(E.attr);if(E.handle===void 0||E.handle===null){if(_||E.eof!==!0||!(E.data instanceof Uint8Array))throw new V("EIO","the operator sent no file handle");return new Gn(t,e,0,g,{inline:E.data})}if(!Number.isSafeInteger(E.handle)||E.handle<=0)throw new V("EIO","the operator sent a bad handle");return new Gn(t,e,E.handle,g,{writable:_,inline:E.eof===!0&&E.data instanceof Uint8Array&&!_?E.data:null})},async create(l,{mode:h}={}){let d=await i("create",{path:o(l),...h!==void 0?{mode:h}:{}});if(!Number.isSafeInteger(d.handle)||d.handle<=0)throw new V("EIO","the operator sent a bad handle");return new Gn(t,e,d.handle,it(d.attr),{writable:!0})},async readFile(l,{maxBytes:h=a}={}){let d=await c.open(l,["read"],{inlineBytes:t.maxBytes});try{if(d.attr.size>h)throw new V("EFBIG",`the file is ${d.attr.size} bytes, more than ${h}`);let w=[],y=0;for(;;){let{data:g,eof:A}=await d.read(y,t.maxBytes);if(g.byteLength&&w.push(g),y+=g.byteLength,y>h)throw new V("EFBIG",`the file is bigger than ${h} bytes`);if(A||g.byteLength===0)break}if(w.length===1)return w[0];let _=new Uint8Array(y),E=0;for(let g of w)_.set(g,E),E+=g.byteLength;return _}finally{await d.close()}},async writeFile(l,h,{mode:d,truncate:w=!0}={}){let y=await c.open(l,["write","create",...w?["trunc"]:[]],{mode:d});try{return await y.write(0,h)}finally{await y.close()}},async mkdir(l,{mode:h}={}){return it((await i("mkdir",{path:o(l),...h!==void 0?{mode:h}:{}})).attr)},async unlink(l){await i("unlink",{path:o(l)})},async rmdir(l){await i("rmdir",{path:o(l)})},async rename(l,h){await i("rename",{path:o(l),to:o(h)})},async setattr(l,h){return it((await i("setattr",{path:o(l),attr:hl(h)})).attr)},async truncate(l,h){return c.setattr(l,{size:h})},async chmod(l,h){return c.setattr(l,{mode:h})},async utimes(l,h,d){return c.setattr(l,{atimeMs:h,mtimeMs:d})},async operate(l,h,{offset:d,length:w,newPath:y,data:_}={}){let E=(g,A)=>({name:A,size:g.size,modified:Math.floor(g.mtimeMs/1e3),type:g.type,...g.target!==void 0?{symlink_target:g.target}:{}});switch(l){case"list":return{entries:(await c.readdir(h||"/")).map(g=>E(g,g.name)),metadata:{path:h||"/"}};case"stat":{let g=await c.lstat(h);return{metadata:E(g,String(h).split("/").filter(Boolean).pop()??"")}}case"read":{let g=await c.open(h,["read"]);try{let A=Math.min(Number(w??t.maxBytes),t.maxBytes),{data:I}=await g.read(Math.max(0,Number(d??0)),A);return{metadata:{data:I,size:g.attr.size}}}finally{await g.close()}}case"write":return await c.writeAt(h,_,d),{metadata:{written:_.byteLength}};case"mkdir":return await c.mkdir(h),{metadata:{}};case"remove":return await((await c.lstat(h)).isDirectory()?c.rmdir(h):c.unlink(h)),{metadata:{removed:h}};case"rename":return await c.rename(h,y),{metadata:{renamed:h,to:y}};default:throw new V("ENOTSUP",`"${l}" is not offered (list, stat, read, write, rename, mkdir, remove)`)}},async readWhole(l){return c.readFile(l)},async writeWhole(l,h){await c.writeFile(l,h)},async writeAt(l,h,d=0){let w=await c.open(l,["write","create"]);try{await w.write(Number(d),h)}finally{await w.close()}}};return c}function fl({send:t,onShare:e,who:n,log:r=()=>{},timeoutMs:s}){let i=Xf({send:t,log:r,timeoutMs:s}),o=new AbortController,a=!1,c=new Map;function l(h){if(a){r("ignored a second ShareOffer");return}a=!0;let d=Array.isArray(h.shares)?h.shares:[];if(!d.length||d.length>$f||d.some(_=>typeof _!="string"||!vf.test(_))||new Set(d).size!==d.length){r("ignored a ShareOffer with bad share names");return}let w=new Set(Array.isArray(h.writable)?h.writable.filter(_=>d.includes(_)):[]);i.configure({maxInflight:cl(h.max_inflight,1,Hf),maxBytes:cl(h.max_bytes,ul,Gf)});let y=Bf(h.paths,d.length);for(let[_,E]of d.entries()){let g=Jf(i,E,w.has(E),o.signal,y[_]);c.set(E,g),Promise.resolve().then(()=>e(E,g,n())).catch(A=>r(`onShare(${JSON.stringify(E)}) threw: ${A?.message??A}`))}r(`shares offered: ${d.map(_=>`${_}${w.has(_)?" (rw)":""}`).join(", ")}`)}return{shares:c,stats:i.stats,handle(h){switch(h.type){case f.SHARE_OFFER:return l(h),!0;case f.SHARE_REPLY:return i.reply(h),!0;case f.SHARE_REQUEST:return r("ignored a ShareRequest from the operator (only the host asks)"),!0;default:return!1}},close(){o.abort(),i.close()}}}function dl(t,e){if(t!=null&&typeof t!="function")throw new TypeError(`${e}: onShare must be a function (name, fs, who) => void`)}var Qf="stream-announce";function Zf(t,{dataStreams:e=!0}={}){let n=e?[Qf]:[];return t.mcp&&n.push($t,mn),t.gateway&&n.push(...Kc(t.gateway)),t.files&&n.push("file-transfer","file-write","file-rename"),t.targets&&(n.push(Qe),!t.files&&[...t.targets.values()].some(r=>r.files)&&n.push("file-transfer","file-write","file-rename")),t.onShare&&n.push(ll),t.relay&&(n.push(Xs,Pe),t.relay.maxOperatorsPerPeer>1&&n.push(Vc)),t.e2e&&!e&&n.push(lc,...t.e2e.signKey?[Xs]:[]),t.sealSession&&t.hostKey&&!e&&n.push(_n,...t.sealSession==="require"?[Er]:[]),t.rpc&&t.rpc.protocols.size&&n.push(e?tt:Xt,...[...t.rpc.protocols.keys()].map(xt),Dn+t.rpc.maxMessageBytes),n}var ed=8,td=4096,nd=3e4,pl=64,yl=32*1024,rd=new TextEncoder,di=()=>crypto.randomUUID(),pi=t=>crypto.getRandomValues(new Uint8Array(t)),yi=t=>typeof t=="string"?rd.encode(t):t;function El(t){if(!t||typeof t.authorize!="function")throw new TypeError("createConnectionFactory: authorize(who) is required (a host that lets everyone in is not a default)");t={...t,execOptions:t.execOptions??{},methods:t.methods??{pubkey:!0,password:null},bindTimeoutMs:t.bindTimeoutMs??3e3,log:t.log??(()=>{}),usernamePattern:Vr(t.usernamePattern,"createConnectionFactory")},zr(t.onRefused,"createConnectionFactory");let e=qc(t.onRefused,t.log),n=0,r=Bn(t.execOptions?.clientEnv),s=Bn(t.pty?.clientEnv),i=t.targets&&t.targets.size?new Map([...t.targets].map(([d,w])=>[d,{...w,execEnv:Bn(w.execOptions?.clientEnv),ptyEnv:Bn(w.pty?.clientEnv)}])):null,o=!!i&&!!t.requireTarget,a={execRunner:t.execRunner,execOptions:t.execOptions,execEnv:r,pty:t.pty,ptyEnv:s,files:t.files,ownHost:!0},c="no such target",l=new Set,h=d=>[...d.execRunner?["exec"]:[],...d.pty?["pty"]:[],...d.files?["file"]:[],...d.endpoints?["endpoint"]:[]];return function({send:w,sendMessage:y=null,remote:_={},authenticated:E=null,dataStreams:g=!0,closeTransport:A=null,e2e:I,channelBinding:S=null,datagrams:O=null,sealSession:N}){let D=++n,x=u=>t.log(`[conn ${D}] ${u}`),m={sessionId:di(),nonce:null,username:E?.username??null,authed:!!E,closed:!1,nextChannel:0,fingerprint:E?.fingerprint??null,grant:null},L=new Map,G={channels:L,fingerprint:()=>m.fingerprint};l.add(G);let $=()=>m.fingerprint?t.authorize.permissionsFor?.(m.fingerprint)??null:null;function ee(u){let p=0;for(let b of l)if(b.fingerprint()===u)for(let R of b.channels.values())R.keyed&&p++;return t.sessions&&(p+=t.sessions.listFor(u).filter(b=>b.state!=="exited").length),p}let ie=()=>[$(),m.grant].filter(Boolean);function Re(u,p){for(let b of ie()){let R=u.kind==="open"&&(u.channel==="pty"||u.channel==="exec")&&b.maxSessions!==null,T=jr(b,u,{activeSessions:R?ee(m.fingerprint):0});if(T){if(!p){let C=`${u.kind}${u.channel?` ${u.channel}`:""}${u.protocol?` ${u.protocol}`:""}`;x(`key permissions refused ${C} for ${m.username??"?"} (${T.code}${T.capability?`: ${T.capability}`:""})`),e(T.code==="key-expired"?"key-expired":"not-permitted",{username:m.username,fingerprint:m.fingerprint,address:_.address},`${T.code}: ${T.reason} (${C})`)}return T}}return null}let me=u=>Re(u,!1),Rt=u=>Re(u,!0)===null,zn=()=>{for(let u of ie())if(Array.isArray(u.capabilities))return u.capabilities.slice();return null},ot=(u,{now:p}={})=>ie().every(b=>!jr(b,u,{now:p}));function Jr(u){let p,b=!1;switch(u.type){case f.OPEN_TCP:p={kind:"tcp",host:u.host,port:u.port};break;case f.OPEN_UDP:p={kind:"udp",host:u.host,port:u.port};break;case f.RESOLVE_DNS:p={kind:"dns",name:u.name};break;case f.OPEN_UNIX:p={kind:"unix",path:u.path};break;case f.OPEN_ENDPOINT:p={kind:"endpoint",name:u.name,target:u.target??void 0};break;case f.LISTEN_REQUEST:p={kind:"listen-tcp",port:u.port},b=!0;break;case f.LISTEN_UNIX:p={kind:"listen-unix",path:u.path},b=!0;break;default:return null}let R=me(p);return R?b?er({listenerId:u.listener_id,reason:R.reason}):Qn({gatewayId:u.gateway_id,code:Ee.POLICY_DENIED,message:R.reason}):null}let Te=new Map,Ie=new Set,Ge=new Map,at=[],jn=new je,nn=[],Ot=null,Ue=Promise.resolve(),X=null,xe=null;if(N!==void 0&&N!=="require")throw new TypeError("attach: sealSession can only be 'require' for one connection");if(N==="require"&&(!t.hostKey||g))throw new Error("this connection must be sealed, and this host cannot seal it (it needs a host key and dataStreams: false)");let ve=N==="require"?"require":t.sealSession,xi=!!ve&&!!t.hostKey&&!g,Qr=xi&&ve==="require",We={bridge:null,responder:null};if(t.gateway&&typeof t.createGatewaySession!="function")throw new TypeError("createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)");let rn=t.gateway?t.createGatewaySession(t.gateway,u=>k(u),x,{who:()=>({username:m.username,fingerprint:m.fingerprint}),datagrams:O,target:async u=>{let p=await Yn(u,"endpoint");return p.refuse?{refuse:p.refuse}:{endpoints:p.b.endpoints??null}},requireTarget:()=>o}):null,Zr=t.onShare?fl({send:u=>k(u),onShare:t.onShare,who:()=>({username:m.username,fingerprint:m.fingerprint}),log:x,timeoutMs:t.shareTimeoutMs}):null,ct=y?null:new Ft({isClient:!1,send:u=>{m.closed||w(u)}}),sn=new Map,lt=new Map,Cl=64,es=I===void 0?t.e2e:I,ts=es&&!g?new Ln({signKey:es.signKey??null,hybrid:es.hybrid!==!1}):null,Si=Promise.resolve(),Ri=u=>lt.get(sn.get(u)),k=u=>{if(m.closed)return Promise.resolve();if(u.type===f.OPEN_OK&&typeof u.session_id=="string"&&sn.set(u.channel_id,u.session_id),lt.size===0)return ns(u);let p=Si.then(async()=>{let b=u.type===f.SESSION_DATA?Ri(u.channel_id):void 0;if(!b)return ns(u);let R=sn.get(u.channel_id),{nonce:T,ciphertext:C}=await Et(b.key,R,De.responder,b.sendCounter++,u.data);return ns(Mt({channelId:u.channel_id,nonce:T,ciphertext:C,sessionId:R}))});return Si=p.catch(()=>{}),p.catch(()=>{})},ns=u=>We.bridge&&u.type!==f.PING&&u.type!==f.PONG?We.bridge.seal(u).then(p=>Vn(p),p=>{x(`could not seal: ${p.message}`)}):Vn(u),Vn=u=>{if(m.closed)return Promise.resolve();if(y)try{return Promise.resolve(y(u)).catch(()=>{})}catch{return Promise.resolve()}let p=Nt(u);return Ot?Ot.write(p).catch(()=>{}):(nn.push(p),Promise.resolve())};function Ct(u){if(!m.closed){m.closed=!0,l.delete(G),clearTimeout(xe);for(let p of[...L.values()])(p.detach??p.kill)?.call(p);L.clear(),ts?.close(),rn?.close(),Zr?.close(),lt.clear();for(let p of Ie)p.abort(new Error("connection closed"));Ie.clear(),Ge.clear();for(let p of Te.values())clearTimeout(p.timer);Te.clear();try{ct?.destroy(new Error(u))}catch{}try{A?.()}catch{}X&&t.relay?.drop(X),x(`closed (${u})`)}}let It=u=>{Ue=Ue.then(()=>Ct(u))};ct&&(ct.onError=u=>x(`qmux error: ${u.message}`),ct.onClose=()=>It("peer sent CONNECTION_CLOSE"),ct.onStreamOpen=u=>{if(u.id!==0){Oi(u);return}Ot=u,u.onData=p=>{let b;try{b=jn.feed(p)}catch(R){x(`frame decode error: ${R.message}`);return}for(let R of b)Ue=Ue.then(()=>Ci(R)).catch(T=>x(`handler error: ${T.message}`))},u.onEnd=()=>It("control stream FIN"),u.onReset=()=>It("control stream reset");for(let p of nn.splice(0))u.write(p).catch(()=>{})},ct.sendHandshake());function Oi(u){let p=at.shift(),b=p!==void 0?L.get(p):void 0;if(!b?.bind){u.close().catch(()=>{});return}b.bind(u)}async function Ci(u){if(!m.closed){if(!m.authed)return Ll(u);if(xi){let p=await kl(u);if(p===void 0)return;u=p}if(!await Ul(u)){if(u.type===f.GATEWAY_CREDIT&&Vt(u.gateway_id)!==void 0){L.get(Vt(u.gateway_id))?.credit?.(u.bytes);return}if(rn){let p=Jr(u);if(p)return k(p);if(await rn.handle(u))return}if(!(Zr&&Zr.handle(u)))switch(u.type){case f.PING:return k(Jn({id:u.id}));case f.OPEN:return Kl(u);case f.SESSION_DATA:if(Ri(u.channel_id)){x(`ignored plaintext SessionData on E2E channel ${u.channel_id}`);return}L.get(u.channel_id)?.input?.(u.data);return;case f.KEY_EXCHANGE:return Il(u);case f.ENCRYPTED_FRAME:return Nl(u);case f.RESIZE:L.get(u.channel_id)?.resize?.(u.cols,u.rows);return;case f.SIGNAL:L.get(u.channel_id)?.signal?.(String(u.signal??""));return;case f.CLOSE:{let p=L.get(u.channel_id);p&&p.kill?.();return}case f.FILE_OP:return Yl(u);case f.FILE_CHUNK:return Te.has(u.channel_id)?Xl(u):L.get(u.channel_id)?.chunk?.(u);case f.ATTACH:return Pi(u,!1);case f.RESUME:return Pi(u,!0);case f.DETACH:return Bl(u);case f.SESSION_LIST_REQUEST:return Hl();case f.LIST_TARGETS:return $l();case f.MCP_DISCOVER:return vl();case f.MCP_CALL:Fl(u);return;case f.MCP_CANCEL:typeof u.call_id=="string"&&Ge.get(u.call_id)?.abort(new Error("cancelled by the caller"));return;default:if(typeof u.type=="string"&&Object.hasOwn(t.extensions??{},u.type)&&typeof t.extensions[u.type]=="function"){try{await t.extensions[u.type](u,{username:m.username,fingerprint:m.fingerprint,send:k})}catch(p){x(`extension "${u.type}" threw: ${p.message}`)}return}x(`ignored message type ${typeof u.type=="number"?`0x${u.type.toString(16)}`:JSON.stringify(String(u.type)).slice(0,80)}`)}}}}async function Il(u){if(!ts){x("ignored KeyExchange (end-to-end encryption is not enabled here)");return}if(!(typeof u.session_id=="string"&&[...sn.values()].includes(u.session_id))){x("ignored KeyExchange for a session this connection does not have");return}if(!lt.has(u.session_id)&<.size>=Cl){x("ignored KeyExchange (too many encrypted sessions)");return}let b;try{b=await ts.respond(u,k)}catch(R){x(`KeyExchange refused: ${R.message}`);return}b.key&&(lt.set(b.sessionId,{key:b.key,sendCounter:0,recvCounter:0}),x(`end-to-end encryption on for session ${b.sessionId.slice(0,8)}${b.hybrid?" (hybrid)":""}`))}async function Nl(u){let p=lt.get(u.session_id);if(!p||sn.get(u.channel_id)!==u.session_id){x("dropped an EncryptedFrame for a session without E2E");return}let b;try{b=await wt(p.key,u.session_id,p.recvCounter,{nonce:u.nonce,ciphertext:u.ciphertext,expectedRoleTag:De.initiator})}catch(R){x(`dropped an EncryptedFrame: ${R.message}`);return}p.recvCounter+=1,L.get(u.channel_id)?.input?.(b)}async function Ii(){let u=t.connectionTtlMs??0;u>0&&(xe=setTimeout(()=>{x("connection ttl reached"),It("connection ttl reached")},u),xe.unref?.()),await k(ji({sessionId:m.sessionId,token:pi(16),ttl:Math.ceil(u/1e3)}))}let Ni=!1;function on(u,p,b={}){Ni||(Ni=!0,e(u,{username:m.username,fingerprint:m.fingerprint,address:_.address,...b},p))}async function he(u,p="bad-request",b){x(`AUTH_FAIL: ${u}`),on(p,u,b),await k(Vi({reason:u})),setTimeout(()=>Ct("auth failed"),50)}async function Ll(u){if(u.type===f.HELLO){let p=String(u.username??"");if(!al(t.usernamePattern,p))return he(`bad username ${JSON.stringify(p)}`);let b=u.auth_method||"pubkey";if(b==="password"){if(!t.methods.password)return he("password auth is not enabled on this host","method-disabled",{username:p})}else if(b==="pubkey"){if(!t.methods.pubkey)return he("pubkey auth is not enabled on this host","method-disabled",{username:p})}else return he(`unsupported auth method ${JSON.stringify(b)}`,"bad-request",{username:p});if(Qr&&b!=="pubkey")return he("this host requires a sealed session, which needs a key login","not-sealed",{username:p});m.username=p,m.method=b,rn?.setPeerFeatures(u.features);let R=Zf(ve===t.sealSession?t:{...t,sealSession:ve},{dataStreams:g});O&&t.gateway?.tcp&&t.gateway.udp?.datagrams&&R.push(zt);let T;if(t.hostKey){T=t.hostKey.fingerprint;let C=bc(u.features);if(C){let M=await t.hostKey.sign(Br({sessionId:m.sessionId,clientNonce:C,username:p}));R.push($r+Fn(t.hostKey.publicKey),Kr+Fn(M))}}if(b==="pubkey"){m.bindingHeld={...S??{}},t.hostKey&&(m.bindingHeld.host=[t.hostKey.publicKey]);let C=Object.keys(m.bindingHeld).filter(M=>m.bindingHeld[M]?.length);R.push(...Oa(C,{required:!!t.requireChannelBinding}))}m.features=R,m.hostFingerprint=T??null,await k(Wi({sessionId:m.sessionId,features:R,hostFingerprint:T})),b==="pubkey"?(m.nonce=_s(),await k(zi({nonce:m.nonce,sessionId:m.sessionId}))):m.awaitingPassword=!0;return}if(u.type===f.AUTH&&m.awaitingPassword)return Ml(u);if(u.type===f.AUTH){if(!m.nonce)return;if(u.method!=="pubkey"||!(u.public_key instanceof Uint8Array)||!(u.signature instanceof Uint8Array))return he("expected a pubkey AUTH with public_key and signature");let p,b;try{p=await oe(u.public_key),b=await pe(u.public_key)}catch{return he("malformed public key")}let R={fingerprint:p},T=t.requireChannelBinding??!1,C=await Ia(m.bindingHeld??{},{required:T}),M=!1,v=[];try{for(let P of C)if(await rr(b,u.signature,m.sessionId,m.nonce,{username:m.username,channelBinding:P.binding})){M=!0,v=P.kinds;break}}catch{M=!1}if(!M){if(T){let P=!1;try{P=await rr(b,u.signature,m.sessionId,m.nonce,{username:m.username})}catch{}if(P)return he("channel binding required: the signature is not bound to this connection","binding-required",R)}return he("signature does not verify over the transcript","bad-signature",R)}m.channelBinding=v;let F=!1;try{F=await t.authorize({username:m.username,fingerprint:p,publicKey:u.public_key,...Qr?{sealRequired:!0}:{}})}catch(P){x(`authorize threw: ${P.message}`)}if(!F)return he("key not authorized","unauthorized",R);let U=typeof F=="object"?F.permissions??null:null;for(let P of[t.authorize.permissionsFor?.(p)??null,U])if(P&&jr(P,{kind:"login"}))return he("key has expired","key-expired",R);m.grant=U,m.authed=!0,m.fingerprint=p,m.publicKey=u.public_key,m.nonce=null,await Ii(),x(`authenticated ${m.username} (${p.slice(0,12)}...)`)}}async function kl(u){if(We.bridge){if(u.type===f.PING)return u;if(!We.bridge.isFrame(u)){x(`dropped a plaintext message (type ${u.type}) on a sealed session`);return}try{return await We.bridge.open(u)}catch(p){x(`a sealed frame did not open (${p.message}): closing the session`),on("seal-failed",`a sealed frame did not open: ${p.message}`),Ct("sealed frame did not open");return}}if(u.type===f.KEY_EXCHANGE&&u.session_id===m.sessionId){if(!m.publicKey){x("sealed session refused: no login key to authenticate the initiator with"),on("seal-failed","no login key to authenticate the initiator with"),Ct("sealed session needs a key login");return}We.responder??=new Ln({signKey:t.hostKey,hybrid:!0,identity:t.hostKey.publicKey,initiator:{publicKey:m.publicKey,require:!0}});try{let p=await We.responder.respond(u,b=>Vn(b));if(p.key){We.bridge=new Tt({key:p.key,sessionId:m.sessionId,role:"responder",scope:"session"}),x(`session sealed${p.hybrid?" (hybrid)":""}`);try{t.onSealed?.({username:m.username,fingerprint:m.fingerprint})}catch(b){x(`onSealed threw: ${b.message}`)}}}catch(p){x(`sealed session refused: ${p.message}`),on("seal-failed",`key exchange failed: ${p.message}`),Ct("sealed session key exchange failed")}return}if(u.type===f.PING)return u;if(Qr){x(`refused a plaintext message (type ${u.type}): this host requires a sealed session`),on("not-sealed",`a plaintext message (type ${u.type}) on a host that requires a sealed session`),await Vn(qe({code:1,message:"this host requires a sealed session (e2e-session-required)"})),setTimeout(()=>Ct("sealed session required"),50);return}return u}async function Ml(u){if(m.awaitingPassword=!1,u.method!=="password"||typeof u.password!="string")return he("expected a password AUTH","bad-request");let p=t.rateLimit,b=p.key({address:_.address,headers:_.headers,username:m.username}),R=p.limiter.lockedFor(b);if(R>0)return he(`too many failed attempts; try again in ${Math.ceil(R/1e3)}s`,"rate-limited");let T=!1;try{T=await t.methods.password(m.username,u.password)===!0}catch(C){x(`password check threw: ${C.message}`)}if(!T)return p.limiter.fail(b),p.failureDelayMs>0&&await new Promise(C=>setTimeout(C,p.failureDelayMs)),he("authentication failed","unauthorized");p.limiter.succeed(b),m.authed=!0,await Ii(),x(`authenticated ${m.username} (password)`)}let Dl=new Set([f.REVERSE_REGISTER,f.REVERSE_LIST,f.REVERSE_CONNECT,f.REVERSE_ACCEPT,f.REVERSE_REJECT,f.RELAY_FORWARD,f.REVERSE_CHALLENGE,f.REVERSE_PROOF]);function Pl(){return X??={send:k,fingerprint:m.fingerprint,username:m.username,close:()=>It("relay bridge ended")},X}async function Ul(u){let p=t.relay;if(!p)return u.type===f.REVERSE_LIST?(await k(lo({peers:[]})),!0):u.type===f.REVERSE_CONNECT?(await k(us({targetFingerprint:String(u.target_fingerprint??""),username:"",reason:"relay is not enabled on this server"})),!0):u.type===f.REVERSE_REGISTER?(await k(qe({code:3,message:"relay is not enabled on this server"})),!0):!1;if(!Dl.has(u.type))return X?(p.touch(X),p.forward(X,u)):!1;if(!m.fingerprint)return await k(qe({code:2,message:"relay operations need a key login"})),!0;if(u.type===f.REVERSE_REGISTER||u.type===f.REVERSE_LIST||u.type===f.REVERSE_CONNECT){let R=me({kind:"relay"});if(R)return u.type===f.REVERSE_CONNECT?await k(us({targetFingerprint:String(u.target_fingerprint??""),username:"",reason:R.reason})):await k(qe({code:2,message:R.reason})),!0}let b=Pl();switch(u.type){case f.REVERSE_REGISTER:{let R=await p.register(b,u,{username:m.username,fingerprint:m.fingerprint});return R&&(x(`ReverseRegister refused: ${R}`),await k(qe({code:2,message:`registration refused: ${R}`}))),!0}case f.REVERSE_LIST:return await k(await p.list({username:m.username,fingerprint:m.fingerprint})),!0;case f.REVERSE_CONNECT:return await p.connect(b,u),!0;case f.REVERSE_ACCEPT:case f.REVERSE_REJECT:return p.answer(b,u),!0;case f.REVERSE_CHALLENGE:return p.challenge(b,u),!0;case f.REVERSE_PROOF:return p.proof(b,u),!0;default:return p.forward(b,u),!0}}let Li=()=>({username:m.username,fingerprint:m.fingerprint});async function vl(){let u=[];if(t.mcp&&Rt({kind:"mcp"})){try{u=await t.mcp.list(m.username,Li())}catch(p){x(`mcp discover failed: ${p.message}`)}u=u.filter(p=>Rt({kind:"mcp-tool",tool:p.name}))}return k(so({tools:u}))}function Fl(u){let p=typeof u.call_id=="string"?u.call_id:void 0,b=C=>{try{return k(ls({result:C,callId:p}))}catch(M){return x(`mcp result for ${u.tool} not encodable: ${M.message}`),k(ls({result:{success:!1,error:"tool result could not be encoded"},callId:p}))}},R=C=>b({success:!1,error:C});if(!t.mcp){R("mcp is not enabled on this server");return}{let C=me({kind:"mcp-call",tool:typeof u.tool=="string"?u.tool:""});if(C){R(C.reason);return}}if(Ie.size>=t.mcp.maxConcurrent){R("too many concurrent MCP calls");return}let T=new AbortController;Ie.add(T),p!==void 0&&Ge.set(p,T),(async()=>{let C=typeof u.tool=="string"?u.tool:"",M=C?await t.mcp.find(C,m.username,Li()):null;if(!M)return R(`unknown tool: ${C||String(u.tool)}`);let v=u.arguments??{},F=t.mcp.validate(M,v);if(F)return R(`invalid arguments: ${F}`);let U=null,P=new Promise((B,Q)=>{T.signal.addEventListener("abort",()=>Q(T.signal.reason??new Error("aborted")),{once:!0})});P.catch(()=>{}),t.mcp.timeoutMs>0&&(U=setTimeout(()=>T.abort(new Error(`tool ${C} timed out after ${t.mcp.timeoutMs}ms`)),t.mcp.timeoutMs));try{let B={user:m.username,fingerprint:m.fingerprint,signal:T.signal},Q=await Promise.race([Promise.resolve().then(()=>M.call(v,B)),P]);return b(Q===void 0?null:Q)}catch(B){return m.closed||x(`mcp tool ${C} failed: ${B?.message??B}`),R(String(B?.message??B))}finally{clearTimeout(U)}})().catch(C=>x(`mcp call ${u.tool}: ${C.message}`)).finally(()=>{Ie.delete(T),p!==void 0&&Ge.get(p)===T&&Ge.delete(p)})}async function Yn(u,p){if(u==null)return o?{refuse:"a target is required"}:{b:a};if(!i)return{refuse:"this host has no targets"};let b=typeof u=="string"&&li.test(u)?i.get(u):void 0;if(!b)return{refuse:c};if(b.authorize){let R=!1;try{R=await b.authorize({username:m.username,fingerprint:m.fingerprint},{target:u,kind:p})===!0}catch(T){x(`target ${u} authorize threw: ${T.message}`)}if(!R)return x(`target ${u} refused for ${m.username??"?"} (${p})`),{refuse:c}}return{b}}async function $l(){if(!i)return k(qe({code:3,message:"this host has no targets"}));let u=[];for(let[p,b]of i)!Rt({kind:"target",name:p})||(await Yn(p,"list")).refuse||u.push({name:p,...b.description!==void 0?{description:b.description}:{},capabilities:h(b)});return k(jo({targets:u}))}async function Kl(u){if(L.size>=pl)return k(re({reason:"too many open channels"}));let p=u.target??void 0;switch(u.kind){case"exec":case"pty":case"file":{let b={kind:"open",channel:u.kind,target:p,direction:u.kind==="file"?String(u.command??"").startsWith("download:")?"download":"upload":void 0},R=me(b);if(R)return k(re({reason:R.reason}));let T=await Yn(p,u.kind);if(T.refuse)return k(re({reason:T.refuse}));let C=Rt(b)?null:me(b);return C?k(re({reason:C.reason})):u.kind==="exec"?Gl(u,T.b,p):u.kind==="pty"?jl(u,T.b,p):Vl(u,T.b)}case"rpc":if(p!==void 0)return k(re({reason:"rpc channels do not take a target"}));if(o)return k(re({reason:"a target is required"}));{let b=typeof u.command=="string"?u.command:"",R=me({kind:"open",channel:"rpc",protocol:b,scoped:t.rpc?.protocols.get(b)?.capabilityScoped===!0,authorizesItself:t.rpc?.protocols.get(b)?.authorizesItself===!0});if(R)return k(re({reason:R.reason}))}return Wl(u);default:return k(re({reason:`kind "${u.kind}" is not supported by this server`}))}}function an(u,p){return!L.has(u)||m.closed?Promise.resolve():(L.delete(u),k(os({channelId:u,code:p})).then(()=>k(Lt({channelId:u}))))}let cn=()=>m.fingerprint??`password:${m.username}`,ki=()=>({username:m.username,fingerprint:m.fingerprint,principal:cn()});function Mi(u,p,b){let R=Promise.resolve(),T=C=>(R=R.then(C).catch(()=>{}),R);return{connId:D,channelId:p,mode:b,username:m.username,principal:cn(),write:C=>T(()=>k(yt({channelId:p,data:C}))),notify:C=>T(()=>k(cs(C))),exit:C=>T(async()=>{L.delete(p),await k(os({channelId:p,code:C})),await k(Lt({channelId:p}))}),flush:()=>R}}function Di(u,p){let b=()=>p.mode==="control",R={session:u,attachment:p,input:T=>{b()&&u.handlers.input?.(T)},resize:(T,C)=>{b()&&u.handlers.resize?.(T,C)},signal:T=>{b()&&u.handlers.signal?.(T)},kill:()=>{p.principal===u.owner.principal&&b()?u.kill():R.detach()},detach:()=>{L.delete(p.channelId),u.detach(p)}};return L.set(p.channelId,R),R}async function Pi(u,p){let b=t.sessions,R=(z,ln)=>k(qe({code:z,message:ln}));if(!b)return R(3,`${p?"resume":"attach"} is not enabled on this server (no "sessions" option)`);let T=b.get(u.session_id),C=!!T&&T.owner.principal===cn(),M=!!T&&u.token!==void 0&&b.checkToken(T,u.token);if(!T||!(p?M&&C:M||C))return x(`${p?"resume":"attach"} refused for ${String(u.session_id).slice(0,8)}`),R(2,"unknown session or not authorized");if([...L.values()].some(z=>z.session===T))return R(3,"already attached to this session on this connection");if(T.attachments.size>=16)return R(3,"too many attachments to this session");if(L.size>=pl)return R(3,"too many open channels");let v=T.ring.start;if(p){let z=u.last_seq;if(!Number.isSafeInteger(z)||z<0)return R(3,"last_seq must be a non-negative integer");if(z>T.ring.end)return R(4,`last_seq ${z} is ahead of the session (it has produced ${T.ring.end} bytes)`);if(z<T.ring.start)return R(4,`output gap: this session's retained output starts at seq ${T.ring.start} but last_seq is ${z}; attach for the retained output instead`);v=z}let F=!p&&/^(readonly|read|view|ro)$/i.test(String(u.mode??""))?"readonly":"control",U=++m.nextChannel,P=Mi(T,U,F);Di(T,P);let B={session_id:T.id,mode:F,username:m.username,channel_id:U,seq:v};P.notify({attachments:[B,...T.roster()]});let Q=T.ring.read(v);for(let z=0;z<Q.byteLength;z+=yl)P.write(Q.subarray(z,z+yl));T.state==="exited"?P.exit(T.exitCode??0):T.attach(P),x(`${p?"resumed":`attached (${F})`} session ${T.id.slice(0,8)} on channel ${U} from seq ${v}`)}async function Bl(u){let p=t.sessions?.get(u.session_id),b=p&&[...L.entries()].find(([,M])=>M.session===p);if(!b)return k(wo({reason:"not attached to this session on this connection"}));let[R,T]=b,C=T.attachment.flush();return T.detach(),await C,await k(Lt({channelId:R})),k(Eo({sessionId:p.id}))}function Hl(){let u=Date.now(),p=(t.sessions?.listFor(cn())??[]).map(b=>({session_id:b.id,username:b.owner.username,fingerprint_short:(b.owner.fingerprint??"").slice(0,8),created_at_secs:Math.floor(b.createdAt/1e3),idle_secs:Math.max(0,Math.floor((u-b.lastActivity)/1e3)),attached_count:b.attachments.size}));return k(po({sessions:p}))}async function Gl(u,p,b){if(!p.execRunner)return k(re({reason:`exec is not enabled ${p.ownHost?"on this server":"for this target"}`}));let R=$()?.forcedCommand??String(u.command??"").trim();if(!R)return k(re({reason:'command is required for kind "exec"'}));let T=++m.nextChannel,C=new AbortController,M=t.sessions?t.sessions.create({owner:ki(),kind:"exec",command:R}):null,v=null,F=!1,U=Promise.resolve(),P=[],B=[],Q=[],z=[],ln=[],Ui=H=>{let J=H.replace(/^SIG/,"").toUpperCase();for(let fe of ln)fe(J);/^(INT|TERM|KILL|HUP)$/.test(J)&&ln.length===0&&C.abort()},un={keyed:!M,kill:()=>C.abort(),signal:Ui,bind(H){v=H,H.onData=fe=>{if(!(!F&&(F=!0,fe.byteLength===1&&fe[0]===0))&&fe.byteLength)for(let Ql of Q)Ql(fe)},H.onEnd=()=>{for(let fe of z)fe()},H.onReset=()=>{M||C.abort()};let J=P.splice(0);U=U.then(async()=>{for(let fe of J)await H.write(fe).catch(()=>{})});for(let fe of B.splice(0))fe()}};L.set(T,un),g?at.push(T):un.input=H=>{for(let J of Q)J(H)};let rs=null;p.execOptions.timeoutMs>0&&(rs=setTimeout(()=>C.abort(),p.execOptions.timeoutMs));let vi=H=>{if(!g)return U=U.then(()=>k(yt({channelId:T,data:H}))),U;if(!v)return P.push(H),Promise.resolve();let J=v;return U=U.then(()=>J.write(H).catch(()=>{})),U},Fi=async H=>{g&&!v&&await Promise.race([new Promise(J=>B.push(J)),new Promise(J=>setTimeout(J,t.bindTimeoutMs))]),g&&!v&&x(`exec channel ${T}: data stream never appeared; output dropped`),await U;try{await v?.close()}catch{}await an(T,Number.isInteger(H)?H:0)};if(M){let H={connId:D,channelId:T,mode:"control",username:m.username,principal:cn(),write:vi,notify:J=>k(cs(J)),exit:J=>Fi(J),flush:()=>U};M.handlers={input:J=>{for(let fe of Q)fe(J)},inputEnd:()=>{for(let J of z)J()},signal:Ui,resize:()=>{},kill:()=>C.abort()},un.session=M,un.attachment=H,un.detach=()=>{L.delete(T),M.detach(H);try{v?.close().catch(()=>{})}catch{}},M.attach(H)}let $i={user:m.username,target:b,env:p.execEnv(u.env),cols:u.cols||80,rows:u.rows||24,signal:C.signal,write(H){let J=yi(H);return M?(M.push(J),U):vi(J)},onInput:H=>Q.push(H),onInputEnd:H=>z.push(H),onSignal:H=>ln.push(H)};await k(Ye({channelId:T,dataMode:g?"stream":"virtual",capabilities:["signal"],sessionId:M?.id??di(),token:M?.token??pi(16)})),x(`exec channel ${T}: ${R}`),Jl().catch(H=>x(`exec channel ${T}: ${H.message}`));async function Jl(){let H;try{H=await p.execRunner(R,$i)}catch(J){await $i.write(`wsh: ${J.message}
|
|
4
|
+
`),H=1}if(rs&&clearTimeout(rs),M){M.finish(Number.isInteger(H)?H:0);return}await Fi(H)}}async function Wl(u){let p=t.rpc,b=typeof u.command=="string"?u.command:"",R=p?.protocols.get(b);if(!p||!R){let F=p?`protocol "${b}" is not supported by this server`:"rpc is not enabled on this server";return k(re({reason:`UNSUPPORTED_PROTOCOL: ${F}`}))}if(!g)return zl(u,b,R,p);let T=++m.nextChannel,C=null,M=null,v={kill:()=>{L.delete(T),C?.handleClose("peer-closed");try{M?.close().catch(()=>{})}catch{}},bind(F){M=F,C=new Be({maxMessageBytes:p.maxMessageBytes,maxInflight:p.maxInflight,write:B=>F.write(B),close:async()=>{try{await F.close()}catch{}await an(T,0)}}),F.onData=B=>C.feed(B),F.onEnd=()=>{C.close("stream-end")},F.onReset=()=>C.handleClose("stream-reset");let U={protocol:b,channelId:T,user:m.username,fingerprint:m.fingerprint,remote:_,features:m.features??[],hostFingerprint:m.hostFingerprint,capabilities:zn(),permits:ot,log:B=>x(`rpc ${b} channel ${T}: ${B}`)};C.hold();let P;try{P=Promise.resolve(R(C,U))}catch(B){P=Promise.reject(B)}P.then(()=>C.release(),B=>{x(`rpc ${b} channel ${T}: handler failed: ${B?.message??B}`),C.close("handler-error")})}};L.set(T,v),at.push(T),await k(Ye({channelId:T,dataMode:"stream",capabilities:[]})),x(`rpc channel ${T}: ${b}`)}async function zl(u,p,b,R){let T=++m.nextChannel,C=null,M=new jt({sendData:U=>k(yt({channelId:T,data:U})),sendCredit:U=>k(Xe({gatewayId:Pr(T),bytes:U})),onViolation:U=>{x(`rpc ${p} channel ${T}: ${U}; closing it`),C?.close("credit-violation")}});C=new Be({maxMessageBytes:R.maxMessageBytes,maxInflight:R.maxInflight,write:U=>M.write(U),onConsumed:U=>M.consumed(U),close:async()=>{M.close(),await an(T,0)}}),L.set(T,{kill:()=>{L.delete(T),M.close(),C.handleClose("peer-closed")},input:U=>{U?.length&&M.receive(U.length)&&C.feed(U)},credit:U=>M.grant(U)});let v={protocol:p,channelId:T,user:m.username,fingerprint:m.fingerprint,remote:_,features:m.features??[],hostFingerprint:m.hostFingerprint,capabilities:zn(),permits:ot,log:U=>x(`rpc ${p} channel ${T}: ${U}`)};C.hold(),await k(Ye({channelId:T,dataMode:"virtual",capabilities:[]})),x(`rpc channel ${T}: ${p} (virtual)`);let F;try{F=Promise.resolve(b(C,v))}catch(U){F=Promise.reject(U)}F.then(()=>C.release(),U=>{x(`rpc ${p} channel ${T}: handler failed: ${U?.message??U}`),C.close("handler-error")})}async function jl(u,p,b){if(!p.pty)return k(re({reason:`pty is not enabled ${p.ownHost?"on this server":"for this target"}`}));let R=++m.nextChannel,T=u.cols||80,C=u.rows||24,M=p.pty,v;try{let P=u.command?["-c",String(u.command)]:[];v=M.spawn(M.shell,P,{name:M.term,cols:T,rows:C,cwd:M.cwd,env:{...M.env??globalThis.process?.env,TERM:M.term,...p.ptyEnv(u.env)},...b!==void 0?{target:b}:{}})}catch(P){return k(re({reason:`pty spawn failed: ${P.message}`}))}let F={keyed:!t.sessions,input:P=>{try{v.write(Uint8Array.from(P))}catch(B){x(`pty channel ${R}: input not written: ${B?.message??B}`)}},resize:(P,B)=>{try{v.resize(P||T,B||C)}catch{}},signal:P=>{try{v.kill(`SIG${P.replace(/^SIG/,"").toUpperCase()}`)}catch{}},kill:()=>{try{v.kill()}catch{}}};if(t.sessions){let P=t.sessions.create({owner:ki(),kind:"pty",command:u.command});P.handlers=F;let B=Mi(P,R,"control");Di(P,B),v.onData(z=>P.push(Uint8Array.from(yi(z)))),v.onExit(({exitCode:z})=>P.finish(z??0));let Q=k(Ye({channelId:R,dataMode:"virtual",capabilities:["resize","signal"],sessionId:P.id,token:P.token}));P.attach(B),await Q,x(`pty channel ${R} opened (${T}x${C}), session ${P.id.slice(0,8)}`);return}L.set(R,F);let U=Promise.resolve();v.onData(P=>{U=U.then(()=>k(yt({channelId:R,data:yi(P)})))}),v.onExit(({exitCode:P})=>{U.then(()=>an(R,P??0))}),await k(Ye({channelId:R,dataMode:"virtual",capabilities:["resize","signal"],sessionId:di(),token:pi(16)})),x(`pty channel ${R} opened (${T}x${C})`)}async function Vl(u,p){let b=p.files;if(!b)return k(re({reason:`file access is not enabled ${p.ownHost?"on this server":"for this target"}`}));let T=String(u.command??"").match(/^(upload|download):(.*)$/s);if(!T)return k(re({reason:"file channel expects upload:<path> or download:<path>"}));let[,C,M]=T,v=++m.nextChannel;if(C==="download"){let P;try{P=await b.readWhole(M)}catch(z){return k(re({reason:z.message}))}let B=!1;L.set(v,{kill:()=>{L.delete(v)&&(B=!0,x(`download ${M}: closed before completion`))}}),await k(Ye({channelId:v,dataMode:"virtual",capabilities:[]}));let Q=0;do{if(B)return;let z=Math.min(Q+65536,P.byteLength);await k(hn({channelId:v,offset:Q,data:P.subarray(Q,z),isFinal:z>=P.byteLength,totalSize:P.byteLength})),Q=z}while(Q<P.byteLength);x(`download ${M} (${P.byteLength} B)`);return}let F={buf:null,kill:()=>{L.delete(v)&&x(`upload ${M}: closed before completion, nothing written`)}};L.set(v,F);let U=async(P,B)=>{B&&x(`upload ${M}: ${B}`),await an(v,P)};F.chunk=async P=>{if(F.failed)return;let B=Number(P.total_size??0);if(B>b.maxFileBytes)return F.failed=!0,U(1,`refused: ${B} B exceeds ${b.maxFileBytes} B`);F.buf??=new Uint8Array(B);let Q=P.data instanceof Uint8Array?P.data:new Uint8Array(0);if(P.offset+Q.byteLength>F.buf.byteLength)return F.failed=!0,U(1,"chunk past total_size");if(F.buf.set(Q,P.offset),P.is_final){try{await b.writeWhole(M,F.buf)}catch(z){return F.failed=!0,U(1,z.message)}return U(0,`stored ${F.buf.byteLength} B`)}},await k(Ye({channelId:v,dataMode:"virtual",capabilities:[]}))}async function Yl(u){let p=u.channel_id,b=u.target??void 0,R=me({kind:"file-op",op:u.op,target:b});if(R)return k(de({channelId:p,success:!1,errorMessage:R.reason}));let T=await Yn(b,"file");if(T.refuse)return k(de({channelId:p,success:!1,errorMessage:T.refuse}));let C=T.b.files;if(!C)return k(de({channelId:p,success:!1,errorMessage:`file access is not enabled ${T.b.ownHost?"on this server":"for this target"}`}));if(u.op==="write"||u.op==="rename")return ql(u,C);try{let M=await C.operate(u.op,u.path,{offset:u.offset,length:u.length});return k(de({channelId:p,success:!0,metadata:M.metadata??{},entries:M.entries??[]}))}catch(M){let v=M.wsh?M.message:M.code==="ENOENT"?"no such file or directory":`${u.op} failed`;return!M.wsh&&M.code!=="ENOENT"&&x(`file ${u.op} ${u.path}: ${M.message}`),k(de({channelId:p,success:!1,errorMessage:v}))}}async function ql(u,p){let b=u.channel_id,R=U=>k(de({channelId:b,success:!1,errorMessage:U})),T=u.op==="rename",C=Number(u.length);if(!Number.isSafeInteger(C)||C<0)return R(`${u.op} needs a length`);let M=T?td:p.maxFileBytes;if(C>M)return R(`${u.op} payload of ${C} bytes exceeds the ${M} byte limit`);if(L.has(b)||Te.has(b))return R("channel id already in use");if(Te.size>=ed)return R("too many writes in flight");let v={rename:T,files:p,path:u.path,offset:u.offset,length:C,buf:new Uint8Array(C),next:0,timer:null},F=()=>{clearTimeout(v.timer),v.timer=setTimeout(()=>{Te.delete(b)&&R("write timed out waiting for data")},nd),v.timer.unref?.()};F(),v.arm=F,Te.set(b,v)}async function Xl(u){let p=u.channel_id,b=Te.get(p),R=C=>(clearTimeout(b.timer),Te.delete(p),k(de({channelId:p,success:!1,errorMessage:C}))),T=u.data instanceof Uint8Array?u.data:new Uint8Array(0);if(u.offset!==b.next)return R("chunks must arrive in order");if(b.next+T.byteLength>b.length)return R("chunk past the declared length");if(b.buf.set(T,b.next),b.next+=T.byteLength,!u.is_final){b.arm();return}if(clearTimeout(b.timer),Te.delete(p),b.next!==b.length)return k(de({channelId:p,success:!1,errorMessage:"payload ended short of the declared length"}));try{let C=b.rename?await b.files.operate("rename",b.path,{newPath:new TextDecoder("utf-8",{fatal:!0}).decode(b.buf)}):await b.files.operate("write",b.path,{offset:b.offset,data:b.buf});return k(de({channelId:p,success:!0,metadata:C.metadata??{}}))}catch(C){let M=C.wsh?C.message:C.code==="ENOENT"?"no such file or directory":`${b.rename?"rename":"write"} failed`;return!C.wsh&&C.code!=="ENOENT"&&x(`file write ${b.path}: ${C.message}`),k(de({channelId:p,success:!1,errorMessage:M}))}}return{receive(u){m.closed||ct?.receiveBytes(u)},receiveDatagram(u){!m.closed&&m.authed&&rn?.handleDatagram?.(u)},receiveMessage(u){m.closed||(Ue=Ue.then(()=>Ci(u)).catch(p=>x(`handler error: ${p.message}`)))},bindStream:Oi,close(){It("transport closed")}}}}function sd(t){let e=[],n=[];return String(t??"").split(`
|
|
5
|
+
`).forEach((r,s)=>{let i=ol(r);i.refused?n.push({line:s+1,...i.refused,key:i.key}):i.key&&e.push({key:i.key,options:i.options,permissions:i.permissions,line:s+1})}),{entries:e,refused:n}}async function wl(t,{log:e=()=>{}}={}){let n=new Map,r=a=>Object.assign(a,{permissionsFor:c=>c?n.get(c)??null:null}),s=a=>{if(a===!0)return!0;if(a&&typeof a=="object"&&!Array.isArray(a)&&(a.capabilities!==void 0||a.expires!==void 0)){let c=il(a);if(c.ok)return{permissions:c.permissions};e(`authorize returned a grant that is not understood (${c.code}): ${c.reason}`)}return!1};if(typeof t=="function")return r(async a=>s(await t(a)));if(!t)return r(async()=>!1);let i=null;if(t.authorizedKeys!==void 0){i=new Set;let a=Array.isArray(t.authorizedKeys)?t.authorizedKeys:[t.authorizedKeys];for(let c of a){let l;if(typeof c=="string"){let{entries:h,refused:d}=sd(c);for(let w of d)e(`authorized_keys line ${w.line}: key refused (${w.code}): ${w.reason}`);l=h}else l=[{key:c,permissions:null}];for(let{key:h,permissions:d}of l){if(!(h instanceof Uint8Array)||h.byteLength!==32)throw new TypeError("createWshServer: auth.authorizedKeys entries must be ssh-ed25519 lines or raw 32-byte Ed25519 keys");let w=await oe(h);!i.has(w)&&d&&n.set(w,d),i.add(w)}}}let o=typeof t.authorize=="function"?t.authorize:null;return r(!i&&!o?async()=>!1:async a=>i&&!i.has(a.fingerprint)?!1:o?s(await o(a)):!0)}function ml(t){if(typeof t=="function")return{pubkey:!0,password:null};if(!t)return{pubkey:!1,password:null};if(t.password!==void 0&&typeof t.password!="function")throw new TypeError("createWshServer: auth.password must be a function (user, pass) => boolean | Promise<boolean>");return{pubkey:t.authorizedKeys!==void 0||typeof t.authorize=="function",password:t.password??null}}var Yr=class{#e=new Map;#n;constructor({maxFailures:e=5,windowMs:n=6e4,lockoutMs:r=6e4,now:s=Date.now}={}){this.maxFailures=e,this.windowMs=n,this.lockoutMs=r,this.#n=s}lockedFor(e){let n=this.#e.get(e);if(!n)return 0;let r=this.#n();return n.lockedUntil>r?n.lockedUntil-r:(r-n.first>this.windowMs&&this.#e.delete(e),0)}fail(e){let n=this.#n(),r=this.#e.get(e);(!r||n-r.first>this.windowMs)&&(r={count:0,first:n,lockedUntil:0},this.#e.set(e,r)),r.count++,r.count>=this.maxFailures&&(r.lockedUntil=n+this.lockoutMs),this.#e.size>1e4&&this.#e.delete(this.#e.keys().next().value)}succeed(e){this.#e.delete(e)}};async function gl(t){if(t instanceof Uint8Array)return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t)){let e=await Promise.all(t.map(gl)),n=new Uint8Array(e.reduce((s,i)=>s+i.byteLength,0)),r=0;for(let s of e)n.set(s,r),r+=s.byteLength;return n}return t&&typeof t.arrayBuffer=="function"?new Uint8Array(await t.arrayBuffer()):null}function _l(t,e,{remote:n={},dataStreams:r,sealSession:s}={}){if(!t||typeof t.send!="function"||typeof t.close!="function")throw new TypeError("accept: socket must be a WebSocket-like duplex with send() and close()");let i=typeof t.addEventListener=="function"?(E,g)=>t.addEventListener(E,A=>g(E==="message"?A?.data:A)):typeof t.on=="function"?(E,g)=>t.on(E,g):null;if(!i)throw new TypeError("accept: socket must support addEventListener() or on()");try{t.binaryType="arraybuffer"}catch{}let o=null,a=!1,c=[],l=0,h=()=>{let E=c;if(c=[],l=0,t.readyState===1)for(let g of E)t.send(g)},d=E=>{if(t.readyState===1){c.length&&h(),t.send(E);return}t.readyState===0&&l+E.byteLength<=262144&&(c.push(E),l+=E.byteLength)},w=e.then(E=>{a||(o=E({send:d,remote:{address:n.address,headers:n.headers??{}},dataStreams:r,...s!==void 0?{sealSession:s}:{},closeTransport:()=>{try{t.close(1e3)}catch{}}}))}),y=!1,_=()=>{y||(y=!0,w=w.then(()=>(a=!0,o?.close())).catch(()=>{}))};return i("message",E=>{y||(w=w.then(async()=>{if(a||!o)return;let g=await gl(E);g&&!a&&o.receive(g)}).catch(()=>{}))}),i("open",h),i("close",_),i("error",()=>{}),w.then(()=>({close(){_();try{t.close(1e3)}catch{}}}))}var mi=1024*1024,gi=3e5,_i=16;var id=new Uint8Array(8).fill(255),Ei=class{#e=[];#n=0;start=0;end=0;constructor(e){this.max=e}push(e){if(e.byteLength)for(this.#e.push(Uint8Array.from(e)),this.#n+=e.byteLength,this.end+=e.byteLength;this.#n>this.max;){let n=this.#n-this.max,r=this.#e[0];r.byteLength<=n?(this.#e.shift(),this.#n-=r.byteLength,this.start+=r.byteLength):(this.#e[0]=r.subarray(n),this.#n-=n,this.start+=n)}}read(e=this.start){let n=Math.max(0,e-this.start),r=new Uint8Array(Math.max(0,this.#n-n)),s=0,i=0;for(let o of this.#e){if(i+o.byteLength>n){let a=o.subarray(Math.max(0,n-i));r.set(a,s),s+=a.byteLength}i+=o.byteLength}return r}},wi=class{attachments=new Set;state="attached";disposed=!1;exitCode=null;createdAt=Date.now();lastActivity=Date.now();detachedAt=0;name;#e=null;constructor(e,{id:n,token:r,owner:s,kind:i,command:o,ringBytes:a}){this.registry=e,this.id=n,this.token=r,this.owner=s,this.kind=i,this.command=o,this.ring=new Ei(a),this.handlers={}}push(e){this.lastActivity=Date.now(),this.ring.push(e);for(let n of this.attachments)n.write(e)}attach(e){this.attachments.add(e),this.state="attached",this.#r(),this.broadcastPresence(e)}detach(e){this.attachments.delete(e)&&(this.broadcastPresence(),this.attachments.size===0&&this.#n())}roster(){return[...this.attachments].map(e=>({session_id:this.id,mode:e.mode,username:e.username}))}broadcastPresence(e){if(this.attachments.size===0)return;let n={attachments:this.roster()};for(let r of this.attachments)r!==e&&r.notify(n)}finish(e){if(this.state==="exited")return;this.exitCode=e,this.state="exited";let n=[...this.attachments];this.attachments.clear();for(let r of n)r.exit(e);this.#n()}kill(){try{this.handlers.kill?.()}catch{}}dispose(){this.disposed=!0,this.#r(),this.registry._forget(this),this.state!=="exited"&&(this.kill(),this.state="exited")}#n(){if(this.disposed)return;this.detachedAt=Date.now(),this.state!=="exited"&&(this.state="detached"),this.#r();let e=this.registry.detachTtlMs;if(e<=0){this.dispose();return}this.#e=setTimeout(()=>{this.registry.log(`session ${this.id} expired after ${e}ms detached`),this.dispose()},e),this.#e.unref?.(),this.registry._enforceMaxDetached(this)}#r(){clearTimeout(this.#e),this.#e=null}},qr=class{#e=new Map;constructor({detachTtlMs:e=gi,maxDetached:n=_i,ringBytes:r=mi,log:s=()=>{}}={}){this.detachTtlMs=e,this.maxDetached=n,this.ringBytes=r,this.log=s}create({owner:e,kind:n,command:r}){let s=globalThis.crypto.randomUUID(),i=new wi(this,{id:s,token:this.mintToken(s),owner:e,kind:n,command:r,ringBytes:this.ringBytes});return this.#e.set(s,i),i}get(e){return typeof e=="string"?this.#e.get(e):void 0}mintToken(e){let n=new Uint8Array(40);return n.set(id,0),globalThis.crypto.getRandomValues(n.subarray(8)),n}checkToken(e,n){if(!(n instanceof Uint8Array)||n.byteLength!==40||e.token.byteLength!==40)return!1;let r=0;for(let s=0;s<40;s++)r|=n[s]^e.token[s];return r===0}listFor(e){return[...this.#e.values()].filter(n=>n.owner.principal===e)}get size(){return this.#e.size}closeAll(){for(let e of[...this.#e.values()])e.dispose()}_forget(e){this.#e.delete(e.id)}_enforceMaxDetached(){let e=[...this.#e.values()].filter(n=>n.attachments.size===0).sort((n,r)=>n.detachedAt-r.detachedAt);for(;e.length>this.maxDetached;){let n=e.shift();this.log(`session ${n.id} evicted (more than ${this.maxDetached} detached)`),n.dispose()}}};var bl=0,Xr=1,bi=2,Ai=3,Al="ws://memory.invalid/";function Tl(t,e){let n=new Event(t);return Object.assign(n,e),n}var Wn=class extends EventTarget{static CONNECTING=bl;static OPEN=Xr;static CLOSING=bi;static CLOSED=Ai;readyState=bl;binaryType="arraybuffer";peer=null;send(e){if(this.readyState!==Xr)throw new Error("WebSocket is not open");if(typeof e=="string")return;let r=(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).slice().buffer,s=this.peer;queueMicrotask(()=>{s.readyState===Xr&&s.dispatchEvent(Tl("message",{data:r}))})}close(e=1e3,n=""){if(this.readyState>=bi)return;this.readyState=bi;let r=this.peer;queueMicrotask(()=>{for(let s of[this,r])s.readyState!==Ai&&(s.readyState=Ai,s.dispatchEvent(Tl("close",{code:e,reason:n,wasClean:!0})))})}};function xl(){let t=new Wn,e=new Wn;return t.peer=e,e.peer=t,queueMicrotask(()=>{for(let n of[t,e])n.readyState=Xr,n.dispatchEvent(new Event("open"))}),[t,e]}function od(t,e){let n=t===!0?{}:t;if(typeof n!="object"||Array.isArray(n))throw new TypeError("createMemoryHost: sessions must be true or { detachTtlMs, maxDetached, ringBytes }");let{detachTtlMs:r=gi,maxDetached:s=_i,ringBytes:i=mi}=n;if(!(Number.isFinite(r)&&r>=0))throw new TypeError("createMemoryHost: sessions.detachTtlMs must be a non-negative number");if(!Number.isSafeInteger(s)||s<0)throw new TypeError("createMemoryHost: sessions.maxDetached must be a non-negative integer");if(!Number.isSafeInteger(i)||i<1)throw new TypeError("createMemoryHost: sessions.ringBytes must be a positive integer");return new qr({detachTtlMs:r,maxDetached:s,ringBytes:i,log:e})}function ad({auth:t,exec:e,pty:n,fs:r,hostKey:s,mcp:i,extensions:o,rpc:a,rpcMaxMessageBytes:c=He,rpcMaxInflight:l=64,sessions:h,endpoints:d,dataStreams:w=!0,bindTimeoutMs:y=3e3,connectionTtlMs:_=0,requireChannelBinding:E=!1,sealSession:g=!1,onLog:A=()=>{},onShare:I,onRefused:S,onSealed:O,targets:N,requireTarget:D,usernamePattern:x}={}){if(O!==void 0&&typeof O!="function")throw new TypeError("createMemoryHost: onSealed must be a function");if(Vr(x,"createMemoryHost"),dl(I,"createMemoryHost"),zr(S,"createMemoryHost"),!Number.isFinite(_)||_<0)throw new TypeError("createMemoryHost: connectionTtlMs must be a non-negative number");if(E!==!1&&E!==!0&&!(Array.isArray(E)&&E.every(X=>Kt.includes(X))))throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${Kt.join(", ")})`);if(Array.isArray(E)&&E.some(X=>X!=="host"))throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');if(E&&!s)throw new TypeError("createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)");if(g!==!1&&g!=="offer"&&g!=="require")throw new TypeError("createMemoryHost: sealSession must be false, 'offer' or 'require'");if(g&&!s)throw new TypeError("createMemoryHost: sealSession needs a hostKey (the host signs its half of the key exchange with it)");if(e===!0)throw new TypeError("createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with");if(e!==void 0&&typeof e!="function"&&typeof e?.run!="function")throw new TypeError("createMemoryHost: exec must be a function or { run }");if(o!==void 0&&(o===null||typeof o!="object"))throw new TypeError("createMemoryHost: extensions must be an object of handlers");if(typeof w!="boolean")throw new TypeError("createMemoryHost: dataStreams must be true or false");let m=a==null?null:Wc(a,c,l,"createMemoryHost"),L=h==null||h===!1?null:od(h,A),{execRunner:G,execOptions:$,pty:ee,files:ie,mcp:Re,targets:me,requireTarget:Rt}=zc({exec:e,pty:n,fs:r,mcp:i,targets:N,requireTarget:D}),zn=s==null||s===!1?Promise.resolve(null):jc(s,"createMemoryHost: hostKey"),ot=t?.rateLimit??{},Jr={limiter:new Yr(ot),key:typeof ot.key=="function"?ot.key:({address:X})=>String(X??"unknown"),failureDelayMs:ot.failureDelayMs??250},Te=ml(t),Ie=d==null?null:ci({endpoints:d});me&&[...me.values()].some(X=>X.endpoints)&&(Ie={...Ie??ci({}),targetEndpoints:!0});let Ge=Promise.all([wl(t,{log:A}),zn]).then(([X,xe])=>El({authorize:X,execRunner:G,execOptions:$,pty:ee,files:ie,bindTimeoutMs:y,connectionTtlMs:_,requireChannelBinding:E,sealSession:g,log:A,methods:Te,hostKey:xe,rateLimit:Jr,extensions:o,mcp:Re,rpc:m,onShare:I,onRefused:S,onSealed:O,targets:me,requireTarget:Rt,usernamePattern:x,gateway:Ie,createGatewaySession:Ie?Bc:void 0,sessions:L,relay:null}));Ge.catch(()=>{});let at=new Set,jn=!1;async function nn(X,xe){if(jn)throw new Error("createMemoryHost: host is closed");let ve=await _l(X,Ge,{dataStreams:w,...xe});return at.add(ve),ve}class Ot extends Wn{constructor(){super();let[xe,ve]=xl();return nn(ve,{remote:{address:"memory"}}).catch(A),xe}}let Ue={url:Al,WebSocket:Ot,accept:nn,socketPair:xl,createClient(X={}){return new rt({...X,transportFactories:{ws:()=>new Me({WebSocket:Ot}),wt:()=>{throw new Error("createMemoryHost: WebTransport is not available in memory")}}})},async connect(X){let xe=Ue.createClient();return await xe.connect(Al,{transport:"ws",...X}),xe},async close(){jn=!0;for(let X of at)X.close();at.clear(),L?.closeAll()}};return Ue}var Sl=0,Ti=1,cd=2,Rl=3,ld=64*1024,ud=4*1024*1024,Ol=t=>t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):null,tn=class extends Event{constructor(e,n={}){super(e),Object.assign(this,n)}};function hd({send:t,close:e,maxMessageBytes:n=ld,maxBufferedBytes:r=ud}={}){if(typeof t!="function")throw new TypeError("createDuplexSocket: send(bytes) is required");if(e!==void 0&&typeof e!="function")throw new TypeError("createDuplexSocket: close must be a function");if(!Number.isSafeInteger(n)||n<256)throw new TypeError("createDuplexSocket: maxMessageBytes must be a whole number of at least 256");if(!Number.isSafeInteger(r)||r<n)throw new TypeError("createDuplexSocket: maxBufferedBytes must be a whole number of at least maxMessageBytes");let s=new EventTarget,i=0,o=Promise.resolve(),a=!1,c=(_,E,{callClose:g=!0}={})=>{if(!a){if(a=!0,y.readyState=Rl,g)try{e?.(E)}catch{}s.dispatchEvent(new tn("close",{code:_,reason:E,wasClean:_===1e3}))}},l=!1,h=0,d=[],w=()=>{if(!(!l||h===0))for(;d.length&&!a;)s.dispatchEvent(new tn("message",{data:d.shift()}))},y={CONNECTING:Sl,OPEN:Ti,CLOSING:cd,CLOSED:Rl,readyState:Sl,binaryType:"arraybuffer",get bufferedAmount(){return i},addEventListener:(_,E,g)=>{s.addEventListener(_,E,g),_==="open"&&l&&!a&&queueMicrotask(()=>{a||E(new tn("open"))}),_==="message"&&(h++,queueMicrotask(w))},removeEventListener:(_,E)=>s.removeEventListener(_,E),send(_){if(y.readyState!==Ti)throw new Error("WebSocket is not open");let E=Ol(_);if(E)for(let g=0;g<E.byteLength;g+=n){let A=E.slice(g,g+n);if(i+A.byteLength>r){c(1013,"the duplex does not take what is written to it");return}i+=A.byteLength,o=o.then(async()=>{if(!a)try{await t(A)}catch{c(1011,"the duplex failed to send")}finally{i-=A.byteLength}})}},close(_=1e3,E=""){c(_,E)}};return queueMicrotask(()=>{a||(y.readyState=Ti,l=!0,s.dispatchEvent(new tn("open")),w())}),{socket:y,receive(_){if(a)return;let E=Ol(_);if(!E){c(1003,"a message that is not bytes");return}if(E.byteLength>n){c(1009,"a message larger than maxMessageBytes");return}if(d.reduce((g,A)=>g+A.byteLength,0)+E.byteLength>r){c(1013,"more arrived than the receiver takes");return}d.push(E.slice().buffer),queueMicrotask(w)},end(_="the duplex ended"){c(1006,_,{callClose:!1})},get closed(){return a}}}function fd(t,{allowUnsealed:e=!1,...n}={}){if(typeof e!="boolean")throw new TypeError("connectWshOverDuplex: allowUnsealed must be true or false");if(n.password!==void 0&&!e)throw new TypeError("connectWshOverDuplex: a password login cannot be sealed (a hop would read it): use a key, or say allowUnsealed: true");if(n.expectHostKey===void 0&&n.knownHosts===void 0&&n.trustOnFirstUse!==!0&&n.onHostKey===void 0)throw new TypeError("connectWshOverDuplex: name the host key you expect (expectHostKey: its hex fingerprint, over a mesh the peer's pod id converted with podIdToFingerprint), or knownHosts, or say trustOnFirstUse: true (a hop on the duplex could answer as the host)");let r=hd(t),s=!1;function i(){if(s)throw new Error("this duplex carries one connection and it is in use");return s=!0,r.socket}let o=new rt({transportFactories:{ws:()=>new Me({WebSocket:i}),wt:()=>{throw new Error("connectWshOverDuplex: a duplex is not WebTransport")}}}),a=o.connect("ws://duplex.invalid/",{transport:"ws",...e?{}:{sealSession:!0,requireChannelBinding:["host"]},...n}).then(()=>o);return a.catch(()=>{}),{receive:r.receive,end:r.end,client:o,connected:a,close:()=>o.disconnect()}}export{ye as HostKeyError,j as RPC_ERROR,q as RpcError,Wr as SessionRecorder,Me as WebSocketTransport,rt as WshClient,Gr as WshKnownHosts,fd as connectWshOverDuplex,ad as createMemoryHost,fn as exportPublicKeyRaw,Ut as exportPublicKeySSH,oe as fingerprint,Yo as importPrivateKeyPKCS8,Vo as isEd25519Supported,xt as rpcProtocolFeature};
|