@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,293 @@
|
|
|
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 { tokenUsage } from "../record.js";
|
|
49
|
+
import { TextAccumulator, read, scalarParams } from "../util.js";
|
|
50
|
+
import { StreamState, stainlessFiles, } from "./core.js";
|
|
51
|
+
import { wrapStainlessMethod } from "./stainless.js";
|
|
52
|
+
export const PROVIDER = "openai";
|
|
53
|
+
export const PACKAGE = "openai";
|
|
54
|
+
export const VERIFIED_VERSION = "7.62.0";
|
|
55
|
+
const CHAT_PARAMS = [
|
|
56
|
+
"temperature", "top_p", "max_tokens", "max_completion_tokens", "n", "seed",
|
|
57
|
+
"frequency_penalty", "presence_penalty", "reasoning_effort", "service_tier",
|
|
58
|
+
];
|
|
59
|
+
const RESPONSES_PARAMS = ["temperature", "top_p", "max_output_tokens", "service_tier", "truncation"];
|
|
60
|
+
const COMPLETIONS_PARAMS = ["temperature", "top_p", "max_tokens", "n", "seed", "frequency_penalty", "presence_penalty"];
|
|
61
|
+
const EMBEDDINGS_PARAMS = ["dimensions", "encoding_format"];
|
|
62
|
+
function completionUsage(usage) {
|
|
63
|
+
return tokenUsage(read(usage, "prompt_tokens"), read(usage, "completion_tokens"), read(usage, "total_tokens"), {
|
|
64
|
+
cached_tokens: read(usage, "prompt_tokens_details", "cached_tokens"),
|
|
65
|
+
reasoning_tokens: read(usage, "completion_tokens_details", "reasoning_tokens"),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function responseUsage(usage) {
|
|
69
|
+
return tokenUsage(read(usage, "input_tokens"), read(usage, "output_tokens"), read(usage, "total_tokens"), {
|
|
70
|
+
cached_tokens: read(usage, "input_tokens_details", "cached_tokens"),
|
|
71
|
+
reasoning_tokens: read(usage, "output_tokens_details", "reasoning_tokens"),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function firstChoice(obj) {
|
|
75
|
+
const choices = read(obj, "choices");
|
|
76
|
+
return Array.isArray(choices) && choices.length > 0 ? choices[0] : undefined;
|
|
77
|
+
}
|
|
78
|
+
function chatInfo(result, wantContent) {
|
|
79
|
+
const choice = firstChoice(result);
|
|
80
|
+
const info = {
|
|
81
|
+
model: read(result, "model"),
|
|
82
|
+
response_id: read(result, "id"),
|
|
83
|
+
request_id: read(result, "_request_id"),
|
|
84
|
+
finish_reason: read(choice, "finish_reason"),
|
|
85
|
+
usage: completionUsage(read(result, "usage")),
|
|
86
|
+
extra: { service_tier: read(result, "service_tier") },
|
|
87
|
+
};
|
|
88
|
+
if (wantContent) {
|
|
89
|
+
const message = read(choice, "message");
|
|
90
|
+
const content = { content: read(message, "content") ?? null };
|
|
91
|
+
const toolCalls = read(message, "tool_calls");
|
|
92
|
+
if (Array.isArray(toolCalls) && toolCalls.length)
|
|
93
|
+
content["tool_calls"] = toolCalls;
|
|
94
|
+
const refusal = read(message, "refusal");
|
|
95
|
+
if (refusal)
|
|
96
|
+
content["refusal"] = refusal;
|
|
97
|
+
info.content = content;
|
|
98
|
+
}
|
|
99
|
+
return info;
|
|
100
|
+
}
|
|
101
|
+
function responsesInfo(result, wantContent) {
|
|
102
|
+
const info = {
|
|
103
|
+
model: read(result, "model"),
|
|
104
|
+
response_id: read(result, "id"),
|
|
105
|
+
request_id: read(result, "_request_id"),
|
|
106
|
+
finish_reason: read(result, "incomplete_details", "reason") ?? read(result, "status"),
|
|
107
|
+
usage: responseUsage(read(result, "usage")),
|
|
108
|
+
extra: { service_tier: read(result, "service_tier"), response_error_code: read(result, "error", "code") },
|
|
109
|
+
};
|
|
110
|
+
if (wantContent)
|
|
111
|
+
info.content = { content: read(result, "output_text") ?? null };
|
|
112
|
+
return info;
|
|
113
|
+
}
|
|
114
|
+
function completionsInfo(result, wantContent) {
|
|
115
|
+
const choice = firstChoice(result);
|
|
116
|
+
const info = {
|
|
117
|
+
model: read(result, "model"),
|
|
118
|
+
response_id: read(result, "id"),
|
|
119
|
+
request_id: read(result, "_request_id"),
|
|
120
|
+
finish_reason: read(choice, "finish_reason"),
|
|
121
|
+
usage: completionUsage(read(result, "usage")),
|
|
122
|
+
};
|
|
123
|
+
if (wantContent)
|
|
124
|
+
info.content = { content: read(choice, "text") ?? null };
|
|
125
|
+
return info;
|
|
126
|
+
}
|
|
127
|
+
function embeddingsInfo(result) {
|
|
128
|
+
const usage = read(result, "usage");
|
|
129
|
+
const data = read(result, "data");
|
|
130
|
+
// Embeddings have no completion side: 0 is what the API reports, not a guess.
|
|
131
|
+
return {
|
|
132
|
+
model: read(result, "model"),
|
|
133
|
+
request_id: read(result, "_request_id"),
|
|
134
|
+
usage: tokenUsage(read(usage, "prompt_tokens"), read(usage, "prompt_tokens") === undefined ? undefined : 0, read(usage, "total_tokens")),
|
|
135
|
+
extra: { embedding_count: Array.isArray(data) ? data.length : undefined },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
class OpenAIStream extends StreamState {
|
|
139
|
+
inst;
|
|
140
|
+
text;
|
|
141
|
+
data;
|
|
142
|
+
constructor(call, inst, requestId) {
|
|
143
|
+
super(call);
|
|
144
|
+
this.inst = inst;
|
|
145
|
+
this.text = new TextAccumulator(inst.options.maxContentChars);
|
|
146
|
+
this.data = { request_id: requestId };
|
|
147
|
+
}
|
|
148
|
+
observe(_chunk) { }
|
|
149
|
+
info() {
|
|
150
|
+
const info = { ...this.data };
|
|
151
|
+
if (this.inst.capturesContent)
|
|
152
|
+
info.content = { content: this.text.text };
|
|
153
|
+
return info;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** `ChatCompletionChunk` (and legacy `Completion`) chunks. */
|
|
157
|
+
class ChatStream extends OpenAIStream {
|
|
158
|
+
observe(chunk) {
|
|
159
|
+
const model = read(chunk, "model");
|
|
160
|
+
if (model)
|
|
161
|
+
this.data.model = model;
|
|
162
|
+
const id = read(chunk, "id");
|
|
163
|
+
if (id)
|
|
164
|
+
this.data.response_id = id;
|
|
165
|
+
const usage = completionUsage(read(chunk, "usage"));
|
|
166
|
+
if (usage)
|
|
167
|
+
this.data.usage = usage;
|
|
168
|
+
const choice = firstChoice(chunk);
|
|
169
|
+
if (choice !== undefined) {
|
|
170
|
+
const finish = read(choice, "finish_reason");
|
|
171
|
+
if (finish)
|
|
172
|
+
this.data.finish_reason = finish;
|
|
173
|
+
if (this.inst.capturesContent)
|
|
174
|
+
this.text.add(read(choice, "delta", "content") ?? read(choice, "text"));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const TERMINAL = new Set(["response.created", "response.completed", "response.incomplete", "response.failed"]);
|
|
179
|
+
/** `ResponseStreamEvent` events. */
|
|
180
|
+
class ResponsesStream extends OpenAIStream {
|
|
181
|
+
observe(event) {
|
|
182
|
+
const kind = read(event, "type");
|
|
183
|
+
if (typeof kind === "string" && TERMINAL.has(kind)) {
|
|
184
|
+
const response = read(event, "response");
|
|
185
|
+
if (response) {
|
|
186
|
+
const requestId = this.data.request_id;
|
|
187
|
+
const next = responsesInfo(response, false);
|
|
188
|
+
this.data = { ...next, request_id: next.request_id ?? requestId };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else if (kind === "response.output_text.delta" && this.inst.capturesContent) {
|
|
192
|
+
this.text.add(read(event, "delta"));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
export const SURFACES = [
|
|
197
|
+
{
|
|
198
|
+
specifier: "openai/resources/chat/completions/completions",
|
|
199
|
+
className: "Completions",
|
|
200
|
+
decisionType: "llm.openai.chat",
|
|
201
|
+
functionBase: "openai.chat.completions",
|
|
202
|
+
params: CHAT_PARAMS,
|
|
203
|
+
inputKeys: ["messages", "tools"],
|
|
204
|
+
info: chatInfo,
|
|
205
|
+
stream: ChatStream,
|
|
206
|
+
streamUsage: true,
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
specifier: "openai/resources/responses/responses",
|
|
210
|
+
className: "Responses",
|
|
211
|
+
decisionType: "llm.openai.responses",
|
|
212
|
+
functionBase: "openai.responses",
|
|
213
|
+
params: RESPONSES_PARAMS,
|
|
214
|
+
inputKeys: ["instructions", "input", "tools"],
|
|
215
|
+
info: responsesInfo,
|
|
216
|
+
stream: ResponsesStream,
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
specifier: "openai/resources/completions",
|
|
220
|
+
className: "Completions",
|
|
221
|
+
decisionType: "llm.openai.completions",
|
|
222
|
+
functionBase: "openai.completions",
|
|
223
|
+
params: COMPLETIONS_PARAMS,
|
|
224
|
+
inputKeys: ["prompt"],
|
|
225
|
+
info: completionsInfo,
|
|
226
|
+
stream: ChatStream,
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
specifier: "openai/resources/embeddings",
|
|
230
|
+
className: "Embeddings",
|
|
231
|
+
decisionType: "llm.openai.embeddings",
|
|
232
|
+
functionBase: "openai.embeddings",
|
|
233
|
+
params: EMBEDDINGS_PARAMS,
|
|
234
|
+
inputKeys: ["input"],
|
|
235
|
+
info: (result) => embeddingsInfo(result),
|
|
236
|
+
},
|
|
237
|
+
];
|
|
238
|
+
/** `options.__metadata.helperMethod` (e.g. "stream", "chat.completions.parse") to a method name. */
|
|
239
|
+
function methodName(options) {
|
|
240
|
+
const helper = read(options, "__metadata", "helperMethod");
|
|
241
|
+
if (typeof helper === "string" && helper)
|
|
242
|
+
return helper.split(".").pop() || "create";
|
|
243
|
+
return "create";
|
|
244
|
+
}
|
|
245
|
+
function given(value) {
|
|
246
|
+
return value !== undefined && value !== null;
|
|
247
|
+
}
|
|
248
|
+
function targetFor(inst, surface, owner) {
|
|
249
|
+
const begin = (args) => {
|
|
250
|
+
const body = args[0];
|
|
251
|
+
if (!body || typeof body !== "object")
|
|
252
|
+
return null;
|
|
253
|
+
return inst.begin(surface.decisionType, `${surface.functionBase}.${methodName(args[1])}`, {
|
|
254
|
+
model: read(body, "model"),
|
|
255
|
+
params: scalarParams(body, surface.params),
|
|
256
|
+
inputs: () => {
|
|
257
|
+
const out = {};
|
|
258
|
+
for (const key of surface.inputKeys)
|
|
259
|
+
if (given(read(body, key)))
|
|
260
|
+
out[key] = read(body, key);
|
|
261
|
+
return out;
|
|
262
|
+
},
|
|
263
|
+
stream: read(body, "stream") === true,
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
const hooks = {
|
|
267
|
+
requestIdHeader: "x-request-id",
|
|
268
|
+
info: (parsed) => surface.info(parsed, inst.capturesContent),
|
|
269
|
+
streamState: (call, requestId) => surface.stream ? new surface.stream(call, inst, requestId) : new (class extends OpenAIStream {
|
|
270
|
+
})(call, inst, requestId),
|
|
271
|
+
};
|
|
272
|
+
const prepare = surface.streamUsage && inst.options.streamUsage
|
|
273
|
+
? (args) => {
|
|
274
|
+
const body = args[0];
|
|
275
|
+
if (body["stream"] !== true || (body["stream_options"] && typeof body["stream_options"] === "object"))
|
|
276
|
+
return args;
|
|
277
|
+
return [{ ...body, stream_options: { include_usage: true } }, ...args.slice(1)];
|
|
278
|
+
}
|
|
279
|
+
: undefined;
|
|
280
|
+
return {
|
|
281
|
+
kind: "method",
|
|
282
|
+
owner: read(owner, "prototype"),
|
|
283
|
+
key: "create",
|
|
284
|
+
label: `${surface.specifier}#${surface.className}.create`,
|
|
285
|
+
wrap: wrapStainlessMethod(inst, begin, hooks, prepare),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/** Builds the patch targets for one module copy (`modules[specifier]` is that copy's namespace). */
|
|
289
|
+
export function targets(inst, modules) {
|
|
290
|
+
return SURFACES.map((surface) => targetFor(inst, surface, modules[surface.specifier]?.[surface.className]));
|
|
291
|
+
}
|
|
292
|
+
export const SPECIFIERS = SURFACES.map((s) => s.specifier);
|
|
293
|
+
export const FILES = stainlessFiles(PACKAGE, SPECIFIERS);
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the Stainless-generated SDKs (`openai`, `@anthropic-ai/sdk`).
|
|
3
|
+
*
|
|
4
|
+
* Verified by reading `core/api-promise.mjs` and `core/streaming.mjs` in
|
|
5
|
+
* openai 7.62.0 and @anthropic-ai/sdk 1.12.0:
|
|
6
|
+
*
|
|
7
|
+
* - A resource method returns an `APIPromise` (a `Promise` subclass) holding
|
|
8
|
+
* two own fields: `responsePromise` (the raw response, body unread) and
|
|
9
|
+
* `parseResponse(client, props)`. `.then` / `.withResponse()` / `.parse()`
|
|
10
|
+
* parse through `this.parseResponse`; `.asResponse()` reads
|
|
11
|
+
* `this.responsePromise` and never parses. `_thenUnwrap` builds a new
|
|
12
|
+
* APIPromise from `this.responsePromise` and `this.parseResponse`.
|
|
13
|
+
* - So we keep the caller's APIPromise object and replace only those two
|
|
14
|
+
* fields on it: the response promise is observed (errors, request id)
|
|
15
|
+
* without reading the body, and the parse step reports the parsed value.
|
|
16
|
+
* A response that is only ever read with `.asResponse()` is recorded with
|
|
17
|
+
* its request id but no usage, when the promise is garbage-collected or
|
|
18
|
+
* the process exits.
|
|
19
|
+
* - `stream: true` parses to a `Stream` whose own `iterator` field is the
|
|
20
|
+
* source generator factory used by `[Symbol.asyncIterator]`, `tee()` and
|
|
21
|
+
* `toReadableStream()`. We replace that field on the same object.
|
|
22
|
+
*/
|
|
23
|
+
import { type CallInfo, type Instrumentor, type ProviderCall, type StreamState, isAbortError } from "./core.js";
|
|
24
|
+
export interface StainlessHooks {
|
|
25
|
+
/** Header carrying the request id (`x-request-id` / `request-id`). */
|
|
26
|
+
requestIdHeader: string;
|
|
27
|
+
/** Record fields from a parsed, non-streamed result. */
|
|
28
|
+
info(parsed: unknown, requestId: string | null): CallInfo;
|
|
29
|
+
/** Bookkeeping for a streamed result. */
|
|
30
|
+
streamState(call: ProviderCall, requestId: string | null): StreamState;
|
|
31
|
+
}
|
|
32
|
+
/** Reports a streamed result's chunks and end; keeps the caller's Stream object. */
|
|
33
|
+
export declare function instrumentStainlessStream(stream: unknown, call: ProviderCall, state: StreamState): void;
|
|
34
|
+
/**
|
|
35
|
+
* Observes an APIPromise in place. Returns false when `result` does not have
|
|
36
|
+
* the verified APIPromise shape (the caller then finishes the call itself).
|
|
37
|
+
*/
|
|
38
|
+
export declare function observeApiPromise(result: unknown, call: ProviderCall, inst: Instrumentor, hooks: StainlessHooks): boolean;
|
|
39
|
+
/** Wraps a Stainless resource method (`create`). */
|
|
40
|
+
export declare function wrapStainlessMethod(inst: Instrumentor, begin: (args: unknown[]) => ProviderCall | null, hooks: StainlessHooks, prepareArgs?: (args: unknown[]) => unknown[]): (original: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown;
|
|
41
|
+
export { isAbortError };
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the Stainless-generated SDKs (`openai`, `@anthropic-ai/sdk`).
|
|
3
|
+
*
|
|
4
|
+
* Verified by reading `core/api-promise.mjs` and `core/streaming.mjs` in
|
|
5
|
+
* openai 7.62.0 and @anthropic-ai/sdk 1.12.0:
|
|
6
|
+
*
|
|
7
|
+
* - A resource method returns an `APIPromise` (a `Promise` subclass) holding
|
|
8
|
+
* two own fields: `responsePromise` (the raw response, body unread) and
|
|
9
|
+
* `parseResponse(client, props)`. `.then` / `.withResponse()` / `.parse()`
|
|
10
|
+
* parse through `this.parseResponse`; `.asResponse()` reads
|
|
11
|
+
* `this.responsePromise` and never parses. `_thenUnwrap` builds a new
|
|
12
|
+
* APIPromise from `this.responsePromise` and `this.parseResponse`.
|
|
13
|
+
* - So we keep the caller's APIPromise object and replace only those two
|
|
14
|
+
* fields on it: the response promise is observed (errors, request id)
|
|
15
|
+
* without reading the body, and the parse step reports the parsed value.
|
|
16
|
+
* A response that is only ever read with `.asResponse()` is recorded with
|
|
17
|
+
* its request id but no usage, when the promise is garbage-collected or
|
|
18
|
+
* the process exits.
|
|
19
|
+
* - `stream: true` parses to a `Stream` whose own `iterator` field is the
|
|
20
|
+
* source generator factory used by `[Symbol.asyncIterator]`, `tee()` and
|
|
21
|
+
* `toReadableStream()`. We replace that field on the same object.
|
|
22
|
+
*/
|
|
23
|
+
import { callStore, finishWhenCollected, isAbortError, observeAsyncIterator, } from "./core.js";
|
|
24
|
+
import { debug, describeError, read, safe } from "../util.js";
|
|
25
|
+
function isApiPromise(value) {
|
|
26
|
+
if (!value || typeof value !== "object")
|
|
27
|
+
return false;
|
|
28
|
+
const rp = value["responsePromise"];
|
|
29
|
+
const parse = value["parseResponse"];
|
|
30
|
+
return !!rp && typeof rp.then === "function" && typeof parse === "function";
|
|
31
|
+
}
|
|
32
|
+
function header(props, name) {
|
|
33
|
+
try {
|
|
34
|
+
const headers = read(props, "response", "headers");
|
|
35
|
+
const value = headers?.get?.(name);
|
|
36
|
+
return typeof value === "string" && value ? value : null;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function isStainlessStream(value) {
|
|
43
|
+
return !!value && typeof value === "object" && typeof value["iterator"] === "function";
|
|
44
|
+
}
|
|
45
|
+
/** Reports a streamed result's chunks and end; keeps the caller's Stream object. */
|
|
46
|
+
export function instrumentStainlessStream(stream, call, state) {
|
|
47
|
+
if (!isStainlessStream(stream)) {
|
|
48
|
+
debug("stream result has no iterator field; recorded without its chunks");
|
|
49
|
+
call.finish({}, { stream: { chunk_count: 0, stream_completed: false } });
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const original = stream.iterator;
|
|
53
|
+
const target = stream;
|
|
54
|
+
target.iterator = function (...args) {
|
|
55
|
+
const inner = original.apply(this, args);
|
|
56
|
+
return observeAsyncIterator(inner, {
|
|
57
|
+
onItem: (item) => state.onItem(item),
|
|
58
|
+
onEnd: (kind, error) => {
|
|
59
|
+
const aborted = !!target.controller?.signal?.aborted;
|
|
60
|
+
state.onEnd(kind, error, aborted);
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
finishWhenCollected(stream, call);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Observes an APIPromise in place. Returns false when `result` does not have
|
|
68
|
+
* the verified APIPromise shape (the caller then finishes the call itself).
|
|
69
|
+
*/
|
|
70
|
+
export function observeApiPromise(result, call, inst, hooks) {
|
|
71
|
+
if (!isApiPromise(result))
|
|
72
|
+
return false;
|
|
73
|
+
const promise = result;
|
|
74
|
+
const originalResponse = promise.responsePromise;
|
|
75
|
+
const originalParse = promise.parseResponse;
|
|
76
|
+
let requestId = null;
|
|
77
|
+
let parsedOnce = false;
|
|
78
|
+
promise.responsePromise = originalResponse.then((props) => {
|
|
79
|
+
safe(() => {
|
|
80
|
+
requestId = header(props, hooks.requestIdHeader);
|
|
81
|
+
call.fallback = { request_id: requestId };
|
|
82
|
+
}, "response hook");
|
|
83
|
+
return props;
|
|
84
|
+
}, (error) => {
|
|
85
|
+
call.finish({}, { error });
|
|
86
|
+
throw error;
|
|
87
|
+
});
|
|
88
|
+
promise.parseResponse = async function (client, props) {
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = await originalParse.call(this, client, props);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
call.finish({ request_id: requestId }, { error });
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
if (!parsedOnce && inst.active) {
|
|
98
|
+
parsedOnce = true;
|
|
99
|
+
try {
|
|
100
|
+
if (read(props, "options", "stream") === true || isStainlessStream(parsed)) {
|
|
101
|
+
call.markStream();
|
|
102
|
+
instrumentStainlessStream(parsed, call, hooks.streamState(call, requestId));
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const info = hooks.info(parsed, requestId);
|
|
106
|
+
if (info.request_id === undefined || info.request_id === null)
|
|
107
|
+
info.request_id = requestId;
|
|
108
|
+
call.finish(info);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
debug(`could not read the parsed response: ${describeError(error)}`);
|
|
113
|
+
call.finish({ request_id: requestId });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return parsed;
|
|
117
|
+
};
|
|
118
|
+
finishWhenCollected(promise, call);
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
/** Wraps a Stainless resource method (`create`). */
|
|
122
|
+
export function wrapStainlessMethod(inst, begin, hooks, prepareArgs) {
|
|
123
|
+
return (original) => function (...args) {
|
|
124
|
+
const call = safe(() => begin(args), "begin") ?? null;
|
|
125
|
+
if (!call)
|
|
126
|
+
return original.apply(this, args);
|
|
127
|
+
const callArgs = prepareArgs ? (safe(() => prepareArgs(args), "prepare args") ?? args) : args;
|
|
128
|
+
let result;
|
|
129
|
+
call.owner = this;
|
|
130
|
+
try {
|
|
131
|
+
result = callStore.run(call, () => original.apply(this, callArgs));
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
call.finish({}, { error });
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
const observed = safe(() => observeApiPromise(result, call, inst, hooks), "observe") ?? false;
|
|
138
|
+
if (!observed) {
|
|
139
|
+
// Not the verified APIPromise shape: follow it as a plain thenable without changing it.
|
|
140
|
+
const then = result?.then;
|
|
141
|
+
if (typeof then === "function") {
|
|
142
|
+
result.then((value) => call.finish(safe(() => hooks.info(value, null), "info") ?? {}), (error) => call.finish({}, { error }));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
call.finish({});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
export { isAbortError };
|
package/dist/loader.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy patching: each SDK copy is patched when the application loads it,
|
|
3
|
+
* not up front.
|
|
4
|
+
*
|
|
5
|
+
* - A synchronous, in-thread load hook (`module.registerHooks`, Node >= 26
|
|
6
|
+
* here) watches for the few SDK files that hold patch targets (each
|
|
7
|
+
* provider's `FILES`). For those files only, it appends one statement to
|
|
8
|
+
* the source Node is about to evaluate: it reports the module's own
|
|
9
|
+
* exports (`module.exports` for CommonJS, the module namespace for ESM,
|
|
10
|
+
* through a self-import) to a function this package keeps on
|
|
11
|
+
* `globalThis`. The statement runs after the module body, so every class
|
|
12
|
+
* is defined; nothing else in the file changes. Every other module goes
|
|
13
|
+
* through untouched (`nextLoad`'s result is returned as is).
|
|
14
|
+
* - The same statement is what the esbuild plugin (`esbuild.ts`) appends
|
|
15
|
+
* when it bundles an SDK into an application, so bundled copies report
|
|
16
|
+
* themselves the same way.
|
|
17
|
+
* - Reports that arrive before anything is listening are queued in an array
|
|
18
|
+
* on that `globalThis` key and replayed when `auto()` installs the
|
|
19
|
+
* listener.
|
|
20
|
+
*
|
|
21
|
+
* Copies are grouped per package root, format and build (`SdkFile.group`);
|
|
22
|
+
* a provider is applied to a copy once all of its files for that copy have
|
|
23
|
+
* reported (so the all-or-none rule of `Instrumentor.applyAll` still
|
|
24
|
+
* holds per copy).
|
|
25
|
+
*/
|
|
26
|
+
import type { SdkFile } from "./instrument/core.js";
|
|
27
|
+
export declare const LOADED_KEY: unique symbol;
|
|
28
|
+
export type Origin = "node" | "bundle" | "test" | "client";
|
|
29
|
+
export interface WatchedFile extends SdkFile {
|
|
30
|
+
provider: string;
|
|
31
|
+
packageName: string;
|
|
32
|
+
}
|
|
33
|
+
export interface LoadedCopy {
|
|
34
|
+
key: string;
|
|
35
|
+
provider: string;
|
|
36
|
+
packageName: string;
|
|
37
|
+
format: "esm" | "cjs";
|
|
38
|
+
group: string;
|
|
39
|
+
origin: Origin;
|
|
40
|
+
root: string;
|
|
41
|
+
/** One file of the copy, for version lookup. */
|
|
42
|
+
file: string;
|
|
43
|
+
modules: Record<string, Record<string, unknown>>;
|
|
44
|
+
}
|
|
45
|
+
type Listener = (copy: LoadedCopy) => void;
|
|
46
|
+
/** Sets the SDK files to watch (every provider's, whether or not it is enabled). */
|
|
47
|
+
export declare function setWatchedFiles(files: WatchedFile[]): void;
|
|
48
|
+
/** Called for each copy whenever one of its files reports. */
|
|
49
|
+
export declare function setCopyListener(fn: Listener | null): void;
|
|
50
|
+
/**
|
|
51
|
+
* The statement appended to a watched SDK file. `tag` is "esm" / "cjs"
|
|
52
|
+
* (loaded by Node) or "bundle-esm" / "bundle-cjs" (inlined by a bundler).
|
|
53
|
+
* `self` is the specifier an ES module uses to import its own namespace.
|
|
54
|
+
*/
|
|
55
|
+
export declare function notifierSource(tag: string, file: string, self?: string): string;
|
|
56
|
+
/** A file resolved from this package's location (also matched when it is not under node_modules, e.g. a linked SDK). */
|
|
57
|
+
export declare function addKnownFile(path: string, file: WatchedFile): void;
|
|
58
|
+
/** The watched entry a file path is, and the package root it sits in. */
|
|
59
|
+
export declare function matchFile(path: string): {
|
|
60
|
+
file: WatchedFile;
|
|
61
|
+
root: string;
|
|
62
|
+
} | null;
|
|
63
|
+
/** Records one reported module and hands its copy to the listener. */
|
|
64
|
+
export declare function report(tag: string, path: string, ns: unknown, explicit?: {
|
|
65
|
+
file: WatchedFile;
|
|
66
|
+
root: string;
|
|
67
|
+
}): void;
|
|
68
|
+
/**
|
|
69
|
+
* Installs the listener and the load hook once per thread. Returns false
|
|
70
|
+
* when the hook could not be registered (the caller then falls back to
|
|
71
|
+
* loading the SDK copies up front).
|
|
72
|
+
*/
|
|
73
|
+
export declare function installLoadHooks(): boolean;
|
|
74
|
+
/** Reports CommonJS (and require(esm)) SDK files already in `require.cache`. */
|
|
75
|
+
export declare function scanRequireCache(cache: Record<string, {
|
|
76
|
+
loaded?: boolean;
|
|
77
|
+
exports?: unknown;
|
|
78
|
+
} | undefined>): void;
|
|
79
|
+
export {};
|