metergraph 0.4.0 → 0.6.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.
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ /**
3
+ * The narrow adapter boundary batchFirst() drives, plus a worker-only OpenAI
4
+ * Batch API implementation. Deliberately duck-typed against the openai
5
+ * package's shape (see OpenAIBatchCapableClient) rather than importing it —
6
+ * `openai` is an optional peer dependency of this package, and structural
7
+ * typing already lets a real `OpenAI` client instance satisfy this
8
+ * interface without any import, type-only or otherwise.
9
+ *
10
+ * Every method here returns only bounded, structural information — a
11
+ * status, a result the caller explicitly asked for, and a boolean noting
12
+ * whether that result happened to contain a tool-call plan. No adapter
13
+ * method inspects or logs a provider error body, a credential, or a raw
14
+ * prompt.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ProviderBatchError = void 0;
18
+ exports.createOpenAIBatchAdapter = createOpenAIBatchAdapter;
19
+ exports.createAnthropicBatchAdapter = createAnthropicBatchAdapter;
20
+ exports.createGoogleBatchAdapter = createGoogleBatchAdapter;
21
+ const OPENAI_BATCH_ENDPOINT = "/v1/responses";
22
+ const OPENAI_COMPLETION_WINDOW = "24h";
23
+ // "validating" | "in_progress" | "finalizing" | "cancelling" all fall
24
+ // through to "pending" below, alongside any future status OpenAI adds —
25
+ // only a recognized terminal status is ever treated as terminal.
26
+ const OPENAI_FAILED_STATUSES = new Set(["failed", "cancelled"]);
27
+ function get(value, key) {
28
+ return value && typeof value === "object" ? value[key] : undefined;
29
+ }
30
+ function hasFunctionCall(body) {
31
+ const output = get(body, "output");
32
+ if (!Array.isArray(output))
33
+ return false;
34
+ return output.some((item) => get(item, "type") === "function_call");
35
+ }
36
+ function randomCustomId() {
37
+ if (typeof globalThis.crypto?.randomUUID === "function")
38
+ return globalThis.crypto.randomUUID();
39
+ return `batch-first-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
40
+ }
41
+ class ProviderBatchError extends Error {
42
+ }
43
+ exports.ProviderBatchError = ProviderBatchError;
44
+ function createOpenAIBatchAdapter(client) {
45
+ return {
46
+ eligibility(request) {
47
+ if (request.stream === true) {
48
+ return { eligible: false, reason: "streaming requests are direct-only" };
49
+ }
50
+ return { eligible: true };
51
+ },
52
+ async submitOne(request) {
53
+ const customId = randomCustomId();
54
+ const line = JSON.stringify({
55
+ custom_id: customId,
56
+ method: "POST",
57
+ url: OPENAI_BATCH_ENDPOINT,
58
+ body: request,
59
+ });
60
+ const file = new Blob([`${line}\n`], { type: "application/jsonl" });
61
+ const uploaded = await client.files.create({ file, purpose: "batch" });
62
+ const batch = await client.batches.create({
63
+ input_file_id: uploaded.id,
64
+ endpoint: OPENAI_BATCH_ENDPOINT,
65
+ completion_window: OPENAI_COMPLETION_WINDOW,
66
+ });
67
+ const handle = { providerBatchId: batch.id, customId };
68
+ return handle;
69
+ },
70
+ async poll(handle) {
71
+ const batch = await client.batches.retrieve(handle.providerBatchId);
72
+ const status = batch.status ?? "";
73
+ if (status === "completed")
74
+ return { status: "completed" };
75
+ if (status === "expired")
76
+ return { status: "expired" };
77
+ if (OPENAI_FAILED_STATUSES.has(status))
78
+ return { status: "failed" };
79
+ return { status: "pending" };
80
+ },
81
+ async readResult(handle) {
82
+ const openaiHandle = handle;
83
+ const batch = await client.batches.retrieve(handle.providerBatchId);
84
+ const outputFileId = batch.output_file_id;
85
+ if (!outputFileId) {
86
+ throw new ProviderBatchError("openai batch has no output file to read");
87
+ }
88
+ const file = await client.files.content(outputFileId);
89
+ const text = await file.text();
90
+ for (const rawLine of text.split(/\r?\n/)) {
91
+ const line = rawLine.trim();
92
+ if (!line)
93
+ continue;
94
+ let item;
95
+ try {
96
+ item = JSON.parse(line);
97
+ }
98
+ catch {
99
+ continue;
100
+ }
101
+ if (get(item, "custom_id") !== openaiHandle.customId)
102
+ continue;
103
+ const response = get(item, "response");
104
+ const statusCode = Number(get(response, "status_code"));
105
+ const body = get(response, "body");
106
+ const error = get(item, "error");
107
+ if (error != null || (Number.isFinite(statusCode) && statusCode >= 400)) {
108
+ // Never surface the provider's own error text — only that this
109
+ // one item failed.
110
+ throw new ProviderBatchError("openai batch item returned an error response");
111
+ }
112
+ return { result: body, containedToolCallPlan: hasFunctionCall(body) };
113
+ }
114
+ throw new ProviderBatchError("openai batch output did not contain our submitted item");
115
+ },
116
+ async direct(request) {
117
+ const response = await client.responses.create(request);
118
+ return { result: response, containedToolCallPlan: hasFunctionCall(response) };
119
+ },
120
+ };
121
+ }
122
+ function hasToolUse(message) {
123
+ const content = get(message, "content");
124
+ if (!Array.isArray(content))
125
+ return false;
126
+ return content.some((block) => get(block, "type") === "tool_use");
127
+ }
128
+ function createAnthropicBatchAdapter(client) {
129
+ return {
130
+ eligibility(request) {
131
+ if (request.stream === true) {
132
+ return { eligible: false, reason: "streaming requests are direct-only" };
133
+ }
134
+ return { eligible: true };
135
+ },
136
+ async submitOne(request) {
137
+ const customId = randomCustomId();
138
+ const batch = await client.messages.batches.create({
139
+ requests: [{ custom_id: customId, params: request }],
140
+ });
141
+ const handle = { providerBatchId: batch.id, customId };
142
+ return handle;
143
+ },
144
+ async poll(handle) {
145
+ const batch = await client.messages.batches.retrieve(handle.providerBatchId);
146
+ if (batch.processing_status !== "ended")
147
+ return { status: "pending" };
148
+ // "ended" is itself a terminal signal — there is no un-ending it, so
149
+ // any bucket shape we don't recognize is bounded to "failed" rather
150
+ // than left pending forever.
151
+ const counts = batch.request_counts ?? {};
152
+ if ((counts.succeeded ?? 0) > 0)
153
+ return { status: "completed" };
154
+ if ((counts.expired ?? 0) > 0)
155
+ return { status: "expired" };
156
+ return { status: "failed" };
157
+ },
158
+ async readResult(handle) {
159
+ const anthropicHandle = handle;
160
+ for await (const item of client.messages.batches.results(handle.providerBatchId)) {
161
+ if (get(item, "custom_id") !== anthropicHandle.customId)
162
+ continue;
163
+ const result = get(item, "result");
164
+ if (get(result, "type") !== "succeeded") {
165
+ // Never surface the provider's own error text — only that this
166
+ // one item failed.
167
+ throw new ProviderBatchError("anthropic batch item did not succeed");
168
+ }
169
+ const message = get(result, "message");
170
+ return { result: message, containedToolCallPlan: hasToolUse(message) };
171
+ }
172
+ throw new ProviderBatchError("anthropic batch results did not contain our submitted item");
173
+ },
174
+ async direct(request) {
175
+ const response = await client.messages.create(request);
176
+ return { result: response, containedToolCallPlan: hasToolUse(response) };
177
+ },
178
+ };
179
+ }
180
+ const GOOGLE_TERMINAL_STATUS = {
181
+ JOB_STATE_SUCCEEDED: "completed",
182
+ JOB_STATE_FAILED: "failed",
183
+ JOB_STATE_CANCELLED: "failed",
184
+ JOB_STATE_EXPIRED: "expired",
185
+ };
186
+ function hasFunctionCallPart(response) {
187
+ const candidates = get(response, "candidates");
188
+ if (!Array.isArray(candidates))
189
+ return false;
190
+ return candidates.some((candidate) => {
191
+ const parts = get(get(candidate, "content"), "parts");
192
+ if (!Array.isArray(parts))
193
+ return false;
194
+ return parts.some((part) => get(part, "functionCall") != null || get(part, "function_call") != null);
195
+ });
196
+ }
197
+ function createGoogleBatchAdapter(client) {
198
+ return {
199
+ eligibility(request) {
200
+ if (request.stream === true) {
201
+ return { eligible: false, reason: "streaming requests are direct-only" };
202
+ }
203
+ return { eligible: true };
204
+ },
205
+ async submitOne(request) {
206
+ const { model, ...inlineRequest } = request;
207
+ if (typeof model !== "string" || model.trim().length === 0) {
208
+ throw new ProviderBatchError("google batch requests require a non-blank request.model");
209
+ }
210
+ const job = await client.batches.create({
211
+ model,
212
+ src: { inlinedRequests: [inlineRequest] },
213
+ });
214
+ const handle = { providerBatchId: job.name };
215
+ return handle;
216
+ },
217
+ async poll(handle) {
218
+ const job = await client.batches.get({ name: handle.providerBatchId });
219
+ const state = job.state ?? job.metadata?.state ?? "";
220
+ return { status: GOOGLE_TERMINAL_STATUS[state] ?? "pending" };
221
+ },
222
+ async readResult(handle) {
223
+ const job = await client.batches.get({ name: handle.providerBatchId });
224
+ const entries = job.dest?.inlinedResponses;
225
+ // A single-item batch is unambiguous by construction: index 0 is
226
+ // "our" item, the same way a custom_id would be for the other
227
+ // providers — there is no cross-item confusion possible here.
228
+ const entry = entries?.[0];
229
+ if (!entry) {
230
+ throw new ProviderBatchError("google batch produced no inline response");
231
+ }
232
+ if (entry.error != null) {
233
+ // Never surface the provider's own error text — only that this
234
+ // one item failed.
235
+ throw new ProviderBatchError("google batch item returned an error response");
236
+ }
237
+ if (!entry.response) {
238
+ throw new ProviderBatchError("google batch item had no response body");
239
+ }
240
+ return { result: entry.response, containedToolCallPlan: hasFunctionCallPart(entry.response) };
241
+ },
242
+ async direct(request) {
243
+ const response = await client.models.generateContent(request);
244
+ return { result: response, containedToolCallPlan: hasFunctionCallPart(response) };
245
+ },
246
+ };
247
+ }
@@ -18,5 +18,5 @@ export declare function discoverRepoConfig(appRoot: string): RepoConfig | undefi
18
18
  export declare function writeConfigAtomically(repoRoot: string, repository: string): RepoConfig | undefined;
19
19
  /** Discover an existing repo config, or detect+write one once at the git top
20
20
  * level. Fail-open: any detection or write failure returns undefined
21
- * (legacy protocol v1), never throws. */
21
+ * (app-token ingestion), never throws. */
22
22
  export declare function ensureRepoConfig(appRoot: string): RepoConfig | undefined;
@@ -1,5 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SUPPORTED_CONFIG_VERSION = exports.CONFIG_FILENAME = exports.CONFIG_DIRNAME = void 0;
4
+ exports.normalizeGithubRemote = normalizeGithubRemote;
5
+ exports.discoverRepoConfig = discoverRepoConfig;
6
+ exports.writeConfigAtomically = writeConfigAtomically;
7
+ exports.ensureRepoConfig = ensureRepoConfig;
1
8
  /**
2
- * Repository-aware ingest protocol v2: discover, detect, and write
9
+ * SDK 0.4+ repository-aware ingestion: discover, detect, and write
3
10
  * .metergraph/config.json.
4
11
  *
5
12
  * Discovery is purely file-based (never shells out to git), so a committed
@@ -8,13 +15,13 @@
8
15
  * out to git to find the repo's top level and GitHub origin, then writes the
9
16
  * config there exactly once. An existing file is always authoritative and is
10
17
  * never overwritten. Every failure mode here is fail-open -- callers get
11
- * undefined and fall back to legacy protocol v1, never a thrown error.
18
+ * undefined and fall back to app-token ingestion, never a thrown error.
12
19
  */
13
- import { closeSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, writeSync } from "node:fs";
14
- import { dirname, isAbsolute, join, resolve } from "node:path";
15
- export const CONFIG_DIRNAME = ".metergraph";
16
- export const CONFIG_FILENAME = "config.json";
17
- export const SUPPORTED_CONFIG_VERSION = 2;
20
+ const node_fs_1 = require("node:fs");
21
+ const node_path_1 = require("node:path");
22
+ exports.CONFIG_DIRNAME = ".metergraph";
23
+ exports.CONFIG_FILENAME = "config.json";
24
+ exports.SUPPORTED_CONFIG_VERSION = 2;
18
25
  const MAX_WALK_UP = 64;
19
26
  const REMOTE_PATTERNS = [
20
27
  /^git@github\.com:([^/]+\/[^/]+?)(\.git)?\/?$/,
@@ -23,7 +30,7 @@ const REMOTE_PATTERNS = [
23
30
  ];
24
31
  /** Return 'owner/repo' from a GitHub SSH or HTTPS remote URL, or undefined
25
32
  * if the URL isn't a recognized GitHub origin. */
26
- export function normalizeGithubRemote(url) {
33
+ function normalizeGithubRemote(url) {
27
34
  const trimmed = url.trim();
28
35
  for (const pattern of REMOTE_PATTERNS) {
29
36
  const match = pattern.exec(trimmed);
@@ -35,14 +42,14 @@ export function normalizeGithubRemote(url) {
35
42
  function load(path, repoRoot) {
36
43
  let doc;
37
44
  try {
38
- doc = JSON.parse(readFileSync(path, "utf8"));
45
+ doc = JSON.parse((0, node_fs_1.readFileSync)(path, "utf8"));
39
46
  }
40
47
  catch (error) {
41
48
  console.warn(`metergraph: found ${path} but could not read it: ${error instanceof Error ? error.message : String(error)}`);
42
49
  return undefined;
43
50
  }
44
- if (typeof doc !== "object" || doc === null || doc.version !== SUPPORTED_CONFIG_VERSION) {
45
- console.warn(`metergraph: ${path} has an unsupported schema version; ignoring (expected version ${SUPPORTED_CONFIG_VERSION})`);
51
+ if (typeof doc !== "object" || doc === null || (doc.version ?? exports.SUPPORTED_CONFIG_VERSION) !== exports.SUPPORTED_CONFIG_VERSION) {
52
+ console.warn(`metergraph: ${path} has an unsupported schema version; ignoring (expected version ${exports.SUPPORTED_CONFIG_VERSION})`);
46
53
  return undefined;
47
54
  }
48
55
  const repository = doc.repository;
@@ -54,24 +61,24 @@ function load(path, repoRoot) {
54
61
  }
55
62
  /** Walk upward from appRoot looking for .metergraph/config.json. Returns
56
63
  * undefined -- silently, the normal v1 state -- when nothing is found. */
57
- export function discoverRepoConfig(appRoot) {
64
+ function discoverRepoConfig(appRoot) {
58
65
  let current;
59
66
  try {
60
- current = realpathSync(appRoot);
67
+ current = (0, node_fs_1.realpathSync)(appRoot);
61
68
  }
62
69
  catch {
63
70
  return undefined;
64
71
  }
65
72
  for (let i = 0; i < MAX_WALK_UP; i += 1) {
66
- const candidate = join(current, CONFIG_DIRNAME, CONFIG_FILENAME);
73
+ const candidate = (0, node_path_1.join)(current, exports.CONFIG_DIRNAME, exports.CONFIG_FILENAME);
67
74
  try {
68
- readFileSync(candidate);
75
+ (0, node_fs_1.readFileSync)(candidate);
69
76
  return load(candidate, current);
70
77
  }
71
78
  catch {
72
79
  // no config at this level; keep walking up
73
80
  }
74
- const parent = dirname(current);
81
+ const parent = (0, node_path_1.dirname)(current);
75
82
  if (parent === current)
76
83
  break;
77
84
  current = parent;
@@ -79,15 +86,15 @@ export function discoverRepoConfig(appRoot) {
79
86
  return undefined;
80
87
  }
81
88
  function gitDirectory(repoRoot) {
82
- const marker = join(repoRoot, ".git");
89
+ const marker = (0, node_path_1.join)(repoRoot, ".git");
83
90
  try {
84
- if (statSync(marker).isDirectory())
91
+ if ((0, node_fs_1.statSync)(marker).isDirectory())
85
92
  return marker;
86
- const match = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, "utf8"));
93
+ const match = /^gitdir:\s*(.+)$/m.exec((0, node_fs_1.readFileSync)(marker, "utf8"));
87
94
  const path = match?.[1];
88
95
  if (!path)
89
96
  return undefined;
90
- return isAbsolute(path) ? path : resolve(repoRoot, path);
97
+ return (0, node_path_1.isAbsolute)(path) ? path : (0, node_path_1.resolve)(repoRoot, path);
91
98
  }
92
99
  catch {
93
100
  return undefined;
@@ -97,7 +104,7 @@ function ownedByCurrentUser(path) {
97
104
  if (typeof process.getuid !== "function")
98
105
  return true;
99
106
  try {
100
- return statSync(path).uid === process.getuid();
107
+ return (0, node_fs_1.statSync)(path).uid === process.getuid();
101
108
  }
102
109
  catch {
103
110
  return false;
@@ -105,7 +112,7 @@ function ownedByCurrentUser(path) {
105
112
  }
106
113
  function gitTopLevel(appRoot) {
107
114
  try {
108
- let current = realpathSync(appRoot);
115
+ let current = (0, node_fs_1.realpathSync)(appRoot);
109
116
  for (let i = 0; i < MAX_WALK_UP; i += 1) {
110
117
  const gitDir = gitDirectory(current);
111
118
  if (gitDir) {
@@ -116,7 +123,7 @@ function gitTopLevel(appRoot) {
116
123
  ? current
117
124
  : undefined;
118
125
  }
119
- const parent = dirname(current);
126
+ const parent = (0, node_path_1.dirname)(current);
120
127
  if (parent === current)
121
128
  break;
122
129
  current = parent;
@@ -134,14 +141,14 @@ function gitOriginUrl(repoRoot) {
134
141
  return undefined;
135
142
  let commonDir = gitDir;
136
143
  try {
137
- const relative = readFileSync(join(gitDir, "commondir"), "utf8").trim();
144
+ const relative = (0, node_fs_1.readFileSync)((0, node_path_1.join)(gitDir, "commondir"), "utf8").trim();
138
145
  if (relative)
139
- commonDir = resolve(gitDir, relative);
146
+ commonDir = (0, node_path_1.resolve)(gitDir, relative);
140
147
  }
141
148
  catch {
142
149
  // Normal repositories keep config directly in .git.
143
150
  }
144
- const config = readFileSync(join(commonDir, "config"), "utf8");
151
+ const config = (0, node_fs_1.readFileSync)((0, node_path_1.join)(commonDir, "config"), "utf8");
145
152
  let inOrigin = false;
146
153
  for (const line of config.split(/\r?\n/)) {
147
154
  const section = /^\s*\[remote\s+"([^"]+)"\]\s*$/.exec(line);
@@ -167,18 +174,18 @@ function gitOriginUrl(repoRoot) {
167
174
  * exist. Uses O_CREAT|O_EXCL ("wx") for an atomic create-only-if-absent; a
168
175
  * concurrent writer (or a file that appeared between discovery and this
169
176
  * call) always wins over us, and we simply read back whatever is there. */
170
- export function writeConfigAtomically(repoRoot, repository) {
171
- const configDir = join(repoRoot, CONFIG_DIRNAME);
172
- const configPath = join(configDir, CONFIG_FILENAME);
173
- const payload = `${JSON.stringify({ version: SUPPORTED_CONFIG_VERSION, repository })}\n`;
177
+ function writeConfigAtomically(repoRoot, repository) {
178
+ const configDir = (0, node_path_1.join)(repoRoot, exports.CONFIG_DIRNAME);
179
+ const configPath = (0, node_path_1.join)(configDir, exports.CONFIG_FILENAME);
180
+ const payload = `${JSON.stringify({ version: exports.SUPPORTED_CONFIG_VERSION, repository })}\n`;
174
181
  try {
175
- mkdirSync(configDir, { recursive: true });
176
- const fd = openSync(configPath, "wx", 0o644);
182
+ (0, node_fs_1.mkdirSync)(configDir, { recursive: true });
183
+ const fd = (0, node_fs_1.openSync)(configPath, "wx", 0o644);
177
184
  try {
178
- writeSync(fd, payload);
185
+ (0, node_fs_1.writeSync)(fd, payload);
179
186
  }
180
187
  finally {
181
- closeSync(fd);
188
+ (0, node_fs_1.closeSync)(fd);
182
189
  }
183
190
  }
184
191
  catch (error) {
@@ -191,8 +198,8 @@ export function writeConfigAtomically(repoRoot, repository) {
191
198
  }
192
199
  /** Discover an existing repo config, or detect+write one once at the git top
193
200
  * level. Fail-open: any detection or write failure returns undefined
194
- * (legacy protocol v1), never throws. */
195
- export function ensureRepoConfig(appRoot) {
201
+ * (app-token ingestion), never throws. */
202
+ function ensureRepoConfig(appRoot) {
196
203
  const existing = discoverRepoConfig(appRoot);
197
204
  if (existing)
198
205
  return existing;
package/dist/session.js CHANGED
@@ -1,5 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionManager = exports.MAX_BACKOFF_MS = exports.REFRESH_MARGIN_MS = exports.DEFAULT_TTL_MS = exports.DEFAULT_TIMEOUT_MS = void 0;
1
4
  /**
2
- * Repository-aware ingest protocol v2: app-token -> session-token exchange.
5
+ * SDK 0.4+ repository-aware ingestion: app-token -> session-token exchange.
3
6
  *
4
7
  * The app token is sent only on POST /v1/ingest/sessions. The resulting
5
8
  * session token is cached in memory and reused until it's within
@@ -10,30 +13,30 @@
10
13
  * mode is fail-open: getToken() resolves to undefined and callers drop that
11
14
  * batch rather than ever sending the app token to /v1/ingest.
12
15
  */
13
- import { FailureLogger } from "./failure-log.js";
14
- export const DEFAULT_TIMEOUT_MS = 3_000;
15
- export const DEFAULT_TTL_MS = 300_000;
16
- export const REFRESH_MARGIN_MS = 30_000;
17
- export const MAX_BACKOFF_MS = 60_000;
16
+ const failure_log_js_1 = require("./failure-log.js");
17
+ exports.DEFAULT_TIMEOUT_MS = 3_000;
18
+ exports.DEFAULT_TTL_MS = 300_000;
19
+ exports.REFRESH_MARGIN_MS = 30_000;
20
+ exports.MAX_BACKOFF_MS = 60_000;
18
21
  function parseExpiresAt(value) {
19
22
  if (typeof value !== "string")
20
23
  return undefined;
21
24
  const parsed = Date.parse(value);
22
25
  return Number.isNaN(parsed) ? undefined : parsed;
23
26
  }
24
- export class SessionManager {
27
+ class SessionManager {
25
28
  appToken;
26
29
  repository;
27
30
  sdkVersion;
28
31
  timeoutMs;
29
32
  url;
30
- failureLog = new FailureLogger();
33
+ failureLog = new failure_log_js_1.FailureLogger();
31
34
  token;
32
35
  expiresAt = 0;
33
36
  stopped = false;
34
37
  retryAt = 0;
35
38
  backoffMs = 1_000;
36
- constructor(appToken, baseUrl, repository, sdkVersion, timeoutMs = DEFAULT_TIMEOUT_MS) {
39
+ constructor(appToken, baseUrl, repository, sdkVersion, timeoutMs = exports.DEFAULT_TIMEOUT_MS) {
37
40
  this.appToken = appToken;
38
41
  this.repository = repository;
39
42
  this.sdkVersion = sdkVersion;
@@ -43,7 +46,7 @@ export class SessionManager {
43
46
  async getToken() {
44
47
  if (this.stopped)
45
48
  return undefined;
46
- if (this.token !== undefined && Date.now() < this.expiresAt - REFRESH_MARGIN_MS) {
49
+ if (this.token !== undefined && Date.now() < this.expiresAt - exports.REFRESH_MARGIN_MS) {
47
50
  return this.token;
48
51
  }
49
52
  if (Date.now() < this.retryAt)
@@ -89,7 +92,7 @@ export class SessionManager {
89
92
  this.markFailed();
90
93
  return;
91
94
  }
92
- const expiresAt = parseExpiresAt(doc?.expires_at) ?? Date.now() + DEFAULT_TTL_MS;
95
+ const expiresAt = parseExpiresAt(doc?.expires_at) ?? Date.now() + exports.DEFAULT_TTL_MS;
93
96
  if (!this.stopped) {
94
97
  this.token = token;
95
98
  this.expiresAt = expiresAt;
@@ -104,6 +107,7 @@ export class SessionManager {
104
107
  }
105
108
  markFailed() {
106
109
  this.retryAt = Date.now() + this.backoffMs;
107
- this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
110
+ this.backoffMs = Math.min(this.backoffMs * 2, exports.MAX_BACKOFF_MS);
108
111
  }
109
112
  }
113
+ exports.SessionManager = SessionManager;
package/dist/template.js CHANGED
@@ -1,3 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scrub = scrub;
4
+ exports.templateHash = templateHash;
1
5
  const sensitive = new Set([
2
6
  "api-key",
3
7
  "api_key",
@@ -15,7 +19,7 @@ const sensitive = new Set([
15
19
  "token",
16
20
  "x-api-key",
17
21
  ]);
18
- export function scrub(value) {
22
+ function scrub(value) {
19
23
  if (Array.isArray(value))
20
24
  return value.map(scrub);
21
25
  if (value && typeof value === "object") {
@@ -52,6 +56,6 @@ function fnv1a(value) {
52
56
  }
53
57
  return hash.toString(16).padStart(16, "0");
54
58
  }
55
- export function templateHash(request) {
59
+ function templateHash(request) {
56
60
  return fnv1a(JSON.stringify(normalized(scrub(request))));
57
61
  }
package/dist/track.js CHANGED
@@ -1,11 +1,14 @@
1
- import { contextSnapshot, runWithContext } from "./context.js";
2
- export function track(nameOrFn, maybeFn) {
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.track = track;
4
+ const context_js_1 = require("./context.js");
5
+ function track(nameOrFn, maybeFn) {
3
6
  const fn = typeof nameOrFn === "string" ? maybeFn : nameOrFn;
4
7
  if (typeof fn !== "function")
5
8
  throw new TypeError("track requires a function");
6
9
  const funcName = typeof nameOrFn === "string" ? nameOrFn : fn.name || "<anonymous>";
7
10
  const wrapped = function (...args) {
8
- return runWithContext({ ...contextSnapshot(), funcName }, () => fn.apply(this, args));
11
+ return (0, context_js_1.runWithContext)({ ...(0, context_js_1.contextSnapshot)(), funcName }, () => fn.apply(this, args));
9
12
  };
10
13
  return wrapped;
11
14
  }
package/dist/transport.js CHANGED
@@ -1,5 +1,8 @@
1
- import { FailureLogger } from "./failure-log.js";
2
- export const MAX_BATCH_BYTES = 512 * 1024;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = exports.MAX_BATCH_BYTES = void 0;
4
+ const failure_log_js_1 = require("./failure-log.js");
5
+ exports.MAX_BATCH_BYTES = 512 * 1024;
3
6
  function detectedMode() {
4
7
  const env = typeof process === "undefined" ? {} : process.env;
5
8
  const agent = typeof navigator === "undefined" ? "" : navigator.userAgent;
@@ -13,7 +16,7 @@ async function gzipBody(body) {
13
16
  const source = new Blob([body]).stream();
14
17
  return new Response(source.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
15
18
  }
16
- export class Transport {
19
+ class Transport {
17
20
  token;
18
21
  baseUrl;
19
22
  queue = [];
@@ -29,7 +32,7 @@ export class Transport {
29
32
  errors = 0;
30
33
  retryAt = 0;
31
34
  backoffMs = 1_000;
32
- failureLog = new FailureLogger();
35
+ failureLog = new failure_log_js_1.FailureLogger();
33
36
  session;
34
37
  constructor(token, baseUrl, options = {}) {
35
38
  this.token = token;
@@ -114,7 +117,7 @@ export class Transport {
114
117
  const raw = encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
115
118
  const compressed = raw.byteLength > 32 * 1024;
116
119
  const body = compressed ? await gzipBody(raw) : raw;
117
- if (body.byteLength > MAX_BATCH_BYTES) {
120
+ if (body.byteLength > exports.MAX_BATCH_BYTES) {
118
121
  if (rows.length === 1) {
119
122
  this.dropped += 1;
120
123
  return;
@@ -175,3 +178,4 @@ export class Transport {
175
178
  await this.flush();
176
179
  }
177
180
  }
181
+ exports.Transport = Transport;
package/dist/vercel-ai.js CHANGED
@@ -1,5 +1,8 @@
1
- import { chunkText } from "./capture.js";
2
- import { getCaptureRuntime } from "./wrap.js";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createVercelAISDKMiddleware = createVercelAISDKMiddleware;
4
+ const capture_js_1 = require("./capture.js");
5
+ const wrap_js_1 = require("./wrap.js");
3
6
  const GATEWAY_PROVIDERS = new Set(["gateway", "vercel", "vercel-ai-gateway"]);
4
7
  function canonicalProvider(provider, modelId) {
5
8
  const raw = String(provider ?? "unknown").trim().toLowerCase();
@@ -82,7 +85,7 @@ function wrapStreamResult(result, capture, state, started) {
82
85
  const observe = (part) => {
83
86
  if (firstOutputAt === undefined && outputChunk(part))
84
87
  firstOutputAt = performance.now();
85
- const delta = chunkText(part);
88
+ const delta = (0, capture_js_1.chunkText)(part);
86
89
  if (delta !== undefined)
87
90
  text += delta;
88
91
  if (["tool-call", "tool-result", "tool-error", "file", "source"].includes(part?.type)) {
@@ -146,7 +149,7 @@ function wrapStreamResult(result, capture, state, started) {
146
149
  });
147
150
  return { ...result, stream };
148
151
  }
149
- export function createVercelAISDKMiddleware(options = {}) {
152
+ function createVercelAISDKMiddleware(options = {}) {
150
153
  if (options.aiSdkVersion === 5 && options.specificationVersion !== undefined) {
151
154
  throw new TypeError("aiSdkVersion and specificationVersion cannot be combined");
152
155
  }
@@ -154,7 +157,7 @@ export function createVercelAISDKMiddleware(options = {}) {
154
157
  return {
155
158
  specificationVersion,
156
159
  async wrapGenerate({ doGenerate, params, model }) {
157
- const capture = getCaptureRuntime();
160
+ const capture = (0, wrap_js_1.getCaptureRuntime)();
158
161
  if (!capture)
159
162
  return await doGenerate();
160
163
  const state = startCapture(capture, "generate", params, model);
@@ -169,7 +172,7 @@ export function createVercelAISDKMiddleware(options = {}) {
169
172
  }
170
173
  },
171
174
  async wrapStream({ doStream, params, model }) {
172
- const capture = getCaptureRuntime();
175
+ const capture = (0, wrap_js_1.getCaptureRuntime)();
173
176
  if (!capture)
174
177
  return await doStream();
175
178
  const started = performance.now();
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.4.0";
1
+ export declare const SDK_VERSION = "0.6.0";
package/dist/version.js CHANGED
@@ -1 +1,4 @@
1
- export const SDK_VERSION = "0.4.0";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SDK_VERSION = void 0;
4
+ exports.SDK_VERSION = "0.6.0";