@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/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";
@@ -40,6 +45,16 @@ export {
40
45
  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";
48
+ export {
49
+ currentTurn,
50
+ type SpanOptions,
51
+ type SpanRecord,
52
+ TRACE_MARK_AFTER,
53
+ type TraceHeaders,
54
+ Turn,
55
+ type TurnOptions,
56
+ } from "./traces.ts";
57
+ export { type TraceRecord, Traces } from "./traces-api.ts";
43
58
  export type { HeadersLike } from "./transport.ts";
44
- export { SDK_VERSION } from "./util.ts";
45
- export { type CdpEndpoint, type PtyExit, PtySession } from "./ws.ts";
59
+ export { SDK_VERSION, TRACEPARENT_RE, traceIdOf } from "./util.ts";
60
+ 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;
@@ -0,0 +1,80 @@
1
+ // `b3.traces`: the hand-written turn helpers of observability.md 8.3 (core/traces.ts holds the context and the rules),
2
+ // and the one trace route of phase 2a, `GET /v1/traces/{trace_id}`, which the edge assembles from the request log and
3
+ // usage records.
4
+
5
+ import type { B3OSCore, RequestOptions } from "./client.ts";
6
+ import type { APIPromise } from "./promise.ts";
7
+ import {
8
+ currentTurn,
9
+ runSpan,
10
+ runTurn,
11
+ type SpanOptions,
12
+ type SpanRecord,
13
+ type TraceHeaders,
14
+ type Turn,
15
+ type TurnOptions,
16
+ wrapFetch,
17
+ } from "./traces.ts";
18
+
19
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
20
+
21
+ /** A trace as phase 2a assembles it: its requests, flat, with their usage (platform.yaml `Trace`). */
22
+ export interface TraceRecord {
23
+ object: "trace";
24
+ id: string;
25
+ [k: string]: unknown;
26
+ }
27
+
28
+ export class Traces {
29
+ readonly #client: B3OSCore;
30
+
31
+ constructor(client: B3OSCore) {
32
+ this.#client = client;
33
+ }
34
+
35
+ /**
36
+ * Runs `fn` as one turn: a new trace that every B3OS call inside joins (`tracestate: b3os=turn`), with the turn's
37
+ * conversation, subject and metadata on each call's `baggage`. Resolves with what `fn` returns.
38
+ *
39
+ * ```ts
40
+ * await b3.traces.turn("answer", async (turn) => {
41
+ * const page = await b3.vision.scrape({ url }); // joins the turn
42
+ * const reply = await openai.chat.completions.create(req, { headers: turn.headers({ baggage: true }) });
43
+ * }, { conversation: thread.id, subject: user.id });
44
+ * ```
45
+ */
46
+ turn<R>(name: string, fn: (turn: Turn) => R | Promise<R>, options: TurnOptions = {}): Promise<R> {
47
+ return runTurn(name, fn, options, this.#client._onSpan);
48
+ }
49
+
50
+ /** Times a step of the harness inside the current turn; the calls made inside it name it as their parent. */
51
+ span<R>(name: string, fn: () => R | Promise<R>, options: SpanOptions = {}): Promise<R> {
52
+ return runSpan(name, fn, options);
53
+ }
54
+
55
+ /** The turn the calling code runs in, if any. */
56
+ current(): Turn | undefined {
57
+ return currentTurn();
58
+ }
59
+
60
+ /** The current turn's trace headers for another client, or undefined outside a turn. */
61
+ headers(o: { baggage?: boolean } = {}): TraceHeaders | undefined {
62
+ return currentTurn()?.headers(o);
63
+ }
64
+
65
+ /**
66
+ * A fetch that adds the current turn's trace headers to every request, for a model SDK's `fetch` option. Baggage
67
+ * goes only to B3OS hosts (this client's API host and node URL among them).
68
+ */
69
+ wrapFetch(inner?: FetchLike): FetchLike {
70
+ return wrapFetch(inner, this.#client._origins);
71
+ }
72
+
73
+ /** `GET /v1/traces/{trace_id}`: one trace's requests, in start order, with their usage (7 days). */
74
+ get(traceId: string, options?: RequestOptions): APIPromise<TraceRecord> {
75
+ if (!/^[0-9a-f]{32}$/.test(traceId)) throw new TypeError("@b3os/sdk: traces.get takes a 32-hex trace id");
76
+ return this.#client.request<TraceRecord>({ method: "GET", path: `/v1/traces/${traceId}`, edge: true }, options);
77
+ }
78
+ }
79
+
80
+ export type { SpanOptions, SpanRecord, TraceHeaders, Turn, TurnOptions };
@@ -0,0 +1,375 @@
1
+ // Turns and trace marks (NOTES/deploy-platform/observability.md 3.3, 3.4, 8.3): the SDK's side of "one trace per turn".
2
+ //
3
+ // - `b3.traces.turn(name, fn, { conversation, subject, metadata })` mints a trace id and runs `fn` with it in
4
+ // async-local context (AsyncLocalStorage, where the runtime has it). Every B3OS call inside joins the turn: its
5
+ // `traceparent` names the turn's trace and the current span as parent, and it sends `tracestate: b3os=turn` plus a
6
+ // W3C `baggage` header with the turn's name, conversation, subject and metadata. `turn.headers()` gives the same
7
+ // trace headers for another client (an OpenAI SDK pointed at B3OS); `turn.env()` gives them as `TRACEPARENT` and
8
+ // `TRACESTATE` for a command in another sandbox (a "hands" sandbox the turn hands work to).
9
+ // - Outside a turn each SDK call keeps its own trace, one span per attempt, as before, and now says so:
10
+ // `tracestate: b3os=call`, so the node never takes an SDK-minted per-call trace for a turn. A caller's own
11
+ // `traceparent` (on the call, or on the client's headers, as an MCP server's per-request client has) carries no
12
+ // mark: that trace is the caller's.
13
+ // - `b3.traces.span(name, fn, { kind })` times a step of the harness's own and makes it the parent of the calls made
14
+ // inside it. Phase 2a has no ingest door, so spans are kept on the turn (`turn.spans`) and handed to
15
+ // `ClientOptions.onSpan`; nothing is exported over the network yet.
16
+ // - `b3.traces.wrapFetch(fetch)` adds the turn's trace headers to every request a model SDK sends inside a turn
17
+ // (baggage only to B3OS hosts, so an end user's id never reaches a third party).
18
+ //
19
+ // The node reads the marks from phase 2b on. Until then the request log keeps only the trace id, so a turn's calls
20
+ // are found with `GET /v1/requests?trace_id=<turn.traceId>` or `GET /v1/traces/{trace_id}`. Older SDKs send no mark;
21
+ // the node and the trace view treat their traces as per-call by their User-Agent (`TRACE_MARK_AFTER`).
22
+
23
+ import { builtin, newSpanId, newTraceId, TRACEPARENT_RE } from "./util.ts";
24
+
25
+ /** The `tracestate` list member key B3OS reads (W3C Trace Context: `<key>=<value>`, leftmost is the newest). */
26
+ export const TRACESTATE_KEY = "b3os";
27
+ /**
28
+ * The last SDK versions that send no mark (`b3os-sdk-ts/<v>`, `b3os-sdk-python/<v>`): a request from one of these,
29
+ * or an older one, without `tracestate` is treated as `b3os=call` (observability.md 3.3, tier 1).
30
+ */
31
+ export const TRACE_MARK_AFTER = { ts: "0.1.3", python: "0.1.3" } as const;
32
+
33
+ /** observability.md 2.4 (proposed bounds): a subject of at most 128 characters, 16 metadata keys of 64, values of 512. */
34
+ export const SUBJECT_MAX = 128;
35
+ export const METADATA_KEYS_MAX = 16;
36
+ export const METADATA_KEY_MAX = 64;
37
+ export const METADATA_VALUE_MAX = 512;
38
+ /** Harness spans one turn keeps in memory at most; past it they are counted, not kept. */
39
+ export const TURN_SPANS_MAX = 1000;
40
+
41
+ export type SpanKind = "turn" | "harness" | "tool" | "agent" | "model";
42
+
43
+ /** A span the SDK timed: a turn's root, or a step of the harness (`traces.span`). */
44
+ export interface SpanRecord {
45
+ trace_id: string;
46
+ span_id: string;
47
+ parent_span_id: string | null;
48
+ name: string;
49
+ kind: SpanKind;
50
+ started_at: string;
51
+ duration_ms: number;
52
+ status: "ok" | "error";
53
+ /** The error's message, when `status` is `error`. */
54
+ error?: string;
55
+ attributes: Record<string, string | number | boolean>;
56
+ }
57
+
58
+ export interface TurnOptions {
59
+ /** Groups turns into a task (`gen_ai.conversation.id`): a session or thread id of yours. */
60
+ conversation?: string;
61
+ /** The end user the turn is for: an opaque id, never an email. */
62
+ subject?: string;
63
+ /** Up to 16 keys of yours, filterable later. */
64
+ metadata?: Record<string, string>;
65
+ /** Join this trace (32 hex digits) instead of minting one, e.g. an incoming request's. */
66
+ traceId?: string;
67
+ }
68
+
69
+ export interface SpanOptions {
70
+ kind?: Exclude<SpanKind, "turn">;
71
+ attributes?: Record<string, string | number | boolean>;
72
+ }
73
+
74
+ /** The trace headers of one call (`traceparent`, and `tracestate` and `baggage` when there is a mark or a turn). */
75
+ export type TraceHeaders = { traceparent: string; tracestate?: string; baggage?: string };
76
+
77
+ interface Frame {
78
+ turn: Turn;
79
+ /** The span calls made here name as their parent: the turn's root, or the innermost `traces.span`. */
80
+ spanId: string;
81
+ }
82
+
83
+ interface Store<T> {
84
+ getStore(): T | undefined;
85
+ run<R>(store: T, fn: () => R): R;
86
+ }
87
+
88
+ type AlsCtor = new <T>() => Store<T>;
89
+
90
+ /**
91
+ * The async-local context: Node's AsyncLocalStorage where it exists (Node, Bun, Deno, Workers with nodejs_compat).
92
+ * Elsewhere a stack that holds while `fn` runs synchronously: calls made after an `await` inside a turn then carry no
93
+ * turn, so pass `turn.headers()` yourself there.
94
+ */
95
+ function makeStore(): { store: Store<Frame>; async: boolean } {
96
+ const g = globalThis as { AsyncLocalStorage?: AlsCtor };
97
+ const Als =
98
+ builtin<{ AsyncLocalStorage?: AlsCtor }>("node:async_hooks")?.AsyncLocalStorage ?? g.AsyncLocalStorage ?? null;
99
+ if (Als) return { store: new Als<Frame>(), async: true };
100
+ const stack: Frame[] = [];
101
+ return {
102
+ store: {
103
+ getStore: () => stack.at(-1),
104
+ run: (f, fn) => {
105
+ stack.push(f);
106
+ try {
107
+ return fn();
108
+ } finally {
109
+ stack.pop();
110
+ }
111
+ },
112
+ },
113
+ async: false,
114
+ };
115
+ }
116
+
117
+ const made = makeStore();
118
+ const store = made.store;
119
+
120
+ /** Whether this runtime carries a turn across `await` (AsyncLocalStorage); without it, only synchronous code does. */
121
+ export const asyncContext: boolean = made.async;
122
+
123
+ const TRACE_ID = /^(?!0{32})[0-9a-f]{32}$/;
124
+
125
+ function checkOptions(o: TurnOptions): void {
126
+ if (o.traceId !== undefined && !TRACE_ID.test(o.traceId))
127
+ throw new TypeError("@b3os/sdk: traces.turn: traceId must be 32 lower-case hex digits, not all zero");
128
+ if (o.subject !== undefined && (typeof o.subject !== "string" || o.subject.length > SUBJECT_MAX))
129
+ throw new TypeError(`@b3os/sdk: traces.turn: subject is a string of at most ${SUBJECT_MAX} characters`);
130
+ if (o.conversation !== undefined && (typeof o.conversation !== "string" || o.conversation.length > SUBJECT_MAX))
131
+ throw new TypeError(`@b3os/sdk: traces.turn: conversation is a string of at most ${SUBJECT_MAX} characters`);
132
+ const m = o.metadata ?? {};
133
+ const keys = Object.keys(m);
134
+ if (keys.length > METADATA_KEYS_MAX)
135
+ throw new TypeError(`@b3os/sdk: traces.turn: metadata takes at most ${METADATA_KEYS_MAX} keys`);
136
+ for (const k of keys) {
137
+ if (!/^[A-Za-z0-9_.-]+$/.test(k) || k.length > METADATA_KEY_MAX)
138
+ throw new TypeError(
139
+ `@b3os/sdk: traces.turn: metadata key ${JSON.stringify(k)} must be letters, digits, _ . or -, at most ${METADATA_KEY_MAX}`,
140
+ );
141
+ const v = m[k];
142
+ if (typeof v !== "string" || v.length > METADATA_VALUE_MAX)
143
+ throw new TypeError(
144
+ `@b3os/sdk: traces.turn: metadata ${k} is a string of at most ${METADATA_VALUE_MAX} characters`,
145
+ );
146
+ }
147
+ }
148
+
149
+ /** A W3C baggage value: percent-encoded, so commas, semicolons and spaces survive. */
150
+ const bag = (v: string) => encodeURIComponent(v);
151
+
152
+ /** `tracestate` with `b3os=<mark>` first and any earlier `b3os` member dropped (W3C: one member per key). */
153
+ export function withMark(existing: string | undefined, mark: "turn" | "call"): string {
154
+ const rest = (existing ?? "")
155
+ .split(",")
156
+ .map((x) => x.trim())
157
+ .filter((x) => x && !x.startsWith(`${TRACESTATE_KEY}=`));
158
+ return [`${TRACESTATE_KEY}=${mark}`, ...rest].slice(0, 32).join(",");
159
+ }
160
+
161
+ /** One turn of an agent: a trace id, the turn's root span, and what goes on every call inside it. */
162
+ export class Turn {
163
+ readonly traceId: string;
164
+ /** The turn's root span: the parent of calls made in the turn outside any `traces.span`. */
165
+ readonly spanId: string;
166
+ readonly name: string;
167
+ readonly conversation: string | undefined;
168
+ readonly subject: string | undefined;
169
+ readonly metadata: Readonly<Record<string, string>>;
170
+ /** The turn's root and the harness spans timed in it, in the order they ended (TURN_SPANS_MAX at most). */
171
+ readonly spans: SpanRecord[] = [];
172
+ /** Spans past TURN_SPANS_MAX, counted only. */
173
+ dropped = 0;
174
+ readonly #baggage: string | undefined;
175
+ readonly #onSpan: ((s: SpanRecord) => void) | undefined;
176
+
177
+ constructor(name: string, o: TurnOptions = {}, onSpan?: (s: SpanRecord) => void) {
178
+ if (typeof name !== "string" || !name.trim() || name.length > 128)
179
+ throw new TypeError("@b3os/sdk: traces.turn: name is a string of 1 to 128 characters");
180
+ checkOptions(o);
181
+ this.name = name;
182
+ this.traceId = o.traceId ?? newTraceId();
183
+ this.spanId = newSpanId();
184
+ this.conversation = o.conversation;
185
+ this.subject = o.subject;
186
+ this.metadata = Object.freeze({ ...(o.metadata ?? {}) });
187
+ this.#onSpan = onSpan;
188
+ const members = [`b3os.turn=${bag(name)}`];
189
+ if (o.conversation !== undefined) members.push(`b3os.conversation=${bag(o.conversation)}`);
190
+ if (o.subject !== undefined) members.push(`b3os.subject=${bag(o.subject)}`);
191
+ for (const [k, v] of Object.entries(this.metadata)) members.push(`b3os.meta.${k}=${bag(v)}`);
192
+ this.#baggage = members.join(",");
193
+ }
194
+
195
+ /** `traceparent` for a call made now: this turn's trace, the current span (or the turn's root) as parent. */
196
+ traceparent(parent = currentSpanIn(this) ?? this.spanId): string {
197
+ return `00-${this.traceId}-${parent}-01`;
198
+ }
199
+
200
+ /**
201
+ * The headers that join another client's requests to this turn: `traceparent` and `tracestate: b3os=turn`, plus,
202
+ * with `{ baggage: true }`, the `baggage` header with the turn's name, conversation, subject and metadata. Send the
203
+ * baggage only to B3OS (it holds your end user's id).
204
+ */
205
+ headers(o: { baggage?: boolean } = {}): TraceHeaders {
206
+ const h: TraceHeaders = { traceparent: this.traceparent(), tracestate: withMark(undefined, "turn") };
207
+ if (o.baggage && this.#baggage) h.baggage = this.#baggage;
208
+ return h;
209
+ }
210
+
211
+ /** The baggage header B3OS calls in this turn carry. */
212
+ get baggage(): string | undefined {
213
+ return this.#baggage;
214
+ }
215
+
216
+ /**
217
+ * The same headers as environment variables for a command in another sandbox (`TRACEPARENT`, `TRACESTATE`), the
218
+ * convention B3OS's SDKs read when they start: pass them as `env` to `sandboxes.exec`, so the hands sandbox's
219
+ * calls join the turn the head runs.
220
+ */
221
+ env(): { TRACEPARENT: string; TRACESTATE: string } {
222
+ return { TRACEPARENT: this.traceparent(), TRACESTATE: withMark(undefined, "turn") };
223
+ }
224
+
225
+ /** @internal */
226
+ _record(s: SpanRecord): void {
227
+ if (this.spans.length < TURN_SPANS_MAX) this.spans.push(s);
228
+ else this.dropped++;
229
+ try {
230
+ this.#onSpan?.(s);
231
+ } catch {
232
+ // A hook must never break the turn.
233
+ }
234
+ }
235
+ }
236
+
237
+ function currentSpanIn(turn: Turn): string | undefined {
238
+ const f = store.getStore();
239
+ return f && f.turn === turn ? f.spanId : undefined;
240
+ }
241
+
242
+ /** The turn the calling code runs in, if any. */
243
+ export function currentTurn(): Turn | undefined {
244
+ return store.getStore()?.turn;
245
+ }
246
+
247
+ /**
248
+ * The trace headers of one attempt of an SDK call, by the rules above. `own`: the call's own `traceparent`
249
+ * (RequestOptions), `client`: the client's default `traceparent` and `tracestate` headers, `traceId`: the call's
250
+ * per-call trace when it has no other.
251
+ */
252
+ export function callTraceHeaders(
253
+ own: string | undefined,
254
+ ownState: string | undefined,
255
+ client: { traceparent?: string; tracestate?: string },
256
+ traceId: string,
257
+ ): TraceHeaders {
258
+ if (own) return ownState ? { traceparent: own, tracestate: ownState } : { traceparent: own };
259
+ if (client.traceparent && TRACEPARENT_RE.test(client.traceparent.trim().toLowerCase())) {
260
+ const h: TraceHeaders = { traceparent: `00-${traceId}-${newSpanId()}-01` };
261
+ if (client.tracestate) h.tracestate = client.tracestate;
262
+ return h;
263
+ }
264
+ const f = store.getStore();
265
+ if (f) {
266
+ const h: TraceHeaders = {
267
+ traceparent: `00-${f.turn.traceId}-${f.spanId}-01`,
268
+ tracestate: withMark(client.tracestate, "turn"),
269
+ };
270
+ if (f.turn.baggage) h.baggage = f.turn.baggage;
271
+ return h;
272
+ }
273
+ return { traceparent: `00-${traceId}-${newSpanId()}-01`, tracestate: withMark(client.tracestate, "call") };
274
+ }
275
+
276
+ async function timed<R>(
277
+ turn: Turn,
278
+ span: { id: string; parent: string | null; name: string; kind: SpanKind; attributes: SpanRecord["attributes"] },
279
+ fn: () => R | Promise<R>,
280
+ ): Promise<R> {
281
+ const t0 = performance.now();
282
+ const startedAt = new Date().toISOString();
283
+ const end = (status: SpanRecord["status"], error?: unknown) =>
284
+ turn._record({
285
+ trace_id: turn.traceId,
286
+ span_id: span.id,
287
+ parent_span_id: span.parent,
288
+ name: span.name,
289
+ kind: span.kind,
290
+ started_at: startedAt,
291
+ duration_ms: Math.round((performance.now() - t0) * 1000) / 1000,
292
+ status,
293
+ ...(error !== undefined ? { error: error instanceof Error ? error.message : String(error) } : {}),
294
+ attributes: span.attributes,
295
+ });
296
+ try {
297
+ const out = await store.run({ turn, spanId: span.id }, fn);
298
+ end("ok");
299
+ return out;
300
+ } catch (e) {
301
+ end("error", e);
302
+ throw e;
303
+ }
304
+ }
305
+
306
+ /** Runs `fn` as one turn (see the module comment). Nested turns are separate traces. */
307
+ export function runTurn<R>(
308
+ name: string,
309
+ fn: (turn: Turn) => R | Promise<R>,
310
+ o: TurnOptions = {},
311
+ onSpan?: (s: SpanRecord) => void,
312
+ ): Promise<R> {
313
+ let turn: Turn;
314
+ try {
315
+ turn = new Turn(name, o, onSpan);
316
+ } catch (e) {
317
+ return Promise.reject(e);
318
+ }
319
+ const attributes: SpanRecord["attributes"] = {};
320
+ if (turn.conversation !== undefined) attributes["gen_ai.conversation.id"] = turn.conversation;
321
+ if (turn.subject !== undefined) attributes["user.id"] = turn.subject;
322
+ for (const [k, v] of Object.entries(turn.metadata)) attributes[`metadata.${k}`] = v;
323
+ return timed(turn, { id: turn.spanId, parent: null, name, kind: "turn", attributes }, () => fn(turn));
324
+ }
325
+
326
+ /** Times `fn` as a span of the current turn, the parent of the calls made inside it; outside a turn it only runs fn. */
327
+ export async function runSpan<R>(name: string, fn: () => R | Promise<R>, o: SpanOptions = {}): Promise<R> {
328
+ const f = store.getStore();
329
+ if (!f) return fn();
330
+ return timed(
331
+ f.turn,
332
+ { id: newSpanId(), parent: f.spanId, name, kind: o.kind ?? "harness", attributes: { ...(o.attributes ?? {}) } },
333
+ fn,
334
+ );
335
+ }
336
+
337
+ /** Hosts a turn's baggage may go to: B3OS's own (the API host, the dashboard, a node, a sandbox's loopback). */
338
+ export function isB3osUrl(url: string, extra: readonly string[] = []): boolean {
339
+ let u: URL;
340
+ try {
341
+ u = new URL(url);
342
+ } catch {
343
+ return false;
344
+ }
345
+ const origin = u.origin;
346
+ if (extra.some((e) => e && origin === new URL(e).origin)) return true;
347
+ const h = u.hostname;
348
+ return (
349
+ h === "b3os.org" || h.endsWith(".b3os.org") || (u.protocol === "http:" && h === "127.0.0.1" && u.port === "7700")
350
+ );
351
+ }
352
+
353
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
354
+
355
+ /**
356
+ * A fetch that adds the current turn's trace headers to every request it sends (and nothing outside a turn), for a
357
+ * model SDK's `fetch` option: `new OpenAI({ fetch: b3.traces.wrapFetch() })`. Headers the request already has win.
358
+ * Baggage goes only to B3OS hosts. Model spans for provider hosts are phase 2b.
359
+ */
360
+ export function wrapFetch(inner: FetchLike = globalThis.fetch.bind(globalThis), b3osOrigins: string[] = []): FetchLike {
361
+ return (input, init) => {
362
+ const f = store.getStore();
363
+ if (!f) return inner(input, init);
364
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
365
+ const base = input instanceof Request ? input.headers : undefined;
366
+ const headers = new Headers(init?.headers ?? base);
367
+ if (!headers.has("traceparent")) {
368
+ headers.set("traceparent", f.turn.traceparent(f.spanId));
369
+ headers.set("tracestate", withMark(headers.get("tracestate") ?? undefined, "turn"));
370
+ }
371
+ if (!headers.has("baggage") && f.turn.baggage && isB3osUrl(url, b3osOrigins))
372
+ headers.set("baggage", f.turn.baggage);
373
+ return inner(input, { ...init, headers });
374
+ };
375
+ }