@b3os/sdk 0.1.3 → 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 (80) hide show
  1. package/README.md +4 -3
  2. package/dist/cjs/core/client.d.ts +21 -2
  3. package/dist/cjs/core/client.js +26 -1
  4. package/dist/cjs/core/client.js.map +1 -1
  5. package/dist/cjs/core/handle.d.ts +5 -0
  6. package/dist/cjs/core/handle.js +13 -2
  7. package/dist/cjs/core/handle.js.map +1 -1
  8. package/dist/cjs/core/index.d.ts +2 -0
  9. package/dist/cjs/core/index.js +7 -1
  10. package/dist/cjs/core/index.js.map +1 -1
  11. package/dist/cjs/core/traces-api.d.ts +42 -0
  12. package/dist/cjs/core/traces-api.js +54 -0
  13. package/dist/cjs/core/traces-api.js.map +1 -0
  14. package/dist/cjs/core/traces.d.ts +120 -0
  15. package/dist/cjs/core/traces.js +306 -0
  16. package/dist/cjs/core/traces.js.map +1 -0
  17. package/dist/cjs/core/util.d.ts +1 -1
  18. package/dist/cjs/core/util.js +1 -1
  19. package/dist/cjs/generated/errors.d.ts +1 -1
  20. package/dist/cjs/generated/errors.js +12 -0
  21. package/dist/cjs/generated/errors.js.map +1 -1
  22. package/dist/cjs/generated/ids.d.ts +12 -0
  23. package/dist/cjs/generated/ids.js +3 -0
  24. package/dist/cjs/generated/ids.js.map +1 -1
  25. package/dist/cjs/generated/ns/keys.d.ts +2 -1
  26. package/dist/cjs/generated/ns/keys.js +2 -1
  27. package/dist/cjs/generated/ns/keys.js.map +1 -1
  28. package/dist/cjs/generated/ns/render.d.ts +22 -2
  29. package/dist/cjs/generated/ns/render.js +13 -2
  30. package/dist/cjs/generated/ns/render.js.map +1 -1
  31. package/dist/cjs/generated/ns/sandboxes.d.ts +29 -0
  32. package/dist/cjs/generated/ns/sandboxes.js +49 -0
  33. package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
  34. package/dist/cjs/generated/types.d.ts +820 -53
  35. package/dist/esm/core/client.d.ts +21 -2
  36. package/dist/esm/core/client.js +27 -2
  37. package/dist/esm/core/client.js.map +1 -1
  38. package/dist/esm/core/handle.d.ts +5 -0
  39. package/dist/esm/core/handle.js +13 -2
  40. package/dist/esm/core/handle.js.map +1 -1
  41. package/dist/esm/core/index.d.ts +2 -0
  42. package/dist/esm/core/index.js +2 -0
  43. package/dist/esm/core/index.js.map +1 -1
  44. package/dist/esm/core/traces-api.d.ts +42 -0
  45. package/dist/esm/core/traces-api.js +50 -0
  46. package/dist/esm/core/traces-api.js.map +1 -0
  47. package/dist/esm/core/traces.d.ts +120 -0
  48. package/dist/esm/core/traces.js +295 -0
  49. package/dist/esm/core/traces.js.map +1 -0
  50. package/dist/esm/core/util.d.ts +1 -1
  51. package/dist/esm/core/util.js +1 -1
  52. package/dist/esm/generated/errors.d.ts +1 -1
  53. package/dist/esm/generated/errors.js +12 -0
  54. package/dist/esm/generated/errors.js.map +1 -1
  55. package/dist/esm/generated/ids.d.ts +12 -0
  56. package/dist/esm/generated/ids.js +3 -0
  57. package/dist/esm/generated/ids.js.map +1 -1
  58. package/dist/esm/generated/ns/keys.d.ts +2 -1
  59. package/dist/esm/generated/ns/keys.js +2 -1
  60. package/dist/esm/generated/ns/keys.js.map +1 -1
  61. package/dist/esm/generated/ns/render.d.ts +22 -2
  62. package/dist/esm/generated/ns/render.js +13 -2
  63. package/dist/esm/generated/ns/render.js.map +1 -1
  64. package/dist/esm/generated/ns/sandboxes.d.ts +29 -0
  65. package/dist/esm/generated/ns/sandboxes.js +49 -0
  66. package/dist/esm/generated/ns/sandboxes.js.map +1 -1
  67. package/dist/esm/generated/types.d.ts +820 -53
  68. package/package.json +1 -1
  69. package/src/core/client.ts +36 -4
  70. package/src/core/handle.ts +12 -2
  71. package/src/core/index.ts +10 -0
  72. package/src/core/traces-api.ts +80 -0
  73. package/src/core/traces.ts +375 -0
  74. package/src/core/util.ts +1 -1
  75. package/src/generated/errors.ts +24 -0
  76. package/src/generated/ids.ts +3 -0
  77. package/src/generated/ns/keys.ts +2 -1
  78. package/src/generated/ns/render.ts +22 -2
  79. package/src/generated/ns/sandboxes.ts +59 -0
  80. package/src/generated/types.ts +825 -52
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@b3os/sdk",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript SDK for B3OS beta: vision (web pages and browsers), render, infer, sandboxes, routines, actions and vault, on the machine that runs the model.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -30,6 +30,8 @@ import {
30
30
  } from "./promise.ts";
31
31
  import { ResponseInfo, remember } from "./response.ts";
32
32
  import { EventStream, type EventStreamOptions, type SSEMessage } from "./sse.ts";
33
+ import { callTraceHeaders, type SpanRecord } from "./traces.ts";
34
+ import { Traces } from "./traces-api.ts";
33
35
  import {
34
36
  FetchTransport,
35
37
  NodeHttpTransport,
@@ -51,7 +53,6 @@ import {
51
53
  SDK_VERSION,
52
54
  sleep,
53
55
  traceIdOf,
54
- traceparentIn,
55
56
  uuid,
56
57
  } from "./util.ts";
57
58
 
@@ -123,6 +124,11 @@ export interface ClientOptions {
123
124
  headers?: Record<string, string>;
124
125
  /** Called after every response head, successful or not. */
125
126
  onResponse?: (info: ResponseInfo) => void;
127
+ /**
128
+ * Called with each span `traces.turn` and `traces.span` time (the turn's root and the harness's steps), so you can
129
+ * send them to an exporter of yours. B3OS's own ingest door is phase 2b.
130
+ */
131
+ onSpan?: (span: SpanRecord) => void;
126
132
  }
127
133
 
128
134
  export interface RequestOptions {
@@ -137,10 +143,13 @@ export interface RequestOptions {
137
143
  signal?: AbortSignal;
138
144
  headers?: Record<string, string>;
139
145
  /**
140
- * W3C trace context, propagated into product calls and routine steps. Sent as given; without one, each call
141
- * gets its own trace (every attempt a new span in it), and calls through a resource handle share the handle's.
146
+ * W3C trace context, propagated into product calls and routine steps. Sent as given; without one, a call inside
147
+ * `traces.turn` joins the turn, and any other call gets its own trace (every attempt a new span in it, marked
148
+ * `tracestate: b3os=call`); calls through a resource handle share the handle's.
142
149
  */
143
150
  traceparent?: string;
151
+ /** W3C `tracestate` sent with your `traceparent` (only with it). */
152
+ tracestate?: string;
144
153
  }
145
154
 
146
155
  export interface StreamOptions extends RequestOptions {
@@ -405,6 +414,9 @@ export class B3OSCore {
405
414
  readonly maxRetries: number;
406
415
  readonly maxRetryDelayMs: number;
407
416
  readonly timeoutMs: number | undefined;
417
+ /** @internal Handed each span the turn helper times (ClientOptions.onSpan). */
418
+ readonly _onSpan: ((span: SpanRecord) => void) | undefined;
419
+ #traces: Traces | undefined;
408
420
  private edge: Route;
409
421
  private node: Route;
410
422
  private readonly headers: Record<string, string>;
@@ -475,6 +487,7 @@ export class B3OSCore {
475
487
  this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
476
488
  this.timeoutMs = options.timeoutMs;
477
489
  this.onResponse = options.onResponse;
490
+ this._onSpan = options.onSpan;
478
491
  const headers: Record<string, string> = {};
479
492
  const rt = runtime();
480
493
  if (rt === "node" || rt === "bun" || rt === "deno" || rt === "workerd") {
@@ -567,6 +580,20 @@ export class B3OSCore {
567
580
  return this._call<Ping>(PING_OP, {}, options);
568
581
  }
569
582
 
583
+ /**
584
+ * Turns and spans (observability.md 3.4): `traces.turn(name, fn)` groups the calls of one turn of your agent into
585
+ * one trace, `traces.span(name, fn)` times a step of its own, `traces.get(traceId)` reads a trace back.
586
+ */
587
+ get traces(): Traces {
588
+ this.#traces ??= new Traces(this);
589
+ return this.#traces;
590
+ }
591
+
592
+ /** The origins this client sends to (its API host and node URL), where a turn's baggage may go. */
593
+ get _origins(): string[] {
594
+ return [this.baseUrl, this.node.kind === "node-http" ? this.node.base : ""].filter(Boolean);
595
+ }
596
+
570
597
  /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
571
598
  close(): void {
572
599
  this.node.transport.close?.();
@@ -579,7 +606,12 @@ export class B3OSCore {
579
606
  private headersFor(route: Route, op: Op, o: RequestOptions, accept: string, traceId: string): Record<string, string> {
580
607
  const h: Record<string, string> = { ...this.headers, accept };
581
608
  if (route.auth && this.apiKey) h.authorization = `Bearer ${this.apiKey}`;
582
- h.traceparent = o.traceparent ?? traceparentIn(traceId);
609
+ // The call's own traceparent, else the client's, else the current turn's, else a per-call trace marked
610
+ // b3os=call (core/traces.ts).
611
+ const t = callTraceHeaders(o.traceparent, o.tracestate, this.headers, traceId);
612
+ h.traceparent = t.traceparent;
613
+ if (t.tracestate) h.tracestate = t.tracestate;
614
+ if (t.baggage) h.baggage = h.baggage ? `${t.baggage},${h.baggage}` : t.baggage;
583
615
  if (o.headers) for (const [k, v] of Object.entries(o.headers)) h[k.toLowerCase()] = v;
584
616
  void op;
585
617
  return h;
@@ -12,6 +12,7 @@
12
12
  // so a chain of calls across products shows up as one trace in the request log.
13
13
 
14
14
  import type { RequestOptions } from "./client.ts";
15
+ import { currentTurn, withMark } from "./traces.ts";
15
16
  import { newTraceId, traceparentIn } from "./util.ts";
16
17
 
17
18
  export interface HandleOptions {
@@ -35,12 +36,19 @@ function attach(bodyError: unknown, disposeError: unknown): void {
35
36
  export abstract class Handle {
36
37
  /** The trace every call through this handle joins, and the handles it creates. */
37
38
  readonly traceId: string;
39
+ /**
40
+ * How its calls are marked (observability.md 3.4): `turn` when it was made inside a turn (it joins that turn),
41
+ * `call` when the SDK minted its trace, none when the trace is the caller's (`traceId` given).
42
+ */
43
+ readonly traceMark: "turn" | "call" | null;
38
44
  /** The error the dispose ended with, once it failed. */
39
45
  disposeError: unknown = undefined;
40
46
  #disposal: Promise<void> | undefined;
41
47
 
42
48
  protected constructor(options: HandleOptions = {}) {
43
- this.traceId = options.parent?.traceId ?? options.traceId ?? newTraceId();
49
+ const turn = currentTurn();
50
+ this.traceId = options.parent?.traceId ?? options.traceId ?? turn?.traceId ?? newTraceId();
51
+ this.traceMark = options.parent ? options.parent.traceMark : options.traceId ? null : turn ? "turn" : "call";
44
52
  }
45
53
 
46
54
  /** Releases the resource (delete the sandbox, close the session). Called at most once per handle. */
@@ -92,6 +100,8 @@ export abstract class Handle {
92
100
 
93
101
  /** Options for one call through this handle: a new span in the handle's trace, unless `o` names a traceparent. */
94
102
  protected callOptions<O extends RequestOptions>(o?: O): O {
95
- return { ...o, traceparent: o?.traceparent ?? traceparentIn(this.traceId) } as O;
103
+ if (o?.traceparent) return { ...o };
104
+ const mark = this.traceMark ? { tracestate: withMark(undefined, this.traceMark) } : {};
105
+ return { ...o, traceparent: traceparentIn(this.traceId), ...mark } as O;
96
106
  }
97
107
  }
package/src/core/index.ts CHANGED
@@ -45,6 +45,16 @@ export {
45
45
  export { type RateLimitInfo, ResponseInfo, responseOf } from "./response.ts";
46
46
  export { EventStream, type EventStreamOptions, SSEDecoder, type SSEMessage } from "./sse.ts";
47
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";
48
58
  export type { HeadersLike } from "./transport.ts";
49
59
  export { SDK_VERSION, TRACEPARENT_RE, traceIdOf } from "./util.ts";
50
60
  export { type CdpEndpoint, type PtyExit, PtySession, type TicketedUrl } from "./ws.ts";
@@ -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
+ }
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.3";
4
+ export const SDK_VERSION = "0.2.0";
5
5
 
6
6
  interface ProcessLike {
7
7
  env?: Record<string, string | undefined>;