@b3os/sdk 0.1.3 → 0.2.1
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.
- package/README.md +4 -3
- package/dist/cjs/core/client.d.ts +21 -2
- package/dist/cjs/core/client.js +26 -1
- package/dist/cjs/core/client.js.map +1 -1
- package/dist/cjs/core/handle.d.ts +5 -0
- package/dist/cjs/core/handle.js +13 -2
- package/dist/cjs/core/handle.js.map +1 -1
- package/dist/cjs/core/index.d.ts +2 -0
- package/dist/cjs/core/index.js +7 -1
- package/dist/cjs/core/index.js.map +1 -1
- package/dist/cjs/core/sse.d.ts +2 -0
- package/dist/cjs/core/sse.js +17 -5
- package/dist/cjs/core/sse.js.map +1 -1
- package/dist/cjs/core/traces-api.d.ts +42 -0
- package/dist/cjs/core/traces-api.js +54 -0
- package/dist/cjs/core/traces-api.js.map +1 -0
- package/dist/cjs/core/traces.d.ts +120 -0
- package/dist/cjs/core/traces.js +306 -0
- package/dist/cjs/core/traces.js.map +1 -0
- package/dist/cjs/core/util.d.ts +1 -1
- package/dist/cjs/core/util.js +1 -1
- package/dist/cjs/generated/errors.d.ts +1 -1
- package/dist/cjs/generated/errors.js +32 -0
- package/dist/cjs/generated/errors.js.map +1 -1
- package/dist/cjs/generated/ids.d.ts +12 -0
- package/dist/cjs/generated/ids.js +3 -0
- package/dist/cjs/generated/ids.js.map +1 -1
- package/dist/cjs/generated/ns/actions.d.ts +66 -1
- package/dist/cjs/generated/ns/actions.js +101 -1
- package/dist/cjs/generated/ns/actions.js.map +1 -1
- package/dist/cjs/generated/ns/keys.d.ts +2 -1
- package/dist/cjs/generated/ns/keys.js +2 -1
- package/dist/cjs/generated/ns/keys.js.map +1 -1
- package/dist/cjs/generated/ns/render.d.ts +22 -2
- package/dist/cjs/generated/ns/render.js +13 -2
- package/dist/cjs/generated/ns/render.js.map +1 -1
- package/dist/cjs/generated/ns/sandboxes.d.ts +29 -0
- package/dist/cjs/generated/ns/sandboxes.js +49 -0
- package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
- package/dist/cjs/generated/types.d.ts +1038 -65
- package/dist/cjs/helpers/sandboxes.d.ts +26 -2
- package/dist/cjs/helpers/sandboxes.js +114 -13
- package/dist/cjs/helpers/sandboxes.js.map +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/core/client.d.ts +21 -2
- package/dist/esm/core/client.js +27 -2
- package/dist/esm/core/client.js.map +1 -1
- package/dist/esm/core/handle.d.ts +5 -0
- package/dist/esm/core/handle.js +13 -2
- package/dist/esm/core/handle.js.map +1 -1
- package/dist/esm/core/index.d.ts +2 -0
- package/dist/esm/core/index.js +2 -0
- package/dist/esm/core/index.js.map +1 -1
- package/dist/esm/core/sse.d.ts +2 -0
- package/dist/esm/core/sse.js +17 -5
- package/dist/esm/core/sse.js.map +1 -1
- package/dist/esm/core/traces-api.d.ts +42 -0
- package/dist/esm/core/traces-api.js +50 -0
- package/dist/esm/core/traces-api.js.map +1 -0
- package/dist/esm/core/traces.d.ts +120 -0
- package/dist/esm/core/traces.js +295 -0
- package/dist/esm/core/traces.js.map +1 -0
- package/dist/esm/core/util.d.ts +1 -1
- package/dist/esm/core/util.js +1 -1
- package/dist/esm/generated/errors.d.ts +1 -1
- package/dist/esm/generated/errors.js +32 -0
- package/dist/esm/generated/errors.js.map +1 -1
- package/dist/esm/generated/ids.d.ts +12 -0
- package/dist/esm/generated/ids.js +3 -0
- package/dist/esm/generated/ids.js.map +1 -1
- package/dist/esm/generated/ns/actions.d.ts +66 -1
- package/dist/esm/generated/ns/actions.js +101 -1
- package/dist/esm/generated/ns/actions.js.map +1 -1
- package/dist/esm/generated/ns/keys.d.ts +2 -1
- package/dist/esm/generated/ns/keys.js +2 -1
- package/dist/esm/generated/ns/keys.js.map +1 -1
- package/dist/esm/generated/ns/render.d.ts +22 -2
- package/dist/esm/generated/ns/render.js +13 -2
- package/dist/esm/generated/ns/render.js.map +1 -1
- package/dist/esm/generated/ns/sandboxes.d.ts +29 -0
- package/dist/esm/generated/ns/sandboxes.js +49 -0
- package/dist/esm/generated/ns/sandboxes.js.map +1 -1
- package/dist/esm/generated/types.d.ts +1038 -65
- package/dist/esm/helpers/sandboxes.d.ts +26 -2
- package/dist/esm/helpers/sandboxes.js +113 -12
- package/dist/esm/helpers/sandboxes.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/client.ts +36 -4
- package/src/core/handle.ts +12 -2
- package/src/core/index.ts +10 -0
- package/src/core/sse.ts +17 -5
- package/src/core/traces-api.ts +80 -0
- package/src/core/traces.ts +375 -0
- package/src/core/util.ts +1 -1
- package/src/generated/errors.ts +64 -0
- package/src/generated/ids.ts +3 -0
- package/src/generated/ns/actions.ts +110 -1
- package/src/generated/ns/keys.ts +2 -1
- package/src/generated/ns/render.ts +22 -2
- package/src/generated/ns/sandboxes.ts +59 -0
- package/src/generated/types.ts +1057 -63
- package/src/helpers/sandboxes.ts +136 -12
- package/src/index.ts +1 -0
|
@@ -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
|
|
4
|
+
export const SDK_VERSION = "0.2.1";
|
|
5
5
|
|
|
6
6
|
interface ProcessLike {
|
|
7
7
|
env?: Record<string, string | undefined>;
|
package/src/generated/errors.ts
CHANGED
|
@@ -12,6 +12,7 @@ export const ERROR_CATALOG: Readonly<Record<string, readonly [status: number, re
|
|
|
12
12
|
payload_too_large: [413, 0, "Payload too large"],
|
|
13
13
|
route_not_found: [404, 0, "Route not found"],
|
|
14
14
|
feature_not_enabled: [404, 0, "Feature not enabled"],
|
|
15
|
+
flags_unavailable: [503, 1, "Feature flags unavailable"],
|
|
15
16
|
method_not_allowed: [405, 0, "Method not allowed"],
|
|
16
17
|
edge_only: [421, 0, "Served by beta-api.b3os.org"],
|
|
17
18
|
limit_exceeded: [422, 0, "Limit exceeded"],
|
|
@@ -76,6 +77,31 @@ export const ERROR_CATALOG: Readonly<Record<string, readonly [status: number, re
|
|
|
76
77
|
turnstile_required: [400, 0, "Turnstile token required"],
|
|
77
78
|
turnstile_failed: [403, 0, "Turnstile check failed"],
|
|
78
79
|
turnstile_unavailable: [503, 1, "Turnstile unavailable"],
|
|
80
|
+
github_app_not_configured: [503, 0, "GitHub App not configured"],
|
|
81
|
+
github_installation_not_found: [404, 0, "GitHub installation not found"],
|
|
82
|
+
github_repository_not_accessible: [404, 0, "GitHub repository not accessible"],
|
|
83
|
+
repository_link_not_found: [404, 0, "Repository link not found"],
|
|
84
|
+
eval_run_not_found: [404, 0, "Eval run not found"],
|
|
85
|
+
alert_destination_not_found: [404, 0, "Alert destination not found"],
|
|
86
|
+
trace_not_found: [404, 0, "Trace not found"],
|
|
87
|
+
deploy_not_found: [404, 0, "Deploy not found"],
|
|
88
|
+
deploy_not_rollbackable: [409, 0, "Deploy cannot be rolled back to"],
|
|
89
|
+
deploy_not_updatable: [409, 0, "Deploy cannot change this way"],
|
|
90
|
+
app_host_label_taken: [409, 0, "Address label taken"],
|
|
91
|
+
app_host_label_reserved: [422, 0, "Address label reserved"],
|
|
92
|
+
app_host_conflict: [409, 0, "Address label is fixed"],
|
|
93
|
+
app_host_route_conflict: [409, 1, "Address switched by another call"],
|
|
94
|
+
app_host_not_found: [404, 0, "Address not found"],
|
|
95
|
+
app_host_blocked: [403, 0, "Address blocked"],
|
|
96
|
+
app_host_public_needs_spend_cap: [422, 0, "Public address needs a spend cap"],
|
|
97
|
+
app_host_port_public: [422, 0, "Address port is public"],
|
|
98
|
+
sandbox_routed: [409, 0, "Sandbox serves an address"],
|
|
99
|
+
app_not_found: [404, 0, "No app at this address"],
|
|
100
|
+
app_link_required: [401, 0, "App shared by link"],
|
|
101
|
+
app_deploying: [503, 1, "App not live yet"],
|
|
102
|
+
app_not_running: [503, 1, "App not running"],
|
|
103
|
+
app_blocked: [410, 0, "Address unavailable"],
|
|
104
|
+
app_unavailable: [503, 1, "App unavailable"],
|
|
79
105
|
authorization_pending: [400, 1, "Authorization pending"],
|
|
80
106
|
slow_down: [400, 1, "Slow down"],
|
|
81
107
|
access_denied: [400, 0, "Access denied"],
|
|
@@ -114,6 +140,7 @@ export const ERROR_CATALOG: Readonly<Record<string, readonly [status: number, re
|
|
|
114
140
|
capture_failed: [502, 1, "Capture failed"],
|
|
115
141
|
script_invalid: [422, 0, "Invalid video script"],
|
|
116
142
|
script_step_failed: [422, 0, "Script step failed"],
|
|
143
|
+
profile_expired: [422, 0, "Profile no longer signs in"],
|
|
117
144
|
restyle_unavailable: [409, 0, "Restyle not available"],
|
|
118
145
|
background_unavailable: [503, 1, "Background unavailable"],
|
|
119
146
|
style_invalid: [422, 0, "Invalid style"],
|
|
@@ -130,6 +157,8 @@ export const ERROR_CATALOG: Readonly<Record<string, readonly [status: number, re
|
|
|
130
157
|
guest_outdated: [409, 0, "Sandbox agent predates the operation"],
|
|
131
158
|
file_too_large: [413, 0, "File too large"],
|
|
132
159
|
port_not_exposed: [404, 0, "Port not exposed"],
|
|
160
|
+
app_token_invalid: [403, 0, "App address credential refused"],
|
|
161
|
+
upstream_first_byte_timeout: [504, 0, "Upstream first byte timeout"],
|
|
133
162
|
process_not_found: [404, 0, "Process not found"],
|
|
134
163
|
kernel_unavailable: [409, 0, "Code kernel unavailable"],
|
|
135
164
|
language_unsupported: [422, 0, "Language not supported"],
|
|
@@ -174,6 +203,9 @@ export const ERROR_CATALOG: Readonly<Record<string, readonly [status: number, re
|
|
|
174
203
|
connection_mismatch: [422, 0, "Connection does not match"],
|
|
175
204
|
pack_unavailable: [503, 1, "Pack unavailable"],
|
|
176
205
|
action_expression_error: [422, 0, "Action expression failed"],
|
|
206
|
+
tool_failed: [502, 0, "Hosted tool failed"],
|
|
207
|
+
tool_timed_out: [504, 0, "Hosted tool timed out"],
|
|
208
|
+
tool_unavailable: [503, 1, "Hosted tool unavailable"],
|
|
177
209
|
connection_not_found: [404, 0, "Connection not found"],
|
|
178
210
|
connection_invalid: [422, 0, "Invalid connection"],
|
|
179
211
|
blob_not_found: [404, 0, "Stored object not found"],
|
|
@@ -197,6 +229,7 @@ export type B3OSServerErrorCode =
|
|
|
197
229
|
| "payload_too_large"
|
|
198
230
|
| "route_not_found"
|
|
199
231
|
| "feature_not_enabled"
|
|
232
|
+
| "flags_unavailable"
|
|
200
233
|
| "method_not_allowed"
|
|
201
234
|
| "edge_only"
|
|
202
235
|
| "limit_exceeded"
|
|
@@ -261,6 +294,31 @@ export type B3OSServerErrorCode =
|
|
|
261
294
|
| "turnstile_required"
|
|
262
295
|
| "turnstile_failed"
|
|
263
296
|
| "turnstile_unavailable"
|
|
297
|
+
| "github_app_not_configured"
|
|
298
|
+
| "github_installation_not_found"
|
|
299
|
+
| "github_repository_not_accessible"
|
|
300
|
+
| "repository_link_not_found"
|
|
301
|
+
| "eval_run_not_found"
|
|
302
|
+
| "alert_destination_not_found"
|
|
303
|
+
| "trace_not_found"
|
|
304
|
+
| "deploy_not_found"
|
|
305
|
+
| "deploy_not_rollbackable"
|
|
306
|
+
| "deploy_not_updatable"
|
|
307
|
+
| "app_host_label_taken"
|
|
308
|
+
| "app_host_label_reserved"
|
|
309
|
+
| "app_host_conflict"
|
|
310
|
+
| "app_host_route_conflict"
|
|
311
|
+
| "app_host_not_found"
|
|
312
|
+
| "app_host_blocked"
|
|
313
|
+
| "app_host_public_needs_spend_cap"
|
|
314
|
+
| "app_host_port_public"
|
|
315
|
+
| "sandbox_routed"
|
|
316
|
+
| "app_not_found"
|
|
317
|
+
| "app_link_required"
|
|
318
|
+
| "app_deploying"
|
|
319
|
+
| "app_not_running"
|
|
320
|
+
| "app_blocked"
|
|
321
|
+
| "app_unavailable"
|
|
264
322
|
| "authorization_pending"
|
|
265
323
|
| "slow_down"
|
|
266
324
|
| "access_denied"
|
|
@@ -299,6 +357,7 @@ export type B3OSServerErrorCode =
|
|
|
299
357
|
| "capture_failed"
|
|
300
358
|
| "script_invalid"
|
|
301
359
|
| "script_step_failed"
|
|
360
|
+
| "profile_expired"
|
|
302
361
|
| "restyle_unavailable"
|
|
303
362
|
| "background_unavailable"
|
|
304
363
|
| "style_invalid"
|
|
@@ -315,6 +374,8 @@ export type B3OSServerErrorCode =
|
|
|
315
374
|
| "guest_outdated"
|
|
316
375
|
| "file_too_large"
|
|
317
376
|
| "port_not_exposed"
|
|
377
|
+
| "app_token_invalid"
|
|
378
|
+
| "upstream_first_byte_timeout"
|
|
318
379
|
| "process_not_found"
|
|
319
380
|
| "kernel_unavailable"
|
|
320
381
|
| "language_unsupported"
|
|
@@ -359,6 +420,9 @@ export type B3OSServerErrorCode =
|
|
|
359
420
|
| "connection_mismatch"
|
|
360
421
|
| "pack_unavailable"
|
|
361
422
|
| "action_expression_error"
|
|
423
|
+
| "tool_failed"
|
|
424
|
+
| "tool_timed_out"
|
|
425
|
+
| "tool_unavailable"
|
|
362
426
|
| "connection_not_found"
|
|
363
427
|
| "connection_invalid"
|
|
364
428
|
| "blob_not_found"
|
package/src/generated/ids.ts
CHANGED
|
@@ -31,6 +31,9 @@ export const ID_PREFIXES = {
|
|
|
31
31
|
tkt: { object: "stream_ticket", product: "platform", secret: true },
|
|
32
32
|
evt: { object: "event", product: "platform" },
|
|
33
33
|
usr: { object: "user", product: "platform" },
|
|
34
|
+
dep: { object: "deploy", product: "platform" },
|
|
35
|
+
evr: { object: "eval_run", product: "platform" },
|
|
36
|
+
alt: { object: "alert", product: "platform" },
|
|
34
37
|
} as const;
|
|
35
38
|
|
|
36
39
|
export type IdPrefix = keyof typeof ID_PREFIXES;
|