@agentmatrix.pro/browser-sdk 0.0.0-stage → 0.1.0-rc.2

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 ADDED
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-rc.2
4
+
5
+ _Release prepared 2026-10-30 for the official npm `next` channel._
6
+
7
+ Requires Platform `0.160.0`. The matching API contract is deployed in AgentMatrix
8
+ `release-2026-10-30.3`; Guest/profile/Worker enablement and real takeover
9
+ qualification remain pending. This package stays a prerelease.
10
+
11
+ - Support backend owner-bound API keys for get/acquire/release without UserJWT or CSRF (Platform 0.160.0).
12
+ - Add one-use `BrowserViewer.takeAccess()` and `createBrowserViewer()` for authenticated backend-to-frontend capability transfer; keep API keys off the frontend.
13
+ - Preserve Workspace authentication, single-attempt transport, explicit handback, and unknown-result readback.
14
+
15
+ ## 0.1.0-rc.1
16
+
17
+ First AgentMatrix browser SDK prerelease, prepared for the official npm `next`
18
+ channel. Requires Platform `0.159.1` with browser control enabled and the calling
19
+ Workspace origin allowed. Real Identity/Guest enablement qualification remains
20
+ pending; installing the package does not enable the server feature or exit Q0.
21
+
22
+ - Keep `BrowserViewer` type-only in built declarations, matching the runtime exports.
23
+ - Refuse attachment after `stopInput()` and enforce the contract's 8192-byte JWT limit before transport.
24
+ - Adopt Platform `0.159.1` error metadata, preserving both Gateway refusals and wrapped Workspace `error.details` responses.
25
+
26
+ - Add human-authorized original-browser status, acquisition and handback with single-attempt transport and an iframe grant helper.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 AgentOS Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # AgentMatrix browser control
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Owner-authorized control of an existing Agent browser. Applications can use an
4
+ owner-bound data-plane API key on their backend; users do not need a separate
5
+ AgentMatrix login. Existing Workspace JWT + selected key ID + CSRF calls remain
6
+ supported.
7
+
8
+ This source targets **Platform 0.160.0**. The API-key path and capability transfer
9
+ are introduced in `@agentmatrix.pro/browser-sdk@0.1.0-rc.2`; the earlier
10
+ `0.1.0-rc.1` does not include them. Install that exact prerelease for integration:
11
+
12
+ ```bash
13
+ npm install @agentmatrix.pro/browser-sdk@0.1.0-rc.2
14
+ ```
15
+
16
+ The deployment must enable browser control and approve the frontend's exact
17
+ parent origin in both Guest and Preview configuration. Installing the SDK does
18
+ not enable the server feature or exit Q0. This remains a prerelease while real
19
+ Identity/Guest enablement qualification is pending.
20
+
21
+ ## Backend with an API key
22
+
23
+ Keep the key on your server. It must belong to the Session owner, include
24
+ `session.full`, and permit the selected namespace. Tenant and owner are derived
25
+ from the verified key; do not supply a JWT, tenant ID, key ID or CSRF token.
26
+
27
+ ```ts
28
+ import { BrowserControlClient } from "@agentmatrix.pro/browser-sdk";
29
+
30
+ const control = new BrowserControlClient({ baseURL: gatewayOrigin });
31
+ const context = { apiKey: serverSecret, sessionId, namespaceId: "default" };
32
+ const current = await control.get(context);
33
+ // In your endpoint, authorize the application's own user for this Session first.
34
+ // Only continue for an explicit takeover action. Persist/reuse its operation ID.
35
+ if (current.data.allowed_actions.includes("acquire") && current.data.control_id) {
36
+ const result = await control.acquire(context, {
37
+ operation_id: operationId,
38
+ expected_control_id: current.data.control_id,
39
+ expected_revision: current.data.revision,
40
+ });
41
+ const response = {
42
+ data: result.data,
43
+ viewer_access: result.viewer?.takeAccess(),
44
+ };
45
+ // Return response only to that authenticated user over HTTPS, Cache-Control: no-store.
46
+ // It contains a short-lived secret: never log, cache or persist it.
47
+ }
48
+ ```
49
+
50
+ Omitting `namespaceId` uses the deployment's ordinary API-key default namespace.
51
+ The SDK sends only Bearer authentication, the contract version and the optional
52
+ namespace, with `credentials: omit`. It never exchanges the key for a user JWT.
53
+ A key authorizes its owner, not arbitrary users of your application: your backend
54
+ must enforce its own Session access checks before returning a viewer capability.
55
+
56
+ ## Frontend with the transferred capability
57
+
58
+ ```ts
59
+ import { createBrowserViewer } from "@agentmatrix.pro/browser-sdk";
60
+
61
+ // Received from your authenticated backend; never contains the API key.
62
+ const viewer = createBrowserViewer(response.viewer_access);
63
+ viewer.attach(iframe); // once, on a deployment-approved parent origin
64
+ // Keep viewer and the original control_id in memory for handback.
65
+ ```
66
+
67
+ `takeAccess()` consumes an unused handle once and returns `{ url, token,
68
+ expires_at }`. The returned object intentionally contains secrets; ordinary
69
+ handle serialization and Node inspection remain redacted. After transfer, the
70
+ original handle can neither attach nor export again. `createBrowserViewer`
71
+ validates and copies that capability; it does not mint, renew, reacquire or prove
72
+ server authorization. Do not duplicate it for multiple clients or put it in a
73
+ URL, log, localStorage, sessionStorage or persistent application state.
74
+
75
+ The helper binds both message source and exact viewer origin, delivers the token
76
+ once, and keeps it out of the iframe URL. The Preview URL itself is sensitive.
77
+ Grant expiry stops input and hides the frame while leaving the cleanup connection
78
+ alive. Use `viewer.expiresAt`, together with the latest lease, for local input
79
+ expiry. On unknown/stale state, also call `stopInput()`.
80
+
81
+ ## Existing Workspace authentication
82
+
83
+ Workspace applications can continue to call the same client directly with their
84
+ current authenticated user/scope context:
85
+
86
+ ```ts
87
+ const context = { userJWT, tenantId, namespaceId, apiKeyId, sessionId, csrfToken };
88
+ const current = await control.get(context);
89
+ // acquire/release use the same intent fields as the backend API-key example.
90
+ ```
91
+
92
+ This selects the Workspace routes with `credentials: include`. The key **ID** is
93
+ not a key secret; mutations require the existing matching CSRF cookie/header.
94
+ The SDK does not sign users in, refresh credentials, select tenants/keys, create
95
+ browsers or configure CORS/cookies. Mixing API-key and JWT context fields is
96
+ rejected before transport.
97
+
98
+ ## Handback and failed replies
99
+
100
+ On explicit handback, first call `viewer.stopInput()` on the frontend. Keep the
101
+ iframe mounted. Your backend reads a fresh status for the **original control_id**
102
+ and calls `release(context, { operation_id, expected_control_id,
103
+ expected_revision, lease_id })` using that observation. If the control changed,
104
+ discard the old intent rather than switching it to another browser.
105
+
106
+ A `202` or `revoking` state retains responsibility: the iframe must receive the
107
+ Guest's real clear challenge. After confirmed Agent handback, call
108
+ `viewer.dispose()`. When `allowed_actions` includes `release`, offer an explicit
109
+ **Continue handback** action using a fresh observation and a new user intent.
110
+ Do not automatically change operation IDs or resend mutations. A replay never
111
+ reconstructs a viewer; `takeAccess()` cannot recover a lost response.
112
+
113
+ Each `get`, `acquire` or `release` makes one HTTP attempt, with no implicit retry,
114
+ authentication refresh, polling or generated operation ID. Defaults are a
115
+ 15-second read and 200-second mutation total deadline; per-call
116
+ `{ signal, timeoutMs }` includes headers and the complete body. An injected
117
+ `fetch` must also avoid hidden retries. A proxy in your application must allow
118
+ this mutation budget.
119
+
120
+ `BrowserControlError` exposes only a bounded code, optional status and reason.
121
+ After dispatch, a lost, timed-out or cancelled reply has `replyUnproven: true`:
122
+ read state before offering another action. A refusal cannot clear earlier debt.
123
+ The legacy reason `browser_control_human_required` also covers insufficient
124
+ API-key owner/scope/current authority; it does not require an API-key caller to log in.
125
+ HTTP 202, expiry, iframe closure and native browser closure do not prove handback.
126
+
127
+ `BrowserViewer` is a TypeScript interface, with no runtime constructor or
128
+ `instanceof` value. `stopInput()` before attachment permanently prevents that
129
+ handle from attaching or transferring. `dispose()` is local teardown, not server
130
+ cleanup proof. On user, tenant or Session changes, cancel calls, discard late
131
+ replies and dispose the old viewer; the server retains unresolved responsibility.
132
+
133
+ The root data-plane SDK still provides the convenient read-only
134
+ `AgentMatrix.sessions.browserControl.get(sessionId)`. Use this separate browser package
135
+ for API-key or Workspace control and iframe handling; Tenant Management grants
136
+ no browser control.
@@ -0,0 +1,272 @@
1
+ type components = {
2
+ schemas: {
3
+ BrowserControlReadResponse: {
4
+ data: components["schemas"]["BrowserControlStatus"];
5
+ };
6
+ /** @description Safe business projection. It never includes a viewer grant, page data, physical/Worker/envd coordinates or management credentials. A closed original context is not physical release or writer-drain proof. */
7
+ BrowserControlStatus: {
8
+ session_id: string;
9
+ /** @description SM logical control identity, never a physical handle or Guest browser ID. Null before a control slot exists. */
10
+ control_id: string | null;
11
+ /**
12
+ * Format: int64
13
+ * @description SM durable control/intent CAS revision. Upstream observations and action availability still require fresh checks.
14
+ */
15
+ revision: number;
16
+ state: components["schemas"]["BrowserControlState"];
17
+ lease: components["schemas"]["BrowserControlLease"] | null;
18
+ reason: components["schemas"]["BrowserControlReason"] | null;
19
+ allowed_actions: components["schemas"]["BrowserControlAction"][];
20
+ };
21
+ /**
22
+ * @description Contract-first browser lifecycle model; handlers and activation are delivered separately. Business revision is not a Guest revision or a complete-response ETag.
23
+ * @enum {string}
24
+ */
25
+ BrowserControlState: "unavailable" | "agent" | "acquiring" | "human" | "revoking" | "blocked" | "closed";
26
+ BrowserControlLease: {
27
+ lease_id: string;
28
+ /**
29
+ * Format: date-time
30
+ * @description Conservative server-owned deadline. Expiry revokes human admission; it never returns Agent authority or clears retained debt.
31
+ */
32
+ expires_at: string;
33
+ };
34
+ /** @enum {string} */
35
+ BrowserControlReason: "browser_control_disabled" | "browser_not_open" | "browser_control_unsupported" | "browser_control_busy" | "browser_control_expired" | "browser_control_revoked" | "browser_control_unproven" | "browser_control_viewer_clear_pending" | "browser_control_binding_changed" | "browser_control_closed" | "browser_control_grant_unavailable";
36
+ /**
37
+ * @description Advisory UI action after fresh authorization; never effect authority.
38
+ * @enum {string}
39
+ */
40
+ BrowserControlAction: "acquire" | "release";
41
+ GatewayError: {
42
+ /**
43
+ * @example unauthenticated
44
+ * @enum {string}
45
+ */
46
+ code: "invalid_input" | "unauthenticated" | "permission_denied" | "not_found" | "method_not_allowed" | "conflict" | "rate_limited" | "idempotent_hit" | "invalid_state" | "has_open_turn" | "internal" | "unavailable";
47
+ message: string;
48
+ request_id?: string;
49
+ };
50
+ GatewayOrErrorEnvelope: components["schemas"]["GatewayError"] | components["schemas"]["ErrorEnvelope"];
51
+ ErrorEnvelope: {
52
+ error: {
53
+ /**
54
+ * @example invalid_input
55
+ * @enum {string}
56
+ */
57
+ code: "invalid_input" | "unauthenticated" | "permission_denied" | "not_found" | "method_not_allowed" | "conflict" | "rate_limited" | "idempotent_hit" | "invalid_state" | "has_open_turn" | "internal" | "unavailable" | "invalid_dependency" | "dependency_not_authorized" | "dependency_validation_limit" | "dependency_unavailable" | "idempotency_conflict" | "version_conflict" | "channel_onboarding_disabled" | "adapter_installation_not_found" | "adapter_installation_suspended" | "adapter_installation_archived" | "binding_not_found" | "binding_conflict" | "binding_idempotency_mismatch" | "binding_limit_exceeded" | "reply_anchor_required" | "observed_tip_required" | "invalid_reply_target" | "stale_observed_tip" | "session_not_active" | "stale_interrupt_target" | "interrupt_not_available" | "invalid_tool_action_target" | "tool_action_not_pending" | "persistent_approval_required" | "persistent_approval_denied" | "persistent_approval_expired" | "persistent_approval_idempotency_mismatch" | "persistent_approval_target_changed" | "inbound_idempotency_mismatch" | "inbound_idempotency_expired" | "subscription_not_found" | "subscription_scope_immutable" | "subscription_disabling" | "subscription_disabled" | "subscription_deprovisioning" | "subscription_deprovisioned" | "subscription_quota_exceeded" | "subscription_cursor_invalid" | "delivery_not_found" | "dlq_item_not_found" | "dlq_generation_not_open" | "dlq_operation_idempotency_mismatch" | "link_authorization_denied" | "link_authorization_expired" | "link_authorization_idempotency_mismatch";
58
+ message: string;
59
+ request_id?: string;
60
+ /** @description Optional non-secret structured error details, such as the current optimistic revision. */
61
+ details?: {
62
+ [key: string]: unknown;
63
+ };
64
+ };
65
+ };
66
+ /** @description One explicit user intent. Owner, targets, paths, origins, credentials and TTL are derived by trusted owners, never supplied here. Same-operation readback cannot repeat effects or recover a grant. */
67
+ AcquireBrowserControlRequest: {
68
+ operation_id: string;
69
+ expected_control_id: string;
70
+ /** Format: int64 */
71
+ expected_revision: number;
72
+ };
73
+ BrowserControlAcquireResponse: {
74
+ data: components["schemas"]["BrowserControlStatus"];
75
+ viewer_access?: components["schemas"]["BrowserViewerAccess"];
76
+ };
77
+ /** @description Ephemeral successful-acquisition delivery only. Never returned by status/replay/release, logged, persisted or placed in EventLog. Ordinary Preview authorization is independent and cannot replace this human capability. */
78
+ BrowserViewerAccess: {
79
+ /**
80
+ * Format: uri
81
+ * @description Trusted Preview-owner URL. The human token is never placed in this URL; the parent sends it only to the exact iframe origin.
82
+ */
83
+ url: string;
84
+ /** Format: password */
85
+ token: string;
86
+ /**
87
+ * Format: date-time
88
+ * @description Never later than the business lease or original Guest grant deadline. A caller cannot extend it from receipt time.
89
+ */
90
+ expires_at: string;
91
+ };
92
+ /** @description Revoke the exact original lease. Missing clear/drain evidence retains revoking/blocked state; release is not Session Archive or original-context destruction. */
93
+ ReleaseBrowserControlRequest: {
94
+ operation_id: string;
95
+ expected_control_id: string;
96
+ /** Format: int64 */
97
+ expected_revision: number;
98
+ lease_id: string;
99
+ };
100
+ /** @enum {string} */
101
+ BrowserControlErrorReason: "browser_control_request_invalid" | "browser_control_human_required" | "browser_control_revision_mismatch" | "browser_control_lease_mismatch" | "browser_control_operation_mismatch" | "browser_control_busy" | "browser_control_unproven" | "browser_control_unsupported" | "browser_control_not_ready" | "browser_control_closed";
102
+ };
103
+ responses: {
104
+ /** @description Aggregate tenant public API rate limit exceeded. */
105
+ TenantRateLimit: {
106
+ headers: {
107
+ /** @description Seconds to wait before retrying. */
108
+ "Retry-After"?: number;
109
+ [name: string]: unknown;
110
+ };
111
+ content: {
112
+ "application/json": components["schemas"]["GatewayError"];
113
+ };
114
+ };
115
+ /** @description Gateway admission can return a flat error; Workspace returns an error envelope with optional error.details.reason from BrowserControlErrorReason. A refusal concerns this request only and does not settle earlier browser responsibility. An unknown result requires status readback, never automatic mutation replay. */
116
+ BrowserControlError: {
117
+ headers: {
118
+ [name: string]: unknown;
119
+ };
120
+ content: {
121
+ "application/json": components["schemas"]["GatewayOrErrorEnvelope"];
122
+ };
123
+ };
124
+ };
125
+ parameters: {
126
+ /** @example ssn_01HX... */
127
+ SessionId: string;
128
+ /** @description Tenant selected in the User Dashboard resource URL. Identity verifies that the authenticated user has an active membership in this tenant before forwarding to canonical data-plane APIs. */
129
+ WorkspaceTenantId: string;
130
+ /** @example default */
131
+ NamespaceId: string;
132
+ /** @description Canonical Session identifier to reauthorize under the currently selected key. */
133
+ WorkspaceSessionId: string;
134
+ /** @description Current tenant selected by the browser. Gateway resolves active membership and selected-key ownership before signing the private Workspace hop. */
135
+ WorkspaceCurrentTenantIdHeader: string;
136
+ /** @description Current namespace selected by the browser and authorized against the selected key before the Workspace API is called. */
137
+ WorkspaceNamespaceHeader: string;
138
+ /** @description Dashboard-selected user-owned data-plane API key. Required when calling canonical session event append/stream or approved Volume routes with UserJWT. Ignored for direct `ariadra_*` API-key callers. */
139
+ DashboardAPIKeyIdHeader: string;
140
+ /** @description Required on Workspace state-changing requests and must match the readable `ariadra_csrf_token` cookie. Gateway consumes both values; neither reaches the Workspace API. */
141
+ WorkspaceCSRFTokenHeader: string;
142
+ /** @description Required on Gateway-authenticated Workspace state-changing requests and must match `X-CSRF-Token`. Gateway consumes both values; neither reaches the Workspace API. */
143
+ WorkspaceCSRFTokenCookie: string;
144
+ };
145
+ requestBodies: never;
146
+ headers: never;
147
+ pathItems: never;
148
+ };
149
+
150
+ /** Sensitive short-lived capability. Deliver only to your authenticated frontend; never log or store it. */
151
+ type BrowserViewerAccess = components["schemas"]["BrowserViewerAccess"];
152
+ /** Import a capability delivered by your own trusted backend, without exposing its API key. */
153
+ declare function createBrowserViewer(access: BrowserViewerAccess): BrowserViewer;
154
+ /** Structural DOM types keep Node clients importable without a DOM global or shim. */
155
+ interface BrowserViewerMessage {
156
+ source: unknown;
157
+ origin: string;
158
+ data: unknown;
159
+ }
160
+ interface BrowserViewerWindow {
161
+ addEventListener(type: "message", listener: (event: BrowserViewerMessage) => void): void;
162
+ removeEventListener(type: "message", listener: (event: BrowserViewerMessage) => void): void;
163
+ }
164
+ interface BrowserViewerFrame {
165
+ src: string;
166
+ style: {
167
+ visibility: string;
168
+ };
169
+ contentWindow: {
170
+ postMessage(message: unknown, targetOrigin: string): void;
171
+ } | null;
172
+ ownerDocument: {
173
+ defaultView: BrowserViewerWindow | null;
174
+ };
175
+ setAttribute(name: string, value: string): void;
176
+ removeAttribute(name: string): void;
177
+ blur(): void;
178
+ }
179
+ /** Acquired handle only; no public constructor or runtime BrowserViewer export. */
180
+ interface BrowserViewer {
181
+ readonly expiresAt: string;
182
+ /** Consume once for an authenticated backend-to-frontend response. The returned value contains secrets. */
183
+ takeAccess(): BrowserViewerAccess;
184
+ /** Attach once, before the iframe loads. */
185
+ attach(frame: BrowserViewerFrame): void;
186
+ /** Stop local input while retaining the iframe for the Guest's actual clear ACK. */
187
+ stopInput(): void;
188
+ /** Local teardown only; never proof of handback or settled server responsibility. */
189
+ dispose(): void;
190
+ toJSON(): string;
191
+ }
192
+
193
+ type BrowserControlStatus = components["schemas"]["BrowserControlStatus"];
194
+ type BrowserControlState = components["schemas"]["BrowserControlState"];
195
+ type BrowserControlAction = components["schemas"]["BrowserControlAction"];
196
+ type BrowserControlReason = components["schemas"]["BrowserControlReason"];
197
+ type BrowserControlErrorReason = components["schemas"]["BrowserControlErrorReason"];
198
+ type AcquireBrowserControlRequest = components["schemas"]["AcquireBrowserControlRequest"];
199
+ type ReleaseBrowserControlRequest = components["schemas"]["ReleaseBrowserControlRequest"];
200
+ /** One current user/context snapshot. Never pass a data-plane API key as userJWT. */
201
+ interface BrowserControlContext {
202
+ userJWT: string;
203
+ tenantId: string;
204
+ namespaceId: string;
205
+ apiKeyId: string;
206
+ sessionId: string;
207
+ }
208
+ interface BrowserControlMutationContext extends BrowserControlContext {
209
+ /** Must match the browser's ariadra_csrf_token cookie on the Gateway origin. */
210
+ csrfToken: string;
211
+ }
212
+ /** Server-side API-key context. Never pass this credential to a user browser. */
213
+ interface BrowserControlAPIKeyContext {
214
+ apiKey: string;
215
+ sessionId: string;
216
+ /** Omission uses the key's default namespace routing. */
217
+ namespaceId?: string;
218
+ userJWT?: never;
219
+ tenantId?: never;
220
+ apiKeyId?: never;
221
+ csrfToken?: never;
222
+ }
223
+ interface BrowserControlRequestOptions {
224
+ signal?: AbortSignal;
225
+ /** Total budget including the complete response body. Defaults to 15s read / 200s mutation. */
226
+ timeoutMs?: number;
227
+ }
228
+ interface BrowserControlResult {
229
+ status: 200 | 202;
230
+ data: BrowserControlStatus;
231
+ replayed: boolean;
232
+ }
233
+ interface BrowserControlAcquisition extends BrowserControlResult {
234
+ status: 200;
235
+ /** Present only on a fresh successful acquisition. Not serializable or reusable. */
236
+ viewer?: BrowserViewer;
237
+ }
238
+ interface BrowserControlClientOptions {
239
+ /** Exact Gateway origin, HTTPS except local development. No implicit hosted default. */
240
+ baseURL: string;
241
+ /** Must implement a single fetch attempt, without authentication refresh or retries. */
242
+ fetch?: typeof globalThis.fetch;
243
+ }
244
+
245
+ /** Owner-authorized client. No cached context, automatic reads, retries, grants or operation IDs. */
246
+ declare class BrowserControlClient {
247
+ #private;
248
+ constructor(options: BrowserControlClientOptions);
249
+ get(context: BrowserControlContext | BrowserControlAPIKeyContext, options?: BrowserControlRequestOptions): Promise<BrowserControlResult>;
250
+ acquire(context: BrowserControlMutationContext | BrowserControlAPIKeyContext, intent: AcquireBrowserControlRequest, options?: BrowserControlRequestOptions): Promise<BrowserControlAcquisition>;
251
+ release(context: BrowserControlMutationContext | BrowserControlAPIKeyContext, intent: ReleaseBrowserControlRequest, options?: BrowserControlRequestOptions): Promise<BrowserControlResult>;
252
+ }
253
+
254
+ type BrowserControlFailure = "invalid_input" | "aborted" | "timeout" | "transport_unproven" | "response_unproven" | "refused";
255
+ /**
256
+ * Contains only bounded classifications: no URL, headers, body, token or peer error/cause.
257
+ * A false replyUnproven does not settle a previous lease or operation. No error authorizes a retry.
258
+ */
259
+ declare class BrowserControlError extends Error {
260
+ readonly code: BrowserControlFailure;
261
+ readonly replyUnproven: boolean;
262
+ readonly status?: number | undefined;
263
+ readonly reason?: BrowserControlErrorReason | undefined;
264
+ readonly name = "BrowserControlError";
265
+ constructor(code: BrowserControlFailure, replyUnproven: boolean, status?: number | undefined, reason?: BrowserControlErrorReason | undefined);
266
+ }
267
+
268
+ declare const CONTRACT_VERSION = "0.160.0";
269
+
270
+ declare const BROWSER_SDK_VERSION = "0.1.0-rc.2";
271
+
272
+ export { type AcquireBrowserControlRequest, BROWSER_SDK_VERSION, type BrowserControlAPIKeyContext, type BrowserControlAcquisition, type BrowserControlAction, BrowserControlClient, type BrowserControlClientOptions, type BrowserControlContext, BrowserControlError, type BrowserControlErrorReason, type BrowserControlFailure, type BrowserControlMutationContext, type BrowserControlReason, type BrowserControlRequestOptions, type BrowserControlResult, type BrowserControlState, type BrowserControlStatus, type BrowserViewer, type BrowserViewerAccess, type BrowserViewerFrame, type BrowserViewerMessage, type BrowserViewerWindow, CONTRACT_VERSION, type ReleaseBrowserControlRequest, createBrowserViewer };
package/dist/index.js ADDED
@@ -0,0 +1,442 @@
1
+ // ../../packages/browser-sdk/src/errors.ts
2
+ var BrowserControlError = class extends Error {
3
+ constructor(code, replyUnproven, status, reason) {
4
+ super(`Browser control request failed: ${code}.`);
5
+ this.code = code;
6
+ this.replyUnproven = replyUnproven;
7
+ this.status = status;
8
+ this.reason = reason;
9
+ }
10
+ code;
11
+ replyUnproven;
12
+ status;
13
+ reason;
14
+ name = "BrowserControlError";
15
+ };
16
+
17
+ // ../../packages/browser-sdk/src/generated/contract-version.ts
18
+ var CONTRACT_VERSION = "0.160.0";
19
+
20
+ // ../../packages/browser-sdk/src/validation.ts
21
+ var identifier = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
22
+ var reasons = [
23
+ "browser_control_disabled",
24
+ "browser_not_open",
25
+ "browser_control_unsupported",
26
+ "browser_control_busy",
27
+ "browser_control_expired",
28
+ "browser_control_revoked",
29
+ "browser_control_unproven",
30
+ "browser_control_viewer_clear_pending",
31
+ "browser_control_binding_changed",
32
+ "browser_control_closed",
33
+ "browser_control_grant_unavailable"
34
+ ];
35
+ var errorReasons = [
36
+ "browser_control_request_invalid",
37
+ "browser_control_human_required",
38
+ "browser_control_revision_mismatch",
39
+ "browser_control_lease_mismatch",
40
+ "browser_control_operation_mismatch",
41
+ "browser_control_busy",
42
+ "browser_control_unproven",
43
+ "browser_control_unsupported",
44
+ "browser_control_not_ready",
45
+ "browser_control_closed"
46
+ ];
47
+ var record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
48
+ var id = (v) => typeof v === "string" && identifier.test(v);
49
+ var date = (v) => typeof v === "string" && v.length <= 64 && Number.isFinite(Date.parse(v));
50
+ var keys = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
51
+ function invalidInput() {
52
+ throw new BrowserControlError("invalid_input", false);
53
+ }
54
+ function secret(v, max) {
55
+ return typeof v === "string" && v.length > 0 && v.length <= max && /^[\x21-\x7e]+$/.test(v);
56
+ }
57
+ function contextPath(c, mutation) {
58
+ if (record(c) && "apiKey" in c) {
59
+ if (!keys(c, ["apiKey", "sessionId", "namespaceId"]) || !secret(c.apiKey, 8192) || !id(c.sessionId) || c.namespaceId !== void 0 && (typeof c.namespaceId !== "string" || c.namespaceId.length > 63 || !/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(c.namespaceId)))
60
+ invalidInput();
61
+ return `/v1/sessions/${encodeURIComponent(c.sessionId)}/browser-control`;
62
+ }
63
+ if (!record(c) || !secret(c.userJWT, 8192) || typeof c.tenantId !== "string" || !/^tnt_[0-9A-HJKMNP-TV-Z]{26}$/.test(c.tenantId) || typeof c.apiKeyId !== "string" || !/^ak_[0-9A-HJKMNP-TV-Z]{26}$/.test(c.apiKeyId) || typeof c.namespaceId !== "string" || c.namespaceId.length > 63 || !/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(c.namespaceId) || !id(c.sessionId) || mutation && !secret(c.csrfToken, 8192))
64
+ invalidInput();
65
+ return `/v1/users/me/resources/t/${encodeURIComponent(c.tenantId)}/n/${encodeURIComponent(c.namespaceId)}/sessions/${encodeURIComponent(c.sessionId)}/browser-control`;
66
+ }
67
+ function validateViewerAccess(value) {
68
+ if (!record(value) || !keys(value, ["url", "token", "expires_at"]) || typeof value.url !== "string" || value.url.length > 8192 || typeof value.token !== "string" || !/^[a-f0-9]{64}$/.test(value.token) || !date(value.expires_at) || Date.parse(value.expires_at) <= Date.now())
69
+ invalidInput();
70
+ try {
71
+ const url = new URL(value.url);
72
+ if (!safeURL(url) || url.hash || decodeURIComponent(value.url).includes(value.token))
73
+ invalidInput();
74
+ } catch {
75
+ invalidInput();
76
+ }
77
+ return { url: value.url, token: value.token, expires_at: value.expires_at };
78
+ }
79
+ function validateIntent(value, release) {
80
+ if (!record(value) || !keys(value, [
81
+ "operation_id",
82
+ "expected_control_id",
83
+ "expected_revision",
84
+ ...release ? ["lease_id"] : []
85
+ ]) || !id(value.operation_id) || !id(value.expected_control_id) || !Number.isSafeInteger(value.expected_revision) || value.expected_revision < 1 || release && !id(value.lease_id))
86
+ invalidInput();
87
+ return {
88
+ operation_id: value.operation_id,
89
+ expected_control_id: value.expected_control_id,
90
+ expected_revision: value.expected_revision,
91
+ ...release ? { lease_id: value.lease_id } : {}
92
+ };
93
+ }
94
+ function parseReply(value, sessionId, allowGrant) {
95
+ const invalid = () => {
96
+ throw new BrowserControlError("response_unproven", true);
97
+ };
98
+ if (!record(value) || !keys(value, ["data", ...allowGrant ? ["viewer_access"] : []]) || !record(value.data))
99
+ return invalid();
100
+ const s = value.data;
101
+ if (!keys(s, [
102
+ "session_id",
103
+ "control_id",
104
+ "revision",
105
+ "state",
106
+ "lease",
107
+ "reason",
108
+ "allowed_actions"
109
+ ]) || s.session_id !== sessionId || !id(s.session_id) || !Number.isSafeInteger(s.revision) || s.revision < 0 || s.control_id !== null && !id(s.control_id) || s.reason !== null && !reasons.includes(s.reason) || !Array.isArray(s.allowed_actions) || s.allowed_actions.length > 1)
110
+ return invalid();
111
+ const lease = s.lease;
112
+ if (lease !== null && (!record(lease) || !keys(lease, ["lease_id", "expires_at"]) || !id(lease.lease_id) || !date(lease.expires_at)))
113
+ return invalid();
114
+ let action;
115
+ switch (s.state) {
116
+ case "unavailable":
117
+ if (lease !== null || s.reason === null || (s.control_id === null ? s.revision !== 0 : s.revision < 1))
118
+ return invalid();
119
+ break;
120
+ case "agent":
121
+ if (lease !== null || s.reason !== null) return invalid();
122
+ action = "acquire";
123
+ break;
124
+ case "acquiring":
125
+ case "human":
126
+ case "revoking":
127
+ if (lease === null || s.state === "human" && s.reason !== null)
128
+ return invalid();
129
+ action = "release";
130
+ break;
131
+ case "blocked":
132
+ case "closed":
133
+ if (s.reason === null) return invalid();
134
+ break;
135
+ default:
136
+ return invalid();
137
+ }
138
+ if (s.state !== "unavailable" && (!id(s.control_id) || s.revision < 1) || s.allowed_actions.some((a) => a !== action))
139
+ return invalid();
140
+ const result = {
141
+ data: s
142
+ };
143
+ if (value.viewer_access !== void 0) {
144
+ const v = value.viewer_access;
145
+ if (!allowGrant || s.state !== "human" || !record(lease) || !record(v) || !keys(v, ["url", "token", "expires_at"]) || typeof v.token !== "string" || !/^[a-f0-9]{64}$/.test(v.token) || !date(v.expires_at) || Date.parse(v.expires_at) > Date.parse(lease.expires_at) || typeof v.url !== "string" || v.url.length > 8192)
146
+ return invalid();
147
+ try {
148
+ const url = new URL(v.url);
149
+ if (!safeURL(url) || url.hash || decodeURIComponent(v.url).includes(v.token))
150
+ return invalid();
151
+ } catch {
152
+ return invalid();
153
+ }
154
+ result.access = v;
155
+ }
156
+ return result;
157
+ }
158
+ function safeURL(url) {
159
+ return !url.username && !url.password && (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname));
160
+ }
161
+
162
+ // ../../packages/browser-sdk/src/viewer.ts
163
+ function createBrowserViewer(access) {
164
+ return new BrowserViewerHandle(validateViewerAccess(access));
165
+ }
166
+ var BrowserViewerHandle = class {
167
+ expiresAt;
168
+ #url;
169
+ #token;
170
+ #frame;
171
+ #detach;
172
+ #timer;
173
+ #used = false;
174
+ /** @internal Created only from a validated fresh acquisition reply. */
175
+ constructor(access) {
176
+ this.expiresAt = access.expires_at;
177
+ this.#url = access.url;
178
+ this.#token = access.token;
179
+ }
180
+ takeAccess() {
181
+ if (this.#used || !this.#token || Date.parse(this.expiresAt) <= Date.now())
182
+ throw new BrowserControlError("invalid_input", false);
183
+ const access = {
184
+ url: this.#url,
185
+ token: this.#token,
186
+ expires_at: this.expiresAt
187
+ };
188
+ this.#used = true;
189
+ this.#url = "";
190
+ this.#token = void 0;
191
+ return access;
192
+ }
193
+ /** Attach once, before the iframe loads. Use the exact Workspace origin approved by the deployment. */
194
+ attach(frame) {
195
+ if (this.#used || !frame.ownerDocument.defaultView || Date.parse(this.expiresAt) <= Date.now()) {
196
+ throw new BrowserControlError("invalid_input", false);
197
+ }
198
+ this.#used = true;
199
+ this.#frame = frame;
200
+ const owner = frame.ownerDocument.defaultView;
201
+ const origin = new URL(this.#url).origin;
202
+ const receive = (event) => {
203
+ if (!this.#token || event.source !== frame.contentWindow || event.origin !== origin || !event.data || typeof event.data !== "object" || !("type" in event.data) || event.data.type !== "ariadra-browser-ready")
204
+ return;
205
+ if (Date.now() >= Date.parse(this.expiresAt)) {
206
+ this.stopInput();
207
+ return;
208
+ }
209
+ const token = this.#token;
210
+ this.#token = void 0;
211
+ frame.contentWindow?.postMessage(
212
+ { type: "ariadra-browser-grant", token },
213
+ origin
214
+ );
215
+ };
216
+ owner.addEventListener("message", receive);
217
+ this.#detach = () => owner.removeEventListener("message", receive);
218
+ frame.setAttribute(
219
+ "sandbox",
220
+ "allow-scripts allow-same-origin allow-forms"
221
+ );
222
+ frame.setAttribute("referrerpolicy", "no-referrer");
223
+ frame.removeAttribute("inert");
224
+ frame.style.visibility = "visible";
225
+ this.#timer = setTimeout(
226
+ () => this.stopInput(),
227
+ Math.min(Date.parse(this.expiresAt) - Date.now(), 2147483647)
228
+ );
229
+ frame.src = this.#url;
230
+ this.#url = "";
231
+ }
232
+ /** Call before release, on lost/unknown status, expiry or scope change. Keeps the iframe alive for real clear ACK. */
233
+ stopInput() {
234
+ this.#used = true;
235
+ this.#token = void 0;
236
+ this.#detach?.();
237
+ this.#detach = void 0;
238
+ clearTimeout(this.#timer);
239
+ this.#timer = void 0;
240
+ if (this.#frame) {
241
+ this.#frame.setAttribute("inert", "");
242
+ this.#frame.style.visibility = "hidden";
243
+ this.#frame.blur();
244
+ }
245
+ }
246
+ /** Local teardown only: never means handback, clear ACK or server debt settlement. */
247
+ dispose() {
248
+ this.stopInput();
249
+ this.#used = true;
250
+ this.#url = "";
251
+ if (this.#frame) this.#frame.src = "about:blank";
252
+ this.#frame = void 0;
253
+ }
254
+ toJSON() {
255
+ return "[REDACTED BrowserViewer]";
256
+ }
257
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
258
+ return this.toJSON();
259
+ }
260
+ };
261
+
262
+ // ../../packages/browser-sdk/src/client.ts
263
+ var BrowserControlClient = class {
264
+ #origin;
265
+ #fetch;
266
+ constructor(options) {
267
+ try {
268
+ const url = new URL(options.baseURL);
269
+ if (!safeURL(url) || url.origin !== options.baseURL) invalidInput();
270
+ this.#origin = url.origin;
271
+ } catch {
272
+ invalidInput();
273
+ }
274
+ this.#fetch = options.fetch ?? globalThis.fetch;
275
+ if (typeof this.#fetch !== "function") invalidInput();
276
+ }
277
+ async get(context, options = {}) {
278
+ return this.#request("get", context, void 0, options);
279
+ }
280
+ async acquire(context, intent, options = {}) {
281
+ return this.#request(
282
+ "acquire",
283
+ context,
284
+ intent,
285
+ options
286
+ );
287
+ }
288
+ async release(context, intent, options = {}) {
289
+ return this.#request("release", context, intent, options);
290
+ }
291
+ async #request(action, context, intent, options) {
292
+ const mutation = action !== "get";
293
+ const path = contextPath(context, mutation);
294
+ const frozenIntent = mutation ? validateIntent(intent, action === "release") : void 0;
295
+ const timeoutMs = options.timeoutMs ?? (mutation ? 2e5 : 15e3);
296
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5)
297
+ invalidInput();
298
+ if (options.signal?.aborted)
299
+ throw new BrowserControlError("aborted", false);
300
+ const sessionId = context.sessionId;
301
+ const apiKey = "apiKey" in context;
302
+ const headers = new Headers({
303
+ accept: "application/json",
304
+ authorization: `Bearer ${apiKey ? context.apiKey : context.userJWT}`,
305
+ "x-ariadra-api-version": CONTRACT_VERSION
306
+ });
307
+ if (context.namespaceId !== void 0)
308
+ headers.set("x-ariadra-namespace-id", context.namespaceId);
309
+ if (!apiKey) {
310
+ headers.set("x-ariadra-current-tenant-id", context.tenantId);
311
+ headers.set("x-ariadra-dashboard-api-key-id", context.apiKeyId);
312
+ }
313
+ if (mutation) {
314
+ headers.set("content-type", "application/json");
315
+ if (!apiKey)
316
+ headers.set(
317
+ "x-csrf-token",
318
+ context.csrfToken
319
+ );
320
+ }
321
+ const body = frozenIntent ? JSON.stringify(frozenIntent) : void 0;
322
+ const expectedControl = frozenIntent?.expected_control_id;
323
+ const expectedRevision = frozenIntent?.expected_revision;
324
+ const controller = new AbortController();
325
+ let submitted = false;
326
+ let rejectDeadline = () => {
327
+ };
328
+ const deadline = new Promise((_, reject) => {
329
+ rejectDeadline = reject;
330
+ });
331
+ const stop = (code) => {
332
+ rejectDeadline(new BrowserControlError(code, submitted));
333
+ controller.abort();
334
+ };
335
+ const aborted = () => stop("aborted");
336
+ const timer = setTimeout(() => stop("timeout"), timeoutMs);
337
+ options.signal?.addEventListener("abort", aborted, { once: true });
338
+ const perform = async () => {
339
+ submitted = true;
340
+ let response;
341
+ try {
342
+ const request = {
343
+ method: mutation ? "POST" : "GET",
344
+ headers,
345
+ ...body === void 0 ? {} : { body },
346
+ cache: "no-store",
347
+ credentials: apiKey ? "omit" : "include",
348
+ redirect: "error",
349
+ signal: controller.signal
350
+ };
351
+ response = await this.#fetch(
352
+ `${this.#origin}${path}${mutation ? `/${action}` : ""}`,
353
+ request
354
+ );
355
+ } catch {
356
+ throw new BrowserControlError("transport_unproven", true);
357
+ }
358
+ const allowed = response.status === 200 || action === "release" && response.status === 202;
359
+ let value;
360
+ try {
361
+ value = JSON.parse(await readBody(response, controller.signal));
362
+ } catch {
363
+ throw new BrowserControlError(
364
+ "response_unproven",
365
+ true,
366
+ response.status
367
+ );
368
+ }
369
+ if (!allowed) {
370
+ const reason = record(value) && record(value.error) && record(value.error.details) ? value.error.details.reason : void 0;
371
+ const known = errorReasons.find((item) => item === reason);
372
+ const refused = [400, 401, 403, 404, 409, 429].includes(
373
+ response.status
374
+ );
375
+ throw new BrowserControlError(
376
+ refused ? "refused" : "response_unproven",
377
+ !refused,
378
+ response.status,
379
+ known
380
+ );
381
+ }
382
+ const replay = response.headers.get("x-ariadra-idempotent-replay");
383
+ if (replay !== null && replay !== "true" && replay !== "false")
384
+ throw new BrowserControlError("response_unproven", true);
385
+ const reply = parseReply(
386
+ value,
387
+ sessionId,
388
+ action === "acquire" && replay !== "true"
389
+ );
390
+ if (mutation && (reply.data.control_id !== expectedControl || reply.data.revision < expectedRevision)) {
391
+ throw new BrowserControlError("response_unproven", true);
392
+ }
393
+ const result = {
394
+ status: response.status,
395
+ data: reply.data,
396
+ replayed: replay === "true"
397
+ };
398
+ return reply.access ? {
399
+ ...result,
400
+ status: 200,
401
+ viewer: new BrowserViewerHandle(reply.access)
402
+ } : result;
403
+ };
404
+ try {
405
+ return await Promise.race([deadline, perform()]);
406
+ } finally {
407
+ clearTimeout(timer);
408
+ options.signal?.removeEventListener("abort", aborted);
409
+ }
410
+ }
411
+ };
412
+ async function readBody(response, signal) {
413
+ if (!response.body) throw new BrowserControlError("response_unproven", true);
414
+ const reader = response.body.getReader();
415
+ const cancel = () => {
416
+ void reader.cancel().catch(() => {
417
+ });
418
+ };
419
+ signal.addEventListener("abort", cancel, { once: true });
420
+ const decoder = new TextDecoder("utf-8", { fatal: true });
421
+ let text = "", bytes = 0;
422
+ try {
423
+ if (signal.aborted) throw new BrowserControlError("aborted", true);
424
+ while (true) {
425
+ const next = await reader.read();
426
+ if (next.done) return text + decoder.decode();
427
+ bytes += next.value.byteLength;
428
+ if (bytes > 65536)
429
+ throw new BrowserControlError("response_unproven", true);
430
+ text += decoder.decode(next.value, { stream: true });
431
+ }
432
+ } finally {
433
+ signal.removeEventListener("abort", cancel);
434
+ cancel();
435
+ reader.releaseLock();
436
+ }
437
+ }
438
+
439
+ // src/version.ts
440
+ var BROWSER_SDK_VERSION = "0.1.0-rc.2";
441
+
442
+ export { BROWSER_SDK_VERSION, BrowserControlClient, BrowserControlError, CONTRACT_VERSION, createBrowserViewer };
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@agentmatrix.pro/browser-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-rc.2",
4
+ "description": "Human-authorized browser control client for AgentMatrix.",
5
+ "homepage": "https://agentmatrix.pro",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "engines": {
10
+ "node": ">=18"
11
+ },
12
+ "files": [
13
+ "CHANGELOG.md",
14
+ "dist"
15
+ ],
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "scripts": {
26
+ "build": "tsup --config tsup.config.ts",
27
+ "check": "npm run check:branding && npm run check:exports && npm run check:metadata && npm run check:boundaries && npm run typecheck && npm run build",
28
+ "check:boundaries": "tsx ../../scripts/check-module-boundaries.ts",
29
+ "check:branding": "tsx ../../scripts/check-branding.ts",
30
+ "check:exports": "tsx ../../scripts/gen-publication-exports.ts --check",
31
+ "check:metadata": "tsx ../../scripts/check-package-metadata.ts --package agentmatrix-browser-sdk",
32
+ "clean": "rm -rf dist",
33
+ "gen:exports": "tsx ../../scripts/gen-publication-exports.ts",
34
+ "lint": "biome check .",
35
+ "pack:dry": "npm pack --dry-run",
36
+ "prepack": "npm run check",
37
+ "typecheck": "tsc --project tsconfig.json --noEmit"
38
+ },
39
+ "keywords": [
40
+ "ariadra",
41
+ "sdk",
42
+ "openapi"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "registry": "https://registry.npmjs.org/"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/vibengine-ai/ariadra-sdk-typescript.git",
51
+ "directory": "publications/agentmatrix-browser-sdk"
52
+ }
53
+ }