@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,71 @@
1
+ /**
2
+ * Instrumentation for the `@google/genai` Node SDK.
3
+ *
4
+ * Verified against @google/genai 3.6.1 (npm), by reading the installed
5
+ * package's `dist/node/index.mjs` / `index.cjs` and `dist/node/node.d.ts`,
6
+ * and by the offline tests in `test/google-genai.test.ts`.
7
+ *
8
+ * Patch technique: in 3.6.1 `Models.generateContent` and
9
+ * `Models.generateContentStream` are NOT prototype methods. The `Models`
10
+ * constructor assigns them per instance (`this.generateContent = async
11
+ * (params) => ...`, a plain assignment in the compiled output). We install
12
+ * an accessor for each name on `Models.prototype`: the constructor's
13
+ * assignment runs our setter, which stores the wrapped function as the
14
+ * instance's own, writable, enumerable data property (the same shape the
15
+ * SDK creates). After applying, a probe `new Models(undefined)` checks that
16
+ * the assignment really went through the setter; if a future SDK defines
17
+ * them differently, the copy is rolled back and skipped with a warning.
18
+ * Clients constructed BEFORE the patch are covered through the internal
19
+ * methods on the shared `Models.prototype` that those instance functions
20
+ * call (see `targets()` below).
21
+ * Both the ESM (`dist/node/index.mjs`) and CJS (`dist/node/index.cjs`)
22
+ * copies are patched, and the bundler builds (`dist/index.*`) when loaded.
23
+ *
24
+ * Recorded as `decision_type: "llm.google_genai.generate_content"`.
25
+ * `client.chats` sends through the same `Models` instance, so chat sessions
26
+ * are covered. Automatic function calling and automatic continuation make
27
+ * several HTTP requests inside one `generateContent` call; that is one
28
+ * record with the final response's usage (as in Python).
29
+ *
30
+ * Fields read (3.6.1 `GenerateContentResponse`): `usageMetadata`
31
+ * (`promptTokenCount`, `candidatesTokenCount`, `totalTokenCount`,
32
+ * `cachedContentTokenCount`, `thoughtsTokenCount`), `modelVersion`,
33
+ * `responseId`, `candidates[0].finishReason`. Every stream chunk is a
34
+ * `GenerateContentResponse`. No request id is exposed. Request config
35
+ * names are recorded under Python's snake_case names (`top_p`, ...).
36
+ */
37
+ import { type Instrumentor, type PatchTarget, type SdkFile } from "./core.js";
38
+ export declare const PROVIDER = "google-genai";
39
+ export declare const PACKAGE = "@google/genai";
40
+ export declare const VERIFIED_VERSION = "3.6.1";
41
+ export declare const DECISION_TYPE = "llm.google_genai.generate_content";
42
+ export declare const SPECIFIERS: string[];
43
+ /** `dist/node` is what Node resolves; `dist/index.*` is what a bundler without the `node` condition picks. */
44
+ export declare const FILES: SdkFile[];
45
+ /**
46
+ * Patch targets for one copy of the package:
47
+ *
48
+ * 1. `generateContent` / `generateContentStream` accessors on
49
+ * `Models.prototype` (see the header): every client constructed after
50
+ * the patch records one record per public call. Each such instance is
51
+ * remembered in `covered`.
52
+ * 2. Clients constructed BEFORE the patch keep the SDK's own, unwrapped
53
+ * instance functions. Those functions do their work through methods
54
+ * that live on the shared `Models.prototype` (read in 3.6.1):
55
+ * non-streamed calls through `generateContentWithContinuation` (which
56
+ * calls `generateContentInternal` once per continuation hop) or
57
+ * `generateContentInternal` directly; streamed calls through
58
+ * `processAfcStream` (default), `generateContentStreamWithContinuation`
59
+ * or `generateContentStreamInternal`. Those five are wrapped. A wrapper
60
+ * records only for an instance that is not in `covered` and only for
61
+ * the outermost of them (an inner one runs inside the outer call's
62
+ * context and passes through), so each public call is one record.
63
+ * Exception, documented: non-streamed automatic function calling
64
+ * calls `generateContentWithContinuation` once per model round from
65
+ * the instance function itself, so a pre-existing client records one
66
+ * record per round there (each with that round's usage).
67
+ */
68
+ export declare function targets(inst: Instrumentor, modules: Record<string, Record<string, unknown> | undefined>): {
69
+ targets: PatchTarget[];
70
+ verify: () => string | null;
71
+ };
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Instrumentation for the `@google/genai` Node SDK.
3
+ *
4
+ * Verified against @google/genai 3.6.1 (npm), by reading the installed
5
+ * package's `dist/node/index.mjs` / `index.cjs` and `dist/node/node.d.ts`,
6
+ * and by the offline tests in `test/google-genai.test.ts`.
7
+ *
8
+ * Patch technique: in 3.6.1 `Models.generateContent` and
9
+ * `Models.generateContentStream` are NOT prototype methods. The `Models`
10
+ * constructor assigns them per instance (`this.generateContent = async
11
+ * (params) => ...`, a plain assignment in the compiled output). We install
12
+ * an accessor for each name on `Models.prototype`: the constructor's
13
+ * assignment runs our setter, which stores the wrapped function as the
14
+ * instance's own, writable, enumerable data property (the same shape the
15
+ * SDK creates). After applying, a probe `new Models(undefined)` checks that
16
+ * the assignment really went through the setter; if a future SDK defines
17
+ * them differently, the copy is rolled back and skipped with a warning.
18
+ * Clients constructed BEFORE the patch are covered through the internal
19
+ * methods on the shared `Models.prototype` that those instance functions
20
+ * call (see `targets()` below).
21
+ * Both the ESM (`dist/node/index.mjs`) and CJS (`dist/node/index.cjs`)
22
+ * copies are patched, and the bundler builds (`dist/index.*`) when loaded.
23
+ *
24
+ * Recorded as `decision_type: "llm.google_genai.generate_content"`.
25
+ * `client.chats` sends through the same `Models` instance, so chat sessions
26
+ * are covered. Automatic function calling and automatic continuation make
27
+ * several HTTP requests inside one `generateContent` call; that is one
28
+ * record with the final response's usage (as in Python).
29
+ *
30
+ * Fields read (3.6.1 `GenerateContentResponse`): `usageMetadata`
31
+ * (`promptTokenCount`, `candidatesTokenCount`, `totalTokenCount`,
32
+ * `cachedContentTokenCount`, `thoughtsTokenCount`), `modelVersion`,
33
+ * `responseId`, `candidates[0].finishReason`. Every stream chunk is a
34
+ * `GenerateContentResponse`. No request id is exposed. Request config
35
+ * names are recorded under Python's snake_case names (`top_p`, ...).
36
+ */
37
+ import { tokenUsage } from "../record.js";
38
+ import { TextAccumulator, read, safe } from "../util.js";
39
+ import { StreamState, WRAPPED, callStore, finishWhenCollected, instrumentAsyncIterable, } from "./core.js";
40
+ export const PROVIDER = "google-genai";
41
+ export const PACKAGE = "@google/genai";
42
+ export const VERIFIED_VERSION = "3.6.1";
43
+ export const DECISION_TYPE = "llm.google_genai.generate_content";
44
+ export const SPECIFIERS = ["@google/genai"];
45
+ /** `dist/node` is what Node resolves; `dist/index.*` is what a bundler without the `node` condition picks. */
46
+ export const FILES = [
47
+ { specifier: "@google/genai", rel: "dist/node/index.mjs", format: "esm", group: "node" },
48
+ { specifier: "@google/genai", rel: "dist/node/index.cjs", format: "cjs", group: "node" },
49
+ { specifier: "@google/genai", rel: "dist/index.mjs", format: "esm", group: "default" },
50
+ { specifier: "@google/genai", rel: "dist/index.cjs", format: "cjs", group: "default" },
51
+ ];
52
+ const PARAMS = {
53
+ temperature: "temperature",
54
+ topP: "top_p",
55
+ topK: "top_k",
56
+ maxOutputTokens: "max_output_tokens",
57
+ candidateCount: "candidate_count",
58
+ seed: "seed",
59
+ };
60
+ function configParams(config) {
61
+ const out = {};
62
+ for (const [js, py] of Object.entries(PARAMS)) {
63
+ const value = read(config, js);
64
+ if (typeof value === "number" && Number.isFinite(value))
65
+ out[py] = value;
66
+ }
67
+ return out;
68
+ }
69
+ function usage(meta) {
70
+ return tokenUsage(read(meta, "promptTokenCount"), read(meta, "candidatesTokenCount"), read(meta, "totalTokenCount"), {
71
+ cached_content_token_count: read(meta, "cachedContentTokenCount"),
72
+ thoughts_token_count: read(meta, "thoughtsTokenCount"),
73
+ });
74
+ }
75
+ function firstCandidate(response) {
76
+ const candidates = read(response, "candidates");
77
+ return Array.isArray(candidates) && candidates.length ? candidates[0] : undefined;
78
+ }
79
+ /** Text parts of the first candidate, skipping thoughts (read directly: `.text` warns on non-text parts). */
80
+ function text(response) {
81
+ const parts = read(firstCandidate(response), "content", "parts");
82
+ let out = "";
83
+ for (const part of Array.isArray(parts) ? parts : []) {
84
+ const t = read(part, "text");
85
+ if (typeof t === "string" && !read(part, "thought"))
86
+ out += t;
87
+ }
88
+ return out;
89
+ }
90
+ function info(response, wantContent) {
91
+ const result = {
92
+ model: read(response, "modelVersion"),
93
+ response_id: read(response, "responseId"),
94
+ finish_reason: read(firstCandidate(response), "finishReason"),
95
+ usage: usage(read(response, "usageMetadata")),
96
+ };
97
+ if (wantContent)
98
+ result.content = { content: text(response) };
99
+ return result;
100
+ }
101
+ class GenerateStream extends StreamState {
102
+ inst;
103
+ acc;
104
+ data = {};
105
+ constructor(call, inst) {
106
+ super(call);
107
+ this.inst = inst;
108
+ this.acc = new TextAccumulator(inst.options.maxContentChars);
109
+ }
110
+ observe(chunk) {
111
+ for (const [key, value] of Object.entries(info(chunk, false))) {
112
+ if (value !== undefined && value !== null)
113
+ this.data[key] = value;
114
+ }
115
+ if (this.inst.capturesContent)
116
+ this.acc.add(text(chunk));
117
+ }
118
+ info() {
119
+ const out = { ...this.data };
120
+ if (this.inst.capturesContent)
121
+ out.content = { content: this.acc.text };
122
+ return out;
123
+ }
124
+ }
125
+ function begin(inst, functionName, params, stream) {
126
+ if (!params || typeof params !== "object")
127
+ return null;
128
+ const config = read(params, "config");
129
+ return inst.begin(DECISION_TYPE, functionName, {
130
+ model: read(params, "model"),
131
+ params: configParams(config),
132
+ inputs: () => {
133
+ const out = { contents: read(params, "contents") };
134
+ const system = read(config, "systemInstruction");
135
+ if (system !== undefined)
136
+ out["system_instruction"] = system;
137
+ return out;
138
+ },
139
+ stream,
140
+ });
141
+ }
142
+ /** Runs one non-streamed generate call under `call` and records its result. */
143
+ function runGenerate(inst, call, invoke) {
144
+ let pending;
145
+ try {
146
+ pending = callStore.run(call, invoke);
147
+ }
148
+ catch (error) {
149
+ call.finish({}, { error });
150
+ throw error;
151
+ }
152
+ return Promise.resolve(pending).then((response) => {
153
+ safe(() => call.finish(info(response, inst.capturesContent)), "finish");
154
+ return response;
155
+ }, (error) => {
156
+ call.finish({}, { error });
157
+ throw error;
158
+ });
159
+ }
160
+ /** Runs one streamed generate call under `call`; the SDK's generator is instrumented in place. */
161
+ function runStream(inst, call, invoke) {
162
+ let pending;
163
+ try {
164
+ pending = callStore.run(call, invoke);
165
+ }
166
+ catch (error) {
167
+ call.finish({}, { error });
168
+ throw error;
169
+ }
170
+ return Promise.resolve(pending).then((generator) => {
171
+ safe(() => {
172
+ const state = new GenerateStream(call, inst);
173
+ const ok = instrumentAsyncIterable(generator, { onItem: (chunk) => state.onItem(chunk), onEnd: (kind, error) => state.onEnd(kind, error) },
174
+ // Later hops (automatic continuation / function calling) are requested while the
175
+ // consumer iterates: run them inside the call so they count as covered.
176
+ (fn) => callStore.run(call, fn));
177
+ if (!ok)
178
+ call.finish({}, { stream: { chunk_count: 0, stream_completed: false } });
179
+ else
180
+ finishWhenCollected(generator, call);
181
+ }, "stream instrumentation");
182
+ return generator;
183
+ }, (error) => {
184
+ call.finish({}, { error });
185
+ throw error;
186
+ });
187
+ }
188
+ /**
189
+ * Patch targets for one copy of the package:
190
+ *
191
+ * 1. `generateContent` / `generateContentStream` accessors on
192
+ * `Models.prototype` (see the header): every client constructed after
193
+ * the patch records one record per public call. Each such instance is
194
+ * remembered in `covered`.
195
+ * 2. Clients constructed BEFORE the patch keep the SDK's own, unwrapped
196
+ * instance functions. Those functions do their work through methods
197
+ * that live on the shared `Models.prototype` (read in 3.6.1):
198
+ * non-streamed calls through `generateContentWithContinuation` (which
199
+ * calls `generateContentInternal` once per continuation hop) or
200
+ * `generateContentInternal` directly; streamed calls through
201
+ * `processAfcStream` (default), `generateContentStreamWithContinuation`
202
+ * or `generateContentStreamInternal`. Those five are wrapped. A wrapper
203
+ * records only for an instance that is not in `covered` and only for
204
+ * the outermost of them (an inner one runs inside the outer call's
205
+ * context and passes through), so each public call is one record.
206
+ * Exception, documented: non-streamed automatic function calling
207
+ * calls `generateContentWithContinuation` once per model round from
208
+ * the instance function itself, so a pre-existing client records one
209
+ * record per round there (each with that round's usage).
210
+ */
211
+ export function targets(inst, modules) {
212
+ const Models = modules["@google/genai"]?.["Models"];
213
+ const owner = read(Models, "prototype");
214
+ const fnBase = "google.genai.models";
215
+ const covered = new WeakSet();
216
+ const remember = (instance) => {
217
+ covered.add(instance);
218
+ };
219
+ const generate = {
220
+ kind: "instance-assign",
221
+ owner,
222
+ key: "generateContent",
223
+ label: "@google/genai#Models.generateContent",
224
+ assigned: remember,
225
+ wrap: (original) => function (...args) {
226
+ const call = safe(() => begin(inst, `${fnBase}.generate_content`, args[0], false), "begin") ?? null;
227
+ if (!call)
228
+ return original.apply(this, args);
229
+ call.owner = this;
230
+ return runGenerate(inst, call, () => original.apply(this, args));
231
+ },
232
+ };
233
+ const generateStream = {
234
+ kind: "instance-assign",
235
+ owner,
236
+ key: "generateContentStream",
237
+ label: "@google/genai#Models.generateContentStream",
238
+ assigned: remember,
239
+ wrap: (original) => function (...args) {
240
+ const call = safe(() => begin(inst, `${fnBase}.generate_content_stream`, args[0], true), "begin") ?? null;
241
+ if (!call)
242
+ return original.apply(this, args);
243
+ call.owner = this;
244
+ return runStream(inst, call, () => original.apply(this, args));
245
+ },
246
+ };
247
+ const seam = (key, stream) => ({
248
+ kind: "method",
249
+ owner,
250
+ key,
251
+ label: `@google/genai#Models.${key} (clients created before auto())`,
252
+ wrap: (original) => function (...args) {
253
+ const self = this;
254
+ if (!inst.active || !self || covered.has(self) || callStore.getStore()?.owner === self)
255
+ return original.apply(this, args);
256
+ const name = stream ? `${fnBase}.generate_content_stream` : `${fnBase}.generate_content`;
257
+ const call = safe(() => begin(inst, name, args[0], stream), "begin") ?? null;
258
+ if (!call)
259
+ return original.apply(this, args);
260
+ call.owner = self;
261
+ return stream ? runStream(inst, call, () => original.apply(this, args)) : runGenerate(inst, call, () => original.apply(this, args));
262
+ },
263
+ });
264
+ const verify = () => {
265
+ if (typeof Models !== "function")
266
+ return "Models is not a class";
267
+ const probe = new Models(undefined);
268
+ for (const key of ["generateContent", "generateContentStream"]) {
269
+ const desc = Object.getOwnPropertyDescriptor(probe, key);
270
+ const fn = desc?.value;
271
+ if (!desc || typeof fn !== "function" || !fn[WRAPPED]) {
272
+ return `new Models() did not assign ${key} through the prototype (the SDK defines it differently)`;
273
+ }
274
+ }
275
+ return null;
276
+ };
277
+ return {
278
+ targets: [
279
+ generate,
280
+ generateStream,
281
+ seam("generateContentInternal", false),
282
+ seam("generateContentWithContinuation", false),
283
+ seam("generateContentStreamInternal", true),
284
+ seam("generateContentStreamWithContinuation", true),
285
+ seam("processAfcStream", true),
286
+ ],
287
+ verify,
288
+ };
289
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Instrumentation for the `openai` Node SDK.
3
+ *
4
+ * Verified against openai 7.62.0 (npm), by reading the installed package's
5
+ * `.mjs` / `.js` sources and `.d.ts` types, and by the offline tests in
6
+ * `test/openai.test.ts`.
7
+ *
8
+ * Patch targets (prototype methods; every client instance shares them, so
9
+ * clients created before or after `auto()` are covered). The package ships
10
+ * separate CommonJS (`*.js`) and ESM (`*.mjs`) builds, which Node loads as
11
+ * separate module instances with separate classes, so each target is patched
12
+ * in both copies:
13
+ *
14
+ * | module | class.method | decision_type |
15
+ * |-----------------------------------------|-----------------------|---------------------------|
16
+ * | `openai/resources/chat/completions/completions` | `Completions.create` | `llm.openai.chat` |
17
+ * | `openai/resources/responses/responses` | `Responses.create` | `llm.openai.responses` |
18
+ * | `openai/resources/completions` | `Completions.create` | `llm.openai.completions` |
19
+ * | `openai/resources/embeddings` | `Embeddings.create` | `llm.openai.embeddings` |
20
+ *
21
+ * Layout facts relied on, as found in 7.62.0:
22
+ *
23
+ * - `chat.completions.parse()` calls `client.chat.completions.create()`;
24
+ * `chat.completions.stream()` (ChatCompletionStream) and
25
+ * `responses.stream()` / `responses.parse()` call `create()` too, with
26
+ * `options.__metadata.helperMethod` naming the helper. So they are
27
+ * covered by the `create` patches (one record per HTTP call) and the
28
+ * helper objects (`.on()`, `.finalChatCompletion()`) are untouched.
29
+ * - `create()` returns an `APIPromise` (see `stainless.ts`); with
30
+ * `stream: true` it parses to a `Stream` (chat: after
31
+ * `normalizeChatCompletionStream`, which sets an own
32
+ * `[Symbol.asyncIterator]` that still calls `this.iterator()`).
33
+ * - Usage: `CompletionUsage` (`prompt_tokens`, `completion_tokens`,
34
+ * `total_tokens`, `prompt_tokens_details.cached_tokens`,
35
+ * `completion_tokens_details.reasoning_tokens`) and `ResponseUsage`
36
+ * (`input_tokens`, `output_tokens`, `total_tokens`,
37
+ * `input_tokens_details.cached_tokens`,
38
+ * `output_tokens_details.reasoning_tokens`). The request id is the
39
+ * `x-request-id` response header (also `_request_id` on parsed bodies).
40
+ * - A chat stream carries usage only when the request sets
41
+ * `stream_options: { include_usage: true }`; it is added (on a copy of
42
+ * the request body) only with `auto({ streamUsage: true })`, because it
43
+ * adds a final chunk with empty `choices` to the stream the app reads.
44
+ * - Responses stream events: `response.created` / `response.completed` /
45
+ * `response.incomplete` / `response.failed` carry `response`;
46
+ * `response.output_text.delta` carries `delta`.
47
+ */
48
+ import { type CallInfo, type Instrumentor, type PatchTarget, type ProviderCall, type SdkFile, StreamState } from "./core.js";
49
+ export declare const PROVIDER = "openai";
50
+ export declare const PACKAGE = "openai";
51
+ export declare const VERIFIED_VERSION = "7.62.0";
52
+ interface Surface {
53
+ specifier: string;
54
+ className: string;
55
+ decisionType: string;
56
+ functionBase: string;
57
+ params: readonly string[];
58
+ inputKeys: readonly string[];
59
+ info: (result: unknown, wantContent: boolean) => CallInfo;
60
+ stream?: new (call: ProviderCall, inst: Instrumentor, requestId: string | null) => StreamState;
61
+ streamUsage?: boolean;
62
+ }
63
+ export declare const SURFACES: Surface[];
64
+ /** Builds the patch targets for one module copy (`modules[specifier]` is that copy's namespace). */
65
+ export declare function targets(inst: Instrumentor, modules: Record<string, Record<string, unknown> | undefined>): PatchTarget[];
66
+ export declare const SPECIFIERS: string[];
67
+ export declare const FILES: SdkFile[];
68
+ export {};