@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
package/README.md CHANGED
@@ -1,30 +1,61 @@
1
1
  # @b3os/sdk
2
2
 
3
+ Vision (web pages and browsers), render, infer, sandboxes, routines, actions and vault, next to the GPUs on the B3IQ
4
+ machine that serves open models.
5
+
6
+ Measured 2026-11-01 on the beta node, by a client on the same machine: sandbox claim and first command 1.85 ms p50
7
+ from a warm pool; durable workflow step 195 µs p50. From anywhere else, add your round trip to the node. Current
8
+ numbers and raw data: https://beta.b3os.org/benchmarks
9
+
10
+ <!-- Figures: bench/board/board.json sandboxes.claim_first_exec/gap-100ms+bg/2026-11-01T08:21:48.305Z#claim_exec_ms
11
+ (1.8518 ms) and routines.durable_step/b2b-c1/2026-11-01T08:17:17.333Z#durable_step_us (195.3333 us), medians of run
12
+ medians. Dated on purpose: a published README is frozen at release. -->
13
+
3
14
  TypeScript SDK for B3OS beta: browsers and web extraction (vision), screenshots and videos (render), microVM
4
15
  sandboxes, routines, marketplace actions, the credential vault and inference. One client, one key. Generated from
5
- `packages/spec/dist/openapi.json` (138 operations in 14 namespaces) with a hand-written runtime. ESM and CommonJS,
6
- no runtime dependencies. Targets Node 20.16+ (it needs `process.getBuiltinModule`), Bun, Deno, Cloudflare Workers
7
- and browsers. What has been run so far: the unit and Prism suites on Node 25.8 and 24.22; the live suite against a
8
- dev b3osd on Node 24.22; the benchmark (same calls, Unix socket and TCP) on Node 24.22 and Bun 1.4.4; a Worker run
9
- locally in workerd by Wrangler 4.42.0, with and without `nodejs_compat` (JSON call, typed error, Server-Timing, an
10
- exec event stream, webhook verification); and a unit test that runs a neutral-platform bundle with only web
11
- globals. Deno and browsers have not been run yet. On Workers, a `fetch` option is called unbound: pass a bound
12
- function if yours needs its `this` (a service binding's `env.API.fetch.bind(env.API)`).
16
+ `packages/spec/dist/openapi.json` (138 operations in 14 namespaces) with a hand-written runtime. ESM and CommonJS, no
17
+ runtime dependencies. Targets Node 22.3+ (`process.getBuiltinModule` for the Unix socket and node URL transport, and
18
+ the global `WebSocket` for terminals), Bun, Deno, Cloudflare Workers and browsers. What has been run so far: the unit
19
+ suite on Node 22.3.0, the floor (Node 20.16 has no global `WebSocket`, and 22.0 to 22.2 have no `getBuiltinModule`);
20
+ the unit and Prism suites on Node 25.8 and 24.22; the live suite against a dev b3osd on Node 24.22; the benchmark
21
+ (same calls, Unix socket and TCP) on Node 24.22 and Bun 1.4.4; a Worker run locally in workerd by Wrangler 4.42.0,
22
+ with and without `nodejs_compat` (JSON call, typed error, Server-Timing, an exec event stream, webhook verification);
23
+ and a unit test that runs a neutral-platform bundle with only web globals. Deno and browsers have not been run yet.
24
+ On Workers, a `fetch` option is called unbound: pass a bound function if yours needs its `this` (a service binding's
25
+ `env.API.fetch.bind(env.API)`).
13
26
 
14
27
  ```ts
15
28
  import { B3OS } from "@b3os/sdk";
16
29
 
17
- const b3 = new B3OS(); // B3OS_API_KEY
30
+ const b3os = new B3OS(); // B3OS_API_KEY, or your b3os login (see Credentials)
18
31
 
19
- const page = await b3.vision.scrape({ url: "https://example.com", formats: ["markdown"] });
32
+ const page = await b3os.vision.scrape({ url: "https://example.com", formats: ["markdown"] });
20
33
  console.log(page.markdown);
21
34
 
22
- const sbx = await b3.sandboxes.createSandbox({ template: "base" });
23
- const out = await b3.sandboxes.exec(sbx.id, { cmd: "python3 -c 'print(2 + 2)'" });
35
+ await using sbx = await b3os.sandboxes.create({ template: "base" }); // deleted when the scope ends
36
+ const out = await sbx.exec("python3 -c 'print(2 + 2)'");
24
37
  console.log(out.stdout); // "4\n"
25
- await b3.sandboxes.deleteSandbox(sbx.id);
26
38
  ```
27
39
 
40
+ `b3os.sandboxes.create()` returns a `Sandbox` handle bound to one sandbox (`exec`, `files`, `ports`, `snapshot`,
41
+ `fork`). The same calls also exist by id for code that keeps ids: `createSandbox` sends the same request and returns
42
+ the sandbox object (`SandboxInfo`), then `exec(id, …)` and `deleteSandbox(id)`. Nothing deletes that sandbox for
43
+ you.
44
+
45
+ ## Credentials
46
+
47
+ The client sends the first credential it finds:
48
+
49
+ 1. `apiKey` in the client options (`null` sends none).
50
+ 2. `B3OS_API_KEY`.
51
+ 3. The token `b3os login` stored, read from the file the CLI and the MCP server use: `~/.config/b3os/credentials.json`
52
+ (`$XDG_CONFIG_HOME/b3os/` when that is set, or `B3OS_CREDENTIALS_FILE`). Only on a developer's machine: the SDK
53
+ skips it when `CI` or `GITHUB_ACTIONS` is set and inside a B3OS sandbox. When it uses the token it prints one line
54
+ on stderr, and it sends the token only to the API host it was issued by. Node, Bun and Deno only.
55
+
56
+ So after `b3os login` the example above runs as it is. In CI and in deployed code, set `B3OS_API_KEY` to a key
57
+ made for that job.
58
+
28
59
  ## Where requests go
29
60
 
30
61
  Every operation is either served by the node (products) or by beta-api.b3os.org (keys, usage, limits, orgs,
@@ -34,13 +65,13 @@ projects, the pack registry; `x-b3os-served-by: edge`). The client picks the sho
34
65
  |---|---|---|
35
66
  | Default | `https://beta-api.b3os.org` with `Authorization: Bearer $B3OS_API_KEY` | same |
36
67
  | Inside a B3OS sandbox (`B3OS_API_URL=http://127.0.0.1:7700`) | that URL, no key sent; the sandbox's `api` grant decides | beta-api.b3os.org with the key if one is set |
37
- | On a B3OS node, with `B3OS_SOCKET` set, or with no key and no base URL configured and `/run/b3os/b3osd/b3osd.sock` present | b3osd's Unix socket, no key sent; the node maps your uid to a principal | beta-api.b3os.org with the key |
68
+ | On a B3OS node, with `B3OS_SOCKET` set, or with no key (a stored `b3os login` counts as one) and no base URL configured and `/run/b3os/b3osd/b3osd.sock` present | b3osd's Unix socket, no key sent; the node maps your uid to a principal | beta-api.b3os.org with the key |
38
69
 
39
70
  Options and environment:
40
71
 
41
72
  | Option | Environment | Meaning |
42
73
  |---|---|---|
43
- | `apiKey` | `B3OS_API_KEY` | `b3os_sk_…` key or `b3os_pat_…` CLI token |
74
+ | `apiKey` | `B3OS_API_KEY` | `b3os_sk_…` key or `b3os_pat_…` CLI token; without one, the stored `b3os login` (see Credentials) |
44
75
  | `baseUrl` | `B3OS_BASE_URL` | API host (default `https://beta-api.b3os.org`) |
45
76
  | `nodeUrl` | `B3OS_API_URL` | node-local URL for node operations, sent without the key |
46
77
  | `socketPath` | `B3OS_SOCKET` | b3osd's Unix socket; `false` (or `B3OS_SOCKET=off`) disables it |
@@ -65,26 +96,36 @@ product prefix. Arguments are path parameters in path order, then an object of q
65
96
  the body, then request options:
66
97
 
67
98
  ```ts
68
- await b3.sandboxes.getSandbox("sbx_01m5t68q1b590rj801nbzsqzkk");
69
- await b3.sandboxes.listSandboxes({ status: "running", limit: 50 });
70
- await b3.sandboxes.writeFile(id, { path: "/workspace/main.py", mkdir: 1 }, "print(1)\n");
71
- const bytes = await b3.sandboxes.readFile(id, { path: "/workspace/out.bin" }); // Uint8Array
72
- const listing = await b3.sandboxes.readFile(id, { path: "/workspace", list: 1 }); // JSON listing
73
- const md = await b3.vision.readUrl("https://example.com/pricing", { only_main_content: false }); // string
74
- const png = await b3.render.createScreenshot({ url }, { accept: "image/png" }); // Uint8Array
99
+ await b3os.sandboxes.getSandbox("sbx_01m5t68q1b590rj801nbzsqzkk");
100
+ await b3os.sandboxes.listSandboxes({ status: "running", limit: 50 });
101
+ await b3os.sandboxes.writeFile(id, { path: "/workspace/main.py", mkdir: true }, "print(1)\n");
102
+ const bytes = await b3os.sandboxes.readFile(id, { path: "/workspace/out.bin" }); // Uint8Array
103
+ const listing = await b3os.sandboxes.readFile(id, { path: "/workspace", list: true }); // JSON listing
104
+ const md = await b3os.vision.readUrl("https://example.com/pricing", { only_main_content: false }); // string
105
+ const png = await b3os.render.createScreenshot({ url }, { accept: "image/png" }); // Uint8Array
106
+ const shot = await b3os.render.createScreenshot({ url }); // JSON with signed artifact URLs
107
+ const { bytes, via } = await b3os.render.fetchArtifact(shot.artifacts[0]); // via "node" on the node itself
75
108
  ```
76
109
 
110
+ Artifact URLs are on usercontent.b3os.org. `render.fetchArtifact` reads an artifact through the node's own signed
111
+ route when the client reaches the node (its socket, or `B3OS_API_URL` in a sandbox), so the bytes never leave the
112
+ machine; any other client fetches the URL.
113
+
114
+ The API's 0/1 flags (`list`, `mkdir`, `recursive`) also take `true` and `false`, sent as `1` and `0`.
115
+
77
116
  Request options (last argument of every method): `idempotencyKey`, `timeoutMs`, `maxRetries`, `signal`, `headers`,
78
117
  `traceparent`.
79
118
 
80
- Every type in the spec is exported (`import type { Sandbox, ScrapeRequest } from "@b3os/sdk"`).
119
+ Every type in the spec is exported (`import type { SandboxInfo, ScrapeRequest } from "@b3os/sdk"`). The spec's
120
+ sandbox object is `SandboxInfo` here because `Sandbox` is the handle class (`b3os.sandboxes.create()`, `sbx.info`
121
+ holds the object); `@b3os/sdk/types` keeps the spec's own names, so `Sandbox` there is the object.
81
122
 
82
123
  ## Responses and timing
83
124
 
84
125
  Every call returns an awaitable with `.withResponse()`:
85
126
 
86
127
  ```ts
87
- const { data, response } = await b3.vision.scrape({ url }).withResponse();
128
+ const { data, response } = await b3os.vision.scrape({ url }).withResponse();
88
129
  response.requestId; // req_… (for GET /v1/requests/{id} and support)
89
130
  response.timing; // parsed Server-Timing: { total_ms, edge_ms, phases: { edge_auth, claim, navigate, … }, entries }
90
131
  response.attempts; // 1 + retries
@@ -103,17 +144,24 @@ OpenAI-shaped (infer) and OAuth-shaped (device login) bodies are parsed into the
103
144
 
104
145
  ```ts
105
146
  try {
106
- await b3.sandboxes.exec(id, { cmd: "ls" });
147
+ await b3os.sandboxes.exec(id, { cmd: "ls" });
107
148
  } catch (e) {
108
- if (B3OSError.is(e, "sandbox_not_running")) await b3.sandboxes.resumeSandbox(id);
149
+ if (B3OSError.is(e, "sandbox_not_running")) await b3os.sandboxes.resumeSandbox(id);
109
150
  else throw e;
110
151
  }
111
152
  ```
112
153
 
154
+ `B3OSError.is` completes the codes this SDK knows; any other string still works, and editors mark it deprecated,
155
+ so a misspelled code stands out. Compare `e.code` for a code newer than the SDK.
156
+
113
157
  Client-side failures use codes no server sends: `connection_error` (`B3OSConnectionError`), `timeout`
114
158
  (`B3OSTimeoutError`), `aborted` (`B3OSAbortError`, named `AbortError`), `invalid_response`, `stream_interrupted`,
115
- `unsupported_transport`. A job that ends failed or canceled while you wait for it throws `B3OSJobError` with the
116
- job's own problem and `.job`.
159
+ `unsupported_transport`, `process_exited` (a sandbox process a helper waited on exited first). A job that ends
160
+ failed or canceled while you wait for it throws `B3OSJobError` with the job's own problem and `.job`.
161
+
162
+ With no API key and no `b3os login`, a call to beta-api.b3os.org that needs a key throws `unauthorized` with
163
+ `status` null before any request, as the API would answer 401; its message says how to sign in and where keys are
164
+ made.
117
165
 
118
166
  ## Retries and idempotency
119
167
 
@@ -131,23 +179,35 @@ call reuses it. Retries use equal-jitter exponential backoff (0.5 s doubling, at
131
179
  - never for timeouts (`timeout`, `request_timeout`, `scrape_timeout`, `upstream_timeout`, `job_timed_out`), and never
132
180
  when `Retry-After` exceeds `maxRetryDelayMs`.
133
181
 
182
+ Idempotency keys live 24 hours per project and replay the stored answer only to the same principal
183
+ (`responseOf(r)?.idempotentReplayed`). A key reused with another body is `409 idempotency_key_conflict`; one whose
184
+ first request still runs is `409 idempotency_request_in_progress` (retried after `Retry-After: 1`). When the node's
185
+ store of keys is full, a request with a new key is refused before it runs, never run without dedupe:
186
+ `429 quota_exceeded` when your organization's share is used up, `503 capacity_unavailable` when the node's is (the
187
+ SDK retries the 503 with backoff; the 429 says when to try again in `Retry-After`). Throttled calls carry
188
+ `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` and `RateLimit-Policy`, parsed as
189
+ `info.rateLimit` (`{limit, remaining, reset, policy}`) on any response that has them and readable on a `B3OSError`
190
+ through `e.headers`. `info.rateLimit` is `null` on a response with none of them, such as a call the edge let through
191
+ before it was counted. A body in a content type the operation does not take is `415 unsupported_media_type`: the
192
+ generated methods always send the declared one; `b3os.request()` sends JSON unless you set `bodyType`.
193
+
134
194
  ## Jobs
135
195
 
136
196
  Crawls, batch scrapes, extracts, videos and routine runs are jobs (`x-b3os-job`). A job-creating method returns a
137
197
  `JobPromise`:
138
198
 
139
199
  ```ts
140
- const job = await b3.vision.createCrawl({ url, limit: 50 }); // the job as created (queued or running)
141
- const done = await b3.vision.createCrawl({ url, limit: 50 }).wait(); // the finished job
142
- for await (const ev of b3.vision.createCrawl({ url }).events()) console.log(ev.type); // job.queued … job.succeeded
200
+ const job = await b3os.vision.createCrawl({ url, limit: 50 }); // the job as created (queued or running)
201
+ const done = await b3os.vision.createCrawl({ url, limit: 50 }).wait(); // the finished job
202
+ for await (const ev of b3os.vision.createCrawl({ url }).events()) console.log(ev.type); // job.queued … job.succeeded
143
203
  ```
144
204
 
145
205
  `.wait()` sends the create with `?wait` (up to 60 s), then follows the job's event stream to its terminal event,
146
206
  polling the job if the deployment has no events operation. It resolves with the succeeded job or throws
147
207
  `B3OSJobError` (`{ throwOnFailure: false }` returns the job instead); `timeoutMs`, `signal` and `onEvent` are
148
208
  options. Called right away, `.wait()` and `.events()` shape the creating request itself (one request); called later
149
- they follow up with the job's get and events operations. For any job: `b3.jobs.wait(job)`, `b3.jobs.events(job)`,
150
- `b3.jobs.get(job)`, `b3.jobs.cancel(job)` with the job object or its id. The platform-wide `job_` prefix (extracts)
209
+ they follow up with the job's get and events operations. For any job: `b3os.jobs.wait(job)`, `b3os.jobs.events(job)`,
210
+ `b3os.jobs.get(job)`, `b3os.jobs.cancel(job)` with the job object or its id. The platform-wide `job_` prefix (extracts)
151
211
  is shared by several job kinds, so those take the job object, whose `kind` says which operations serve it; a bare
152
212
  `job_` id is refused.
153
213
 
@@ -158,12 +218,12 @@ Event streams are async iterables. Job and log streams resume after a dropped co
158
218
  drop). A stream that cannot resume (exec output, chat) fails with `stream_interrupted` or `timeout` instead.
159
219
 
160
220
  ```ts
161
- for await (const ev of b3.sandboxes.exec(id, { cmd: "npm test" }, { stream: true })) {
221
+ for await (const ev of b3os.sandboxes.exec(id, { cmd: "npm test" }, { stream: true })) {
162
222
  if (ev.type === "exec.stdout") process.stdout.write(ev.data ?? "");
163
223
  }
164
- const chunks = b3.infer.createChatCompletion({ model, messages, stream: true });
224
+ const chunks = b3os.infer.createChatCompletion({ model, messages, stream: true });
165
225
  for await (const c of chunks) process.stdout.write(c.choices[0]?.delta?.content ?? "");
166
- for await (const ev of b3.routines.runEvents(runId, { lastEventId: "41" })) console.log(ev);
226
+ for await (const ev of b3os.routines.runEvents(runId, { lastEventId: "41" })) console.log(ev);
167
227
  ```
168
228
 
169
229
  `stream.close()` ends a loop quietly; `stream.lastEventId` is where to resume later.
@@ -173,20 +233,90 @@ for await (const ev of b3.routines.runEvents(runId, { lastEventId: "41" })) cons
173
233
  List methods return one page when awaited and walk every item across pages with `for await`:
174
234
 
175
235
  ```ts
176
- for await (const s of b3.sandboxes.listSandboxes({ status: "running" })) console.log(s.id);
177
- for await (const page of b3.vision.listCrawlPages(crawlId).pages()) console.log(page.data.length);
236
+ for await (const s of b3os.sandboxes.listSandboxes({ status: "running" })) console.log(s.id);
237
+ for await (const page of b3os.vision.listCrawlPages(crawlId).pages()) console.log(page.data.length);
238
+ ```
239
+
240
+ ## Readiness and services
241
+
242
+ A sandbox is running when `create` returns; the program you start in it takes longer. `waitUntilReady`
243
+ polls a probe inside the sandbox until it passes, `service` (`startService` by id) starts a background process and
244
+ waits for it:
245
+
246
+ ```ts
247
+ await using sbx = await b3os.sandboxes.create({ template: "base", ports: [{ port: 8000 }] });
248
+ const svc = await sbx.service({
249
+ cmd: "python3 -m http.server 8000",
250
+ ready: { port: 8000 }, // or { http: { port: 8000, path: "/health" } }, { exec: "test -f /tmp/ok" },
251
+ previewPort: 8000, // or { log: /listening/, pid } (a line the process prints)
252
+ });
253
+ console.log(svc.readyMs, svc.url); // client-side time from the start request to the passing probe
254
+ await svc.stop();
255
+ ```
256
+
257
+ There are two waits. `waitUntilReady` (what `ready` uses) runs the probe from this client through `exec`, one
258
+ request per try, and takes ports, HTTP status, commands and log lines. `waitReady` asks the node instead: it runs
259
+ the sandbox's `readiness` probe (a port or a command, set at create or in the call) and answers in one request,
260
+ with `time_to_ready_ms` counted from the create's start.
261
+
262
+ The first probe runs at once, later ones back off from 25 to 250 ms (`intervalMs`, `maxIntervalMs`), `timeoutMs`
263
+ (default 60 s) bounds the wait, and a service whose process exits first fails with `process_exited` at once.
264
+ Probes run with `exec` (bash's `/dev/tcp` for ports, python3 for HTTP), so they work on every route.
265
+
266
+ ## Routines in TypeScript
267
+
268
+ `@b3os/sdk/routines` builds routine definitions with the product steps' `with` typed as their API bodies, and
269
+ checks what it can before the node does (step ids, `needs`, the `uses` grammar, every `${{` closed, scanned as the node scans it, so a literal `}}` in a JSON body or a prompt is fine):
270
+
271
+ ```ts
272
+ import { defineRoutine, expr, output, step } from "@b3os/sdk/routines";
273
+
274
+ const digest = defineRoutine({
275
+ name: "hn-digest",
276
+ inputs: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
277
+ steps: [
278
+ step.vision.scrape("page", { url: expr("inputs.url"), formats: ["markdown"] }),
279
+ step.infer.chat("summary", { model: "b3os/qwen3.5-9b", messages: [{ role: "user", content: output("page", "markdown") }] }),
280
+ step.core.wait("approval", { signal: "approved" }),
281
+ step.action("issue", "io.b3os/github/create-issue@1", { title: output("summary", "choices[0].message.content") }),
282
+ ],
283
+ });
284
+ await b3os.routines.publishRoutine(digest.name, digest);
285
+ ```
286
+
287
+ ## Hosted agent harnesses
288
+
289
+ Provider-hosted agent loops whose tools run in a B3OS sandbox, over outbound connections only. In a sandbox the
290
+ helper creates, credentials become sandbox `secrets` (environment variables B3OS never returns or logs, readable by
291
+ code in the VM), and egress is limited to the provider's API host (plus `baseUrl`'s or `remoteUrl`'s host) unless
292
+ you pass `egressAllow`. An existing sandbox (`sandboxId`) keeps the secrets and egress it was created with, which
293
+ cannot change later: the helper uses the secrets it holds (`secret_names`), refuses one it lacks unless you set
294
+ `execEnvCredentials: true` (the value then goes in the worker's exec `env`, outside the `secrets` guarantee), and
295
+ refuses a sandbox whose egress cannot reach the provider. The workers are the providers' own binaries, which the
296
+ sandbox template has to carry (`command` overrides the path):
297
+
298
+ ```ts
299
+ // Claude Managed Agents, self-hosted environment: one always-on worker (`ant beta:worker poll`)
300
+ const worker = await b3os.sandboxes.startManagedAgentsWorker({ environmentId, environmentKey });
301
+ // ... or one sandbox per session claimed by the Anthropic SDK's WorkPoller (`ant beta:worker run`)
302
+ for await (const work of poller) {
303
+ await b3os.sandboxes.launchManagedAgentsSession({ environmentId, environmentKey, work, snapshot, on_timeout: "pause" });
304
+ }
305
+ // Codex remote environment: `codex exec-server --remote <url> --environment-id <id>`
306
+ const exec = await b3os.sandboxes.startCodexExecServer({ remoteUrl, environmentId, accessToken });
307
+ await worker.close(); // stops the worker and deletes the sandbox it created
178
308
  ```
179
309
 
180
310
  ## Terminals and CDP
181
311
 
182
312
  ```ts
183
- const pty = await b3.sandboxes.openPty(id, { cols: 120, rows: 40 }); // mints a stream ticket, opens the WebSocket
313
+ const pty = await b3os.sandboxes.openPty(id, { cols: 120, rows: 40 }); // mints a stream ticket, opens the WebSocket
184
314
  pty.onData((bytes) => process.stdout.write(bytes));
185
315
  pty.write("ls -la\n");
186
316
  pty.resize(160, 48);
187
- const { code } = await pty.exit;
317
+ const { code, exited } = await pty.exit; // exited: false when the connection closed before the shell exited
188
318
 
189
- const { url } = await b3.vision.connectCdp(sessionId); // wss://…/cdp?ticket=tkt_… (valid 30 s, single use)
319
+ const { url } = await b3os.vision.connectCdp(sessionId); // wss://…/cdp?ticket=tkt_… (valid 30 s, single use)
190
320
  const browser = await chromium.connectOverCDP(url);
191
321
  ```
192
322
 
@@ -216,7 +346,7 @@ const sandboxes = new SandboxesAPI(new B3OSCore({ apiKey }));
216
346
  Every namespace has a subpath (`@b3os/sdk/vision`, `/render`, `/sandboxes`, `/routines`, `/actions`, `/vault`,
217
347
  `/infer`, `/keys`, …); `@b3os/sdk/types` has the types alone. Node built-ins are loaded through
218
348
  `process.getBuiltinModule` only when a Node transport is used, so bundles for Workers and browsers contain no
219
- `node:` imports. For any operation not wrapped here (device login, newer endpoints): `b3.request({ method, path,
349
+ `node:` imports. For any operation not wrapped here (device login, newer endpoints): `b3os.request({ method, path,
220
350
  query, body })`.
221
351
 
222
352
  ## Development
@@ -0,0 +1,30 @@
1
+ import type { ResponseInfo } from "./response.ts";
2
+ import { type TransportResponse } from "./transport.ts";
3
+ /** What opens the request: the client's send, under the stream's own signal. */
4
+ export type ByteStreamOpen = (signal: AbortSignal) => Promise<{
5
+ res: TransportResponse;
6
+ info: ResponseInfo;
7
+ }>;
8
+ /**
9
+ * The bytes of one response, chunk by chunk. The request starts on the first use (`for await`, `response()`,
10
+ * `bytes()`); an error before the first byte is the operation's own `B3OSError`. Iterate once.
11
+ */
12
+ export declare class ByteStream implements AsyncIterable<Uint8Array> {
13
+ private readonly controller;
14
+ private opened;
15
+ private iterating;
16
+ private closed;
17
+ /** True once the whole body arrived. */
18
+ completed: boolean;
19
+ private readonly operationId;
20
+ private readonly open;
21
+ constructor(operationId: string, open: ByteStreamOpen, signal?: AbortSignal);
22
+ private start;
23
+ /** The response head: status, headers and Server-Timing (`ttfa` for speech). Starts the request. */
24
+ response(): Promise<ResponseInfo>;
25
+ /** Stops reading and closes the connection; a loop iterating the stream ends without an error. */
26
+ close(): void;
27
+ /** Reads the whole body into one array. */
28
+ bytes(): Promise<Uint8Array>;
29
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
30
+ }
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ // A response body read as it arrives (R-infer-37): `infer.createSpeech({ ..., stream_format: "audio" })` returns
3
+ // one, so the first audio plays before the last is made.
4
+ //
5
+ // const audio = b3os.infer.createSpeech({ model: "kokoro-82m", voice: "af_heart", input, stream_format: "audio" });
6
+ // for await (const chunk of audio) player.write(chunk);
7
+ // (await audio.response()).timing.phases.ttfa; // ms from the request to the first audio (Server-Timing)
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ByteStream = void 0;
10
+ const errors_ts_1 = require("./errors.js");
11
+ const transport_ts_1 = require("./transport.js");
12
+ const util_ts_1 = require("./util.js");
13
+ /**
14
+ * The bytes of one response, chunk by chunk. The request starts on the first use (`for await`, `response()`,
15
+ * `bytes()`); an error before the first byte is the operation's own `B3OSError`. Iterate once.
16
+ */
17
+ class ByteStream {
18
+ controller = new AbortController();
19
+ opened;
20
+ iterating = false;
21
+ closed = false;
22
+ /** True once the whole body arrived. */
23
+ completed = false;
24
+ operationId;
25
+ open;
26
+ constructor(operationId, open, signal) {
27
+ this.operationId = operationId;
28
+ this.open = open;
29
+ if (signal) {
30
+ if (signal.aborted)
31
+ this.controller.abort(signal.reason);
32
+ else
33
+ signal.addEventListener("abort", () => this.controller.abort(signal.reason), { once: true });
34
+ }
35
+ }
36
+ start() {
37
+ this.opened ??= this.open(this.controller.signal);
38
+ return this.opened;
39
+ }
40
+ /** The response head: status, headers and Server-Timing (`ttfa` for speech). Starts the request. */
41
+ async response() {
42
+ return (await this.start()).info;
43
+ }
44
+ /** Stops reading and closes the connection; a loop iterating the stream ends without an error. */
45
+ close() {
46
+ this.closed = true;
47
+ this.controller.abort(new errors_ts_1.B3OSAbortError({ detail: "The byte stream was closed", operationId: this.operationId }));
48
+ void this.opened?.then(({ res }) => res.cancel()).catch(() => { });
49
+ }
50
+ /** Reads the whole body into one array. */
51
+ async bytes() {
52
+ const parts = [];
53
+ let n = 0;
54
+ for await (const c of this) {
55
+ parts.push(c);
56
+ n += c.length;
57
+ }
58
+ const out = new Uint8Array(n);
59
+ let o = 0;
60
+ for (const p of parts) {
61
+ out.set(p, o);
62
+ o += p.length;
63
+ }
64
+ return out;
65
+ }
66
+ async *[Symbol.asyncIterator]() {
67
+ if (this.iterating)
68
+ throw new Error("@b3os/sdk: a ByteStream can be iterated only once");
69
+ this.iterating = true;
70
+ let res;
71
+ try {
72
+ ({ res } = await this.start());
73
+ }
74
+ catch (e) {
75
+ if (this.closed)
76
+ return;
77
+ throw e;
78
+ }
79
+ try {
80
+ for await (const chunk of res.chunks()) {
81
+ if (this.closed)
82
+ return;
83
+ if (chunk.length)
84
+ yield chunk;
85
+ }
86
+ this.completed = !this.closed;
87
+ }
88
+ catch (e) {
89
+ if (this.closed)
90
+ return;
91
+ if (e instanceof errors_ts_1.B3OSError)
92
+ throw e;
93
+ if (this.controller.signal.aborted) {
94
+ throw new errors_ts_1.B3OSAbortError({ operationId: this.operationId, cause: this.controller.signal.reason });
95
+ }
96
+ if (e instanceof transport_ts_1.TransportTimeout) {
97
+ throw new errors_ts_1.B3OSTimeoutError({
98
+ detail: `${this.operationId}: the body stopped arriving`,
99
+ operationId: this.operationId,
100
+ cause: e,
101
+ });
102
+ }
103
+ throw new errors_ts_1.B3OSConnectionError({
104
+ detail: `The response body of ${this.operationId} broke: ${(0, util_ts_1.describeErr)(e)}`,
105
+ operationId: this.operationId,
106
+ cause: e,
107
+ });
108
+ }
109
+ finally {
110
+ res.cancel();
111
+ }
112
+ }
113
+ }
114
+ exports.ByteStream = ByteStream;
115
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes.js","sourceRoot":"","sources":["../../../src/core/bytes.ts"],"names":[],"mappings":"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"}
@@ -1,15 +1,37 @@
1
+ import { ByteStream } from "./bytes.ts";
1
2
  import type { CallArgs, JobOps, Op } from "./op.ts";
2
3
  import { APIPromise, JobEventStream, type JobEventsOptions, type JobLike, JobPromise, type ListPage, ListPromise, type WaitOptions } from "./promise.ts";
3
4
  import { ResponseInfo } from "./response.ts";
4
5
  import { EventStream, type SSEMessage } from "./sse.ts";
6
+ import { type SpanRecord } from "./traces.ts";
7
+ import { Traces } from "./traces-api.ts";
5
8
  import { type RequestBody, type Transport, type TransportResponse } from "./transport.ts";
6
9
  /** A binary request body (file uploads, pack bundles). */
7
10
  export type BinaryInput = RequestBody;
8
11
  export declare const DEFAULT_BASE_URL = "https://beta-api.b3os.org";
12
+ /** Where API keys are made (the console's API keys page). */
13
+ export declare const KEYS_PAGE = "https://beta.b3os.org/app/keys";
9
14
  /** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
10
15
  export declare const DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
16
+ /** What `GET /v1/ping` answers (requests.yaml `Ping`). */
17
+ export interface Ping {
18
+ object: "ping";
19
+ /** The node that answered (`n1`). */
20
+ node: string;
21
+ /** The node's clock when it answered, RFC 3339 in UTC with milliseconds. */
22
+ ts: string;
23
+ }
24
+ /**
25
+ * `platformPing` from packages/spec/dist (routes.json has no SDK name for it: it belongs to no namespace), so the
26
+ * core carries it; test/ping.test.ts checks it against routes.json.
27
+ */
28
+ export declare const PING_OP: Op;
11
29
  export interface ClientOptions {
12
- /** API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`. */
30
+ /**
31
+ * API key (`b3os_sk_…`) or CLI token (`b3os_pat_…`). Default: `B3OS_API_KEY`, else, on a developer's machine, the
32
+ * token `b3os login` stored (never in CI, on GitHub Actions or in a B3OS sandbox; one stderr line says when it is
33
+ * used). `null` sends no key and skips the stored login.
34
+ */
13
35
  apiKey?: string | null;
14
36
  /** The API host for edge-served operations and remote calls. Default: `B3OS_BASE_URL`, else beta-api.b3os.org. */
15
37
  baseUrl?: string;
@@ -42,16 +64,31 @@ export interface ClientOptions {
42
64
  headers?: Record<string, string>;
43
65
  /** Called after every response head, successful or not. */
44
66
  onResponse?: (info: ResponseInfo) => void;
67
+ /**
68
+ * Called with each span `traces.turn` and `traces.span` time (the turn's root and the harness's steps), so you can
69
+ * send them to an exporter of yours. B3OS's own ingest door is phase 2b.
70
+ */
71
+ onSpan?: (span: SpanRecord) => void;
45
72
  }
46
73
  export interface RequestOptions {
47
- /** `Idempotency-Key` for this call; generated when the operation takes one and you pass none. */
74
+ /**
75
+ * `Idempotency-Key` for this call; generated when the operation takes one and you pass none, except for
76
+ * operations whose effect cannot be repeated (`x-b3os-idempotency: caller`, `sandboxes.exec`): those send only
77
+ * the key you pass.
78
+ */
48
79
  idempotencyKey?: string;
49
80
  timeoutMs?: number;
50
81
  maxRetries?: number;
51
82
  signal?: AbortSignal;
52
83
  headers?: Record<string, string>;
53
- /** W3C trace context, propagated into product calls and routine steps. */
84
+ /**
85
+ * W3C trace context, propagated into product calls and routine steps. Sent as given; without one, a call inside
86
+ * `traces.turn` joins the turn, and any other call gets its own trace (every attempt a new span in it, marked
87
+ * `tracestate: b3os=call`); calls through a resource handle share the handle's.
88
+ */
54
89
  traceparent?: string;
90
+ /** W3C `tracestate` sent with your `traceparent` (only with it). */
91
+ tracestate?: string;
55
92
  }
56
93
  export interface StreamOptions extends RequestOptions {
57
94
  /** Resume after this event id (`seq`). */
@@ -87,16 +124,37 @@ interface Sent {
87
124
  res: TransportResponse;
88
125
  info: ResponseInfo;
89
126
  }
127
+ /**
128
+ * The query string. Arrays repeat their key (`style: form`, `explode: true`); an object is sent as `name[key]=value`
129
+ * pairs when the operation declares the parameter `style: deepObject` (`metadata[team]=infra`), and is refused
130
+ * otherwise rather than sent as "[object Object]". A boolean for one of the operation's 0/1 flags is sent as `1` or
131
+ * `0` (`list: true` is `list=1`); other booleans as `true` or `false`.
132
+ */
133
+ export declare function buildQuery(query: object | undefined, extra?: Record<string, string>, op?: Pick<Op, "id" | "deepObject" | "flags">): string;
90
134
  export declare class B3OSCore {
135
+ #private;
136
+ /**
137
+ * The key this client sends. Readable, but not enumerable: `JSON.stringify`, `console.log` and `util.inspect` of a
138
+ * client show only its last four characters (see `toJSON`).
139
+ */
91
140
  readonly apiKey: string | null;
141
+ /**
142
+ * The sandbox this code runs in (`B3OS_SANDBOX_ID`, set inside every B3OS sandbox with `B3OS_API_URL`), or null.
143
+ * Useful as the id for operations on the sandbox itself: `b3os.sandboxes.createSnapshot(b3os.sandboxId!)`.
144
+ */
145
+ readonly sandboxId: string | null;
92
146
  readonly baseUrl: string;
93
147
  readonly maxRetries: number;
94
148
  readonly maxRetryDelayMs: number;
95
149
  readonly timeoutMs: number | undefined;
150
+ /** @internal Handed each span the turn helper times (ClientOptions.onSpan). */
151
+ readonly _onSpan: ((span: SpanRecord) => void) | undefined;
96
152
  private edge;
97
153
  private node;
98
154
  private readonly headers;
99
155
  private readonly onResponse;
156
+ /** What `JSON.stringify(client)` prints: the settings, with the key redacted. */
157
+ toJSON(): Record<string, unknown>;
100
158
  constructor(options?: ClientOptions);
101
159
  private udsRoute;
102
160
  /** Where node-served and edge-served operations go (`unix:/run/b3os/b3osd/b3osd.sock`, a URL). */
@@ -104,7 +162,21 @@ export declare class B3OSCore {
104
162
  node: string;
105
163
  edge: string;
106
164
  nodeKind: Route["kind"];
165
+ sandboxId: string | null;
107
166
  };
167
+ /**
168
+ * The smallest call the node serves, `GET /v1/ping`: the node's id and clock once the credential is checked,
169
+ * and nothing else. Any valid credential may call it. Its time is the round trip to the node (the "edge round
170
+ * trip" that latency targets are written against); `.withResponse()` gives the Server-Timing phases.
171
+ */
172
+ ping(options?: RequestOptions): APIPromise<Ping>;
173
+ /**
174
+ * Turns and spans (observability.md 3.4): `traces.turn(name, fn)` groups the calls of one turn of your agent into
175
+ * one trace, `traces.span(name, fn)` times a step of its own, `traces.get(traceId)` reads a trace back.
176
+ */
177
+ get traces(): Traces;
178
+ /** The origins this client sends to (its API host and node URL), where a turn's baggage may go. */
179
+ get _origins(): string[];
108
180
  /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
109
181
  close(): void;
110
182
  private headersFor;
@@ -131,6 +203,11 @@ export declare class B3OSCore {
131
203
  doneSentinel?: boolean;
132
204
  extraQuery?: Record<string, string>;
133
205
  }): EventStream<E>;
206
+ /**
207
+ * @internal A response body read as it arrives (speech with `stream_format: "audio"`): the per-attempt timeout
208
+ * covers the response head only, and nothing is retried once bytes have been handed out.
209
+ */
210
+ _postBytes(op: Op, args: CallArgs, options?: RequestOptions, accept?: string): ByteStream;
134
211
  /** @internal A job-creating operation (`x-b3os-job`). */
135
212
  _job<J extends JobLike, E>(op: Op, args: CallArgs, options?: RequestOptions): JobPromise<J, E>;
136
213
  private createStream;