@b3os/sdk 0.1.0 → 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 +14 -3
  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
@@ -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";
@@ -0,0 +1,98 @@
1
+ // The `b3os login` token as the credential of last resort. The CLI keeps it in $XDG_CONFIG_HOME/b3os/credentials.json
2
+ // (default ~/.config/b3os/; B3OS_CREDENTIALS_FILE moves it), and the local MCP server reads the same file
3
+ // (packages/mcp/src/stdio.ts). The SDK reads it only on a developer's machine: never in CI, on a GitHub Actions
4
+ // runner or inside a B3OS sandbox, where code should run on a key made for it. It needs a file system, so Node, Bun
5
+ // and Deno only; nothing here imports a Node module statically.
6
+
7
+ import type * as NodeFs from "node:fs";
8
+ import type * as NodeOs from "node:os";
9
+ import type * as NodePath from "node:path";
10
+ import { builtin, env } from "./util.ts";
11
+
12
+ export interface StoredLogin {
13
+ /** `b3os_pat_…` from the device login. */
14
+ token: string;
15
+ /** The API host the token belongs to (the file's `base_url`), without a trailing slash. */
16
+ baseUrl: string | undefined;
17
+ /** The file it was read from. */
18
+ file: string;
19
+ }
20
+
21
+ /** CI services that do not set `CI` themselves. */
22
+ const CI_MARKERS = ["JENKINS_URL", "TF_BUILD", "CODEBUILD_BUILD_ID", "TEAMCITY_VERSION"];
23
+
24
+ /**
25
+ * Where the stored login is never read: "a B3OS sandbox" (B3OS sets `B3OS_SANDBOX_ID` and `B3OS_API_URL` in every
26
+ * sandbox), "GitHub Actions" (`GITHUB_ACTIONS`), "CI" (`CI` set to anything but `false` or `0`, or a CI service's own
27
+ * variable), or undefined on a developer's machine.
28
+ */
29
+ export function loginBlockedBy(): string | undefined {
30
+ if (env("B3OS_SANDBOX_ID") || env("B3OS_API_URL")) return "a B3OS sandbox";
31
+ if (env("GITHUB_ACTIONS")) return "GitHub Actions";
32
+ const ci = env("CI")?.toLowerCase();
33
+ if ((ci && ci !== "false" && ci !== "0") || CI_MARKERS.some((v) => env(v))) return "CI";
34
+ return undefined;
35
+ }
36
+
37
+ /** The credentials file `b3os login` writes, or undefined where there is no file system. */
38
+ export function credentialsFile(): string | undefined {
39
+ const explicit = env("B3OS_CREDENTIALS_FILE");
40
+ if (explicit) return explicit;
41
+ try {
42
+ const path = builtin<typeof NodePath>("node:path");
43
+ const os = builtin<typeof NodeOs>("node:os");
44
+ if (!path || !os) return undefined;
45
+ return path.join(env("XDG_CONFIG_HOME") ?? path.join(os.homedir(), ".config"), "b3os", "credentials.json");
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /** True when this runtime can read the credentials file at all. */
52
+ export function canReadLogin(): boolean {
53
+ return builtin("node:fs") !== undefined;
54
+ }
55
+
56
+ /** The stored login when there is one and it has not expired. Never throws. */
57
+ export function readStoredLogin(): StoredLogin | undefined {
58
+ try {
59
+ const fs = builtin<typeof NodeFs>("node:fs");
60
+ const file = credentialsFile();
61
+ if (!fs || !file) return undefined;
62
+ const c = JSON.parse(fs.readFileSync(file, "utf8")) as {
63
+ token?: unknown;
64
+ base_url?: unknown;
65
+ expires_at?: unknown;
66
+ };
67
+ if (typeof c.token !== "string" || !c.token) return undefined;
68
+ if (typeof c.expires_at === "string" && Date.parse(c.expires_at) < Date.now()) return undefined;
69
+ const baseUrl = typeof c.base_url === "string" && c.base_url ? c.base_url.replace(/\/+$/, "") : undefined;
70
+ return { token: c.token, baseUrl, file };
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ let announced = false;
77
+
78
+ /** The one stderr line per process that says the stored login is in use, and where it is not. */
79
+ export function announceLogin(login: StoredLogin, shownToken: string): void {
80
+ if (announced) return;
81
+ announced = true;
82
+ let file = login.file;
83
+ try {
84
+ const home = builtin<typeof NodeOs>("node:os")?.homedir();
85
+ if (home && file.startsWith(`${home}/`)) file = `~${file.slice(home.length)}`;
86
+ } catch {
87
+ // the full path is fine
88
+ }
89
+ console.warn(
90
+ `@b3os/sdk: no API key set, so using your b3os login (${shownToken}, ${file}). ` +
91
+ "CI and B3OS sandboxes never read it: set B3OS_API_KEY there.",
92
+ );
93
+ }
94
+
95
+ /** Tests only: let the next login announce itself again. */
96
+ export function resetLoginNotice(): void {
97
+ announced = false;
98
+ }
@@ -1,6 +1,6 @@
1
1
  import type { B3OSCore } from "./client.ts";
2
2
 
3
- /** Base of every generated namespace (`b3.vision`, `b3.sandboxes`, …). Construct one on a core client to use a
3
+ /** Base of every generated namespace (`b3os.vision`, `b3os.sandboxes`, …). Construct one on a core client to use a
4
4
  * single product without the rest: `new SandboxesAPI(new B3OSCore())`. */
5
5
  export abstract class Namespace {
6
6
  protected readonly _client: B3OSCore;
package/src/core/op.ts CHANGED
@@ -21,6 +21,10 @@ export interface Op {
21
21
  readonly wildcard?: string;
22
22
  /** Header parameters: option key → header name (`format` → `X-B3OS-Format`). */
23
23
  readonly headerParams?: Readonly<Record<string, string>>;
24
+ /** Query parameters with `style: deepObject`: an object value is sent as `name[key]=value` pairs. */
25
+ readonly deepObject?: readonly string[];
26
+ /** Query parameters the API takes as 0 or 1 (`list`, `mkdir`, `recursive`): a boolean is sent as `1` or `0`. */
27
+ readonly flags?: readonly string[];
24
28
  /** Request body kind. */
25
29
  readonly body?: "json" | "bytes" | "yaml";
26
30
  /** Content type of a binary body (`application/octet-stream`, `application/gzip`). */
@@ -29,11 +33,17 @@ export interface Op {
29
33
  readonly edge?: boolean;
30
34
  /** Accepts `Idempotency-Key`; the SDK sends one (generated unless you pass your own), so retries are safe. */
31
35
  readonly idem?: boolean;
36
+ /**
37
+ * `x-b3os-idempotency: caller` (sandboxesExec): no generated key (yours is sent), and the call is resent only
38
+ * after an answer that shows it did no work, never after a node error, an error page (the edge's 503
39
+ * `node_unavailable` included), a timeout or a connection lost after the request was sent.
40
+ */
41
+ readonly callerKey?: boolean;
32
42
  readonly stream?: "sse" | "ws";
33
43
  /** `x-b3os-timeout-ms`. */
34
44
  readonly timeoutMs: number;
35
45
  /** Error body shape when not RFC 9457. */
36
- readonly errorFormat?: "openai" | "oauth2" | "firecrawl";
46
+ readonly errorFormat?: "openai" | "anthropic" | "oauth2" | "firecrawl";
37
47
  /** Job companions (`x-b3os-job-ops`). */
38
48
  readonly job?: JobOps;
39
49
  /** `x-b3os-stage: stretch`: in the contract, may answer `501 not_implemented`. */
@@ -1,6 +1,8 @@
1
1
  // W3C Server-Timing parsing (https://www.w3.org/TR/server-timing/). B3OS sends one metric per phase with `dur` in
2
2
  // milliseconds; `total` is the node's request-head-to-response-head time for bodies of known size, and the edge
3
- // prepends `edge_auth` and `edge_upstream` (ARCHITECTURE §4.1, §6).
3
+ // prepends `edge_auth` and `edge_upstream` (ARCHITECTURE §4.1, §6). A response the edge answers itself names the colo
4
+ // in `edge_colo;desc=...` and, when nothing was measured, says `edge;desc="answered at edge"` with no `total`: metrics
5
+ // without a `dur` are annotations, so they appear in `entries` but never as a phase or in `edge_ms`.
4
6
 
5
7
  export interface ServerTimingEntry {
6
8
  name: string;
@@ -12,7 +14,7 @@ export interface ServerTimingEntry {
12
14
  export interface ServerTiming {
13
15
  /** Every metric in header order. */
14
16
  entries: ServerTimingEntry[];
15
- /** `name → dur` for every metric except `total` (later duplicates are summed). */
17
+ /** `name → dur` for every metric that carries a `dur`, except `total` (later duplicates are summed). */
16
18
  phases: Record<string, number>;
17
19
  /** The `total` metric, or null when the response had none (streams report their totals in the final event). */
18
20
  total_ms: number | null;
@@ -60,6 +62,7 @@ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
60
62
  /** Parses one or more `Server-Timing` header values. Malformed metrics are skipped, never thrown. */
61
63
  export function parseServerTiming(header: string | string[] | null | undefined): ServerTiming {
62
64
  const entries: ServerTimingEntry[] = [];
65
+ const annotations = new Set<ServerTimingEntry>();
63
66
  const values = header == null ? [] : Array.isArray(header) ? header : [header];
64
67
  for (const value of values) {
65
68
  for (const metric of splitOutsideQuotes(value, ",")) {
@@ -81,6 +84,7 @@ export function parseServerTiming(header: string | string[] | null | undefined):
81
84
  entry.desc = raw;
82
85
  }
83
86
  }
87
+ if (!seen.has("dur")) annotations.add(entry);
84
88
  entries.push(entry);
85
89
  }
86
90
  }
@@ -88,6 +92,7 @@ export function parseServerTiming(header: string | string[] | null | undefined):
88
92
  let total: number | null = null;
89
93
  let edge: number | null = null;
90
94
  for (const e of entries) {
95
+ if (annotations.has(e)) continue;
91
96
  if (e.name === "total") {
92
97
  total = e.dur;
93
98
  continue;
@@ -331,7 +331,7 @@ export class NodeHttpTransport implements Transport {
331
331
  /** Over a Unix socket (`{socketPath}`) or to a plain-HTTP base URL (`{baseUrl}`). */
332
332
  constructor(target: { socketPath: string } | { baseUrl: string }) {
333
333
  const http = builtin<typeof NodeHttp>("node:http");
334
- if (!http) throw new Error("@b3os/sdk: this transport needs node:http (Node 20.16+)");
334
+ if (!http) throw new Error("@b3os/sdk: this transport needs node:http (Node 22.3+)");
335
335
  this.http = http;
336
336
  // Pooled sockets idle for 20-25 s are closed by a sweep, before b3osd's 30 s header-read timeout can close one
337
337
  // under a new request. The agent's `timeout` option would do the same, but it costs every request a listener
package/src/core/util.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Small runtime helpers shared by the core. Nothing here imports a Node module statically, so the package loads
2
2
  // unchanged on Node, Bun, Deno, Cloudflare Workers and browsers.
3
3
 
4
- export const SDK_VERSION = "0.1.0";
4
+ export const SDK_VERSION = "0.1.3";
5
5
 
6
6
  interface ProcessLike {
7
7
  env?: Record<string, string | undefined>;
@@ -78,6 +78,42 @@ export function uuid(): string {
78
78
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
79
79
  }
80
80
 
81
+ /** `n` random bytes as lower-case hex, never all zeros (W3C trace context forbids all-zero ids). */
82
+ function randomHex(n: number): string {
83
+ const c = globalThis.crypto as typeof globalThis.crypto | undefined;
84
+ const b = new Uint8Array(n);
85
+ for (;;) {
86
+ if (c && typeof c.getRandomValues === "function") c.getRandomValues(b);
87
+ // Trace ids identify, they do not authorize: Math.random is enough where no CSPRNG exists.
88
+ else for (let i = 0; i < n; i++) b[i] = Math.floor(Math.random() * 256);
89
+ if (b.some((x) => x !== 0)) return Array.from(b, (x: number) => x.toString(16).padStart(2, "0")).join("");
90
+ }
91
+ }
92
+
93
+ /** A W3C trace-id: 32 hex digits. */
94
+ export function newTraceId(): string {
95
+ return randomHex(16);
96
+ }
97
+
98
+ /** A W3C parent-id (span id): 16 hex digits. */
99
+ export function newSpanId(): string {
100
+ return randomHex(8);
101
+ }
102
+
103
+ /** A sampled W3C `traceparent` (version 00) in trace `traceId`, with a new span id. */
104
+ export function traceparentIn(traceId: string): string {
105
+ return `00-${traceId}-${newSpanId()}-01`;
106
+ }
107
+
108
+ /** `traceparent` as W3C Trace Context level 1 defines version 00 (lower-case hex, non-zero ids). */
109
+ export const TRACEPARENT_RE = /^00-(?!0{32})[0-9a-f]{32}-(?!0{16})[0-9a-f]{16}-[0-9a-f]{2}$/;
110
+
111
+ /** The trace-id of a valid version-00 `traceparent`, else undefined. */
112
+ export function traceIdOf(traceparent: string | undefined): string | undefined {
113
+ const t = traceparent?.trim().toLowerCase();
114
+ return t && TRACEPARENT_RE.test(t) ? t.slice(3, 35) : undefined;
115
+ }
116
+
81
117
  /** Resolves after `ms`, or rejects with the signal's reason when it aborts first. */
82
118
  export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
83
119
  return new Promise((resolve, reject) => {
@@ -117,8 +153,11 @@ export function isObject(v: unknown): v is Record<string, unknown> {
117
153
  return typeof v === "object" && v !== null && !Array.isArray(v);
118
154
  }
119
155
 
120
- export const textDecoder = new TextDecoder();
121
- export const textEncoder = new TextEncoder();
156
+ // Typed through the global value, which each project's own lib declares: an inferred type would be written into the
157
+ // .d.ts as @types/node's `import("util").TextDecoder`, which a Workers or browser project without @types/node
158
+ // cannot resolve (dx#8).
159
+ export const textDecoder: InstanceType<typeof TextDecoder> = new TextDecoder();
160
+ export const textEncoder: InstanceType<typeof TextEncoder> = new TextEncoder();
122
161
 
123
162
  export function concatBytes(chunks: Uint8Array[], total?: number): Uint8Array {
124
163
  if (chunks.length === 1 && chunks[0]) return chunks[0];
@@ -136,3 +175,14 @@ export function concatBytes(chunks: Uint8Array[], total?: number): Uint8Array {
136
175
  export function camel(s: string): string {
137
176
  return s.replace(/[-_]([a-z0-9])/g, (_, c: string) => c.toUpperCase());
138
177
  }
178
+
179
+ /** A transport error as one line: its code and the cause's message when they add something. */
180
+ export function describeErr(err: unknown): string {
181
+ if (err instanceof Error) {
182
+ const cause = (err as Error & { cause?: { code?: string; message?: string } }).cause;
183
+ const code = (err as { code?: string }).code ?? cause?.code;
184
+ const msg = cause?.message && cause.message !== err.message ? `${err.message} (${cause.message})` : err.message;
185
+ return code && !msg.includes(code) ? `${code}: ${msg}` : msg;
186
+ }
187
+ return String(err);
188
+ }
package/src/core/ws.ts CHANGED
@@ -94,7 +94,10 @@ export function openSocket(url: string, protocols: string[], signal?: AbortSigna
94
94
  }
95
95
 
96
96
  export interface PtyExit {
97
+ /** The shell's exit code; `null` when it was killed by a signal or when no exit message came. */
97
98
  code: number | null;
99
+ /** True when the server sent the exit message; false when the socket closed without one (a lost connection). */
100
+ exited: boolean;
98
101
  /** WebSocket close code and reason when the socket closed without an exit message. */
99
102
  closeCode?: number;
100
103
  closeReason?: string;
@@ -112,6 +115,7 @@ export class PtySession implements AsyncIterable<Uint8Array> {
112
115
  private iterated = false;
113
116
  private queued = 0;
114
117
  private exitCode: number | null = null;
118
+ private exited = false;
115
119
  private readonly listeners = new Set<(chunk: Uint8Array) => void>();
116
120
  readonly socket: WebSocket;
117
121
 
@@ -126,7 +130,10 @@ export class PtySession implements AsyncIterable<Uint8Array> {
126
130
  if (typeof d === "string") {
127
131
  try {
128
132
  const msg = JSON.parse(d) as { type?: string; code?: number };
129
- if (msg.type === "exit") this.exitCode = typeof msg.code === "number" ? msg.code : null;
133
+ if (msg.type === "exit") {
134
+ this.exited = true;
135
+ this.exitCode = typeof msg.code === "number" ? msg.code : null;
136
+ }
130
137
  } catch {
131
138
  this.push(textEncoder.encode(d));
132
139
  }
@@ -140,9 +147,9 @@ export class PtySession implements AsyncIterable<Uint8Array> {
140
147
  for (const w of this.waiters) w({ value: undefined, done: true });
141
148
  this.waiters = [];
142
149
  settle(
143
- this.exitCode !== null
144
- ? { code: this.exitCode }
145
- : { code: null, closeCode: ev.code, closeReason: ev.reason || undefined },
150
+ this.exited
151
+ ? { code: this.exitCode, exited: true }
152
+ : { code: null, exited: false, closeCode: ev.code, closeReason: ev.reason || undefined },
146
153
  );
147
154
  });
148
155
  }
@@ -24,8 +24,8 @@ import { WebhooksAPI } from "./ns/webhooks.ts";
24
24
  *
25
25
  * ```ts
26
26
  * import { B3OS } from "@b3os/sdk";
27
- * const b3 = new B3OS();
28
- * const page = await b3.vision.scrape({ url: "https://example.com" });
27
+ * const b3os = new B3OS();
28
+ * const page = await b3os.vision.scrape({ url: "https://example.com" });
29
29
  * ```
30
30
  */
31
31
  export class B3OS extends B3OSCore {