@b3os/sdk 0.0.1 → 0.1.3

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 (204) hide show
  1. package/README.md +171 -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 +61 -3
  6. package/dist/cjs/core/client.js +211 -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 +31 -0
  12. package/dist/cjs/core/handle.js +86 -0
  13. package/dist/cjs/core/handle.js.map +1 -0
  14. package/dist/cjs/core/index.d.ts +6 -4
  15. package/dist/cjs/core/index.js +8 -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/transport.js +1 -1
  27. package/dist/cjs/core/transport.js.map +1 -1
  28. package/dist/cjs/core/util.d.ts +15 -3
  29. package/dist/cjs/core/util.js +54 -2
  30. package/dist/cjs/core/util.js.map +1 -1
  31. package/dist/cjs/core/ws.d.ts +4 -0
  32. package/dist/cjs/core/ws.js +7 -4
  33. package/dist/cjs/core/ws.js.map +1 -1
  34. package/dist/cjs/generated/client.d.ts +2 -2
  35. package/dist/cjs/generated/client.js +2 -2
  36. package/dist/cjs/generated/errors.d.ts +1 -1
  37. package/dist/cjs/generated/errors.js +30 -0
  38. package/dist/cjs/generated/errors.js.map +1 -1
  39. package/dist/cjs/generated/jobs.js +1 -1
  40. package/dist/cjs/generated/ns/actions.d.ts +48 -6
  41. package/dist/cjs/generated/ns/actions.js +59 -6
  42. package/dist/cjs/generated/ns/actions.js.map +1 -1
  43. package/dist/cjs/generated/ns/infer.d.ts +185 -54
  44. package/dist/cjs/generated/ns/infer.js +28 -74
  45. package/dist/cjs/generated/ns/infer.js.map +1 -1
  46. package/dist/cjs/generated/ns/keys.d.ts +12 -0
  47. package/dist/cjs/generated/ns/keys.js +22 -0
  48. package/dist/cjs/generated/ns/keys.js.map +1 -1
  49. package/dist/cjs/generated/ns/render.d.ts +95 -6
  50. package/dist/cjs/generated/ns/render.js +124 -7
  51. package/dist/cjs/generated/ns/render.js.map +1 -1
  52. package/dist/cjs/generated/ns/requests.d.ts +3 -1
  53. package/dist/cjs/generated/ns/requests.js +3 -1
  54. package/dist/cjs/generated/ns/requests.js.map +1 -1
  55. package/dist/cjs/generated/ns/routines.d.ts +131 -9
  56. package/dist/cjs/generated/ns/routines.js +186 -9
  57. package/dist/cjs/generated/ns/routines.js.map +1 -1
  58. package/dist/cjs/generated/ns/sandboxes.d.ts +298 -31
  59. package/dist/cjs/generated/ns/sandboxes.js +368 -29
  60. package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
  61. package/dist/cjs/generated/ns/vision.d.ts +133 -14
  62. package/dist/cjs/generated/ns/vision.js +158 -12
  63. package/dist/cjs/generated/ns/vision.js.map +1 -1
  64. package/dist/cjs/generated/ns/webhooks.d.ts +8 -5
  65. package/dist/cjs/generated/ns/webhooks.js +8 -5
  66. package/dist/cjs/generated/ns/webhooks.js.map +1 -1
  67. package/dist/cjs/generated/types.d.ts +1956 -301
  68. package/dist/cjs/helpers/agents.d.ts +95 -0
  69. package/dist/cjs/helpers/agents.js +205 -0
  70. package/dist/cjs/helpers/agents.js.map +1 -0
  71. package/dist/cjs/helpers/render.d.ts +15 -0
  72. package/dist/cjs/helpers/render.js +74 -0
  73. package/dist/cjs/helpers/render.js.map +1 -0
  74. package/dist/cjs/helpers/routines.d.ts +61 -0
  75. package/dist/cjs/helpers/routines.js +234 -0
  76. package/dist/cjs/helpers/routines.js.map +1 -0
  77. package/dist/cjs/helpers/sandboxes.d.ts +237 -0
  78. package/dist/cjs/helpers/sandboxes.js +608 -0
  79. package/dist/cjs/helpers/sandboxes.js.map +1 -0
  80. package/dist/cjs/index.d.ts +4 -1
  81. package/dist/cjs/index.js +8 -5
  82. package/dist/cjs/index.js.map +1 -1
  83. package/dist/cjs/routines.d.ts +1 -0
  84. package/dist/cjs/routines.js +21 -0
  85. package/dist/cjs/routines.js.map +1 -0
  86. package/dist/cjs/webhooks.js.map +1 -1
  87. package/dist/esm/core/bytes.d.ts +30 -0
  88. package/dist/esm/core/bytes.js +111 -0
  89. package/dist/esm/core/bytes.js.map +1 -0
  90. package/dist/esm/core/client.d.ts +61 -3
  91. package/dist/esm/core/client.js +208 -31
  92. package/dist/esm/core/client.js.map +1 -1
  93. package/dist/esm/core/errors.d.ts +16 -4
  94. package/dist/esm/core/errors.js +9 -6
  95. package/dist/esm/core/errors.js.map +1 -1
  96. package/dist/esm/core/handle.d.ts +31 -0
  97. package/dist/esm/core/handle.js +82 -0
  98. package/dist/esm/core/handle.js.map +1 -0
  99. package/dist/esm/core/index.d.ts +6 -4
  100. package/dist/esm/core/index.js +4 -2
  101. package/dist/esm/core/index.js.map +1 -1
  102. package/dist/esm/core/login.d.ts +24 -0
  103. package/dist/esm/core/login.js +85 -0
  104. package/dist/esm/core/login.js.map +1 -0
  105. package/dist/esm/core/namespace.d.ts +1 -1
  106. package/dist/esm/core/namespace.js +1 -1
  107. package/dist/esm/core/op.d.ts +11 -1
  108. package/dist/esm/core/timing.d.ts +1 -1
  109. package/dist/esm/core/timing.js +8 -1
  110. package/dist/esm/core/timing.js.map +1 -1
  111. package/dist/esm/core/transport.js +1 -1
  112. package/dist/esm/core/transport.js.map +1 -1
  113. package/dist/esm/core/util.d.ts +15 -3
  114. package/dist/esm/core/util.js +48 -1
  115. package/dist/esm/core/util.js.map +1 -1
  116. package/dist/esm/core/ws.d.ts +4 -0
  117. package/dist/esm/core/ws.js +7 -4
  118. package/dist/esm/core/ws.js.map +1 -1
  119. package/dist/esm/generated/client.d.ts +2 -2
  120. package/dist/esm/generated/client.js +2 -2
  121. package/dist/esm/generated/errors.d.ts +1 -1
  122. package/dist/esm/generated/errors.js +30 -0
  123. package/dist/esm/generated/errors.js.map +1 -1
  124. package/dist/esm/generated/jobs.js +1 -1
  125. package/dist/esm/generated/ns/actions.d.ts +48 -6
  126. package/dist/esm/generated/ns/actions.js +59 -6
  127. package/dist/esm/generated/ns/actions.js.map +1 -1
  128. package/dist/esm/generated/ns/infer.d.ts +185 -54
  129. package/dist/esm/generated/ns/infer.js +28 -74
  130. package/dist/esm/generated/ns/infer.js.map +1 -1
  131. package/dist/esm/generated/ns/keys.d.ts +12 -0
  132. package/dist/esm/generated/ns/keys.js +22 -0
  133. package/dist/esm/generated/ns/keys.js.map +1 -1
  134. package/dist/esm/generated/ns/render.d.ts +95 -6
  135. package/dist/esm/generated/ns/render.js +124 -7
  136. package/dist/esm/generated/ns/render.js.map +1 -1
  137. package/dist/esm/generated/ns/requests.d.ts +3 -1
  138. package/dist/esm/generated/ns/requests.js +3 -1
  139. package/dist/esm/generated/ns/requests.js.map +1 -1
  140. package/dist/esm/generated/ns/routines.d.ts +131 -9
  141. package/dist/esm/generated/ns/routines.js +186 -9
  142. package/dist/esm/generated/ns/routines.js.map +1 -1
  143. package/dist/esm/generated/ns/sandboxes.d.ts +298 -31
  144. package/dist/esm/generated/ns/sandboxes.js +368 -29
  145. package/dist/esm/generated/ns/sandboxes.js.map +1 -1
  146. package/dist/esm/generated/ns/vision.d.ts +133 -14
  147. package/dist/esm/generated/ns/vision.js +158 -12
  148. package/dist/esm/generated/ns/vision.js.map +1 -1
  149. package/dist/esm/generated/ns/webhooks.d.ts +8 -5
  150. package/dist/esm/generated/ns/webhooks.js +8 -5
  151. package/dist/esm/generated/ns/webhooks.js.map +1 -1
  152. package/dist/esm/generated/types.d.ts +1956 -301
  153. package/dist/esm/helpers/agents.d.ts +95 -0
  154. package/dist/esm/helpers/agents.js +199 -0
  155. package/dist/esm/helpers/agents.js.map +1 -0
  156. package/dist/esm/helpers/render.d.ts +15 -0
  157. package/dist/esm/helpers/render.js +70 -0
  158. package/dist/esm/helpers/render.js.map +1 -0
  159. package/dist/esm/helpers/routines.d.ts +61 -0
  160. package/dist/esm/helpers/routines.js +226 -0
  161. package/dist/esm/helpers/routines.js.map +1 -0
  162. package/dist/esm/helpers/sandboxes.d.ts +237 -0
  163. package/dist/esm/helpers/sandboxes.js +600 -0
  164. package/dist/esm/helpers/sandboxes.js.map +1 -0
  165. package/dist/esm/index.d.ts +4 -1
  166. package/dist/esm/index.js +6 -5
  167. package/dist/esm/index.js.map +1 -1
  168. package/dist/esm/routines.d.ts +1 -0
  169. package/dist/esm/routines.js +5 -0
  170. package/dist/esm/routines.js.map +1 -0
  171. package/dist/esm/webhooks.js.map +1 -1
  172. package/package.json +18 -7
  173. package/src/core/bytes.ts +112 -0
  174. package/src/core/client.ts +253 -33
  175. package/src/core/errors.ts +27 -10
  176. package/src/core/handle.ts +97 -0
  177. package/src/core/index.ts +7 -2
  178. package/src/core/login.ts +98 -0
  179. package/src/core/namespace.ts +1 -1
  180. package/src/core/op.ts +11 -1
  181. package/src/core/timing.ts +7 -2
  182. package/src/core/transport.ts +1 -1
  183. package/src/core/util.ts +53 -3
  184. package/src/core/ws.ts +11 -4
  185. package/src/generated/client.ts +2 -2
  186. package/src/generated/errors.ts +60 -0
  187. package/src/generated/jobs.ts +1 -1
  188. package/src/generated/ns/actions.ts +69 -6
  189. package/src/generated/ns/infer.ts +229 -61
  190. package/src/generated/ns/keys.ts +23 -0
  191. package/src/generated/ns/render.ts +152 -7
  192. package/src/generated/ns/requests.ts +3 -1
  193. package/src/generated/ns/routines.ts +205 -9
  194. package/src/generated/ns/sandboxes.ts +434 -34
  195. package/src/generated/ns/vision.ts +168 -14
  196. package/src/generated/ns/webhooks.ts +8 -5
  197. package/src/generated/types.ts +2211 -422
  198. package/src/helpers/agents.ts +300 -0
  199. package/src/helpers/render.ts +91 -0
  200. package/src/helpers/routines.ts +278 -0
  201. package/src/helpers/sandboxes.ts +788 -0
  202. package/src/index.ts +29 -5
  203. package/src/routines.ts +5 -0
  204. 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,
@@ -37,17 +39,58 @@ import {
37
39
  type TransportResponse,
38
40
  TransportTimeout,
39
41
  } from "./transport.ts";
40
- import { backoffMs, env, isObject, parseRetryAfter, runtime, runtimeLabel, SDK_VERSION, sleep, uuid } from "./util.ts";
42
+ import {
43
+ backoffMs,
44
+ describeErr,
45
+ env,
46
+ isObject,
47
+ newTraceId,
48
+ parseRetryAfter,
49
+ runtime,
50
+ runtimeLabel,
51
+ SDK_VERSION,
52
+ sleep,
53
+ traceIdOf,
54
+ traceparentIn,
55
+ uuid,
56
+ } from "./util.ts";
41
57
 
42
58
  /** A binary request body (file uploads, pack bundles). */
43
59
  export type BinaryInput = RequestBody;
44
60
 
45
61
  export const DEFAULT_BASE_URL = "https://beta-api.b3os.org";
62
+ /** Where API keys are made (the console's API keys page). */
63
+ export const KEYS_PAGE = "https://beta.b3os.org/app/keys";
46
64
  /** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
47
65
  export const DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
48
66
 
67
+ /** What `GET /v1/ping` answers (requests.yaml `Ping`). */
68
+ export interface Ping {
69
+ object: "ping";
70
+ /** The node that answered (`n1`). */
71
+ node: string;
72
+ /** The node's clock when it answered, RFC 3339 in UTC with milliseconds. */
73
+ ts: string;
74
+ }
75
+
76
+ /**
77
+ * `platformPing` from packages/spec/dist (routes.json has no SDK name for it: it belongs to no namespace), so the
78
+ * core carries it; test/ping.test.ts checks it against routes.json.
79
+ */
80
+ export const PING_OP: Op = {
81
+ id: "platformPing",
82
+ method: "GET",
83
+ path: "/v1/ping",
84
+ timeoutMs: 5000,
85
+ scope: "authenticated",
86
+ };
87
+
49
88
  export interface ClientOptions {
50
- /** API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`. */
89
+ /**
90
+ * API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`, else, on a developer's machine, the
91
+ * token `b3os login` stored (never in CI, on GitHub Actions or in a B3OS sandbox; one stderr line says when it is
92
+ * used). `null` sends no key and skips the stored login.
93
+ */
51
94
  apiKey?: string | null;
52
95
  /** The API host for edge-served operations and remote calls. Default: `B3OS_BASE_URL`, else beta-api.b3os.org. */
53
96
  baseUrl?: string;
@@ -83,13 +126,20 @@ export interface ClientOptions {
83
126
  }
84
127
 
85
128
  export interface RequestOptions {
86
- /** `Idempotency-Key` for this call; generated when the operation takes one and you pass none. */
129
+ /**
130
+ * `Idempotency-Key` for this call; generated when the operation takes one and you pass none, except for
131
+ * operations whose effect cannot be repeated (`x-b3os-idempotency: caller`, `sandboxes.exec`): those send only
132
+ * the key you pass.
133
+ */
87
134
  idempotencyKey?: string;
88
135
  timeoutMs?: number;
89
136
  maxRetries?: number;
90
137
  signal?: AbortSignal;
91
138
  headers?: Record<string, string>;
92
- /** W3C trace context, propagated into product calls and routine steps. */
139
+ /**
140
+ * W3C trace context, propagated into product calls and routine steps. Sent as given; without one, each call
141
+ * gets its own trace (every attempt a new span in it), and calls through a resource handle share the handle's.
142
+ */
93
143
  traceparent?: string;
94
144
  }
95
145
 
@@ -155,6 +205,23 @@ const REJECTED_BEFORE_WORK = new Set([
155
205
  "auth_unavailable",
156
206
  "idempotency_request_in_progress",
157
207
  ]);
208
+ /**
209
+ * Codes in REJECTED_BEFORE_WORK that the edge also sends after it forwarded the request, so a B3OS body with one
210
+ * does not show that the request did no work: 503 `node_unavailable` covers a tunnel or a node that failed while it
211
+ * held the request (apps/edge/src/gateway/forward.ts maps every fetch failure and every answer without the node's
212
+ * request id to it). A caller-keyed operation (sandboxesExec) is not resent after one; other operations still are.
213
+ */
214
+ const MAYBE_FORWARDED = new Set(["node_unavailable"]);
215
+
216
+ /**
217
+ * True when the answer shows that the request was refused before any work, so even a call that is not retry-safe
218
+ * may be sent again.
219
+ */
220
+ function rejectedBeforeWorkFor(op: Op, code: string, status: number, codeFromStatus: boolean | undefined): boolean {
221
+ if (!REJECTED_BEFORE_WORK.has(code)) return false;
222
+ if (codeFromStatus) return NEVER_REACHED_STATUSES.has(status);
223
+ return !(op.callerKey && MAYBE_FORWARDED.has(code));
224
+ }
158
225
 
159
226
  function trimSlash(s: string): string {
160
227
  return s.endsWith("/") ? s.replace(/\/+$/, "") : s;
@@ -240,15 +307,41 @@ function buildPath(op: Op, values: readonly (string | number)[] | undefined): st
240
307
  });
241
308
  }
242
309
 
243
- function buildQuery(query: object | undefined, extra?: Record<string, string>): string {
310
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
311
+ typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
312
+ const queryValue = (v: unknown): string => (v instanceof Date ? v.toISOString() : String(v));
313
+
314
+ /** `name[key]=value` for each member of a deepObject value (nested objects add a bracket; arrays repeat the key). */
315
+ function appendDeep(sp: URLSearchParams, name: string, v: unknown): void {
316
+ if (v === undefined || v === null) return;
317
+ if (isPlainObject(v)) for (const [k, x] of Object.entries(v)) appendDeep(sp, `${name}[${k}]`, x);
318
+ else if (Array.isArray(v)) for (const x of v) appendDeep(sp, name, x);
319
+ else sp.append(name, queryValue(v));
320
+ }
321
+
322
+ /**
323
+ * The query string. Arrays repeat their key (`style: form`, `explode: true`); an object is sent as `name[key]=value`
324
+ * pairs when the operation declares the parameter `style: deepObject` (`metadata[team]=infra`), and is refused
325
+ * otherwise rather than sent as "[object Object]". A boolean for one of the operation's 0/1 flags is sent as `1` or
326
+ * `0` (`list: true` is `list=1`); other booleans as `true` or `false`.
327
+ */
328
+ export function buildQuery(
329
+ query: object | undefined,
330
+ extra?: Record<string, string>,
331
+ op?: Pick<Op, "id" | "deepObject" | "flags">,
332
+ ): string {
244
333
  let sp: URLSearchParams | undefined;
245
334
  if (query) {
246
335
  for (const [k, v] of Object.entries(query)) {
247
336
  if (v === undefined || v === null) continue;
248
337
  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));
338
+ if (isPlainObject(v)) {
339
+ if (!op?.deepObject?.includes(k))
340
+ throw new TypeError(`b3os: ${op?.id ?? "request"}: the query parameter ${k} does not take an object`);
341
+ appendDeep(sp, k, v);
342
+ } else if (Array.isArray(v)) for (const x of v) sp.append(k, queryValue(x));
343
+ else if (typeof v === "boolean" && op?.flags?.includes(k)) sp.append(k, v ? "1" : "0");
344
+ else sp.append(k, queryValue(v));
252
345
  }
253
346
  }
254
347
  if (extra) {
@@ -278,18 +371,36 @@ function connectRefused(err: unknown): boolean {
278
371
  return code === "ENOENT" || code === "ECONNREFUSED" || code === "EACCES" || code === "EPERM";
279
372
  }
280
373
 
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);
374
+ /**
375
+ * Why a call to a caller-keyed operation (`x-b3os-idempotency: caller`, sandboxesExec) was not sent again: `what`
376
+ * happened after the request may have reached the server, so its effect may have happened.
377
+ */
378
+ function mayHaveRun(op: Op, key: string | undefined, what: string): string | undefined {
379
+ if (!op.callerKey) return undefined;
380
+ const again = key
381
+ ? `Call it again with the same idempotencyKey ("${key}") to get its recorded outcome rather than run it twice`
382
+ : "Check its effect before running it again, or pass an idempotencyKey so a second call returns the recorded outcome";
383
+ return `${op.id} may have run: ${what}, so the SDK did not send it again. ${again}`;
384
+ }
385
+
386
+ /** `b3os_sk_…abcd`: enough to tell keys apart in a log, never enough to use one. */
387
+ function redactKey(key: string | null): string | null {
388
+ if (!key) return key;
389
+ const prefix = /^b3os_[a-z]+_/.exec(key)?.[0] ?? "";
390
+ return `${prefix}…${key.slice(-4)}`;
289
391
  }
290
392
 
291
393
  export class B3OSCore {
292
- readonly apiKey: string | null;
394
+ /**
395
+ * The key this client sends. Readable, but not enumerable: `JSON.stringify`, `console.log` and `util.inspect` of a
396
+ * client show only its last four characters (see `toJSON`).
397
+ */
398
+ declare readonly apiKey: string | null;
399
+ /**
400
+ * The sandbox this code runs in (`B3OS_SANDBOX_ID`, set inside every B3OS sandbox with `B3OS_API_URL`), or null.
401
+ * Useful as the id for operations on the sandbox itself: `b3os.sandboxes.createSnapshot(b3os.sandboxId!)`.
402
+ */
403
+ readonly sandboxId: string | null;
293
404
  readonly baseUrl: string;
294
405
  readonly maxRetries: number;
295
406
  readonly maxRetryDelayMs: number;
@@ -298,10 +409,67 @@ export class B3OSCore {
298
409
  private node: Route;
299
410
  private readonly headers: Record<string, string>;
300
411
  private readonly onResponse: ((info: ResponseInfo) => void) | undefined;
412
+ /** What a call without a key says: why no key was found, and how to give one. */
413
+ readonly #noKeyHint: string;
414
+ /**
415
+ * Whether a call that needs a key and has none is answered here, with no request: only for the B3OS API host
416
+ * (which answers every such call 401), with the SDK's own fetch, outside a B3OS sandbox. Another host may be a mock
417
+ * or a node that answers first, a custom fetch may add the credential, and a sandbox's egress proxy may.
418
+ */
419
+ readonly #keylessAnswersLocally: boolean;
420
+
421
+ /** What `JSON.stringify(client)` prints: the settings, with the key redacted. */
422
+ toJSON(): Record<string, unknown> {
423
+ return {
424
+ baseUrl: this.baseUrl,
425
+ apiKey: redactKey(this.apiKey),
426
+ sandboxId: this.sandboxId,
427
+ maxRetries: this.maxRetries,
428
+ maxRetryDelayMs: this.maxRetryDelayMs,
429
+ timeoutMs: this.timeoutMs,
430
+ };
431
+ }
432
+
433
+ /** What `console.log(client)` and `util.inspect(client)` print on Node, Bun and Deno: the same as `toJSON`. */
434
+ [Symbol.for("nodejs.util.inspect.custom")](): Record<string, unknown> {
435
+ return this.toJSON();
436
+ }
301
437
 
302
438
  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");
439
+ let apiKey = options.apiKey !== undefined ? options.apiKey : (env("B3OS_API_KEY") ?? null);
440
+ let explicitBase = options.baseUrl ?? env("B3OS_BASE_URL");
441
+ let noKeyHint = "No API key is set: set B3OS_API_KEY or pass apiKey";
442
+ if (options.apiKey === null) {
443
+ noKeyHint =
444
+ "No API key is set: this client was made with apiKey: null. Pass apiKey, or leave it out to use " +
445
+ "B3OS_API_KEY or your b3os login";
446
+ } else if (apiKey === null) {
447
+ // The stored `b3os login`, on a developer's machine only, and only for the API host it was issued by.
448
+ const blocked = loginBlockedBy();
449
+ const login = blocked ? undefined : readStoredLogin();
450
+ const loginBase = login?.baseUrl ?? DEFAULT_BASE_URL;
451
+ if (blocked) {
452
+ noKeyHint += ` (the SDK does not read the b3os login in ${blocked})`;
453
+ } else if (login && (explicitBase === undefined || trimSlash(explicitBase) === loginBase)) {
454
+ apiKey = login.token;
455
+ if (explicitBase === undefined && loginBase !== DEFAULT_BASE_URL) explicitBase = loginBase;
456
+ announceLogin(login, redactKey(login.token) ?? "");
457
+ } else if (login) {
458
+ noKeyHint += ` (your b3os login is for ${loginBase}, not ${trimSlash(explicitBase ?? "")})`;
459
+ } else if (canReadLogin()) {
460
+ noKeyHint = "Not signed in: run b3os login, set B3OS_API_KEY or pass apiKey";
461
+ }
462
+ }
463
+ const onApiHost = trimSlash(explicitBase ?? DEFAULT_BASE_URL) === DEFAULT_BASE_URL;
464
+ this.#noKeyHint = onApiHost ? `${noKeyHint}. Make a key at ${KEYS_PAGE}` : noKeyHint;
465
+ this.#keylessAnswersLocally =
466
+ onApiHost && !options.fetch && !env("B3OS_SANDBOX_ID") && !env("B3OS_API_URL") && !apiKey;
467
+ Object.defineProperty(this, "apiKey", {
468
+ value: apiKey,
469
+ enumerable: false,
470
+ writable: false,
471
+ configurable: false,
472
+ });
305
473
  this.baseUrl = trimSlash(explicitBase ?? DEFAULT_BASE_URL);
306
474
  this.maxRetries = options.maxRetries ?? 2;
307
475
  this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
@@ -322,6 +490,8 @@ export class B3OSCore {
322
490
  const sockEnv = env("B3OS_SOCKET");
323
491
  const sockDisabled = options.socketPath === false || sockEnv === "0" || sockEnv === "off";
324
492
  const nodeUrl = options.nodeUrl !== undefined ? options.nodeUrl : (env("B3OS_API_URL") ?? null);
493
+ const sbx = env("B3OS_SANDBOX_ID");
494
+ this.sandboxId = sbx && /^sbx_[0-9a-hjkmnp-tv-z]{26}$/.test(sbx) ? sbx : null;
325
495
  let node: Route = this.edge;
326
496
  if (pref !== "http") {
327
497
  const explicitSock =
@@ -379,8 +549,22 @@ export class B3OSCore {
379
549
  }
380
550
 
381
551
  /** 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 };
552
+ get routes(): { node: string; edge: string; nodeKind: Route["kind"]; sandboxId: string | null } {
553
+ return {
554
+ node: this.node.transport.label,
555
+ edge: this.edge.transport.label,
556
+ nodeKind: this.node.kind,
557
+ sandboxId: this.sandboxId,
558
+ };
559
+ }
560
+
561
+ /**
562
+ * The smallest call the node serves, `GET /v1/ping`: the node's id and clock once the credential is checked,
563
+ * and nothing else. Any valid credential may call it. Its time is the round trip to the node (the "edge round
564
+ * trip" that latency targets are written against); `.withResponse()` gives the Server-Timing phases.
565
+ */
566
+ ping(options?: RequestOptions): APIPromise<Ping> {
567
+ return this._call<Ping>(PING_OP, {}, options);
384
568
  }
385
569
 
386
570
  /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
@@ -392,10 +576,10 @@ export class B3OSCore {
392
576
  // ------------------------------------------------------------------------------------------------------------
393
577
  // The request pipeline
394
578
 
395
- private headersFor(route: Route, op: Op, o: RequestOptions, accept: string): Record<string, string> {
579
+ private headersFor(route: Route, op: Op, o: RequestOptions, accept: string, traceId: string): Record<string, string> {
396
580
  const h: Record<string, string> = { ...this.headers, accept };
397
581
  if (route.auth && this.apiKey) h.authorization = `Bearer ${this.apiKey}`;
398
- if (o.traceparent) h.traceparent = o.traceparent;
582
+ h.traceparent = o.traceparent ?? traceparentIn(traceId);
399
583
  if (o.headers) for (const [k, v] of Object.entries(o.headers)) h[k.toLowerCase()] = v;
400
584
  void op;
401
585
  return h;
@@ -435,9 +619,7 @@ export class B3OSCore {
435
619
  ? `${op.id} is served by ${this.baseUrl}`
436
620
  : `${op.id} is served by ${this.baseUrl}; set B3OS_API_KEY (or pass apiKey) so the SDK can send it there`;
437
621
  }
438
- if (err.status === 401 && route.auth && !this.apiKey) {
439
- return "No API key is configured: set B3OS_API_KEY or pass apiKey";
440
- }
622
+ if (err.status === 401 && route.auth && !this.apiKey) return this.#noKeyHint;
441
623
  if (err.status === 403 && err.reason === "scope" && route.kind === "uds") {
442
624
  return (
443
625
  "Over the node's Unix socket this process acts as the local principal its uid maps to in b3osd.toml " +
@@ -451,18 +633,26 @@ export class B3OSCore {
451
633
  private async send(op: Op, args: CallArgs, o: RequestOptions, x: SendExtras): Promise<Sent> {
452
634
  const method = op.method;
453
635
  const pathStr = buildPath(op, args.path);
454
- const query = buildQuery(args.query, x.extraQuery);
636
+ const query = buildQuery(args.query, x.extraQuery, op);
455
637
  let idemKey = o.idempotencyKey;
456
- if (!idemKey && op.idem && method !== "GET") idemKey = uuid();
638
+ if (!idemKey && op.idem && !op.callerKey && method !== "GET") idemKey = uuid();
457
639
  const streamBody = typeof ReadableStream !== "undefined" && args.body instanceof ReadableStream;
640
+ // A caller-keyed operation (sandboxesExec) is resent only after an answer that shows it did no work, key or not:
641
+ // the node cannot always tell whether a command it handed on ran, and a retry must never run it twice.
458
642
  const retrySafe =
459
- !streamBody && (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
643
+ !streamBody &&
644
+ !op.callerKey &&
645
+ (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
460
646
  const maxRetries = streamBody ? 0 : (o.maxRetries ?? this.maxRetries);
461
647
  const perAttempt = o.timeoutMs ?? this.timeoutMs ?? (x.sse ? 30_000 : Math.min(op.timeoutMs, 65_000) + 5_000);
462
648
  let route = op.edge ? this.edge : this.node;
463
649
  let attempt = 0;
650
+ // One trace per call (attempts are spans in it) unless the caller sent a traceparent, which is kept as is. A
651
+ // client made with a `traceparent` header (an MCP server's per-request client) joins that trace: each call is a
652
+ // new span in it, so the header's own span id is never sent twice.
653
+ const traceId = traceIdOf(this.headers.traceparent) ?? newTraceId();
464
654
  for (;;) {
465
- const headers = this.headersFor(route, op, o, x.accept);
655
+ const headers = this.headersFor(route, op, o, x.accept, traceId);
466
656
  if (idemKey) headers["idempotency-key"] = idemKey;
467
657
  if (op.headerParams && args.headerParams) {
468
658
  for (const [k, name] of Object.entries(op.headerParams)) {
@@ -470,6 +660,17 @@ export class B3OSCore {
470
660
  if (v !== undefined && v !== null) headers[name.toLowerCase()] = String(v);
471
661
  }
472
662
  }
663
+ // No key, and the API host would answer 401: say so without the round trip. Scope `public` needs no key, and
664
+ // `unknown` is a raw `request()`, which may be to a route that needs none (the device login).
665
+ if (
666
+ route.auth &&
667
+ this.#keylessAnswersLocally &&
668
+ !headers.authorization &&
669
+ op.scope !== "public" &&
670
+ op.scope !== "unknown"
671
+ ) {
672
+ throw new B3OSError({ code: "unauthorized", detail: this.#noKeyHint, operationId: op.id });
673
+ }
473
674
  const body = this.encodeBody(op, args, headers);
474
675
  const path = pathStr + query;
475
676
  const url = route.base + path;
@@ -501,11 +702,15 @@ export class B3OSCore {
501
702
  ? new B3OSTimeoutError({
502
703
  detail: `${op.id} did not answer within ${perAttempt} ms (${route.transport.label})`,
503
704
  operationId: op.id,
705
+ hint: mayHaveRun(op, idemKey, "it did not answer in time"),
504
706
  cause,
505
707
  })
506
708
  : new B3OSConnectionError({
507
709
  detail: `Could not reach ${route.transport.label}: ${describeErr(cause)}`,
508
710
  operationId: op.id,
711
+ hint: connectRefused(cause)
712
+ ? undefined
713
+ : mayHaveRun(op, idemKey, "the connection failed after the request may have been sent"),
509
714
  cause,
510
715
  });
511
716
  // Timeouts are not retried: the budget is spent. A refused connection never reached the server.
@@ -562,7 +767,12 @@ export class B3OSCore {
562
767
  retryAfterMs,
563
768
  operationId: op.id,
564
769
  });
565
- const hint = this.hint(route, op, err0);
770
+ const rejectedBeforeWork = rejectedBeforeWorkFor(op, err0.code, res.status, parsed.codeFromStatus);
771
+ const hint =
772
+ this.hint(route, op, err0) ??
773
+ (rejectedBeforeWork || res.status < 500
774
+ ? undefined
775
+ : mayHaveRun(op, idemKey, `the answer was ${res.status} ${err0.code}`));
566
776
  const err = hint
567
777
  ? new B3OSError({
568
778
  code: err0.code,
@@ -580,8 +790,6 @@ export class B3OSCore {
580
790
  hint,
581
791
  })
582
792
  : err0;
583
- const rejectedBeforeWork =
584
- REJECTED_BEFORE_WORK.has(err.code) && (!parsed.codeFromStatus || NEVER_REACHED_STATUSES.has(res.status));
585
793
  const retryable =
586
794
  rejectedBeforeWork ||
587
795
  (retrySafe && err.retryable && (err.status ?? 0) >= 500 && !NO_RETRY_TIMEOUT_CODES.has(err.code));
@@ -765,6 +973,18 @@ export class B3OSCore {
765
973
  });
766
974
  }
767
975
 
976
+ /**
977
+ * @internal A response body read as it arrives (speech with `stream_format: "audio"`): the per-attempt timeout
978
+ * covers the response head only, and nothing is retried once bytes have been handed out.
979
+ */
980
+ _postBytes(op: Op, args: CallArgs, options: RequestOptions = {}, accept = "application/octet-stream"): ByteStream {
981
+ return new ByteStream(
982
+ op.id,
983
+ (signal) => this.send(op, args, { ...options, signal }, { accept, sse: true }),
984
+ options.signal,
985
+ );
986
+ }
987
+
768
988
  /** @internal A job-creating operation (`x-b3os-job`). */
769
989
  _job<J extends JobLike, E>(op: Op, args: CallArgs, options: RequestOptions = {}): JobPromise<J, E> {
770
990
  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,97 @@
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 { newTraceId, traceparentIn } from "./util.ts";
16
+
17
+ export interface HandleOptions {
18
+ /** Join this handle's trace (a handle created from another handle). */
19
+ parent?: Handle | undefined;
20
+ /** Join this trace (32 hex digits), e.g. from an incoming request's `traceparent`. */
21
+ traceId?: string | undefined;
22
+ }
23
+
24
+ /** Puts the dispose error on the body's error without changing what the caller catches. */
25
+ function attach(bodyError: unknown, disposeError: unknown): void {
26
+ if ((typeof bodyError === "object" && bodyError !== null) || typeof bodyError === "function") {
27
+ try {
28
+ Object.defineProperty(bodyError, "disposeError", { value: disposeError, configurable: true });
29
+ } catch {
30
+ // frozen or non-extensible: the handle still has it
31
+ }
32
+ }
33
+ }
34
+
35
+ export abstract class Handle {
36
+ /** The trace every call through this handle joins, and the handles it creates. */
37
+ readonly traceId: string;
38
+ /** The error the dispose ended with, once it failed. */
39
+ disposeError: unknown = undefined;
40
+ #disposal: Promise<void> | undefined;
41
+
42
+ protected constructor(options: HandleOptions = {}) {
43
+ this.traceId = options.parent?.traceId ?? options.traceId ?? newTraceId();
44
+ }
45
+
46
+ /** Releases the resource (delete the sandbox, close the session). Called at most once per handle. */
47
+ protected abstract _dispose(): Promise<void>;
48
+
49
+ /** True once dispose has started. */
50
+ get disposed(): boolean {
51
+ return this.#disposal !== undefined;
52
+ }
53
+
54
+ /** Releases the resource once; every later call returns the same promise (and the same error, if it failed). */
55
+ dispose(): Promise<void> {
56
+ this.#disposal ??= (async () => {
57
+ try {
58
+ await this._dispose();
59
+ } catch (err) {
60
+ this.disposeError = err;
61
+ throw err;
62
+ }
63
+ })();
64
+ return this.#disposal;
65
+ }
66
+
67
+ /** `await using h = await b3os.sandboxes.create(...)`: disposes when the block ends, also when it throws. */
68
+ [Symbol.asyncDispose](): Promise<void> {
69
+ return this.dispose();
70
+ }
71
+
72
+ /**
73
+ * Runs `body` with this handle and disposes it afterwards, also when `body` throws. The body's error wins: a
74
+ * dispose error after it is kept as `disposeError` on the handle and on the body's error. Without a body error,
75
+ * a dispose error is thrown.
76
+ */
77
+ async use<R>(body: (handle: this) => R | Promise<R>): Promise<R> {
78
+ let result: R;
79
+ try {
80
+ result = await body(this);
81
+ } catch (bodyError) {
82
+ try {
83
+ await this.dispose();
84
+ } catch (disposeError) {
85
+ attach(bodyError, disposeError);
86
+ }
87
+ throw bodyError;
88
+ }
89
+ await this.dispose();
90
+ return result;
91
+ }
92
+
93
+ /** Options for one call through this handle: a new span in the handle's trace, unless `o` names a traceparent. */
94
+ protected callOptions<O extends RequestOptions>(o?: O): O {
95
+ return { ...o, traceparent: o?.traceparent ?? traceparentIn(this.traceId) } as O;
96
+ }
97
+ }
package/src/core/index.ts CHANGED
@@ -3,12 +3,15 @@
3
3
  // import { VisionAPI } from "@b3os/sdk/vision";
4
4
  // const vision = new VisionAPI(new B3OSCore({ apiKey }));
5
5
 
6
+ export { ByteStream } from "./bytes.ts";
6
7
  export {
7
8
  B3OSCore,
8
9
  type BinaryInput,
9
10
  type ClientOptions,
10
11
  DEFAULT_BASE_URL,
11
12
  DEFAULT_SOCKET_PATH,
13
+ PING_OP,
14
+ type Ping,
12
15
  type RawRequest,
13
16
  type RequestOptions,
14
17
  type StreamOptions,
@@ -21,8 +24,10 @@ export {
21
24
  type B3OSErrorCode,
22
25
  type B3OSErrorInit,
23
26
  B3OSJobError,
27
+ type B3OSKnownErrorCode,
24
28
  B3OSTimeoutError,
25
29
  } from "./errors.ts";
30
+ export { Handle, type HandleOptions } from "./handle.ts";
26
31
  export { isTerminalJob, isTerminalJobEvent, type JobRef, Jobs } from "./jobs.ts";
27
32
  export { Namespace } from "./namespace.ts";
28
33
  export type { CallArgs, HttpMethod, JobOps, Op } from "./op.ts";
@@ -41,5 +46,5 @@ export { type RateLimitInfo, ResponseInfo, responseOf } from "./response.ts";
41
46
  export { EventStream, type EventStreamOptions, SSEDecoder, type SSEMessage } from "./sse.ts";
42
47
  export { formatServerTiming, parseServerTiming, type ServerTiming, type ServerTimingEntry } from "./timing.ts";
43
48
  export type { HeadersLike } from "./transport.ts";
44
- export { SDK_VERSION } from "./util.ts";
45
- export { type CdpEndpoint, type PtyExit, PtySession } from "./ws.ts";
49
+ export { SDK_VERSION, TRACEPARENT_RE, traceIdOf } from "./util.ts";
50
+ export { type CdpEndpoint, type PtyExit, PtySession, type TicketedUrl } from "./ws.ts";