@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.
- package/README.md +102 -2
- 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 +82 -4
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared machinery for provider instrumentation (the TypeScript counterpart
|
|
3
|
+
* of `briefcase/integrations/providers/_base.py`):
|
|
4
|
+
*
|
|
5
|
+
* - `Instrumentor`: owns the patches of one provider. Every target of a
|
|
6
|
+
* module copy is checked before any is applied, so an SDK whose layout
|
|
7
|
+
* differs from the verified one is skipped whole (one warning), never
|
|
8
|
+
* half-patched. `undo()` restores an original only while our wrapper is
|
|
9
|
+
* still the installed value; a later patch by someone else is left alone.
|
|
10
|
+
* - `ProviderCall`: one call in flight; `finish()` emits exactly one record
|
|
11
|
+
* and never throws.
|
|
12
|
+
* - `observeAsyncIterator`: reports the items and the end of an async
|
|
13
|
+
* iterator without changing what the consumer sees.
|
|
14
|
+
* - `loadCopies`: the ESM and CommonJS copies of an SDK (dual packages load
|
|
15
|
+
* them as separate module instances, with separate classes).
|
|
16
|
+
*/
|
|
17
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
18
|
+
import { createRequire } from "node:module";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
22
|
+
import { startRecord } from "../record.js";
|
|
23
|
+
import { state } from "../state.js";
|
|
24
|
+
import { DEFAULT_MAX_CONTENT_CHARS, asInt, debug, describeError, isoTimestamp, moduleUrl, jsonable, read, safe, sha256Hex, stableText, typeName, warn, } from "../util.js";
|
|
25
|
+
export function normalizeContentMode(value) {
|
|
26
|
+
if (value === undefined || value === null || value === false)
|
|
27
|
+
return "none";
|
|
28
|
+
if (value === true)
|
|
29
|
+
return "full";
|
|
30
|
+
if (value === "none" || value === "hash" || value === "full")
|
|
31
|
+
return value;
|
|
32
|
+
throw new Error(`captureContent must be a boolean or one of "none", "hash", "full"; got ${JSON.stringify(value)}`);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The call being recorded in the current async context. Wrappers run the
|
|
36
|
+
* SDK's own method inside it, so nested SDK internals can tell they are
|
|
37
|
+
* already covered and the request detector (`detect.ts`) can tell a
|
|
38
|
+
* recorded request from one made through an uninstrumented SDK copy.
|
|
39
|
+
*/
|
|
40
|
+
export const callStore = new AsyncLocalStorage();
|
|
41
|
+
/** Runs `fn` inside `call`'s context (no-op wrapper when `call` is null). */
|
|
42
|
+
export function within(call, fn) {
|
|
43
|
+
return call ? callStore.run(call, fn) : fn();
|
|
44
|
+
}
|
|
45
|
+
/** Marker on every wrapper we install; holds the wrapped original. */
|
|
46
|
+
export const WRAPPED = Symbol.for("briefcase-ai.auto.wrapped");
|
|
47
|
+
function markWrapper(wrapper, original) {
|
|
48
|
+
Object.defineProperty(wrapper, WRAPPED, { value: original });
|
|
49
|
+
safe(() => Object.defineProperty(wrapper, "name", { value: original.name, configurable: true }));
|
|
50
|
+
safe(() => Object.defineProperty(wrapper, "length", { value: original.length, configurable: true }));
|
|
51
|
+
}
|
|
52
|
+
export class Instrumentor {
|
|
53
|
+
provider;
|
|
54
|
+
options;
|
|
55
|
+
active = true;
|
|
56
|
+
applied = [];
|
|
57
|
+
/** Module copies (see `loader.ts`) this instrumentor has already handled. */
|
|
58
|
+
handledCopies = new Set();
|
|
59
|
+
report;
|
|
60
|
+
constructor(provider, options, packageName, verifiedVersion) {
|
|
61
|
+
this.provider = provider;
|
|
62
|
+
this.options = options;
|
|
63
|
+
this.report = {
|
|
64
|
+
name: provider,
|
|
65
|
+
state: "skipped",
|
|
66
|
+
packageName,
|
|
67
|
+
sdkVersion: null,
|
|
68
|
+
verifiedVersion,
|
|
69
|
+
patched: [],
|
|
70
|
+
skipped: [],
|
|
71
|
+
refusedUndo: [],
|
|
72
|
+
unrecordedRequests: 0,
|
|
73
|
+
instrumentor: this,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
get capturesContent() {
|
|
77
|
+
return this.options.captureContent !== "none";
|
|
78
|
+
}
|
|
79
|
+
/** Checks one target; returns why it cannot be patched, or null. */
|
|
80
|
+
problem(target) {
|
|
81
|
+
const owner = target.owner;
|
|
82
|
+
if (!owner || (typeof owner !== "object" && typeof owner !== "function"))
|
|
83
|
+
return "owner not found";
|
|
84
|
+
const desc = Object.getOwnPropertyDescriptor(owner, target.key);
|
|
85
|
+
if (target.kind === "method") {
|
|
86
|
+
const fn = desc ? desc.value : target.inherited ? owner[target.key] : undefined;
|
|
87
|
+
if (!desc && !target.inherited)
|
|
88
|
+
return `${target.key} not found`;
|
|
89
|
+
if (typeof fn !== "function")
|
|
90
|
+
return `${target.key} is not a method`;
|
|
91
|
+
if (fn[WRAPPED])
|
|
92
|
+
return "already instrumented";
|
|
93
|
+
if (desc && !desc.configurable && !desc.writable)
|
|
94
|
+
return `${target.key} is read-only`;
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
if (desc) {
|
|
98
|
+
if (desc.get && desc.get[WRAPPED])
|
|
99
|
+
return "already instrumented";
|
|
100
|
+
return `${target.key} is already defined on the prototype`;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Applies every target, or none: if any target is missing or reshaped the
|
|
106
|
+
* whole set is skipped with one warning. Returns true when applied.
|
|
107
|
+
*/
|
|
108
|
+
applyAll(copy, targets, verify) {
|
|
109
|
+
const problems = targets
|
|
110
|
+
.map((t) => [t, this.problem(t)])
|
|
111
|
+
.filter((entry) => entry[1] !== null);
|
|
112
|
+
if (problems.length > 0) {
|
|
113
|
+
const already = problems.every(([, p]) => p === "already instrumented");
|
|
114
|
+
const reason = problems.map(([t, p]) => `${t.label}: ${p}`).join("; ");
|
|
115
|
+
for (const [t, p] of problems)
|
|
116
|
+
this.report.skipped.push({ target: `${copy} ${t.label}`, reason: p });
|
|
117
|
+
if (!already) {
|
|
118
|
+
warn(`${this.provider} (${copy}): the installed SDK does not have the layout this version was verified ` +
|
|
119
|
+
`against (${this.report.packageName} ${this.report.verifiedVersion}); nothing in this copy was patched. ${reason}`);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
debug(`${this.provider} (${copy}): already instrumented; not wrapping again`);
|
|
123
|
+
}
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const start = this.applied.length;
|
|
127
|
+
try {
|
|
128
|
+
for (const target of targets)
|
|
129
|
+
this.applyOne(target, copy);
|
|
130
|
+
const failed = verify ? verify() : null;
|
|
131
|
+
if (failed)
|
|
132
|
+
throw new Error(failed);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
this.rollback(start);
|
|
136
|
+
const reason = describeError(error);
|
|
137
|
+
this.report.skipped.push({ target: `${copy} ${targets.map((t) => t.label).join(", ")}`, reason });
|
|
138
|
+
warn(`${this.provider} (${copy}): could not be instrumented (${reason}); nothing in this copy was patched.`);
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
for (const target of targets)
|
|
142
|
+
this.report.patched.push(`${copy} ${target.label}`);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
applyOne(target, copy) {
|
|
146
|
+
const owner = target.owner;
|
|
147
|
+
const original = Object.getOwnPropertyDescriptor(owner, target.key);
|
|
148
|
+
let installed;
|
|
149
|
+
if (target.kind === "method") {
|
|
150
|
+
const fn = (original ? original.value : owner[target.key]);
|
|
151
|
+
const wrapper = target.wrap(fn);
|
|
152
|
+
markWrapper(wrapper, fn);
|
|
153
|
+
installed = original
|
|
154
|
+
? { ...original, value: wrapper }
|
|
155
|
+
: { value: wrapper, writable: true, configurable: true, enumerable: false };
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
const wrap = target.wrap;
|
|
159
|
+
const assigned = target.assigned;
|
|
160
|
+
const inst = this;
|
|
161
|
+
const key = target.key;
|
|
162
|
+
const get = function () {
|
|
163
|
+
return undefined;
|
|
164
|
+
};
|
|
165
|
+
const set = function (value) {
|
|
166
|
+
let stored = value;
|
|
167
|
+
if (typeof value === "function" && inst.active) {
|
|
168
|
+
const original = value;
|
|
169
|
+
const wrapper = wrap(original);
|
|
170
|
+
markWrapper(wrapper, original);
|
|
171
|
+
stored = wrapper;
|
|
172
|
+
if (assigned)
|
|
173
|
+
safe(() => assigned(this), "assigned hook");
|
|
174
|
+
}
|
|
175
|
+
Object.defineProperty(this, key, { value: stored, writable: true, enumerable: true, configurable: true });
|
|
176
|
+
};
|
|
177
|
+
Object.defineProperty(get, WRAPPED, { value: true });
|
|
178
|
+
installed = { get, set, enumerable: false, configurable: true };
|
|
179
|
+
}
|
|
180
|
+
Object.defineProperty(owner, target.key, installed);
|
|
181
|
+
this.applied.push({ owner, key: target.key, label: `${copy} ${target.label}`, original, installed });
|
|
182
|
+
}
|
|
183
|
+
rollback(start) {
|
|
184
|
+
while (this.applied.length > start) {
|
|
185
|
+
const patch = this.applied.pop();
|
|
186
|
+
safe(() => {
|
|
187
|
+
if (patch.original)
|
|
188
|
+
Object.defineProperty(patch.owner, patch.key, patch.original);
|
|
189
|
+
else
|
|
190
|
+
delete patch.owner[patch.key];
|
|
191
|
+
}, "rollback");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Restores each original whose slot still holds our wrapper. A slot that
|
|
196
|
+
* now holds something else (another tool patched it after us) is left as
|
|
197
|
+
* it is; our wrapper inside it is switched to pass-through.
|
|
198
|
+
*/
|
|
199
|
+
undo() {
|
|
200
|
+
this.active = false;
|
|
201
|
+
const restored = [];
|
|
202
|
+
const refused = [];
|
|
203
|
+
while (this.applied.length > 0) {
|
|
204
|
+
const patch = this.applied.pop();
|
|
205
|
+
const current = Object.getOwnPropertyDescriptor(patch.owner, patch.key);
|
|
206
|
+
const ours = current !== undefined &&
|
|
207
|
+
(current.value !== undefined ? current.value === patch.installed.value : current.get === patch.installed.get);
|
|
208
|
+
if (!ours) {
|
|
209
|
+
refused.push(patch.label);
|
|
210
|
+
warn(`undo: ${patch.label} was replaced by someone else after auto(); leaving their patch in place ` +
|
|
211
|
+
"(the briefcase wrapper underneath now passes calls straight through).");
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
if (patch.original)
|
|
216
|
+
Object.defineProperty(patch.owner, patch.key, patch.original);
|
|
217
|
+
else
|
|
218
|
+
delete patch.owner[patch.key];
|
|
219
|
+
restored.push(patch.label);
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
refused.push(patch.label);
|
|
223
|
+
warn(`undo: could not restore ${patch.label} (${describeError(error)})`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
this.report.refusedUndo.push(...refused);
|
|
227
|
+
this.report.patched = [];
|
|
228
|
+
this.report.state = "undone";
|
|
229
|
+
return { restored, refused };
|
|
230
|
+
}
|
|
231
|
+
/** Starts a record, or returns null when nothing is exporting (the call then runs untouched). */
|
|
232
|
+
begin(decisionType, functionName, request) {
|
|
233
|
+
try {
|
|
234
|
+
if (!this.active)
|
|
235
|
+
return null;
|
|
236
|
+
const pipeline = state().pipeline;
|
|
237
|
+
if (!pipeline || pipeline.closed)
|
|
238
|
+
return null;
|
|
239
|
+
const { record, startedEpochMs, t0 } = startRecord(decisionType, functionName, this.options.contextVersion);
|
|
240
|
+
if (request.inputs && this.capturesContent) {
|
|
241
|
+
try {
|
|
242
|
+
record.inputs = asObject(this.content(jsonable(request.inputs(), this.options.maxContentChars)));
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
debug(`inputs could not be captured: ${describeError(error)}`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const model = typeof request.model === "string" && request.model ? request.model : null;
|
|
249
|
+
return new ProviderCall(this, record, startedEpochMs, t0, model, request.params ?? {}, request.stream ?? false);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
debug(`capture could not start: ${describeError(error)}`);
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** Applies the content mode to an inputs / outputs value (Python's CaptureOptions.content). */
|
|
257
|
+
content(value) {
|
|
258
|
+
const mode = this.options.captureContent;
|
|
259
|
+
if (mode === "none")
|
|
260
|
+
return {};
|
|
261
|
+
if (mode === "hash") {
|
|
262
|
+
if (value === null || value === undefined || value === "" || isEmpty(value))
|
|
263
|
+
return {};
|
|
264
|
+
const text = stableText(value);
|
|
265
|
+
return { sha256: sha256Hex(text), chars: text.length };
|
|
266
|
+
}
|
|
267
|
+
const redact = this.options.redact;
|
|
268
|
+
return redact ? redactDeep(value, redact) : value;
|
|
269
|
+
}
|
|
270
|
+
errorText(error) {
|
|
271
|
+
const cls = errorClass(error);
|
|
272
|
+
const mode = this.options.captureContent;
|
|
273
|
+
if (mode === "none")
|
|
274
|
+
return cls;
|
|
275
|
+
const message = errorMessage(error);
|
|
276
|
+
if (mode === "hash")
|
|
277
|
+
return `${cls}:sha256:${sha256Hex(message)}`;
|
|
278
|
+
const text = message || cls;
|
|
279
|
+
const redacted = this.options.redact ? redactString(text, this.options.redact) : text;
|
|
280
|
+
return redacted.slice(0, this.options.maxContentChars);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function isEmpty(value) {
|
|
284
|
+
if (Array.isArray(value))
|
|
285
|
+
return value.length === 0;
|
|
286
|
+
if (value && typeof value === "object")
|
|
287
|
+
return Object.keys(value).length === 0;
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
function asObject(value) {
|
|
291
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : { content: value };
|
|
292
|
+
}
|
|
293
|
+
function redactString(text, redact) {
|
|
294
|
+
try {
|
|
295
|
+
const out = redact(text);
|
|
296
|
+
return typeof out === "string" ? out : "<redaction-failed>";
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return "<redaction-failed>";
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function redactDeep(value, redact) {
|
|
303
|
+
if (typeof value === "string")
|
|
304
|
+
return redactString(value, redact);
|
|
305
|
+
if (Array.isArray(value))
|
|
306
|
+
return value.map((v) => redactDeep(v, redact));
|
|
307
|
+
if (value && typeof value === "object") {
|
|
308
|
+
const out = {};
|
|
309
|
+
for (const [k, v] of Object.entries(value))
|
|
310
|
+
out[k] = redactDeep(v, redact);
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
return value;
|
|
314
|
+
}
|
|
315
|
+
/** Class name of a thrown value (Python's `type(error).__name__`). */
|
|
316
|
+
export function errorClass(error) {
|
|
317
|
+
const cls = typeName(error);
|
|
318
|
+
const name = read(error, "name");
|
|
319
|
+
if ((cls === "Error" || cls === "DOMException" || cls === "object") && typeof name === "string" && name)
|
|
320
|
+
return name;
|
|
321
|
+
return cls;
|
|
322
|
+
}
|
|
323
|
+
function errorMessage(error) {
|
|
324
|
+
const message = read(error, "message");
|
|
325
|
+
return typeof message === "string" ? message : String(error);
|
|
326
|
+
}
|
|
327
|
+
export function isAbortError(error) {
|
|
328
|
+
const cls = errorClass(error);
|
|
329
|
+
return cls === "AbortError" || /Abort/.test(cls) || read(error, "name") === "AbortError";
|
|
330
|
+
}
|
|
331
|
+
export class ProviderCall {
|
|
332
|
+
inst;
|
|
333
|
+
record;
|
|
334
|
+
startedEpochMs;
|
|
335
|
+
t0;
|
|
336
|
+
model;
|
|
337
|
+
params;
|
|
338
|
+
stream;
|
|
339
|
+
done = false;
|
|
340
|
+
/** The SDK object whose method started this call (used to recognise nested internal calls). */
|
|
341
|
+
owner = undefined;
|
|
342
|
+
firstChunkMs = null;
|
|
343
|
+
/** What the record says if the call is abandoned (process exit) before it finishes. */
|
|
344
|
+
fallback = {};
|
|
345
|
+
chunks = 0;
|
|
346
|
+
constructor(inst, record, startedEpochMs, t0, model, params, stream) {
|
|
347
|
+
this.inst = inst;
|
|
348
|
+
this.record = record;
|
|
349
|
+
this.startedEpochMs = startedEpochMs;
|
|
350
|
+
this.t0 = t0;
|
|
351
|
+
this.model = model;
|
|
352
|
+
this.params = params;
|
|
353
|
+
this.stream = stream;
|
|
354
|
+
state().pending.add(this);
|
|
355
|
+
}
|
|
356
|
+
get provider() {
|
|
357
|
+
return this.inst.provider;
|
|
358
|
+
}
|
|
359
|
+
markStream() {
|
|
360
|
+
this.stream = true;
|
|
361
|
+
}
|
|
362
|
+
firstChunk() {
|
|
363
|
+
if (this.firstChunkMs === null)
|
|
364
|
+
this.firstChunkMs = performance.now() - this.t0;
|
|
365
|
+
}
|
|
366
|
+
/** Emits the record now, as an unfinished call (stream never read to the end). */
|
|
367
|
+
abandon() {
|
|
368
|
+
this.finish(this.fallback, this.stream ? { stream: { chunk_count: this.chunks, stream_completed: false } } : {});
|
|
369
|
+
}
|
|
370
|
+
/** Completes and exports the record exactly once. Never throws. */
|
|
371
|
+
finish(info = {}, outcome = {}) {
|
|
372
|
+
if (this.done)
|
|
373
|
+
return;
|
|
374
|
+
this.done = true;
|
|
375
|
+
state().pending.delete(this);
|
|
376
|
+
try {
|
|
377
|
+
this.build(info, outcome);
|
|
378
|
+
state().pipeline?.enqueue(this.record);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
debug(`record could not be completed: ${describeError(error)}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
build(info, outcome) {
|
|
385
|
+
const inst = this.inst;
|
|
386
|
+
const record = this.record;
|
|
387
|
+
const elapsed = performance.now() - this.t0;
|
|
388
|
+
record.ended_at = isoTimestamp(this.startedEpochMs + elapsed);
|
|
389
|
+
record.execution_time_ms = elapsed;
|
|
390
|
+
if ("error" in outcome) {
|
|
391
|
+
const error = outcome.error;
|
|
392
|
+
record.status = isAbortError(error) ? "cancelled" : "error";
|
|
393
|
+
record.error = inst.errorText(error);
|
|
394
|
+
record.error_type = errorClass(error);
|
|
395
|
+
const status = asInt(read(error, "status")) ??
|
|
396
|
+
asInt(read(error, "$metadata", "httpStatusCode")) ??
|
|
397
|
+
asInt(read(error, "$response", "statusCode"));
|
|
398
|
+
if (status !== null)
|
|
399
|
+
record.http_status = status;
|
|
400
|
+
if (info.request_id === undefined || info.request_id === null) {
|
|
401
|
+
const rid = read(error, "requestID") ?? read(error, "request_id") ?? read(error, "$metadata", "requestId");
|
|
402
|
+
if (typeof rid === "string" && rid)
|
|
403
|
+
info = { ...info, request_id: rid };
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
record.status = info.cancelled ? "cancelled" : "ok";
|
|
408
|
+
}
|
|
409
|
+
let outputs = {};
|
|
410
|
+
if (info.content !== undefined && inst.capturesContent) {
|
|
411
|
+
outputs = asObject(inst.content(jsonable(info.content, inst.options.maxContentChars)));
|
|
412
|
+
}
|
|
413
|
+
if (outcome.stream)
|
|
414
|
+
Object.assign(outputs, outcome.stream);
|
|
415
|
+
record.outputs = outputs;
|
|
416
|
+
const model = (typeof info.model === "string" && info.model) || this.model;
|
|
417
|
+
const parameters = { provider: inst.provider };
|
|
418
|
+
if (model)
|
|
419
|
+
parameters["model_name"] = String(model);
|
|
420
|
+
if (this.model && model && this.model !== model)
|
|
421
|
+
parameters["requested_model"] = this.model;
|
|
422
|
+
Object.assign(parameters, this.params);
|
|
423
|
+
record.model_parameters = parameters;
|
|
424
|
+
record.token_usage = info.usage ?? null;
|
|
425
|
+
for (const key of ["finish_reason", "response_id", "request_id"]) {
|
|
426
|
+
const value = info[key];
|
|
427
|
+
if (value !== undefined && value !== null && value !== "")
|
|
428
|
+
record[key] = String(value);
|
|
429
|
+
}
|
|
430
|
+
record.stream = this.stream;
|
|
431
|
+
if (this.firstChunkMs !== null)
|
|
432
|
+
record.time_to_first_chunk_ms = this.firstChunkMs;
|
|
433
|
+
for (const [key, value] of Object.entries(info.extra ?? {})) {
|
|
434
|
+
if (value !== undefined && value !== null && !(key in record))
|
|
435
|
+
record[key] = value;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/** Per-chunk bookkeeping for a streamed call; provider modules subclass it. */
|
|
440
|
+
export class StreamState {
|
|
441
|
+
call;
|
|
442
|
+
constructor(call) {
|
|
443
|
+
this.call = call;
|
|
444
|
+
}
|
|
445
|
+
onItem(chunk) {
|
|
446
|
+
this.call.chunks += 1;
|
|
447
|
+
if (this.call.chunks === 1)
|
|
448
|
+
this.call.firstChunk();
|
|
449
|
+
this.observe(chunk);
|
|
450
|
+
this.call.fallback = safe(() => this.info(), "stream info") ?? this.call.fallback;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Finishes the call. `exhausted` with `aborted` set means the request was
|
|
454
|
+
* aborted and the SDK ended the iteration quietly: recorded as cancelled.
|
|
455
|
+
* `returned` (the consumer stopped early) is recorded as an incomplete
|
|
456
|
+
* stream with status ok, as Python records a stream closed early.
|
|
457
|
+
*/
|
|
458
|
+
onEnd(kind, error, aborted = false) {
|
|
459
|
+
if (this.call.done)
|
|
460
|
+
return;
|
|
461
|
+
const info = safe(() => this.info(), "stream info") ?? {};
|
|
462
|
+
const completed = kind === "exhausted" && !aborted;
|
|
463
|
+
if (kind === "exhausted" && aborted)
|
|
464
|
+
info.cancelled = true;
|
|
465
|
+
const stream = { chunk_count: this.call.chunks, stream_completed: completed };
|
|
466
|
+
if (kind === "error")
|
|
467
|
+
this.call.finish(info, { error, stream });
|
|
468
|
+
else
|
|
469
|
+
this.call.finish(info, { stream });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Wraps an async iterator so each item and the end are reported once. The
|
|
474
|
+
* consumer sees the same items, errors and `return()` behaviour; hook
|
|
475
|
+
* failures are swallowed.
|
|
476
|
+
*/
|
|
477
|
+
export function observeAsyncIterator(inner, hooks) {
|
|
478
|
+
let ended = false;
|
|
479
|
+
const end = (kind, error) => {
|
|
480
|
+
if (ended)
|
|
481
|
+
return;
|
|
482
|
+
ended = true;
|
|
483
|
+
safe(() => hooks.onEnd(kind, error), "stream end hook");
|
|
484
|
+
};
|
|
485
|
+
const iterator = {
|
|
486
|
+
async next(...args) {
|
|
487
|
+
let result;
|
|
488
|
+
try {
|
|
489
|
+
result = await inner.next(...args);
|
|
490
|
+
}
|
|
491
|
+
catch (error) {
|
|
492
|
+
end("error", error);
|
|
493
|
+
throw error;
|
|
494
|
+
}
|
|
495
|
+
if (result.done)
|
|
496
|
+
end("exhausted");
|
|
497
|
+
else if (!ended)
|
|
498
|
+
safe(() => hooks.onItem(result.value), "stream item hook");
|
|
499
|
+
return result;
|
|
500
|
+
},
|
|
501
|
+
async return(value) {
|
|
502
|
+
try {
|
|
503
|
+
if (typeof inner.return === "function")
|
|
504
|
+
return await inner.return(value);
|
|
505
|
+
return { done: true, value: value };
|
|
506
|
+
}
|
|
507
|
+
finally {
|
|
508
|
+
end("returned");
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
async throw(error) {
|
|
512
|
+
end("error", error);
|
|
513
|
+
if (typeof inner.throw === "function")
|
|
514
|
+
return inner.throw(error);
|
|
515
|
+
throw error;
|
|
516
|
+
},
|
|
517
|
+
[Symbol.asyncIterator]() {
|
|
518
|
+
return this;
|
|
519
|
+
},
|
|
520
|
+
};
|
|
521
|
+
return iterator;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Instruments an async iterable in place, keeping the caller's object:
|
|
525
|
+
* an async generator (or any object that is its own iterator) gets own
|
|
526
|
+
* `next` / `return` / `throw` that report to `hooks`; any other async
|
|
527
|
+
* iterable gets an own `[Symbol.asyncIterator]` returning an observed
|
|
528
|
+
* iterator. Returns false when `obj` is not async-iterable.
|
|
529
|
+
*/
|
|
530
|
+
export function instrumentAsyncIterable(obj, hooks, runInside) {
|
|
531
|
+
if (!obj || typeof obj !== "object")
|
|
532
|
+
return false;
|
|
533
|
+
const target = obj;
|
|
534
|
+
const iterFn = target[Symbol.asyncIterator];
|
|
535
|
+
if (typeof iterFn !== "function")
|
|
536
|
+
return false;
|
|
537
|
+
const next = target["next"];
|
|
538
|
+
if (typeof next === "function") {
|
|
539
|
+
const ret = target["return"];
|
|
540
|
+
const thr = target["throw"];
|
|
541
|
+
const run = runInside ?? ((fn) => fn());
|
|
542
|
+
const inner = {
|
|
543
|
+
next: (...args) => run(() => next.apply(obj, args)),
|
|
544
|
+
};
|
|
545
|
+
if (typeof ret === "function")
|
|
546
|
+
inner.return = (value) => ret.call(obj, value);
|
|
547
|
+
if (typeof thr === "function")
|
|
548
|
+
inner.throw = (error) => thr.call(obj, error);
|
|
549
|
+
const observed = observeAsyncIterator(inner, hooks);
|
|
550
|
+
for (const key of ["next", "return", "throw"]) {
|
|
551
|
+
Object.defineProperty(obj, key, { value: observed[key].bind(observed), writable: true, configurable: true, enumerable: false });
|
|
552
|
+
}
|
|
553
|
+
return true;
|
|
554
|
+
}
|
|
555
|
+
Object.defineProperty(obj, Symbol.asyncIterator, {
|
|
556
|
+
value: function (...args) {
|
|
557
|
+
const it = iterFn.apply(this, args);
|
|
558
|
+
const inner = runInside
|
|
559
|
+
? {
|
|
560
|
+
next: (...a) => runInside(() => it.next(...a)),
|
|
561
|
+
...(it.return ? { return: (v) => it.return(v) } : {}),
|
|
562
|
+
...(it.throw ? { throw: (e) => it.throw(e) } : {}),
|
|
563
|
+
}
|
|
564
|
+
: it;
|
|
565
|
+
return observeAsyncIterator(inner, hooks);
|
|
566
|
+
},
|
|
567
|
+
writable: true,
|
|
568
|
+
configurable: true,
|
|
569
|
+
enumerable: false,
|
|
570
|
+
});
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
/** Frees the record of a stream object that is garbage-collected without being read. */
|
|
574
|
+
const streamRegistry = new FinalizationRegistry((call) => {
|
|
575
|
+
safe(() => call.abandon(), "finalizer");
|
|
576
|
+
});
|
|
577
|
+
export function finishWhenCollected(target, call) {
|
|
578
|
+
safe(() => streamRegistry.register(target, call, call), "finalizer registration");
|
|
579
|
+
}
|
|
580
|
+
export const DEFAULT_OPTIONS = {
|
|
581
|
+
captureContent: "none",
|
|
582
|
+
maxContentChars: DEFAULT_MAX_CONTENT_CHARS,
|
|
583
|
+
streamUsage: false,
|
|
584
|
+
};
|
|
585
|
+
/** The `.mjs` / `.js` pair of a Stainless resource module (`openai/resources/x` -> `resources/x.mjs`, `resources/x.js`). */
|
|
586
|
+
export function stainlessFiles(packageName, specifiers) {
|
|
587
|
+
return specifiers.flatMap((specifier) => {
|
|
588
|
+
const rel = specifier.slice(packageName.length + 1);
|
|
589
|
+
return [
|
|
590
|
+
{ specifier, rel: `${rel}.mjs`, format: "esm", group: "main" },
|
|
591
|
+
{ specifier, rel: `${rel}.js`, format: "cjs", group: "main" },
|
|
592
|
+
];
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
const localRequire = createRequire(moduleUrl(import.meta.url));
|
|
596
|
+
const ESM_CONDITIONS = ["node", "import", "default"];
|
|
597
|
+
function pickConditional(value) {
|
|
598
|
+
if (typeof value === "string")
|
|
599
|
+
return value;
|
|
600
|
+
if (Array.isArray(value)) {
|
|
601
|
+
for (const item of value) {
|
|
602
|
+
const hit = pickConditional(item);
|
|
603
|
+
if (hit)
|
|
604
|
+
return hit;
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
if (value && typeof value === "object") {
|
|
609
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
610
|
+
if (ESM_CONDITIONS.includes(key)) {
|
|
611
|
+
const hit = pickConditional(nested);
|
|
612
|
+
if (hit)
|
|
613
|
+
return hit;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Resolves `specifier` the way an `import` from Node would, by reading the
|
|
621
|
+
* package's `exports` map with the conditions node / import / default.
|
|
622
|
+
* Used when `import.meta.resolve` is unavailable (some test runners and
|
|
623
|
+
* transpilers); `cjsPath` locates the package directory.
|
|
624
|
+
*/
|
|
625
|
+
export function resolveEsmFromExports(specifier, cjsPath) {
|
|
626
|
+
const parts = specifier.split("/");
|
|
627
|
+
const nameParts = specifier.startsWith("@") ? 2 : 1;
|
|
628
|
+
const packageName = parts.slice(0, nameParts).join("/");
|
|
629
|
+
const subpath = parts.length > nameParts ? `./${parts.slice(nameParts).join("/")}` : ".";
|
|
630
|
+
let dir = dirname(cjsPath);
|
|
631
|
+
let pkg = null;
|
|
632
|
+
for (let i = 0; i < 12; i++) {
|
|
633
|
+
const candidate = join(dir, "package.json");
|
|
634
|
+
if (existsSync(candidate)) {
|
|
635
|
+
try {
|
|
636
|
+
const parsed = JSON.parse(readFileSync(candidate, "utf8"));
|
|
637
|
+
if (parsed.name === packageName) {
|
|
638
|
+
pkg = parsed;
|
|
639
|
+
break;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
// keep walking
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const parent = dirname(dir);
|
|
647
|
+
if (parent === dir)
|
|
648
|
+
break;
|
|
649
|
+
dir = parent;
|
|
650
|
+
}
|
|
651
|
+
if (!pkg)
|
|
652
|
+
return null;
|
|
653
|
+
let exportsMap = pkg.exports;
|
|
654
|
+
if (exportsMap === undefined)
|
|
655
|
+
return cjsPath; // no exports: import and require both use "main"
|
|
656
|
+
if (typeof exportsMap === "string" || Array.isArray(exportsMap) || !Object.keys(exportsMap).some((k) => k.startsWith("."))) {
|
|
657
|
+
exportsMap = { ".": exportsMap };
|
|
658
|
+
}
|
|
659
|
+
const map = exportsMap;
|
|
660
|
+
let target = null;
|
|
661
|
+
if (subpath in map)
|
|
662
|
+
target = pickConditional(map[subpath]);
|
|
663
|
+
else {
|
|
664
|
+
for (const [key, value] of Object.entries(map)) {
|
|
665
|
+
const star = key.indexOf("*");
|
|
666
|
+
if (star < 0)
|
|
667
|
+
continue;
|
|
668
|
+
const prefix = key.slice(0, star);
|
|
669
|
+
const suffix = key.slice(star + 1);
|
|
670
|
+
if (subpath.startsWith(prefix) && subpath.endsWith(suffix) && subpath.length >= key.length - 1) {
|
|
671
|
+
const match = subpath.slice(prefix.length, subpath.length - suffix.length);
|
|
672
|
+
const picked = pickConditional(value);
|
|
673
|
+
if (picked) {
|
|
674
|
+
target = picked.split("*").join(match);
|
|
675
|
+
break;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (!target)
|
|
681
|
+
return null;
|
|
682
|
+
const file = join(dir, target);
|
|
683
|
+
return existsSync(file) ? file : null;
|
|
684
|
+
}
|
|
685
|
+
function resolveEsm(specifier, cjsPath) {
|
|
686
|
+
try {
|
|
687
|
+
const meta = import.meta;
|
|
688
|
+
if (typeof meta.resolve === "function") {
|
|
689
|
+
const url = meta.resolve(specifier);
|
|
690
|
+
return url.startsWith("file:") ? fileURLToPath(url) : null;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
catch {
|
|
694
|
+
// fall through
|
|
695
|
+
}
|
|
696
|
+
return cjsPath ? resolveEsmFromExports(specifier, cjsPath) : null;
|
|
697
|
+
}
|
|
698
|
+
export function isNotFound(error) {
|
|
699
|
+
const code = read(error, "code");
|
|
700
|
+
return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* The files an application could get for `specifier` from this package's
|
|
704
|
+
* location: what `import` resolves to and what `require` resolves to. For
|
|
705
|
+
* dual packages these differ and load as separate module instances.
|
|
706
|
+
* Resolution only; nothing is loaded. Null when not installed.
|
|
707
|
+
*/
|
|
708
|
+
export function resolveCopies(specifier) {
|
|
709
|
+
let cjsPath = null;
|
|
710
|
+
try {
|
|
711
|
+
cjsPath = localRequire.resolve(specifier);
|
|
712
|
+
}
|
|
713
|
+
catch (error) {
|
|
714
|
+
if (!isNotFound(error))
|
|
715
|
+
debug(`resolve ${specifier} (require): ${describeError(error)}`);
|
|
716
|
+
}
|
|
717
|
+
const esmPath = resolveEsm(specifier, cjsPath);
|
|
718
|
+
if (!cjsPath && !esmPath)
|
|
719
|
+
return null;
|
|
720
|
+
return { esm: esmPath && esmPath !== cjsPath ? esmPath : null, cjs: cjsPath };
|
|
721
|
+
}
|
|
722
|
+
/** Loads one file with `require()` (an ES module through require(esm): the same instance `import` gets). */
|
|
723
|
+
export function requireFile(path) {
|
|
724
|
+
return localRequire(path);
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Loads every copy of `specifier` an application could get (see
|
|
728
|
+
* `resolveCopies`). Used by `auto({ eager: true })`. Returns null when the
|
|
729
|
+
* package is not installed.
|
|
730
|
+
*/
|
|
731
|
+
export function loadCopies(specifier) {
|
|
732
|
+
const paths = resolveCopies(specifier);
|
|
733
|
+
if (!paths)
|
|
734
|
+
return null;
|
|
735
|
+
const copies = [];
|
|
736
|
+
const problems = [];
|
|
737
|
+
const load = (format, path) => {
|
|
738
|
+
try {
|
|
739
|
+
copies.push({ format, path, ns: requireFile(path) });
|
|
740
|
+
}
|
|
741
|
+
catch (error) {
|
|
742
|
+
problems.push(`${format} copy could not be loaded (${describeError(error)})`);
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
if (paths.esm)
|
|
746
|
+
load("esm", paths.esm);
|
|
747
|
+
if (paths.cjs)
|
|
748
|
+
load("cjs", paths.cjs);
|
|
749
|
+
return { copies, problems };
|
|
750
|
+
}
|
|
751
|
+
/** The `version` of the installed package that contains `file`. */
|
|
752
|
+
export function packageVersion(file, packageName) {
|
|
753
|
+
let dir = dirname(file);
|
|
754
|
+
for (let i = 0; i < 8; i++) {
|
|
755
|
+
const candidate = join(dir, "package.json");
|
|
756
|
+
if (existsSync(candidate)) {
|
|
757
|
+
try {
|
|
758
|
+
const pkg = JSON.parse(readFileSync(candidate, "utf8"));
|
|
759
|
+
if (pkg.name === packageName)
|
|
760
|
+
return pkg.version ?? null;
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
// keep walking
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const parent = dirname(dir);
|
|
767
|
+
if (parent === dir)
|
|
768
|
+
break;
|
|
769
|
+
dir = parent;
|
|
770
|
+
}
|
|
771
|
+
return null;
|
|
772
|
+
}
|