@north-light/sdk 0.3.720 → 0.3.722

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.
@@ -40,17 +40,24 @@ export interface InferenceEndpointOptions {
40
40
  apiKey: string;
41
41
  /** Strength to model: `anthropic/<model id>` for each rung the endpoint serves. A request naming any other model is refused. Every model needs a list price in this SDK; the constructor throws for one that has none. */
42
42
  rungs: Partial<Record<InferenceRung, string>>;
43
- /** The app's `OAuth2Client.directoryToken`: a directory API token as the app, re-minted when called with the token the directory just refused. */
44
- directoryToken: (rejected?: string) => Promise<string>;
45
- /** Where usage reports wait until the directory accepts them. */
46
- settlements: SettlementStore;
43
+ /** The app's `OAuth2Client.directoryToken`: a directory API token as the app, re-minted when called with the token the directory just refused. Required unless `billing` is `'app'`. */
44
+ directoryToken?: (rejected?: string) => Promise<string>;
45
+ /** Where usage reports wait until the directory accepts them. Required unless `billing` is `'app'`. */
46
+ settlements?: SettlementStore;
47
47
  /** Called with ids, model and the vendor's token counts only: never the prompt, the answer or a key. */
48
48
  log?: (entry: Record<string, unknown>) => void;
49
49
  /** The `fetch` used for the directory, its keys and the upstream call (default: the global `fetch`). */
50
50
  fetch?: typeof fetch;
51
+ /**
52
+ * `'app'`: the app pays for its own model calls, the path for any app outside the Northlight team. The runtime's token is still
53
+ * verified against the directory's keys, but the directory's `admit-model` and `settle-model` (which refuse such apps) are never
54
+ * called: every call goes to Anthropic with `apiKey`, Northlight records no charge, usage goes only to `log`, `sweep` does nothing.
55
+ * `directoryToken` and `settlements` are then not needed. Omitted (default): Northlight's own billing, where both are required.
56
+ */
57
+ billing?: 'app';
51
58
  }
52
59
  /**
53
- * The server side of an app whose model calls Northlight pays for or bills: a handler for `POST <baseURL>/anthropic/v1/messages`
60
+ * The server side of an app's model endpoint. A third-party app passes `billing: 'app'` (see `billing`) and pays Anthropic on its own key with no directory billing calls. The rest of this comment describes the default, where Northlight pays for or bills the calls: a handler for `POST <baseURL>/anthropic/v1/messages`
54
61
  * that serves a person's runtime the Anthropic Messages API. Mount `handle` at the path of `baseURL`; call `sweep` on a timer.
55
62
  *
56
63
  * The request carries a directory token (`x-api-key` or `Authorization: Bearer`) that the handler verifies (issuer, `aud` =
@@ -143,7 +143,7 @@ function chargedBody(body, contentType, charge) {
143
143
  }));
144
144
  }
145
145
  /**
146
- * The server side of an app whose model calls Northlight pays for or bills: a handler for `POST <baseURL>/anthropic/v1/messages`
146
+ * The server side of an app's model endpoint. A third-party app passes `billing: 'app'` (see `billing`) and pays Anthropic on its own key with no directory billing calls. The rest of this comment describes the default, where Northlight pays for or bills the calls: a handler for `POST <baseURL>/anthropic/v1/messages`
147
147
  * that serves a person's runtime the Anthropic Messages API. Mount `handle` at the path of `baseURL`; call `sweep` on a timer.
148
148
  *
149
149
  * The request carries a directory token (`x-api-key` or `Authorization: Bearer`) that the handler verifies (issuer, `aud` =
@@ -184,6 +184,10 @@ export function inferenceEndpoint(options) {
184
184
  throw new Error('inferenceEndpoint: rungs must name at least one model');
185
185
  const issuerBase = options.issuer.replace(/\/+$/, '');
186
186
  const jwks = new JwksCache(options.issuer, (input, init) => upstreamFetch(input, init), `${issuerBase}/.well-known/jwks.json`);
187
+ const appPaid = options.billing === 'app';
188
+ if (!appPaid && (options.directoryToken === undefined || options.settlements === undefined))
189
+ throw new Error("inferenceEndpoint: directoryToken and settlements are required unless billing is 'app'");
190
+ const billed = appPaid ? undefined : { directoryToken: options.directoryToken, settlements: options.settlements };
187
191
  const vendorRefPrefix = options.app.replace(/^app:/, '');
188
192
  /** A POST to the directory as the app; a 401 hands the refused token back and retries once with a fresh one. */
189
193
  const directoryPost = async (path, body) => {
@@ -193,10 +197,11 @@ export function inferenceEndpoint(options) {
193
197
  body: JSON.stringify(body),
194
198
  signal: AbortSignal.timeout(DIRECTORY_TIMEOUT_MS),
195
199
  });
196
- const token = await options.directoryToken();
200
+ const tokens = billed.directoryToken;
201
+ const token = await tokens();
197
202
  let response = await send(token);
198
203
  if (response.status === 401)
199
- response = await send(await options.directoryToken(token));
204
+ response = await send(await tokens(token));
200
205
  return { status: response.status, json: await response.json().catch(() => undefined) };
201
206
  };
202
207
  /** Asks the directory to admit one model call. Anything but an explicit admission or a payment refusal is a refusal to serve. */
@@ -250,11 +255,11 @@ export function inferenceEndpoint(options) {
250
255
  log({ settle_status: status, admission: settlement.admission_id });
251
256
  return false;
252
257
  }
253
- await options.settlements.remove(settlement.admission_id);
258
+ await billed.settlements.remove(settlement.admission_id);
254
259
  return true;
255
260
  };
256
261
  const record = async (settlement) => {
257
- await options.settlements.save(settlement);
262
+ await billed.settlements.save(settlement);
258
263
  for (let attempt = 0; attempt < IMMEDIATE_ATTEMPTS; attempt++) {
259
264
  if (await deliver(settlement))
260
265
  return;
@@ -263,10 +268,12 @@ export function inferenceEndpoint(options) {
263
268
  }
264
269
  };
265
270
  const sweep = async (now = new Date()) => {
266
- for (const { settlement, attempts } of await options.settlements.due(now, SWEEP_BATCH)) {
271
+ if (billed === undefined)
272
+ return;
273
+ for (const { settlement, attempts } of await billed.settlements.due(now, SWEEP_BATCH)) {
267
274
  if (await deliver(settlement))
268
275
  continue;
269
- await options.settlements.retryLater(settlement.admission_id, new Date(now.getTime() + backoffMs(attempts + 1)), attempts + 1);
276
+ await billed.settlements.retryLater(settlement.admission_id, new Date(now.getTime() + backoffMs(attempts + 1)), attempts + 1);
270
277
  }
271
278
  };
272
279
  const handle = async (request) => {
@@ -308,7 +315,9 @@ export function inferenceEndpoint(options) {
308
315
  return refuse(400, 'invalid_request', 'The request body must be JSON naming a model.');
309
316
  if (!served.has(model))
310
317
  return refuse(404, 'model_unavailable', `This endpoint does not serve ${model}.`);
311
- const admission = await admit(token, model);
318
+ const admission = appPaid
319
+ ? { kind: 'admitted', admissionId: crypto.randomUUID(), chargeId: '', pool: undefined }
320
+ : await admit(token, model);
312
321
  if (admission.kind === 'refused') {
313
322
  return Response.json({ type: 'error', error: { type: 'invalid_request_error', message: admission.payment.message }, payment: admission.payment }, { status: 402 });
314
323
  }
@@ -364,7 +373,8 @@ export function inferenceEndpoint(options) {
364
373
  if (answer.body === null || !answer.ok) {
365
374
  return new Response(answer.body, { status: answer.status, statusText: answer.statusText, headers: responseHeaders });
366
375
  }
367
- responseHeaders.set('Crtr-Charge-Id', admission.chargeId);
376
+ if (!appPaid)
377
+ responseHeaders.set('Crtr-Charge-Id', admission.chargeId);
368
378
  const [toCaller, toUsage] = answer.body.tee();
369
379
  const vendorRef = answer.headers.get('request-id') ?? `${vendorRefPrefix}:${admission.admissionId}`;
370
380
  const contentType = answer.headers.get('content-type') ?? '';
@@ -408,10 +418,11 @@ export function inferenceEndpoint(options) {
408
418
  if (result === undefined)
409
419
  return;
410
420
  const { settlement, usage } = result;
411
- await record(settlement);
421
+ if (!appPaid)
422
+ await record(settlement);
412
423
  log({ sub, model, served_model: settlement.served_model, admission: admission.admissionId, upstream, list_usd: settlement.list_usd, cost_usd: settlement.cost_usd, usage });
413
424
  }).catch((error) => { log({ sub, admission: admission.admissionId, settle_failed: String(error) }); });
414
- const charge = calculated.then((result) => result === undefined ? undefined : { id: admission.chargeId, served_model: result.settlement.served_model, list_usd: result.settlement.list_usd }, () => undefined);
425
+ const charge = calculated.then((result) => result === undefined || appPaid ? undefined : { id: admission.chargeId, served_model: result.settlement.served_model, list_usd: result.settlement.list_usd }, () => undefined);
415
426
  return new Response(chargedBody(toCaller, contentType, charge), { status: answer.status, statusText: answer.statusText, headers: responseHeaders });
416
427
  };
417
428
  return { handle, sweep };
@@ -2,7 +2,7 @@
2
2
  name: northlight
3
3
  description: "Use when building, debugging or shipping an app that signs people in with Northlight, starts runs on their Northlight runtime, or calls Northlight providers (sms, search, integrations, context, device) with @north-light/sdk."
4
4
  metadata:
5
- sdk-version: "0.3.720"
5
+ sdk-version: "0.3.722"
6
6
  ---
7
7
 
8
8
  # Building a Northlight app
@@ -27,7 +27,7 @@ Never text a person first: Comms refuses a send to anyone who has not texted you
27
27
 
28
28
  ## First: check this skill matches the SDK
29
29
 
30
- This skill is for SDK version `0.3.720`. If the project has `node_modules/@north-light/sdk/package.json`, compare its `version` with that number. If they differ, run `npx @north-light/sdk skill` in the project, then read the rewritten `.agents/skills/northlight/SKILL.md` (or `.claude/skills/northlight/SKILL.md`) instead of this copy. It needs no account. A project that has no SDK yet starts with `npx @north-light/sdk@latest init <dir>`.
30
+ This skill is for SDK version `0.3.722`. If the project has `node_modules/@north-light/sdk/package.json`, compare its `version` with that number. If they differ, run `npx @north-light/sdk skill` in the project, then read the rewritten `.agents/skills/northlight/SKILL.md` (or `.claude/skills/northlight/SKILL.md`) instead of this copy. It needs no account. A project that has no SDK yet starts with `npx @north-light/sdk@latest init <dir>`.
31
31
 
32
32
  ## Where things run
33
33
 
package/dist/version.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** This SDK's release version. Informational only: compatibility is the contract level, not this number. */
2
- export declare const SDK_VERSION = "0.3.720";
2
+ export declare const SDK_VERSION = "0.3.722";
3
3
  /** The release sent in `Crouter-Minimum-Runtime-Version` on every request. It is frozen, so a runtime from before the
4
4
  * contract level existed (which only knows this header) refuses this SDK, while every later runtime accepts it. */
5
5
  export declare const LEGACY_FLOOR = "0.3.423";
package/dist/version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // SDK_VERSION is written by scripts/release-version.mjs on every release; do not edit by hand.
2
2
  /** This SDK's release version. Informational only: compatibility is the contract level, not this number. */
3
- export const SDK_VERSION = '0.3.720';
3
+ export const SDK_VERSION = '0.3.722';
4
4
  // LEGACY_FLOOR is written once by `scripts/contract.mjs release`, at the first release that carries the contract level
5
5
  // (the `0.0.0` placeholder is replaced there and never again); do not edit by hand.
6
6
  /** The release sent in `Crouter-Minimum-Runtime-Version` on every request. It is frozen, so a runtime from before the
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@north-light/sdk",
3
- "version": "0.3.720",
4
- "crouterContract": "1.70",
3
+ "version": "0.3.722",
4
+ "crouterContract": "1.71",
5
5
  "description": "Typed Node and browser client for running crouter agents through the crtrd /v1 API.",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -44,9 +44,9 @@
44
44
  "prepublishOnly": "node -e \"if (process.env.npm_config_tag !== 'next') { console.error('@north-light/sdk publishes only with --tag next; scripts/promote-sdk.mjs is the only mover of latest.'); process.exit(1); }\""
45
45
  },
46
46
  "dependencies": {
47
- "@north-light/api": "0.3.720",
48
- "@north-light/identity": "0.3.720",
49
- "@north-light/plugin": "0.3.720",
47
+ "@north-light/api": "0.3.722",
48
+ "@north-light/identity": "0.3.722",
49
+ "@north-light/plugin": "0.3.722",
50
50
  "jose": "^6.2.1"
51
51
  },
52
52
  "peerDependencies": {