hyperbrane 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +41 -0
  2. package/dist/agent/agentService.d.ts +31 -0
  3. package/dist/agent/agentService.js +388 -0
  4. package/dist/agent/agentStorage.d.ts +27 -0
  5. package/dist/agent/agentStorage.js +52 -0
  6. package/dist/agent/api.d.ts +264 -0
  7. package/dist/agent/api.js +14 -0
  8. package/dist/agent/gatewaySignIns.d.ts +5 -0
  9. package/dist/agent/gatewaySignIns.js +11 -0
  10. package/dist/agent/session/client.d.ts +14 -0
  11. package/dist/agent/session/client.js +47 -0
  12. package/dist/agent/session/sessionStorage.d.ts +66 -0
  13. package/dist/agent/session/sessionStorage.js +89 -0
  14. package/dist/agent/session/sharedConnection.d.ts +13 -0
  15. package/dist/agent/session/sharedConnection.js +55 -0
  16. package/dist/agent/session/worker/jsonRpc.d.ts +39 -0
  17. package/dist/agent/session/worker/jsonRpc.js +102 -0
  18. package/dist/agent/session/worker/protocol.d.ts +120 -0
  19. package/dist/agent/session/worker/protocol.js +32 -0
  20. package/dist/agent/session/workerConnection.d.ts +29 -0
  21. package/dist/agent/session/workerConnection.js +44 -0
  22. package/dist/agent/session/workerSseConnection.d.ts +15 -0
  23. package/dist/agent/session/workerSseConnection.js +26 -0
  24. package/dist/agent/workerBundle.d.ts +19 -0
  25. package/dist/agent/workerBundle.generated.d.ts +1 -0
  26. package/dist/agent/workerBundle.generated.js +2 -0
  27. package/dist/agent/workerBundle.js +31 -0
  28. package/dist/cli/agent.d.ts +3 -0
  29. package/dist/cli/agent.js +423 -0
  30. package/dist/cli/command.d.ts +46 -0
  31. package/dist/cli/command.js +98 -0
  32. package/dist/cli/dimension.d.ts +2 -0
  33. package/dist/cli/dimension.js +85 -0
  34. package/dist/cli/gateway.d.ts +6 -0
  35. package/dist/cli/gateway.js +245 -0
  36. package/dist/cli/main.d.ts +2 -0
  37. package/dist/cli/main.js +125 -0
  38. package/dist/cli/portal.d.ts +2 -0
  39. package/dist/cli/portal.js +39 -0
  40. package/dist/cli/services.d.ts +18 -0
  41. package/dist/cli/services.js +33 -0
  42. package/dist/cli/streamPrinter.d.ts +23 -0
  43. package/dist/cli/streamPrinter.js +251 -0
  44. package/dist/cli/table.d.ts +7 -0
  45. package/dist/cli/table.js +54 -0
  46. package/dist/dimension/api.d.ts +67 -0
  47. package/dist/dimension/api.js +81 -0
  48. package/dist/dimension/http.d.ts +7 -0
  49. package/dist/dimension/http.js +77 -0
  50. package/dist/dimension/image.d.ts +13 -0
  51. package/dist/dimension/image.js +43 -0
  52. package/dist/dimension/imageFiles.generated.d.ts +1 -0
  53. package/dist/dimension/imageFiles.generated.js +5 -0
  54. package/dist/dimension/paths.d.ts +5 -0
  55. package/dist/dimension/paths.js +7 -0
  56. package/dist/dimension/service.d.ts +22 -0
  57. package/dist/dimension/service.js +242 -0
  58. package/dist/dimension/storage.d.ts +39 -0
  59. package/dist/dimension/storage.js +78 -0
  60. package/dist/index.d.ts +18 -0
  61. package/dist/index.js +25 -0
  62. package/dist/lib/docker-api.d.ts +13787 -0
  63. package/dist/lib/docker-api.js +5 -0
  64. package/dist/lib/docker.d.ts +77 -0
  65. package/dist/lib/docker.js +214 -0
  66. package/dist/lib/image.d.ts +14 -0
  67. package/dist/lib/image.js +29 -0
  68. package/dist/lib/jsonDirectory.d.ts +28 -0
  69. package/dist/lib/jsonDirectory.js +102 -0
  70. package/dist/lib/sleep.d.ts +2 -0
  71. package/dist/lib/sleep.js +4 -0
  72. package/dist/lib/tar.d.ts +2 -0
  73. package/dist/lib/tar.js +65 -0
  74. package/dist/lib/version.d.ts +1 -0
  75. package/dist/lib/version.js +1 -0
  76. package/dist/portal-gateway/api.d.ts +98 -0
  77. package/dist/portal-gateway/api.js +12 -0
  78. package/dist/portal-gateway/fakes.d.ts +3 -0
  79. package/dist/portal-gateway/fakes.js +11 -0
  80. package/dist/portal-gateway/gatewayService.d.ts +37 -0
  81. package/dist/portal-gateway/gatewayService.js +380 -0
  82. package/dist/portal-gateway/gatewayStorage.d.ts +66 -0
  83. package/dist/portal-gateway/gatewayStorage.js +125 -0
  84. package/dist/portal-gateway/image.d.ts +6 -0
  85. package/dist/portal-gateway/image.js +13 -0
  86. package/dist/portal-gateway/imageFiles.generated.d.ts +1 -0
  87. package/dist/portal-gateway/imageFiles.generated.js +8 -0
  88. package/dist/portal-gateway/portalService.d.ts +48 -0
  89. package/dist/portal-gateway/portalService.js +327 -0
  90. package/dist/portal-gateway/portalStorage.d.ts +34 -0
  91. package/dist/portal-gateway/portalStorage.js +44 -0
  92. package/dist/portal-gateway/upstream.d.ts +157 -0
  93. package/dist/portal-gateway/upstream.js +4 -0
  94. package/dist/sandbox/api.d.ts +184 -0
  95. package/dist/sandbox/api.js +14 -0
  96. package/dist/sandbox/boatService.d.ts +52 -0
  97. package/dist/sandbox/boatService.js +335 -0
  98. package/dist/sandbox/containerService.d.ts +15 -0
  99. package/dist/sandbox/containerService.js +177 -0
  100. package/dist/sandbox/endpointProxy.d.ts +90 -0
  101. package/dist/sandbox/endpointProxy.js +701 -0
  102. package/dist/sandbox/exeDevAuth.d.ts +16 -0
  103. package/dist/sandbox/exeDevAuth.js +49 -0
  104. package/dist/sandbox/localService.d.ts +19 -0
  105. package/dist/sandbox/localService.js +182 -0
  106. package/dist/sandbox/sseConnection.d.ts +41 -0
  107. package/dist/sandbox/sseConnection.js +166 -0
  108. package/dist/sandbox/sshService.d.ts +30 -0
  109. package/dist/sandbox/sshService.js +647 -0
  110. package/dist/upstreams/anthropic.d.ts +7 -0
  111. package/dist/upstreams/anthropic.js +27 -0
  112. package/dist/upstreams/index.d.ts +6 -0
  113. package/dist/upstreams/index.js +7 -0
  114. package/dist/upstreams/openai.d.ts +7 -0
  115. package/dist/upstreams/openai.js +40 -0
  116. package/dist/vendor-types/claude/agent-sdk/agentSdkTypes.d.ts +1 -0
  117. package/dist/vendor-types/claude/agent-sdk/bridge.d.ts +388 -0
  118. package/dist/vendor-types/claude/agent-sdk/browser-sdk.d.ts +184 -0
  119. package/dist/vendor-types/claude/agent-sdk/core.d.ts +20 -0
  120. package/dist/vendor-types/claude/agent-sdk/extractFromBunfs.d.ts +1 -0
  121. package/dist/vendor-types/claude/agent-sdk/sdk-tools.d.ts +4153 -0
  122. package/dist/vendor-types/claude/agent-sdk/sdk.d.ts +9833 -0
  123. package/package.json +55 -0
@@ -0,0 +1,6 @@
1
+ import type { UpstreamDefinition } from "../portal-gateway/upstream.ts";
2
+ /**
3
+ * Registered on every gateway whose creator doesn't list its own: a gateway that doesn't know an
4
+ * upstream passes its tokens through to the dimension untouched.
5
+ */
6
+ export declare const BUILTIN_UPSTREAMS: UpstreamDefinition[];
@@ -0,0 +1,7 @@
1
+ import anthropic from "./anthropic.js";
2
+ import openai from "./openai.js";
3
+ /**
4
+ * Registered on every gateway whose creator doesn't list its own: a gateway that doesn't know an
5
+ * upstream passes its tokens through to the dimension untouched.
6
+ */
7
+ export const BUILTIN_UPSTREAMS = [anthropic, openai];
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Codex: a ChatGPT plan through `codex login --device-auth`, or an OpenAI API key. Once the gateway
3
+ * holds a sign-in, `codex login --device-auth` in any dimension completes without a browser: the
4
+ * gateway approves the device login and answers the exchange itself.
5
+ */
6
+ declare const _default: import("../portal-gateway/upstream.ts").UpstreamDefinition;
7
+ export default _default;
@@ -0,0 +1,40 @@
1
+ import { defineUpstream } from "../portal-gateway/upstream.js";
2
+ /**
3
+ * Codex: a ChatGPT plan through `codex login --device-auth`, or an OpenAI API key. Once the gateway
4
+ * holds a sign-in, `codex login --device-auth` in any dimension completes without a browser: the
5
+ * gateway approves the device login and answers the exchange itself.
6
+ */
7
+ export default defineUpstream({
8
+ name: "openai",
9
+ modes: {
10
+ oauth: {
11
+ // The API (HTTP and websocket) is on chatgpt.com; auth.openai.com is the token endpoint.
12
+ hosts: ["chatgpt.com", "auth.openai.com"],
13
+ present: { header: "authorization", scheme: "Bearer" },
14
+ // The sign-in exchange is form-encoded, the refresh JSON.
15
+ tokenUrl: "https://auth.openai.com/oauth/token",
16
+ // codex decodes both JWTs: the access token's exp decides when it refreshes, and the id
17
+ // token's claims give it the account and plan.
18
+ fakes: {
19
+ access: { jwt: true },
20
+ id: { jwt: true },
21
+ refresh: { prefix: "rt.1." },
22
+ },
23
+ // Another session token, in the body and again in a header; codex doesn't keep it.
24
+ strip: { fields: ["oai_is"], headers: ["x-oai-is-update"] },
25
+ // codex polls this until the device login is approved, then exchanges the code it returns
26
+ // (with the returned verifier, which it doesn't check) at tokenUrl, answered by the gateway.
27
+ answers: [
28
+ {
29
+ url: "https://auth.openai.com/api/accounts/deviceauth/token",
30
+ json: { status: "success", authorization_code: "gateway", code_challenge: "gateway", code_verifier: "gateway" },
31
+ },
32
+ ],
33
+ },
34
+ apiKey: {
35
+ hosts: ["api.openai.com"],
36
+ present: { header: "authorization", scheme: "Bearer" },
37
+ fake: { prefix: "sk-proj-" },
38
+ },
39
+ },
40
+ });
@@ -0,0 +1 @@
1
+ export * from './sdk.js'
@@ -0,0 +1,388 @@
1
+ /**
2
+ * API surface definition for @anthropic-ai/claude-agent-sdk/bridge.
3
+ *
4
+ * This file is the source of truth for the /bridge export's public types.
5
+ * It imports ONLY from agentSdkTypes.ts so the compiled .d.ts has exactly
6
+ * one import to rewrite (./agentSdkTypes → ./sdk) for the flat package layout.
7
+ *
8
+ * Compiled by scripts/build-ant-sdk-typings.sh; see build-agent-sdk.sh for the
9
+ * copy into the package. Runtime code is in agentSdkBridge.ts (separate file,
10
+ * bun-built to bridge.mjs).
11
+ *
12
+ * The two type definitions below are copied from src/bridge/sessionHandle.ts.
13
+ * Keep in sync — sessionHandle.ts is the implementation source of truth;
14
+ * this file exists to produce a clean .d.ts without walking the implementation
15
+ * import graph.
16
+ */
17
+ import type { PermissionMode, SDKControlRequest, SDKControlResponse, SDKMessage } from './agentSdkTypes.js';
18
+ /**
19
+ * Session state reported to the CCR /worker endpoint.
20
+ * @alpha
21
+ */
22
+ export type SessionState = 'idle' | 'running' | 'requires_action';
23
+ /**
24
+ * Per-session bridge transport handle.
25
+ *
26
+ * Auth is instance-scoped — the JWT lives in this handle's closure, not a
27
+ * process-wide env var, so multiple handles can coexist without stomping
28
+ * each other.
29
+ * @alpha
30
+ */
31
+ export type BridgeSessionHandle = {
32
+ readonly sessionId: string;
33
+ /**
34
+ * Live SSE event-stream high-water mark. Updates as the underlying
35
+ * transport receives frames. Persist this and pass back as
36
+ * `initialSequenceNum` on re-attach so the server resumes instead of
37
+ * replaying full history.
38
+ */
39
+ getSequenceNum(): number;
40
+ /**
41
+ * Worker epoch the current transport is writing as. Callers that
42
+ * reconnect for a token refresh (not a cold re-attach) pass this back
43
+ * via `reconnectTransport({epoch})` so the handle reuses the epoch
44
+ * instead of calling registerWorker again.
45
+ */
46
+ getEpoch(): number | undefined;
47
+ /** True once the write path (CCRClient initialize) is ready. */
48
+ isConnected(): boolean;
49
+ /** Write a single SDKMessage. `session_id` is injected automatically. */
50
+ write(msg: SDKMessage): void;
51
+ /** Signal turn boundary — claude.ai stops the "working" spinner. */
52
+ sendResult(): void;
53
+ /** Forward a permission request (`can_use_tool`) to claude.ai. */
54
+ sendControlRequest(req: SDKControlRequest): void;
55
+ /** Forward a permission response back through the bridge. */
56
+ sendControlResponse(res: SDKControlResponse): void;
57
+ /**
58
+ * Tell claude.ai to dismiss a pending permission prompt (e.g. caller
59
+ * aborted the turn locally before the user answered).
60
+ */
61
+ sendControlCancelRequest(requestId: string): void;
62
+ /**
63
+ * Swap the underlying transport in place with a fresh JWT (and epoch).
64
+ * Carries the SSE sequence number so the server resumes the stream.
65
+ * Call this when the poll loop re-dispatches work for the same session
66
+ * with a fresh secret (JWT is 4h; backend mints a new one every dispatch).
67
+ *
68
+ * Throws if `createV2ReplTransport` fails (registerWorker error, etc).
69
+ * Caller should treat that as a close and drop this handle.
70
+ */
71
+ reconnectTransport(opts: {
72
+ ingressToken: string;
73
+ apiBaseUrl: string;
74
+ /** Omit to reuse the current transport's epoch (token-refresh reconnect); provide to override. */
75
+ epoch?: number;
76
+ }): Promise<void>;
77
+ /**
78
+ * PUT /worker state. Multi-session workers: `running` on turn start,
79
+ * `requires_action` on permission prompt, `idle` on turn end. Daemon
80
+ * callers don't need this — user watches the REPL locally.
81
+ */
82
+ reportState(state: SessionState): void;
83
+ /** PUT /worker external_metadata (branch, dir shown on claude.ai). */
84
+ reportMetadata(metadata: Record<string, unknown>): void;
85
+ /**
86
+ * POST /worker/events/{id}/delivery. Populates CCR's processing_at /
87
+ * processed_at columns. `received` is auto-fired internally; this
88
+ * surfaces `processing` (turn start) and `processed` (turn end).
89
+ */
90
+ reportDelivery(eventId: string, status: 'processing' | 'processed'): void;
91
+ /** Drain the write queue. Call before close() when delivery matters. */
92
+ flush(): Promise<void>;
93
+ close(): void;
94
+ };
95
+ /** @alpha */
96
+ export type AttachBridgeSessionOptions = {
97
+ /**
98
+ * Session ID (`cse_*` form). Comes from `WorkResponse.data.id` in the
99
+ * poll-loop path, or from whatever created the session.
100
+ */
101
+ sessionId: string;
102
+ /** Worker JWT. Comes from `decodeWorkSecret(work.secret).session_ingress_token`. */
103
+ ingressToken: string;
104
+ /** `WorkSecret.api_base_url` or wherever the session ingress lives. */
105
+ apiBaseUrl: string;
106
+ /**
107
+ * Worker epoch if already known (e.g. from a `/bridge` call that bumps
108
+ * epoch server-side). Omit to have `createV2ReplTransport` call
109
+ * `registerWorker` itself — correct for poll-loop callers where the
110
+ * work secret doesn't carry epoch.
111
+ */
112
+ epoch?: number;
113
+ /**
114
+ * SSE sequence-number high-water mark from a prior handle or persisted
115
+ * state. Seeds the first SSE connect's `from_sequence_num` so the server
116
+ * resumes instead of replaying full history. Omit (→ 0) for genuinely
117
+ * fresh attach.
118
+ */
119
+ initialSequenceNum?: number;
120
+ /**
121
+ * CCRClient heartbeat interval seed. Defaults to 20s. The server-advised
122
+ * interval (ccr_heartbeat_policy) overrides this after the first heartbeat.
123
+ */
124
+ heartbeatIntervalMs?: number;
125
+ /**
126
+ * When true, the bridge only forwards events outbound (local → CCR). The
127
+ * SSE read stream is not opened — no inbound events are received. Control
128
+ * requests that arrive via the write-path ACK channel reply with an error
129
+ * instead of false-success. onInboundMessage is never called. Use for
130
+ * mirror-mode attachments where the remote UI should see the session but
131
+ * not be able to drive it.
132
+ */
133
+ outboundOnly?: boolean;
134
+ /**
135
+ * User message typed on claude.ai. Echoes of outbound writes and
136
+ * re-deliveries of prompts already forwarded are filtered before this
137
+ * fires. May be async (e.g. attachment resolution).
138
+ */
139
+ onInboundMessage?: (msg: SDKMessage) => void | Promise<void>;
140
+ /**
141
+ * `control_response` from claude.ai — the user answered a `can_use_tool`
142
+ * prompt sent via `sendControlRequest`. Caller correlates by `request_id`.
143
+ * Return `false` when the response is rejected (malformed/forged) so the
144
+ * prompt stays eligible for initialize re-delivery; void = accepted.
145
+ */
146
+ onPermissionResponse?: (res: SDKControlResponse) => boolean | void;
147
+ /** `interrupt` control_request from claude.ai. Already auto-replied-to. */
148
+ onInterrupt?: () => void;
149
+ /**
150
+ * `stop_task` control_request from claude.ai — per-task Stop from the
151
+ * client's tasks panel. Resolve = stopped (hosts should treat a task the
152
+ * process no longer tracks or that already finished as stopped and
153
+ * resolve, so the client prunes the stale row — but NOT a live paused or
154
+ * pending task, nor an ambiguous name matching several live tasks: those
155
+ * should reject so the user sees an accurate
156
+ * refusal); reject = error control_response with the
157
+ * rejection's message. Omit if the host has no task registry — the CLI
158
+ * then answers with a "not supported in this context" error.
159
+ */
160
+ onStopTask?: (taskId: string) => Promise<void>;
161
+ /**
162
+ * `background_tasks` from claude.ai — the client's Ctrl+B. With a
163
+ * toolUseId, background the single foreground task that tool_use block
164
+ * started and return whether one was found; without, background every
165
+ * foreground task and return true. May answer asynchronously (e.g. by
166
+ * delegating to `Query.backgroundTasks()`); a rejection is sent as an
167
+ * error reply. Omit if the host has no task registry — the CLI then
168
+ * answers with a "not supported in this context" error.
169
+ */
170
+ onBackgroundTasks?: (toolUseId: string | undefined) => boolean | Promise<boolean>;
171
+ onSetModel?: (model: string | undefined) => {
172
+ ok: true;
173
+ notices?: string[];
174
+ } | {
175
+ ok: false;
176
+ error: string;
177
+ } | void | Promise<{
178
+ ok: true;
179
+ notices?: string[];
180
+ } | {
181
+ ok: false;
182
+ error: string;
183
+ }>;
184
+ onSetMaxThinkingTokens?: (tokens: number | null | undefined, thinkingDisplay?: 'summarized' | 'omitted' | 'highlights' | null) => {
185
+ ok: true;
186
+ } | {
187
+ ok: false;
188
+ error: string;
189
+ } | void | Promise<{
190
+ ok: true;
191
+ } | {
192
+ ok: false;
193
+ error: string;
194
+ } | void>;
195
+ /**
196
+ * `set_permission_mode` from claude.ai. Return an error verdict to send
197
+ * an error control_response (vs silently false-succeeding). Omit if
198
+ * the caller doesn't support permission modes — the shared handler
199
+ * returns a "not supported in this context" error.
200
+ */
201
+ onSetPermissionMode?: (mode: PermissionMode) => {
202
+ ok: true;
203
+ } | {
204
+ ok: false;
205
+ error: string;
206
+ };
207
+ /** `rename_session` from claude.ai. Return an error verdict to reject. */
208
+ onRenameSession?: (title: string) => {
209
+ ok: true;
210
+ } | {
211
+ ok: false;
212
+ error: string;
213
+ };
214
+ /**
215
+ * Transport died permanently. 401 = JWT expired (re-attach with fresh
216
+ * secret), 4090 = epoch superseded (no longer the active worker),
217
+ * 4091 = CCRClient init failed, 4092 = codeless close (defensive
218
+ * fallback — cause unknown), 4093 = presence heartbeats kept failing
219
+ * while the SSE stream stayed healthy (transport self-heal candidate),
220
+ * 4094 = worker credential expired or rejected on the request path
221
+ * (heartbeat/write auth exhaustion — re-attach with a fresh secret,
222
+ * like 401), 403/404 = permanent SSE HTTP rejection. Transient
223
+ * disconnects (503, network blips) retry indefinitely inside
224
+ * SSETransport and do NOT fire this.
225
+ */
226
+ onClose?: (code?: number) => void;
227
+ };
228
+ /**
229
+ * Attach to an existing bridge session. Creates the v2 transport
230
+ * (SSETransport + CCRClient), wires ingress routing and control dispatch,
231
+ * returns a handle scoped to this one session.
232
+ *
233
+ * Throws if `createV2ReplTransport` fails (registerWorker error, etc).
234
+ *
235
+ * ALPHA STABILITY. This is a separate versioning universe from the main
236
+ * `query()` surface: breaking changes here do NOT bump the package major.
237
+ * @alpha
238
+ */
239
+ export declare function attachBridgeSession(opts: AttachBridgeSessionOptions): Promise<BridgeSessionHandle>;
240
+ /**
241
+ * Worker credentials from `POST /v1/code/sessions/{id}/bridge`.
242
+ * Each call bumps `worker_epoch` server-side — the call IS the worker register.
243
+ * @alpha
244
+ */
245
+ export type RemoteCredentials = {
246
+ worker_jwt: string;
247
+ api_base_url: string;
248
+ expires_in: number;
249
+ worker_epoch: number;
250
+ };
251
+ /**
252
+ * Terminal failure from `fetchRemoteCredentials` — retrying with the same
253
+ * inputs is guaranteed to fail. Server-minted reasons arrive as 403 with
254
+ * `error.resource` set to `"untrusted_device"` (token missing/revoked —
255
+ * enroll) or `"session_stale_relogin"` (OAuth session older than the
256
+ * freshness window — re-authenticate). `"invalid_session_id"` is
257
+ * client-minted: the session id failed validation (`/^[a-zA-Z0-9_-]+$/`)
258
+ * before any request was sent. `"request_rejected"` is any other
259
+ * authoritative non-retryable 4xx (the server answered; neither time nor a
260
+ * new credential changes the request). `"malformed_response"` is a 2xx this
261
+ * client could not parse — the mint SUCCEEDED server-side (each call bumps
262
+ * `worker_epoch`), so retrying epoch-bumps per attempt; not transient, not
263
+ * an authoritative denial.
264
+ * @alpha
265
+ */
266
+ export type CredentialsFailure = {
267
+ terminal: true;
268
+ reason: 'untrusted_device' | 'session_stale_relogin' | 'invalid_session_id';
269
+ } | {
270
+ terminal: true;
271
+ reason: 'request_rejected';
272
+ /** HTTP status, for the debug trail and user-facing hints. */
273
+ status: number;
274
+ /**
275
+ * 403 only: who wrote the rejection, from response headers — the
276
+ * origin (`request-id: req_…`), a Cloudflare edge before it, or a hop
277
+ * that never reached Anthropic. Attribution for telemetry/copy; not a
278
+ * verdict on ownership.
279
+ */
280
+ source?: 'origin' | 'nonorigin_cf' | 'nonorigin_other';
281
+ } | {
282
+ terminal: true;
283
+ reason: 'malformed_response';
284
+ /** HTTP status, for the debug trail and user-facing hints. */
285
+ status: number;
286
+ };
287
+ /**
288
+ * Non-terminal classified rejection: the OAuth bearer itself was rejected
289
+ * (401). Retrying with the SAME credential is pointless, but a DIFFERENT
290
+ * credential can succeed (post-re-authentication) — distinct from
291
+ * `CredentialsFailure` (`terminal: true`) and from null, which is reserved
292
+ * for transient transport-shaped failures (network error / timeout / 5xx).
293
+ * @alpha
294
+ */
295
+ export type CredentialsRejection = {
296
+ terminal: false;
297
+ reason: 'oauth_rejected';
298
+ };
299
+ /**
300
+ * Type guard for `fetchRemoteCredentials` results.
301
+ * @alpha
302
+ */
303
+ export declare function isCredentialsFailure(r: RemoteCredentials | CredentialsFailure | CredentialsRejection | null): r is CredentialsFailure;
304
+ /**
305
+ * Type guard for the non-terminal classified 401 rejection. Accepts
306
+ * `unknown`: callers hand it unions whose success arm is a plain string
307
+ * (session ids), and it narrows structurally.
308
+ * @alpha
309
+ */
310
+ export declare function isCredentialsRejection(r: unknown): r is CredentialsRejection;
311
+ /**
312
+ * Git source/outcome context attached to a v2 code session on create.
313
+ * @alpha
314
+ */
315
+ export type CodeSessionGitContext = {
316
+ gitRepoUrl: string;
317
+ branch: string;
318
+ /**
319
+ * The repo's default branch, when authoritatively known. LOAD-BEARING
320
+ * for branch continuity: when absent, `branch` is omitted from
321
+ * `outcomes.branches` entirely (the classification never acts on a
322
+ * guess), so the remote session works on a runner-generated branch
323
+ * instead of `branch`, with only a debug-level signal. Callers that
324
+ * want the session to check out AND push to `branch` must supply
325
+ * this — read `git symbolic-ref refs/remotes/origin/HEAD`, or run
326
+ * `git remote set-head origin -a` to repair a missing symref.
327
+ */
328
+ defaultBranch?: string;
329
+ };
330
+ /**
331
+ * Caller-owned dedupe state for createCodeSession's branch-drop debug
332
+ * signal: create one object per logical create (outside your retry
333
+ * loop) and pass it to every attempt so the drop logs once per
334
+ * decision. Omit it to log on every attempt.
335
+ * @alpha
336
+ */
337
+ export declare type BranchDropLogDedup = {
338
+ lastKey?: string | null;
339
+ };
340
+ /**
341
+ * Terminal failure from `POST /v1/code/sessions` — retrying with the same
342
+ * inputs fails identically. `reason` distinguishes the recognized
343
+ * `session_grouping_id` rejection family (`"grouping_rejected"` — the
344
+ * caller may retry without the grouping) from any other authoritative
345
+ * non-retryable 4xx (`"request_rejected"`) and from a 2xx this client
346
+ * could not parse (`"malformed_response"` — the create SUCCEEDED
347
+ * server-side, so a retry would orphan one session per attempt).
348
+ * @alpha
349
+ */
350
+ export type CreateSessionFailure = {
351
+ terminal: true;
352
+ reason: 'grouping_rejected' | 'request_rejected' | 'malformed_response';
353
+ status: number;
354
+ detail: string | undefined;
355
+ };
356
+ /**
357
+ * Type guard for `createCodeSession` results. Matches only `terminal: true`
358
+ * failures — a `CredentialsRejection` (`terminal: false`) does not match.
359
+ * @alpha
360
+ */
361
+ export declare function isCreateSessionFailure(r: string | CreateSessionFailure | CredentialsRejection | null): r is CreateSessionFailure;
362
+ /**
363
+ * `POST /v1/code/sessions` — create a fresh CCR session. Returns the `cse_*`
364
+ * session id on success, a classified `CreateSessionFailure` (terminal —
365
+ * don't retry; see its `reason`), a `CredentialsRejection` when the OAuth
366
+ * bearer was rejected (retry only with a NEW credential), or null on
367
+ * transient transport-shaped failures (network error / timeout / 5xx).
368
+ *
369
+ * Callers supply their own OAuth token — this is a thin HTTP wrapper with no
370
+ * implicit auth, so it works from any process (not just the CLI).
371
+ * @alpha
372
+ */
373
+ export declare function createCodeSession(baseUrl: string, accessToken: string, title: string, timeoutMs: number, tags?: string[], gitContext?: CodeSessionGitContext, cwd?: string, model?: string, sessionGroupingId?: string, dropLogDedup?: BranchDropLogDedup): Promise<string | CreateSessionFailure | CredentialsRejection | null>;
374
+ /**
375
+ * `POST /v1/code/sessions/{id}/bridge` — mint a worker JWT for the session.
376
+ * Returns credentials, a `CredentialsFailure` for terminal failures (don't
377
+ * retry — see `CredentialsFailure.reason` for remediation), a
378
+ * `CredentialsRejection` when the OAuth bearer was rejected (retry only
379
+ * with a NEW credential), or null on transient transport-shaped failure. The call IS the worker register (bumps epoch
380
+ * server-side), so pass `epoch: creds.worker_epoch` to `attachBridgeSession`
381
+ * to skip a redundant register.
382
+ *
383
+ * `trustedDeviceToken` sets the `X-Trusted-Device-Token` header. Required
384
+ * when the server's `sessions_elevated_auth_enforcement` flag is on
385
+ * (bridge sessions are SecurityTier=ELEVATED). See anthropics/anthropic#274559.
386
+ * @alpha
387
+ */
388
+ export declare function fetchRemoteCredentials(sessionId: string, baseUrl: string, accessToken: string, timeoutMs: number, trustedDeviceToken?: string): Promise<RemoteCredentials | CredentialsFailure | CredentialsRejection | null>;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * API surface definition for @anthropic-ai/claude-agent-sdk/browser.
3
+ *
4
+ * This file is the source of truth for the browser export's public types.
5
+ * It imports ONLY from agentSdkTypes.ts so the compiled .d.ts has exactly
6
+ * one import to rewrite (./agentSdkTypes → ./sdk) for the flat package layout.
7
+ *
8
+ * Compiled by scripts/build-ant-sdk-typings.sh; see build-agent-sdk.sh for the
9
+ * path rewrite and copy into the package.
10
+ */
11
+ import type { CanUseTool, HookCallbackMatcher, HookEvent, McpServerConfig, OnElicitation, OnUserDialog, Query, SDKMessage, SDKUserMessage } from './agentSdkTypes.js';
12
+ export type { CanUseTool, ElicitationRequest, ElicitationResult, HookCallbackMatcher, HookEvent, McpSdkServerConfigWithInstance, McpServerConfig, OnElicitation, OnUserDialog, Query, SDKAssistantMessage, SDKMessage, SDKResultMessage, SDKSystemMessage, SDKUserMessage, UserDialogRequest, UserDialogResult, } from './agentSdkTypes.js';
13
+ export { createSdkMcpServer, tool } from './agentSdkTypes.js';
14
+ export type OAuthCredential = {
15
+ type: 'oauth';
16
+ token: string;
17
+ };
18
+ export type AuthMessage = {
19
+ type: 'auth';
20
+ credential: OAuthCredential;
21
+ };
22
+ export type WebSocketOptions = {
23
+ url: string;
24
+ headers?: Record<string, string>;
25
+ authMessage?: AuthMessage;
26
+ };
27
+ export type SSEOptions = {
28
+ /** SSE read endpoint, e.g. `…/v1/code/sessions/{id}/events/stream`. */
29
+ streamUrl: string;
30
+ /** POST write endpoint, e.g. `…/v1/code/sessions/{id}/events`. */
31
+ sendUrl: string;
32
+ /**
33
+ * The CCR session ID — required to build the `AddClientEventFromClient`
34
+ * request body that `sendUrl` expects.
35
+ */
36
+ sessionId: string;
37
+ /**
38
+ * Headers sent on both the SSE GET and every POST. Set `Authorization` and
39
+ * `anthropic-client-platform` here — the SDK cannot determine the host
40
+ * surface (web / iOS / Android / desktop) itself.
41
+ */
42
+ headers?: Record<string, string>;
43
+ /**
44
+ * Resume cursor for the first connect: the stream delivers only events
45
+ * whose `sequence_num` is greater. For a consumer that seeded its
46
+ * transcript from the REST event list — pass the highest `sequence_num` it
47
+ * has already applied (for a query replacing an earlier one,
48
+ * `getSseLastSequenceNum()` of that query, which only ever covers messages
49
+ * it actually yielded). Omitted or 0 starts from the beginning of the
50
+ * retained stream.
51
+ */
52
+ fromSequenceNum?: number;
53
+ /**
54
+ * Called when the server reports (`catch_up_truncated`) that it could not
55
+ * replay every event after the resume cursor — the stream continues from a
56
+ * later point, so re-fetch the gap from the REST event list and reseed.
57
+ * Each occurrence is also counted in `getSseDropCounts()` under
58
+ * `catch_up_truncated`. Exceptions thrown by the handler are contained.
59
+ */
60
+ onCatchUpTruncated?: () => void;
61
+ /**
62
+ * Called for each `delivery_update` frame: the worker's acknowledgement of
63
+ * one event this session was sent (`event_id` — matches the `event_id` of
64
+ * that event's own durable echo, see `getCcrEvent()`), with the raw server
65
+ * status string — `"DELIVERY_STATUS_RECEIVED"`, `"DELIVERY_STATUS_PROCESSING"`
66
+ * (the worker began the turn) or `"DELIVERY_STATUS_PROCESSED"` (that turn
67
+ * ended); treat unknown values as informational — and the server
68
+ * `timestamp` when present. Not durable: a reconnect does not replay
69
+ * earlier updates. Malformed frames are counted in `getSseDropCounts()`
70
+ * under `malformed_delivery_update`; handler exceptions are contained.
71
+ */
72
+ onDeliveryUpdate?: (update: {
73
+ event_id: string;
74
+ status: string;
75
+ timestamp?: string;
76
+ }) => void;
77
+ };
78
+ type BrowserQueryOptionsBase = {
79
+ prompt: AsyncIterable<SDKUserMessage>;
80
+ abortController?: AbortController;
81
+ canUseTool?: CanUseTool;
82
+ hooks?: Partial<Record<HookEvent, HookCallbackMatcher[]>>;
83
+ mcpServers?: Record<string, McpServerConfig>;
84
+ jsonSchema?: Record<string, unknown>;
85
+ onElicitation?: OnElicitation;
86
+ onUserDialog?: OnUserDialog;
87
+ /**
88
+ * When enabled, the remote CLI emits a `prompt_suggestion` message after
89
+ * each turn's result. At most one per turn.
90
+ */
91
+ promptSuggestions?: boolean;
92
+ };
93
+ /**
94
+ * Exactly one of `websocket` | `sse` must be provided. `sse` is the v1alpha2
95
+ * path and is preferred for new integrations; `websocket` remains for
96
+ * existing callers during the migration.
97
+ */
98
+ export type BrowserQueryOptions = BrowserQueryOptionsBase & ({
99
+ websocket: WebSocketOptions;
100
+ sse?: never;
101
+ } | {
102
+ sse: SSEOptions;
103
+ websocket?: never;
104
+ });
105
+ /**
106
+ * Create a Claude Code query in the browser over either SSE (preferred) or
107
+ * WebSocket.
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * import { query } from './browser-sdk.js'
112
+ *
113
+ * const messages = query({
114
+ * prompt: messageStream,
115
+ * sse: {
116
+ * streamUrl: 'https://api.example.com/v1/code/sessions/ID/events/stream',
117
+ * sendUrl: 'https://api.example.com/v1/code/sessions/ID/events',
118
+ * headers: { Authorization: `Bearer ${token}` },
119
+ * },
120
+ * })
121
+ * for await (const message of messages) {
122
+ * console.log(message)
123
+ * }
124
+ * ```
125
+ */
126
+ export declare function query(options: BrowserQueryOptions): Query;
127
+ /**
128
+ * Readiness sentinel for the peer-frame text-envelope guard
129
+ * (userFrameRequiresWorkerSource): `true` means the SSE transport enforces
130
+ * the full predicate on peer-authored `user` frames. The change enabling
131
+ * `ccr_v2_subscribe_sse_web` in a consumer repo must assert this reads
132
+ * `true` before flipping the flag.
133
+ */
134
+ export declare const G4_TEXT_ENVELOPE_ARM_PORTED: boolean;
135
+ /**
136
+ * Cumulative per-category dropped-frame counts for a query() created with
137
+ * the `sse` transport — the aggregated receipt for the
138
+ * `ccr_v2_subscribe_sse_web` enablement review (category → count only,
139
+ * never frame contents). Returns undefined for WebSocket-transport queries.
140
+ */
141
+ export declare function getSseDropCounts(query: Query): Readonly<Record<string, number>> | undefined;
142
+ /**
143
+ * Resume cursor of a query() created with the `sse` transport: the highest
144
+ * `sequence_num` of a durable message this query has yielded (or the
145
+ * `fromSequenceNum` seed before any was). It is advanced immediately before
146
+ * each message is yielded, so while the consumer handles message `m` it is
147
+ * already `>= getCcrEvent(query, m).sequence_num`, and it never covers a
148
+ * message the consumer was not handed — frames still buffered when the
149
+ * consumer stops iterating, and durable events the SDK dropped or consumed
150
+ * internally, do not advance it. So at any point — mid-stream, after a
151
+ * `break`, or once the iterator has finished — it is where a REST catch-up
152
+ * fetch or a replacement query()'s `fromSequenceNum` should resume (the
153
+ * transport's own transparent reconnects use a separate internal wire
154
+ * cursor). Per-message ordering still reads `getCcrEvent(query, message)`.
155
+ * Returns undefined for WebSocket-transport queries and before any sequence
156
+ * number is known.
157
+ */
158
+ export declare function getSseLastSequenceNum(query: Query): number | undefined;
159
+ /**
160
+ * The wire envelope of the durable CCR event (SSE `client_event` frame) that
161
+ * delivered `message` on the `sse` query `query`: `sequence_num` is the
162
+ * session-wide order the server assigned, `event_id` is unique per event,
163
+ * `created_at` (RFC 3339 store time) and `source` (server-assigned channel,
164
+ * e.g. `worker`) appear when the frame carries them. Provenance contract:
165
+ * the transport records the envelope from the delivering frame, keyed by the
166
+ * exact message object it yields, and never writes it onto the message; a
167
+ * `ccr_event` field arriving inside any payload is a sender-authored claim
168
+ * and is stripped, so this accessor is the only way to read an envelope.
169
+ * Looked up by object identity — pass the message exactly as the query
170
+ * yielded it. Returns undefined for anything that transport did not itself
171
+ * yield from a durable frame: unsequenced ephemerals (`stream_event`,
172
+ * `sources_changed`, live-only `system` status frames), messages of a
173
+ * WebSocket-transport query, copies, and caller-constructed objects,
174
+ * regardless of the fields they carry. `sequence_num` is dense over ALL of
175
+ * the session's events, including control frames the SDK consumes
176
+ * internally and frames it drops, so consecutive yielded messages need not
177
+ * carry consecutive numbers.
178
+ */
179
+ export declare function getCcrEvent(query: Query, message: SDKMessage): {
180
+ event_id: string;
181
+ sequence_num: number;
182
+ created_at?: string;
183
+ source?: string;
184
+ } | undefined;
@@ -0,0 +1,20 @@
1
+ export {
2
+ AbortError,
3
+ createSdkMcpServer,
4
+ deleteSession,
5
+ EXIT_REASONS,
6
+ filterEscalatingDefaultMode,
7
+ HOOK_EVENTS,
8
+ ORG_POLICY_LIMIT_PREFIXES,
9
+ query,
10
+ renameSession,
11
+ resolveSettings,
12
+ startup,
13
+ SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
14
+ tagSession,
15
+ tool,
16
+ USAGE_LIMIT_ERROR_PREFIXES,
17
+ USAGE_TRANSITION_PREFIXES,
18
+ USAGE_WARNING_PREFIXES,
19
+ } from './sdk.js'
20
+ export type * from './sdk.js'
@@ -0,0 +1 @@
1
+ export function extractFromBunfs(embeddedPath: string): string