stitchkit 0.133.1 → 0.134.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/CHANGELOG.md +121 -0
- package/README.md +14 -11
- package/dist/agent-executor/acp/v1-connect.d.ts +5 -0
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-map.d.ts +13 -3
- package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-probe.d.ts +3 -0
- package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-protocol.d.ts +61 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +3 -0
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +2 -0
- package/dist/agent-executor/codex/connect.d.ts.map +1 -1
- package/dist/agent-executor/codex/driver.d.ts +3 -0
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/contract.d.ts +42 -0
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine-process.d.ts +20 -0
- package/dist/agent-executor/engine-process.d.ts.map +1 -1
- package/dist/agent-executor/executor-contract.d.ts +42 -0
- package/dist/agent-executor/executor-contract.d.ts.map +1 -1
- package/dist/agent-executor/handoff-schemas.d.ts +30 -0
- package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
- package/dist/agent-executor/projection.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +4 -1
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -1
- package/dist/agent-executor/vocabulary.d.ts +100 -0
- package/dist/agent-executor/vocabulary.d.ts.map +1 -1
- package/dist/agent-parts/model.d.ts +1559 -0
- package/dist/agent-parts/model.d.ts.map +1 -0
- package/dist/agent-parts/parts.d.ts +21 -0
- package/dist/agent-parts/parts.d.ts.map +1 -1
- package/dist/agent-runtime/ai-sdk-convert.d.ts +15 -0
- package/dist/agent-runtime/ai-sdk-convert.d.ts.map +1 -0
- package/dist/agent-runtime/ai-sdk.d.ts +31 -0
- package/dist/agent-runtime/ai-sdk.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-media.d.ts +11 -0
- package/dist/agent-runtime/anthropic-media.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-messages.d.ts +24 -0
- package/dist/agent-runtime/anthropic-messages.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-options.d.ts +79 -0
- package/dist/agent-runtime/anthropic-options.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-response.d.ts +19 -0
- package/dist/agent-runtime/anthropic-response.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic-sse.d.ts +4 -0
- package/dist/agent-runtime/anthropic-sse.d.ts.map +1 -0
- package/dist/agent-runtime/anthropic.d.ts +27 -0
- package/dist/agent-runtime/anthropic.d.ts.map +1 -0
- package/dist/agent-runtime/branch-observations.d.ts +25 -25
- package/dist/agent-runtime/branch-provider.d.ts +86 -0
- package/dist/agent-runtime/branch-provider.d.ts.map +1 -1
- package/dist/agent-runtime/branch-replay.d.ts +30 -0
- package/dist/agent-runtime/branch-replay.d.ts.map +1 -1
- package/dist/agent-runtime/browser-control-contract.d.ts +204 -0
- package/dist/agent-runtime/browser-control-contract.d.ts.map +1 -1
- package/dist/agent-runtime/browser-controller-view.d.ts +44 -0
- package/dist/agent-runtime/browser-controller-view.d.ts.map +1 -0
- package/dist/agent-runtime/browser-controller.d.ts +12 -8
- package/dist/agent-runtime/browser-controller.d.ts.map +1 -1
- package/dist/agent-runtime/child-budget-policy.d.ts +2 -3
- package/dist/agent-runtime/child-budget-policy.d.ts.map +1 -1
- package/dist/agent-runtime/compaction.d.ts +27 -10
- package/dist/agent-runtime/compaction.d.ts.map +1 -1
- package/dist/agent-runtime/control-interaction-schema.d.ts +157 -0
- package/dist/agent-runtime/control-interaction-schema.d.ts.map +1 -0
- package/dist/agent-runtime/control-schema.d.ts +183 -27
- package/dist/agent-runtime/control-schema.d.ts.map +1 -1
- package/dist/agent-runtime/control-view.d.ts +64 -0
- package/dist/agent-runtime/control-view.d.ts.map +1 -0
- package/dist/agent-runtime/conversations.d.ts +10 -0
- package/dist/agent-runtime/conversations.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tool-selection.d.ts +2 -2
- package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tool-types.d.ts +2 -2
- package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tools-internal.d.ts +8 -11
- package/dist/agent-runtime/deferred-tools-internal.d.ts.map +1 -1
- package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
- package/dist/agent-runtime/event-schema.d.ts +80 -0
- package/dist/agent-runtime/event-schema.d.ts.map +1 -1
- package/dist/agent-runtime/harness-contract.d.ts +2 -2
- package/dist/agent-runtime/harness-contract.d.ts.map +1 -1
- package/dist/agent-runtime/harness-control.d.ts.map +1 -1
- package/dist/agent-runtime/harness-realtime.d.ts.map +1 -1
- package/dist/agent-runtime/harness.d.ts +2 -2
- package/dist/agent-runtime/harness.d.ts.map +1 -1
- package/dist/agent-runtime/history.d.ts +25 -16
- package/dist/agent-runtime/history.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-attempt.d.ts +7 -3
- package/dist/agent-runtime/invocation-attempt.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-payload.d.ts +13 -7
- package/dist/agent-runtime/invocation-payload.d.ts.map +1 -1
- package/dist/agent-runtime/invocation-stream.d.ts +20 -0
- package/dist/agent-runtime/invocation-stream.d.ts.map +1 -0
- package/dist/agent-runtime/invocations.d.ts +2 -2
- package/dist/agent-runtime/invocations.d.ts.map +1 -1
- package/dist/agent-runtime/models-driver-step.d.ts +212 -0
- package/dist/agent-runtime/models-driver-step.d.ts.map +1 -0
- package/dist/agent-runtime/models-driver-telemetry.d.ts +42 -0
- package/dist/agent-runtime/models-driver-telemetry.d.ts.map +1 -0
- package/dist/agent-runtime/models-driver.d.ts +235 -0
- package/dist/agent-runtime/models-driver.d.ts.map +1 -0
- package/dist/agent-runtime/models.d.ts +3 -26
- package/dist/agent-runtime/models.d.ts.map +1 -1
- package/dist/agent-runtime/observability.d.ts +64 -0
- package/dist/agent-runtime/observability.d.ts.map +1 -1
- package/dist/agent-runtime/openai-messages.d.ts +11 -0
- package/dist/agent-runtime/openai-messages.d.ts.map +1 -0
- package/dist/agent-runtime/openai-options.d.ts +91 -0
- package/dist/agent-runtime/openai-options.d.ts.map +1 -0
- package/dist/agent-runtime/openai-response.d.ts +77 -0
- package/dist/agent-runtime/openai-response.d.ts.map +1 -0
- package/dist/agent-runtime/openai-sse-state.d.ts +54 -0
- package/dist/agent-runtime/openai-sse-state.d.ts.map +1 -0
- package/dist/agent-runtime/openai-sse.d.ts +4 -0
- package/dist/agent-runtime/openai-sse.d.ts.map +1 -0
- package/dist/agent-runtime/openai.d.ts +31 -0
- package/dist/agent-runtime/openai.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-admission.d.ts +3 -0
- package/dist/agent-runtime/openrouter-admission.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-benchmarks.d.ts +17 -0
- package/dist/agent-runtime/openrouter-benchmarks.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog-cache.d.ts +70 -0
- package/dist/agent-runtime/openrouter-catalog-cache.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog-query.d.ts +57 -0
- package/dist/agent-runtime/openrouter-catalog-query.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter-catalog.d.ts +189 -14
- package/dist/agent-runtime/openrouter-catalog.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-models.d.ts +168 -31
- package/dist/agent-runtime/openrouter-models.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-options.d.ts +45 -15
- package/dist/agent-runtime/openrouter-options.d.ts.map +1 -1
- package/dist/agent-runtime/openrouter-response.d.ts +22 -0
- package/dist/agent-runtime/openrouter-response.d.ts.map +1 -0
- package/dist/agent-runtime/openrouter.d.ts +21 -24
- package/dist/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/agent-runtime/owned-provider-stream.d.ts +4 -4
- package/dist/agent-runtime/owned-provider-stream.d.ts.map +1 -1
- package/dist/agent-runtime/prompt.d.ts +3 -3
- package/dist/agent-runtime/prompt.d.ts.map +1 -1
- package/dist/agent-runtime/protocol.d.ts +28 -3
- package/dist/agent-runtime/protocol.d.ts.map +1 -1
- package/dist/agent-runtime/provider-cache.d.ts +30 -0
- package/dist/agent-runtime/provider-cache.d.ts.map +1 -0
- package/dist/agent-runtime/provider-content.d.ts +147 -0
- package/dist/agent-runtime/provider-content.d.ts.map +1 -1
- package/dist/agent-runtime/provider-failure.d.ts +51 -26
- package/dist/agent-runtime/provider-failure.d.ts.map +1 -1
- package/dist/agent-runtime/provider-history.d.ts +13 -0
- package/dist/agent-runtime/provider-history.d.ts.map +1 -0
- package/dist/agent-runtime/provider-http.d.ts +68 -0
- package/dist/agent-runtime/provider-http.d.ts.map +1 -0
- package/dist/agent-runtime/provider-journal.d.ts +149 -0
- package/dist/agent-runtime/provider-journal.d.ts.map +1 -1
- package/dist/agent-runtime/provider-json-schema-strip.d.ts +8 -0
- package/dist/agent-runtime/provider-json-schema-strip.d.ts.map +1 -0
- package/dist/agent-runtime/provider-json-schema.d.ts +28 -0
- package/dist/agent-runtime/provider-json-schema.d.ts.map +1 -0
- package/dist/agent-runtime/provider-media.d.ts +49 -0
- package/dist/agent-runtime/provider-media.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat-helpers.d.ts +27 -0
- package/dist/agent-runtime/provider-openai-chat-helpers.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat-sse.d.ts +25 -0
- package/dist/agent-runtime/provider-openai-chat-sse.d.ts.map +1 -0
- package/dist/agent-runtime/provider-openai-chat.d.ts +27 -0
- package/dist/agent-runtime/provider-openai-chat.d.ts.map +1 -0
- package/dist/agent-runtime/provider-origin.d.ts +3 -12
- package/dist/agent-runtime/provider-origin.d.ts.map +1 -1
- package/dist/agent-runtime/provider-sse.d.ts +30 -0
- package/dist/agent-runtime/provider-sse.d.ts.map +1 -0
- package/dist/agent-runtime/provider-stream-parts.d.ts +5 -0
- package/dist/agent-runtime/provider-stream-parts.d.ts.map +1 -0
- package/dist/agent-runtime/provider-stream-segments.d.ts +63 -0
- package/dist/agent-runtime/provider-stream-segments.d.ts.map +1 -0
- package/dist/agent-runtime/provider-usage.d.ts +24 -0
- package/dist/agent-runtime/provider-usage.d.ts.map +1 -0
- package/dist/agent-runtime/retry-policy.d.ts +19 -3
- package/dist/agent-runtime/retry-policy.d.ts.map +1 -1
- package/dist/agent-runtime/run-acquisition.d.ts +4 -4
- package/dist/agent-runtime/run-acquisition.d.ts.map +1 -1
- package/dist/agent-runtime/run-approval.d.ts +82 -0
- package/dist/agent-runtime/run-approval.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-retry.d.ts +24 -0
- package/dist/agent-runtime/run-complete-retry.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-stream.d.ts +9 -0
- package/dist/agent-runtime/run-complete-stream.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-tools.d.ts +21 -0
- package/dist/agent-runtime/run-complete-tools.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete-types.d.ts +168 -0
- package/dist/agent-runtime/run-complete-types.d.ts.map +1 -0
- package/dist/agent-runtime/run-complete.d.ts +25 -0
- package/dist/agent-runtime/run-complete.d.ts.map +1 -0
- package/dist/agent-runtime/run-driver-compose.d.ts +21 -0
- package/dist/agent-runtime/run-driver-compose.d.ts.map +1 -0
- package/dist/agent-runtime/run-execution-state.d.ts +23 -10
- package/dist/agent-runtime/run-execution-state.d.ts.map +1 -1
- package/dist/agent-runtime/run-execution.d.ts +2 -2
- package/dist/agent-runtime/run-execution.d.ts.map +1 -1
- package/dist/agent-runtime/run-failure.d.ts +2 -2
- package/dist/agent-runtime/run-failure.d.ts.map +1 -1
- package/dist/agent-runtime/run-history-parts.d.ts +14 -0
- package/dist/agent-runtime/run-history-parts.d.ts.map +1 -0
- package/dist/agent-runtime/run-loop-events.d.ts +126 -0
- package/dist/agent-runtime/run-loop-events.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-attempts.d.ts +2 -2
- package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -1
- package/dist/agent-runtime/run-model-messages.d.ts +9 -0
- package/dist/agent-runtime/run-model-messages.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-step.d.ts +43 -0
- package/dist/agent-runtime/run-model-step.d.ts.map +1 -0
- package/dist/agent-runtime/run-model-stream.d.ts +27 -0
- package/dist/agent-runtime/run-model-stream.d.ts.map +1 -0
- package/dist/agent-runtime/run-operation-lifecycle.d.ts +8 -4
- package/dist/agent-runtime/run-operation-lifecycle.d.ts.map +1 -1
- package/dist/agent-runtime/run-prompt-history.d.ts +8 -13
- package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -1
- package/dist/agent-runtime/run-provider-ledger.d.ts +7 -4
- package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -1
- package/dist/agent-runtime/run-step-barriers.d.ts +58 -16
- package/dist/agent-runtime/run-step-barriers.d.ts.map +1 -1
- package/dist/agent-runtime/run-step-helpers.d.ts +49 -0
- package/dist/agent-runtime/run-step-helpers.d.ts.map +1 -0
- package/dist/agent-runtime/run-step-prepare.d.ts +34 -0
- package/dist/agent-runtime/run-step-prepare.d.ts.map +1 -0
- package/dist/agent-runtime/run-step-spend.d.ts +85 -10
- package/dist/agent-runtime/run-step-spend.d.ts.map +1 -1
- package/dist/agent-runtime/run-stream-parts.d.ts +13 -9
- package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -1
- package/dist/agent-runtime/run-stream-recorded.d.ts +8 -0
- package/dist/agent-runtime/run-stream-recorded.d.ts.map +1 -0
- package/dist/agent-runtime/run-stream-step-text.d.ts +29 -0
- package/dist/agent-runtime/run-stream-step-text.d.ts.map +1 -0
- package/dist/agent-runtime/run-terminal.d.ts +3 -3
- package/dist/agent-runtime/run-terminal.d.ts.map +1 -1
- package/dist/agent-runtime/run-tool-approval-flow.d.ts +36 -0
- package/dist/agent-runtime/run-tool-approval-flow.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-approval-records.d.ts +24 -0
- package/dist/agent-runtime/run-tool-approval-records.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-call.d.ts +73 -0
- package/dist/agent-runtime/run-tool-call.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-errors.d.ts +29 -0
- package/dist/agent-runtime/run-tool-errors.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-executor.d.ts +34 -0
- package/dist/agent-runtime/run-tool-executor.d.ts.map +1 -0
- package/dist/agent-runtime/run-tool-progress.d.ts +2 -2
- package/dist/agent-runtime/run-tool-progress.d.ts.map +1 -1
- package/dist/agent-runtime/run-turn-preparation.d.ts +7 -6
- package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -1
- package/dist/agent-runtime/run-unacquired.d.ts +2 -2
- package/dist/agent-runtime/run-unacquired.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-control.d.ts +4 -4
- package/dist/agent-runtime/runtime-control.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-internals.d.ts +35 -44
- package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-recovery.d.ts +3 -3
- package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-state.d.ts +3 -3
- package/dist/agent-runtime/runtime-state.d.ts.map +1 -1
- package/dist/agent-runtime/runtime-submit.d.ts +2 -2
- package/dist/agent-runtime/runtime-submit.d.ts.map +1 -1
- package/dist/agent-runtime/runtime.d.ts +51 -16
- package/dist/agent-runtime/runtime.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox-process-linux.d.ts +8 -0
- package/dist/agent-runtime/sandbox-process-linux.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-macos.d.ts +21 -0
- package/dist/agent-runtime/sandbox-process-macos.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-spec.d.ts +114 -0
- package/dist/agent-runtime/sandbox-process-spec.d.ts.map +1 -0
- package/dist/agent-runtime/sandbox-process-wrapper.d.ts +19 -0
- package/dist/agent-runtime/sandbox-process-wrapper.d.ts.map +1 -0
- package/dist/agent-runtime/schemas-message.d.ts +10 -0
- package/dist/agent-runtime/schemas-message.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-provider.d.ts +2 -0
- package/dist/agent-runtime/schemas-provider.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-run.d.ts +10 -0
- package/dist/agent-runtime/schemas-run.d.ts.map +1 -1
- package/dist/agent-runtime/schemas-usage-state.d.ts +6 -0
- package/dist/agent-runtime/schemas-usage-state.d.ts.map +1 -0
- package/dist/agent-runtime/schemas-usage.d.ts +8 -0
- package/dist/agent-runtime/schemas-usage.d.ts.map +1 -1
- package/dist/agent-runtime/sql-rows.d.ts +20 -10
- package/dist/agent-runtime/sql-rows.d.ts.map +1 -1
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts +40 -20
- package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +1 -1
- package/dist/agent-runtime/store-conformance-support.d.ts +20 -10
- package/dist/agent-runtime/store-conformance-support.d.ts.map +1 -1
- package/dist/agent-runtime/store-driver-contract.d.ts +70 -0
- package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
- package/dist/agent-runtime/store-events.d.ts +120 -0
- package/dist/agent-runtime/store-events.d.ts.map +1 -1
- package/dist/agent-runtime/store.d.ts +140 -0
- package/dist/agent-runtime/store.d.ts.map +1 -1
- package/dist/agent-runtime/terminal-commit.d.ts +10 -0
- package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
- package/dist/agent-runtime/testing.d.ts +20 -0
- package/dist/agent-runtime/testing.d.ts.map +1 -1
- package/dist/browser/client-call-arguments.d.ts.map +1 -1
- package/dist/browser/client-executors.d.ts.map +1 -1
- package/dist/browser/client-url.d.ts.map +1 -1
- package/dist/browser/client.d.ts +6 -0
- package/dist/browser/client.d.ts.map +1 -1
- package/dist/browser/device-presence-client.d.ts +42 -0
- package/dist/browser/device-presence-client.d.ts.map +1 -0
- package/dist/browser/device-presence-ops.d.ts +47 -0
- package/dist/browser/device-presence-ops.d.ts.map +1 -0
- package/dist/browser/device-presence-relay-adapter.d.ts +37 -0
- package/dist/browser/device-presence-relay-adapter.d.ts.map +1 -0
- package/dist/browser/http-fetch.d.ts +7 -2
- package/dist/browser/http-fetch.d.ts.map +1 -1
- package/dist/browser/http-helpers.d.ts +15 -0
- package/dist/browser/http-helpers.d.ts.map +1 -0
- package/dist/browser/http.d.ts +8 -0
- package/dist/browser/http.d.ts.map +1 -1
- package/dist/contract/client-types.d.ts +8 -0
- package/dist/contract/client-types.d.ts.map +1 -1
- package/dist/contract/runtime-context.d.ts +13 -1
- package/dist/contract/runtime-context.d.ts.map +1 -1
- package/dist/device-relay/agent-handlers.d.ts +45 -0
- package/dist/device-relay/agent-handlers.d.ts.map +1 -0
- package/dist/device-relay/agent.d.ts +80 -0
- package/dist/device-relay/agent.d.ts.map +1 -0
- package/dist/device-relay/broker.d.ts +49 -0
- package/dist/device-relay/broker.d.ts.map +1 -0
- package/dist/device-relay/contract.d.ts +614 -0
- package/dist/device-relay/contract.d.ts.map +1 -0
- package/dist/device-relay/encoding.d.ts +30 -0
- package/dist/device-relay/encoding.d.ts.map +1 -0
- package/dist/device-relay/hub-connection.d.ts +43 -0
- package/dist/device-relay/hub-connection.d.ts.map +1 -0
- package/dist/device-relay/hub-dispatch.d.ts +19 -0
- package/dist/device-relay/hub-dispatch.d.ts.map +1 -0
- package/dist/device-relay/hub-handshake.d.ts +20 -0
- package/dist/device-relay/hub-handshake.d.ts.map +1 -0
- package/dist/device-relay/hub-shared-streams.d.ts +24 -0
- package/dist/device-relay/hub-shared-streams.d.ts.map +1 -0
- package/dist/device-relay/hub-streams.d.ts +57 -0
- package/dist/device-relay/hub-streams.d.ts.map +1 -0
- package/dist/device-relay/hub.d.ts +117 -0
- package/dist/device-relay/hub.d.ts.map +1 -0
- package/dist/entrypoints/agent-executor/acp.d.ts +1 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +224 -47
- package/dist/entrypoints/agent-executor/claude-sdk.js +15 -15
- package/dist/entrypoints/agent-executor/claude.js +13 -15
- package/dist/entrypoints/agent-executor/codex.js +88 -48
- package/dist/entrypoints/agent-executor/testing/claude-sdk.js +5 -5
- package/dist/entrypoints/agent-executor/testing.js +31 -30
- package/dist/entrypoints/agent-executor.d.ts +2 -2
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +23 -17
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +9 -0
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/ai-sdk.js +821 -0
- package/dist/entrypoints/agent-runtime/anthropic.d.ts +4 -0
- package/dist/entrypoints/agent-runtime/anthropic.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/anthropic.js +1260 -0
- package/dist/entrypoints/agent-runtime/browser.d.ts +4 -1
- package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/browser.js +449 -50
- package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
- package/dist/entrypoints/agent-runtime/harness.js +24 -19
- package/dist/entrypoints/agent-runtime/openai.d.ts +4 -0
- package/dist/entrypoints/agent-runtime/openai.d.ts.map +1 -0
- package/dist/entrypoints/agent-runtime/openai.js +1246 -0
- package/dist/entrypoints/agent-runtime/openrouter.d.ts +5 -2
- package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/openrouter.js +2355 -371
- package/dist/entrypoints/agent-runtime/postgres.js +12 -10
- package/dist/entrypoints/agent-runtime/realtime.js +11 -10
- package/dist/entrypoints/agent-runtime/sandbox.d.ts +3 -0
- package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/sandbox.js +530 -7
- package/dist/entrypoints/agent-runtime/sqlite/bun.js +13 -11
- package/dist/entrypoints/agent-runtime/sqlite/node.js +13 -11
- package/dist/entrypoints/agent-runtime/testing.d.ts +1 -1
- package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/testing.js +56 -15
- package/dist/entrypoints/agent-runtime.d.ts +14 -6
- package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime.js +1412 -115
- package/dist/entrypoints/application/diagnostic-journal.js +6 -6
- package/dist/entrypoints/application/directory-inbox.js +6 -6
- package/dist/entrypoints/application/opentelemetry.js +3 -3
- package/dist/entrypoints/application.js +17 -17
- package/dist/entrypoints/cli/publish.js +8 -8
- package/dist/entrypoints/cli.js +14 -15
- package/dist/entrypoints/contract.d.ts +1 -0
- package/dist/entrypoints/contract.d.ts.map +1 -1
- package/dist/entrypoints/contract.js +13 -9
- package/dist/entrypoints/device-relay.d.ts +10 -0
- package/dist/entrypoints/device-relay.d.ts.map +1 -0
- package/dist/entrypoints/device-relay.js +2517 -0
- package/dist/entrypoints/files/packaging.js +3 -3
- package/dist/entrypoints/files.js +11 -11
- package/dist/entrypoints/geo.js +5 -5
- package/dist/entrypoints/google.js +1 -1
- package/dist/entrypoints/handler.js +6 -6
- package/dist/entrypoints/http.js +9 -9
- package/dist/entrypoints/index.js +21 -17
- package/dist/entrypoints/live.js +4 -4
- package/dist/entrypoints/node.js +13 -13
- package/dist/entrypoints/observability.js +9 -9
- package/dist/entrypoints/process/bootstrap.js +1 -1
- package/dist/entrypoints/process.js +5 -5
- package/dist/entrypoints/react.js +4 -4
- package/dist/entrypoints/realtime.d.ts +3 -0
- package/dist/entrypoints/realtime.d.ts.map +1 -1
- package/dist/entrypoints/realtime.js +413 -4
- package/dist/entrypoints/release.js +1 -1
- package/dist/entrypoints/remote.js +10 -10
- package/dist/entrypoints/server.d.ts +1 -0
- package/dist/entrypoints/server.d.ts.map +1 -1
- package/dist/entrypoints/server.js +546 -40
- package/dist/entrypoints/service-host/macos.js +10 -10
- package/dist/entrypoints/service-host/work.js +7 -7
- package/dist/entrypoints/service-host.js +15 -15
- package/dist/entrypoints/spend.js +3 -3
- package/dist/entrypoints/sync.js +4 -4
- package/dist/entrypoints/telegram/screens.js +6 -6
- package/dist/entrypoints/telegram.js +20 -20
- package/dist/entrypoints/testing.js +14 -14
- package/dist/entrypoints/tools/agent.d.ts +2 -1
- package/dist/entrypoints/tools/agent.d.ts.map +1 -1
- package/dist/entrypoints/tools/agent.js +8 -7
- package/dist/entrypoints/tools/connections.js +5 -5
- package/dist/entrypoints/tools/invoker.js +3 -4
- package/dist/entrypoints/tools/mcp.js +8 -9
- package/dist/entrypoints/tools/toolkit.js +32 -13
- package/dist/entrypoints/tools.d.ts +3 -1
- package/dist/entrypoints/tools.d.ts.map +1 -1
- package/dist/entrypoints/tools.js +37 -35
- package/dist/entrypoints/tracking/contract.js +1 -1
- package/dist/entrypoints/tracking/performance.js +4 -4
- package/dist/entrypoints/tracking.js +3 -3
- package/dist/{index-09f7w2qq.js → index-02kdtrcd.js} +1 -1
- package/dist/{index-y53cqwke.js → index-033tyx59.js} +1 -1
- package/dist/{index-9ft4n9j1.js → index-05b65gj4.js} +2 -2
- package/dist/{index-d04w81fz.js → index-0sxj3y45.js} +1 -1
- package/dist/{index-dm6nxkn1.js → index-18pf56dq.js} +4 -6
- package/dist/index-1gmgwfn3.js +439 -0
- package/dist/index-23wn8sgf.js +47 -0
- package/dist/{index-tqjamnax.js → index-27srek2g.js} +15 -13
- package/dist/{index-2nwvn7m2.js → index-29v1p1f4.js} +2 -2
- package/dist/index-36dmtzjr.js +194 -0
- package/dist/{index-ycr4pk0z.js → index-42n9jycn.js} +3 -3
- package/dist/{index-ke02kxsr.js → index-43k180c2.js} +1 -1
- package/dist/{index-pbekeqzm.js → index-5c4m8zdf.js} +2 -2
- package/dist/{index-qggqqja2.js → index-5dxgx3yj.js} +1 -1
- package/dist/{index-x5ayy5bn.js → index-5gdexvke.js} +3 -1
- package/dist/{index-t1a2jrg7.js → index-5xsxvk2x.js} +1 -1
- package/dist/{index-mbd92r1w.js → index-654rhe5d.js} +1 -1
- package/dist/{index-2dzc7mv9.js → index-67pnt4bh.js} +1 -1
- package/dist/index-6kpwkpgx.js +415 -0
- package/dist/{index-s43tr4my.js → index-6kwdfb9m.js} +18 -3
- package/dist/{index-1qwd54n3.js → index-6nzzj7qr.js} +1 -1
- package/dist/{index-rkjfzs0a.js → index-6p5pshcd.js} +2 -2
- package/dist/{index-118aebbg.js → index-6t4c98gr.js} +1 -1
- package/dist/{index-pws5c3x6.js → index-6xw1wf4m.js} +51 -32
- package/dist/{index-kwsr7j5k.js → index-6yb4stq3.js} +1 -1
- package/dist/{index-8jf4bt7v.js → index-76yhxa41.js} +8 -8
- package/dist/{index-7416mhyh.js → index-79vqbjcz.js} +1 -1
- package/dist/{index-13wmzpa6.js → index-7an2fs5h.js} +1 -1
- package/dist/index-7qza24g1.js +14 -0
- package/dist/{index-gtaaxe9d.js → index-8cek82ar.js} +1 -1
- package/dist/index-9f60gnfn.js +393 -0
- package/dist/{index-stpy56r3.js → index-aacwkve4.js} +209 -10
- package/dist/{index-rpyn7geq.js → index-ac3rfec5.js} +2 -2
- package/dist/{index-d2drhb9c.js → index-b0mh2t9x.js} +2 -2
- package/dist/index-b23s6e2c.js +158 -0
- package/dist/{index-an7vcmwf.js → index-bvpevwt6.js} +5 -5
- package/dist/{index-msxf2r8x.js → index-by8w2461.js} +1 -1
- package/dist/{index-8t9dr41h.js → index-c0yym4a0.js} +4 -4
- package/dist/{index-wddcfbng.js → index-c7fj4yw9.js} +1 -1
- package/dist/{index-tf70nm22.js → index-cb4nnvfr.js} +8 -6
- package/dist/{index-205456mf.js → index-d3s070eh.js} +2 -2
- package/dist/{index-apf5g7y9.js → index-dz6tstcp.js} +2 -2
- package/dist/{index-agy5fqgf.js → index-e1y74yra.js} +15 -8
- package/dist/index-edtg4tak.js +55 -0
- package/dist/{index-pq6g1k9t.js → index-ek9w11r0.js} +2 -2
- package/dist/{index-x46y9z26.js → index-epyj7ptp.js} +7 -5
- package/dist/{index-6kmjcm81.js → index-er483f3w.js} +93 -4
- package/dist/{index-827bgv33.js → index-f16b7rze.js} +1 -1
- package/dist/{index-gbhj370g.js → index-fec05c9k.js} +21 -21
- package/dist/{index-9wdrwx3b.js → index-fjac2w5e.js} +20 -22
- package/dist/{index-6918kxbf.js → index-fthw8dwa.js} +1 -0
- package/dist/{index-2mz8hj58.js → index-g04hszcm.js} +1 -1
- package/dist/{index-rw8ze745.js → index-ga6avd48.js} +1 -1
- package/dist/{index-paff5y0r.js → index-grhhsrd5.js} +9 -7
- package/dist/{index-mxt0wfjy.js → index-h20qcyh5.js} +5 -2
- package/dist/index-j3r7r1mh.js +150 -0
- package/dist/{index-vgytj9wp.js → index-jmaw365j.js} +1 -1
- package/dist/{index-t5g5rm9n.js → index-jzdbkanz.js} +5 -3
- package/dist/index-k137ezb6.js +79 -0
- package/dist/{index-tazm4dxf.js → index-kdw0n92g.js} +1 -1
- package/dist/{index-wh70tmpd.js → index-ke6jtxkd.js} +1 -1
- package/dist/index-kgj8j7bv.js +83 -0
- package/dist/{index-9kpxz49v.js → index-kgkevngs.js} +1 -1
- package/dist/{index-hab790s6.js → index-kp1j7cc8.js} +4 -4
- package/dist/{index-jcge9tx3.js → index-krekhmp7.js} +142 -123
- package/dist/{index-3y2tzhr8.js → index-ky79wwgs.js} +4 -4
- package/dist/{index-39rmc00v.js → index-mfe9a266.js} +1 -1
- package/dist/{index-qpzyahe3.js → index-mgr0mdqp.js} +5 -2
- package/dist/{index-n20tybgk.js → index-mh3jdb25.js} +2 -2
- package/dist/{index-g5fgeb6v.js → index-mkmep637.js} +1 -1
- package/dist/{index-02r5sq9p.js → index-mrng24wq.js} +19 -21
- package/dist/index-mx2gya05.js +465 -0
- package/dist/{index-8yt3rwe7.js → index-n2t87ggz.js} +5 -5
- package/dist/index-nfeafbzh.js +7379 -0
- package/dist/{index-j0ef04jw.js → index-nfm15ej7.js} +4 -4
- package/dist/index-pd9e8rz4.js +193 -0
- package/dist/{index-zwgwyvdt.js → index-pdcbjd6a.js} +1 -1
- package/dist/{index-q427q23r.js → index-pjjh91vw.js} +2 -2
- package/dist/{index-gnjgkecx.js → index-q46b16xz.js} +1 -1
- package/dist/{index-9xr44d2g.js → index-qv5v6w9c.js} +330 -106
- package/dist/{index-tmv3ez1h.js → index-qymek778.js} +69 -12
- package/dist/{index-yrr3n391.js → index-ry8m2mhg.js} +2 -2
- package/dist/{index-93n6jwy0.js → index-s0n0nnz5.js} +3 -3
- package/dist/{index-1p8q0yrt.js → index-t5zp1jjj.js} +5 -7
- package/dist/{index-2rf33y2h.js → index-tav72wz5.js} +4 -2
- package/dist/{index-jpecjm30.js → index-tgehj4bp.js} +1 -1
- package/dist/{index-ma26mfnt.js → index-v5hmyef8.js} +1 -1
- package/dist/index-vebzvse6.js +230 -0
- package/dist/index-vv0hxrmy.js +295 -0
- package/dist/index-vxm0ya3f.js +707 -0
- package/dist/{index-t3qcac2a.js → index-w3s79kcb.js} +1 -1
- package/dist/{index-r97ppg0g.js → index-x1r7kxzd.js} +1 -1
- package/dist/{index-kynwa08q.js → index-xrsryvd2.js} +2 -2
- package/dist/{index-3mcbr8sx.js → index-xtxxt87z.js} +1 -1
- package/dist/index-zk839vzf.js +231 -0
- package/dist/{index-9c76vfxf.js → index-zyyerdny.js} +4 -4
- package/dist/internal/base64.d.ts +9 -0
- package/dist/internal/base64.d.ts.map +1 -0
- package/dist/internal/deadline-budget.d.ts +57 -0
- package/dist/internal/deadline-budget.d.ts.map +1 -0
- package/dist/internal/deadline.d.ts.map +1 -1
- package/dist/internal/timers.d.ts +2 -0
- package/dist/internal/timers.d.ts.map +1 -1
- package/dist/realtime/device-presence-contract.d.ts +194 -0
- package/dist/realtime/device-presence-contract.d.ts.map +1 -0
- package/dist/server/context-contribution.d.ts.map +1 -1
- package/dist/server/contract-method.d.ts.map +1 -1
- package/dist/server/device-presence-handlers.d.ts +54 -0
- package/dist/server/device-presence-handlers.d.ts.map +1 -0
- package/dist/server/device-presence-registry.d.ts +35 -0
- package/dist/server/device-presence-registry.d.ts.map +1 -0
- package/dist/server/device-presence.d.ts +45 -0
- package/dist/server/device-presence.d.ts.map +1 -0
- package/dist/server/endpoint-dispatch.d.ts.map +1 -1
- package/dist/server/middleware/cors.d.ts +3 -1
- package/dist/server/middleware/cors.d.ts.map +1 -1
- package/dist/server/types.d.ts +4 -11
- package/dist/server/types.d.ts.map +1 -1
- package/dist/service-host/systemd-render-shared.d.ts.map +1 -1
- package/dist/tools/agent-messages.d.ts +6 -0
- package/dist/tools/agent-messages.d.ts.map +1 -0
- package/dist/tools/agent-tool-error.d.ts +2 -2
- package/dist/tools/agent-tools.d.ts +153 -0
- package/dist/tools/agent-tools.d.ts.map +1 -0
- package/dist/tools/agent.d.ts +6 -56
- package/dist/tools/agent.d.ts.map +1 -1
- package/dist/tools/runtime-tool.d.ts +3 -4
- package/dist/tools/runtime-tool.d.ts.map +1 -1
- package/dist/tools/toolkit.d.ts +3 -1
- package/dist/tools/toolkit.d.ts.map +1 -1
- package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -1
- package/llms/agent-executor-acp.txt +4 -4
- package/llms/agent-executor-codex.txt +1 -1
- package/llms/agent-executor.txt +7 -3
- package/llms/agent-runtime-ai-sdk.txt +26 -0
- package/llms/agent-runtime-anthropic.txt +33 -0
- package/llms/agent-runtime-browser.txt +22 -8
- package/llms/agent-runtime-harness.txt +2 -2
- package/llms/agent-runtime-openai.txt +31 -0
- package/llms/agent-runtime-openrouter.txt +17 -7
- package/llms/agent-runtime-sandbox.txt +53 -1
- package/llms/agent-runtime-testing.txt +4 -2
- package/llms/agent-runtime.2.txt +158 -271
- package/llms/agent-runtime.3.txt +289 -243
- package/llms/agent-runtime.4.txt +273 -216
- package/llms/agent-runtime.5.txt +209 -2
- package/llms/agent-runtime.txt +238 -181
- package/llms/contract.txt +2 -1
- package/llms/device-relay.txt +34 -0
- package/llms/realtime.txt +20 -0
- package/llms/server.2.txt +125 -1
- package/llms/server.3.txt +111 -122
- package/llms/server.4.txt +1 -1
- package/llms/server.5.txt +3 -1
- package/llms/server.txt +31 -1
- package/llms/spend.txt +11 -6
- package/llms/stitchkit.2.txt +21 -43
- package/llms/stitchkit.3.txt +43 -0
- package/llms/stitchkit.txt +93 -84
- package/llms/tools-agent.txt +7 -5
- package/llms/tools-toolkit.txt +1 -1
- package/llms/tools.4.txt +7 -2
- package/llms/{upgrading-0.128.0-0.133.0.txt → upgrading-0.128.0-0.134.0.txt} +173 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +983 -212
- package/llms.txt +21 -17
- package/package.json +18 -7
- package/dist/index-0p0s5hrj.js +0 -249
- package/dist/index-1dn2wjq6.js +0 -135
- package/dist/index-1psbyyhj.js +0 -21
- package/dist/index-34k82crg.js +0 -3961
- package/dist/index-5n3a8hd8.js +0 -102
- package/dist/index-97rp94ff.js +0 -8
- package/dist/index-bn2baakz.js +0 -336
- package/dist/index-eh71zr32.js +0 -14
- package/dist/index-emgrmavr.js +0 -1193
- package/dist/index-fzd477xk.js +0 -135
- package/dist/index-vgzhw2zk.js +0 -304
- package/dist/internal/ai-sdk-typed.d.ts +0 -14
- package/dist/internal/ai-sdk-typed.d.ts.map +0 -1
- package/dist/tools/runtime-call-context.d.ts +0 -15
- package/dist/tools/runtime-call-context.d.ts.map +0 -1
- package/dist/{index-vmbxj75t.js → index-jwtmw39p.js} +0 -0
- package/dist/{index-877e9y8r.js → index-sk03xe0n.js} +3 -3
- package/dist/{index-21cfxc4z.js → index-vh4291qh.js} +3 -3
|
@@ -0,0 +1,2517 @@
|
|
|
1
|
+
import"../index-0k1ba0ss.js";
|
|
2
|
+
import"../index-4s0fep5q.js";
|
|
3
|
+
import {
|
|
4
|
+
createBackoff2
|
|
5
|
+
} from "../index-q46b16xz.js";
|
|
6
|
+
import {
|
|
7
|
+
defineRealtimeContract2
|
|
8
|
+
} from "../index-814xpr6d.js";
|
|
9
|
+
import {
|
|
10
|
+
bytesToBase642,
|
|
11
|
+
base64ToBytes
|
|
12
|
+
} from "../index-edtg4tak.js";
|
|
13
|
+
import {
|
|
14
|
+
bindRealtimeClient2
|
|
15
|
+
} from "../index-033tyx59.js";
|
|
16
|
+
import {
|
|
17
|
+
serializeCanonicalJson
|
|
18
|
+
} from "../index-fmzg39a8.js";
|
|
19
|
+
import {
|
|
20
|
+
utf8ByteLength
|
|
21
|
+
} from "../index-f16b7rze.js";
|
|
22
|
+
import {
|
|
23
|
+
assertPositiveSafeInteger
|
|
24
|
+
} from "../index-gr0kxymw.js";
|
|
25
|
+
import {
|
|
26
|
+
assertTimerMs,
|
|
27
|
+
withSignalDeadline,
|
|
28
|
+
startIdleTimer
|
|
29
|
+
} from "../index-e1y74yra.js";
|
|
30
|
+
import {
|
|
31
|
+
MAX_TIMER_MS
|
|
32
|
+
} from "../index-h20qcyh5.js";
|
|
33
|
+
import {
|
|
34
|
+
abortReason,
|
|
35
|
+
raceAbort
|
|
36
|
+
} from "../index-rptj3qnc.js";
|
|
37
|
+
import {
|
|
38
|
+
abortError
|
|
39
|
+
} from "../index-wz392jyz.js";
|
|
40
|
+
|
|
41
|
+
// src/device-relay/contract.ts
|
|
42
|
+
import { z } from "zod";
|
|
43
|
+
var DEVICE_RELAY_ORIGIN = "http://device-relay.invalid";
|
|
44
|
+
var DEFAULT_DEVICE_RELAY_LEASE_TTL_MS = 30000;
|
|
45
|
+
var DEFAULT_DEVICE_RELAY_HEARTBEAT_INTERVAL_MS = 1e4;
|
|
46
|
+
var DEFAULT_DEVICE_RELAY_RPC_TIMEOUT_MS = 30000;
|
|
47
|
+
var DEFAULT_DEVICE_RELAY_MAX_REQUEST_BYTES = 64 * 1024;
|
|
48
|
+
var DEFAULT_DEVICE_RELAY_MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
49
|
+
var DEFAULT_DEVICE_RELAY_MAX_STREAM_FRAME_BYTES = 64 * 1024;
|
|
50
|
+
var DEFAULT_DEVICE_RELAY_MAX_IN_FLIGHT_RPCS = 64;
|
|
51
|
+
var DEFAULT_DEVICE_RELAY_MAX_CONCURRENT_STREAMS = 32;
|
|
52
|
+
var DEFAULT_DEVICE_RELAY_MAX_BUFFERED_FRAMES = 128;
|
|
53
|
+
var DeviceRelayHeaderEntrySchema = z.tuple([z.string(), z.string()]);
|
|
54
|
+
var DeviceRelayBodyEncodingSchema = z.enum(["utf8", "base64"]);
|
|
55
|
+
var DeviceRelayStatusSchema = z.enum(["online", "offline"]);
|
|
56
|
+
var DeviceRelayOfflineReasonSchema = z.enum([
|
|
57
|
+
"disconnected",
|
|
58
|
+
"lease-expired",
|
|
59
|
+
"replaced",
|
|
60
|
+
"closed"
|
|
61
|
+
]);
|
|
62
|
+
var DeviceRelayDeliveryStateSchema = z.enum(["not-sent", "unknown", "delivered"]);
|
|
63
|
+
var DeviceRelayErrorCodeSchema = z.enum([
|
|
64
|
+
"UNAUTHORIZED",
|
|
65
|
+
"FORBIDDEN",
|
|
66
|
+
"IDENTITY_MISMATCH",
|
|
67
|
+
"OPERATION_NOT_ALLOWED",
|
|
68
|
+
"INVALID_REQUEST",
|
|
69
|
+
"PAYLOAD_TOO_LARGE",
|
|
70
|
+
"DEVICE_OFFLINE",
|
|
71
|
+
"DELIVERY_UNKNOWN",
|
|
72
|
+
"DEVICE_BUSY",
|
|
73
|
+
"STREAM_CAPACITY",
|
|
74
|
+
"STREAM_UNAVAILABLE",
|
|
75
|
+
"STREAM_OVERFLOW",
|
|
76
|
+
"FRAME_UNREPRESENTABLE",
|
|
77
|
+
"TIMEOUT",
|
|
78
|
+
"TRANSPORT_ERROR",
|
|
79
|
+
"BROKER_UNAVAILABLE",
|
|
80
|
+
"CLOSED"
|
|
81
|
+
]);
|
|
82
|
+
var RETRYABLE_ERROR_CODES = new Set([
|
|
83
|
+
"DEVICE_OFFLINE",
|
|
84
|
+
"DEVICE_BUSY",
|
|
85
|
+
"STREAM_CAPACITY",
|
|
86
|
+
"TIMEOUT",
|
|
87
|
+
"TRANSPORT_ERROR",
|
|
88
|
+
"BROKER_UNAVAILABLE"
|
|
89
|
+
]);
|
|
90
|
+
function isDeviceRelayRetryableCode(code) {
|
|
91
|
+
return RETRYABLE_ERROR_CODES.has(code);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
class DeviceRelayError extends Error {
|
|
95
|
+
code;
|
|
96
|
+
retryable;
|
|
97
|
+
delivery;
|
|
98
|
+
deviceId;
|
|
99
|
+
constructor(code, message, options = {}) {
|
|
100
|
+
super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
|
|
101
|
+
this.name = "DeviceRelayError";
|
|
102
|
+
this.code = code;
|
|
103
|
+
this.retryable = options.retryable ?? isDeviceRelayRetryableCode(code);
|
|
104
|
+
this.delivery = options.delivery ?? (code === "DELIVERY_UNKNOWN" ? "unknown" : "not-sent");
|
|
105
|
+
if (options.deviceId !== undefined)
|
|
106
|
+
this.deviceId = options.deviceId;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function isRetryableDeviceRelayError(error) {
|
|
110
|
+
return error instanceof DeviceRelayError && error.retryable;
|
|
111
|
+
}
|
|
112
|
+
var DeviceRelayStateSchema = z.strictObject({
|
|
113
|
+
accountId: z.string().min(1),
|
|
114
|
+
deviceId: z.string().min(1),
|
|
115
|
+
status: DeviceRelayStatusSchema,
|
|
116
|
+
capabilities: z.array(z.string().min(1)),
|
|
117
|
+
instanceId: z.string().min(1),
|
|
118
|
+
connectedAt: z.int().nonnegative(),
|
|
119
|
+
lastHeartbeatAt: z.int().nonnegative(),
|
|
120
|
+
leaseExpiresAt: z.int().nonnegative(),
|
|
121
|
+
offlineReason: DeviceRelayOfflineReasonSchema.optional()
|
|
122
|
+
});
|
|
123
|
+
var DeviceRelayHelloSchema = z.strictObject({
|
|
124
|
+
schemaVersion: z.literal(1),
|
|
125
|
+
deviceId: z.string().min(1).max(128),
|
|
126
|
+
capabilities: z.array(z.string().min(1).max(128)).max(128),
|
|
127
|
+
leaseTtlMs: z.int().positive().max(MAX_TIMER_MS).optional()
|
|
128
|
+
});
|
|
129
|
+
var DeviceRelayHelloAckSchema = z.discriminatedUnion("outcome", [
|
|
130
|
+
z.strictObject({
|
|
131
|
+
schemaVersion: z.literal(1),
|
|
132
|
+
outcome: z.literal("ok"),
|
|
133
|
+
leaseTtlMs: z.int().positive().max(MAX_TIMER_MS),
|
|
134
|
+
leaseExpiresAtMs: z.int().nonnegative(),
|
|
135
|
+
serverTimeMs: z.int().nonnegative(),
|
|
136
|
+
instanceId: z.string().min(1)
|
|
137
|
+
}),
|
|
138
|
+
z.strictObject({
|
|
139
|
+
schemaVersion: z.literal(1),
|
|
140
|
+
outcome: z.literal("error"),
|
|
141
|
+
code: DeviceRelayErrorCodeSchema,
|
|
142
|
+
message: z.string().min(1),
|
|
143
|
+
retryable: z.boolean()
|
|
144
|
+
})
|
|
145
|
+
]);
|
|
146
|
+
var DeviceRelayHeartbeatSchema = z.strictObject({
|
|
147
|
+
schemaVersion: z.literal(1),
|
|
148
|
+
deviceId: z.string().min(1).max(128),
|
|
149
|
+
sentAtMs: z.int().nonnegative()
|
|
150
|
+
});
|
|
151
|
+
var DeviceRelayHeartbeatAckSchema = z.discriminatedUnion("outcome", [
|
|
152
|
+
z.strictObject({
|
|
153
|
+
schemaVersion: z.literal(1),
|
|
154
|
+
outcome: z.literal("ok"),
|
|
155
|
+
leaseExpiresAtMs: z.int().nonnegative(),
|
|
156
|
+
serverTimeMs: z.int().nonnegative()
|
|
157
|
+
}),
|
|
158
|
+
z.strictObject({
|
|
159
|
+
schemaVersion: z.literal(1),
|
|
160
|
+
outcome: z.literal("error"),
|
|
161
|
+
code: DeviceRelayErrorCodeSchema,
|
|
162
|
+
message: z.string().min(1),
|
|
163
|
+
retryable: z.boolean()
|
|
164
|
+
})
|
|
165
|
+
]);
|
|
166
|
+
var DeviceRelayRpcRequestSchema = z.strictObject({
|
|
167
|
+
schemaVersion: z.literal(1),
|
|
168
|
+
requestId: z.string().min(1).max(128),
|
|
169
|
+
method: z.string().min(1).max(32),
|
|
170
|
+
path: z.string().min(1),
|
|
171
|
+
headers: z.array(DeviceRelayHeaderEntrySchema),
|
|
172
|
+
body: z.string().optional(),
|
|
173
|
+
bodyEncoding: DeviceRelayBodyEncodingSchema.optional(),
|
|
174
|
+
maxResponseBodyBytes: z.int().positive().optional()
|
|
175
|
+
});
|
|
176
|
+
var DeviceRelayRpcCancelSchema = z.strictObject({
|
|
177
|
+
schemaVersion: z.literal(1),
|
|
178
|
+
requestId: z.string().min(1).max(128),
|
|
179
|
+
reason: z.string().min(1).max(256).optional()
|
|
180
|
+
});
|
|
181
|
+
var DeviceRelayRpcResponseSchema = z.discriminatedUnion("outcome", [
|
|
182
|
+
z.strictObject({
|
|
183
|
+
schemaVersion: z.literal(1),
|
|
184
|
+
requestId: z.string().min(1).max(128),
|
|
185
|
+
outcome: z.literal("response"),
|
|
186
|
+
status: z.int().min(200).max(599),
|
|
187
|
+
statusText: z.string(),
|
|
188
|
+
headers: z.array(DeviceRelayHeaderEntrySchema),
|
|
189
|
+
body: z.string().optional(),
|
|
190
|
+
bodyEncoding: DeviceRelayBodyEncodingSchema.optional()
|
|
191
|
+
}),
|
|
192
|
+
z.strictObject({
|
|
193
|
+
schemaVersion: z.literal(1),
|
|
194
|
+
requestId: z.string().min(1).max(128),
|
|
195
|
+
outcome: z.literal("error"),
|
|
196
|
+
code: DeviceRelayErrorCodeSchema,
|
|
197
|
+
message: z.string().min(1),
|
|
198
|
+
retryable: z.boolean()
|
|
199
|
+
})
|
|
200
|
+
]);
|
|
201
|
+
var DeviceRelayJsonValueSchema = z.json();
|
|
202
|
+
var DeviceRelayStreamOpenSchema = z.strictObject({
|
|
203
|
+
schemaVersion: z.literal(1),
|
|
204
|
+
streamId: z.string().min(1).max(128),
|
|
205
|
+
topic: z.string().min(1).max(256),
|
|
206
|
+
cursor: z.string().min(1).max(512).optional(),
|
|
207
|
+
params: z.record(z.string(), DeviceRelayJsonValueSchema).optional(),
|
|
208
|
+
initialCredits: z.int().positive(),
|
|
209
|
+
maxFrameBytes: z.int().positive()
|
|
210
|
+
});
|
|
211
|
+
var DeviceRelayStreamOpenAckSchema = z.discriminatedUnion("outcome", [
|
|
212
|
+
z.strictObject({
|
|
213
|
+
schemaVersion: z.literal(1),
|
|
214
|
+
streamId: z.string().min(1).max(128),
|
|
215
|
+
outcome: z.literal("ok")
|
|
216
|
+
}),
|
|
217
|
+
z.strictObject({
|
|
218
|
+
schemaVersion: z.literal(1),
|
|
219
|
+
streamId: z.string().min(1).max(128),
|
|
220
|
+
outcome: z.literal("error"),
|
|
221
|
+
code: DeviceRelayErrorCodeSchema,
|
|
222
|
+
message: z.string().min(1),
|
|
223
|
+
retryable: z.boolean()
|
|
224
|
+
})
|
|
225
|
+
]);
|
|
226
|
+
var DeviceRelayStreamCreditSchema = z.strictObject({
|
|
227
|
+
schemaVersion: z.literal(1),
|
|
228
|
+
streamId: z.string().min(1).max(128),
|
|
229
|
+
credits: z.int().positive()
|
|
230
|
+
});
|
|
231
|
+
var DeviceRelayStreamCloseSchema = z.strictObject({
|
|
232
|
+
schemaVersion: z.literal(1),
|
|
233
|
+
streamId: z.string().min(1).max(128),
|
|
234
|
+
reason: z.string().min(1).max(256).optional()
|
|
235
|
+
});
|
|
236
|
+
var DeviceRelayStreamEventSchema = z.discriminatedUnion("kind", [
|
|
237
|
+
z.strictObject({
|
|
238
|
+
schemaVersion: z.literal(1),
|
|
239
|
+
streamId: z.string().min(1).max(128),
|
|
240
|
+
kind: z.literal("data"),
|
|
241
|
+
cursor: z.string().min(1).max(512).optional(),
|
|
242
|
+
payload: DeviceRelayJsonValueSchema
|
|
243
|
+
}),
|
|
244
|
+
z.strictObject({
|
|
245
|
+
schemaVersion: z.literal(1),
|
|
246
|
+
streamId: z.string().min(1).max(128),
|
|
247
|
+
kind: z.literal("end"),
|
|
248
|
+
cursor: z.string().min(1).max(512).optional(),
|
|
249
|
+
reason: z.string().min(1).max(256).optional()
|
|
250
|
+
}),
|
|
251
|
+
z.strictObject({
|
|
252
|
+
schemaVersion: z.literal(1),
|
|
253
|
+
streamId: z.string().min(1).max(128),
|
|
254
|
+
kind: z.literal("error"),
|
|
255
|
+
code: DeviceRelayErrorCodeSchema,
|
|
256
|
+
message: z.string().min(1),
|
|
257
|
+
retryable: z.boolean()
|
|
258
|
+
})
|
|
259
|
+
]);
|
|
260
|
+
var deviceRelayRealtimeContract = defineRealtimeContract2({
|
|
261
|
+
serverToClient: {
|
|
262
|
+
"stitchkit.relay.rpc-request": { args: z.tuple([DeviceRelayRpcRequestSchema]) },
|
|
263
|
+
"stitchkit.relay.rpc-cancel": { args: z.tuple([DeviceRelayRpcCancelSchema]) },
|
|
264
|
+
"stitchkit.relay.stream-open": { args: z.tuple([DeviceRelayStreamOpenSchema]) },
|
|
265
|
+
"stitchkit.relay.stream-credit": { args: z.tuple([DeviceRelayStreamCreditSchema]) },
|
|
266
|
+
"stitchkit.relay.stream-close": { args: z.tuple([DeviceRelayStreamCloseSchema]) }
|
|
267
|
+
},
|
|
268
|
+
clientToServer: {
|
|
269
|
+
"stitchkit.relay.hello": {
|
|
270
|
+
args: z.tuple([DeviceRelayHelloSchema]),
|
|
271
|
+
ack: DeviceRelayHelloAckSchema
|
|
272
|
+
},
|
|
273
|
+
"stitchkit.relay.heartbeat": {
|
|
274
|
+
args: z.tuple([DeviceRelayHeartbeatSchema]),
|
|
275
|
+
ack: DeviceRelayHeartbeatAckSchema
|
|
276
|
+
},
|
|
277
|
+
"stitchkit.relay.rpc-response": { args: z.tuple([DeviceRelayRpcResponseSchema]) },
|
|
278
|
+
"stitchkit.relay.stream-open-ack": { args: z.tuple([DeviceRelayStreamOpenAckSchema]) },
|
|
279
|
+
"stitchkit.relay.stream-event": { args: z.tuple([DeviceRelayStreamEventSchema]) }
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// src/device-relay/encoding.ts
|
|
284
|
+
var STRIPPED_REQUEST_HEADERS = new Set([
|
|
285
|
+
"host",
|
|
286
|
+
"origin",
|
|
287
|
+
"x-forwarded-for",
|
|
288
|
+
"x-real-ip",
|
|
289
|
+
"forwarded",
|
|
290
|
+
"connection",
|
|
291
|
+
"transfer-encoding"
|
|
292
|
+
]);
|
|
293
|
+
var FORBIDDEN_RELAY_PATH_RE = /\\|\.\.|%2e|%2f|%5c|%00|[\u0000-\u001f\u007f]/i;
|
|
294
|
+
function decodeRelayBase64(encoded) {
|
|
295
|
+
try {
|
|
296
|
+
return base64ToBytes(encoded);
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
throw new DeviceRelayError("INVALID_REQUEST", cause instanceof Error ? cause.message : "Invalid base64 payload", { cause });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function normalizeRelayHeaders(input, stripTrustHeaders) {
|
|
302
|
+
if (!input)
|
|
303
|
+
return [];
|
|
304
|
+
const entries = [];
|
|
305
|
+
const push = (key, value) => {
|
|
306
|
+
if (stripTrustHeaders && STRIPPED_REQUEST_HEADERS.has(key.toLowerCase()))
|
|
307
|
+
return;
|
|
308
|
+
entries.push([key, value]);
|
|
309
|
+
};
|
|
310
|
+
if (input instanceof Headers) {
|
|
311
|
+
input.forEach((value, key) => {
|
|
312
|
+
push(key, value);
|
|
313
|
+
});
|
|
314
|
+
return entries;
|
|
315
|
+
}
|
|
316
|
+
if (Array.isArray(input)) {
|
|
317
|
+
for (const pair of input) {
|
|
318
|
+
if (pair.length === 2)
|
|
319
|
+
push(String(pair[0]), String(pair[1]));
|
|
320
|
+
}
|
|
321
|
+
return entries;
|
|
322
|
+
}
|
|
323
|
+
for (const [key, value] of Object.entries(input)) {
|
|
324
|
+
push(key, value);
|
|
325
|
+
}
|
|
326
|
+
return entries;
|
|
327
|
+
}
|
|
328
|
+
function canonicalizeRelayPath(input, options = {}) {
|
|
329
|
+
const raw = typeof input === "string" ? input : input.toString();
|
|
330
|
+
const allowOrigin = options.allowOrigin ?? false;
|
|
331
|
+
let rawRelative = raw;
|
|
332
|
+
if (allowOrigin) {
|
|
333
|
+
if (raw.toLowerCase().startsWith(DEVICE_RELAY_ORIGIN)) {
|
|
334
|
+
const rest = raw.slice(DEVICE_RELAY_ORIGIN.length);
|
|
335
|
+
if (rest === "" || rest.startsWith("/") || rest.startsWith("?") || rest.startsWith("#")) {
|
|
336
|
+
rawRelative = rest === "" ? "/" : rest;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
} else if (!raw.startsWith("/") || raw.startsWith("//")) {
|
|
340
|
+
throw new DeviceRelayError("INVALID_REQUEST", `Invalid relay path: ${raw}`);
|
|
341
|
+
}
|
|
342
|
+
const rawPathPart = rawRelative.split(/[?#]/, 1)[0] ?? "";
|
|
343
|
+
if (FORBIDDEN_RELAY_PATH_RE.test(rawPathPart)) {
|
|
344
|
+
throw new DeviceRelayError("INVALID_REQUEST", `Forbidden relay path: ${raw}`);
|
|
345
|
+
}
|
|
346
|
+
let parsed;
|
|
347
|
+
try {
|
|
348
|
+
parsed = new URL(raw, DEVICE_RELAY_ORIGIN);
|
|
349
|
+
} catch (cause) {
|
|
350
|
+
throw new DeviceRelayError("INVALID_REQUEST", `Invalid relay path: ${raw}`, { cause });
|
|
351
|
+
}
|
|
352
|
+
if (parsed.origin !== DEVICE_RELAY_ORIGIN || parsed.username !== "" || parsed.password !== "") {
|
|
353
|
+
throw new DeviceRelayError("INVALID_REQUEST", `Relay path must stay on relay origin: ${raw}`);
|
|
354
|
+
}
|
|
355
|
+
if (!parsed.pathname.startsWith("/") || parsed.pathname.startsWith("//") || FORBIDDEN_RELAY_PATH_RE.test(parsed.pathname)) {
|
|
356
|
+
throw new DeviceRelayError("INVALID_REQUEST", `Invalid relay path: ${raw}`);
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
pathname: parsed.pathname,
|
|
360
|
+
search: parsed.search,
|
|
361
|
+
path: `${parsed.pathname}${parsed.search}`
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
function normalizeRelativeRelayPath(input) {
|
|
365
|
+
return canonicalizeRelayPath(input, { allowOrigin: true }).path;
|
|
366
|
+
}
|
|
367
|
+
async function readStreamBytesBounded(stream, maxBytes, label) {
|
|
368
|
+
const reader = stream.getReader();
|
|
369
|
+
const chunks = [];
|
|
370
|
+
let total = 0;
|
|
371
|
+
try {
|
|
372
|
+
for (;; ) {
|
|
373
|
+
const { done, value } = await reader.read();
|
|
374
|
+
if (done)
|
|
375
|
+
break;
|
|
376
|
+
if (!value)
|
|
377
|
+
continue;
|
|
378
|
+
total += value.byteLength;
|
|
379
|
+
if (total > maxBytes) {
|
|
380
|
+
await reader.cancel().catch(() => {
|
|
381
|
+
return;
|
|
382
|
+
});
|
|
383
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `${label} exceeds the ${maxBytes}-byte limit`);
|
|
384
|
+
}
|
|
385
|
+
chunks.push(value);
|
|
386
|
+
}
|
|
387
|
+
} finally {
|
|
388
|
+
reader.releaseLock();
|
|
389
|
+
}
|
|
390
|
+
const merged = new Uint8Array(total);
|
|
391
|
+
let offset = 0;
|
|
392
|
+
for (const chunk of chunks) {
|
|
393
|
+
merged.set(chunk, offset);
|
|
394
|
+
offset += chunk.byteLength;
|
|
395
|
+
}
|
|
396
|
+
return merged;
|
|
397
|
+
}
|
|
398
|
+
async function encodeFetchRequestBody(input, init, method, maxRequestBodyBytes) {
|
|
399
|
+
if (method === "GET" || method === "HEAD")
|
|
400
|
+
return {};
|
|
401
|
+
const rawBody = init?.body;
|
|
402
|
+
if (rawBody === undefined || rawBody === null) {
|
|
403
|
+
if (!(input instanceof Request) || !input.body)
|
|
404
|
+
return {};
|
|
405
|
+
const bytes = await readStreamBytesBounded(input.body, maxRequestBodyBytes, "Relay request body");
|
|
406
|
+
if (bytes.byteLength === 0)
|
|
407
|
+
return {};
|
|
408
|
+
return { body: bytesToBase642(bytes), bodyEncoding: "base64" };
|
|
409
|
+
}
|
|
410
|
+
if (typeof rawBody === "string") {
|
|
411
|
+
if (utf8ByteLength(rawBody) > maxRequestBodyBytes) {
|
|
412
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay request body exceeds the ${maxRequestBodyBytes}-byte limit`);
|
|
413
|
+
}
|
|
414
|
+
return { body: rawBody, bodyEncoding: "utf8" };
|
|
415
|
+
}
|
|
416
|
+
if (rawBody instanceof URLSearchParams) {
|
|
417
|
+
const text = rawBody.toString();
|
|
418
|
+
if (utf8ByteLength(text) > maxRequestBodyBytes) {
|
|
419
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay request body exceeds the ${maxRequestBodyBytes}-byte limit`);
|
|
420
|
+
}
|
|
421
|
+
return { body: text, bodyEncoding: "utf8" };
|
|
422
|
+
}
|
|
423
|
+
if (rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody)) {
|
|
424
|
+
const bytes = rawBody instanceof ArrayBuffer ? new Uint8Array(rawBody) : new Uint8Array(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength);
|
|
425
|
+
if (bytes.byteLength > maxRequestBodyBytes) {
|
|
426
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay request body exceeds the ${maxRequestBodyBytes}-byte limit`);
|
|
427
|
+
}
|
|
428
|
+
return { body: bytesToBase642(bytes), bodyEncoding: "base64" };
|
|
429
|
+
}
|
|
430
|
+
if (rawBody instanceof Blob) {
|
|
431
|
+
if (rawBody.size > maxRequestBodyBytes) {
|
|
432
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay request body exceeds the ${maxRequestBodyBytes}-byte limit`);
|
|
433
|
+
}
|
|
434
|
+
const bytes = new Uint8Array(await rawBody.arrayBuffer());
|
|
435
|
+
return { body: bytesToBase642(bytes), bodyEncoding: "base64" };
|
|
436
|
+
}
|
|
437
|
+
if (rawBody instanceof ReadableStream) {
|
|
438
|
+
const bytes = await readStreamBytesBounded(rawBody, maxRequestBodyBytes, "Relay request body");
|
|
439
|
+
return { body: bytesToBase642(bytes), bodyEncoding: "base64" };
|
|
440
|
+
}
|
|
441
|
+
throw new DeviceRelayError("INVALID_REQUEST", "Unsupported relay request body type");
|
|
442
|
+
}
|
|
443
|
+
function decodedBodyByteLength(body, encoding) {
|
|
444
|
+
if (body === undefined)
|
|
445
|
+
return 0;
|
|
446
|
+
if (encoding === "base64")
|
|
447
|
+
return decodeRelayBase64(body).byteLength;
|
|
448
|
+
return utf8ByteLength(body);
|
|
449
|
+
}
|
|
450
|
+
async function encodeFetchResponse(requestId, response, maxResponseBodyBytes) {
|
|
451
|
+
const nullBody = response.status === 204 || response.status === 205 || response.status === 304;
|
|
452
|
+
let body;
|
|
453
|
+
let bodyEncoding;
|
|
454
|
+
if (!nullBody) {
|
|
455
|
+
const contentLengthHeader = response.headers.get("content-length");
|
|
456
|
+
if (contentLengthHeader !== null) {
|
|
457
|
+
const declared = Number(contentLengthHeader);
|
|
458
|
+
if (Number.isFinite(declared) && declared > maxResponseBodyBytes) {
|
|
459
|
+
response.body?.cancel?.().catch(() => {
|
|
460
|
+
return;
|
|
461
|
+
});
|
|
462
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay response body exceeds the ${maxResponseBodyBytes}-byte limit`);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const bytes = response.body ? await readStreamBytesBounded(response.body, maxResponseBodyBytes, "Relay response body") : new Uint8Array(await response.arrayBuffer());
|
|
466
|
+
if (bytes.byteLength > maxResponseBodyBytes) {
|
|
467
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay response body exceeds the ${maxResponseBodyBytes}-byte limit`);
|
|
468
|
+
}
|
|
469
|
+
if (bytes.byteLength > 0) {
|
|
470
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
471
|
+
const textual = contentType === "" || /^text\//i.test(contentType) || /application\/(?:[\w.+-]+\+)?(?:json|xml|javascript|x-www-form-urlencoded)/i.test(contentType);
|
|
472
|
+
if (textual) {
|
|
473
|
+
try {
|
|
474
|
+
body = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
475
|
+
bodyEncoding = "utf8";
|
|
476
|
+
} catch {
|
|
477
|
+
body = bytesToBase642(bytes);
|
|
478
|
+
bodyEncoding = "base64";
|
|
479
|
+
}
|
|
480
|
+
} else {
|
|
481
|
+
body = bytesToBase642(bytes);
|
|
482
|
+
bodyEncoding = "base64";
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
schemaVersion: 1,
|
|
488
|
+
requestId,
|
|
489
|
+
outcome: "response",
|
|
490
|
+
status: response.status,
|
|
491
|
+
statusText: response.statusText,
|
|
492
|
+
headers: normalizeRelayHeaders(response.headers, false),
|
|
493
|
+
...body !== undefined && { body },
|
|
494
|
+
...bodyEncoding !== undefined && { bodyEncoding }
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function buildFetchRequestFromRelay(request, signal) {
|
|
498
|
+
const canonical = canonicalizeRelayPath(request.path, { allowOrigin: false });
|
|
499
|
+
const headers = new Headers;
|
|
500
|
+
for (const [key, value] of request.headers) {
|
|
501
|
+
if (STRIPPED_REQUEST_HEADERS.has(key.toLowerCase()))
|
|
502
|
+
continue;
|
|
503
|
+
headers.append(key, value);
|
|
504
|
+
}
|
|
505
|
+
const method = request.method.toUpperCase();
|
|
506
|
+
let body;
|
|
507
|
+
if (request.body !== undefined && method !== "GET" && method !== "HEAD") {
|
|
508
|
+
body = request.bodyEncoding === "base64" ? decodeRelayBase64(request.body) : request.body;
|
|
509
|
+
}
|
|
510
|
+
return new Request(`${DEVICE_RELAY_ORIGIN}${canonical.path}`, {
|
|
511
|
+
method,
|
|
512
|
+
headers,
|
|
513
|
+
...body !== undefined && { body },
|
|
514
|
+
signal
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
function buildFetchResponseFromRelay(frame) {
|
|
518
|
+
const headers = new Headers;
|
|
519
|
+
for (const [key, value] of frame.headers) {
|
|
520
|
+
headers.append(key, value);
|
|
521
|
+
}
|
|
522
|
+
const nullBody = frame.status === 204 || frame.status === 205 || frame.status === 304;
|
|
523
|
+
if (nullBody || frame.body === undefined) {
|
|
524
|
+
return new Response(null, { status: frame.status, statusText: frame.statusText, headers });
|
|
525
|
+
}
|
|
526
|
+
const body = frame.bodyEncoding === "base64" ? decodeRelayBase64(frame.body) : frame.body;
|
|
527
|
+
return new Response(body, { status: frame.status, statusText: frame.statusText, headers });
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// src/device-relay/agent-handlers.ts
|
|
531
|
+
function matchesPathPrefix(pathname, pathPrefix) {
|
|
532
|
+
if (!pathPrefix.startsWith("/"))
|
|
533
|
+
return false;
|
|
534
|
+
if (pathPrefix === "/")
|
|
535
|
+
return pathname.startsWith("/");
|
|
536
|
+
if (pathPrefix.endsWith("/"))
|
|
537
|
+
return pathname.startsWith(pathPrefix);
|
|
538
|
+
return pathname === pathPrefix || pathname.startsWith(`${pathPrefix}/`);
|
|
539
|
+
}
|
|
540
|
+
function matchesRpcAllowlist(allowRpc, method, path) {
|
|
541
|
+
if (!allowRpc)
|
|
542
|
+
return false;
|
|
543
|
+
let canonical;
|
|
544
|
+
try {
|
|
545
|
+
canonical = canonicalizeRelayPath(path, { allowOrigin: false });
|
|
546
|
+
} catch {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
if (typeof allowRpc === "function")
|
|
550
|
+
return allowRpc({ method, path: canonical.path });
|
|
551
|
+
const pathname = canonical.pathname;
|
|
552
|
+
for (const rule of allowRpc) {
|
|
553
|
+
if (rule.methods !== undefined && !rule.methods.some((allowed) => allowed.toUpperCase() === method.toUpperCase())) {
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (rule.exactPath !== undefined && pathname !== rule.exactPath)
|
|
557
|
+
continue;
|
|
558
|
+
if (rule.pathPrefix !== undefined && !matchesPathPrefix(pathname, rule.pathPrefix))
|
|
559
|
+
continue;
|
|
560
|
+
if (rule.exactPath === undefined && rule.pathPrefix === undefined && rule.methods === undefined) {
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
function matchesTopicAllowlist(allowTopics, topic) {
|
|
568
|
+
if (!allowTopics)
|
|
569
|
+
return false;
|
|
570
|
+
if (typeof allowTopics === "function")
|
|
571
|
+
return allowTopics(topic);
|
|
572
|
+
return allowTopics.includes(topic);
|
|
573
|
+
}
|
|
574
|
+
async function handleAgentRpcRequest(input) {
|
|
575
|
+
const { config, client, limits, inFlightRpcs, isClosed, request } = input;
|
|
576
|
+
const sendError = (code, message, retryable) => {
|
|
577
|
+
client.emit("stitchkit.relay.rpc-response", {
|
|
578
|
+
schemaVersion: 1,
|
|
579
|
+
requestId: request.requestId,
|
|
580
|
+
outcome: "error",
|
|
581
|
+
code,
|
|
582
|
+
message,
|
|
583
|
+
retryable: retryable ?? new DeviceRelayError(code, message).retryable
|
|
584
|
+
});
|
|
585
|
+
};
|
|
586
|
+
let canonicalPath;
|
|
587
|
+
try {
|
|
588
|
+
canonicalPath = canonicalizeRelayPath(request.path, { allowOrigin: false }).path;
|
|
589
|
+
} catch (error) {
|
|
590
|
+
if (error instanceof DeviceRelayError) {
|
|
591
|
+
sendError(error.code, error.message, error.retryable);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
sendError("INVALID_REQUEST", "Invalid relay request path", false);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (!matchesRpcAllowlist(config.allowRpc, request.method, canonicalPath)) {
|
|
598
|
+
sendError("OPERATION_NOT_ALLOWED", `RPC "${request.method} ${canonicalPath}" is not allowed by local device policy`, false);
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (!config.fetch) {
|
|
602
|
+
sendError("OPERATION_NOT_ALLOWED", "Local device agent has no RPC handler configured", false);
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
let bodyByteLength;
|
|
606
|
+
try {
|
|
607
|
+
bodyByteLength = decodedBodyByteLength(request.body, request.bodyEncoding);
|
|
608
|
+
} catch (error) {
|
|
609
|
+
if (error instanceof DeviceRelayError) {
|
|
610
|
+
sendError(error.code, error.message, error.retryable);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
sendError("INVALID_REQUEST", "Invalid relay request body encoding", false);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
if (bodyByteLength > limits.maxRequestBodyBytes) {
|
|
617
|
+
sendError("PAYLOAD_TOO_LARGE", `Request body exceeds device limit of ${limits.maxRequestBodyBytes} bytes`, false);
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
if (inFlightRpcs.has(request.requestId)) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (inFlightRpcs.size >= limits.maxInFlightRequests) {
|
|
624
|
+
sendError("DEVICE_BUSY", "Local device in-flight request limit reached", true);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const canonicalRequest = { ...request, path: canonicalPath };
|
|
628
|
+
const controller = new AbortController;
|
|
629
|
+
inFlightRpcs.set(request.requestId, controller);
|
|
630
|
+
try {
|
|
631
|
+
const fetchRequest = buildFetchRequestFromRelay(canonicalRequest, controller.signal);
|
|
632
|
+
const response = await config.fetch(fetchRequest, { signal: controller.signal });
|
|
633
|
+
if (controller.signal.aborted || isClosed())
|
|
634
|
+
return;
|
|
635
|
+
const limit = Math.min(limits.maxResponseBodyBytes, request.maxResponseBodyBytes ?? limits.maxResponseBodyBytes);
|
|
636
|
+
const encoded = await encodeFetchResponse(request.requestId, response, limit);
|
|
637
|
+
if (controller.signal.aborted || isClosed())
|
|
638
|
+
return;
|
|
639
|
+
client.emit("stitchkit.relay.rpc-response", encoded);
|
|
640
|
+
} catch (error) {
|
|
641
|
+
if (controller.signal.aborted || isClosed())
|
|
642
|
+
return;
|
|
643
|
+
if (error instanceof DeviceRelayError) {
|
|
644
|
+
sendError(error.code, error.message, error.retryable);
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
sendError("TRANSPORT_ERROR", error instanceof Error ? error.message : "Local RPC execution failed", false);
|
|
648
|
+
} finally {
|
|
649
|
+
if (inFlightRpcs.get(request.requestId) === controller) {
|
|
650
|
+
inFlightRpcs.delete(request.requestId);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function handleAgentStreamOpen(input) {
|
|
655
|
+
const { config, client, limits, activeStreams, isClosed, request } = input;
|
|
656
|
+
if (activeStreams.has(request.streamId)) {
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
const refuse = (code, message, retryable) => {
|
|
660
|
+
client.emit("stitchkit.relay.stream-open-ack", {
|
|
661
|
+
schemaVersion: 1,
|
|
662
|
+
streamId: request.streamId,
|
|
663
|
+
outcome: "error",
|
|
664
|
+
code,
|
|
665
|
+
message,
|
|
666
|
+
retryable
|
|
667
|
+
});
|
|
668
|
+
};
|
|
669
|
+
if (!matchesTopicAllowlist(config.allowStreamTopics, request.topic)) {
|
|
670
|
+
refuse("OPERATION_NOT_ALLOWED", `Stream topic "${request.topic}" is not allowed by local device policy`, false);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
if (!config.openStream) {
|
|
674
|
+
refuse("STREAM_UNAVAILABLE", "Local device agent has no stream handler configured", false);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (activeStreams.size >= limits.maxConcurrentStreams) {
|
|
678
|
+
refuse("STREAM_CAPACITY", "Local device stream capacity reached", true);
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const streamState = {
|
|
682
|
+
controller: new AbortController,
|
|
683
|
+
credits: request.initialCredits,
|
|
684
|
+
closed: false
|
|
685
|
+
};
|
|
686
|
+
activeStreams.set(request.streamId, streamState);
|
|
687
|
+
pumpAgentStream({
|
|
688
|
+
config,
|
|
689
|
+
client,
|
|
690
|
+
maxStreamFrameBytes: limits.maxStreamFrameBytes,
|
|
691
|
+
activeStreams,
|
|
692
|
+
isClosed,
|
|
693
|
+
request,
|
|
694
|
+
streamState
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
async function pumpAgentStream(input) {
|
|
698
|
+
const {
|
|
699
|
+
config,
|
|
700
|
+
client,
|
|
701
|
+
maxStreamFrameBytes,
|
|
702
|
+
activeStreams,
|
|
703
|
+
isClosed,
|
|
704
|
+
request,
|
|
705
|
+
streamState
|
|
706
|
+
} = input;
|
|
707
|
+
const frameLimit = Math.min(maxStreamFrameBytes, request.maxFrameBytes);
|
|
708
|
+
let iterator;
|
|
709
|
+
let openAckSent = false;
|
|
710
|
+
try {
|
|
711
|
+
const iterable = await config.openStream?.({
|
|
712
|
+
topic: request.topic,
|
|
713
|
+
...request.cursor !== undefined && { cursor: request.cursor },
|
|
714
|
+
...request.params !== undefined && { params: request.params },
|
|
715
|
+
signal: streamState.controller.signal
|
|
716
|
+
});
|
|
717
|
+
if (!iterable) {
|
|
718
|
+
client.emit("stitchkit.relay.stream-open-ack", {
|
|
719
|
+
schemaVersion: 1,
|
|
720
|
+
streamId: request.streamId,
|
|
721
|
+
outcome: "error",
|
|
722
|
+
code: "STREAM_UNAVAILABLE",
|
|
723
|
+
message: "Local stream handler is unavailable",
|
|
724
|
+
retryable: false
|
|
725
|
+
});
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (streamState.closed || isClosed())
|
|
729
|
+
return;
|
|
730
|
+
iterator = iterable[Symbol.asyncIterator]();
|
|
731
|
+
client.emit("stitchkit.relay.stream-open-ack", {
|
|
732
|
+
schemaVersion: 1,
|
|
733
|
+
streamId: request.streamId,
|
|
734
|
+
outcome: "ok"
|
|
735
|
+
});
|
|
736
|
+
openAckSent = true;
|
|
737
|
+
while (!streamState.closed && !isClosed()) {
|
|
738
|
+
while (streamState.credits <= 0 && !streamState.closed && !isClosed()) {
|
|
739
|
+
await new Promise((resolve) => {
|
|
740
|
+
streamState.wakeCredit = resolve;
|
|
741
|
+
});
|
|
742
|
+
streamState.wakeCredit = undefined;
|
|
743
|
+
}
|
|
744
|
+
if (streamState.closed || isClosed())
|
|
745
|
+
break;
|
|
746
|
+
const step = await iterator.next();
|
|
747
|
+
if (streamState.closed || isClosed())
|
|
748
|
+
break;
|
|
749
|
+
if (step.done) {
|
|
750
|
+
client.emit("stitchkit.relay.stream-event", {
|
|
751
|
+
schemaVersion: 1,
|
|
752
|
+
streamId: request.streamId,
|
|
753
|
+
kind: "end"
|
|
754
|
+
});
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
const payload = step.value.payload;
|
|
758
|
+
if (utf8ByteLength(JSON.stringify(payload)) > frameLimit) {
|
|
759
|
+
client.emit("stitchkit.relay.stream-event", {
|
|
760
|
+
schemaVersion: 1,
|
|
761
|
+
streamId: request.streamId,
|
|
762
|
+
kind: "error",
|
|
763
|
+
code: "FRAME_UNREPRESENTABLE",
|
|
764
|
+
message: `Stream frame exceeded ${frameLimit} bytes`,
|
|
765
|
+
retryable: false
|
|
766
|
+
});
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
streamState.credits -= 1;
|
|
770
|
+
client.emit("stitchkit.relay.stream-event", {
|
|
771
|
+
schemaVersion: 1,
|
|
772
|
+
streamId: request.streamId,
|
|
773
|
+
kind: "data",
|
|
774
|
+
...step.value.cursor !== undefined && { cursor: step.value.cursor },
|
|
775
|
+
payload
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
} catch (error) {
|
|
779
|
+
if (streamState.closed || streamState.controller.signal.aborted || isClosed())
|
|
780
|
+
return;
|
|
781
|
+
const relayError = error instanceof DeviceRelayError ? error : new DeviceRelayError("STREAM_UNAVAILABLE", error instanceof Error ? error.message : "Upstream stream failed", { retryable: false, deviceId: config.deviceId, cause: error });
|
|
782
|
+
if (!openAckSent) {
|
|
783
|
+
client.emit("stitchkit.relay.stream-open-ack", {
|
|
784
|
+
schemaVersion: 1,
|
|
785
|
+
streamId: request.streamId,
|
|
786
|
+
outcome: "error",
|
|
787
|
+
code: relayError.code,
|
|
788
|
+
message: relayError.message,
|
|
789
|
+
retryable: relayError.retryable
|
|
790
|
+
});
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
client.emit("stitchkit.relay.stream-event", {
|
|
794
|
+
schemaVersion: 1,
|
|
795
|
+
streamId: request.streamId,
|
|
796
|
+
kind: "error",
|
|
797
|
+
code: relayError.code,
|
|
798
|
+
message: relayError.message,
|
|
799
|
+
retryable: relayError.retryable
|
|
800
|
+
});
|
|
801
|
+
} finally {
|
|
802
|
+
if (activeStreams.get(request.streamId) === streamState) {
|
|
803
|
+
activeStreams.delete(request.streamId);
|
|
804
|
+
}
|
|
805
|
+
streamState.closed = true;
|
|
806
|
+
await iterator?.return?.().catch(() => {
|
|
807
|
+
return;
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// src/device-relay/agent.ts
|
|
813
|
+
function validateAgentConfig(config) {
|
|
814
|
+
if (!config.deviceId.trim()) {
|
|
815
|
+
throw new TypeError("DeviceRelayAgentConfig.deviceId cannot be empty");
|
|
816
|
+
}
|
|
817
|
+
const leaseTtlMs = config.leaseTtlMs ?? DEFAULT_DEVICE_RELAY_LEASE_TTL_MS;
|
|
818
|
+
const heartbeatIntervalMs = config.heartbeatIntervalMs ?? Math.min(DEFAULT_DEVICE_RELAY_HEARTBEAT_INTERVAL_MS, Math.max(10, Math.floor(leaseTtlMs / 3)));
|
|
819
|
+
const helloTimeoutMs = config.helloTimeoutMs ?? 1e4;
|
|
820
|
+
const heartbeatTimeoutMs = config.heartbeatTimeoutMs ?? 5000;
|
|
821
|
+
const limits = {
|
|
822
|
+
maxRequestBodyBytes: config.maxRequestBodyBytes ?? DEFAULT_DEVICE_RELAY_MAX_REQUEST_BYTES,
|
|
823
|
+
maxResponseBodyBytes: config.maxResponseBodyBytes ?? DEFAULT_DEVICE_RELAY_MAX_RESPONSE_BYTES,
|
|
824
|
+
maxInFlightRequests: config.maxInFlightRequests ?? DEFAULT_DEVICE_RELAY_MAX_IN_FLIGHT_RPCS,
|
|
825
|
+
maxConcurrentStreams: config.maxConcurrentStreams ?? DEFAULT_DEVICE_RELAY_MAX_CONCURRENT_STREAMS,
|
|
826
|
+
maxStreamFrameBytes: config.maxStreamFrameBytes ?? DEFAULT_DEVICE_RELAY_MAX_STREAM_FRAME_BYTES
|
|
827
|
+
};
|
|
828
|
+
assertTimerMs("DeviceRelayAgentConfig.leaseTtlMs", leaseTtlMs);
|
|
829
|
+
assertTimerMs("DeviceRelayAgentConfig.heartbeatIntervalMs", heartbeatIntervalMs);
|
|
830
|
+
assertTimerMs("DeviceRelayAgentConfig.helloTimeoutMs", helloTimeoutMs);
|
|
831
|
+
assertTimerMs("DeviceRelayAgentConfig.heartbeatTimeoutMs", heartbeatTimeoutMs);
|
|
832
|
+
if (heartbeatIntervalMs >= leaseTtlMs) {
|
|
833
|
+
throw new RangeError("DeviceRelayAgentConfig.heartbeatIntervalMs must be less than leaseTtlMs");
|
|
834
|
+
}
|
|
835
|
+
assertPositiveSafeInteger("DeviceRelayAgentConfig.maxRequestBodyBytes", limits.maxRequestBodyBytes);
|
|
836
|
+
assertPositiveSafeInteger("DeviceRelayAgentConfig.maxResponseBodyBytes", limits.maxResponseBodyBytes);
|
|
837
|
+
assertPositiveSafeInteger("DeviceRelayAgentConfig.maxInFlightRequests", limits.maxInFlightRequests);
|
|
838
|
+
assertPositiveSafeInteger("DeviceRelayAgentConfig.maxConcurrentStreams", limits.maxConcurrentStreams);
|
|
839
|
+
assertPositiveSafeInteger("DeviceRelayAgentConfig.maxStreamFrameBytes", limits.maxStreamFrameBytes);
|
|
840
|
+
return { leaseTtlMs, heartbeatIntervalMs, helloTimeoutMs, heartbeatTimeoutMs, limits };
|
|
841
|
+
}
|
|
842
|
+
var HELLO_RETRY_BACKOFF = {
|
|
843
|
+
minDelayMs: 50,
|
|
844
|
+
maxDelayMs: 5000,
|
|
845
|
+
jitter: 0.2
|
|
846
|
+
};
|
|
847
|
+
function createAgentLifecycle(input) {
|
|
848
|
+
const { config, validated, client, now, abortAllWork } = input;
|
|
849
|
+
const helloBackoff = createBackoff2(HELLO_RETRY_BACKOFF);
|
|
850
|
+
let heartbeatTimer;
|
|
851
|
+
let helloRetryTimer;
|
|
852
|
+
let generation = 0;
|
|
853
|
+
let closed = false;
|
|
854
|
+
let permanentlyRefused = false;
|
|
855
|
+
let state = { status: "idle", deviceId: config.deviceId };
|
|
856
|
+
const setState = (next) => {
|
|
857
|
+
state = next;
|
|
858
|
+
config.onStateChange?.(next);
|
|
859
|
+
};
|
|
860
|
+
const stopHeartbeat = () => {
|
|
861
|
+
if (heartbeatTimer !== undefined) {
|
|
862
|
+
clearInterval(heartbeatTimer);
|
|
863
|
+
heartbeatTimer = undefined;
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
const stopHelloRetry = () => {
|
|
867
|
+
if (helloRetryTimer !== undefined) {
|
|
868
|
+
helloRetryTimer.stop();
|
|
869
|
+
helloRetryTimer = undefined;
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
const scheduleHelloRetry = (epoch) => {
|
|
873
|
+
stopHelloRetry();
|
|
874
|
+
if (closed || permanentlyRefused || epoch !== generation || !client.connected)
|
|
875
|
+
return;
|
|
876
|
+
helloRetryTimer = startIdleTimer(helloBackoff.next(), () => {
|
|
877
|
+
helloRetryTimer = undefined;
|
|
878
|
+
if (closed || permanentlyRefused || epoch !== generation || !client.connected)
|
|
879
|
+
return;
|
|
880
|
+
register(epoch);
|
|
881
|
+
}, { unref: true });
|
|
882
|
+
};
|
|
883
|
+
const startHeartbeat = (epoch, effectiveLeaseMs) => {
|
|
884
|
+
stopHeartbeat();
|
|
885
|
+
const intervalMs = Math.min(validated.heartbeatIntervalMs, Math.max(10, Math.floor(effectiveLeaseMs / 2)));
|
|
886
|
+
heartbeatTimer = setInterval(() => {
|
|
887
|
+
if (closed || permanentlyRefused || epoch !== generation || !client.connected)
|
|
888
|
+
return;
|
|
889
|
+
client.request("stitchkit.relay.heartbeat", { schemaVersion: 1, deviceId: config.deviceId, sentAtMs: now() }, { timeoutMs: validated.heartbeatTimeoutMs }).then((ack) => {
|
|
890
|
+
if (closed || epoch !== generation)
|
|
891
|
+
return;
|
|
892
|
+
if (ack.outcome === "ok") {
|
|
893
|
+
setState({
|
|
894
|
+
status: "online",
|
|
895
|
+
deviceId: config.deviceId,
|
|
896
|
+
leaseExpiresAt: ack.leaseExpiresAtMs
|
|
897
|
+
});
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
const err = new DeviceRelayError(ack.code, ack.message, {
|
|
901
|
+
retryable: ack.retryable,
|
|
902
|
+
deviceId: config.deviceId
|
|
903
|
+
});
|
|
904
|
+
config.onError?.(err);
|
|
905
|
+
stopHeartbeat();
|
|
906
|
+
abortAllWork(ack.message);
|
|
907
|
+
if (!ack.retryable) {
|
|
908
|
+
permanentlyRefused = true;
|
|
909
|
+
setState({ status: "refused", deviceId: config.deviceId, lastError: err });
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
setState({ status: "disconnected", deviceId: config.deviceId, lastError: err });
|
|
913
|
+
scheduleHelloRetry(epoch);
|
|
914
|
+
}).catch((cause) => {
|
|
915
|
+
if (closed || epoch !== generation)
|
|
916
|
+
return;
|
|
917
|
+
config.onError?.(new DeviceRelayError("TRANSPORT_ERROR", "Relay heartbeat failed", {
|
|
918
|
+
retryable: true,
|
|
919
|
+
deviceId: config.deviceId,
|
|
920
|
+
cause
|
|
921
|
+
}));
|
|
922
|
+
});
|
|
923
|
+
}, intervalMs);
|
|
924
|
+
heartbeatTimer.unref?.();
|
|
925
|
+
};
|
|
926
|
+
const register = async (epoch) => {
|
|
927
|
+
stopHelloRetry();
|
|
928
|
+
if (closed || permanentlyRefused || epoch !== generation || !client.connected)
|
|
929
|
+
return;
|
|
930
|
+
setState({ status: "registering", deviceId: config.deviceId });
|
|
931
|
+
try {
|
|
932
|
+
const ack = await client.request("stitchkit.relay.hello", {
|
|
933
|
+
schemaVersion: 1,
|
|
934
|
+
deviceId: config.deviceId,
|
|
935
|
+
capabilities: [...config.capabilities],
|
|
936
|
+
leaseTtlMs: validated.leaseTtlMs
|
|
937
|
+
}, { timeoutMs: validated.helloTimeoutMs });
|
|
938
|
+
if (closed || epoch !== generation)
|
|
939
|
+
return;
|
|
940
|
+
if (ack.outcome === "error") {
|
|
941
|
+
const err = new DeviceRelayError(ack.code, ack.message, {
|
|
942
|
+
retryable: ack.retryable,
|
|
943
|
+
deviceId: config.deviceId
|
|
944
|
+
});
|
|
945
|
+
config.onError?.(err);
|
|
946
|
+
if (!ack.retryable) {
|
|
947
|
+
permanentlyRefused = true;
|
|
948
|
+
stopHeartbeat();
|
|
949
|
+
stopHelloRetry();
|
|
950
|
+
setState({ status: "refused", deviceId: config.deviceId, lastError: err });
|
|
951
|
+
} else {
|
|
952
|
+
setState({ status: "disconnected", deviceId: config.deviceId, lastError: err });
|
|
953
|
+
scheduleHelloRetry(epoch);
|
|
954
|
+
}
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
helloBackoff.reset();
|
|
958
|
+
stopHelloRetry();
|
|
959
|
+
setState({
|
|
960
|
+
status: "online",
|
|
961
|
+
deviceId: config.deviceId,
|
|
962
|
+
leaseExpiresAt: ack.leaseExpiresAtMs
|
|
963
|
+
});
|
|
964
|
+
startHeartbeat(epoch, ack.leaseTtlMs);
|
|
965
|
+
} catch (cause) {
|
|
966
|
+
if (closed || epoch !== generation)
|
|
967
|
+
return;
|
|
968
|
+
const err = new DeviceRelayError("TRANSPORT_ERROR", "Relay hello failed", {
|
|
969
|
+
retryable: true,
|
|
970
|
+
deviceId: config.deviceId,
|
|
971
|
+
cause
|
|
972
|
+
});
|
|
973
|
+
config.onError?.(err);
|
|
974
|
+
setState({ status: "disconnected", deviceId: config.deviceId, lastError: err });
|
|
975
|
+
scheduleHelloRetry(epoch);
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
return {
|
|
979
|
+
getState: () => state,
|
|
980
|
+
isClosed: () => closed,
|
|
981
|
+
onConnection(connected) {
|
|
982
|
+
if (closed || permanentlyRefused)
|
|
983
|
+
return;
|
|
984
|
+
generation += 1;
|
|
985
|
+
const epoch = generation;
|
|
986
|
+
stopHelloRetry();
|
|
987
|
+
helloBackoff.reset();
|
|
988
|
+
if (!connected) {
|
|
989
|
+
stopHeartbeat();
|
|
990
|
+
abortAllWork("Transport disconnected");
|
|
991
|
+
setState({ status: "disconnected", deviceId: config.deviceId });
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
register(epoch);
|
|
995
|
+
},
|
|
996
|
+
close() {
|
|
997
|
+
if (closed)
|
|
998
|
+
return;
|
|
999
|
+
closed = true;
|
|
1000
|
+
generation += 1;
|
|
1001
|
+
stopHeartbeat();
|
|
1002
|
+
stopHelloRetry();
|
|
1003
|
+
abortAllWork("Agent closed");
|
|
1004
|
+
setState({ status: "closed", deviceId: config.deviceId });
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
function createDeviceRelayAgent(config) {
|
|
1009
|
+
const validated = validateAgentConfig(config);
|
|
1010
|
+
const client = bindRealtimeClient2(deviceRelayRealtimeContract, config.transport);
|
|
1011
|
+
const now = config.now ?? (() => Date.now());
|
|
1012
|
+
const inFlightRpcs = new Map;
|
|
1013
|
+
const activeStreams = new Map;
|
|
1014
|
+
const abortAllWork = (reason) => {
|
|
1015
|
+
for (const controller of inFlightRpcs.values())
|
|
1016
|
+
controller.abort(abortError(reason));
|
|
1017
|
+
inFlightRpcs.clear();
|
|
1018
|
+
for (const stream of activeStreams.values()) {
|
|
1019
|
+
stream.closed = true;
|
|
1020
|
+
stream.controller.abort(abortError(reason));
|
|
1021
|
+
stream.wakeCredit?.();
|
|
1022
|
+
}
|
|
1023
|
+
activeStreams.clear();
|
|
1024
|
+
};
|
|
1025
|
+
const lifecycle = createAgentLifecycle({ config, validated, client, now, abortAllWork });
|
|
1026
|
+
const offRpc = client.on("stitchkit.relay.rpc-request", (request) => {
|
|
1027
|
+
handleAgentRpcRequest({
|
|
1028
|
+
config,
|
|
1029
|
+
client,
|
|
1030
|
+
limits: validated.limits,
|
|
1031
|
+
inFlightRpcs,
|
|
1032
|
+
isClosed: lifecycle.isClosed,
|
|
1033
|
+
request
|
|
1034
|
+
});
|
|
1035
|
+
});
|
|
1036
|
+
const offCancel = client.on("stitchkit.relay.rpc-cancel", (cancel) => {
|
|
1037
|
+
inFlightRpcs.get(cancel.requestId)?.abort(abortError(cancel.reason ?? "Cancelled by hub"));
|
|
1038
|
+
});
|
|
1039
|
+
const offStreamOpen = client.on("stitchkit.relay.stream-open", (request) => {
|
|
1040
|
+
handleAgentStreamOpen({
|
|
1041
|
+
config,
|
|
1042
|
+
client,
|
|
1043
|
+
limits: validated.limits,
|
|
1044
|
+
activeStreams,
|
|
1045
|
+
isClosed: lifecycle.isClosed,
|
|
1046
|
+
request
|
|
1047
|
+
});
|
|
1048
|
+
});
|
|
1049
|
+
const offStreamCredit = client.on("stitchkit.relay.stream-credit", (credit) => {
|
|
1050
|
+
const entry = activeStreams.get(credit.streamId);
|
|
1051
|
+
if (!entry || entry.closed)
|
|
1052
|
+
return;
|
|
1053
|
+
entry.credits += credit.credits;
|
|
1054
|
+
entry.wakeCredit?.();
|
|
1055
|
+
});
|
|
1056
|
+
const offStreamClose = client.on("stitchkit.relay.stream-close", (closeFrame) => {
|
|
1057
|
+
const entry = activeStreams.get(closeFrame.streamId);
|
|
1058
|
+
if (!entry)
|
|
1059
|
+
return;
|
|
1060
|
+
entry.closed = true;
|
|
1061
|
+
entry.controller.abort(abortError(closeFrame.reason ?? "Closed by hub"));
|
|
1062
|
+
entry.wakeCredit?.();
|
|
1063
|
+
});
|
|
1064
|
+
const offConnection = client.onConnectionChange((connected) => lifecycle.onConnection(connected));
|
|
1065
|
+
if (client.connected)
|
|
1066
|
+
lifecycle.onConnection(true);
|
|
1067
|
+
return {
|
|
1068
|
+
getState: lifecycle.getState,
|
|
1069
|
+
close() {
|
|
1070
|
+
offRpc();
|
|
1071
|
+
offCancel();
|
|
1072
|
+
offStreamOpen();
|
|
1073
|
+
offStreamCredit();
|
|
1074
|
+
offStreamClose();
|
|
1075
|
+
offConnection();
|
|
1076
|
+
lifecycle.close();
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
// src/device-relay/broker.ts
|
|
1081
|
+
var DEFAULT_MAX_OFFLINE_DEVICES = 1024;
|
|
1082
|
+
var DEFAULT_OFFLINE_DEVICE_TTL_MS = 5 * 60000;
|
|
1083
|
+
function createMemoryRelayBroker(options) {
|
|
1084
|
+
const maxOfflineDevices = options?.maxOfflineDevices ?? DEFAULT_MAX_OFFLINE_DEVICES;
|
|
1085
|
+
const offlineTtlMs = options?.offlineTtlMs ?? DEFAULT_OFFLINE_DEVICE_TTL_MS;
|
|
1086
|
+
const now = options?.now ?? (() => Date.now());
|
|
1087
|
+
assertPositiveSafeInteger("MemoryRelayBroker.maxOfflineDevices", maxOfflineDevices);
|
|
1088
|
+
assertTimerMs("MemoryRelayBroker.offlineTtlMs", offlineTtlMs);
|
|
1089
|
+
const devices = new Map;
|
|
1090
|
+
const offlineAt = new Map;
|
|
1091
|
+
const instances = new Map;
|
|
1092
|
+
const evictOffline = () => {
|
|
1093
|
+
const cutoff = now() - offlineTtlMs;
|
|
1094
|
+
for (const [deviceId, markedAt] of offlineAt) {
|
|
1095
|
+
if (markedAt > cutoff)
|
|
1096
|
+
break;
|
|
1097
|
+
offlineAt.delete(deviceId);
|
|
1098
|
+
if (devices.get(deviceId)?.status === "offline") {
|
|
1099
|
+
devices.delete(deviceId);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
while (offlineAt.size > maxOfflineDevices) {
|
|
1103
|
+
const oldest = offlineAt.keys().next().value;
|
|
1104
|
+
if (oldest === undefined)
|
|
1105
|
+
break;
|
|
1106
|
+
offlineAt.delete(oldest);
|
|
1107
|
+
if (devices.get(oldest)?.status === "offline") {
|
|
1108
|
+
devices.delete(oldest);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
return {
|
|
1113
|
+
registerDevice(record) {
|
|
1114
|
+
offlineAt.delete(record.deviceId);
|
|
1115
|
+
devices.set(record.deviceId, { ...record, capabilities: [...record.capabilities] });
|
|
1116
|
+
evictOffline();
|
|
1117
|
+
},
|
|
1118
|
+
refreshDeviceLease({ deviceId, instanceId, lastHeartbeatAt, leaseExpiresAt }) {
|
|
1119
|
+
const existing = devices.get(deviceId);
|
|
1120
|
+
if (!existing || existing.instanceId !== instanceId || existing.status !== "online")
|
|
1121
|
+
return;
|
|
1122
|
+
devices.set(deviceId, { ...existing, lastHeartbeatAt, leaseExpiresAt });
|
|
1123
|
+
},
|
|
1124
|
+
markDeviceOffline({ deviceId, instanceId, reason }) {
|
|
1125
|
+
const existing = devices.get(deviceId);
|
|
1126
|
+
if (!existing || existing.instanceId !== instanceId)
|
|
1127
|
+
return;
|
|
1128
|
+
devices.set(deviceId, { ...existing, status: "offline", offlineReason: reason });
|
|
1129
|
+
offlineAt.delete(deviceId);
|
|
1130
|
+
offlineAt.set(deviceId, now());
|
|
1131
|
+
evictOffline();
|
|
1132
|
+
},
|
|
1133
|
+
lookupDevice(deviceId) {
|
|
1134
|
+
evictOffline();
|
|
1135
|
+
return devices.get(deviceId);
|
|
1136
|
+
},
|
|
1137
|
+
listDevicesByAccount(accountId) {
|
|
1138
|
+
evictOffline();
|
|
1139
|
+
const list = [];
|
|
1140
|
+
for (const record of devices.values()) {
|
|
1141
|
+
if (record.accountId === accountId)
|
|
1142
|
+
list.push(record);
|
|
1143
|
+
}
|
|
1144
|
+
return list;
|
|
1145
|
+
},
|
|
1146
|
+
bindInstance(instanceId, handler) {
|
|
1147
|
+
instances.set(instanceId, handler);
|
|
1148
|
+
return () => {
|
|
1149
|
+
if (instances.get(instanceId) === handler)
|
|
1150
|
+
instances.delete(instanceId);
|
|
1151
|
+
};
|
|
1152
|
+
},
|
|
1153
|
+
async forwardRpc(instanceId, deviceId, request, signal) {
|
|
1154
|
+
const handler = instances.get(instanceId);
|
|
1155
|
+
if (!handler) {
|
|
1156
|
+
throw new DeviceRelayError("BROKER_UNAVAILABLE", `Relay backend instance "${instanceId}" is not reachable`, { deviceId });
|
|
1157
|
+
}
|
|
1158
|
+
return handler.executeLocalRpc(deviceId, request, signal);
|
|
1159
|
+
},
|
|
1160
|
+
async forwardStreamOpen(instanceId, deviceId, request, sink, signal) {
|
|
1161
|
+
const handler = instances.get(instanceId);
|
|
1162
|
+
if (!handler) {
|
|
1163
|
+
throw new DeviceRelayError("BROKER_UNAVAILABLE", `Relay backend instance "${instanceId}" is not reachable`, { deviceId });
|
|
1164
|
+
}
|
|
1165
|
+
return handler.openLocalStream(deviceId, request, sink, signal);
|
|
1166
|
+
}
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
// src/device-relay/hub-handshake.ts
|
|
1170
|
+
function closedHelloAck() {
|
|
1171
|
+
return {
|
|
1172
|
+
schemaVersion: 1,
|
|
1173
|
+
outcome: "error",
|
|
1174
|
+
code: "CLOSED",
|
|
1175
|
+
message: "Device relay hub is closed",
|
|
1176
|
+
retryable: false
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
async function handleDeviceHello(input) {
|
|
1180
|
+
const { runtime, connection, binding, hello, ack, teardown } = input;
|
|
1181
|
+
const seq = ++binding.helloSeq;
|
|
1182
|
+
const isStale = () => runtime.isClosed() || binding.detached || seq !== binding.helloSeq;
|
|
1183
|
+
try {
|
|
1184
|
+
if (isStale()) {
|
|
1185
|
+
ack(closedHelloAck());
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
const verified = await runtime.config.authenticateDevice({
|
|
1189
|
+
identity: connection.raw.data,
|
|
1190
|
+
hello,
|
|
1191
|
+
socketId: connection.raw.id
|
|
1192
|
+
});
|
|
1193
|
+
if (isStale()) {
|
|
1194
|
+
ack(closedHelloAck());
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (!verified) {
|
|
1198
|
+
ack({
|
|
1199
|
+
schemaVersion: 1,
|
|
1200
|
+
outcome: "error",
|
|
1201
|
+
code: "UNAUTHORIZED",
|
|
1202
|
+
message: "Device authentication refused",
|
|
1203
|
+
retryable: false
|
|
1204
|
+
});
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
if (verified.deviceId !== hello.deviceId) {
|
|
1208
|
+
ack({
|
|
1209
|
+
schemaVersion: 1,
|
|
1210
|
+
outcome: "error",
|
|
1211
|
+
code: "IDENTITY_MISMATCH",
|
|
1212
|
+
message: "Authenticated device identity does not match hello deviceId",
|
|
1213
|
+
retryable: false
|
|
1214
|
+
});
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
if (binding.activeDeviceId !== undefined && binding.activeDeviceId !== verified.deviceId) {
|
|
1218
|
+
const priorDeviceId = binding.activeDeviceId;
|
|
1219
|
+
const priorSession = binding.activeSession;
|
|
1220
|
+
binding.activeDeviceId = undefined;
|
|
1221
|
+
binding.activeSession = undefined;
|
|
1222
|
+
await teardown(runtime, priorDeviceId, priorSession, "replaced");
|
|
1223
|
+
if (isStale()) {
|
|
1224
|
+
ack(closedHelloAck());
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
const previous = runtime.localDevices.get(verified.deviceId);
|
|
1229
|
+
if (previous && previous.connection !== connection) {
|
|
1230
|
+
await teardown(runtime, verified.deviceId, previous, "replaced");
|
|
1231
|
+
if (isStale()) {
|
|
1232
|
+
ack(closedHelloAck());
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
const sameSocketPrevious = previous && previous.connection === connection ? previous : undefined;
|
|
1237
|
+
const effectiveLeaseMs = Math.min(runtime.leaseTtlMs, hello.leaseTtlMs ?? runtime.leaseTtlMs);
|
|
1238
|
+
const timestamp = runtime.now();
|
|
1239
|
+
const state = {
|
|
1240
|
+
accountId: verified.accountId,
|
|
1241
|
+
deviceId: verified.deviceId,
|
|
1242
|
+
status: "online",
|
|
1243
|
+
capabilities: [...verified.capabilities ?? hello.capabilities],
|
|
1244
|
+
instanceId: runtime.instanceId,
|
|
1245
|
+
connectedAt: timestamp,
|
|
1246
|
+
lastHeartbeatAt: timestamp,
|
|
1247
|
+
leaseExpiresAt: timestamp + effectiveLeaseMs
|
|
1248
|
+
};
|
|
1249
|
+
const session = {
|
|
1250
|
+
state,
|
|
1251
|
+
effectiveLeaseMs,
|
|
1252
|
+
connection,
|
|
1253
|
+
binding,
|
|
1254
|
+
inFlightRpcs: sameSocketPrevious ? sameSocketPrevious.inFlightRpcs : new Map,
|
|
1255
|
+
openStreams: sameSocketPrevious ? sameSocketPrevious.openStreams : new Map
|
|
1256
|
+
};
|
|
1257
|
+
binding.activeDeviceId = verified.deviceId;
|
|
1258
|
+
binding.activeSession = session;
|
|
1259
|
+
runtime.localDevices.set(verified.deviceId, session);
|
|
1260
|
+
try {
|
|
1261
|
+
await runtime.broker.registerDevice(state);
|
|
1262
|
+
} catch (error) {
|
|
1263
|
+
if (runtime.localDevices.get(verified.deviceId) === session) {
|
|
1264
|
+
runtime.localDevices.delete(verified.deviceId);
|
|
1265
|
+
}
|
|
1266
|
+
if (binding.activeSession === session) {
|
|
1267
|
+
binding.activeSession = undefined;
|
|
1268
|
+
binding.activeDeviceId = undefined;
|
|
1269
|
+
}
|
|
1270
|
+
runtime.logger?.warn("DeviceRelayHub broker registerDevice failed", {
|
|
1271
|
+
deviceId: verified.deviceId,
|
|
1272
|
+
error
|
|
1273
|
+
});
|
|
1274
|
+
ack({
|
|
1275
|
+
schemaVersion: 1,
|
|
1276
|
+
outcome: "error",
|
|
1277
|
+
code: "BROKER_UNAVAILABLE",
|
|
1278
|
+
message: "Device relay broker failed to register device",
|
|
1279
|
+
retryable: true
|
|
1280
|
+
});
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
if (isStale() || runtime.localDevices.get(verified.deviceId) !== session) {
|
|
1284
|
+
const reason = runtime.isClosed() ? "closed" : "disconnected";
|
|
1285
|
+
if (runtime.localDevices.get(verified.deviceId) === session) {
|
|
1286
|
+
await teardown(runtime, verified.deviceId, session, reason);
|
|
1287
|
+
} else if (!runtime.localDevices.has(verified.deviceId)) {
|
|
1288
|
+
try {
|
|
1289
|
+
await runtime.broker.markDeviceOffline({
|
|
1290
|
+
deviceId: verified.deviceId,
|
|
1291
|
+
instanceId: runtime.instanceId,
|
|
1292
|
+
reason
|
|
1293
|
+
});
|
|
1294
|
+
} catch (error) {
|
|
1295
|
+
runtime.logger?.warn("DeviceRelayHub broker markDeviceOffline failed", {
|
|
1296
|
+
deviceId: verified.deviceId,
|
|
1297
|
+
reason,
|
|
1298
|
+
error
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
ack(closedHelloAck());
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
binding.lastRegisteredDeviceId = verified.deviceId;
|
|
1306
|
+
runtime.notifyState(state);
|
|
1307
|
+
ack({
|
|
1308
|
+
schemaVersion: 1,
|
|
1309
|
+
outcome: "ok",
|
|
1310
|
+
leaseTtlMs: effectiveLeaseMs,
|
|
1311
|
+
leaseExpiresAtMs: state.leaseExpiresAt,
|
|
1312
|
+
serverTimeMs: timestamp,
|
|
1313
|
+
instanceId: runtime.instanceId
|
|
1314
|
+
});
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
runtime.logger?.error("DeviceRelayHub authenticateDevice failed", { error });
|
|
1317
|
+
ack({
|
|
1318
|
+
schemaVersion: 1,
|
|
1319
|
+
outcome: "error",
|
|
1320
|
+
code: "UNAUTHORIZED",
|
|
1321
|
+
message: "Device authentication failed",
|
|
1322
|
+
retryable: false
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
function handleDeviceHeartbeat(runtime, binding, heartbeat, ack, teardown) {
|
|
1327
|
+
if (runtime.isClosed() || binding.detached) {
|
|
1328
|
+
ack({
|
|
1329
|
+
schemaVersion: 1,
|
|
1330
|
+
outcome: "error",
|
|
1331
|
+
code: "CLOSED",
|
|
1332
|
+
message: "Device relay hub is closed",
|
|
1333
|
+
retryable: false
|
|
1334
|
+
});
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
const session = binding.activeSession;
|
|
1338
|
+
if (!session) {
|
|
1339
|
+
if (binding.lastRegisteredDeviceId === heartbeat.deviceId) {
|
|
1340
|
+
ack({
|
|
1341
|
+
schemaVersion: 1,
|
|
1342
|
+
outcome: "error",
|
|
1343
|
+
code: "DEVICE_OFFLINE",
|
|
1344
|
+
message: "Device session is no longer active; re-register with hello",
|
|
1345
|
+
retryable: true
|
|
1346
|
+
});
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
ack({
|
|
1350
|
+
schemaVersion: 1,
|
|
1351
|
+
outcome: "error",
|
|
1352
|
+
code: "IDENTITY_MISMATCH",
|
|
1353
|
+
message: "Device is not registered on this connection",
|
|
1354
|
+
retryable: false
|
|
1355
|
+
});
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (binding.activeDeviceId !== heartbeat.deviceId) {
|
|
1359
|
+
ack({
|
|
1360
|
+
schemaVersion: 1,
|
|
1361
|
+
outcome: "error",
|
|
1362
|
+
code: "IDENTITY_MISMATCH",
|
|
1363
|
+
message: "Device is not registered on this connection",
|
|
1364
|
+
retryable: false
|
|
1365
|
+
});
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
if (session.state.status !== "online" || runtime.localDevices.get(heartbeat.deviceId) !== session) {
|
|
1369
|
+
if (binding.activeSession === session) {
|
|
1370
|
+
binding.activeSession = undefined;
|
|
1371
|
+
binding.activeDeviceId = undefined;
|
|
1372
|
+
}
|
|
1373
|
+
ack({
|
|
1374
|
+
schemaVersion: 1,
|
|
1375
|
+
outcome: "error",
|
|
1376
|
+
code: "DEVICE_OFFLINE",
|
|
1377
|
+
message: "Device session is no longer active; re-register with hello",
|
|
1378
|
+
retryable: true
|
|
1379
|
+
});
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
const timestamp = runtime.now();
|
|
1383
|
+
if (timestamp >= session.state.leaseExpiresAt) {
|
|
1384
|
+
if (binding.activeSession === session) {
|
|
1385
|
+
binding.activeSession = undefined;
|
|
1386
|
+
binding.activeDeviceId = undefined;
|
|
1387
|
+
}
|
|
1388
|
+
observeHubBackground(runtime.logger, "teardownLocalDevice", () => teardown(runtime, heartbeat.deviceId, session, "lease-expired"));
|
|
1389
|
+
ack({
|
|
1390
|
+
schemaVersion: 1,
|
|
1391
|
+
outcome: "error",
|
|
1392
|
+
code: "DEVICE_OFFLINE",
|
|
1393
|
+
message: "Device lease expired; re-register with hello",
|
|
1394
|
+
retryable: true
|
|
1395
|
+
});
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
const leaseExpiresAt = timestamp + session.effectiveLeaseMs;
|
|
1399
|
+
session.state = {
|
|
1400
|
+
...session.state,
|
|
1401
|
+
lastHeartbeatAt: timestamp,
|
|
1402
|
+
leaseExpiresAt
|
|
1403
|
+
};
|
|
1404
|
+
observeHubBackground(runtime.logger, "refreshDeviceLease", () => runtime.broker.refreshDeviceLease({
|
|
1405
|
+
deviceId: heartbeat.deviceId,
|
|
1406
|
+
instanceId: runtime.instanceId,
|
|
1407
|
+
lastHeartbeatAt: timestamp,
|
|
1408
|
+
leaseExpiresAt
|
|
1409
|
+
}));
|
|
1410
|
+
ack({
|
|
1411
|
+
schemaVersion: 1,
|
|
1412
|
+
outcome: "ok",
|
|
1413
|
+
leaseExpiresAtMs: leaseExpiresAt,
|
|
1414
|
+
serverTimeMs: timestamp
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// src/device-relay/hub-connection.ts
|
|
1419
|
+
function observeHubBackground(logger, operation, run) {
|
|
1420
|
+
try {
|
|
1421
|
+
const pending = run();
|
|
1422
|
+
if (pending !== undefined) {
|
|
1423
|
+
Promise.resolve(pending).catch((error) => {
|
|
1424
|
+
logger?.warn(`DeviceRelayHub ${operation} failed`, { error });
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
} catch (error) {
|
|
1428
|
+
logger?.warn(`DeviceRelayHub ${operation} failed`, { error });
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
async function teardownLocalDevice(runtime, deviceId, expected, reason) {
|
|
1432
|
+
const session = runtime.localDevices.get(deviceId);
|
|
1433
|
+
if (!session || expected && session !== expected)
|
|
1434
|
+
return;
|
|
1435
|
+
runtime.localDevices.delete(deviceId);
|
|
1436
|
+
if (session.binding.activeSession === session) {
|
|
1437
|
+
session.binding.activeSession = undefined;
|
|
1438
|
+
session.binding.activeDeviceId = undefined;
|
|
1439
|
+
}
|
|
1440
|
+
session.state = { ...session.state, status: "offline", offlineReason: reason };
|
|
1441
|
+
try {
|
|
1442
|
+
await runtime.broker.markDeviceOffline({
|
|
1443
|
+
deviceId,
|
|
1444
|
+
instanceId: runtime.instanceId,
|
|
1445
|
+
reason
|
|
1446
|
+
});
|
|
1447
|
+
} catch (error) {
|
|
1448
|
+
runtime.logger?.warn("DeviceRelayHub broker markDeviceOffline failed", {
|
|
1449
|
+
deviceId,
|
|
1450
|
+
reason,
|
|
1451
|
+
error
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1454
|
+
runtime.notifyState(session.state);
|
|
1455
|
+
const rpcError = new DeviceRelayError("DELIVERY_UNKNOWN", `Device "${deviceId}" went offline (${reason}) while request was in flight`, { retryable: false, delivery: "unknown", deviceId });
|
|
1456
|
+
for (const pending of session.inFlightRpcs.values()) {
|
|
1457
|
+
pending.cleanup();
|
|
1458
|
+
pending.reject(rpcError);
|
|
1459
|
+
}
|
|
1460
|
+
session.inFlightRpcs.clear();
|
|
1461
|
+
for (const [streamId, open] of session.openStreams) {
|
|
1462
|
+
if (!open.opened && open.resolveOpen) {
|
|
1463
|
+
open.resolveOpen({
|
|
1464
|
+
schemaVersion: 1,
|
|
1465
|
+
streamId,
|
|
1466
|
+
outcome: "error",
|
|
1467
|
+
code: "DEVICE_OFFLINE",
|
|
1468
|
+
message: `Device "${deviceId}" went offline (${reason})`,
|
|
1469
|
+
retryable: true
|
|
1470
|
+
});
|
|
1471
|
+
} else {
|
|
1472
|
+
open.sink.push({
|
|
1473
|
+
schemaVersion: 1,
|
|
1474
|
+
streamId,
|
|
1475
|
+
kind: "error",
|
|
1476
|
+
code: "DEVICE_OFFLINE",
|
|
1477
|
+
message: `Device "${deviceId}" went offline (${reason})`,
|
|
1478
|
+
retryable: true
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
session.openStreams.clear();
|
|
1483
|
+
}
|
|
1484
|
+
async function executeLocalDeviceRpc(runtime, deviceId, request, signal) {
|
|
1485
|
+
const session = runtime.localDevices.get(deviceId);
|
|
1486
|
+
if (session?.state.status !== "online" || runtime.now() >= session.state.leaseExpiresAt) {
|
|
1487
|
+
if (session && runtime.now() >= session.state.leaseExpiresAt) {
|
|
1488
|
+
await teardownLocalDevice(runtime, deviceId, session, "lease-expired");
|
|
1489
|
+
}
|
|
1490
|
+
throw new DeviceRelayError("DEVICE_OFFLINE", `Device "${deviceId}" is offline`, {
|
|
1491
|
+
delivery: "not-sent",
|
|
1492
|
+
deviceId
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
if (session.inFlightRpcs.size >= runtime.maxInFlightPerDevice) {
|
|
1496
|
+
throw new DeviceRelayError("DEVICE_BUSY", `Device "${deviceId}" reached its ${runtime.maxInFlightPerDevice} in-flight request limit`, { delivery: "not-sent", deviceId });
|
|
1497
|
+
}
|
|
1498
|
+
if (signal?.aborted)
|
|
1499
|
+
throw abortReason(signal);
|
|
1500
|
+
return new Promise((resolve, reject) => {
|
|
1501
|
+
const onAbort = () => {
|
|
1502
|
+
if (!session.inFlightRpcs.delete(request.requestId))
|
|
1503
|
+
return;
|
|
1504
|
+
cleanup();
|
|
1505
|
+
try {
|
|
1506
|
+
session.connection.events.emit("stitchkit.relay.rpc-cancel", {
|
|
1507
|
+
schemaVersion: 1,
|
|
1508
|
+
requestId: request.requestId,
|
|
1509
|
+
reason: "aborted"
|
|
1510
|
+
});
|
|
1511
|
+
} catch {}
|
|
1512
|
+
reject(signal ? abortReason(signal) : abortError("Relay request aborted"));
|
|
1513
|
+
};
|
|
1514
|
+
const cleanup = () => {
|
|
1515
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1516
|
+
};
|
|
1517
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1518
|
+
session.inFlightRpcs.set(request.requestId, { resolve, reject, cleanup });
|
|
1519
|
+
const accepted = session.connection.events.emit("stitchkit.relay.rpc-request", request);
|
|
1520
|
+
if (!accepted) {
|
|
1521
|
+
session.inFlightRpcs.delete(request.requestId);
|
|
1522
|
+
cleanup();
|
|
1523
|
+
reject(new DeviceRelayError("DEVICE_OFFLINE", `Device "${deviceId}" transport rejected emit`, {
|
|
1524
|
+
delivery: "not-sent",
|
|
1525
|
+
deviceId
|
|
1526
|
+
}));
|
|
1527
|
+
}
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
function emitStreamCloseSafely(connection, streamId, reason) {
|
|
1531
|
+
try {
|
|
1532
|
+
connection.events.emit("stitchkit.relay.stream-close", {
|
|
1533
|
+
schemaVersion: 1,
|
|
1534
|
+
streamId,
|
|
1535
|
+
...reason !== undefined && { reason }
|
|
1536
|
+
});
|
|
1537
|
+
} catch {}
|
|
1538
|
+
}
|
|
1539
|
+
async function openLocalDeviceStream(runtime, deviceId, request, sink, signal) {
|
|
1540
|
+
const session = runtime.localDevices.get(deviceId);
|
|
1541
|
+
if (session?.state.status !== "online" || runtime.now() >= session.state.leaseExpiresAt) {
|
|
1542
|
+
if (session && runtime.now() >= session.state.leaseExpiresAt) {
|
|
1543
|
+
await teardownLocalDevice(runtime, deviceId, session, "lease-expired");
|
|
1544
|
+
}
|
|
1545
|
+
throw new DeviceRelayError("DEVICE_OFFLINE", `Device "${deviceId}" is offline`, {
|
|
1546
|
+
delivery: "not-sent",
|
|
1547
|
+
deviceId
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
if (session.openStreams.size >= runtime.maxStreamsPerDevice) {
|
|
1551
|
+
throw new DeviceRelayError("STREAM_CAPACITY", `Device "${deviceId}" reached its ${runtime.maxStreamsPerDevice} concurrent stream limit`, { delivery: "not-sent", deviceId });
|
|
1552
|
+
}
|
|
1553
|
+
if (signal?.aborted)
|
|
1554
|
+
throw abortReason(signal);
|
|
1555
|
+
const ack = await new Promise((resolve, reject) => {
|
|
1556
|
+
const cleanupAbort = () => {
|
|
1557
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1558
|
+
};
|
|
1559
|
+
const onAbort = () => {
|
|
1560
|
+
const removed = session.openStreams.delete(request.streamId);
|
|
1561
|
+
cleanupAbort();
|
|
1562
|
+
if (removed) {
|
|
1563
|
+
emitStreamCloseSafely(session.connection, request.streamId, "open-cancelled");
|
|
1564
|
+
}
|
|
1565
|
+
reject(signal ? abortReason(signal) : abortError("Relay stream open aborted"));
|
|
1566
|
+
};
|
|
1567
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1568
|
+
session.openStreams.set(request.streamId, {
|
|
1569
|
+
sink,
|
|
1570
|
+
resolveOpen(frame) {
|
|
1571
|
+
cleanupAbort();
|
|
1572
|
+
resolve(frame);
|
|
1573
|
+
},
|
|
1574
|
+
opened: false
|
|
1575
|
+
});
|
|
1576
|
+
const accepted = session.connection.events.emit("stitchkit.relay.stream-open", request);
|
|
1577
|
+
if (!accepted) {
|
|
1578
|
+
session.openStreams.delete(request.streamId);
|
|
1579
|
+
cleanupAbort();
|
|
1580
|
+
reject(new DeviceRelayError("DEVICE_OFFLINE", `Device "${deviceId}" transport rejected emit`, { delivery: "not-sent", deviceId }));
|
|
1581
|
+
}
|
|
1582
|
+
});
|
|
1583
|
+
if (ack.outcome === "error") {
|
|
1584
|
+
session.openStreams.delete(request.streamId);
|
|
1585
|
+
throw new DeviceRelayError(ack.code, ack.message, {
|
|
1586
|
+
retryable: ack.retryable,
|
|
1587
|
+
deviceId
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
if (signal?.aborted) {
|
|
1591
|
+
if (session.openStreams.delete(request.streamId)) {
|
|
1592
|
+
emitStreamCloseSafely(session.connection, request.streamId, "open-cancelled");
|
|
1593
|
+
}
|
|
1594
|
+
throw abortReason(signal);
|
|
1595
|
+
}
|
|
1596
|
+
const entry = session.openStreams.get(request.streamId);
|
|
1597
|
+
if (entry)
|
|
1598
|
+
entry.opened = true;
|
|
1599
|
+
let closedStream = false;
|
|
1600
|
+
return {
|
|
1601
|
+
grantCredits(credits) {
|
|
1602
|
+
if (closedStream || !session.openStreams.has(request.streamId))
|
|
1603
|
+
return;
|
|
1604
|
+
session.connection.events.emit("stitchkit.relay.stream-credit", {
|
|
1605
|
+
schemaVersion: 1,
|
|
1606
|
+
streamId: request.streamId,
|
|
1607
|
+
credits
|
|
1608
|
+
});
|
|
1609
|
+
},
|
|
1610
|
+
close(reason) {
|
|
1611
|
+
if (closedStream)
|
|
1612
|
+
return;
|
|
1613
|
+
closedStream = true;
|
|
1614
|
+
if (!session.openStreams.delete(request.streamId))
|
|
1615
|
+
return;
|
|
1616
|
+
emitStreamCloseSafely(session.connection, request.streamId, reason);
|
|
1617
|
+
}
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
function attachDeviceConnection(runtime, connection) {
|
|
1621
|
+
const binding = {
|
|
1622
|
+
activeDeviceId: undefined,
|
|
1623
|
+
activeSession: undefined,
|
|
1624
|
+
lastRegisteredDeviceId: undefined,
|
|
1625
|
+
detached: false,
|
|
1626
|
+
helloSeq: 0
|
|
1627
|
+
};
|
|
1628
|
+
const onDisconnect = () => {
|
|
1629
|
+
const deviceId = binding.activeDeviceId;
|
|
1630
|
+
const session = binding.activeSession;
|
|
1631
|
+
binding.activeDeviceId = undefined;
|
|
1632
|
+
binding.activeSession = undefined;
|
|
1633
|
+
cleanup();
|
|
1634
|
+
if (deviceId !== undefined) {
|
|
1635
|
+
observeHubBackground(runtime.logger, "teardownLocalDevice", () => teardownLocalDevice(runtime, deviceId, session, "disconnected"));
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
const offHello = connection.events.on("stitchkit.relay.hello", (hello, ack) => {
|
|
1639
|
+
observeHubBackground(runtime.logger, "handleDeviceHello", () => handleDeviceHello({
|
|
1640
|
+
runtime,
|
|
1641
|
+
connection,
|
|
1642
|
+
binding,
|
|
1643
|
+
hello,
|
|
1644
|
+
ack,
|
|
1645
|
+
teardown: teardownLocalDevice
|
|
1646
|
+
}));
|
|
1647
|
+
});
|
|
1648
|
+
const offHeartbeat = connection.events.on("stitchkit.relay.heartbeat", (heartbeat, ack) => {
|
|
1649
|
+
handleDeviceHeartbeat(runtime, binding, heartbeat, ack, teardownLocalDevice);
|
|
1650
|
+
});
|
|
1651
|
+
const offRpcResponse = connection.events.on("stitchkit.relay.rpc-response", (response) => {
|
|
1652
|
+
const pending = binding.activeSession?.inFlightRpcs.get(response.requestId);
|
|
1653
|
+
if (!pending || !binding.activeSession)
|
|
1654
|
+
return;
|
|
1655
|
+
binding.activeSession.inFlightRpcs.delete(response.requestId);
|
|
1656
|
+
pending.cleanup();
|
|
1657
|
+
pending.resolve(response);
|
|
1658
|
+
});
|
|
1659
|
+
const offStreamAck = connection.events.on("stitchkit.relay.stream-open-ack", (ackFrame) => {
|
|
1660
|
+
const entry = binding.activeSession?.openStreams.get(ackFrame.streamId);
|
|
1661
|
+
if (!entry) {
|
|
1662
|
+
if (ackFrame.outcome === "ok") {
|
|
1663
|
+
emitStreamCloseSafely(connection, ackFrame.streamId, "late-open-ack");
|
|
1664
|
+
}
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (!entry.resolveOpen) {
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
const resolve = entry.resolveOpen;
|
|
1671
|
+
entry.resolveOpen = undefined;
|
|
1672
|
+
if (ackFrame.outcome === "ok") {
|
|
1673
|
+
entry.opened = true;
|
|
1674
|
+
} else {
|
|
1675
|
+
binding.activeSession?.openStreams.delete(ackFrame.streamId);
|
|
1676
|
+
}
|
|
1677
|
+
resolve(ackFrame);
|
|
1678
|
+
});
|
|
1679
|
+
const offStreamEvent = connection.events.on("stitchkit.relay.stream-event", (event) => {
|
|
1680
|
+
const entry = binding.activeSession?.openStreams.get(event.streamId);
|
|
1681
|
+
if (!entry || !binding.activeSession)
|
|
1682
|
+
return;
|
|
1683
|
+
if (event.kind === "end" || event.kind === "error") {
|
|
1684
|
+
binding.activeSession.openStreams.delete(event.streamId);
|
|
1685
|
+
if (!entry.opened && entry.resolveOpen) {
|
|
1686
|
+
const resolve = entry.resolveOpen;
|
|
1687
|
+
entry.resolveOpen = undefined;
|
|
1688
|
+
resolve(event.kind === "error" ? {
|
|
1689
|
+
schemaVersion: 1,
|
|
1690
|
+
streamId: event.streamId,
|
|
1691
|
+
outcome: "error",
|
|
1692
|
+
code: event.code,
|
|
1693
|
+
message: event.message,
|
|
1694
|
+
retryable: event.retryable
|
|
1695
|
+
} : {
|
|
1696
|
+
schemaVersion: 1,
|
|
1697
|
+
streamId: event.streamId,
|
|
1698
|
+
outcome: "error",
|
|
1699
|
+
code: "STREAM_UNAVAILABLE",
|
|
1700
|
+
message: "Stream ended before open acknowledgment",
|
|
1701
|
+
retryable: false
|
|
1702
|
+
});
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
entry.sink.push(event);
|
|
1707
|
+
});
|
|
1708
|
+
connection.raw.on("disconnect", onDisconnect);
|
|
1709
|
+
const cleanup = () => {
|
|
1710
|
+
if (binding.detached)
|
|
1711
|
+
return;
|
|
1712
|
+
binding.detached = true;
|
|
1713
|
+
offHello();
|
|
1714
|
+
offHeartbeat();
|
|
1715
|
+
offRpcResponse();
|
|
1716
|
+
offStreamAck();
|
|
1717
|
+
offStreamEvent();
|
|
1718
|
+
connection.raw.off("disconnect", onDisconnect);
|
|
1719
|
+
runtime.socketCleanups.delete(cleanup);
|
|
1720
|
+
};
|
|
1721
|
+
runtime.socketCleanups.add(cleanup);
|
|
1722
|
+
return cleanup;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// src/device-relay/hub-streams.ts
|
|
1726
|
+
function createRelayStreamConsumer(input) {
|
|
1727
|
+
const queue = [];
|
|
1728
|
+
const waiters = [];
|
|
1729
|
+
let cursor = input.initialCursor;
|
|
1730
|
+
let ended = false;
|
|
1731
|
+
let failure;
|
|
1732
|
+
let closedByConsumer = false;
|
|
1733
|
+
let consumedSinceCredit = 0;
|
|
1734
|
+
const replenishThreshold = Math.max(1, Math.floor(input.maxBufferedFrames / 2));
|
|
1735
|
+
const detachAbort = () => {
|
|
1736
|
+
input.signal?.removeEventListener("abort", onAbort);
|
|
1737
|
+
};
|
|
1738
|
+
const resolveAllWaitersDone = () => {
|
|
1739
|
+
for (const pending of waiters.splice(0)) {
|
|
1740
|
+
pending.resolve({ value: undefined, done: true });
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
const finishClose = (reason) => {
|
|
1744
|
+
if (closedByConsumer)
|
|
1745
|
+
return;
|
|
1746
|
+
closedByConsumer = true;
|
|
1747
|
+
ended = true;
|
|
1748
|
+
detachAbort();
|
|
1749
|
+
resolveAllWaitersDone();
|
|
1750
|
+
input.onClose(reason);
|
|
1751
|
+
};
|
|
1752
|
+
const onAbort = () => {
|
|
1753
|
+
finishClose("aborted");
|
|
1754
|
+
};
|
|
1755
|
+
if (input.signal) {
|
|
1756
|
+
if (input.signal.aborted) {
|
|
1757
|
+
finishClose("aborted");
|
|
1758
|
+
} else {
|
|
1759
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
const fail = (error) => {
|
|
1763
|
+
if (ended)
|
|
1764
|
+
return;
|
|
1765
|
+
ended = true;
|
|
1766
|
+
detachAbort();
|
|
1767
|
+
const first = waiters.shift();
|
|
1768
|
+
if (first) {
|
|
1769
|
+
first.reject(error);
|
|
1770
|
+
resolveAllWaitersDone();
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
failure = error;
|
|
1774
|
+
};
|
|
1775
|
+
const onConsumed = () => {
|
|
1776
|
+
if (ended || closedByConsumer)
|
|
1777
|
+
return;
|
|
1778
|
+
if (input.onFrameConsumed) {
|
|
1779
|
+
input.onFrameConsumed();
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
if (!input.onGrantCredits)
|
|
1783
|
+
return;
|
|
1784
|
+
consumedSinceCredit += 1;
|
|
1785
|
+
if (consumedSinceCredit >= replenishThreshold) {
|
|
1786
|
+
const grant = consumedSinceCredit;
|
|
1787
|
+
consumedSinceCredit = 0;
|
|
1788
|
+
input.onGrantCredits(grant);
|
|
1789
|
+
}
|
|
1790
|
+
};
|
|
1791
|
+
const push = (event) => {
|
|
1792
|
+
if (ended || closedByConsumer)
|
|
1793
|
+
return;
|
|
1794
|
+
if (event.kind === "end") {
|
|
1795
|
+
if (event.cursor !== undefined)
|
|
1796
|
+
cursor = event.cursor;
|
|
1797
|
+
ended = true;
|
|
1798
|
+
detachAbort();
|
|
1799
|
+
resolveAllWaitersDone();
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
if (event.kind === "error") {
|
|
1803
|
+
fail(new DeviceRelayError(event.code, event.message, {
|
|
1804
|
+
retryable: event.retryable,
|
|
1805
|
+
deviceId: input.deviceId
|
|
1806
|
+
}));
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
const frameBytes = utf8ByteLength(JSON.stringify(event.payload));
|
|
1810
|
+
if (frameBytes > input.maxFrameBytes) {
|
|
1811
|
+
const overflow = new DeviceRelayError("FRAME_UNREPRESENTABLE", `Relay stream frame exceeded ${input.maxFrameBytes} bytes`, { retryable: false, deviceId: input.deviceId });
|
|
1812
|
+
fail(overflow);
|
|
1813
|
+
input.onClose("frame-too-large");
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
if (event.cursor !== undefined)
|
|
1817
|
+
cursor = event.cursor;
|
|
1818
|
+
const frame = {
|
|
1819
|
+
...event.cursor !== undefined && { cursor: event.cursor },
|
|
1820
|
+
payload: event.payload
|
|
1821
|
+
};
|
|
1822
|
+
const pending = waiters.shift();
|
|
1823
|
+
if (pending) {
|
|
1824
|
+
pending.resolve({ value: frame, done: false });
|
|
1825
|
+
onConsumed();
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
if (queue.length >= input.maxBufferedFrames) {
|
|
1829
|
+
const overflow = new DeviceRelayError("STREAM_OVERFLOW", `Relay stream exceeded its ${input.maxBufferedFrames}-frame buffer limit`, { retryable: false, deviceId: input.deviceId });
|
|
1830
|
+
fail(overflow);
|
|
1831
|
+
input.onClose("overflow");
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
queue.push(frame);
|
|
1835
|
+
};
|
|
1836
|
+
const stream = {
|
|
1837
|
+
streamId: input.streamId,
|
|
1838
|
+
topic: input.topic,
|
|
1839
|
+
get cursor() {
|
|
1840
|
+
return cursor;
|
|
1841
|
+
},
|
|
1842
|
+
close(reason) {
|
|
1843
|
+
finishClose(reason ?? "closed");
|
|
1844
|
+
},
|
|
1845
|
+
[Symbol.asyncIterator]() {
|
|
1846
|
+
return {
|
|
1847
|
+
next() {
|
|
1848
|
+
const buffered = queue.shift();
|
|
1849
|
+
if (buffered !== undefined) {
|
|
1850
|
+
onConsumed();
|
|
1851
|
+
return Promise.resolve({ value: buffered, done: false });
|
|
1852
|
+
}
|
|
1853
|
+
if (failure) {
|
|
1854
|
+
const error = failure;
|
|
1855
|
+
failure = undefined;
|
|
1856
|
+
return Promise.reject(error);
|
|
1857
|
+
}
|
|
1858
|
+
if (ended)
|
|
1859
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
1860
|
+
return new Promise((resolve, reject) => {
|
|
1861
|
+
waiters.push({ resolve, reject });
|
|
1862
|
+
});
|
|
1863
|
+
},
|
|
1864
|
+
return() {
|
|
1865
|
+
finishClose("iterator-return");
|
|
1866
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
};
|
|
1871
|
+
return { stream, push, fail };
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// src/device-relay/hub-shared-streams.ts
|
|
1875
|
+
function maybeGrantSharedCredits(entry) {
|
|
1876
|
+
if (entry.closed || !entry.handle || entry.subscribers.size === 0)
|
|
1877
|
+
return;
|
|
1878
|
+
let minSafeCeiling = Number.POSITIVE_INFINITY;
|
|
1879
|
+
let minWindow = Number.POSITIVE_INFINITY;
|
|
1880
|
+
for (const sub of entry.subscribers) {
|
|
1881
|
+
const ceiling = sub.joinedAt + sub.consumed + sub.maxBufferedFrames;
|
|
1882
|
+
if (ceiling < minSafeCeiling)
|
|
1883
|
+
minSafeCeiling = ceiling;
|
|
1884
|
+
if (sub.maxBufferedFrames < minWindow)
|
|
1885
|
+
minWindow = sub.maxBufferedFrames;
|
|
1886
|
+
}
|
|
1887
|
+
const threshold = Math.max(1, Math.floor(minWindow / 2));
|
|
1888
|
+
const delta = minSafeCeiling - entry.grantedTotal;
|
|
1889
|
+
if (delta >= threshold) {
|
|
1890
|
+
entry.grantedTotal += delta;
|
|
1891
|
+
entry.handle.grantCredits(delta);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
function deliverSharedEvent(sharedStreams, entry, event) {
|
|
1895
|
+
if (entry.closed)
|
|
1896
|
+
return;
|
|
1897
|
+
if (event.kind === "data")
|
|
1898
|
+
entry.deliveredCount += 1;
|
|
1899
|
+
for (const sub of [...entry.subscribers]) {
|
|
1900
|
+
sub.controller.push(event);
|
|
1901
|
+
}
|
|
1902
|
+
if (event.kind === "end" || event.kind === "error") {
|
|
1903
|
+
entry.closed = true;
|
|
1904
|
+
if (sharedStreams.get(entry.key) === entry) {
|
|
1905
|
+
sharedStreams.delete(entry.key);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
function createSharedSubscriberRecord(sharedStreams, entry, options, maxBufferedFrames, maxFrameBytes, joinedAt) {
|
|
1910
|
+
let recordRef;
|
|
1911
|
+
const controller = createRelayStreamConsumer({
|
|
1912
|
+
streamId: entry.streamId,
|
|
1913
|
+
topic: options.topic,
|
|
1914
|
+
deviceId: options.deviceId,
|
|
1915
|
+
maxBufferedFrames,
|
|
1916
|
+
maxFrameBytes,
|
|
1917
|
+
...options.signal !== undefined && { signal: options.signal },
|
|
1918
|
+
onFrameConsumed: () => {
|
|
1919
|
+
if (!recordRef)
|
|
1920
|
+
return;
|
|
1921
|
+
recordRef.consumed += 1;
|
|
1922
|
+
maybeGrantSharedCredits(entry);
|
|
1923
|
+
},
|
|
1924
|
+
onClose: (reason) => {
|
|
1925
|
+
if (recordRef)
|
|
1926
|
+
entry.subscribers.delete(recordRef);
|
|
1927
|
+
if (entry.subscribers.size === 0 && !entry.closed) {
|
|
1928
|
+
entry.closed = true;
|
|
1929
|
+
if (sharedStreams.get(entry.key) === entry)
|
|
1930
|
+
sharedStreams.delete(entry.key);
|
|
1931
|
+
entry.openController.abort(abortError(reason ?? "last-subscriber-gone"));
|
|
1932
|
+
entry.handle?.close(reason ?? "last-subscriber-gone");
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
maybeGrantSharedCredits(entry);
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
const record = {
|
|
1939
|
+
controller,
|
|
1940
|
+
joinedAt,
|
|
1941
|
+
maxBufferedFrames,
|
|
1942
|
+
consumed: 0
|
|
1943
|
+
};
|
|
1944
|
+
recordRef = record;
|
|
1945
|
+
entry.subscribers.add(record);
|
|
1946
|
+
return record;
|
|
1947
|
+
}
|
|
1948
|
+
async function awaitSharedSubscriberOpen(sharedStreams, entry, subscriber, options, openTimeoutMs) {
|
|
1949
|
+
try {
|
|
1950
|
+
await withSignalDeadline(openTimeoutMs, options.signal, () => new DeviceRelayError("TIMEOUT", `Stream open timed out after ${openTimeoutMs}ms`, {
|
|
1951
|
+
deviceId: options.deviceId
|
|
1952
|
+
}), (waitSignal) => raceAbort(entry.openPromise, waitSignal));
|
|
1953
|
+
} catch (error) {
|
|
1954
|
+
subscriber.controller.stream.close("open-cancelled");
|
|
1955
|
+
entry.subscribers.delete(subscriber);
|
|
1956
|
+
if (entry.subscribers.size === 0 && !entry.closed) {
|
|
1957
|
+
entry.closed = true;
|
|
1958
|
+
if (sharedStreams.get(entry.key) === entry)
|
|
1959
|
+
sharedStreams.delete(entry.key);
|
|
1960
|
+
entry.openController.abort(abortError("open-cancelled"));
|
|
1961
|
+
entry.handle?.close("open-cancelled");
|
|
1962
|
+
}
|
|
1963
|
+
throw error;
|
|
1964
|
+
}
|
|
1965
|
+
return subscriber.controller.stream;
|
|
1966
|
+
}
|
|
1967
|
+
async function openSharedRelayStream(input) {
|
|
1968
|
+
const {
|
|
1969
|
+
ctx,
|
|
1970
|
+
device,
|
|
1971
|
+
options,
|
|
1972
|
+
shareKey,
|
|
1973
|
+
openTimeoutMs,
|
|
1974
|
+
maxBufferedFrames,
|
|
1975
|
+
maxFrameBytes,
|
|
1976
|
+
openUpstream
|
|
1977
|
+
} = input;
|
|
1978
|
+
const existing = ctx.sharedStreams.get(shareKey);
|
|
1979
|
+
if (existing && !existing.closed) {
|
|
1980
|
+
const joinedAt = existing.handle ? existing.deliveredCount : 0;
|
|
1981
|
+
const subscriber = createSharedSubscriberRecord(ctx.sharedStreams, existing, options, maxBufferedFrames, maxFrameBytes, joinedAt);
|
|
1982
|
+
if (existing.handle)
|
|
1983
|
+
return subscriber.controller.stream;
|
|
1984
|
+
return awaitSharedSubscriberOpen(ctx.sharedStreams, existing, subscriber, options, openTimeoutMs);
|
|
1985
|
+
}
|
|
1986
|
+
const streamId = crypto.randomUUID();
|
|
1987
|
+
const openController = new AbortController;
|
|
1988
|
+
const maxPreAttach = maxBufferedFrames + 1;
|
|
1989
|
+
const openReady = Promise.withResolvers();
|
|
1990
|
+
openReady.promise.catch(() => {
|
|
1991
|
+
return;
|
|
1992
|
+
});
|
|
1993
|
+
const entry = {
|
|
1994
|
+
key: shareKey,
|
|
1995
|
+
streamId,
|
|
1996
|
+
openController,
|
|
1997
|
+
openPromise: openReady.promise,
|
|
1998
|
+
pendingEvents: [],
|
|
1999
|
+
subscribers: new Set,
|
|
2000
|
+
handle: undefined,
|
|
2001
|
+
deliveredCount: 0,
|
|
2002
|
+
grantedTotal: maxBufferedFrames,
|
|
2003
|
+
preAttachOverflow: false,
|
|
2004
|
+
closed: false
|
|
2005
|
+
};
|
|
2006
|
+
ctx.sharedStreams.set(shareKey, entry);
|
|
2007
|
+
const opener = createSharedSubscriberRecord(ctx.sharedStreams, entry, options, maxBufferedFrames, maxFrameBytes, 0);
|
|
2008
|
+
const sink = {
|
|
2009
|
+
push(event) {
|
|
2010
|
+
if (entry.closed)
|
|
2011
|
+
return;
|
|
2012
|
+
if (!entry.handle) {
|
|
2013
|
+
if (entry.pendingEvents.length < maxPreAttach) {
|
|
2014
|
+
entry.pendingEvents.push(event);
|
|
2015
|
+
} else {
|
|
2016
|
+
entry.preAttachOverflow = true;
|
|
2017
|
+
}
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
deliverSharedEvent(ctx.sharedStreams, entry, event);
|
|
2021
|
+
}
|
|
2022
|
+
};
|
|
2023
|
+
const openFrame = {
|
|
2024
|
+
schemaVersion: 1,
|
|
2025
|
+
streamId,
|
|
2026
|
+
topic: options.topic,
|
|
2027
|
+
...options.params !== undefined && { params: options.params },
|
|
2028
|
+
initialCredits: maxBufferedFrames,
|
|
2029
|
+
maxFrameBytes
|
|
2030
|
+
};
|
|
2031
|
+
openUpstream({
|
|
2032
|
+
ctx,
|
|
2033
|
+
device,
|
|
2034
|
+
openFrame,
|
|
2035
|
+
sink,
|
|
2036
|
+
openTimeoutMs,
|
|
2037
|
+
openController
|
|
2038
|
+
}).then((handle) => {
|
|
2039
|
+
if (entry.closed || entry.subscribers.size === 0) {
|
|
2040
|
+
entry.closed = true;
|
|
2041
|
+
if (ctx.sharedStreams.get(shareKey) === entry)
|
|
2042
|
+
ctx.sharedStreams.delete(shareKey);
|
|
2043
|
+
entry.pendingEvents.length = 0;
|
|
2044
|
+
handle.close("no-subscribers");
|
|
2045
|
+
openReady.resolve();
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
entry.handle = handle;
|
|
2049
|
+
for (const event of entry.pendingEvents.splice(0)) {
|
|
2050
|
+
deliverSharedEvent(ctx.sharedStreams, entry, event);
|
|
2051
|
+
}
|
|
2052
|
+
if (entry.preAttachOverflow && !entry.closed) {
|
|
2053
|
+
deliverSharedEvent(ctx.sharedStreams, entry, {
|
|
2054
|
+
schemaVersion: 1,
|
|
2055
|
+
streamId,
|
|
2056
|
+
kind: "error",
|
|
2057
|
+
code: "STREAM_OVERFLOW",
|
|
2058
|
+
message: `Relay stream exceeded its ${maxBufferedFrames}-frame buffer limit`,
|
|
2059
|
+
retryable: false
|
|
2060
|
+
});
|
|
2061
|
+
handle.close("overflow");
|
|
2062
|
+
}
|
|
2063
|
+
maybeGrantSharedCredits(entry);
|
|
2064
|
+
openReady.resolve();
|
|
2065
|
+
}, (error) => {
|
|
2066
|
+
entry.closed = true;
|
|
2067
|
+
if (ctx.sharedStreams.get(shareKey) === entry)
|
|
2068
|
+
ctx.sharedStreams.delete(shareKey);
|
|
2069
|
+
entry.pendingEvents.length = 0;
|
|
2070
|
+
for (const sub of [...entry.subscribers]) {
|
|
2071
|
+
sub.controller.stream.close("open-failed");
|
|
2072
|
+
}
|
|
2073
|
+
entry.subscribers.clear();
|
|
2074
|
+
openReady.reject(error);
|
|
2075
|
+
});
|
|
2076
|
+
return awaitSharedSubscriberOpen(ctx.sharedStreams, entry, opener, options, openTimeoutMs);
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// src/device-relay/hub-dispatch.ts
|
|
2080
|
+
function buildRelayFetch(ctx, options) {
|
|
2081
|
+
const timeoutMs = options.timeoutMs ?? ctx.defaultRpcTimeoutMs;
|
|
2082
|
+
const maxRequestBodyBytes = options.maxRequestBodyBytes ?? ctx.defaultMaxRequestBytes;
|
|
2083
|
+
const maxResponseBodyBytes = options.maxResponseBodyBytes ?? ctx.defaultMaxResponseBytes;
|
|
2084
|
+
assertTimerMs("DeviceRelayFetchOptions.timeoutMs", timeoutMs);
|
|
2085
|
+
assertPositiveSafeInteger("DeviceRelayFetchOptions.maxRequestBodyBytes", maxRequestBodyBytes);
|
|
2086
|
+
assertPositiveSafeInteger("DeviceRelayFetchOptions.maxResponseBodyBytes", maxResponseBodyBytes);
|
|
2087
|
+
return async (input, init) => {
|
|
2088
|
+
if (ctx.isClosed())
|
|
2089
|
+
throw new DeviceRelayError("CLOSED", "Device relay hub is closed");
|
|
2090
|
+
const isRequest = input instanceof Request;
|
|
2091
|
+
const method = (init?.method ?? (isRequest ? input.method : "GET")).toUpperCase();
|
|
2092
|
+
const path = normalizeRelativeRelayPath(isRequest ? input.url : input);
|
|
2093
|
+
const device = await ctx.resolveAuthorizedDevice({
|
|
2094
|
+
callerAccountId: options.accountId,
|
|
2095
|
+
deviceId: options.deviceId,
|
|
2096
|
+
kind: "rpc",
|
|
2097
|
+
method,
|
|
2098
|
+
path
|
|
2099
|
+
});
|
|
2100
|
+
const callerSignal = init?.signal ?? (isRequest ? input.signal : undefined) ?? undefined;
|
|
2101
|
+
if (callerSignal?.aborted)
|
|
2102
|
+
throw abortReason(callerSignal);
|
|
2103
|
+
const headers = normalizeRelayHeaders(init?.headers ?? (isRequest ? input.headers : undefined), true);
|
|
2104
|
+
const encoded = await encodeFetchRequestBody(input, init, method, maxRequestBodyBytes);
|
|
2105
|
+
const frame = {
|
|
2106
|
+
schemaVersion: 1,
|
|
2107
|
+
requestId: crypto.randomUUID(),
|
|
2108
|
+
method,
|
|
2109
|
+
path,
|
|
2110
|
+
headers,
|
|
2111
|
+
...encoded.body !== undefined && { body: encoded.body },
|
|
2112
|
+
...encoded.bodyEncoding !== undefined && { bodyEncoding: encoded.bodyEncoding },
|
|
2113
|
+
maxResponseBodyBytes
|
|
2114
|
+
};
|
|
2115
|
+
const controller = new AbortController;
|
|
2116
|
+
let timedOut = false;
|
|
2117
|
+
const onCallerAbort = () => {
|
|
2118
|
+
controller.abort(callerSignal ? abortReason(callerSignal) : abortError("Aborted"));
|
|
2119
|
+
};
|
|
2120
|
+
callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
2121
|
+
const timer = setTimeout(() => {
|
|
2122
|
+
timedOut = true;
|
|
2123
|
+
controller.abort(new DeviceRelayError("TIMEOUT", `Relay RPC timed out after ${timeoutMs}ms`, {
|
|
2124
|
+
delivery: "unknown",
|
|
2125
|
+
deviceId: options.deviceId
|
|
2126
|
+
}));
|
|
2127
|
+
}, timeoutMs);
|
|
2128
|
+
timer.unref?.();
|
|
2129
|
+
let reply;
|
|
2130
|
+
try {
|
|
2131
|
+
reply = await ctx.broker.forwardRpc(device.instanceId, device.deviceId, frame, controller.signal);
|
|
2132
|
+
} catch (error) {
|
|
2133
|
+
if (timedOut) {
|
|
2134
|
+
throw new DeviceRelayError("TIMEOUT", `Relay RPC timed out after ${timeoutMs}ms`, {
|
|
2135
|
+
delivery: "unknown",
|
|
2136
|
+
deviceId: options.deviceId,
|
|
2137
|
+
cause: error
|
|
2138
|
+
});
|
|
2139
|
+
}
|
|
2140
|
+
throw error;
|
|
2141
|
+
} finally {
|
|
2142
|
+
clearTimeout(timer);
|
|
2143
|
+
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
2144
|
+
}
|
|
2145
|
+
if (reply.outcome === "error") {
|
|
2146
|
+
throw new DeviceRelayError(reply.code, reply.message, {
|
|
2147
|
+
retryable: reply.retryable,
|
|
2148
|
+
delivery: "delivered",
|
|
2149
|
+
deviceId: options.deviceId
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
if (decodedBodyByteLength(reply.body, reply.bodyEncoding) > maxResponseBodyBytes) {
|
|
2153
|
+
throw new DeviceRelayError("PAYLOAD_TOO_LARGE", `Relay response body exceeds the ${maxResponseBodyBytes}-byte limit`, { delivery: "delivered", deviceId: options.deviceId });
|
|
2154
|
+
}
|
|
2155
|
+
return buildFetchResponseFromRelay(reply);
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
async function openUpstreamWithTimeout(input) {
|
|
2159
|
+
const { ctx, device, openFrame, sink, openTimeoutMs, openController } = input;
|
|
2160
|
+
let timedOut = false;
|
|
2161
|
+
let settled = false;
|
|
2162
|
+
let timer;
|
|
2163
|
+
const timeoutError = () => new DeviceRelayError("TIMEOUT", `Stream open timed out after ${openTimeoutMs}ms`, {
|
|
2164
|
+
deviceId: device.deviceId
|
|
2165
|
+
});
|
|
2166
|
+
const openTimer = new Promise((_, reject) => {
|
|
2167
|
+
timer = setTimeout(() => {
|
|
2168
|
+
timedOut = true;
|
|
2169
|
+
const err = timeoutError();
|
|
2170
|
+
openController.abort(err);
|
|
2171
|
+
reject(err);
|
|
2172
|
+
}, openTimeoutMs);
|
|
2173
|
+
timer.unref?.();
|
|
2174
|
+
});
|
|
2175
|
+
const openCall = ctx.broker.forwardStreamOpen(device.instanceId, device.deviceId, openFrame, sink, openController.signal);
|
|
2176
|
+
openCall.then((lateHandle) => {
|
|
2177
|
+
if (settled)
|
|
2178
|
+
lateHandle.close("open-abandoned");
|
|
2179
|
+
}, () => {
|
|
2180
|
+
return;
|
|
2181
|
+
});
|
|
2182
|
+
try {
|
|
2183
|
+
const handle = await Promise.race([openCall, openTimer]);
|
|
2184
|
+
settled = true;
|
|
2185
|
+
return handle;
|
|
2186
|
+
} catch (error) {
|
|
2187
|
+
settled = true;
|
|
2188
|
+
if (timedOut) {
|
|
2189
|
+
throw new DeviceRelayError("TIMEOUT", `Stream open timed out after ${openTimeoutMs}ms`, {
|
|
2190
|
+
deviceId: device.deviceId,
|
|
2191
|
+
cause: error
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
throw error;
|
|
2195
|
+
} finally {
|
|
2196
|
+
clearTimeout(timer);
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
async function openDirectRelayStream(input) {
|
|
2200
|
+
const { ctx, device, options, openTimeoutMs, maxBufferedFrames, maxFrameBytes } = input;
|
|
2201
|
+
const streamId = crypto.randomUUID();
|
|
2202
|
+
let directConsumer;
|
|
2203
|
+
const pendingEvents = [];
|
|
2204
|
+
const maxPreAttach = maxBufferedFrames + 1;
|
|
2205
|
+
let preAttachOverflow = false;
|
|
2206
|
+
const sink = {
|
|
2207
|
+
push(event) {
|
|
2208
|
+
if (directConsumer) {
|
|
2209
|
+
directConsumer.push(event);
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
if (pendingEvents.length < maxPreAttach) {
|
|
2213
|
+
pendingEvents.push(event);
|
|
2214
|
+
} else {
|
|
2215
|
+
preAttachOverflow = true;
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
};
|
|
2219
|
+
const openFrame = {
|
|
2220
|
+
schemaVersion: 1,
|
|
2221
|
+
streamId,
|
|
2222
|
+
topic: options.topic,
|
|
2223
|
+
...options.cursor !== undefined && { cursor: options.cursor },
|
|
2224
|
+
...options.params !== undefined && { params: options.params },
|
|
2225
|
+
initialCredits: maxBufferedFrames,
|
|
2226
|
+
maxFrameBytes
|
|
2227
|
+
};
|
|
2228
|
+
const openController = new AbortController;
|
|
2229
|
+
const callerSignal = options.signal;
|
|
2230
|
+
const onCallerAbort = () => {
|
|
2231
|
+
openController.abort(callerSignal ? abortReason(callerSignal) : abortError("Aborted"));
|
|
2232
|
+
};
|
|
2233
|
+
callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
2234
|
+
let handle;
|
|
2235
|
+
try {
|
|
2236
|
+
handle = await openUpstreamWithTimeout({
|
|
2237
|
+
ctx,
|
|
2238
|
+
device,
|
|
2239
|
+
openFrame,
|
|
2240
|
+
sink,
|
|
2241
|
+
openTimeoutMs,
|
|
2242
|
+
openController
|
|
2243
|
+
});
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
pendingEvents.length = 0;
|
|
2246
|
+
throw error;
|
|
2247
|
+
} finally {
|
|
2248
|
+
callerSignal?.removeEventListener("abort", onCallerAbort);
|
|
2249
|
+
}
|
|
2250
|
+
directConsumer = createRelayStreamConsumer({
|
|
2251
|
+
streamId,
|
|
2252
|
+
topic: options.topic,
|
|
2253
|
+
deviceId: options.deviceId,
|
|
2254
|
+
...options.cursor !== undefined && { initialCursor: options.cursor },
|
|
2255
|
+
maxBufferedFrames,
|
|
2256
|
+
maxFrameBytes,
|
|
2257
|
+
...options.signal !== undefined && { signal: options.signal },
|
|
2258
|
+
onGrantCredits: (credits) => handle.grantCredits(credits),
|
|
2259
|
+
onClose: (reason) => handle.close(reason)
|
|
2260
|
+
});
|
|
2261
|
+
for (const event of pendingEvents.splice(0)) {
|
|
2262
|
+
directConsumer.push(event);
|
|
2263
|
+
}
|
|
2264
|
+
if (preAttachOverflow) {
|
|
2265
|
+
directConsumer.fail(new DeviceRelayError("STREAM_OVERFLOW", `Relay stream exceeded its ${maxBufferedFrames}-frame buffer limit`, { retryable: false, deviceId: options.deviceId }));
|
|
2266
|
+
handle.close("overflow");
|
|
2267
|
+
}
|
|
2268
|
+
return directConsumer.stream;
|
|
2269
|
+
}
|
|
2270
|
+
async function openRelayStreamOnHub(ctx, options) {
|
|
2271
|
+
if (ctx.isClosed())
|
|
2272
|
+
throw new DeviceRelayError("CLOSED", "Device relay hub is closed");
|
|
2273
|
+
const openTimeoutMs = options.openTimeoutMs ?? ctx.defaultRpcTimeoutMs;
|
|
2274
|
+
const maxBufferedFrames = options.maxBufferedFrames ?? ctx.defaultMaxBufferedFrames;
|
|
2275
|
+
const maxFrameBytes = options.maxFrameBytes ?? ctx.defaultMaxStreamFrameBytes;
|
|
2276
|
+
assertTimerMs("DeviceRelayStreamOpenOptions.openTimeoutMs", openTimeoutMs);
|
|
2277
|
+
assertPositiveSafeInteger("DeviceRelayStreamOpenOptions.maxBufferedFrames", maxBufferedFrames);
|
|
2278
|
+
assertPositiveSafeInteger("DeviceRelayStreamOpenOptions.maxFrameBytes", maxFrameBytes);
|
|
2279
|
+
if (options.signal?.aborted)
|
|
2280
|
+
throw abortReason(options.signal);
|
|
2281
|
+
const device = await ctx.resolveAuthorizedDevice({
|
|
2282
|
+
callerAccountId: options.accountId,
|
|
2283
|
+
deviceId: options.deviceId,
|
|
2284
|
+
kind: "stream",
|
|
2285
|
+
topic: options.topic
|
|
2286
|
+
});
|
|
2287
|
+
if (options.share === true && options.cursor === undefined) {
|
|
2288
|
+
const shareKey = `${options.accountId}:${options.deviceId}:${options.topic}:${serializeCanonicalJson(options.params ?? {})}`;
|
|
2289
|
+
return openSharedRelayStream({
|
|
2290
|
+
ctx,
|
|
2291
|
+
device,
|
|
2292
|
+
options,
|
|
2293
|
+
shareKey,
|
|
2294
|
+
openTimeoutMs,
|
|
2295
|
+
maxBufferedFrames,
|
|
2296
|
+
maxFrameBytes,
|
|
2297
|
+
openUpstream: openUpstreamWithTimeout
|
|
2298
|
+
});
|
|
2299
|
+
}
|
|
2300
|
+
return openDirectRelayStream({
|
|
2301
|
+
ctx,
|
|
2302
|
+
device,
|
|
2303
|
+
options,
|
|
2304
|
+
openTimeoutMs,
|
|
2305
|
+
maxBufferedFrames,
|
|
2306
|
+
maxFrameBytes
|
|
2307
|
+
});
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// src/device-relay/hub.ts
|
|
2311
|
+
function defaultAuthorizeAccess(input) {
|
|
2312
|
+
return input.callerAccountId === input.deviceAccountId;
|
|
2313
|
+
}
|
|
2314
|
+
function validateHubLimits(config) {
|
|
2315
|
+
const leaseTtlMs = config.leaseTtlMs ?? DEFAULT_DEVICE_RELAY_LEASE_TTL_MS;
|
|
2316
|
+
const leaseSweepIntervalMs = config.leaseSweepIntervalMs ?? Math.min(5000, Math.max(25, Math.floor(leaseTtlMs / 3)));
|
|
2317
|
+
const defaultRpcTimeoutMs = config.defaultRpcTimeoutMs ?? DEFAULT_DEVICE_RELAY_RPC_TIMEOUT_MS;
|
|
2318
|
+
const defaultMaxRequestBytes = config.maxRequestBodyBytes ?? DEFAULT_DEVICE_RELAY_MAX_REQUEST_BYTES;
|
|
2319
|
+
const defaultMaxResponseBytes = config.maxResponseBodyBytes ?? DEFAULT_DEVICE_RELAY_MAX_RESPONSE_BYTES;
|
|
2320
|
+
const maxInFlightPerDevice = config.maxInFlightRequestsPerDevice ?? DEFAULT_DEVICE_RELAY_MAX_IN_FLIGHT_RPCS;
|
|
2321
|
+
const maxStreamsPerDevice = config.maxConcurrentStreamsPerDevice ?? DEFAULT_DEVICE_RELAY_MAX_CONCURRENT_STREAMS;
|
|
2322
|
+
const defaultMaxStreamFrameBytes = config.maxStreamFrameBytes ?? DEFAULT_DEVICE_RELAY_MAX_STREAM_FRAME_BYTES;
|
|
2323
|
+
const defaultMaxBufferedFrames = config.maxBufferedStreamFrames ?? DEFAULT_DEVICE_RELAY_MAX_BUFFERED_FRAMES;
|
|
2324
|
+
assertTimerMs("DeviceRelayHubConfig.leaseTtlMs", leaseTtlMs);
|
|
2325
|
+
assertTimerMs("DeviceRelayHubConfig.leaseSweepIntervalMs", leaseSweepIntervalMs);
|
|
2326
|
+
assertTimerMs("DeviceRelayHubConfig.defaultRpcTimeoutMs", defaultRpcTimeoutMs);
|
|
2327
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxRequestBodyBytes", defaultMaxRequestBytes);
|
|
2328
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxResponseBodyBytes", defaultMaxResponseBytes);
|
|
2329
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxInFlightRequestsPerDevice", maxInFlightPerDevice);
|
|
2330
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxConcurrentStreamsPerDevice", maxStreamsPerDevice);
|
|
2331
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxStreamFrameBytes", defaultMaxStreamFrameBytes);
|
|
2332
|
+
assertPositiveSafeInteger("DeviceRelayHubConfig.maxBufferedStreamFrames", defaultMaxBufferedFrames);
|
|
2333
|
+
return {
|
|
2334
|
+
leaseTtlMs,
|
|
2335
|
+
leaseSweepIntervalMs,
|
|
2336
|
+
defaultRpcTimeoutMs,
|
|
2337
|
+
defaultMaxRequestBytes,
|
|
2338
|
+
defaultMaxResponseBytes,
|
|
2339
|
+
maxInFlightPerDevice,
|
|
2340
|
+
maxStreamsPerDevice,
|
|
2341
|
+
defaultMaxStreamFrameBytes,
|
|
2342
|
+
defaultMaxBufferedFrames
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
function createDeviceRelayHub(config) {
|
|
2346
|
+
const limits = validateHubLimits(config);
|
|
2347
|
+
const instanceId = config.instanceId ?? `relay-${crypto.randomUUID()}`;
|
|
2348
|
+
const broker = config.broker ?? createMemoryRelayBroker();
|
|
2349
|
+
const now = config.now ?? (() => Date.now());
|
|
2350
|
+
const authorize = config.authorizeAccess ?? defaultAuthorizeAccess;
|
|
2351
|
+
const localDevices = new Map;
|
|
2352
|
+
const sharedStreams = new Map;
|
|
2353
|
+
const socketCleanups = new Set;
|
|
2354
|
+
let closed = false;
|
|
2355
|
+
const runtime = {
|
|
2356
|
+
instanceId,
|
|
2357
|
+
broker,
|
|
2358
|
+
config,
|
|
2359
|
+
leaseTtlMs: limits.leaseTtlMs,
|
|
2360
|
+
maxInFlightPerDevice: limits.maxInFlightPerDevice,
|
|
2361
|
+
maxStreamsPerDevice: limits.maxStreamsPerDevice,
|
|
2362
|
+
now,
|
|
2363
|
+
localDevices,
|
|
2364
|
+
socketCleanups,
|
|
2365
|
+
logger: config.logger,
|
|
2366
|
+
isClosed: () => closed,
|
|
2367
|
+
notifyState(state) {
|
|
2368
|
+
try {
|
|
2369
|
+
config.onDeviceStateChange?.(state);
|
|
2370
|
+
} catch (error) {
|
|
2371
|
+
config.logger?.warn("DeviceRelayHub onDeviceStateChange threw", { error });
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
};
|
|
2375
|
+
const unbindBroker = broker.bindInstance(instanceId, {
|
|
2376
|
+
executeLocalRpc: (deviceId, request, signal) => executeLocalDeviceRpc(runtime, deviceId, request, signal),
|
|
2377
|
+
openLocalStream: (deviceId, request, sink, signal) => openLocalDeviceStream(runtime, deviceId, request, sink, signal)
|
|
2378
|
+
});
|
|
2379
|
+
const sweepExpiredLeases = async () => {
|
|
2380
|
+
const currentNow = now();
|
|
2381
|
+
const expired = [];
|
|
2382
|
+
for (const [deviceId, session] of localDevices) {
|
|
2383
|
+
if (currentNow >= session.state.leaseExpiresAt)
|
|
2384
|
+
expired.push([deviceId, session]);
|
|
2385
|
+
}
|
|
2386
|
+
for (const [deviceId, session] of expired) {
|
|
2387
|
+
await teardownLocalDevice(runtime, deviceId, session, "lease-expired");
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
const sweepTimer = setInterval(() => {
|
|
2391
|
+
observeHubBackground(runtime.logger, "sweepExpiredLeases", sweepExpiredLeases);
|
|
2392
|
+
}, limits.leaseSweepIntervalMs);
|
|
2393
|
+
sweepTimer.unref?.();
|
|
2394
|
+
const resolveAuthorizedDevice = async (access) => {
|
|
2395
|
+
await sweepExpiredLeases();
|
|
2396
|
+
const record = await broker.lookupDevice(access.deviceId);
|
|
2397
|
+
if (!record) {
|
|
2398
|
+
const allowedMissing = await authorize({
|
|
2399
|
+
...access,
|
|
2400
|
+
deviceAccountId: access.callerAccountId
|
|
2401
|
+
});
|
|
2402
|
+
if (!allowedMissing) {
|
|
2403
|
+
throw new DeviceRelayError("FORBIDDEN", "Caller is not authorized to access this device", {
|
|
2404
|
+
deviceId: access.deviceId
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
throw new DeviceRelayError("DEVICE_OFFLINE", `Device "${access.deviceId}" is offline`, {
|
|
2408
|
+
delivery: "not-sent",
|
|
2409
|
+
deviceId: access.deviceId
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
const allowed = await authorize({ ...access, deviceAccountId: record.accountId });
|
|
2413
|
+
if (!allowed) {
|
|
2414
|
+
throw new DeviceRelayError("FORBIDDEN", "Caller is not authorized to access this device", {
|
|
2415
|
+
deviceId: access.deviceId
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
if (record.status !== "online" || now() >= record.leaseExpiresAt) {
|
|
2419
|
+
throw new DeviceRelayError("DEVICE_OFFLINE", `Device "${access.deviceId}" is offline`, {
|
|
2420
|
+
delivery: "not-sent",
|
|
2421
|
+
deviceId: access.deviceId
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
return record;
|
|
2425
|
+
};
|
|
2426
|
+
const dispatch = {
|
|
2427
|
+
broker,
|
|
2428
|
+
sharedStreams,
|
|
2429
|
+
defaultRpcTimeoutMs: limits.defaultRpcTimeoutMs,
|
|
2430
|
+
defaultMaxRequestBytes: limits.defaultMaxRequestBytes,
|
|
2431
|
+
defaultMaxResponseBytes: limits.defaultMaxResponseBytes,
|
|
2432
|
+
defaultMaxStreamFrameBytes: limits.defaultMaxStreamFrameBytes,
|
|
2433
|
+
defaultMaxBufferedFrames: limits.defaultMaxBufferedFrames,
|
|
2434
|
+
isClosed: () => closed,
|
|
2435
|
+
resolveAuthorizedDevice
|
|
2436
|
+
};
|
|
2437
|
+
return {
|
|
2438
|
+
instanceId,
|
|
2439
|
+
bindRealtime(server) {
|
|
2440
|
+
return server.onConnection((connection) => {
|
|
2441
|
+
attachDeviceConnection(runtime, connection);
|
|
2442
|
+
});
|
|
2443
|
+
},
|
|
2444
|
+
attachConnection: (connection) => attachDeviceConnection(runtime, connection),
|
|
2445
|
+
async getDevice(accountId, deviceId) {
|
|
2446
|
+
await sweepExpiredLeases();
|
|
2447
|
+
const record = await broker.lookupDevice(deviceId);
|
|
2448
|
+
if (!record || record.accountId !== accountId)
|
|
2449
|
+
return;
|
|
2450
|
+
return record;
|
|
2451
|
+
},
|
|
2452
|
+
async listDevices(accountId) {
|
|
2453
|
+
await sweepExpiredLeases();
|
|
2454
|
+
return broker.listDevicesByAccount(accountId);
|
|
2455
|
+
},
|
|
2456
|
+
createRelayFetch: (options) => buildRelayFetch(dispatch, options),
|
|
2457
|
+
openRelayStream: (options) => openRelayStreamOnHub(dispatch, options),
|
|
2458
|
+
sweepExpiredLeases,
|
|
2459
|
+
async close() {
|
|
2460
|
+
if (closed)
|
|
2461
|
+
return;
|
|
2462
|
+
closed = true;
|
|
2463
|
+
clearInterval(sweepTimer);
|
|
2464
|
+
unbindBroker();
|
|
2465
|
+
for (const cleanup of [...socketCleanups])
|
|
2466
|
+
cleanup();
|
|
2467
|
+
for (const [deviceId, session] of [...localDevices]) {
|
|
2468
|
+
await teardownLocalDevice(runtime, deviceId, session, "closed");
|
|
2469
|
+
}
|
|
2470
|
+
for (const shared of sharedStreams.values()) {
|
|
2471
|
+
shared.closed = true;
|
|
2472
|
+
shared.openController.abort(new DeviceRelayError("CLOSED", "Device relay hub is closed"));
|
|
2473
|
+
shared.handle?.close("hub-closed");
|
|
2474
|
+
}
|
|
2475
|
+
sharedStreams.clear();
|
|
2476
|
+
}
|
|
2477
|
+
};
|
|
2478
|
+
}
|
|
2479
|
+
export {
|
|
2480
|
+
DEFAULT_DEVICE_RELAY_HEARTBEAT_INTERVAL_MS,
|
|
2481
|
+
DEFAULT_DEVICE_RELAY_LEASE_TTL_MS,
|
|
2482
|
+
DEFAULT_DEVICE_RELAY_MAX_BUFFERED_FRAMES,
|
|
2483
|
+
DEFAULT_DEVICE_RELAY_MAX_CONCURRENT_STREAMS,
|
|
2484
|
+
DEFAULT_DEVICE_RELAY_MAX_IN_FLIGHT_RPCS,
|
|
2485
|
+
DEFAULT_DEVICE_RELAY_MAX_REQUEST_BYTES,
|
|
2486
|
+
DEFAULT_DEVICE_RELAY_MAX_RESPONSE_BYTES,
|
|
2487
|
+
DEFAULT_DEVICE_RELAY_MAX_STREAM_FRAME_BYTES,
|
|
2488
|
+
DEFAULT_DEVICE_RELAY_RPC_TIMEOUT_MS,
|
|
2489
|
+
DEVICE_RELAY_ORIGIN,
|
|
2490
|
+
DeviceRelayBodyEncodingSchema,
|
|
2491
|
+
DeviceRelayDeliveryStateSchema,
|
|
2492
|
+
DeviceRelayError,
|
|
2493
|
+
DeviceRelayErrorCodeSchema,
|
|
2494
|
+
DeviceRelayHeaderEntrySchema,
|
|
2495
|
+
DeviceRelayHeartbeatAckSchema,
|
|
2496
|
+
DeviceRelayHeartbeatSchema,
|
|
2497
|
+
DeviceRelayHelloAckSchema,
|
|
2498
|
+
DeviceRelayHelloSchema,
|
|
2499
|
+
DeviceRelayJsonValueSchema,
|
|
2500
|
+
DeviceRelayOfflineReasonSchema,
|
|
2501
|
+
DeviceRelayRpcCancelSchema,
|
|
2502
|
+
DeviceRelayRpcRequestSchema,
|
|
2503
|
+
DeviceRelayRpcResponseSchema,
|
|
2504
|
+
DeviceRelayStateSchema,
|
|
2505
|
+
DeviceRelayStatusSchema,
|
|
2506
|
+
DeviceRelayStreamCloseSchema,
|
|
2507
|
+
DeviceRelayStreamCreditSchema,
|
|
2508
|
+
DeviceRelayStreamEventSchema,
|
|
2509
|
+
DeviceRelayStreamOpenAckSchema,
|
|
2510
|
+
DeviceRelayStreamOpenSchema,
|
|
2511
|
+
createDeviceRelayAgent,
|
|
2512
|
+
createDeviceRelayHub,
|
|
2513
|
+
createMemoryRelayBroker,
|
|
2514
|
+
deviceRelayRealtimeContract,
|
|
2515
|
+
isDeviceRelayRetryableCode,
|
|
2516
|
+
isRetryableDeviceRelayError
|
|
2517
|
+
};
|