@briefcase-ai/auto 0.0.0 → 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.
- package/README.md +103 -0
- package/dist/activate.d.ts +35 -0
- package/dist/activate.js +108 -0
- package/dist/auto.d.ts +92 -0
- package/dist/auto.js +350 -0
- package/dist/context.d.ts +49 -0
- package/dist/context.js +82 -0
- package/dist/detect.d.ts +26 -0
- package/dist/detect.js +127 -0
- package/dist/esbuild.d.ts +40 -0
- package/dist/esbuild.js +55 -0
- package/dist/exporters.d.ts +196 -0
- package/dist/exporters.js +405 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +14 -0
- package/dist/instrument/anthropic.d.ts +40 -0
- package/dist/instrument/anthropic.js +178 -0
- package/dist/instrument/bedrock.d.ts +53 -0
- package/dist/instrument/bedrock.js +256 -0
- package/dist/instrument/core.d.ts +257 -0
- package/dist/instrument/core.js +772 -0
- package/dist/instrument/google-genai.d.ts +71 -0
- package/dist/instrument/google-genai.js +289 -0
- package/dist/instrument/openai.d.ts +68 -0
- package/dist/instrument/openai.js +293 -0
- package/dist/instrument/stainless.d.ts +41 -0
- package/dist/instrument/stainless.js +151 -0
- package/dist/loader.d.ts +79 -0
- package/dist/loader.js +202 -0
- package/dist/observe.d.ts +60 -0
- package/dist/observe.js +246 -0
- package/dist/pipeline.d.ts +48 -0
- package/dist/pipeline.js +155 -0
- package/dist/record.d.ts +54 -0
- package/dist/record.js +55 -0
- package/dist/register.d.ts +9 -0
- package/dist/register.js +12 -0
- package/dist/state.d.ts +25 -0
- package/dist/state.js +29 -0
- package/dist/util.d.ts +51 -0
- package/dist/util.js +198 -0
- package/package.json +84 -1
package/dist/auto.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `auto()`: instrument every installed provider SDK; `instrument()`,
|
|
3
|
+
* `undo()` and `status()`.
|
|
4
|
+
*
|
|
5
|
+
* Same provider names and decision types as Python's `briefcase.auto()`.
|
|
6
|
+
* A package that is not installed is skipped silently; one that is installed
|
|
7
|
+
* but does not have the verified layout is skipped with one warning and is
|
|
8
|
+
* never half-patched. Calling `auto()` again does not wrap anything twice.
|
|
9
|
+
*/
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import * as anthropic from "./instrument/anthropic.js";
|
|
12
|
+
import * as bedrock from "./instrument/bedrock.js";
|
|
13
|
+
import { DEFAULT_OPTIONS, Instrumentor, WRAPPED, loadCopies, normalizeContentMode, packageVersion, requireFile, resolveCopies, } from "./instrument/core.js";
|
|
14
|
+
import * as genai from "./instrument/google-genai.js";
|
|
15
|
+
import * as openai from "./instrument/openai.js";
|
|
16
|
+
import { installDetection } from "./detect.js";
|
|
17
|
+
import { addKnownFile, installLoadHooks, report as reportModule, scanRequireCache, setCopyListener, setWatchedFiles, } from "./loader.js";
|
|
18
|
+
import { state } from "./state.js";
|
|
19
|
+
import { debug, describeError, moduleUrl, read, safe, warn } from "./util.js";
|
|
20
|
+
import { exportStats } from "./observe.js";
|
|
21
|
+
export const PROVIDERS = [
|
|
22
|
+
{ name: openai.PROVIDER, packageName: openai.PACKAGE, verifiedVersion: openai.VERIFIED_VERSION, specifiers: openai.SPECIFIERS, files: openai.FILES, targets: openai.targets },
|
|
23
|
+
{ name: anthropic.PROVIDER, packageName: anthropic.PACKAGE, verifiedVersion: anthropic.VERIFIED_VERSION, specifiers: anthropic.SPECIFIERS, files: anthropic.FILES, targets: anthropic.targets },
|
|
24
|
+
{ name: genai.PROVIDER, packageName: genai.PACKAGE, verifiedVersion: genai.VERIFIED_VERSION, specifiers: genai.SPECIFIERS, files: genai.FILES, targets: genai.targets },
|
|
25
|
+
{ name: bedrock.PROVIDER, packageName: bedrock.PACKAGE, verifiedVersion: bedrock.VERIFIED_VERSION, specifiers: bedrock.SPECIFIERS, files: bedrock.FILES, targets: bedrock.targets },
|
|
26
|
+
];
|
|
27
|
+
export const PROVIDER_NAMES = PROVIDERS.map((p) => p.name);
|
|
28
|
+
export const WATCHED = PROVIDERS.flatMap((spec) => spec.files.map((file) => ({ ...file, provider: spec.name, packageName: spec.packageName })));
|
|
29
|
+
function options(input) {
|
|
30
|
+
const out = {
|
|
31
|
+
...DEFAULT_OPTIONS,
|
|
32
|
+
captureContent: normalizeContentMode(input.captureContent),
|
|
33
|
+
maxContentChars: input.maxContentChars ?? DEFAULT_OPTIONS.maxContentChars,
|
|
34
|
+
streamUsage: input.streamUsage ?? false,
|
|
35
|
+
};
|
|
36
|
+
if (input.redact)
|
|
37
|
+
out.redact = input.redact;
|
|
38
|
+
if (input.contextVersion !== undefined)
|
|
39
|
+
out.contextVersion = input.contextVersion;
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
/** Test seam: replaces how SDK copies are found (and makes auto() load them up front). */
|
|
43
|
+
let copyLoader = null;
|
|
44
|
+
export function setCopyLoaderForTests(loader) {
|
|
45
|
+
copyLoader = loader;
|
|
46
|
+
}
|
|
47
|
+
const localRequire = createRequire(moduleUrl(import.meta.url));
|
|
48
|
+
function copyLabel(copy, inst) {
|
|
49
|
+
let label = copy.format;
|
|
50
|
+
if (copy.origin === "bundle")
|
|
51
|
+
label = `bundle-${copy.format}`;
|
|
52
|
+
else if (copy.origin === "client")
|
|
53
|
+
label = `client-${copy.format}`;
|
|
54
|
+
else if (copy.group !== "main" && copy.group !== "node")
|
|
55
|
+
label = `${copy.format}:${copy.group}`;
|
|
56
|
+
// A second install of the same SDK (another node_modules) gets its root in the label.
|
|
57
|
+
const taken = [...inst.handledCopies].some((key) => key !== copy.key && key.startsWith(`${copy.origin}|${copy.format}|${copy.group}|`));
|
|
58
|
+
return taken ? `${label}@${copy.root}` : label;
|
|
59
|
+
}
|
|
60
|
+
/** Instruments one module copy once all of its files have loaded. Never throws. */
|
|
61
|
+
function applyCopy(copy) {
|
|
62
|
+
safe(() => {
|
|
63
|
+
const report = state().providers.get(copy.provider);
|
|
64
|
+
const inst = report?.instrumentor;
|
|
65
|
+
if (!report || !inst || !inst.active || inst.handledCopies.has(copy.key))
|
|
66
|
+
return;
|
|
67
|
+
const spec = PROVIDERS.find((p) => p.name === copy.provider);
|
|
68
|
+
const needed = copy.origin === "test" || copy.origin === "client"
|
|
69
|
+
? spec.specifiers
|
|
70
|
+
: [...new Set(spec.files.filter((f) => f.format === copy.format && f.group === copy.group).map((f) => f.specifier))];
|
|
71
|
+
if (!needed.every((specifier) => copy.modules[specifier]))
|
|
72
|
+
return; // the rest of this copy has not loaded yet
|
|
73
|
+
const label = copyLabel(copy, inst);
|
|
74
|
+
inst.handledCopies.add(copy.key);
|
|
75
|
+
if (copy.origin !== "client")
|
|
76
|
+
report.sdkVersion ??= packageVersion(copy.file, spec.packageName);
|
|
77
|
+
const built = spec.targets(inst, copy.modules, copy.format);
|
|
78
|
+
const { targets, verify } = Array.isArray(built) ? { targets: built, verify: undefined } : built;
|
|
79
|
+
inst.applyAll(label, targets, verify);
|
|
80
|
+
report.state = report.patched.length > 0 ? "patched" : "skipped";
|
|
81
|
+
debug(`${spec.name}: ${label} ${report.state} (${report.patched.length} target(s), sdk ${report.sdkVersion ?? "unknown"})`);
|
|
82
|
+
}, "apply copy");
|
|
83
|
+
}
|
|
84
|
+
function ensureMachinery() {
|
|
85
|
+
setWatchedFiles(WATCHED);
|
|
86
|
+
setCopyListener(applyCopy);
|
|
87
|
+
installDetection();
|
|
88
|
+
return installLoadHooks();
|
|
89
|
+
}
|
|
90
|
+
/** Starts (or keeps) the instrumentor of one provider; returns null when one is already active. */
|
|
91
|
+
function enable(spec, capture) {
|
|
92
|
+
const providers = state().providers;
|
|
93
|
+
const existing = providers.get(spec.name);
|
|
94
|
+
if (existing?.instrumentor?.active && existing.state !== "skipped")
|
|
95
|
+
return null;
|
|
96
|
+
const inst = new Instrumentor(spec.name, capture, spec.packageName, spec.verifiedVersion);
|
|
97
|
+
const report = inst.report;
|
|
98
|
+
report.state = "not-installed";
|
|
99
|
+
for (const specifier of copyLoader ? [] : spec.specifiers) {
|
|
100
|
+
const paths = safe(() => resolveCopies(specifier), "resolve") ?? null;
|
|
101
|
+
if (!paths)
|
|
102
|
+
continue;
|
|
103
|
+
report.state = "waiting";
|
|
104
|
+
for (const path of [paths.esm, paths.cjs]) {
|
|
105
|
+
if (!path)
|
|
106
|
+
continue;
|
|
107
|
+
report.sdkVersion ??= packageVersion(path, spec.packageName);
|
|
108
|
+
const file = spec.files.find((f) => f.specifier === specifier && f.format === (path === paths.esm ? "esm" : "cjs"));
|
|
109
|
+
if (file)
|
|
110
|
+
addKnownFile(path, { ...file, provider: spec.name, packageName: spec.packageName });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
providers.set(spec.name, report);
|
|
114
|
+
return report;
|
|
115
|
+
}
|
|
116
|
+
/** Loads what is already loaded (or, eager, everything installed) so it reports itself. */
|
|
117
|
+
function catchUp(spec, eager, hooksAtStartup) {
|
|
118
|
+
if (copyLoader) {
|
|
119
|
+
const report = state().providers.get(spec.name);
|
|
120
|
+
for (const specifier of spec.specifiers) {
|
|
121
|
+
const found = copyLoader(specifier);
|
|
122
|
+
if (!found)
|
|
123
|
+
continue;
|
|
124
|
+
if (report.state === "not-installed")
|
|
125
|
+
report.state = "waiting";
|
|
126
|
+
for (const problem of found.problems)
|
|
127
|
+
report.skipped.push({ target: specifier, reason: problem });
|
|
128
|
+
for (const copy of found.copies) {
|
|
129
|
+
const file = { specifier, rel: "", format: copy.format, group: "main", provider: spec.name, packageName: spec.packageName };
|
|
130
|
+
reportModule(copy.format, copy.path, copy.ns, { file, root: `test:${copy.path.slice(0, copy.path.lastIndexOf("/"))}` });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
for (const specifier of spec.specifiers) {
|
|
136
|
+
const paths = safe(() => resolveCopies(specifier), "resolve") ?? null;
|
|
137
|
+
if (!paths)
|
|
138
|
+
continue;
|
|
139
|
+
// Node has no API that says whether an ES module is already loaded. Unless the load hook
|
|
140
|
+
// has watched every load since startup (the preload), ask for the ESM copy: require(esm)
|
|
141
|
+
// returns the loaded instance when there is one, and loads it otherwise.
|
|
142
|
+
const wanted = eager
|
|
143
|
+
? [["esm", paths.esm], ["cjs", paths.cjs]]
|
|
144
|
+
: hooksAtStartup
|
|
145
|
+
? []
|
|
146
|
+
: [["esm", paths.esm]];
|
|
147
|
+
for (const [format, path] of wanted) {
|
|
148
|
+
if (!path)
|
|
149
|
+
continue;
|
|
150
|
+
try {
|
|
151
|
+
reportModule(format, path, requireFile(path));
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
const report = state().providers.get(spec.name);
|
|
155
|
+
report.skipped.push({ target: specifier, reason: `${format} copy could not be loaded (${describeError(error)})` });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Instruments every installed provider SDK (or those named in `only`).
|
|
162
|
+
* Each SDK copy is patched when the application loads it (or now, if it
|
|
163
|
+
* is already loaded); `eager: true` loads and patches every installed copy
|
|
164
|
+
* immediately. Safe to call more than once: a provider that is already
|
|
165
|
+
* instrumented is left as it is. Records are only produced once
|
|
166
|
+
* `observe()` has set a destination.
|
|
167
|
+
*/
|
|
168
|
+
export function auto(input = {}) {
|
|
169
|
+
const capture = options(input);
|
|
170
|
+
const skip = new Set(input.skip ?? []);
|
|
171
|
+
const only = input.only ? new Set(input.only) : null;
|
|
172
|
+
for (const name of [...skip, ...(only ?? [])]) {
|
|
173
|
+
if (!PROVIDER_NAMES.includes(name))
|
|
174
|
+
throw new Error(`Unknown provider: ${JSON.stringify(name)}. Supported: ${PROVIDER_NAMES.join(", ")}`);
|
|
175
|
+
}
|
|
176
|
+
lastCapture = capture;
|
|
177
|
+
const hooked = ensureMachinery();
|
|
178
|
+
const s = state();
|
|
179
|
+
const enabled = [];
|
|
180
|
+
for (const spec of PROVIDERS) {
|
|
181
|
+
if (skip.has(spec.name) || (only && !only.has(spec.name)))
|
|
182
|
+
continue;
|
|
183
|
+
if (enable(spec, capture))
|
|
184
|
+
enabled.push(spec);
|
|
185
|
+
}
|
|
186
|
+
if (enabled.length > 0) {
|
|
187
|
+
if (!copyLoader)
|
|
188
|
+
safe(() => scanRequireCache(localRequire.cache), "require.cache scan");
|
|
189
|
+
for (const spec of enabled)
|
|
190
|
+
catchUp(spec, !!input.eager || !hooked, s.hooksAtStartup && hooked);
|
|
191
|
+
for (const copy of [...s.copies.values()])
|
|
192
|
+
if (!copyLoader || copy.origin === "test")
|
|
193
|
+
applyCopy(copy);
|
|
194
|
+
}
|
|
195
|
+
return status();
|
|
196
|
+
}
|
|
197
|
+
/** Marks the load hook as installed before any application module (called by the preload). */
|
|
198
|
+
export function markStartup() {
|
|
199
|
+
const s = state();
|
|
200
|
+
if (s.loadHooks === "none") {
|
|
201
|
+
s.hooksAtStartup = ensureMachinery();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let lastCapture = null;
|
|
205
|
+
let warnedTarget = false;
|
|
206
|
+
/** Protos and classes found on a client / class, as module namespaces for a provider's `targets()`. */
|
|
207
|
+
function describeTarget(target) {
|
|
208
|
+
const proto = (o) => (o && typeof o === "object" ? Object.getPrototypeOf(o) : null);
|
|
209
|
+
const ns = (className, prototype) => ({ [className]: { prototype } });
|
|
210
|
+
const isFn = (v) => typeof v === "function";
|
|
211
|
+
const t = target;
|
|
212
|
+
if (!t || (typeof t !== "object" && typeof t !== "function"))
|
|
213
|
+
return null;
|
|
214
|
+
// openai: an OpenAI client, or the OpenAI class (its static resource classes).
|
|
215
|
+
const oc = typeof t === "function"
|
|
216
|
+
? [read(t, "Chat", "Completions"), read(t, "Responses"), read(t, "Completions"), read(t, "Embeddings")].map((c) => read(c, "prototype"))
|
|
217
|
+
: [read(t, "chat", "completions"), read(t, "responses"), read(t, "completions"), read(t, "embeddings")].map(proto);
|
|
218
|
+
if (oc.every((p) => p && isFn(read(p, "create")))) {
|
|
219
|
+
const modules = {};
|
|
220
|
+
openai.SURFACES.forEach((surface, i) => (modules[surface.specifier] = ns(surface.className, oc[i])));
|
|
221
|
+
return { provider: openai.PROVIDER, modules, probe: [oc[0], "create"] };
|
|
222
|
+
}
|
|
223
|
+
// @anthropic-ai/sdk: an Anthropic client, or the Anthropic class.
|
|
224
|
+
const ac = typeof t === "function"
|
|
225
|
+
? [read(t, "Messages", "prototype"), read(t, "Beta", "Messages", "prototype")]
|
|
226
|
+
: [proto(read(t, "messages")), proto(read(t, "beta", "messages"))];
|
|
227
|
+
if (ac.every((p) => p && isFn(read(p, "create")))) {
|
|
228
|
+
return {
|
|
229
|
+
provider: anthropic.PROVIDER,
|
|
230
|
+
modules: { [anthropic.SPECIFIERS[0]]: ns("Messages", ac[0]), [anthropic.SPECIFIERS[1]]: ns("Messages", ac[1]) },
|
|
231
|
+
probe: [ac[0], "create"],
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
// @google/genai: a GoogleGenAI client, a Models instance, or the Models class.
|
|
235
|
+
const models = typeof t === "function" ? read(t, "prototype") : isFn(read(t, "generateContentInternal")) ? proto(t) : proto(read(t, "models"));
|
|
236
|
+
if (models && isFn(read(models, "generateContentInternal")) && isFn(read(models, "constructor"))) {
|
|
237
|
+
return { provider: genai.PROVIDER, modules: { [genai.SPECIFIERS[0]]: { Models: read(models, "constructor") } }, probe: [models, "generateContentInternal"] };
|
|
238
|
+
}
|
|
239
|
+
// Bedrock Runtime: a BedrockRuntimeClient / BedrockRuntime client, or one of those classes.
|
|
240
|
+
const instance = typeof t === "function" ? null : t;
|
|
241
|
+
const service = read(instance, "config", "serviceId");
|
|
242
|
+
let p = typeof t === "function" ? read(t, "prototype") : proto(t);
|
|
243
|
+
const isBedrock = typeof t === "function" ? /^BedrockRuntime(Client)?$/.test(String(read(t, "name"))) : service === "Bedrock Runtime";
|
|
244
|
+
if (isBedrock && p) {
|
|
245
|
+
// The prototype just below the one that owns `send` (smithy's Client): BedrockRuntimeClient.prototype.
|
|
246
|
+
while (p && !Object.prototype.hasOwnProperty.call(Object.getPrototypeOf(p) ?? {}, "send"))
|
|
247
|
+
p = Object.getPrototypeOf(p);
|
|
248
|
+
if (p && isFn(read(p, "send"))) {
|
|
249
|
+
return { provider: bedrock.PROVIDER, modules: { [bedrock.SPECIFIERS[0]]: ns("BedrockRuntimeClient", p) }, probe: [p, "send"] };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
const clientCopyIds = new WeakMap();
|
|
255
|
+
let nextClientCopy = 0;
|
|
256
|
+
/**
|
|
257
|
+
* Instruments the SDK copy a client (or client class) belongs to, by its
|
|
258
|
+
* prototypes: for an SDK bundled into the application, or any copy
|
|
259
|
+
* `auto()` cannot reach. Every client of that copy, created before or
|
|
260
|
+
* after, is covered. Returns `target` unchanged. Never throws: an object
|
|
261
|
+
* that is not a supported client is reported once on stderr.
|
|
262
|
+
*
|
|
263
|
+
* Supported: `new OpenAI()` / `OpenAI`, `new Anthropic()` / `Anthropic`,
|
|
264
|
+
* `new GoogleGenAI()` (or its `.models`, or `Models`), and
|
|
265
|
+
* `new BedrockRuntimeClient()` / `new BedrockRuntime()` / either class.
|
|
266
|
+
*/
|
|
267
|
+
export function instrument(target, input = {}) {
|
|
268
|
+
safe(() => {
|
|
269
|
+
const found = describeTarget(target);
|
|
270
|
+
if (!found) {
|
|
271
|
+
if (!warnedTarget) {
|
|
272
|
+
warnedTarget = true;
|
|
273
|
+
warn("instrument(): not a client or client class of a supported SDK (openai, @anthropic-ai/sdk, @google/genai, @aws-sdk/client-bedrock-runtime); nothing was patched.");
|
|
274
|
+
}
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const [probeOwner, probeKey] = found.probe;
|
|
278
|
+
const current = Object.getOwnPropertyDescriptor(probeOwner, probeKey)?.value;
|
|
279
|
+
const report = state().providers.get(found.provider);
|
|
280
|
+
if (current?.[WRAPPED] && report?.instrumentor?.active)
|
|
281
|
+
return; // this copy is already instrumented
|
|
282
|
+
ensureMachinery();
|
|
283
|
+
const spec = PROVIDERS.find((p) => p.name === found.provider);
|
|
284
|
+
const hasOptions = Object.keys(input).length > 0;
|
|
285
|
+
enable(spec, hasOptions || !lastCapture ? options(input) : lastCapture);
|
|
286
|
+
let id = clientCopyIds.get(probeOwner);
|
|
287
|
+
if (!id) {
|
|
288
|
+
id = `client|esm|main|#${++nextClientCopy}`;
|
|
289
|
+
clientCopyIds.set(probeOwner, id);
|
|
290
|
+
}
|
|
291
|
+
applyCopy({
|
|
292
|
+
key: id,
|
|
293
|
+
provider: found.provider,
|
|
294
|
+
packageName: spec.packageName,
|
|
295
|
+
format: "esm",
|
|
296
|
+
group: "main",
|
|
297
|
+
origin: "client",
|
|
298
|
+
root: id,
|
|
299
|
+
file: "",
|
|
300
|
+
modules: found.modules,
|
|
301
|
+
});
|
|
302
|
+
}, "instrument");
|
|
303
|
+
return target;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Restores what `auto()` patched (one provider, or all). A target that
|
|
307
|
+
* someone else re-patched after `auto()` is left in place and listed under
|
|
308
|
+
* `refusedUndo`; our wrapper inside it stops recording.
|
|
309
|
+
*/
|
|
310
|
+
export function undo(name) {
|
|
311
|
+
if (name !== undefined && !PROVIDER_NAMES.includes(name)) {
|
|
312
|
+
throw new Error(`Unknown provider: ${JSON.stringify(name)}. Supported: ${PROVIDER_NAMES.join(", ")}`);
|
|
313
|
+
}
|
|
314
|
+
for (const [key, report] of state().providers) {
|
|
315
|
+
if (name !== undefined && key !== name)
|
|
316
|
+
continue;
|
|
317
|
+
report.instrumentor?.undo();
|
|
318
|
+
}
|
|
319
|
+
return status();
|
|
320
|
+
}
|
|
321
|
+
/** What is patched, what was skipped and why, and the export counters. */
|
|
322
|
+
export function status() {
|
|
323
|
+
const pipeline = state().pipeline;
|
|
324
|
+
const providers = [];
|
|
325
|
+
for (const spec of PROVIDERS) {
|
|
326
|
+
const report = state().providers.get(spec.name);
|
|
327
|
+
if (!report) {
|
|
328
|
+
providers.push({
|
|
329
|
+
name: spec.name,
|
|
330
|
+
state: "not-checked",
|
|
331
|
+
packageName: spec.packageName,
|
|
332
|
+
sdkVersion: null,
|
|
333
|
+
verifiedVersion: spec.verifiedVersion,
|
|
334
|
+
patched: [],
|
|
335
|
+
skipped: [],
|
|
336
|
+
refusedUndo: [],
|
|
337
|
+
unrecordedRequests: 0,
|
|
338
|
+
});
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const { instrumentor: _ignored, ...plain } = report;
|
|
342
|
+
providers.push({ ...plain, patched: [...plain.patched], skipped: [...plain.skipped], refusedUndo: [...plain.refusedUndo] });
|
|
343
|
+
}
|
|
344
|
+
return {
|
|
345
|
+
observing: !!pipeline && !pipeline.closed,
|
|
346
|
+
destination: pipeline && !pipeline.closed ? pipeline.exporter.describe() : null,
|
|
347
|
+
providers,
|
|
348
|
+
stats: exportStats(),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Correlation context carried into every record:
|
|
3
|
+
*
|
|
4
|
+
* - `withWorkflow(name, fn)` runs `fn` inside an AsyncLocalStorage scope, so
|
|
5
|
+
* every provider call made from it (across awaits, timers and streams)
|
|
6
|
+
* carries the same `workflow_id`, the field Python's
|
|
7
|
+
* `briefcase.correlation` workflow writes.
|
|
8
|
+
* - When `@opentelemetry/api` is installed and a span is active, the record
|
|
9
|
+
* carries its W3C trace context as `trace_id`, `parent_span_id` and
|
|
10
|
+
* `trace_flags` (the fields Python's `@capture` writes), so the OTLP
|
|
11
|
+
* exporter can parent the decision span under it.
|
|
12
|
+
*/
|
|
13
|
+
export interface WorkflowContext {
|
|
14
|
+
readonly workflowId: string;
|
|
15
|
+
readonly name: string;
|
|
16
|
+
}
|
|
17
|
+
/** Runs `fn` with a workflow context; returns whatever `fn` returns (a promise stays a promise). */
|
|
18
|
+
export declare function withWorkflow<T>(name: string, fn: () => T, options?: {
|
|
19
|
+
workflowId?: string;
|
|
20
|
+
}): T;
|
|
21
|
+
/** The workflow active in the current async context, if any. */
|
|
22
|
+
export declare function currentWorkflow(): WorkflowContext | undefined;
|
|
23
|
+
interface OtelApi {
|
|
24
|
+
context: {
|
|
25
|
+
active(): unknown;
|
|
26
|
+
};
|
|
27
|
+
trace: {
|
|
28
|
+
getSpan(ctx: unknown): {
|
|
29
|
+
spanContext(): {
|
|
30
|
+
traceId: string;
|
|
31
|
+
spanId: string;
|
|
32
|
+
traceFlags: number;
|
|
33
|
+
};
|
|
34
|
+
} | undefined;
|
|
35
|
+
isSpanContextValid(sc: unknown): boolean;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Loads `@opentelemetry/api` once, at runtime, if it is installed (resolved
|
|
40
|
+
* from the application's directory first, then from this package). The API
|
|
41
|
+
* keeps its global context manager on `globalThis`, so the CommonJS build
|
|
42
|
+
* loaded here sees spans started through the ESM build and vice versa.
|
|
43
|
+
*/
|
|
44
|
+
export declare function loadOtel(): OtelApi | null;
|
|
45
|
+
/** Correlation fields for a record started now. Never throws. */
|
|
46
|
+
export declare function correlationFields(): Record<string, unknown>;
|
|
47
|
+
/** Test hook: forget the cached OpenTelemetry lookup. */
|
|
48
|
+
export declare function resetOtelForTests(api?: OtelApi | null): void;
|
|
49
|
+
export {};
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Correlation context carried into every record:
|
|
3
|
+
*
|
|
4
|
+
* - `withWorkflow(name, fn)` runs `fn` inside an AsyncLocalStorage scope, so
|
|
5
|
+
* every provider call made from it (across awaits, timers and streams)
|
|
6
|
+
* carries the same `workflow_id`, the field Python's
|
|
7
|
+
* `briefcase.correlation` workflow writes.
|
|
8
|
+
* - When `@opentelemetry/api` is installed and a span is active, the record
|
|
9
|
+
* carries its W3C trace context as `trace_id`, `parent_span_id` and
|
|
10
|
+
* `trace_flags` (the fields Python's `@capture` writes), so the OTLP
|
|
11
|
+
* exporter can parent the decision span under it.
|
|
12
|
+
*/
|
|
13
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
|
+
import { randomBytes } from "node:crypto";
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { debug, moduleUrl } from "./util.js";
|
|
18
|
+
const storage = new AsyncLocalStorage();
|
|
19
|
+
/** Runs `fn` with a workflow context; returns whatever `fn` returns (a promise stays a promise). */
|
|
20
|
+
export function withWorkflow(name, fn, options = {}) {
|
|
21
|
+
const context = {
|
|
22
|
+
workflowId: options.workflowId ?? `wf_${randomBytes(6).toString("hex")}`,
|
|
23
|
+
name,
|
|
24
|
+
};
|
|
25
|
+
return storage.run(context, fn);
|
|
26
|
+
}
|
|
27
|
+
/** The workflow active in the current async context, if any. */
|
|
28
|
+
export function currentWorkflow() {
|
|
29
|
+
return storage.getStore();
|
|
30
|
+
}
|
|
31
|
+
let otel;
|
|
32
|
+
/**
|
|
33
|
+
* Loads `@opentelemetry/api` once, at runtime, if it is installed (resolved
|
|
34
|
+
* from the application's directory first, then from this package). The API
|
|
35
|
+
* keeps its global context manager on `globalThis`, so the CommonJS build
|
|
36
|
+
* loaded here sees spans started through the ESM build and vice versa.
|
|
37
|
+
*/
|
|
38
|
+
export function loadOtel() {
|
|
39
|
+
if (otel !== undefined)
|
|
40
|
+
return otel;
|
|
41
|
+
otel = null;
|
|
42
|
+
for (const base of [join(process.cwd(), "noop.js"), moduleUrl(import.meta.url)]) {
|
|
43
|
+
try {
|
|
44
|
+
const mod = createRequire(base)("@opentelemetry/api");
|
|
45
|
+
if (mod && mod.trace && mod.context) {
|
|
46
|
+
otel = mod;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// not installed there
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return otel;
|
|
55
|
+
}
|
|
56
|
+
/** Correlation fields for a record started now. Never throws. */
|
|
57
|
+
export function correlationFields() {
|
|
58
|
+
const out = {};
|
|
59
|
+
try {
|
|
60
|
+
const workflow = storage.getStore();
|
|
61
|
+
if (workflow)
|
|
62
|
+
out["workflow_id"] = workflow.workflowId;
|
|
63
|
+
const api = loadOtel();
|
|
64
|
+
if (api) {
|
|
65
|
+
const span = api.trace.getSpan(api.context.active());
|
|
66
|
+
const sc = span?.spanContext();
|
|
67
|
+
if (sc && api.trace.isSpanContextValid(sc)) {
|
|
68
|
+
out["trace_id"] = sc.traceId;
|
|
69
|
+
out["parent_span_id"] = sc.spanId;
|
|
70
|
+
out["trace_flags"] = sc.traceFlags;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
debug(`correlation lookup failed: ${String(error)}`);
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** Test hook: forget the cached OpenTelemetry lookup. */
|
|
80
|
+
export function resetOtelForTests(api) {
|
|
81
|
+
otel = api === undefined ? undefined : api;
|
|
82
|
+
}
|
package/dist/detect.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notices provider requests that were NOT recorded: a request made by an
|
|
3
|
+
* SDK copy this package did not patch (an SDK bundled into the application
|
|
4
|
+
* without the esbuild plugin, a copy loaded some other way). It warns once
|
|
5
|
+
* per provider and counts them in `status().providers[i].unrecordedRequests`.
|
|
6
|
+
*
|
|
7
|
+
* Seams: Node's built-in diagnostics channels, which only observe:
|
|
8
|
+
* `undici:request:create` (global `fetch`: openai, @anthropic-ai/sdk,
|
|
9
|
+
* @google/genai), `http.client.request.created` and
|
|
10
|
+
* `http2.client.stream.created` (the AWS SDK's Node handlers; Bedrock
|
|
11
|
+
* Runtime 3.1175.0 uses HTTP/2). A request counts as recorded when it is
|
|
12
|
+
* made inside a call our wrappers are recording (`callStore`).
|
|
13
|
+
*
|
|
14
|
+
* Fingerprints, as sent by the verified versions (read from a local test
|
|
15
|
+
* server): Stainless SDKs send `x-stainless-lang`; Anthropic also sends
|
|
16
|
+
* `anthropic-version`, OpenAI a `User-Agent` of `OpenAI/JS <version>`
|
|
17
|
+
* (`<constructor name>/JS`). @google/genai sends `x-goog-api-client:
|
|
18
|
+
* google-genai-sdk/<version>`; the AWS SDK sends `api/bedrock-runtime#<version>`
|
|
19
|
+
* in its user agent. Only the endpoints this package records are counted.
|
|
20
|
+
* A request made with a custom `fetch` is invisible here.
|
|
21
|
+
*/
|
|
22
|
+
type Getter = (name: string) => string | undefined;
|
|
23
|
+
export declare function classify(get: Getter, path: string): string | null;
|
|
24
|
+
/** Subscribes once per thread. The handlers never throw. */
|
|
25
|
+
export declare function installDetection(): void;
|
|
26
|
+
export {};
|
package/dist/detect.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notices provider requests that were NOT recorded: a request made by an
|
|
3
|
+
* SDK copy this package did not patch (an SDK bundled into the application
|
|
4
|
+
* without the esbuild plugin, a copy loaded some other way). It warns once
|
|
5
|
+
* per provider and counts them in `status().providers[i].unrecordedRequests`.
|
|
6
|
+
*
|
|
7
|
+
* Seams: Node's built-in diagnostics channels, which only observe:
|
|
8
|
+
* `undici:request:create` (global `fetch`: openai, @anthropic-ai/sdk,
|
|
9
|
+
* @google/genai), `http.client.request.created` and
|
|
10
|
+
* `http2.client.stream.created` (the AWS SDK's Node handlers; Bedrock
|
|
11
|
+
* Runtime 3.1175.0 uses HTTP/2). A request counts as recorded when it is
|
|
12
|
+
* made inside a call our wrappers are recording (`callStore`).
|
|
13
|
+
*
|
|
14
|
+
* Fingerprints, as sent by the verified versions (read from a local test
|
|
15
|
+
* server): Stainless SDKs send `x-stainless-lang`; Anthropic also sends
|
|
16
|
+
* `anthropic-version`, OpenAI a `User-Agent` of `OpenAI/JS <version>`
|
|
17
|
+
* (`<constructor name>/JS`). @google/genai sends `x-goog-api-client:
|
|
18
|
+
* google-genai-sdk/<version>`; the AWS SDK sends `api/bedrock-runtime#<version>`
|
|
19
|
+
* in its user agent. Only the endpoints this package records are counted.
|
|
20
|
+
* A request made with a custom `fetch` is invisible here.
|
|
21
|
+
*/
|
|
22
|
+
import { subscribe } from "node:diagnostics_channel";
|
|
23
|
+
import { callStore } from "./instrument/core.js";
|
|
24
|
+
import { state } from "./state.js";
|
|
25
|
+
import { safe, warn } from "./util.js";
|
|
26
|
+
export function classify(get, path) {
|
|
27
|
+
if (get("x-stainless-lang") !== undefined) {
|
|
28
|
+
if (get("anthropic-version") !== undefined)
|
|
29
|
+
return /\/v1\/messages(\?|$)/.test(path) ? "anthropic" : null;
|
|
30
|
+
const ua = get("user-agent") ?? "";
|
|
31
|
+
// `<constructor name>/JS`: OpenAI, AzureOpenAI, or a short minified name.
|
|
32
|
+
if (!/^(?:Azure)?OpenAI\/JS |^[A-Za-z_$][\w$]{0,2}\/JS /.test(ua))
|
|
33
|
+
return null;
|
|
34
|
+
return /\/(?:chat\/completions|responses|completions|embeddings)(\?|$)/.test(path) ? "openai" : null;
|
|
35
|
+
}
|
|
36
|
+
if ((get("x-goog-api-client") ?? "").includes("google-genai-sdk/")) {
|
|
37
|
+
return /:(?:generateContent|streamGenerateContent)(\?|$)/.test(path) ? "google-genai" : null;
|
|
38
|
+
}
|
|
39
|
+
const ua = `${get("x-amz-user-agent") ?? ""} ${get("user-agent") ?? ""}`;
|
|
40
|
+
if (ua.includes("api/bedrock-runtime")) {
|
|
41
|
+
return /\/model\/[^/]+\/(?:converse|converse-stream|invoke|invoke-with-response-stream)(\?|$)/.test(path) ? "bedrock" : null;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const warned = new Set();
|
|
46
|
+
function seen(provider) {
|
|
47
|
+
if (!provider)
|
|
48
|
+
return;
|
|
49
|
+
const recording = callStore.getStore();
|
|
50
|
+
if (recording && recording.provider === provider)
|
|
51
|
+
return;
|
|
52
|
+
const s = state();
|
|
53
|
+
const pipeline = s.pipeline;
|
|
54
|
+
if (!pipeline || pipeline.closed)
|
|
55
|
+
return;
|
|
56
|
+
const report = s.providers.get(provider);
|
|
57
|
+
// Only for providers auto() was asked to cover and that were not undone or skipped by the layout check.
|
|
58
|
+
if (!report || report.state === "undone" || report.state === "skipped" || !report.instrumentor?.active)
|
|
59
|
+
return;
|
|
60
|
+
report.unrecordedRequests = (report.unrecordedRequests ?? 0) + 1;
|
|
61
|
+
if (warned.has(provider))
|
|
62
|
+
return;
|
|
63
|
+
warned.add(provider);
|
|
64
|
+
warn(`a request through the ${provider} SDK was made by a copy of the SDK that is not instrumented, so it was not recorded ` +
|
|
65
|
+
"(usually an SDK bundled into the application). Use the @briefcase-ai/auto/esbuild plugin, keep the SDK " +
|
|
66
|
+
"external to the bundle, or call instrument(client). Counted in status().providers[].unrecordedRequests.");
|
|
67
|
+
}
|
|
68
|
+
function headerArray(headers) {
|
|
69
|
+
return (name) => {
|
|
70
|
+
if (Array.isArray(headers)) {
|
|
71
|
+
for (let i = 0; i + 1 < headers.length; i += 2) {
|
|
72
|
+
if (String(headers[i]).toLowerCase() === name)
|
|
73
|
+
return String(headers[i + 1]);
|
|
74
|
+
}
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
if (typeof headers === "string") {
|
|
78
|
+
for (const line of headers.split("\r\n")) {
|
|
79
|
+
const colon = line.indexOf(":");
|
|
80
|
+
if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === name)
|
|
81
|
+
return line.slice(colon + 1).trim();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Subscribes once per thread. The handlers never throw. */
|
|
88
|
+
export function installDetection() {
|
|
89
|
+
const s = state();
|
|
90
|
+
if (s.detecting)
|
|
91
|
+
return;
|
|
92
|
+
s.detecting = true;
|
|
93
|
+
safe(() => {
|
|
94
|
+
subscribe("undici:request:create", (message) => {
|
|
95
|
+
safe(() => {
|
|
96
|
+
const request = message.request;
|
|
97
|
+
if (!request)
|
|
98
|
+
return;
|
|
99
|
+
seen(classify(headerArray(request.headers), String(request.path ?? "")));
|
|
100
|
+
}, "request detection");
|
|
101
|
+
});
|
|
102
|
+
subscribe("http.client.request.created", (message) => {
|
|
103
|
+
safe(() => {
|
|
104
|
+
const request = message.request;
|
|
105
|
+
if (!request || typeof request.getHeader !== "function")
|
|
106
|
+
return;
|
|
107
|
+
const get = (name) => {
|
|
108
|
+
const v = request.getHeader(name);
|
|
109
|
+
return v === undefined ? undefined : String(v);
|
|
110
|
+
};
|
|
111
|
+
seen(classify(get, String(request.path ?? "")));
|
|
112
|
+
}, "request detection");
|
|
113
|
+
});
|
|
114
|
+
subscribe("http2.client.stream.created", (message) => {
|
|
115
|
+
safe(() => {
|
|
116
|
+
const headers = message.headers;
|
|
117
|
+
if (!headers)
|
|
118
|
+
return;
|
|
119
|
+
const get = (name) => {
|
|
120
|
+
const v = headers[name];
|
|
121
|
+
return v === undefined ? undefined : String(v);
|
|
122
|
+
};
|
|
123
|
+
seen(classify(get, String(headers[":path"] ?? "")));
|
|
124
|
+
}, "request detection");
|
|
125
|
+
});
|
|
126
|
+
}, "detection");
|
|
127
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
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
|
+
/** The npm packages this package instruments (for `external: SDK_PACKAGES`). */
|
|
22
|
+
export declare const SDK_PACKAGES: string[];
|
|
23
|
+
/** The subset of esbuild's plugin API this plugin uses (no type dependency on esbuild). */
|
|
24
|
+
export interface EsbuildPluginBuild {
|
|
25
|
+
onLoad(options: {
|
|
26
|
+
filter: RegExp;
|
|
27
|
+
namespace?: string;
|
|
28
|
+
}, callback: (args: {
|
|
29
|
+
path: string;
|
|
30
|
+
}) => Promise<{
|
|
31
|
+
contents: string;
|
|
32
|
+
loader: "js";
|
|
33
|
+
resolveDir: string;
|
|
34
|
+
} | undefined>): void;
|
|
35
|
+
}
|
|
36
|
+
export interface EsbuildPlugin {
|
|
37
|
+
name: string;
|
|
38
|
+
setup(build: EsbuildPluginBuild): void;
|
|
39
|
+
}
|
|
40
|
+
export declare function briefcaseAuto(): EsbuildPlugin;
|