@b3os/sdk 0.1.0 → 0.2.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 (225) hide show
  1. package/README.md +172 -42
  2. package/dist/cjs/core/bytes.d.ts +30 -0
  3. package/dist/cjs/core/bytes.js +115 -0
  4. package/dist/cjs/core/bytes.js.map +1 -0
  5. package/dist/cjs/core/client.d.ts +80 -3
  6. package/dist/cjs/core/client.js +236 -33
  7. package/dist/cjs/core/client.js.map +1 -1
  8. package/dist/cjs/core/errors.d.ts +16 -4
  9. package/dist/cjs/core/errors.js +9 -6
  10. package/dist/cjs/core/errors.js.map +1 -1
  11. package/dist/cjs/core/handle.d.ts +36 -0
  12. package/dist/cjs/core/handle.js +97 -0
  13. package/dist/cjs/core/handle.js.map +1 -0
  14. package/dist/cjs/core/index.d.ts +8 -4
  15. package/dist/cjs/core/index.js +14 -1
  16. package/dist/cjs/core/index.js.map +1 -1
  17. package/dist/cjs/core/login.d.ts +24 -0
  18. package/dist/cjs/core/login.js +93 -0
  19. package/dist/cjs/core/login.js.map +1 -0
  20. package/dist/cjs/core/namespace.d.ts +1 -1
  21. package/dist/cjs/core/namespace.js +1 -1
  22. package/dist/cjs/core/op.d.ts +11 -1
  23. package/dist/cjs/core/timing.d.ts +1 -1
  24. package/dist/cjs/core/timing.js +8 -1
  25. package/dist/cjs/core/timing.js.map +1 -1
  26. package/dist/cjs/core/traces-api.d.ts +42 -0
  27. package/dist/cjs/core/traces-api.js +54 -0
  28. package/dist/cjs/core/traces-api.js.map +1 -0
  29. package/dist/cjs/core/traces.d.ts +120 -0
  30. package/dist/cjs/core/traces.js +306 -0
  31. package/dist/cjs/core/traces.js.map +1 -0
  32. package/dist/cjs/core/transport.js +1 -1
  33. package/dist/cjs/core/transport.js.map +1 -1
  34. package/dist/cjs/core/util.d.ts +15 -3
  35. package/dist/cjs/core/util.js +54 -2
  36. package/dist/cjs/core/util.js.map +1 -1
  37. package/dist/cjs/core/ws.d.ts +4 -0
  38. package/dist/cjs/core/ws.js +7 -4
  39. package/dist/cjs/core/ws.js.map +1 -1
  40. package/dist/cjs/generated/client.d.ts +2 -2
  41. package/dist/cjs/generated/client.js +2 -2
  42. package/dist/cjs/generated/errors.d.ts +1 -1
  43. package/dist/cjs/generated/errors.js +42 -0
  44. package/dist/cjs/generated/errors.js.map +1 -1
  45. package/dist/cjs/generated/ids.d.ts +12 -0
  46. package/dist/cjs/generated/ids.js +3 -0
  47. package/dist/cjs/generated/ids.js.map +1 -1
  48. package/dist/cjs/generated/jobs.js +1 -1
  49. package/dist/cjs/generated/ns/actions.d.ts +48 -6
  50. package/dist/cjs/generated/ns/actions.js +59 -6
  51. package/dist/cjs/generated/ns/actions.js.map +1 -1
  52. package/dist/cjs/generated/ns/infer.d.ts +185 -54
  53. package/dist/cjs/generated/ns/infer.js +28 -74
  54. package/dist/cjs/generated/ns/infer.js.map +1 -1
  55. package/dist/cjs/generated/ns/keys.d.ts +14 -1
  56. package/dist/cjs/generated/ns/keys.js +24 -1
  57. package/dist/cjs/generated/ns/keys.js.map +1 -1
  58. package/dist/cjs/generated/ns/render.d.ts +115 -6
  59. package/dist/cjs/generated/ns/render.js +135 -7
  60. package/dist/cjs/generated/ns/render.js.map +1 -1
  61. package/dist/cjs/generated/ns/requests.d.ts +3 -1
  62. package/dist/cjs/generated/ns/requests.js +3 -1
  63. package/dist/cjs/generated/ns/requests.js.map +1 -1
  64. package/dist/cjs/generated/ns/routines.d.ts +131 -9
  65. package/dist/cjs/generated/ns/routines.js +186 -9
  66. package/dist/cjs/generated/ns/routines.js.map +1 -1
  67. package/dist/cjs/generated/ns/sandboxes.d.ts +327 -31
  68. package/dist/cjs/generated/ns/sandboxes.js +417 -29
  69. package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
  70. package/dist/cjs/generated/ns/vision.d.ts +133 -14
  71. package/dist/cjs/generated/ns/vision.js +158 -12
  72. package/dist/cjs/generated/ns/vision.js.map +1 -1
  73. package/dist/cjs/generated/ns/webhooks.d.ts +8 -5
  74. package/dist/cjs/generated/ns/webhooks.js +8 -5
  75. package/dist/cjs/generated/ns/webhooks.js.map +1 -1
  76. package/dist/cjs/generated/types.d.ts +2750 -328
  77. package/dist/cjs/helpers/agents.d.ts +95 -0
  78. package/dist/cjs/helpers/agents.js +205 -0
  79. package/dist/cjs/helpers/agents.js.map +1 -0
  80. package/dist/cjs/helpers/render.d.ts +15 -0
  81. package/dist/cjs/helpers/render.js +74 -0
  82. package/dist/cjs/helpers/render.js.map +1 -0
  83. package/dist/cjs/helpers/routines.d.ts +61 -0
  84. package/dist/cjs/helpers/routines.js +234 -0
  85. package/dist/cjs/helpers/routines.js.map +1 -0
  86. package/dist/cjs/helpers/sandboxes.d.ts +237 -0
  87. package/dist/cjs/helpers/sandboxes.js +608 -0
  88. package/dist/cjs/helpers/sandboxes.js.map +1 -0
  89. package/dist/cjs/index.d.ts +4 -1
  90. package/dist/cjs/index.js +8 -5
  91. package/dist/cjs/index.js.map +1 -1
  92. package/dist/cjs/routines.d.ts +1 -0
  93. package/dist/cjs/routines.js +21 -0
  94. package/dist/cjs/routines.js.map +1 -0
  95. package/dist/cjs/webhooks.js.map +1 -1
  96. package/dist/esm/core/bytes.d.ts +30 -0
  97. package/dist/esm/core/bytes.js +111 -0
  98. package/dist/esm/core/bytes.js.map +1 -0
  99. package/dist/esm/core/client.d.ts +80 -3
  100. package/dist/esm/core/client.js +233 -31
  101. package/dist/esm/core/client.js.map +1 -1
  102. package/dist/esm/core/errors.d.ts +16 -4
  103. package/dist/esm/core/errors.js +9 -6
  104. package/dist/esm/core/errors.js.map +1 -1
  105. package/dist/esm/core/handle.d.ts +36 -0
  106. package/dist/esm/core/handle.js +93 -0
  107. package/dist/esm/core/handle.js.map +1 -0
  108. package/dist/esm/core/index.d.ts +8 -4
  109. package/dist/esm/core/index.js +6 -2
  110. package/dist/esm/core/index.js.map +1 -1
  111. package/dist/esm/core/login.d.ts +24 -0
  112. package/dist/esm/core/login.js +85 -0
  113. package/dist/esm/core/login.js.map +1 -0
  114. package/dist/esm/core/namespace.d.ts +1 -1
  115. package/dist/esm/core/namespace.js +1 -1
  116. package/dist/esm/core/op.d.ts +11 -1
  117. package/dist/esm/core/timing.d.ts +1 -1
  118. package/dist/esm/core/timing.js +8 -1
  119. package/dist/esm/core/timing.js.map +1 -1
  120. package/dist/esm/core/traces-api.d.ts +42 -0
  121. package/dist/esm/core/traces-api.js +50 -0
  122. package/dist/esm/core/traces-api.js.map +1 -0
  123. package/dist/esm/core/traces.d.ts +120 -0
  124. package/dist/esm/core/traces.js +295 -0
  125. package/dist/esm/core/traces.js.map +1 -0
  126. package/dist/esm/core/transport.js +1 -1
  127. package/dist/esm/core/transport.js.map +1 -1
  128. package/dist/esm/core/util.d.ts +15 -3
  129. package/dist/esm/core/util.js +48 -1
  130. package/dist/esm/core/util.js.map +1 -1
  131. package/dist/esm/core/ws.d.ts +4 -0
  132. package/dist/esm/core/ws.js +7 -4
  133. package/dist/esm/core/ws.js.map +1 -1
  134. package/dist/esm/generated/client.d.ts +2 -2
  135. package/dist/esm/generated/client.js +2 -2
  136. package/dist/esm/generated/errors.d.ts +1 -1
  137. package/dist/esm/generated/errors.js +42 -0
  138. package/dist/esm/generated/errors.js.map +1 -1
  139. package/dist/esm/generated/ids.d.ts +12 -0
  140. package/dist/esm/generated/ids.js +3 -0
  141. package/dist/esm/generated/ids.js.map +1 -1
  142. package/dist/esm/generated/jobs.js +1 -1
  143. package/dist/esm/generated/ns/actions.d.ts +48 -6
  144. package/dist/esm/generated/ns/actions.js +59 -6
  145. package/dist/esm/generated/ns/actions.js.map +1 -1
  146. package/dist/esm/generated/ns/infer.d.ts +185 -54
  147. package/dist/esm/generated/ns/infer.js +28 -74
  148. package/dist/esm/generated/ns/infer.js.map +1 -1
  149. package/dist/esm/generated/ns/keys.d.ts +14 -1
  150. package/dist/esm/generated/ns/keys.js +24 -1
  151. package/dist/esm/generated/ns/keys.js.map +1 -1
  152. package/dist/esm/generated/ns/render.d.ts +115 -6
  153. package/dist/esm/generated/ns/render.js +135 -7
  154. package/dist/esm/generated/ns/render.js.map +1 -1
  155. package/dist/esm/generated/ns/requests.d.ts +3 -1
  156. package/dist/esm/generated/ns/requests.js +3 -1
  157. package/dist/esm/generated/ns/requests.js.map +1 -1
  158. package/dist/esm/generated/ns/routines.d.ts +131 -9
  159. package/dist/esm/generated/ns/routines.js +186 -9
  160. package/dist/esm/generated/ns/routines.js.map +1 -1
  161. package/dist/esm/generated/ns/sandboxes.d.ts +327 -31
  162. package/dist/esm/generated/ns/sandboxes.js +417 -29
  163. package/dist/esm/generated/ns/sandboxes.js.map +1 -1
  164. package/dist/esm/generated/ns/vision.d.ts +133 -14
  165. package/dist/esm/generated/ns/vision.js +158 -12
  166. package/dist/esm/generated/ns/vision.js.map +1 -1
  167. package/dist/esm/generated/ns/webhooks.d.ts +8 -5
  168. package/dist/esm/generated/ns/webhooks.js +8 -5
  169. package/dist/esm/generated/ns/webhooks.js.map +1 -1
  170. package/dist/esm/generated/types.d.ts +2750 -328
  171. package/dist/esm/helpers/agents.d.ts +95 -0
  172. package/dist/esm/helpers/agents.js +199 -0
  173. package/dist/esm/helpers/agents.js.map +1 -0
  174. package/dist/esm/helpers/render.d.ts +15 -0
  175. package/dist/esm/helpers/render.js +70 -0
  176. package/dist/esm/helpers/render.js.map +1 -0
  177. package/dist/esm/helpers/routines.d.ts +61 -0
  178. package/dist/esm/helpers/routines.js +226 -0
  179. package/dist/esm/helpers/routines.js.map +1 -0
  180. package/dist/esm/helpers/sandboxes.d.ts +237 -0
  181. package/dist/esm/helpers/sandboxes.js +600 -0
  182. package/dist/esm/helpers/sandboxes.js.map +1 -0
  183. package/dist/esm/index.d.ts +4 -1
  184. package/dist/esm/index.js +6 -5
  185. package/dist/esm/index.js.map +1 -1
  186. package/dist/esm/routines.d.ts +1 -0
  187. package/dist/esm/routines.js +5 -0
  188. package/dist/esm/routines.js.map +1 -0
  189. package/dist/esm/webhooks.js.map +1 -1
  190. package/package.json +14 -3
  191. package/src/core/bytes.ts +112 -0
  192. package/src/core/client.ts +285 -33
  193. package/src/core/errors.ts +27 -10
  194. package/src/core/handle.ts +107 -0
  195. package/src/core/index.ts +17 -2
  196. package/src/core/login.ts +98 -0
  197. package/src/core/namespace.ts +1 -1
  198. package/src/core/op.ts +11 -1
  199. package/src/core/timing.ts +7 -2
  200. package/src/core/traces-api.ts +80 -0
  201. package/src/core/traces.ts +375 -0
  202. package/src/core/transport.ts +1 -1
  203. package/src/core/util.ts +53 -3
  204. package/src/core/ws.ts +11 -4
  205. package/src/generated/client.ts +2 -2
  206. package/src/generated/errors.ts +84 -0
  207. package/src/generated/ids.ts +3 -0
  208. package/src/generated/jobs.ts +1 -1
  209. package/src/generated/ns/actions.ts +69 -6
  210. package/src/generated/ns/infer.ts +229 -61
  211. package/src/generated/ns/keys.ts +25 -1
  212. package/src/generated/ns/render.ts +172 -7
  213. package/src/generated/ns/requests.ts +3 -1
  214. package/src/generated/ns/routines.ts +205 -9
  215. package/src/generated/ns/sandboxes.ts +493 -34
  216. package/src/generated/ns/vision.ts +168 -14
  217. package/src/generated/ns/webhooks.ts +8 -5
  218. package/src/generated/types.ts +3034 -472
  219. package/src/helpers/agents.ts +300 -0
  220. package/src/helpers/render.ts +91 -0
  221. package/src/helpers/routines.ts +278 -0
  222. package/src/helpers/sandboxes.ts +788 -0
  223. package/src/index.ts +29 -5
  224. package/src/routines.ts +5 -0
  225. package/src/webhooks.ts +5 -1
@@ -2,6 +2,7 @@
2
2
  // pipeline (idempotency keys, retries with jittered backoff, timeouts, typed errors, Server-Timing), and the job
3
3
  // and stream plumbing the generated namespaces call. It knows no product; src/generated/ns/* do.
4
4
 
5
+ import { ByteStream } from "./bytes.ts";
5
6
  import {
6
7
  B3OSAbortError,
7
8
  B3OSConnectionError,
@@ -11,6 +12,7 @@ import {
11
12
  NEVER_REACHED_STATUSES,
12
13
  parseErrorBody,
13
14
  } from "./errors.ts";
15
+ import { announceLogin, canReadLogin, loginBlockedBy, readStoredLogin } from "./login.ts";
14
16
  import type { CallArgs, JobOps, Op } from "./op.ts";
15
17
  import {
16
18
  APIPromise,
@@ -28,6 +30,8 @@ import {
28
30
  } from "./promise.ts";
29
31
  import { ResponseInfo, remember } from "./response.ts";
30
32
  import { EventStream, type EventStreamOptions, type SSEMessage } from "./sse.ts";
33
+ import { callTraceHeaders, type SpanRecord } from "./traces.ts";
34
+ import { Traces } from "./traces-api.ts";
31
35
  import {
32
36
  FetchTransport,
33
37
  NodeHttpTransport,
@@ -37,17 +41,57 @@ import {
37
41
  type TransportResponse,
38
42
  TransportTimeout,
39
43
  } from "./transport.ts";
40
- import { backoffMs, env, isObject, parseRetryAfter, runtime, runtimeLabel, SDK_VERSION, sleep, uuid } from "./util.ts";
44
+ import {
45
+ backoffMs,
46
+ describeErr,
47
+ env,
48
+ isObject,
49
+ newTraceId,
50
+ parseRetryAfter,
51
+ runtime,
52
+ runtimeLabel,
53
+ SDK_VERSION,
54
+ sleep,
55
+ traceIdOf,
56
+ uuid,
57
+ } from "./util.ts";
41
58
 
42
59
  /** A binary request body (file uploads, pack bundles). */
43
60
  export type BinaryInput = RequestBody;
44
61
 
45
62
  export const DEFAULT_BASE_URL = "https://beta-api.b3os.org";
63
+ /** Where API keys are made (the console's API keys page). */
64
+ export const KEYS_PAGE = "https://beta.b3os.org/app/keys";
46
65
  /** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
47
66
  export const DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
48
67
 
68
+ /** What `GET /v1/ping` answers (requests.yaml `Ping`). */
69
+ export interface Ping {
70
+ object: "ping";
71
+ /** The node that answered (`n1`). */
72
+ node: string;
73
+ /** The node's clock when it answered, RFC 3339 in UTC with milliseconds. */
74
+ ts: string;
75
+ }
76
+
77
+ /**
78
+ * `platformPing` from packages/spec/dist (routes.json has no SDK name for it: it belongs to no namespace), so the
79
+ * core carries it; test/ping.test.ts checks it against routes.json.
80
+ */
81
+ export const PING_OP: Op = {
82
+ id: "platformPing",
83
+ method: "GET",
84
+ path: "/v1/ping",
85
+ timeoutMs: 5000,
86
+ scope: "authenticated",
87
+ };
88
+
49
89
  export interface ClientOptions {
50
- /** API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`. */
90
+ /**
91
+ * API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`, else, on a developer's machine, the
92
+ * token `b3os login` stored (never in CI, on GitHub Actions or in a B3OS sandbox; one stderr line says when it is
93
+ * used). `null` sends no key and skips the stored login.
94
+ */
51
95
  apiKey?: string | null;
52
96
  /** The API host for edge-served operations and remote calls. Default: `B3OS_BASE_URL`, else beta-api.b3os.org. */
53
97
  baseUrl?: string;
@@ -80,17 +124,32 @@ export interface ClientOptions {
80
124
  headers?: Record<string, string>;
81
125
  /** Called after every response head, successful or not. */
82
126
  onResponse?: (info: ResponseInfo) => void;
127
+ /**
128
+ * Called with each span `traces.turn` and `traces.span` time (the turn's root and the harness's steps), so you can
129
+ * send them to an exporter of yours. B3OS's own ingest door is phase 2b.
130
+ */
131
+ onSpan?: (span: SpanRecord) => void;
83
132
  }
84
133
 
85
134
  export interface RequestOptions {
86
- /** `Idempotency-Key` for this call; generated when the operation takes one and you pass none. */
135
+ /**
136
+ * `Idempotency-Key` for this call; generated when the operation takes one and you pass none, except for
137
+ * operations whose effect cannot be repeated (`x-b3os-idempotency: caller`, `sandboxes.exec`): those send only
138
+ * the key you pass.
139
+ */
87
140
  idempotencyKey?: string;
88
141
  timeoutMs?: number;
89
142
  maxRetries?: number;
90
143
  signal?: AbortSignal;
91
144
  headers?: Record<string, string>;
92
- /** W3C trace context, propagated into product calls and routine steps. */
145
+ /**
146
+ * W3C trace context, propagated into product calls and routine steps. Sent as given; without one, a call inside
147
+ * `traces.turn` joins the turn, and any other call gets its own trace (every attempt a new span in it, marked
148
+ * `tracestate: b3os=call`); calls through a resource handle share the handle's.
149
+ */
93
150
  traceparent?: string;
151
+ /** W3C `tracestate` sent with your `traceparent` (only with it). */
152
+ tracestate?: string;
94
153
  }
95
154
 
96
155
  export interface StreamOptions extends RequestOptions {
@@ -155,6 +214,23 @@ const REJECTED_BEFORE_WORK = new Set([
155
214
  "auth_unavailable",
156
215
  "idempotency_request_in_progress",
157
216
  ]);
217
+ /**
218
+ * Codes in REJECTED_BEFORE_WORK that the edge also sends after it forwarded the request, so a B3OS body with one
219
+ * does not show that the request did no work: 503 `node_unavailable` covers a tunnel or a node that failed while it
220
+ * held the request (apps/edge/src/gateway/forward.ts maps every fetch failure and every answer without the node's
221
+ * request id to it). A caller-keyed operation (sandboxesExec) is not resent after one; other operations still are.
222
+ */
223
+ const MAYBE_FORWARDED = new Set(["node_unavailable"]);
224
+
225
+ /**
226
+ * True when the answer shows that the request was refused before any work, so even a call that is not retry-safe
227
+ * may be sent again.
228
+ */
229
+ function rejectedBeforeWorkFor(op: Op, code: string, status: number, codeFromStatus: boolean | undefined): boolean {
230
+ if (!REJECTED_BEFORE_WORK.has(code)) return false;
231
+ if (codeFromStatus) return NEVER_REACHED_STATUSES.has(status);
232
+ return !(op.callerKey && MAYBE_FORWARDED.has(code));
233
+ }
158
234
 
159
235
  function trimSlash(s: string): string {
160
236
  return s.endsWith("/") ? s.replace(/\/+$/, "") : s;
@@ -240,15 +316,41 @@ function buildPath(op: Op, values: readonly (string | number)[] | undefined): st
240
316
  });
241
317
  }
242
318
 
243
- function buildQuery(query: object | undefined, extra?: Record<string, string>): string {
319
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
320
+ typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
321
+ const queryValue = (v: unknown): string => (v instanceof Date ? v.toISOString() : String(v));
322
+
323
+ /** `name[key]=value` for each member of a deepObject value (nested objects add a bracket; arrays repeat the key). */
324
+ function appendDeep(sp: URLSearchParams, name: string, v: unknown): void {
325
+ if (v === undefined || v === null) return;
326
+ if (isPlainObject(v)) for (const [k, x] of Object.entries(v)) appendDeep(sp, `${name}[${k}]`, x);
327
+ else if (Array.isArray(v)) for (const x of v) appendDeep(sp, name, x);
328
+ else sp.append(name, queryValue(v));
329
+ }
330
+
331
+ /**
332
+ * The query string. Arrays repeat their key (`style: form`, `explode: true`); an object is sent as `name[key]=value`
333
+ * pairs when the operation declares the parameter `style: deepObject` (`metadata[team]=infra`), and is refused
334
+ * otherwise rather than sent as "[object Object]". A boolean for one of the operation's 0/1 flags is sent as `1` or
335
+ * `0` (`list: true` is `list=1`); other booleans as `true` or `false`.
336
+ */
337
+ export function buildQuery(
338
+ query: object | undefined,
339
+ extra?: Record<string, string>,
340
+ op?: Pick<Op, "id" | "deepObject" | "flags">,
341
+ ): string {
244
342
  let sp: URLSearchParams | undefined;
245
343
  if (query) {
246
344
  for (const [k, v] of Object.entries(query)) {
247
345
  if (v === undefined || v === null) continue;
248
346
  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));
347
+ if (isPlainObject(v)) {
348
+ if (!op?.deepObject?.includes(k))
349
+ throw new TypeError(`b3os: ${op?.id ?? "request"}: the query parameter ${k} does not take an object`);
350
+ appendDeep(sp, k, v);
351
+ } else if (Array.isArray(v)) for (const x of v) sp.append(k, queryValue(x));
352
+ else if (typeof v === "boolean" && op?.flags?.includes(k)) sp.append(k, v ? "1" : "0");
353
+ else sp.append(k, queryValue(v));
252
354
  }
253
355
  }
254
356
  if (extra) {
@@ -278,35 +380,114 @@ function connectRefused(err: unknown): boolean {
278
380
  return code === "ENOENT" || code === "ECONNREFUSED" || code === "EACCES" || code === "EPERM";
279
381
  }
280
382
 
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);
383
+ /**
384
+ * Why a call to a caller-keyed operation (`x-b3os-idempotency: caller`, sandboxesExec) was not sent again: `what`
385
+ * happened after the request may have reached the server, so its effect may have happened.
386
+ */
387
+ function mayHaveRun(op: Op, key: string | undefined, what: string): string | undefined {
388
+ if (!op.callerKey) return undefined;
389
+ const again = key
390
+ ? `Call it again with the same idempotencyKey ("${key}") to get its recorded outcome rather than run it twice`
391
+ : "Check its effect before running it again, or pass an idempotencyKey so a second call returns the recorded outcome";
392
+ return `${op.id} may have run: ${what}, so the SDK did not send it again. ${again}`;
393
+ }
394
+
395
+ /** `b3os_sk_…abcd`: enough to tell keys apart in a log, never enough to use one. */
396
+ function redactKey(key: string | null): string | null {
397
+ if (!key) return key;
398
+ const prefix = /^b3os_[a-z]+_/.exec(key)?.[0] ?? "";
399
+ return `${prefix}…${key.slice(-4)}`;
289
400
  }
290
401
 
291
402
  export class B3OSCore {
292
- readonly apiKey: string | null;
403
+ /**
404
+ * The key this client sends. Readable, but not enumerable: `JSON.stringify`, `console.log` and `util.inspect` of a
405
+ * client show only its last four characters (see `toJSON`).
406
+ */
407
+ declare readonly apiKey: string | null;
408
+ /**
409
+ * The sandbox this code runs in (`B3OS_SANDBOX_ID`, set inside every B3OS sandbox with `B3OS_API_URL`), or null.
410
+ * Useful as the id for operations on the sandbox itself: `b3os.sandboxes.createSnapshot(b3os.sandboxId!)`.
411
+ */
412
+ readonly sandboxId: string | null;
293
413
  readonly baseUrl: string;
294
414
  readonly maxRetries: number;
295
415
  readonly maxRetryDelayMs: number;
296
416
  readonly timeoutMs: number | undefined;
417
+ /** @internal Handed each span the turn helper times (ClientOptions.onSpan). */
418
+ readonly _onSpan: ((span: SpanRecord) => void) | undefined;
419
+ #traces: Traces | undefined;
297
420
  private edge: Route;
298
421
  private node: Route;
299
422
  private readonly headers: Record<string, string>;
300
423
  private readonly onResponse: ((info: ResponseInfo) => void) | undefined;
424
+ /** What a call without a key says: why no key was found, and how to give one. */
425
+ readonly #noKeyHint: string;
426
+ /**
427
+ * Whether a call that needs a key and has none is answered here, with no request: only for the B3OS API host
428
+ * (which answers every such call 401), with the SDK's own fetch, outside a B3OS sandbox. Another host may be a mock
429
+ * or a node that answers first, a custom fetch may add the credential, and a sandbox's egress proxy may.
430
+ */
431
+ readonly #keylessAnswersLocally: boolean;
432
+
433
+ /** What `JSON.stringify(client)` prints: the settings, with the key redacted. */
434
+ toJSON(): Record<string, unknown> {
435
+ return {
436
+ baseUrl: this.baseUrl,
437
+ apiKey: redactKey(this.apiKey),
438
+ sandboxId: this.sandboxId,
439
+ maxRetries: this.maxRetries,
440
+ maxRetryDelayMs: this.maxRetryDelayMs,
441
+ timeoutMs: this.timeoutMs,
442
+ };
443
+ }
444
+
445
+ /** What `console.log(client)` and `util.inspect(client)` print on Node, Bun and Deno: the same as `toJSON`. */
446
+ [Symbol.for("nodejs.util.inspect.custom")](): Record<string, unknown> {
447
+ return this.toJSON();
448
+ }
301
449
 
302
450
  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");
451
+ let apiKey = options.apiKey !== undefined ? options.apiKey : (env("B3OS_API_KEY") ?? null);
452
+ let explicitBase = options.baseUrl ?? env("B3OS_BASE_URL");
453
+ let noKeyHint = "No API key is set: set B3OS_API_KEY or pass apiKey";
454
+ if (options.apiKey === null) {
455
+ noKeyHint =
456
+ "No API key is set: this client was made with apiKey: null. Pass apiKey, or leave it out to use " +
457
+ "B3OS_API_KEY or your b3os login";
458
+ } else if (apiKey === null) {
459
+ // The stored `b3os login`, on a developer's machine only, and only for the API host it was issued by.
460
+ const blocked = loginBlockedBy();
461
+ const login = blocked ? undefined : readStoredLogin();
462
+ const loginBase = login?.baseUrl ?? DEFAULT_BASE_URL;
463
+ if (blocked) {
464
+ noKeyHint += ` (the SDK does not read the b3os login in ${blocked})`;
465
+ } else if (login && (explicitBase === undefined || trimSlash(explicitBase) === loginBase)) {
466
+ apiKey = login.token;
467
+ if (explicitBase === undefined && loginBase !== DEFAULT_BASE_URL) explicitBase = loginBase;
468
+ announceLogin(login, redactKey(login.token) ?? "");
469
+ } else if (login) {
470
+ noKeyHint += ` (your b3os login is for ${loginBase}, not ${trimSlash(explicitBase ?? "")})`;
471
+ } else if (canReadLogin()) {
472
+ noKeyHint = "Not signed in: run b3os login, set B3OS_API_KEY or pass apiKey";
473
+ }
474
+ }
475
+ const onApiHost = trimSlash(explicitBase ?? DEFAULT_BASE_URL) === DEFAULT_BASE_URL;
476
+ this.#noKeyHint = onApiHost ? `${noKeyHint}. Make a key at ${KEYS_PAGE}` : noKeyHint;
477
+ this.#keylessAnswersLocally =
478
+ onApiHost && !options.fetch && !env("B3OS_SANDBOX_ID") && !env("B3OS_API_URL") && !apiKey;
479
+ Object.defineProperty(this, "apiKey", {
480
+ value: apiKey,
481
+ enumerable: false,
482
+ writable: false,
483
+ configurable: false,
484
+ });
305
485
  this.baseUrl = trimSlash(explicitBase ?? DEFAULT_BASE_URL);
306
486
  this.maxRetries = options.maxRetries ?? 2;
307
487
  this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
308
488
  this.timeoutMs = options.timeoutMs;
309
489
  this.onResponse = options.onResponse;
490
+ this._onSpan = options.onSpan;
310
491
  const headers: Record<string, string> = {};
311
492
  const rt = runtime();
312
493
  if (rt === "node" || rt === "bun" || rt === "deno" || rt === "workerd") {
@@ -322,6 +503,8 @@ export class B3OSCore {
322
503
  const sockEnv = env("B3OS_SOCKET");
323
504
  const sockDisabled = options.socketPath === false || sockEnv === "0" || sockEnv === "off";
324
505
  const nodeUrl = options.nodeUrl !== undefined ? options.nodeUrl : (env("B3OS_API_URL") ?? null);
506
+ const sbx = env("B3OS_SANDBOX_ID");
507
+ this.sandboxId = sbx && /^sbx_[0-9a-hjkmnp-tv-z]{26}$/.test(sbx) ? sbx : null;
325
508
  let node: Route = this.edge;
326
509
  if (pref !== "http") {
327
510
  const explicitSock =
@@ -379,8 +562,36 @@ export class B3OSCore {
379
562
  }
380
563
 
381
564
  /** 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 };
565
+ get routes(): { node: string; edge: string; nodeKind: Route["kind"]; sandboxId: string | null } {
566
+ return {
567
+ node: this.node.transport.label,
568
+ edge: this.edge.transport.label,
569
+ nodeKind: this.node.kind,
570
+ sandboxId: this.sandboxId,
571
+ };
572
+ }
573
+
574
+ /**
575
+ * The smallest call the node serves, `GET /v1/ping`: the node's id and clock once the credential is checked,
576
+ * and nothing else. Any valid credential may call it. Its time is the round trip to the node (the "edge round
577
+ * trip" that latency targets are written against); `.withResponse()` gives the Server-Timing phases.
578
+ */
579
+ ping(options?: RequestOptions): APIPromise<Ping> {
580
+ return this._call<Ping>(PING_OP, {}, options);
581
+ }
582
+
583
+ /**
584
+ * Turns and spans (observability.md 3.4): `traces.turn(name, fn)` groups the calls of one turn of your agent into
585
+ * one trace, `traces.span(name, fn)` times a step of its own, `traces.get(traceId)` reads a trace back.
586
+ */
587
+ get traces(): Traces {
588
+ this.#traces ??= new Traces(this);
589
+ return this.#traces;
590
+ }
591
+
592
+ /** The origins this client sends to (its API host and node URL), where a turn's baggage may go. */
593
+ get _origins(): string[] {
594
+ return [this.baseUrl, this.node.kind === "node-http" ? this.node.base : ""].filter(Boolean);
384
595
  }
385
596
 
386
597
  /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
@@ -392,10 +603,15 @@ export class B3OSCore {
392
603
  // ------------------------------------------------------------------------------------------------------------
393
604
  // The request pipeline
394
605
 
395
- private headersFor(route: Route, op: Op, o: RequestOptions, accept: string): Record<string, string> {
606
+ private headersFor(route: Route, op: Op, o: RequestOptions, accept: string, traceId: string): Record<string, string> {
396
607
  const h: Record<string, string> = { ...this.headers, accept };
397
608
  if (route.auth && this.apiKey) h.authorization = `Bearer ${this.apiKey}`;
398
- if (o.traceparent) h.traceparent = o.traceparent;
609
+ // The call's own traceparent, else the client's, else the current turn's, else a per-call trace marked
610
+ // b3os=call (core/traces.ts).
611
+ const t = callTraceHeaders(o.traceparent, o.tracestate, this.headers, traceId);
612
+ h.traceparent = t.traceparent;
613
+ if (t.tracestate) h.tracestate = t.tracestate;
614
+ if (t.baggage) h.baggage = h.baggage ? `${t.baggage},${h.baggage}` : t.baggage;
399
615
  if (o.headers) for (const [k, v] of Object.entries(o.headers)) h[k.toLowerCase()] = v;
400
616
  void op;
401
617
  return h;
@@ -435,9 +651,7 @@ export class B3OSCore {
435
651
  ? `${op.id} is served by ${this.baseUrl}`
436
652
  : `${op.id} is served by ${this.baseUrl}; set B3OS_API_KEY (or pass apiKey) so the SDK can send it there`;
437
653
  }
438
- if (err.status === 401 && route.auth && !this.apiKey) {
439
- return "No API key is configured: set B3OS_API_KEY or pass apiKey";
440
- }
654
+ if (err.status === 401 && route.auth && !this.apiKey) return this.#noKeyHint;
441
655
  if (err.status === 403 && err.reason === "scope" && route.kind === "uds") {
442
656
  return (
443
657
  "Over the node's Unix socket this process acts as the local principal its uid maps to in b3osd.toml " +
@@ -451,18 +665,26 @@ export class B3OSCore {
451
665
  private async send(op: Op, args: CallArgs, o: RequestOptions, x: SendExtras): Promise<Sent> {
452
666
  const method = op.method;
453
667
  const pathStr = buildPath(op, args.path);
454
- const query = buildQuery(args.query, x.extraQuery);
668
+ const query = buildQuery(args.query, x.extraQuery, op);
455
669
  let idemKey = o.idempotencyKey;
456
- if (!idemKey && op.idem && method !== "GET") idemKey = uuid();
670
+ if (!idemKey && op.idem && !op.callerKey && method !== "GET") idemKey = uuid();
457
671
  const streamBody = typeof ReadableStream !== "undefined" && args.body instanceof ReadableStream;
672
+ // A caller-keyed operation (sandboxesExec) is resent only after an answer that shows it did no work, key or not:
673
+ // the node cannot always tell whether a command it handed on ran, and a retry must never run it twice.
458
674
  const retrySafe =
459
- !streamBody && (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
675
+ !streamBody &&
676
+ !op.callerKey &&
677
+ (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
460
678
  const maxRetries = streamBody ? 0 : (o.maxRetries ?? this.maxRetries);
461
679
  const perAttempt = o.timeoutMs ?? this.timeoutMs ?? (x.sse ? 30_000 : Math.min(op.timeoutMs, 65_000) + 5_000);
462
680
  let route = op.edge ? this.edge : this.node;
463
681
  let attempt = 0;
682
+ // One trace per call (attempts are spans in it) unless the caller sent a traceparent, which is kept as is. A
683
+ // client made with a `traceparent` header (an MCP server's per-request client) joins that trace: each call is a
684
+ // new span in it, so the header's own span id is never sent twice.
685
+ const traceId = traceIdOf(this.headers.traceparent) ?? newTraceId();
464
686
  for (;;) {
465
- const headers = this.headersFor(route, op, o, x.accept);
687
+ const headers = this.headersFor(route, op, o, x.accept, traceId);
466
688
  if (idemKey) headers["idempotency-key"] = idemKey;
467
689
  if (op.headerParams && args.headerParams) {
468
690
  for (const [k, name] of Object.entries(op.headerParams)) {
@@ -470,6 +692,17 @@ export class B3OSCore {
470
692
  if (v !== undefined && v !== null) headers[name.toLowerCase()] = String(v);
471
693
  }
472
694
  }
695
+ // No key, and the API host would answer 401: say so without the round trip. Scope `public` needs no key, and
696
+ // `unknown` is a raw `request()`, which may be to a route that needs none (the device login).
697
+ if (
698
+ route.auth &&
699
+ this.#keylessAnswersLocally &&
700
+ !headers.authorization &&
701
+ op.scope !== "public" &&
702
+ op.scope !== "unknown"
703
+ ) {
704
+ throw new B3OSError({ code: "unauthorized", detail: this.#noKeyHint, operationId: op.id });
705
+ }
473
706
  const body = this.encodeBody(op, args, headers);
474
707
  const path = pathStr + query;
475
708
  const url = route.base + path;
@@ -501,11 +734,15 @@ export class B3OSCore {
501
734
  ? new B3OSTimeoutError({
502
735
  detail: `${op.id} did not answer within ${perAttempt} ms (${route.transport.label})`,
503
736
  operationId: op.id,
737
+ hint: mayHaveRun(op, idemKey, "it did not answer in time"),
504
738
  cause,
505
739
  })
506
740
  : new B3OSConnectionError({
507
741
  detail: `Could not reach ${route.transport.label}: ${describeErr(cause)}`,
508
742
  operationId: op.id,
743
+ hint: connectRefused(cause)
744
+ ? undefined
745
+ : mayHaveRun(op, idemKey, "the connection failed after the request may have been sent"),
509
746
  cause,
510
747
  });
511
748
  // Timeouts are not retried: the budget is spent. A refused connection never reached the server.
@@ -562,7 +799,12 @@ export class B3OSCore {
562
799
  retryAfterMs,
563
800
  operationId: op.id,
564
801
  });
565
- const hint = this.hint(route, op, err0);
802
+ const rejectedBeforeWork = rejectedBeforeWorkFor(op, err0.code, res.status, parsed.codeFromStatus);
803
+ const hint =
804
+ this.hint(route, op, err0) ??
805
+ (rejectedBeforeWork || res.status < 500
806
+ ? undefined
807
+ : mayHaveRun(op, idemKey, `the answer was ${res.status} ${err0.code}`));
566
808
  const err = hint
567
809
  ? new B3OSError({
568
810
  code: err0.code,
@@ -580,8 +822,6 @@ export class B3OSCore {
580
822
  hint,
581
823
  })
582
824
  : err0;
583
- const rejectedBeforeWork =
584
- REJECTED_BEFORE_WORK.has(err.code) && (!parsed.codeFromStatus || NEVER_REACHED_STATUSES.has(res.status));
585
825
  const retryable =
586
826
  rejectedBeforeWork ||
587
827
  (retrySafe && err.retryable && (err.status ?? 0) >= 500 && !NO_RETRY_TIMEOUT_CODES.has(err.code));
@@ -765,6 +1005,18 @@ export class B3OSCore {
765
1005
  });
766
1006
  }
767
1007
 
1008
+ /**
1009
+ * @internal A response body read as it arrives (speech with `stream_format: "audio"`): the per-attempt timeout
1010
+ * covers the response head only, and nothing is retried once bytes have been handed out.
1011
+ */
1012
+ _postBytes(op: Op, args: CallArgs, options: RequestOptions = {}, accept = "application/octet-stream"): ByteStream {
1013
+ return new ByteStream(
1014
+ op.id,
1015
+ (signal) => this.send(op, args, { ...options, signal }, { accept, sse: true }),
1016
+ options.signal,
1017
+ );
1018
+ }
1019
+
768
1020
  /** @internal A job-creating operation (`x-b3os-job`). */
769
1021
  _job<J extends JobLike, E>(op: Op, args: CallArgs, options: RequestOptions = {}): JobPromise<J, E> {
770
1022
  const ops = op.job;
@@ -16,10 +16,15 @@ export type B3OSClientErrorCode =
16
16
  | "aborted"
17
17
  | "invalid_response"
18
18
  | "stream_interrupted"
19
- | "unsupported_transport";
19
+ | "unsupported_transport"
20
+ /** A sandbox process the SDK was waiting on (startService, waitUntilReady with `pid`) exited first. */
21
+ | "process_exited";
22
+
23
+ /** The codes this SDK knows: every catalog code plus the client codes. */
24
+ export type B3OSKnownErrorCode = B3OSServerErrorCode | B3OSClientErrorCode;
20
25
 
21
26
  /** Every catalog code plus the client codes; any other string is a code newer than this SDK. */
22
- export type B3OSErrorCode = B3OSServerErrorCode | B3OSClientErrorCode | (string & {});
27
+ export type B3OSErrorCode = B3OSKnownErrorCode | (string & {});
23
28
 
24
29
  export interface B3OSErrorInit {
25
30
  code: string;
@@ -106,8 +111,17 @@ export class B3OSError extends Error {
106
111
  return isObject(l) ? l : undefined;
107
112
  }
108
113
 
109
- /** True when `err` is a B3OSError, optionally with one of the given codes. */
110
- static is(err: unknown, ...codes: B3OSErrorCode[]): err is B3OSError {
114
+ /**
115
+ * True when `err` is a B3OSError, optionally with one of the given codes. Editors complete the codes this SDK
116
+ * knows (`B3OSKnownErrorCode`) and mark any other string as deprecated, so a typo stands out.
117
+ */
118
+ static is(err: unknown, ...codes: B3OSKnownErrorCode[]): err is B3OSError;
119
+ /**
120
+ * @deprecated A code this SDK does not know: a typo, or a code newer than the SDK. It still matches `err.code`
121
+ * (0.1.1 took any string, so such code keeps compiling); prefer a known code, or compare `err.code` yourself.
122
+ */
123
+ static is(err: unknown, ...codes: string[]): err is B3OSError;
124
+ static is(err: unknown, ...codes: string[]): err is B3OSError {
111
125
  return err instanceof B3OSError && (codes.length === 0 || codes.includes(err.code));
112
126
  }
113
127
  }
@@ -260,15 +274,18 @@ export function parseErrorBody(status: number, contentType: string | null, text:
260
274
  retryAfterS: typeof ra === "number" ? ra : undefined,
261
275
  };
262
276
  }
263
- // OpenAI: {"error": {"message", "type", "param", "code"}}.
277
+ // OpenAI: {"error": {"message", "type", "param", "code"}}. Anthropic (/v1/infer/v1/messages*):
278
+ // {"type": "error", "error": {"type", "message"}, "b3os": {"code", "param"?}, "request_id"?}.
264
279
  if (isObject(body.error)) {
265
280
  const e = body.error;
266
- const named = typeof e.code === "string";
267
- const code = named ? (e.code as string) : codeForStatus(status);
281
+ const b3 = body.type === "error" && isObject(body.b3os) ? body.b3os : undefined;
282
+ const named = typeof (b3 ?? e).code === "string";
283
+ const code = named ? ((b3 ?? e).code as string) : codeForStatus(status);
268
284
  const detail = typeof e.message === "string" ? e.message : undefined;
269
- const errors =
270
- typeof e.param === "string" && e.param ? [{ pointer: `/${e.param}`, detail: detail ?? "" }] : undefined;
271
- return { code, detail, errors, problem: body, codeFromStatus: !named };
285
+ const param = (b3 ?? e).param;
286
+ const errors = typeof param === "string" && param ? [{ pointer: `/${param}`, detail: detail ?? "" }] : undefined;
287
+ const instance = typeof body.request_id === "string" ? body.request_id : undefined;
288
+ return { code, detail, errors, problem: body, codeFromStatus: !named, ...(instance ? { instance } : {}) };
272
289
  }
273
290
  // OAuth 2.0 (device login): {"error": "authorization_pending", "error_description": "…"}.
274
291
  if (typeof body.error === "string" && body.success !== false) {
@@ -0,0 +1,107 @@
1
+ // Resource handles (plan 3.4, 2.7 M3): the base a product helper's object for one live resource builds on (a
2
+ // sandbox, a browser session, a video), so every product disposes and traces the same way.
3
+ //
4
+ // - Disposal happens once: `await using h = ...`, `await h.dispose()` or `await h.use(async (h) => ...)`. A second
5
+ // dispose returns the first one's promise.
6
+ // - Under `h.use(fn)` the body's error is what the caller gets; a dispose error after it is kept on the handle
7
+ // (`disposeError`) and on the body's error (`disposeError`, when it is an object) and never replaces it. Under
8
+ // `await using` the language decides: a dispose error after a body error arrives as a `SuppressedError` whose
9
+ // `suppressed` is the body's error.
10
+ // - Tracing: a handle has one trace id. `callOptions()` gives each call through it a new span in that trace (W3C
11
+ // `traceparent`), and a handle created from another (`new Video(client, { parent: session })`) joins its trace,
12
+ // so a chain of calls across products shows up as one trace in the request log.
13
+
14
+ import type { RequestOptions } from "./client.ts";
15
+ import { currentTurn, withMark } from "./traces.ts";
16
+ import { newTraceId, traceparentIn } from "./util.ts";
17
+
18
+ export interface HandleOptions {
19
+ /** Join this handle's trace (a handle created from another handle). */
20
+ parent?: Handle | undefined;
21
+ /** Join this trace (32 hex digits), e.g. from an incoming request's `traceparent`. */
22
+ traceId?: string | undefined;
23
+ }
24
+
25
+ /** Puts the dispose error on the body's error without changing what the caller catches. */
26
+ function attach(bodyError: unknown, disposeError: unknown): void {
27
+ if ((typeof bodyError === "object" && bodyError !== null) || typeof bodyError === "function") {
28
+ try {
29
+ Object.defineProperty(bodyError, "disposeError", { value: disposeError, configurable: true });
30
+ } catch {
31
+ // frozen or non-extensible: the handle still has it
32
+ }
33
+ }
34
+ }
35
+
36
+ export abstract class Handle {
37
+ /** The trace every call through this handle joins, and the handles it creates. */
38
+ readonly traceId: string;
39
+ /**
40
+ * How its calls are marked (observability.md 3.4): `turn` when it was made inside a turn (it joins that turn),
41
+ * `call` when the SDK minted its trace, none when the trace is the caller's (`traceId` given).
42
+ */
43
+ readonly traceMark: "turn" | "call" | null;
44
+ /** The error the dispose ended with, once it failed. */
45
+ disposeError: unknown = undefined;
46
+ #disposal: Promise<void> | undefined;
47
+
48
+ protected constructor(options: HandleOptions = {}) {
49
+ const turn = currentTurn();
50
+ this.traceId = options.parent?.traceId ?? options.traceId ?? turn?.traceId ?? newTraceId();
51
+ this.traceMark = options.parent ? options.parent.traceMark : options.traceId ? null : turn ? "turn" : "call";
52
+ }
53
+
54
+ /** Releases the resource (delete the sandbox, close the session). Called at most once per handle. */
55
+ protected abstract _dispose(): Promise<void>;
56
+
57
+ /** True once dispose has started. */
58
+ get disposed(): boolean {
59
+ return this.#disposal !== undefined;
60
+ }
61
+
62
+ /** Releases the resource once; every later call returns the same promise (and the same error, if it failed). */
63
+ dispose(): Promise<void> {
64
+ this.#disposal ??= (async () => {
65
+ try {
66
+ await this._dispose();
67
+ } catch (err) {
68
+ this.disposeError = err;
69
+ throw err;
70
+ }
71
+ })();
72
+ return this.#disposal;
73
+ }
74
+
75
+ /** `await using h = await b3os.sandboxes.create(...)`: disposes when the block ends, also when it throws. */
76
+ [Symbol.asyncDispose](): Promise<void> {
77
+ return this.dispose();
78
+ }
79
+
80
+ /**
81
+ * Runs `body` with this handle and disposes it afterwards, also when `body` throws. The body's error wins: a
82
+ * dispose error after it is kept as `disposeError` on the handle and on the body's error. Without a body error,
83
+ * a dispose error is thrown.
84
+ */
85
+ async use<R>(body: (handle: this) => R | Promise<R>): Promise<R> {
86
+ let result: R;
87
+ try {
88
+ result = await body(this);
89
+ } catch (bodyError) {
90
+ try {
91
+ await this.dispose();
92
+ } catch (disposeError) {
93
+ attach(bodyError, disposeError);
94
+ }
95
+ throw bodyError;
96
+ }
97
+ await this.dispose();
98
+ return result;
99
+ }
100
+
101
+ /** Options for one call through this handle: a new span in the handle's trace, unless `o` names a traceparent. */
102
+ protected callOptions<O extends RequestOptions>(o?: O): O {
103
+ if (o?.traceparent) return { ...o };
104
+ const mark = this.traceMark ? { tracestate: withMark(undefined, this.traceMark) } : {};
105
+ return { ...o, traceparent: traceparentIn(this.traceId), ...mark } as O;
106
+ }
107
+ }