@b3os/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +233 -2
  3. package/dist/cjs/core/client.d.ts +165 -0
  4. package/dist/cjs/core/client.js +825 -0
  5. package/dist/cjs/core/client.js.map +1 -0
  6. package/dist/cjs/core/errors.d.ts +101 -0
  7. package/dist/cjs/core/errors.js +249 -0
  8. package/dist/cjs/core/errors.js.map +1 -0
  9. package/dist/cjs/core/index.d.ts +12 -0
  10. package/dist/cjs/core/index.js +42 -0
  11. package/dist/cjs/core/index.js.map +1 -0
  12. package/dist/cjs/core/jobs.d.ts +31 -0
  13. package/dist/cjs/core/jobs.js +72 -0
  14. package/dist/cjs/core/jobs.js.map +1 -0
  15. package/dist/cjs/core/namespace.d.ts +7 -0
  16. package/dist/cjs/core/namespace.js +13 -0
  17. package/dist/cjs/core/namespace.js.map +1 -0
  18. package/dist/cjs/core/op.d.ts +47 -0
  19. package/dist/cjs/core/op.js +5 -0
  20. package/dist/cjs/core/op.js.map +1 -0
  21. package/dist/cjs/core/promise.d.ts +106 -0
  22. package/dist/cjs/core/promise.js +200 -0
  23. package/dist/cjs/core/promise.js.map +1 -0
  24. package/dist/cjs/core/response.d.ts +54 -0
  25. package/dist/cjs/core/response.js +92 -0
  26. package/dist/cjs/core/response.js.map +1 -0
  27. package/dist/cjs/core/sse.d.ts +79 -0
  28. package/dist/cjs/core/sse.js +291 -0
  29. package/dist/cjs/core/sse.js.map +1 -0
  30. package/dist/cjs/core/timing.d.ts +20 -0
  31. package/dist/cjs/core/timing.js +96 -0
  32. package/dist/cjs/core/timing.js.map +1 -0
  33. package/dist/cjs/core/transport.d.ts +80 -0
  34. package/dist/cjs/core/transport.js +472 -0
  35. package/dist/cjs/core/transport.js.map +1 -0
  36. package/dist/cjs/core/util.d.ts +25 -0
  37. package/dist/cjs/core/util.js +142 -0
  38. package/dist/cjs/core/util.js.map +1 -0
  39. package/dist/cjs/core/ws.d.ts +52 -0
  40. package/dist/cjs/core/ws.js +181 -0
  41. package/dist/cjs/core/ws.js.map +1 -0
  42. package/dist/cjs/generated/client.d.ts +62 -0
  43. package/dist/cjs/generated/client.js +130 -0
  44. package/dist/cjs/generated/client.js.map +1 -0
  45. package/dist/cjs/generated/errors.d.ts +4 -0
  46. package/dist/cjs/generated/errors.js +160 -0
  47. package/dist/cjs/generated/errors.js.map +1 -0
  48. package/dist/cjs/generated/ids.d.ts +114 -0
  49. package/dist/cjs/generated/ids.js +47 -0
  50. package/dist/cjs/generated/ids.js.map +1 -0
  51. package/dist/cjs/generated/jobs.d.ts +10 -0
  52. package/dist/cjs/generated/jobs.js +24 -0
  53. package/dist/cjs/generated/jobs.js.map +1 -0
  54. package/dist/cjs/generated/ns/actions.d.ts +161 -0
  55. package/dist/cjs/generated/ns/actions.js +304 -0
  56. package/dist/cjs/generated/ns/actions.js.map +1 -0
  57. package/dist/cjs/generated/ns/infer.d.ts +190 -0
  58. package/dist/cjs/generated/ns/infer.js +253 -0
  59. package/dist/cjs/generated/ns/infer.js.map +1 -0
  60. package/dist/cjs/generated/ns/keys.d.ts +76 -0
  61. package/dist/cjs/generated/ns/keys.js +144 -0
  62. package/dist/cjs/generated/ns/keys.js.map +1 -0
  63. package/dist/cjs/generated/ns/limits.d.ts +22 -0
  64. package/dist/cjs/generated/ns/limits.js +32 -0
  65. package/dist/cjs/generated/ns/limits.js.map +1 -0
  66. package/dist/cjs/generated/ns/orgs.d.ts +38 -0
  67. package/dist/cjs/generated/ns/orgs.js +68 -0
  68. package/dist/cjs/generated/ns/orgs.js.map +1 -0
  69. package/dist/cjs/generated/ns/projects.d.ts +57 -0
  70. package/dist/cjs/generated/ns/projects.js +115 -0
  71. package/dist/cjs/generated/ns/projects.js.map +1 -0
  72. package/dist/cjs/generated/ns/render.d.ts +159 -0
  73. package/dist/cjs/generated/ns/render.js +299 -0
  74. package/dist/cjs/generated/ns/render.js.map +1 -0
  75. package/dist/cjs/generated/ns/requests.d.ts +36 -0
  76. package/dist/cjs/generated/ns/requests.js +54 -0
  77. package/dist/cjs/generated/ns/requests.js.map +1 -0
  78. package/dist/cjs/generated/ns/routines.d.ts +212 -0
  79. package/dist/cjs/generated/ns/routines.js +419 -0
  80. package/dist/cjs/generated/ns/routines.js.map +1 -0
  81. package/dist/cjs/generated/ns/sandboxes.d.ts +318 -0
  82. package/dist/cjs/generated/ns/sandboxes.js +549 -0
  83. package/dist/cjs/generated/ns/sandboxes.js.map +1 -0
  84. package/dist/cjs/generated/ns/usage.d.ts +30 -0
  85. package/dist/cjs/generated/ns/usage.js +49 -0
  86. package/dist/cjs/generated/ns/usage.js.map +1 -0
  87. package/dist/cjs/generated/ns/vault.d.ts +69 -0
  88. package/dist/cjs/generated/ns/vault.js +122 -0
  89. package/dist/cjs/generated/ns/vault.js.map +1 -0
  90. package/dist/cjs/generated/ns/vision.d.ts +376 -0
  91. package/dist/cjs/generated/ns/vision.js +736 -0
  92. package/dist/cjs/generated/ns/vision.js.map +1 -0
  93. package/dist/cjs/generated/ns/webhooks.d.ts +50 -0
  94. package/dist/cjs/generated/ns/webhooks.js +91 -0
  95. package/dist/cjs/generated/ns/webhooks.js.map +1 -0
  96. package/dist/cjs/generated/types.d.ts +4613 -0
  97. package/dist/cjs/generated/types.js +4 -0
  98. package/dist/cjs/generated/types.js.map +1 -0
  99. package/dist/cjs/index.d.ts +22 -0
  100. package/dist/cjs/index.js +81 -0
  101. package/dist/cjs/index.js.map +1 -0
  102. package/dist/cjs/package.json +3 -0
  103. package/dist/cjs/webhooks.d.ts +19 -0
  104. package/dist/cjs/webhooks.js +85 -0
  105. package/dist/cjs/webhooks.js.map +1 -0
  106. package/dist/esm/core/client.d.ts +165 -0
  107. package/dist/esm/core/client.js +821 -0
  108. package/dist/esm/core/client.js.map +1 -0
  109. package/dist/esm/core/errors.d.ts +101 -0
  110. package/dist/esm/core/errors.js +239 -0
  111. package/dist/esm/core/errors.js.map +1 -0
  112. package/dist/esm/core/index.d.ts +12 -0
  113. package/dist/esm/core/index.js +15 -0
  114. package/dist/esm/core/index.js.map +1 -0
  115. package/dist/esm/core/jobs.d.ts +31 -0
  116. package/dist/esm/core/jobs.js +66 -0
  117. package/dist/esm/core/jobs.js.map +1 -0
  118. package/dist/esm/core/namespace.d.ts +7 -0
  119. package/dist/esm/core/namespace.js +9 -0
  120. package/dist/esm/core/namespace.js.map +1 -0
  121. package/dist/esm/core/op.d.ts +47 -0
  122. package/dist/esm/core/op.js +4 -0
  123. package/dist/esm/core/op.js.map +1 -0
  124. package/dist/esm/core/promise.d.ts +106 -0
  125. package/dist/esm/core/promise.js +193 -0
  126. package/dist/esm/core/promise.js.map +1 -0
  127. package/dist/esm/core/response.d.ts +54 -0
  128. package/dist/esm/core/response.js +86 -0
  129. package/dist/esm/core/response.js.map +1 -0
  130. package/dist/esm/core/sse.d.ts +79 -0
  131. package/dist/esm/core/sse.js +286 -0
  132. package/dist/esm/core/sse.js.map +1 -0
  133. package/dist/esm/core/timing.d.ts +20 -0
  134. package/dist/esm/core/timing.js +92 -0
  135. package/dist/esm/core/timing.js.map +1 -0
  136. package/dist/esm/core/transport.d.ts +80 -0
  137. package/dist/esm/core/transport.js +465 -0
  138. package/dist/esm/core/transport.js.map +1 -0
  139. package/dist/esm/core/util.d.ts +25 -0
  140. package/dist/esm/core/util.js +128 -0
  141. package/dist/esm/core/util.js.map +1 -0
  142. package/dist/esm/core/ws.d.ts +52 -0
  143. package/dist/esm/core/ws.js +175 -0
  144. package/dist/esm/core/ws.js.map +1 -0
  145. package/dist/esm/generated/client.d.ts +62 -0
  146. package/dist/esm/generated/client.js +126 -0
  147. package/dist/esm/generated/client.js.map +1 -0
  148. package/dist/esm/generated/errors.d.ts +4 -0
  149. package/dist/esm/generated/errors.js +157 -0
  150. package/dist/esm/generated/errors.js.map +1 -0
  151. package/dist/esm/generated/ids.d.ts +114 -0
  152. package/dist/esm/generated/ids.js +42 -0
  153. package/dist/esm/generated/ids.js.map +1 -0
  154. package/dist/esm/generated/jobs.d.ts +10 -0
  155. package/dist/esm/generated/jobs.js +21 -0
  156. package/dist/esm/generated/jobs.js.map +1 -0
  157. package/dist/esm/generated/ns/actions.d.ts +161 -0
  158. package/dist/esm/generated/ns/actions.js +300 -0
  159. package/dist/esm/generated/ns/actions.js.map +1 -0
  160. package/dist/esm/generated/ns/infer.d.ts +190 -0
  161. package/dist/esm/generated/ns/infer.js +249 -0
  162. package/dist/esm/generated/ns/infer.js.map +1 -0
  163. package/dist/esm/generated/ns/keys.d.ts +76 -0
  164. package/dist/esm/generated/ns/keys.js +140 -0
  165. package/dist/esm/generated/ns/keys.js.map +1 -0
  166. package/dist/esm/generated/ns/limits.d.ts +22 -0
  167. package/dist/esm/generated/ns/limits.js +28 -0
  168. package/dist/esm/generated/ns/limits.js.map +1 -0
  169. package/dist/esm/generated/ns/orgs.d.ts +38 -0
  170. package/dist/esm/generated/ns/orgs.js +64 -0
  171. package/dist/esm/generated/ns/orgs.js.map +1 -0
  172. package/dist/esm/generated/ns/projects.d.ts +57 -0
  173. package/dist/esm/generated/ns/projects.js +111 -0
  174. package/dist/esm/generated/ns/projects.js.map +1 -0
  175. package/dist/esm/generated/ns/render.d.ts +159 -0
  176. package/dist/esm/generated/ns/render.js +295 -0
  177. package/dist/esm/generated/ns/render.js.map +1 -0
  178. package/dist/esm/generated/ns/requests.d.ts +36 -0
  179. package/dist/esm/generated/ns/requests.js +50 -0
  180. package/dist/esm/generated/ns/requests.js.map +1 -0
  181. package/dist/esm/generated/ns/routines.d.ts +212 -0
  182. package/dist/esm/generated/ns/routines.js +415 -0
  183. package/dist/esm/generated/ns/routines.js.map +1 -0
  184. package/dist/esm/generated/ns/sandboxes.d.ts +318 -0
  185. package/dist/esm/generated/ns/sandboxes.js +545 -0
  186. package/dist/esm/generated/ns/sandboxes.js.map +1 -0
  187. package/dist/esm/generated/ns/usage.d.ts +30 -0
  188. package/dist/esm/generated/ns/usage.js +45 -0
  189. package/dist/esm/generated/ns/usage.js.map +1 -0
  190. package/dist/esm/generated/ns/vault.d.ts +69 -0
  191. package/dist/esm/generated/ns/vault.js +118 -0
  192. package/dist/esm/generated/ns/vault.js.map +1 -0
  193. package/dist/esm/generated/ns/vision.d.ts +376 -0
  194. package/dist/esm/generated/ns/vision.js +732 -0
  195. package/dist/esm/generated/ns/vision.js.map +1 -0
  196. package/dist/esm/generated/ns/webhooks.d.ts +50 -0
  197. package/dist/esm/generated/ns/webhooks.js +87 -0
  198. package/dist/esm/generated/ns/webhooks.js.map +1 -0
  199. package/dist/esm/generated/types.d.ts +4613 -0
  200. package/dist/esm/generated/types.js +3 -0
  201. package/dist/esm/generated/types.js.map +1 -0
  202. package/dist/esm/index.d.ts +22 -0
  203. package/dist/esm/index.js +28 -0
  204. package/dist/esm/index.js.map +1 -0
  205. package/dist/esm/webhooks.d.ts +19 -0
  206. package/dist/esm/webhooks.js +79 -0
  207. package/dist/esm/webhooks.js.map +1 -0
  208. package/package.json +97 -3
  209. package/src/core/client.ts +1022 -0
  210. package/src/core/errors.ts +296 -0
  211. package/src/core/index.ts +45 -0
  212. package/src/core/jobs.ts +94 -0
  213. package/src/core/namespace.ts +10 -0
  214. package/src/core/op.ts +53 -0
  215. package/src/core/promise.ts +268 -0
  216. package/src/core/response.ts +115 -0
  217. package/src/core/sse.ts +305 -0
  218. package/src/core/timing.ts +106 -0
  219. package/src/core/transport.ts +489 -0
  220. package/src/core/util.ts +138 -0
  221. package/src/core/ws.ts +215 -0
  222. package/src/generated/client.ts +143 -0
  223. package/src/generated/errors.ts +313 -0
  224. package/src/generated/ids.ts +47 -0
  225. package/src/generated/jobs.ts +25 -0
  226. package/src/generated/ns/actions.ts +353 -0
  227. package/src/generated/ns/infer.ts +332 -0
  228. package/src/generated/ns/keys.ts +152 -0
  229. package/src/generated/ns/limits.ts +35 -0
  230. package/src/generated/ns/orgs.ts +77 -0
  231. package/src/generated/ns/projects.ts +122 -0
  232. package/src/generated/ns/render.ts +348 -0
  233. package/src/generated/ns/requests.ts +61 -0
  234. package/src/generated/ns/routines.ts +474 -0
  235. package/src/generated/ns/sandboxes.ts +671 -0
  236. package/src/generated/ns/usage.ts +56 -0
  237. package/src/generated/ns/vault.ts +136 -0
  238. package/src/generated/ns/vision.ts +836 -0
  239. package/src/generated/ns/webhooks.ts +100 -0
  240. package/src/generated/types.ts +5131 -0
  241. package/src/index.ts +30 -0
  242. package/src/webhooks.ts +100 -0
@@ -0,0 +1,1022 @@
1
+ // The core client: configuration, routing between beta-api.b3os.org and the same-host fast paths, the request
2
+ // pipeline (idempotency keys, retries with jittered backoff, timeouts, typed errors, Server-Timing), and the job
3
+ // and stream plumbing the generated namespaces call. It knows no product; src/generated/ns/* do.
4
+
5
+ import {
6
+ B3OSAbortError,
7
+ B3OSConnectionError,
8
+ B3OSError,
9
+ B3OSJobError,
10
+ B3OSTimeoutError,
11
+ NEVER_REACHED_STATUSES,
12
+ parseErrorBody,
13
+ } from "./errors.ts";
14
+ import type { CallArgs, JobOps, Op } from "./op.ts";
15
+ import {
16
+ APIPromise,
17
+ JobEventStream,
18
+ type JobEventsOptions,
19
+ type JobLike,
20
+ JobPromise,
21
+ type JobRunner,
22
+ type ListPage,
23
+ ListPromise,
24
+ TERMINAL_JOB_EVENTS,
25
+ TERMINAL_JOB_STATUSES,
26
+ type WaitOptions,
27
+ type WithResponse,
28
+ } from "./promise.ts";
29
+ import { ResponseInfo, remember } from "./response.ts";
30
+ import { EventStream, type EventStreamOptions, type SSEMessage } from "./sse.ts";
31
+ import {
32
+ FetchTransport,
33
+ NodeHttpTransport,
34
+ type RequestBody,
35
+ socketExists,
36
+ type Transport,
37
+ type TransportResponse,
38
+ TransportTimeout,
39
+ } from "./transport.ts";
40
+ import { backoffMs, env, isObject, parseRetryAfter, runtime, runtimeLabel, SDK_VERSION, sleep, uuid } from "./util.ts";
41
+
42
+ /** A binary request body (file uploads, pack bundles). */
43
+ export type BinaryInput = RequestBody;
44
+
45
+ export const DEFAULT_BASE_URL = "https://beta-api.b3os.org";
46
+ /** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
47
+ export const DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
48
+
49
+ export interface ClientOptions {
50
+ /** API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`. */
51
+ apiKey?: string | null;
52
+ /** The API host for edge-served operations and remote calls. Default: `B3OS_BASE_URL`, else beta-api.b3os.org. */
53
+ baseUrl?: string;
54
+ /**
55
+ * A node-local HTTP URL for node-served operations, sent without the API key. Default: `B3OS_API_URL`, which
56
+ * B3OS sets to `http://127.0.0.1:7700` inside sandboxes (the sandbox's own grant decides what it may call).
57
+ */
58
+ nodeUrl?: string | null;
59
+ /**
60
+ * b3osd's Unix socket for node-served operations (the same-host fast path; the node maps your uid to a
61
+ * principal, no API key is sent). Default: `B3OS_SOCKET`, else `/run/b3os/b3osd/b3osd.sock` when it exists and
62
+ * neither an API key nor a base URL was configured: with a key, node-served calls would otherwise run as the
63
+ * uid's principal (possibly another org) while edge-served calls run as the key's. `false` disables the socket.
64
+ */
65
+ socketPath?: string | false | null;
66
+ /**
67
+ * `auto` (default) picks the fastest path as above; `http` sends everything to `baseUrl` with the API key.
68
+ * Default: `B3OS_TRANSPORT`.
69
+ */
70
+ transport?: "auto" | "http";
71
+ /** Per-attempt timeout. Default: the operation's `x-b3os-timeout-ms` (capped at 65 s) plus 5 s. */
72
+ timeoutMs?: number;
73
+ /** Retries for retry-safe failures. Default 2. */
74
+ maxRetries?: number;
75
+ /** Longest `Retry-After` the client waits out by itself. Default 60 s. */
76
+ maxRetryDelayMs?: number;
77
+ /** A fetch implementation (tests, proxies, Workers service bindings). */
78
+ fetch?: (input: string, init?: RequestInit) => Promise<Response>;
79
+ /** Headers added to every request. */
80
+ headers?: Record<string, string>;
81
+ /** Called after every response head, successful or not. */
82
+ onResponse?: (info: ResponseInfo) => void;
83
+ }
84
+
85
+ export interface RequestOptions {
86
+ /** `Idempotency-Key` for this call; generated when the operation takes one and you pass none. */
87
+ idempotencyKey?: string;
88
+ timeoutMs?: number;
89
+ maxRetries?: number;
90
+ signal?: AbortSignal;
91
+ headers?: Record<string, string>;
92
+ /** W3C trace context, propagated into product calls and routine steps. */
93
+ traceparent?: string;
94
+ }
95
+
96
+ export interface StreamOptions extends RequestOptions {
97
+ /** Resume after this event id (`seq`). */
98
+ lastEventId?: string;
99
+ idleTimeoutMs?: number;
100
+ maxReconnects?: number;
101
+ }
102
+
103
+ /** A request to an operation the generated namespaces do not wrap (`client.request`). */
104
+ export interface RawRequest {
105
+ method: Op["method"];
106
+ path: string;
107
+ query?: object;
108
+ body?: unknown;
109
+ bodyType?: "json" | "bytes" | "yaml" | "form";
110
+ headers?: Record<string, string>;
111
+ /** Send to beta-api.b3os.org (edge-served operations). Default: by path, account paths go to the edge. */
112
+ edge?: boolean;
113
+ /** Error shape of the endpoint. */
114
+ errorFormat?: Op["errorFormat"];
115
+ timeoutMs?: number;
116
+ }
117
+
118
+ interface Route {
119
+ kind: "edge" | "node-http" | "uds";
120
+ transport: Transport;
121
+ /** URL prefix without a trailing slash. */
122
+ base: string;
123
+ /** Send `Authorization: Bearer <apiKey>`. */
124
+ auth: boolean;
125
+ /** Auto-detected default socket: fall back to the edge when it refuses connections. */
126
+ auto: boolean;
127
+ }
128
+
129
+ interface Sent {
130
+ res: TransportResponse;
131
+ info: ResponseInfo;
132
+ }
133
+
134
+ interface SendExtras {
135
+ accept: string;
136
+ /** The response is an event stream: the per-attempt timeout covers only the response head. */
137
+ sse?: boolean;
138
+ extraQuery?: Record<string, string>;
139
+ }
140
+
141
+ const JSON_CT = /^application\/(?:[\w.+-]+\+)?json\b/i;
142
+ const NO_RETRY_TIMEOUT_CODES = new Set(["request_timeout", "upstream_timeout", "scrape_timeout", "job_timed_out"]);
143
+ /**
144
+ * Codes that reject a request before any work, so even non-idempotent calls may be retried. They count only when
145
+ * B3OS said so in the error body, or when the status alone proves the request never got in (NEVER_REACHED_STATUSES):
146
+ * an intermediary's 502 or 503 page may come after the origin already ran the request.
147
+ */
148
+ const REJECTED_BEFORE_WORK = new Set([
149
+ "rate_limited",
150
+ "concurrency_limited",
151
+ "ticket_limit",
152
+ "node_unavailable",
153
+ "product_unavailable",
154
+ "capacity_unavailable",
155
+ "auth_unavailable",
156
+ "idempotency_request_in_progress",
157
+ ]);
158
+
159
+ function trimSlash(s: string): string {
160
+ return s.endsWith("/") ? s.replace(/\/+$/, "") : s;
161
+ }
162
+
163
+ /** Percent-encodes what a request target cannot carry, leaving URL syntax (and existing escapes) alone. */
164
+ function encodeWildcard(v: string): string {
165
+ const hash = v.indexOf("#");
166
+ const s = hash >= 0 ? v.slice(0, hash) : v;
167
+ return s.replace(/[^A-Za-z0-9\-._~:/?\[\]@!$&'()*+,;=%]/g, (c) =>
168
+ Array.from(new TextEncoder().encode(c), (b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`).join(""),
169
+ );
170
+ }
171
+
172
+ /** `.` or `..`, also percent-encoded (`%2e`, `.%2E`): URL parsers (WHATWG, httpx) resolve these segments. */
173
+ const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
174
+ /** `scheme://authority` + path + query of an absolute URL given as a wildcard value (vision.readUrl). */
175
+ const ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*)([^?#]*)(.*)$/s;
176
+
177
+ function hasDotSegment(path: string): boolean {
178
+ return path.split("/").some((seg) => DOT_SEGMENT.test(seg));
179
+ }
180
+
181
+ /** RFC 3986 §5.2.4 remove_dot_segments on an absolute path, treating `%2e` as `.` as WHATWG URL parsing does. */
182
+ function removeDotSegments(path: string): string {
183
+ const segs = path.split("/");
184
+ const out: string[] = [];
185
+ for (let i = 0; i < segs.length; i++) {
186
+ const seg = segs[i] as string;
187
+ const last = i === segs.length - 1;
188
+ if (i > 0 && DOT_SEGMENT.test(seg)) {
189
+ if (seg.replace(/%2e/gi, ".") === ".." && out.length > 1) out.pop();
190
+ if (last) out.push("");
191
+ } else {
192
+ out.push(seg);
193
+ }
194
+ }
195
+ return out.join("/");
196
+ }
197
+
198
+ /**
199
+ * A wildcard path value (a target URL, a model id that contains `/`) with dot segments resolved inside it, so
200
+ * they can never climb out of the operation's own path: `/v1/vision/r/https://x/../../../v1/keys` would
201
+ * otherwise reach `GET /v1/keys` with the API key. An absolute URL is normalized the way the target server
202
+ * would see it anyway; any other value with a dot segment is refused.
203
+ */
204
+ function safeWildcard(op: Op, name: string, v: string): string {
205
+ const hash = v.indexOf("#");
206
+ let s = hash >= 0 ? v.slice(0, hash) : v;
207
+ const q = s.indexOf("?");
208
+ if (hasDotSegment(q >= 0 ? s.slice(0, q) : s)) {
209
+ const m = ABSOLUTE_URL.exec(s);
210
+ if (m) s = `${m[1]}${removeDotSegments(m[2] as string)}${m[3]}`;
211
+ const q2 = s.indexOf("?");
212
+ if (hasDotSegment(q2 >= 0 ? s.slice(0, q2) : s)) {
213
+ throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} must not contain "." or ".." segments`);
214
+ }
215
+ }
216
+ return encodeWildcard(s);
217
+ }
218
+
219
+ /** Account paths `request()` sends to the API host unless told otherwise. */
220
+ const EDGE_PATHS = /^\/v1\/(keys|usage|limits|orgs|projects|auth|actions\/registry)(\/|$)/;
221
+
222
+ function buildPath(op: Op, values: readonly (string | number)[] | undefined): string {
223
+ if (!op.path.includes("{")) return op.path;
224
+ const names = op.params ?? [];
225
+ let i = 0;
226
+ return op.path.replace(/\{([^}]+)\}/g, (_, name: string) => {
227
+ const idx = names.indexOf(name);
228
+ const v = values?.[idx >= 0 ? idx : i];
229
+ i++;
230
+ if (v === undefined || v === null || v === "") {
231
+ throw new TypeError(`@b3os/sdk: ${op.id} needs the path parameter ${name}`);
232
+ }
233
+ const s = String(v);
234
+ if (name === op.wildcard) return safeWildcard(op, name, s);
235
+ if (s === "." || s === "..") {
236
+ // encodeURIComponent keeps dots, and a lone ".." segment would move the request to the parent path.
237
+ throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} cannot be "${s}"`);
238
+ }
239
+ return encodeURIComponent(s);
240
+ });
241
+ }
242
+
243
+ function buildQuery(query: object | undefined, extra?: Record<string, string>): string {
244
+ let sp: URLSearchParams | undefined;
245
+ if (query) {
246
+ for (const [k, v] of Object.entries(query)) {
247
+ if (v === undefined || v === null) continue;
248
+ sp ??= new URLSearchParams();
249
+ if (Array.isArray(v)) for (const x of v) sp.append(k, String(x));
250
+ else if (v instanceof Date) sp.append(k, v.toISOString());
251
+ else sp.append(k, String(v));
252
+ }
253
+ }
254
+ if (extra) {
255
+ sp ??= new URLSearchParams();
256
+ for (const [k, v] of Object.entries(extra)) sp.set(k, v);
257
+ }
258
+ const s = sp ? sp.toString() : "";
259
+ return s ? `?${s}` : "";
260
+ }
261
+
262
+ function isTerminalJob(j: unknown): j is JobLike {
263
+ return isObject(j) && typeof j.status === "string" && TERMINAL_JOB_STATUSES.has(j.status);
264
+ }
265
+
266
+ function jobIdOf(j: unknown): string {
267
+ if (typeof j === "string") return j;
268
+ if (isObject(j) && typeof j.id === "string") return j.id;
269
+ throw new TypeError("@b3os/sdk: expected a job object or a job id");
270
+ }
271
+
272
+ function eventType(ev: unknown): string | undefined {
273
+ return isObject(ev) && typeof ev.type === "string" ? ev.type : undefined;
274
+ }
275
+
276
+ function connectRefused(err: unknown): boolean {
277
+ const code = (err as { code?: string } | undefined)?.code;
278
+ return code === "ENOENT" || code === "ECONNREFUSED" || code === "EACCES" || code === "EPERM";
279
+ }
280
+
281
+ function describeErr(err: unknown): string {
282
+ if (err instanceof Error) {
283
+ const cause = (err as Error & { cause?: { code?: string; message?: string } }).cause;
284
+ const code = (err as { code?: string }).code ?? cause?.code;
285
+ const msg = cause?.message && cause.message !== err.message ? `${err.message} (${cause.message})` : err.message;
286
+ return code && !msg.includes(code) ? `${code}: ${msg}` : msg;
287
+ }
288
+ return String(err);
289
+ }
290
+
291
+ export class B3OSCore {
292
+ readonly apiKey: string | null;
293
+ readonly baseUrl: string;
294
+ readonly maxRetries: number;
295
+ readonly maxRetryDelayMs: number;
296
+ readonly timeoutMs: number | undefined;
297
+ private edge: Route;
298
+ private node: Route;
299
+ private readonly headers: Record<string, string>;
300
+ private readonly onResponse: ((info: ResponseInfo) => void) | undefined;
301
+
302
+ constructor(options: ClientOptions = {}) {
303
+ this.apiKey = options.apiKey !== undefined ? options.apiKey : (env("B3OS_API_KEY") ?? null);
304
+ const explicitBase = options.baseUrl ?? env("B3OS_BASE_URL");
305
+ this.baseUrl = trimSlash(explicitBase ?? DEFAULT_BASE_URL);
306
+ this.maxRetries = options.maxRetries ?? 2;
307
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
308
+ this.timeoutMs = options.timeoutMs;
309
+ this.onResponse = options.onResponse;
310
+ const headers: Record<string, string> = {};
311
+ const rt = runtime();
312
+ if (rt === "node" || rt === "bun" || rt === "deno" || rt === "workerd") {
313
+ headers["user-agent"] = `b3os-sdk-ts/${SDK_VERSION} ${runtimeLabel()}`;
314
+ }
315
+ for (const [k, v] of Object.entries(options.headers ?? {})) headers[k.toLowerCase()] = v;
316
+ this.headers = headers;
317
+
318
+ const fetchT = new FetchTransport(this.baseUrl, options.fetch);
319
+ this.edge = { kind: "edge", transport: fetchT, base: this.baseUrl, auth: true, auto: false };
320
+
321
+ const pref = options.transport ?? (env("B3OS_TRANSPORT") as ClientOptions["transport"]) ?? "auto";
322
+ const sockEnv = env("B3OS_SOCKET");
323
+ const sockDisabled = options.socketPath === false || sockEnv === "0" || sockEnv === "off";
324
+ const nodeUrl = options.nodeUrl !== undefined ? options.nodeUrl : (env("B3OS_API_URL") ?? null);
325
+ let node: Route = this.edge;
326
+ if (pref !== "http") {
327
+ const explicitSock =
328
+ typeof options.socketPath === "string" ? options.socketPath : sockDisabled ? undefined : sockEnv;
329
+ if (explicitSock) {
330
+ node = this.udsRoute(explicitSock, false, options.fetch);
331
+ } else if (nodeUrl) {
332
+ const base = trimSlash(nodeUrl);
333
+ // Plain HTTP to the node (inside a sandbox) goes through node:http keep-alive on Node, unless the caller
334
+ // supplied its own fetch.
335
+ const useNodeHttp = !options.fetch && base.startsWith("http:") && NodeHttpTransport.available();
336
+ node = {
337
+ kind: "node-http",
338
+ transport: useNodeHttp ? new NodeHttpTransport({ baseUrl: base }) : new FetchTransport(base, options.fetch),
339
+ base,
340
+ auth: false,
341
+ auto: false,
342
+ };
343
+ } else if (
344
+ !this.apiKey &&
345
+ !explicitBase &&
346
+ !sockDisabled &&
347
+ options.socketPath !== null &&
348
+ socketExists(DEFAULT_SOCKET_PATH)
349
+ ) {
350
+ // Only without a key: the socket acts as the uid's principal, and silently mixing it with the key's
351
+ // principal (whoami says org A, listSandboxes shows org B) is worse than the network hop.
352
+ node = this.udsRoute(DEFAULT_SOCKET_PATH, true, options.fetch);
353
+ }
354
+ }
355
+ this.node = node;
356
+ }
357
+
358
+ private udsRoute(path: string, auto: boolean, fetchFn: ClientOptions["fetch"]): Route {
359
+ const rt = runtime();
360
+ if (rt === "bun") {
361
+ return {
362
+ kind: "uds",
363
+ transport: new FetchTransport("http://b3osd", fetchFn, path),
364
+ base: "http://b3osd",
365
+ auth: false,
366
+ auto,
367
+ };
368
+ }
369
+ if (!NodeHttpTransport.available()) {
370
+ throw new Error(`@b3os/sdk: the Unix socket ${path} needs Node or Bun; set B3OS_TRANSPORT=http on ${rt}`);
371
+ }
372
+ return {
373
+ kind: "uds",
374
+ transport: new NodeHttpTransport({ socketPath: path }),
375
+ base: "http://b3osd",
376
+ auth: false,
377
+ auto,
378
+ };
379
+ }
380
+
381
+ /** Where node-served and edge-served operations go (`unix:/run/b3os/b3osd/b3osd.sock`, a URL). */
382
+ get routes(): { node: string; edge: string; nodeKind: Route["kind"] } {
383
+ return { node: this.node.transport.label, edge: this.edge.transport.label, nodeKind: this.node.kind };
384
+ }
385
+
386
+ /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
387
+ close(): void {
388
+ this.node.transport.close?.();
389
+ if (this.edge !== this.node) this.edge.transport.close?.();
390
+ }
391
+
392
+ // ------------------------------------------------------------------------------------------------------------
393
+ // The request pipeline
394
+
395
+ private headersFor(route: Route, op: Op, o: RequestOptions, accept: string): Record<string, string> {
396
+ const h: Record<string, string> = { ...this.headers, accept };
397
+ if (route.auth && this.apiKey) h.authorization = `Bearer ${this.apiKey}`;
398
+ if (o.traceparent) h.traceparent = o.traceparent;
399
+ if (o.headers) for (const [k, v] of Object.entries(o.headers)) h[k.toLowerCase()] = v;
400
+ void op;
401
+ return h;
402
+ }
403
+
404
+ private encodeBody(op: Op, args: CallArgs, h: Record<string, string>): RequestBody | undefined {
405
+ const b = args.body;
406
+ if (b === undefined) return undefined;
407
+ const kind = args.bodyType ?? op.body ?? "json";
408
+ if (kind === "json") {
409
+ h["content-type"] ??= "application/json";
410
+ return JSON.stringify(b);
411
+ }
412
+ if (kind === "yaml") {
413
+ h["content-type"] ??= "application/yaml";
414
+ return String(b);
415
+ }
416
+ if (kind === "form") {
417
+ h["content-type"] ??= "application/x-www-form-urlencoded";
418
+ return new URLSearchParams(b as Record<string, string>).toString();
419
+ }
420
+ if (h["content-type"] === undefined) {
421
+ h["content-type"] =
422
+ op.contentType ??
423
+ (typeof Blob !== "undefined" && b instanceof Blob && b.type ? b.type : "application/octet-stream");
424
+ }
425
+ if (typeof b === "string" || b instanceof Uint8Array || b instanceof ArrayBuffer) return b;
426
+ if (typeof Blob !== "undefined" && b instanceof Blob) return b;
427
+ if (typeof ReadableStream !== "undefined" && b instanceof ReadableStream) return b as ReadableStream<Uint8Array>;
428
+ if (ArrayBuffer.isView(b)) return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
429
+ throw new TypeError(`@b3os/sdk: ${op.id} takes a string, Uint8Array, ArrayBuffer, Blob or ReadableStream body`);
430
+ }
431
+
432
+ private hint(route: Route, op: Op, err: B3OSError): string | undefined {
433
+ if (err.code === "edge_only") {
434
+ return this.apiKey
435
+ ? `${op.id} is served by ${this.baseUrl}`
436
+ : `${op.id} is served by ${this.baseUrl}; set B3OS_API_KEY (or pass apiKey) so the SDK can send it there`;
437
+ }
438
+ if (err.status === 401 && route.auth && !this.apiKey) {
439
+ return "No API key is configured: set B3OS_API_KEY or pass apiKey";
440
+ }
441
+ if (err.status === 403 && err.reason === "scope" && route.kind === "uds") {
442
+ return (
443
+ "Over the node's Unix socket this process acts as the local principal its uid maps to in b3osd.toml " +
444
+ "([auth.local_peers], else the read-only [auth.local_default]); set B3OS_TRANSPORT=http to use your API key"
445
+ );
446
+ }
447
+ return undefined;
448
+ }
449
+
450
+ /** Sends one operation with retries. Resolves with a 2xx (or 101) response whose body is still unread. */
451
+ private async send(op: Op, args: CallArgs, o: RequestOptions, x: SendExtras): Promise<Sent> {
452
+ const method = op.method;
453
+ const pathStr = buildPath(op, args.path);
454
+ const query = buildQuery(args.query, x.extraQuery);
455
+ let idemKey = o.idempotencyKey;
456
+ if (!idemKey && op.idem && method !== "GET") idemKey = uuid();
457
+ const streamBody = typeof ReadableStream !== "undefined" && args.body instanceof ReadableStream;
458
+ const retrySafe =
459
+ !streamBody && (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
460
+ const maxRetries = streamBody ? 0 : (o.maxRetries ?? this.maxRetries);
461
+ const perAttempt = o.timeoutMs ?? this.timeoutMs ?? (x.sse ? 30_000 : Math.min(op.timeoutMs, 65_000) + 5_000);
462
+ let route = op.edge ? this.edge : this.node;
463
+ let attempt = 0;
464
+ for (;;) {
465
+ const headers = this.headersFor(route, op, o, x.accept);
466
+ if (idemKey) headers["idempotency-key"] = idemKey;
467
+ if (op.headerParams && args.headerParams) {
468
+ for (const [k, name] of Object.entries(op.headerParams)) {
469
+ const v = (args.headerParams as Record<string, unknown>)[k];
470
+ if (v !== undefined && v !== null) headers[name.toLowerCase()] = String(v);
471
+ }
472
+ }
473
+ const body = this.encodeBody(op, args, headers);
474
+ const path = pathStr + query;
475
+ const url = route.base + path;
476
+ if (o.signal?.aborted) throw new B3OSAbortError({ operationId: op.id, cause: o.signal.reason });
477
+ const t0 = performance.now();
478
+ let res: TransportResponse;
479
+ try {
480
+ // The transport enforces the per-attempt timeout (for streams: until the response head) and the signal.
481
+ res = await route.transport.send({
482
+ method,
483
+ url,
484
+ path,
485
+ headers,
486
+ body,
487
+ signal: o.signal,
488
+ timeoutMs: perAttempt,
489
+ stream: !!x.sse,
490
+ });
491
+ } catch (cause) {
492
+ if (o.signal?.aborted) throw new B3OSAbortError({ operationId: op.id, cause });
493
+ const timedOut = cause instanceof TransportTimeout;
494
+ if (route.auto && connectRefused(cause) && !timedOut) {
495
+ // The node socket exists but refuses us (permissions, stale socket): use the API from now on.
496
+ this.node = this.edge;
497
+ route = this.edge;
498
+ continue;
499
+ }
500
+ const err = timedOut
501
+ ? new B3OSTimeoutError({
502
+ detail: `${op.id} did not answer within ${perAttempt} ms (${route.transport.label})`,
503
+ operationId: op.id,
504
+ cause,
505
+ })
506
+ : new B3OSConnectionError({
507
+ detail: `Could not reach ${route.transport.label}: ${describeErr(cause)}`,
508
+ operationId: op.id,
509
+ cause,
510
+ });
511
+ // Timeouts are not retried: the budget is spent. A refused connection never reached the server.
512
+ if (!timedOut && attempt < maxRetries && (retrySafe || connectRefused(cause))) {
513
+ await sleep(backoffMs(attempt), o.signal).catch(() => {});
514
+ attempt++;
515
+ continue;
516
+ }
517
+ throw err;
518
+ }
519
+ const elapsed = performance.now() - t0;
520
+ const info = new ResponseInfo({
521
+ operationId: op.id,
522
+ method,
523
+ url: route.kind === "uds" ? `${route.transport.label}${path}` : url,
524
+ status: res.status,
525
+ headers: res.headers,
526
+ transport: route.transport.kind,
527
+ attempts: attempt + 1,
528
+ elapsedMs: elapsed,
529
+ idempotencyKey: idemKey,
530
+ });
531
+ try {
532
+ this.onResponse?.(info);
533
+ } catch {
534
+ // A logging hook must never break the call.
535
+ }
536
+ if ((res.status >= 200 && res.status < 300) || res.status === 101) {
537
+ return { res, info };
538
+ }
539
+ // An error answer: read it, decide whether to retry.
540
+ let text = "";
541
+ try {
542
+ text = await res.text();
543
+ } catch {
544
+ text = "";
545
+ }
546
+ const ct = res.headers.get("content-type");
547
+ const parsed = parseErrorBody(res.status, ct, text);
548
+ const retryAfterMs =
549
+ parseRetryAfter(res.headers.get("retry-after")) ??
550
+ (parsed.retryAfterS !== undefined ? parsed.retryAfterS * 1000 : null);
551
+ const err0 = new B3OSError({
552
+ code: parsed.code,
553
+ status: res.status,
554
+ title: parsed.title,
555
+ detail: parsed.detail,
556
+ type: parsed.type,
557
+ requestId: parsed.instance ?? res.headers.get("x-request-id"),
558
+ errors: parsed.errors,
559
+ problem: parsed.problem,
560
+ headers: res.headers,
561
+ timing: info.timing,
562
+ retryAfterMs,
563
+ operationId: op.id,
564
+ });
565
+ const hint = this.hint(route, op, err0);
566
+ const err = hint
567
+ ? new B3OSError({
568
+ code: err0.code,
569
+ status: err0.status,
570
+ title: err0.title,
571
+ detail: err0.detail,
572
+ type: err0.type,
573
+ requestId: err0.requestId,
574
+ errors: err0.errors,
575
+ problem: err0.problem,
576
+ headers: err0.headers,
577
+ timing: err0.timing,
578
+ retryAfterMs,
579
+ operationId: op.id,
580
+ hint,
581
+ })
582
+ : err0;
583
+ const rejectedBeforeWork =
584
+ REJECTED_BEFORE_WORK.has(err.code) && (!parsed.codeFromStatus || NEVER_REACHED_STATUSES.has(res.status));
585
+ const retryable =
586
+ rejectedBeforeWork ||
587
+ (retrySafe && err.retryable && (err.status ?? 0) >= 500 && !NO_RETRY_TIMEOUT_CODES.has(err.code));
588
+ if (attempt < maxRetries && retryable) {
589
+ const delay = retryAfterMs ?? backoffMs(attempt);
590
+ if (delay <= this.maxRetryDelayMs) {
591
+ await sleep(delay + Math.random() * Math.min(250, delay * 0.1), o.signal).catch(() => {});
592
+ if (o.signal?.aborted) throw new B3OSAbortError({ operationId: op.id });
593
+ attempt++;
594
+ continue;
595
+ }
596
+ }
597
+ throw err;
598
+ }
599
+ }
600
+
601
+ private async readBody(
602
+ sent: Sent,
603
+ op: Op,
604
+ expect: "json" | "bytes" | "text" | "auto",
605
+ signal?: AbortSignal,
606
+ ): Promise<unknown> {
607
+ const { res } = sent;
608
+ try {
609
+ if (res.status === 204 || res.status === 101 || op.method === "HEAD") {
610
+ res.cancel();
611
+ return undefined;
612
+ }
613
+ const ct = res.headers.get("content-type") ?? "";
614
+ const isJson = JSON_CT.test(ct);
615
+ if (expect === "bytes" || (expect === "auto" && !isJson && !ct.startsWith("text/"))) {
616
+ return await res.bytes();
617
+ }
618
+ const text = await res.text();
619
+ if (expect === "text" || (expect === "auto" && !isJson)) return text;
620
+ if (text === "") return undefined;
621
+ try {
622
+ return JSON.parse(text);
623
+ } catch (cause) {
624
+ throw new B3OSError({
625
+ code: "invalid_response",
626
+ status: res.status,
627
+ detail: `${op.id} answered ${res.status} with a body that is not JSON (${ct || "no content type"})`,
628
+ requestId: res.headers.get("x-request-id"),
629
+ headers: res.headers,
630
+ operationId: op.id,
631
+ cause,
632
+ });
633
+ }
634
+ } catch (e) {
635
+ if (e instanceof B3OSError) throw e;
636
+ if (e instanceof TransportTimeout) {
637
+ throw new B3OSTimeoutError({
638
+ detail: `${op.id}: the response body did not arrive in time`,
639
+ operationId: op.id,
640
+ cause: e,
641
+ });
642
+ }
643
+ if (signal?.aborted) throw new B3OSAbortError({ operationId: op.id, cause: e });
644
+ throw new B3OSConnectionError({
645
+ detail: `The response body of ${op.id} broke: ${describeErr(e)}`,
646
+ operationId: op.id,
647
+ cause: e,
648
+ });
649
+ }
650
+ }
651
+
652
+ private async exec<T>(
653
+ op: Op,
654
+ args: CallArgs,
655
+ o: RequestOptions,
656
+ accept = "application/json",
657
+ expect: "json" | "bytes" | "text" | "auto" = "auto",
658
+ extraQuery?: Record<string, string>,
659
+ ): Promise<WithResponse<T>> {
660
+ const sent = await this.send(op, args, o, { accept, extraQuery });
661
+ const data = (await this.readBody(sent, op, expect, o.signal)) as T;
662
+ remember(data, sent.info);
663
+ return { data, response: sent.info };
664
+ }
665
+
666
+ // ------------------------------------------------------------------------------------------------------------
667
+ // What the generated namespaces call
668
+
669
+ /** @internal One request, parsed by content type. */
670
+ _call<T>(
671
+ op: Op,
672
+ args: CallArgs,
673
+ options: RequestOptions = {},
674
+ accept?: string,
675
+ expect: "json" | "bytes" | "text" | "auto" = "auto",
676
+ ): APIPromise<T> {
677
+ return new APIPromise<T>(this.exec<T>(op, args, options, accept ?? "application/json", expect));
678
+ }
679
+
680
+ /** @internal A list operation (cursor pagination). */
681
+ _list<P extends ListPage<I>, I>(op: Op, args: CallArgs, options: RequestOptions = {}): ListPromise<P, I> {
682
+ const next = (cursor: string): APIPromise<P> =>
683
+ this._call<P>(op, { ...args, query: { ...(args.query ?? {}), cursor } }, options);
684
+ return new ListPromise<P, I>(this.exec<P>(op, args, options), next);
685
+ }
686
+
687
+ /** @internal A GET event stream (job events, logs), resumed with Last-Event-ID. */
688
+ _stream<E>(
689
+ op: Op,
690
+ args: CallArgs,
691
+ options: StreamOptions = {},
692
+ behavior: { terminal?: (ev: E) => boolean; reconnectOnEnd?: boolean } = {},
693
+ ): EventStream<E> {
694
+ return new EventStream<E>(this.streamOptions<E>(op, args, options, behavior));
695
+ }
696
+
697
+ private streamOptions<E>(
698
+ op: Op,
699
+ args: CallArgs,
700
+ options: StreamOptions,
701
+ behavior: { terminal?: (ev: E) => boolean; reconnectOnEnd?: boolean },
702
+ ): EventStreamOptions<E> {
703
+ return {
704
+ operationId: op.id,
705
+ resumable: true,
706
+ reconnectOnEnd: behavior.reconnectOnEnd ?? false,
707
+ idleTimeoutMs: options.idleTimeoutMs,
708
+ maxReconnects: options.maxReconnects,
709
+ signal: options.signal,
710
+ isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
711
+ open: async (ctx) => {
712
+ const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? options.lastEventId : undefined);
713
+ const headers = { ...(options.headers ?? {}) };
714
+ if (lastId !== undefined) headers["last-event-id"] = lastId;
715
+ const sent = await this.send(
716
+ op,
717
+ args,
718
+ { ...options, headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? options.maxRetries : 0 },
719
+ { accept: "text/event-stream", sse: true },
720
+ );
721
+ return this.expectEventStream(sent, op);
722
+ },
723
+ };
724
+ }
725
+
726
+ private expectEventStream(sent: Sent, op: Op): TransportResponse {
727
+ const res = sent.res;
728
+ const ct = res.headers.get("content-type") ?? "";
729
+ if (!ct.startsWith("text/event-stream")) {
730
+ res.cancel();
731
+ throw new B3OSError({
732
+ code: "invalid_response",
733
+ status: res.status,
734
+ detail: `${op.id} answered ${res.status} with ${ct || "no content type"} instead of an event stream`,
735
+ requestId: sent.info.requestId,
736
+ operationId: op.id,
737
+ });
738
+ }
739
+ return res;
740
+ }
741
+
742
+ /** @internal An SSE response to a POST (exec output, chat chunks): not resumable. */
743
+ _postStream<E>(
744
+ op: Op,
745
+ args: CallArgs,
746
+ options: StreamOptions = {},
747
+ behavior: { terminal?: (ev: E) => boolean; doneSentinel?: boolean; extraQuery?: Record<string, string> } = {},
748
+ ): EventStream<E> {
749
+ return new EventStream<E>({
750
+ operationId: op.id,
751
+ resumable: false,
752
+ doneSentinel: behavior.doneSentinel,
753
+ idleTimeoutMs: options.idleTimeoutMs,
754
+ signal: options.signal,
755
+ isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
756
+ open: async (ctx) => {
757
+ const sent = await this.send(
758
+ op,
759
+ args,
760
+ { ...options, signal: ctx.signal },
761
+ { accept: "text/event-stream", sse: true, extraQuery: behavior.extraQuery },
762
+ );
763
+ return this.expectEventStream(sent, op);
764
+ },
765
+ });
766
+ }
767
+
768
+ /** @internal A job-creating operation (`x-b3os-job`). */
769
+ _job<J extends JobLike, E>(op: Op, args: CallArgs, options: RequestOptions = {}): JobPromise<J, E> {
770
+ const ops = op.job;
771
+ if (!ops) throw new Error(`@b3os/sdk: ${op.id} is not a job operation`);
772
+ // One idempotency key for every request that creates this job, whatever the mode.
773
+ const o: RequestOptions = op.idem ? { ...options, idempotencyKey: options.idempotencyKey ?? uuid() } : options;
774
+ const runner: JobRunner<J, E> = {
775
+ create: () => this.exec<J>(op, args, o),
776
+ createAndWait: async (w) => {
777
+ const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
778
+ const waitS = Math.max(0, Math.min(60, Math.floor((deadline - Date.now()) / 1000)));
779
+ const first = await this.exec<J>(op, args, { ...o, signal: w.signal ?? o.signal }, "application/json", "auto", {
780
+ wait: String(waitS),
781
+ });
782
+ const data = await this.waitJob<J, E>(ops, first.data, { ...w, timeoutMs: deadline - Date.now() });
783
+ return { data, response: first.response };
784
+ },
785
+ createAndStream: (so) => this.createStream<J, E>(op, args, o, so),
786
+ waitFor: (job, w) => this.waitJob<J, E>(ops, job, w),
787
+ eventsFor: (created, so) => this.jobEventStream<J, E>(ops, created, so),
788
+ };
789
+ return new JobPromise<J, E>(runner);
790
+ }
791
+
792
+ private createStream<J extends JobLike, E>(
793
+ op: Op,
794
+ args: CallArgs,
795
+ o: RequestOptions,
796
+ so: JobEventsOptions,
797
+ ): JobEventStream<E, J> {
798
+ const ops = op.job as JobOps;
799
+ return new JobEventStream<E, J>(
800
+ {
801
+ operationId: op.id,
802
+ resumable: true,
803
+ reconnectOnEnd: true,
804
+ idleTimeoutMs: so.idleTimeoutMs,
805
+ maxReconnects: so.maxReconnects,
806
+ signal: so.signal ?? o.signal,
807
+ isTerminal: (ev) => TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
808
+ open: async (ctx) => {
809
+ if (ctx.attempt === 0) {
810
+ const sent = await this.send(
811
+ op,
812
+ args,
813
+ { ...o, headers: { ...o.headers, ...so.headers }, signal: ctx.signal },
814
+ {
815
+ accept: "text/event-stream",
816
+ sse: true,
817
+ },
818
+ );
819
+ return this.expectEventStream(sent, op);
820
+ }
821
+ const jobId =
822
+ isObject(ctx.lastEvent) && typeof ctx.lastEvent.job_id === "string" ? ctx.lastEvent.job_id : null;
823
+ if (!jobId) {
824
+ throw new B3OSError({
825
+ code: "stream_interrupted",
826
+ detail: `${op.id}: the stream broke before the first event, so the job id is unknown`,
827
+ operationId: op.id,
828
+ });
829
+ }
830
+ const headers: Record<string, string> = { ...(so.headers ?? {}) };
831
+ if (ctx.lastEventId !== undefined) headers["last-event-id"] = ctx.lastEventId;
832
+ const sent = await this.send(
833
+ ops.events,
834
+ { path: [jobId] },
835
+ { headers, signal: ctx.signal, maxRetries: 0 },
836
+ { accept: "text/event-stream", sse: true },
837
+ );
838
+ return this.expectEventStream(sent, ops.events);
839
+ },
840
+ },
841
+ (terminal) => this.finalJobFromEvent<J>(ops, terminal),
842
+ );
843
+ }
844
+
845
+ private async finalJobFromEvent<J>(ops: JobOps, ev: unknown): Promise<J> {
846
+ if (isObject(ev) && isObject(ev.job) && isTerminalJob(ev.job)) return ev.job as J;
847
+ const id = isObject(ev) && typeof ev.job_id === "string" ? ev.job_id : undefined;
848
+ if (!id) throw new Error("@b3os/sdk: terminal event without a job");
849
+ return (await this.exec<J>(ops.get, { path: [id] }, {})).data;
850
+ }
851
+
852
+ private jobEventStream<J extends JobLike, E>(
853
+ ops: JobOps,
854
+ jobOrId: Promise<J | string> | J | string,
855
+ so: JobEventsOptions,
856
+ ): JobEventStream<E, J> {
857
+ return new JobEventStream<E, J>(
858
+ {
859
+ operationId: ops.events.id,
860
+ resumable: true,
861
+ reconnectOnEnd: true,
862
+ idleTimeoutMs: so.idleTimeoutMs,
863
+ maxReconnects: so.maxReconnects,
864
+ signal: so.signal,
865
+ isTerminal: (ev) => TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
866
+ open: async (ctx) => {
867
+ const id = jobIdOf(await jobOrId);
868
+ const headers: Record<string, string> = { ...(so.headers ?? {}) };
869
+ const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? so.lastEventId : undefined);
870
+ if (lastId !== undefined) headers["last-event-id"] = lastId;
871
+ const sent = await this.send(
872
+ ops.events,
873
+ { path: [id] },
874
+ { headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? undefined : 0 },
875
+ { accept: "text/event-stream", sse: true },
876
+ );
877
+ return this.expectEventStream(sent, ops.events);
878
+ },
879
+ },
880
+ (terminal) => this.finalJobFromEvent<J>(ops, terminal),
881
+ );
882
+ }
883
+
884
+ private finishJob<J>(job: J, w: WaitOptions<never> | WaitOptions<unknown>): J {
885
+ const j = job as unknown as JobLike & { error?: Record<string, unknown> };
886
+ if (j.status === "succeeded" || w.throwOnFailure === false) return job;
887
+ const e = isObject(j.error) ? j.error : {};
888
+ const code = typeof e.code === "string" ? e.code : j.status === "canceled" ? "job_canceled" : "internal";
889
+ throw new B3OSJobError(job, {
890
+ code,
891
+ status: typeof e.status === "number" ? e.status : null,
892
+ title: typeof e.title === "string" ? e.title : undefined,
893
+ detail: typeof e.detail === "string" ? e.detail : `${j.object} ${j.id} ${j.status}`,
894
+ requestId: typeof e.instance === "string" ? e.instance : null,
895
+ problem: isObject(j.error) ? j.error : null,
896
+ });
897
+ }
898
+
899
+ /** @internal Waits until a job is terminal: its event stream first, polling as the fallback. */
900
+ async waitJob<J, E>(ops: JobOps, jobOrId: J | string, w: WaitOptions<E> = {}): Promise<J> {
901
+ if (typeof jobOrId !== "string" && isTerminalJob(jobOrId)) return this.finishJob(jobOrId, w);
902
+ const id = jobIdOf(jobOrId);
903
+ const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
904
+ const ac = new AbortController();
905
+ const onAbort = () => ac.abort(w.signal?.reason);
906
+ w.signal?.addEventListener("abort", onAbort, { once: true });
907
+ const timer = setTimeout(() => ac.abort(new Error("deadline")), Math.max(0, deadline - Date.now()));
908
+ let polling = false;
909
+ let pollAttempt = 0;
910
+ try {
911
+ for (;;) {
912
+ if (w.signal?.aborted) throw new B3OSAbortError({ operationId: ops.get.id });
913
+ if (Date.now() >= deadline) break;
914
+ if (!polling) {
915
+ try {
916
+ const stream = this.jobEventStream<JobLike, E>(ops, id, { signal: ac.signal });
917
+ for await (const ev of stream) {
918
+ w.onEvent?.(ev);
919
+ if (TERMINAL_JOB_EVENTS.has(eventType(ev) ?? "")) {
920
+ return this.finishJob(await this.finalJobFromEvent<J>(ops, ev), w);
921
+ }
922
+ }
923
+ } catch (e) {
924
+ if (w.signal?.aborted) throw new B3OSAbortError({ operationId: ops.events.id, cause: e });
925
+ if (ac.signal.aborted) break;
926
+ if (!(e instanceof B3OSError)) throw e;
927
+ if (
928
+ e.code === "route_not_found" ||
929
+ e.code === "not_implemented" ||
930
+ e.code === "invalid_response" ||
931
+ e.status === 405 ||
932
+ e.status === 406
933
+ ) {
934
+ // No usable events operation on this deployment: poll the job instead.
935
+ polling = true;
936
+ } else if (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 410) {
937
+ throw e;
938
+ } else if (!e.retryable && e.code !== "stream_interrupted") {
939
+ throw e;
940
+ }
941
+ // Otherwise transient: check the job, then reconnect.
942
+ }
943
+ }
944
+ const cur = await this.exec<J>(ops.get, { path: [id] }, { signal: ac.signal }).catch((e: unknown) => {
945
+ if (ac.signal.aborted && !w.signal?.aborted) return null;
946
+ throw e;
947
+ });
948
+ if (cur === null) break;
949
+ if (isTerminalJob(cur.data)) return this.finishJob(cur.data, w);
950
+ const ra = parseRetryAfter(cur.response.headers.get("retry-after"));
951
+ await sleep(
952
+ Math.min(Math.max(0, deadline - Date.now()), ra ?? backoffMs(pollAttempt++, 1000, 5000)),
953
+ ac.signal,
954
+ ).catch(() => {});
955
+ }
956
+ } finally {
957
+ clearTimeout(timer);
958
+ w.signal?.removeEventListener("abort", onAbort);
959
+ }
960
+ if (w.signal?.aborted) throw new B3OSAbortError({ operationId: ops.get.id });
961
+ throw new B3OSTimeoutError({
962
+ detail: `${id} was not finished after ${w.timeoutMs ?? ops.events.timeoutMs} ms; it keeps running on the server`,
963
+ operationId: ops.get.id,
964
+ });
965
+ }
966
+
967
+ /** @internal Events of an existing job. */
968
+ _jobEvents<J extends JobLike, E>(ops: JobOps, job: J | string, so: JobEventsOptions = {}): JobEventStream<E, J> {
969
+ return this.jobEventStream<J, E>(ops, job, so);
970
+ }
971
+
972
+ /** @internal Raw send for helpers that need the response (WebSocket tickets, downloads). */
973
+ _send(op: Op, args: CallArgs, options: RequestOptions, accept: string): Promise<Sent> {
974
+ return this.send(op, args, options, { accept });
975
+ }
976
+
977
+ /** @internal The route an operation would use (helpers that open WebSockets need the base URL). */
978
+ _routeFor(op: Op): { base: string; kind: Route["kind"]; auth: boolean } {
979
+ const r = op.edge ? this.edge : this.node;
980
+ return { base: r.base, kind: r.kind, auth: r.auth };
981
+ }
982
+
983
+ /** @internal Whether a WebSocket can take the operation's route (not over the Unix socket). */
984
+ _wsRoute(op: Op): { base: string; kind: Route["kind"] } {
985
+ const r = op.edge ? this.edge : this.node;
986
+ if (r.kind !== "uds") return { base: r.base, kind: r.kind };
987
+ if (this.apiKey) return { base: this.edge.base, kind: "edge" };
988
+ throw new B3OSError({
989
+ code: "unsupported_transport",
990
+ detail: `${op.id} opens a WebSocket, which the SDK cannot carry over the Unix socket`,
991
+ hint: "Set B3OS_API_KEY so it goes through beta-api.b3os.org, or B3OS_API_URL to a node URL",
992
+ operationId: op.id,
993
+ });
994
+ }
995
+
996
+ // ------------------------------------------------------------------------------------------------------------
997
+ // Public escape hatch
998
+
999
+ /**
1000
+ * Calls any operation by method and path, for endpoints the namespaces do not wrap (device login) or newer than
1001
+ * this SDK. Account paths (`/v1/keys`, `/v1/auth`, …) go to the edge unless `edge` says otherwise.
1002
+ */
1003
+ request<T = unknown>(req: RawRequest, options: RequestOptions = {}): APIPromise<T> {
1004
+ const op: Op = {
1005
+ id: `${req.method} ${req.path}`,
1006
+ method: req.method,
1007
+ path: req.path.includes("{") ? req.path.replace(/[{}]/g, "") : req.path,
1008
+ edge: req.edge ?? EDGE_PATHS.test(req.path),
1009
+ timeoutMs: req.timeoutMs ?? 65_000,
1010
+ errorFormat: req.errorFormat,
1011
+ scope: "unknown",
1012
+ };
1013
+ const args: CallArgs = { query: req.query, body: req.body, bodyType: req.bodyType as CallArgs["bodyType"] };
1014
+ const o = req.headers ? { ...options, headers: { ...req.headers, ...options.headers } } : options;
1015
+ return new APIPromise<T>(this.exec<T>(op, args, o));
1016
+ }
1017
+
1018
+ /** @internal SSE parse helper for namespaces. */
1019
+ static parseJsonEvent<E>(msg: SSEMessage): E {
1020
+ return JSON.parse(msg.data) as E;
1021
+ }
1022
+ }