@briefcase-ai/auto 0.0.0-stage → 5.0.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 (42) hide show
  1. package/README.md +102 -2
  2. package/dist/activate.d.ts +35 -0
  3. package/dist/activate.js +108 -0
  4. package/dist/auto.d.ts +92 -0
  5. package/dist/auto.js +350 -0
  6. package/dist/context.d.ts +49 -0
  7. package/dist/context.js +82 -0
  8. package/dist/detect.d.ts +26 -0
  9. package/dist/detect.js +127 -0
  10. package/dist/esbuild.d.ts +40 -0
  11. package/dist/esbuild.js +55 -0
  12. package/dist/exporters.d.ts +196 -0
  13. package/dist/exporters.js +405 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.js +14 -0
  16. package/dist/instrument/anthropic.d.ts +40 -0
  17. package/dist/instrument/anthropic.js +178 -0
  18. package/dist/instrument/bedrock.d.ts +53 -0
  19. package/dist/instrument/bedrock.js +256 -0
  20. package/dist/instrument/core.d.ts +257 -0
  21. package/dist/instrument/core.js +772 -0
  22. package/dist/instrument/google-genai.d.ts +71 -0
  23. package/dist/instrument/google-genai.js +289 -0
  24. package/dist/instrument/openai.d.ts +68 -0
  25. package/dist/instrument/openai.js +293 -0
  26. package/dist/instrument/stainless.d.ts +41 -0
  27. package/dist/instrument/stainless.js +151 -0
  28. package/dist/loader.d.ts +79 -0
  29. package/dist/loader.js +202 -0
  30. package/dist/observe.d.ts +60 -0
  31. package/dist/observe.js +246 -0
  32. package/dist/pipeline.d.ts +48 -0
  33. package/dist/pipeline.js +155 -0
  34. package/dist/record.d.ts +54 -0
  35. package/dist/record.js +55 -0
  36. package/dist/register.d.ts +9 -0
  37. package/dist/register.js +12 -0
  38. package/dist/state.d.ts +25 -0
  39. package/dist/state.js +29 -0
  40. package/dist/util.d.ts +51 -0
  41. package/dist/util.js +198 -0
  42. package/package.json +82 -4
@@ -0,0 +1,55 @@
1
+ /**
2
+ * esbuild plugin for applications that bundle a provider SDK.
3
+ *
4
+ * import { build } from "esbuild";
5
+ * import { briefcaseAuto } from "@briefcase-ai/auto/esbuild";
6
+ * await build({ entryPoints: ["app.ts"], bundle: true, platform: "node", plugins: [briefcaseAuto()] });
7
+ *
8
+ * When an SDK is bundled, its classes live inside the bundle, where
9
+ * `auto()` cannot find them. This plugin appends one statement to each SDK
10
+ * file that holds patch targets (the same files and the same statement the
11
+ * Node load hook uses, see `loader.ts`): at run time the bundled module
12
+ * reports its exports to `@briefcase-ai/auto`, which patches them as it
13
+ * patches an installed copy. The bundle still needs `auto()` to run, from
14
+ * the `--import @briefcase-ai/auto/register` preload or from the
15
+ * application (bundled or not). Reports made before `auto()` runs are kept
16
+ * and replayed. Nothing else in the bundle changes.
17
+ *
18
+ * Alternative without the plugin: keep the SDKs out of the bundle
19
+ * (`external: SDK_PACKAGES`) and ship them in node_modules.
20
+ */
21
+ import { randomBytes } from "node:crypto";
22
+ import { readFile } from "node:fs/promises";
23
+ import { basename, dirname } from "node:path";
24
+ import { WATCHED } from "./auto.js";
25
+ import { matchFile, notifierSource, setWatchedFiles } from "./loader.js";
26
+ /** The npm packages this package instruments (for `external: SDK_PACKAGES`). */
27
+ export const SDK_PACKAGES = [...new Set(WATCHED.map((f) => f.packageName))];
28
+ function escape(text) {
29
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\//g, "[\\\\/]");
30
+ }
31
+ export function briefcaseAuto() {
32
+ return {
33
+ name: "briefcase-auto",
34
+ setup(build) {
35
+ setWatchedFiles(WATCHED);
36
+ // One id per build, so two bundles loaded into one process stay separate copies.
37
+ const buildId = randomBytes(4).toString("hex");
38
+ const filter = new RegExp(`[\\\\/]node_modules[\\\\/](?:${WATCHED.map((f) => `${escape(f.packageName)}[\\\\/]${escape(f.rel)}`).join("|")})$`);
39
+ build.onLoad({ filter, namespace: "file" }, async (args) => {
40
+ const hit = matchFile(args.path);
41
+ if (!hit)
42
+ return undefined;
43
+ const text = await readFile(args.path, "utf8");
44
+ // No build-machine path in the bundle: a per-build id and the path inside the package.
45
+ const reported = `bundle:${buildId}/node_modules/${hit.file.packageName}/${hit.file.rel}`;
46
+ const self = `./${basename(args.path)}`;
47
+ return {
48
+ contents: text + notifierSource(`bundle-${hit.file.format}`, reported, self),
49
+ loader: "js",
50
+ resolveDir: dirname(args.path),
51
+ };
52
+ });
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Destinations for decision records. Each exporter receives batches from the
3
+ * bounded queue in `pipeline.ts`:
4
+ *
5
+ * - `ConsoleExporter`: one JSON line per record on stderr.
6
+ * - `JsonlFileExporter`: appends JSON lines to a file (dir 0700, file 0600).
7
+ * - `HttpExporter`: POSTs `{"records": [...]}` batches, the body Python's
8
+ * `briefcase.exporters.HTTPExporter` sends; https required off loopback,
9
+ * bearer token, retry with jittered exponential backoff, no redirects.
10
+ * - `OtlpHttpExporter`: OTLP/HTTP JSON, one `briefcase.decision` span per
11
+ * record with the attributes Python's `OTelExporter` sets.
12
+ * - `MemoryExporter`: keeps records in memory (tests, notebooks).
13
+ */
14
+ import type { DecisionRecord } from "./record.js";
15
+ export type ExportResult = "sent" | "retry" | "rejected";
16
+ export interface Exporter {
17
+ /** Short kind name shown by `status()`: console, jsonl, http, otlp, memory. */
18
+ readonly kind: string;
19
+ /** Records per batch; 1 means "export as soon as a record arrives". */
20
+ readonly batchSize: number;
21
+ /** Also send buffered records this often (ms); 0 disables the timer. */
22
+ readonly flushIntervalMs: number;
23
+ /** Sends one batch. `final` is set during shutdown: no backoff waits. */
24
+ exportBatch(records: DecisionRecord[], final: boolean): ExportResult | Promise<ExportResult>;
25
+ /** Synchronous export, used from the process `exit` handler when available. */
26
+ exportSync?(records: DecisionRecord[]): void;
27
+ /**
28
+ * Export each record synchronously (`exportSync`) the moment it is
29
+ * queued. Set for destinations where that is cheap and where waiting
30
+ * would risk losing it (a worker thread can be terminated at any time).
31
+ */
32
+ readonly immediate?: boolean;
33
+ close?(): void | Promise<void>;
34
+ /** Destination without credentials, for `status()`. */
35
+ describe(): string;
36
+ }
37
+ interface WritableLike {
38
+ write(chunk: string): unknown;
39
+ }
40
+ export declare class ConsoleExporter implements Exporter {
41
+ readonly kind = "console";
42
+ readonly batchSize = 1;
43
+ readonly flushIntervalMs = 0;
44
+ /** In a worker thread, records are written straight to fd 2 (a worker's process.stderr is asynchronous, and lost on terminate()). */
45
+ readonly immediate: boolean;
46
+ private readonly stream;
47
+ constructor(stream?: WritableLike);
48
+ exportBatch(records: DecisionRecord[]): ExportResult;
49
+ exportSync(records: DecisionRecord[]): void;
50
+ describe(): string;
51
+ }
52
+ export declare class JsonlFileExporter implements Exporter {
53
+ readonly path: string;
54
+ readonly kind = "jsonl";
55
+ readonly batchSize = 1;
56
+ readonly flushIntervalMs = 0;
57
+ /** Each record is appended synchronously when it is queued in a worker thread. */
58
+ readonly immediate: boolean;
59
+ private fd;
60
+ constructor(path: string);
61
+ private ensureOpen;
62
+ exportBatch(records: DecisionRecord[]): ExportResult;
63
+ exportSync(records: DecisionRecord[]): void;
64
+ close(): void;
65
+ describe(): string;
66
+ }
67
+ export declare class MemoryExporter implements Exporter {
68
+ readonly kind = "memory";
69
+ readonly batchSize = 1;
70
+ readonly flushIntervalMs = 0;
71
+ readonly records: DecisionRecord[];
72
+ exportBatch(records: DecisionRecord[]): ExportResult;
73
+ exportSync(records: DecisionRecord[]): void;
74
+ clear(): void;
75
+ describe(): string;
76
+ }
77
+ export type FetchLike = (input: string, init: {
78
+ method: string;
79
+ headers: Record<string, string>;
80
+ body: string;
81
+ redirect: "manual";
82
+ signal: AbortSignal;
83
+ }) => Promise<{
84
+ status: number;
85
+ headers: {
86
+ get(name: string): string | null;
87
+ };
88
+ text(): Promise<string>;
89
+ }>;
90
+ export declare function isLoopbackHost(host: string): boolean;
91
+ export interface HttpTransportOptions {
92
+ headers?: Record<string, string>;
93
+ timeoutMs?: number;
94
+ maxRetries?: number;
95
+ backoffBaseMs?: number;
96
+ backoffMaxMs?: number;
97
+ allowInsecure?: boolean;
98
+ /** Replaces the global fetch (tests, proxies). */
99
+ fetch?: FetchLike;
100
+ }
101
+ declare abstract class HttpTransport {
102
+ protected readonly url: string;
103
+ protected readonly logUrl: string;
104
+ protected readonly headers: Record<string, string>;
105
+ private readonly timeoutMs;
106
+ private readonly maxRetries;
107
+ private readonly backoffBaseMs;
108
+ private readonly backoffMaxMs;
109
+ private readonly fetchImpl;
110
+ failedBatches: number;
111
+ constructor(url: string, label: string, options: HttpTransportOptions, defaults: Record<string, string>);
112
+ protected abstract retryable(status: number): boolean;
113
+ protected abstract label: string;
114
+ retryDelayMs(attempt: number, retryAfter: string | null): number;
115
+ /** POSTs `body`; returns sent / retry (transient, after all attempts) / rejected. */
116
+ protected post(body: string, count: number, final: boolean, onOk?: (text: string) => void): Promise<ExportResult>;
117
+ }
118
+ export interface HttpExporterOptions extends HttpTransportOptions {
119
+ token?: string;
120
+ batchSize?: number;
121
+ flushIntervalMs?: number;
122
+ }
123
+ /** POSTs `{"records": [...]}` batches, like Python's HTTPExporter. */
124
+ export declare class HttpExporter extends HttpTransport implements Exporter {
125
+ readonly kind = "http";
126
+ readonly batchSize: number;
127
+ readonly flushIntervalMs: number;
128
+ protected label: string;
129
+ constructor(url: string, options?: HttpExporterOptions);
130
+ protected retryable(status: number): boolean;
131
+ exportBatch(records: DecisionRecord[], final: boolean): Promise<ExportResult>;
132
+ describe(): string;
133
+ }
134
+ export interface OtlpExporterOptions extends HttpTransportOptions {
135
+ serviceName?: string;
136
+ batchSize?: number;
137
+ flushIntervalMs?: number;
138
+ }
139
+ type AnyValue = {
140
+ stringValue: string;
141
+ } | {
142
+ doubleValue: number;
143
+ } | {
144
+ intValue: string;
145
+ } | {
146
+ boolValue: boolean;
147
+ };
148
+ interface KeyValue {
149
+ key: string;
150
+ value: AnyValue;
151
+ }
152
+ /** ISO 8601 timestamp (any fraction length, Z or offset) to epoch nanoseconds. */
153
+ export declare function isoToNanos(value: unknown): bigint | null;
154
+ /**
155
+ * The eight `briefcase.*` span attributes, derived exactly as Python's
156
+ * `OTelExporter._extract_attrs` derives them from a dict record.
157
+ */
158
+ export declare function decisionAttributes(record: Record<string, unknown>): KeyValue[];
159
+ /** One OTLP/JSON `Span` for a record (proto3 JSON mapping: lowerCamelCase, hex ids, enums as integers, int64 as strings). */
160
+ export declare function decisionSpan(record: Record<string, unknown>): Record<string, unknown>;
161
+ export declare const SCOPE_VERSION = "5.0.0";
162
+ export declare function otlpTracesBody(records: DecisionRecord[], serviceName: string): Record<string, unknown>;
163
+ /** OTLP/HTTP with the JSON encoding, posting to a `/v1/traces` URL. */
164
+ export declare class OtlpHttpExporter extends HttpTransport implements Exporter {
165
+ readonly kind = "otlp";
166
+ readonly batchSize: number;
167
+ readonly flushIntervalMs: number;
168
+ readonly serviceName: string;
169
+ rejectedSpans: number;
170
+ protected label: string;
171
+ constructor(endpoint: string, options?: OtlpExporterOptions);
172
+ /** OTLP/HTTP: only 429, 502, 503 and 504 are retryable. */
173
+ protected retryable(status: number): boolean;
174
+ exportBatch(records: DecisionRecord[], final: boolean): Promise<ExportResult>;
175
+ describe(): string;
176
+ }
177
+ /**
178
+ * Used in a worker thread when the main thread is observing: each record is
179
+ * posted to the main thread (a `BroadcastChannel`) the moment it is
180
+ * finished, and exported there by the main thread's destination. A posted
181
+ * message survives the worker being terminated.
182
+ */
183
+ export declare class WorkerForwardExporter implements Exporter {
184
+ readonly channelName: string;
185
+ readonly kind = "main-thread";
186
+ readonly batchSize = 1;
187
+ readonly flushIntervalMs = 0;
188
+ readonly immediate = true;
189
+ private readonly channel;
190
+ constructor(channelName: string);
191
+ exportBatch(records: DecisionRecord[]): ExportResult;
192
+ exportSync(records: DecisionRecord[]): void;
193
+ close(): void;
194
+ describe(): string;
195
+ }
196
+ export {};
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Destinations for decision records. Each exporter receives batches from the
3
+ * bounded queue in `pipeline.ts`:
4
+ *
5
+ * - `ConsoleExporter`: one JSON line per record on stderr.
6
+ * - `JsonlFileExporter`: appends JSON lines to a file (dir 0700, file 0600).
7
+ * - `HttpExporter`: POSTs `{"records": [...]}` batches, the body Python's
8
+ * `briefcase.exporters.HTTPExporter` sends; https required off loopback,
9
+ * bearer token, retry with jittered exponential backoff, no redirects.
10
+ * - `OtlpHttpExporter`: OTLP/HTTP JSON, one `briefcase.decision` span per
11
+ * record with the attributes Python's `OTelExporter` sets.
12
+ * - `MemoryExporter`: keeps records in memory (tests, notebooks).
13
+ */
14
+ import { randomBytes } from "node:crypto";
15
+ import { closeSync, fchmodSync, mkdirSync, openSync, writeSync } from "node:fs";
16
+ import { dirname } from "node:path";
17
+ import { BroadcastChannel, isMainThread } from "node:worker_threads";
18
+ import { read, warn } from "./util.js";
19
+ export class ConsoleExporter {
20
+ kind = "console";
21
+ batchSize = 1;
22
+ flushIntervalMs = 0;
23
+ /** In a worker thread, records are written straight to fd 2 (a worker's process.stderr is asynchronous, and lost on terminate()). */
24
+ immediate = !isMainThread;
25
+ stream;
26
+ constructor(stream) {
27
+ this.stream = stream ?? (isMainThread ? process.stderr : { write: (chunk) => writeSync(2, chunk) });
28
+ }
29
+ exportBatch(records) {
30
+ this.exportSync(records);
31
+ return "sent";
32
+ }
33
+ exportSync(records) {
34
+ for (const record of records)
35
+ this.stream.write(JSON.stringify(record) + "\n");
36
+ }
37
+ describe() {
38
+ return "console (stderr)";
39
+ }
40
+ }
41
+ export class JsonlFileExporter {
42
+ path;
43
+ kind = "jsonl";
44
+ batchSize = 1;
45
+ flushIntervalMs = 0;
46
+ /** Each record is appended synchronously when it is queued in a worker thread. */
47
+ immediate = !isMainThread;
48
+ fd = null;
49
+ constructor(path) {
50
+ this.path = path;
51
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
52
+ }
53
+ ensureOpen() {
54
+ if (this.fd === null) {
55
+ this.fd = openSync(this.path, "a", 0o600);
56
+ fchmodSync(this.fd, 0o600);
57
+ }
58
+ return this.fd;
59
+ }
60
+ exportBatch(records) {
61
+ this.exportSync(records);
62
+ return "sent";
63
+ }
64
+ exportSync(records) {
65
+ if (records.length === 0)
66
+ return;
67
+ const fd = this.ensureOpen();
68
+ writeSync(fd, records.map((r) => JSON.stringify(r) + "\n").join(""));
69
+ }
70
+ close() {
71
+ if (this.fd !== null) {
72
+ closeSync(this.fd);
73
+ this.fd = null;
74
+ }
75
+ }
76
+ describe() {
77
+ return this.path;
78
+ }
79
+ }
80
+ export class MemoryExporter {
81
+ kind = "memory";
82
+ batchSize = 1;
83
+ flushIntervalMs = 0;
84
+ records = [];
85
+ exportBatch(records) {
86
+ this.exportSync(records);
87
+ return "sent";
88
+ }
89
+ exportSync(records) {
90
+ this.records.push(...records);
91
+ }
92
+ clear() {
93
+ this.records.length = 0;
94
+ }
95
+ describe() {
96
+ return "memory";
97
+ }
98
+ }
99
+ export function isLoopbackHost(host) {
100
+ const h = host.replace(/^\[|\]$/g, "").toLowerCase();
101
+ if (h === "localhost" || h === "::1")
102
+ return true;
103
+ return /^127(\.\d{1,3}){3}$/.test(h);
104
+ }
105
+ function sleep(ms) {
106
+ return new Promise((resolve) => {
107
+ const timer = setTimeout(resolve, ms);
108
+ timer.unref?.();
109
+ });
110
+ }
111
+ class HttpTransport {
112
+ url;
113
+ logUrl;
114
+ headers;
115
+ timeoutMs;
116
+ maxRetries;
117
+ backoffBaseMs;
118
+ backoffMaxMs;
119
+ fetchImpl;
120
+ failedBatches = 0;
121
+ constructor(url, label, options, defaults) {
122
+ let parsed;
123
+ try {
124
+ parsed = new URL(url);
125
+ }
126
+ catch {
127
+ throw new Error(`${label} needs an http(s) URL, got ${JSON.stringify(url)}`);
128
+ }
129
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || !parsed.hostname) {
130
+ throw new Error(`${label} needs an http(s) URL, got ${JSON.stringify(url)}`);
131
+ }
132
+ if (parsed.protocol === "http:" && !options.allowInsecure && !isLoopbackHost(parsed.hostname)) {
133
+ throw new Error(`${label} URL uses http with a non-loopback host; records and any bearer token would be ` +
134
+ "sent in cleartext. Use https, or pass allowInsecure: true.");
135
+ }
136
+ this.url = url;
137
+ this.logUrl = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
138
+ this.headers = { ...defaults, ...(options.headers ?? {}) };
139
+ this.timeoutMs = options.timeoutMs ?? 10_000;
140
+ this.maxRetries = Math.max(0, options.maxRetries ?? 3);
141
+ this.backoffBaseMs = Math.max(0, options.backoffBaseMs ?? 500);
142
+ this.backoffMaxMs = Math.max(0, options.backoffMaxMs ?? 30_000);
143
+ const globalFetch = globalThis.fetch;
144
+ const chosen = options.fetch ?? globalFetch;
145
+ if (!chosen)
146
+ throw new Error(`${label} needs fetch (Node >= 26 provides it)`);
147
+ this.fetchImpl = chosen;
148
+ }
149
+ retryDelayMs(attempt, retryAfter) {
150
+ const ceiling = Math.min(this.backoffMaxMs, this.backoffBaseMs * 2 ** attempt);
151
+ let delay = ceiling > 0 ? ceiling / 2 + Math.random() * (ceiling / 2) : 0;
152
+ if (retryAfter) {
153
+ const seconds = Number(retryAfter);
154
+ if (Number.isFinite(seconds) && seconds >= 0)
155
+ delay = Math.max(delay, Math.min(seconds * 1000, this.backoffMaxMs));
156
+ }
157
+ return delay;
158
+ }
159
+ /** POSTs `body`; returns sent / retry (transient, after all attempts) / rejected. */
160
+ async post(body, count, final, onOk) {
161
+ const attempts = 1 + this.maxRetries;
162
+ let problem = "";
163
+ for (let attempt = 0; attempt < attempts; attempt++) {
164
+ let retryAfter = null;
165
+ try {
166
+ const response = await this.fetchImpl(this.url, {
167
+ method: "POST",
168
+ headers: this.headers,
169
+ body,
170
+ redirect: "manual",
171
+ signal: AbortSignal.timeout(this.timeoutMs),
172
+ });
173
+ const text = await response.text().catch(() => "");
174
+ if (response.status >= 200 && response.status < 300) {
175
+ onOk?.(text);
176
+ return "sent";
177
+ }
178
+ problem = `HTTP ${response.status}`;
179
+ retryAfter = response.headers.get("retry-after");
180
+ if (!this.retryable(response.status)) {
181
+ this.failedBatches++;
182
+ warn(`${this.label}: ${this.logUrl} rejected a batch of ${count} record(s) with ${problem}; not retryable, batch dropped`);
183
+ return "rejected";
184
+ }
185
+ }
186
+ catch (error) {
187
+ problem = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
188
+ }
189
+ if (attempt + 1 < attempts && !final)
190
+ await sleep(this.retryDelayMs(attempt, retryAfter));
191
+ }
192
+ this.failedBatches++;
193
+ warn(`${this.label}: sending ${count} record(s) to ${this.logUrl} failed (${problem}) after ${attempts} attempt(s); keeping them for the next flush`);
194
+ return "retry";
195
+ }
196
+ }
197
+ /** POSTs `{"records": [...]}` batches, like Python's HTTPExporter. */
198
+ export class HttpExporter extends HttpTransport {
199
+ kind = "http";
200
+ batchSize;
201
+ flushIntervalMs;
202
+ label = "HttpExporter";
203
+ constructor(url, options = {}) {
204
+ const defaults = {
205
+ "Content-Type": "application/json",
206
+ "User-Agent": "briefcase-ai-auto-http-exporter",
207
+ };
208
+ if (options.token)
209
+ defaults["Authorization"] = `Bearer ${options.token}`;
210
+ super(url, "HttpExporter", options, defaults);
211
+ this.batchSize = Math.max(1, options.batchSize ?? 100);
212
+ this.flushIntervalMs = Math.max(0, options.flushIntervalMs ?? 5000);
213
+ }
214
+ retryable(status) {
215
+ return status === 429 || status >= 500;
216
+ }
217
+ exportBatch(records, final) {
218
+ return this.post(JSON.stringify({ records }), records.length, final);
219
+ }
220
+ describe() {
221
+ return this.logUrl;
222
+ }
223
+ }
224
+ function str(value) {
225
+ return value === null || value === undefined ? "" : String(value);
226
+ }
227
+ function num(value) {
228
+ const n = typeof value === "number" ? value : Number(value);
229
+ return Number.isFinite(n) ? n : 0;
230
+ }
231
+ /** ISO 8601 timestamp (any fraction length, Z or offset) to epoch nanoseconds. */
232
+ export function isoToNanos(value) {
233
+ if (typeof value !== "string")
234
+ return null;
235
+ const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$/.exec(value.trim());
236
+ if (!m)
237
+ return null;
238
+ const seconds = Date.parse(`${m[1]}${m[3] ?? "Z"}`);
239
+ if (!Number.isFinite(seconds))
240
+ return null;
241
+ const fraction = (m[2] ?? "").padEnd(9, "0").slice(0, 9);
242
+ return BigInt(seconds) * 1000000n + BigInt(fraction);
243
+ }
244
+ /**
245
+ * The eight `briefcase.*` span attributes, derived exactly as Python's
246
+ * `OTelExporter._extract_attrs` derives them from a dict record.
247
+ */
248
+ export function decisionAttributes(record) {
249
+ const outputs = record["outputs"];
250
+ let confidence = 0;
251
+ if (Array.isArray(outputs)) {
252
+ const hit = outputs.find((o) => read(o, "confidence") !== undefined && read(o, "confidence") !== null);
253
+ if (hit)
254
+ confidence = num(read(hit, "confidence"));
255
+ }
256
+ else if (outputs && typeof outputs === "object") {
257
+ confidence = num(read(outputs, "confidence") ?? 0);
258
+ }
259
+ if (record["confidence"] !== undefined && record["confidence"] !== null)
260
+ confidence = num(record["confidence"]);
261
+ const routing = record["routing_decision"];
262
+ const params = record["model_parameters"];
263
+ const contextVersion = str(read(record["context"], "version")) || str(record["context_version"]);
264
+ return [
265
+ { key: "briefcase.decision.id", value: { stringValue: str(record["decision_id"] ?? record["id"]) } },
266
+ { key: "briefcase.context.version", value: { stringValue: contextVersion } },
267
+ { key: "briefcase.confidence", value: { doubleValue: confidence } },
268
+ {
269
+ key: "briefcase.routing.action",
270
+ value: { stringValue: routing ? str(read(routing, "action") ?? "unrouted") : "unrouted" },
271
+ },
272
+ { key: "briefcase.model.name", value: { stringValue: str(read(params, "model_name")) } },
273
+ { key: "briefcase.model.provider", value: { stringValue: str(read(params, "provider")) } },
274
+ { key: "briefcase.execution.time_ms", value: { doubleValue: num(record["execution_time_ms"]) } },
275
+ { key: "briefcase.snapshot.type", value: { stringValue: str(record["snapshot_type"] ?? "decision") } },
276
+ ];
277
+ }
278
+ const HEX32 = /^[0-9a-f]{32}$/;
279
+ const HEX16 = /^[0-9a-f]{16}$/;
280
+ /** One OTLP/JSON `Span` for a record (proto3 JSON mapping: lowerCamelCase, hex ids, enums as integers, int64 as strings). */
281
+ export function decisionSpan(record) {
282
+ const traceId = String(record["trace_id"] ?? "").toLowerCase();
283
+ const parentSpanId = String(record["parent_span_id"] ?? "").toLowerCase();
284
+ const hasParent = HEX32.test(traceId) && HEX16.test(parentSpanId) && !/^0+$/.test(traceId) && !/^0+$/.test(parentSpanId);
285
+ let start = isoToNanos(record["started_at"]);
286
+ let end = isoToNanos(record["ended_at"]);
287
+ const execMs = record["execution_time_ms"];
288
+ if (typeof execMs === "number" && Number.isFinite(execMs) && execMs >= 0) {
289
+ const duration = BigInt(Math.round(execMs * 1_000_000));
290
+ if (start !== null && end === null)
291
+ end = start + duration;
292
+ else if (end !== null && start === null)
293
+ start = end - duration;
294
+ }
295
+ const now = BigInt(Date.now()) * 1000000n;
296
+ start ??= now;
297
+ end ??= start;
298
+ if (end < start)
299
+ end = start;
300
+ const flags = typeof record["trace_flags"] === "number" ? record["trace_flags"] & 0xff : 1;
301
+ const span = {
302
+ traceId: hasParent ? traceId : randomBytes(16).toString("hex"),
303
+ spanId: randomBytes(8).toString("hex"),
304
+ name: "briefcase.decision",
305
+ kind: 1, // SPAN_KIND_INTERNAL
306
+ startTimeUnixNano: start.toString(),
307
+ endTimeUnixNano: end.toString(),
308
+ attributes: decisionAttributes(record),
309
+ flags,
310
+ status: record["error"] ? { code: 2 } : {}, // STATUS_CODE_ERROR / unset
311
+ };
312
+ if (hasParent)
313
+ span["parentSpanId"] = parentSpanId;
314
+ return span;
315
+ }
316
+ export const SCOPE_VERSION = "5.0.0";
317
+ export function otlpTracesBody(records, serviceName) {
318
+ return {
319
+ resourceSpans: [
320
+ {
321
+ resource: { attributes: [{ key: "service.name", value: { stringValue: serviceName } }] },
322
+ scopeSpans: [
323
+ {
324
+ scope: { name: "briefcase", version: SCOPE_VERSION },
325
+ spans: records.map((r) => decisionSpan(r)),
326
+ },
327
+ ],
328
+ },
329
+ ],
330
+ };
331
+ }
332
+ /** OTLP/HTTP with the JSON encoding, posting to a `/v1/traces` URL. */
333
+ export class OtlpHttpExporter extends HttpTransport {
334
+ kind = "otlp";
335
+ batchSize;
336
+ flushIntervalMs;
337
+ serviceName;
338
+ rejectedSpans = 0;
339
+ label = "OtlpHttpExporter";
340
+ constructor(endpoint, options = {}) {
341
+ super(endpoint, "OtlpHttpExporter", options, {
342
+ "Content-Type": "application/json",
343
+ "User-Agent": "briefcase-ai-auto-otlp-exporter",
344
+ });
345
+ this.serviceName = options.serviceName ?? "briefcase-ai";
346
+ this.batchSize = Math.max(1, options.batchSize ?? 100);
347
+ this.flushIntervalMs = Math.max(0, options.flushIntervalMs ?? 5000);
348
+ }
349
+ /** OTLP/HTTP: only 429, 502, 503 and 504 are retryable. */
350
+ retryable(status) {
351
+ return status === 429 || status === 502 || status === 503 || status === 504;
352
+ }
353
+ exportBatch(records, final) {
354
+ const body = JSON.stringify(otlpTracesBody(records, this.serviceName));
355
+ return this.post(body, records.length, final, (text) => {
356
+ // A partial success is not retried; report what the server dropped.
357
+ try {
358
+ const rejected = Number(read(JSON.parse(text), "partialSuccess", "rejectedSpans") ?? 0);
359
+ if (rejected > 0) {
360
+ this.rejectedSpans += rejected;
361
+ warn(`OtlpHttpExporter: ${this.logUrl} rejected ${rejected} span(s) (partial success)`);
362
+ }
363
+ }
364
+ catch {
365
+ // empty or non-JSON body: full success
366
+ }
367
+ });
368
+ }
369
+ describe() {
370
+ return `otlp ${this.logUrl}`;
371
+ }
372
+ }
373
+ /**
374
+ * Used in a worker thread when the main thread is observing: each record is
375
+ * posted to the main thread (a `BroadcastChannel`) the moment it is
376
+ * finished, and exported there by the main thread's destination. A posted
377
+ * message survives the worker being terminated.
378
+ */
379
+ export class WorkerForwardExporter {
380
+ channelName;
381
+ kind = "main-thread";
382
+ batchSize = 1;
383
+ flushIntervalMs = 0;
384
+ immediate = true;
385
+ channel;
386
+ constructor(channelName) {
387
+ this.channelName = channelName;
388
+ this.channel = new BroadcastChannel(channelName);
389
+ this.channel.unref();
390
+ }
391
+ exportBatch(records) {
392
+ this.exportSync(records);
393
+ return "sent";
394
+ }
395
+ exportSync(records) {
396
+ for (const record of records)
397
+ this.channel.postMessage(record);
398
+ }
399
+ close() {
400
+ this.channel.close();
401
+ }
402
+ describe() {
403
+ return "the main thread's destination";
404
+ }
405
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @briefcase-ai/auto: zero-code decision capture for Node.
3
+ *
4
+ * import { observe, auto } from "@briefcase-ai/auto";
5
+ * observe(); // destination from BRIEFCASE_EXPORTER / OTEL_EXPORTER_OTLP_*, else stderr
6
+ * auto(); // openai, @anthropic-ai/sdk, @google/genai, @aws-sdk/client-bedrock-runtime
7
+ *
8
+ * or, without editing the program: `node --import @briefcase-ai/auto/register app.js`.
9
+ */
10
+ export { auto, instrument, undo, status, PROVIDER_NAMES, type AutoOptions, type AutoStatus } from "./auto.js";
11
+ export { observe, flush, shutdown, exportStats, exporterFromEnv, resolveExporter, type ObserveOptions, } from "./observe.js";
12
+ export { ConsoleExporter, HttpExporter, JsonlFileExporter, MemoryExporter, OtlpHttpExporter, type Exporter, type ExportResult, type HttpExporterOptions, type OtlpExporterOptions, } from "./exporters.js";
13
+ export { withWorkflow, currentWorkflow, type WorkflowContext } from "./context.js";
14
+ export { SCHEMA_VERSION, type DecisionRecord, type TokenUsage } from "./record.js";
15
+ export type { PipelineStats } from "./pipeline.js";
16
+ export type { ProviderReport } from "./instrument/core.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @briefcase-ai/auto: zero-code decision capture for Node.
3
+ *
4
+ * import { observe, auto } from "@briefcase-ai/auto";
5
+ * observe(); // destination from BRIEFCASE_EXPORTER / OTEL_EXPORTER_OTLP_*, else stderr
6
+ * auto(); // openai, @anthropic-ai/sdk, @google/genai, @aws-sdk/client-bedrock-runtime
7
+ *
8
+ * or, without editing the program: `node --import @briefcase-ai/auto/register app.js`.
9
+ */
10
+ export { auto, instrument, undo, status, PROVIDER_NAMES } from "./auto.js";
11
+ export { observe, flush, shutdown, exportStats, exporterFromEnv, resolveExporter, } from "./observe.js";
12
+ export { ConsoleExporter, HttpExporter, JsonlFileExporter, MemoryExporter, OtlpHttpExporter, } from "./exporters.js";
13
+ export { withWorkflow, currentWorkflow } from "./context.js";
14
+ export { SCHEMA_VERSION } from "./record.js";