@mupt-ai/dari-gateway 1.0.342 → 1.0.344

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.
@@ -48,6 +48,7 @@ import {
48
48
  linkHash,
49
49
  linkSecret,
50
50
  LINK_TOKEN_RETENTION_MS,
51
+ registeredRedirect,
51
52
  TOKEN_PREFIX,
52
53
  } from "./grants.js";
53
54
 
@@ -91,6 +92,7 @@ export type LinkStore = LinkRepo & {
91
92
  codeExpiresAt: number;
92
93
  credentialIds: string[];
93
94
  budget: LinkBudget[];
95
+ limits: LinkLimit[];
94
96
  now: number;
95
97
  }): MaybePromise<string | null>;
96
98
  /**
@@ -167,13 +169,13 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
167
169
  };
168
170
 
169
171
  // A grant's budget windows and each granted plan or key's spend this month.
170
- const standings = async (grant: LinkGrantRecord, now = new Date()): Promise<{
172
+ const standings = async (grant: LinkGrantRecord, known?: LinkSubscription[], now = new Date()): Promise<{
171
173
  budget: LinkBudgetStanding[];
172
174
  spend: LinkSpend[];
173
175
  }> => {
174
176
  const [uses, plans] = await Promise.all([
175
177
  store.budgetUses(grant.id, usesSince(grant.budget, now)),
176
- users.plansWithIds(grant.credentialIds),
178
+ known ?? users.plansWithIds(grant.credentialIds),
177
179
  ]);
178
180
  return {
179
181
  budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
@@ -258,15 +260,17 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
258
260
  },
259
261
  async grant(subject, grantId, clientId) {
260
262
  const grant = await ownGrant(subject, grantId);
261
- return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget };
263
+ return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget, limits: grant.limits };
262
264
  },
263
265
  async approve(request) {
264
- const owned = new Set((await users.plans(request.subject)).map((plan) => plan.id));
266
+ const plans = await users.plans(request.subject);
267
+ const owned = new Set(plans.map((plan) => plan.id));
265
268
  if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => owned.has(id))) {
266
269
  throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
267
270
  }
271
+ requireLimitsFit(request.limits, request.credentialIds, plans);
268
272
  const app = await store.appRecord(request.clientId);
269
- if (app === null || !app.redirectUris.includes(request.redirectUri)) {
273
+ if (app === null || !registeredRedirect(app.redirectUris, request.redirectUri)) {
270
274
  throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
271
275
  }
272
276
  const code = linkSecret(LINK_CODE_PREFIX);
@@ -281,22 +285,30 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
281
285
  codeExpiresAt: now + LINK_CODE_TTL_MS,
282
286
  credentialIds: [...new Set(request.credentialIds)].sort(),
283
287
  budget: request.budget,
288
+ limits: request.limits,
284
289
  now,
285
290
  });
286
291
  if (grantId === null) throw new HttpError(400, "That connection no longer exists.", "invalid_request");
287
292
  return { code };
288
293
  },
289
294
  async connections(subject) {
290
- return await Promise.all((await store.grants(subject)).map(async (grant) => {
291
- const { byModel: _, ...usage } = await protocol.usage(grant.id, { tags: {} });
295
+ const grants = await store.grants(subject);
296
+ // One lookup for every grant's plans, not one per grant per use.
297
+ const plans = await users.plansWithIds([...new Set(grants.flatMap((grant) => grant.credentialIds))]);
298
+ return await Promise.all(grants.map(async (grant) => {
299
+ const shared = plans.filter((plan) => grant.credentialIds.includes(plan.id));
300
+ const [{ byModel: _, ...usage }, standing] = await Promise.all([
301
+ protocol.usage(grant.id, { tags: {} }),
302
+ standings(grant, shared),
303
+ ]);
292
304
  return {
293
305
  id: grant.id,
294
306
  clientId: grant.clientId,
295
307
  appName: grant.appName,
296
308
  endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
297
309
  createdAt: grant.createdAt,
298
- ...(await standings(grant)),
299
- subscriptions: await users.plansWithIds(grant.credentialIds),
310
+ ...standing,
311
+ subscriptions: shared,
300
312
  usage,
301
313
  };
302
314
  }));
@@ -326,6 +338,10 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
326
338
  const { clientSecretHash: _, ...app } = record;
327
339
  return app;
328
340
  },
341
+ async authenticateClient(request) {
342
+ const { clientSecretHash: _, ...app } = await protocol.authenticateClient(request);
343
+ return app;
344
+ },
329
345
  exchangeCode: (request) => protocol.exchangeCode(request),
330
346
  refresh: (request) => protocol.refresh(request),
331
347
  exchangeToken: (request) => protocol.exchangeToken(request),
@@ -301,14 +301,16 @@ export class SqliteLinkStore implements LinkStore {
301
301
 
302
302
  saveGrant(request: Parameters<LinkStore["saveGrant"]>[0]): string | null {
303
303
  const budget = request.budget.length === 0 ? null : JSON.stringify(request.budget);
304
+ const limits = request.limits.length === 0 ? null : JSON.stringify(request.limits);
304
305
  if (request.grantId !== undefined) {
305
306
  const updated = this.db.run(
306
- `UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
307
+ `UPDATE link_grants SET credential_ids = ?, budget = ?, limits = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
307
308
  code_expires_at = ?
308
309
  WHERE id = ? AND client_id = ? AND subject = ? AND revoked_at IS NULL`,
309
310
  [
310
311
  JSON.stringify(request.credentialIds),
311
312
  budget,
313
+ limits,
312
314
  request.codeHash,
313
315
  request.codeChallenge,
314
316
  request.redirectUri,
@@ -323,8 +325,8 @@ export class SqliteLinkStore implements LinkStore {
323
325
  const id = `lgr_${randomUUID().replaceAll("-", "")}`;
324
326
  this.db.run(
325
327
  `INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
326
- code_expires_at, created_at, budget, subject)
327
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
328
+ code_expires_at, created_at, budget, limits, subject)
329
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
328
330
  [
329
331
  id,
330
332
  request.clientId,
@@ -335,6 +337,7 @@ export class SqliteLinkStore implements LinkStore {
335
337
  request.codeExpiresAt,
336
338
  request.now,
337
339
  budget,
340
+ limits,
338
341
  request.subject,
339
342
  ],
340
343
  );
@@ -141,6 +141,8 @@ export type LinkPlatform = {
141
141
  }): Promise<LinkApp & { clientSecret?: string }>;
142
142
  /** The registered app, or null for an unknown client id. */
143
143
  app(clientId: string): Promise<LinkApp | null>;
144
+ /** The app a client id and secret prove; throws `invalid_client` otherwise. */
145
+ authenticateClient(request: LinkClient): Promise<LinkApp>;
144
146
  /** Redeem a code once for the grant's first tokens. */
145
147
  exchangeCode(request: LinkCodeExchange): Promise<LinkTokens>;
146
148
  /**
@@ -259,7 +261,7 @@ export type LinkApprovalPage = {
259
261
  * One of the user's live grants for this app, which an update request edits
260
262
  * in place; null when the user has none by that id.
261
263
  */
262
- grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget"> | null>;
264
+ grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget" | "limits"> | null>;
263
265
  /** Create a grant on the chosen subscriptions and return its one-time code. */
264
266
  approve(request: LinkApproval): Promise<{ code: string }>;
265
267
  /** The user's live grants, oldest first, as the connections page shows them. */
@@ -400,6 +402,8 @@ export type LinkApproval = {
400
402
  codeChallenge: string;
401
403
  credentialIds: string[];
402
404
  budget: LinkBudget[];
405
+ // The most of each shared plan or key the app may use.
406
+ limits: LinkLimit[];
403
407
  };
404
408
 
405
409
  export type LinkCodeExchange = LinkClient & {
@@ -1,5 +1,6 @@
1
1
  import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { HttpError } from "../http/errors.js";
3
+ import { linkUnavailableError, plansExhausted } from "../link/errors.js";
3
4
  import { piMessageToInteractionOutput } from "./pi_output.js";
4
5
  import type { InteractionRequest } from "../interaction/types.js";
5
6
  import { captureOperationalError } from "../observability/errors.js";
@@ -469,6 +470,10 @@ async function throwProviderFailure(args: {
469
470
  { "retry-after": "1" },
470
471
  );
471
472
  }
473
+ if (limit !== null && result.choice.execution.subscriptionLinkGrantId) {
474
+ // A Dari Link app gets the one plan-limit contract, without CLI advice.
475
+ throw linkUnavailableError(plansExhausted([limit.oauthProvider], limit.resetsAt));
476
+ }
472
477
  if (limit !== null) {
473
478
  const accountsUrl = gatewayPlatform().accountsUrl;
474
479
  const codex = codexUsageLimitError(limit, accountsUrl);
@@ -104,7 +104,7 @@ export async function resolveSelfHostedRouter(
104
104
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
105
105
  const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
106
106
  if (keyIndex === null && grant === null) {
107
- throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
107
+ throw new HttpError(401, "Missing or invalid gateway key or Dari Link access token.", "authentication_error");
108
108
  }
109
109
  if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
110
110
  throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
@@ -33,9 +33,10 @@
33
33
  * Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
34
34
  *
35
35
  * Error states on demand: `gateway.setState({...})` (or `POST
36
- * <controlUrl>/state`): `limited: true` makes every provider call a usage-limit
37
- * refusal, so the plans go `unavailable_until` and requests get 424
38
- * `subscription_exhausted`; `five_hour` and `weekly` (0 to 1) are the plan
36
+ * <controlUrl>/state`): `limited: true` holds every plan at its usage limit
37
+ * for an hour at once (`plans[].state` `plan_limit` with `available_at`) and
38
+ * makes every provider call a usage-limit refusal, so Link requests get 424
39
+ * `subscription_exhausted`; `limited: false` (or a state without it) clears it; `five_hour` and `weekly` (0 to 1) are the plan
39
40
  * usage each default reply reports, which fills `plans[].usage`. A grant's
40
41
  * token budget, once its replies' tokens reach it, leads to 424
41
42
  * `grant_budget_exhausted`.
@@ -65,6 +66,7 @@ import { authorizeUrl, LinkError } from "../link/client.js";
65
66
  import { linkUserCookie } from "../link/endpoints.js";
66
67
  import type { SubscriptionKind } from "../types.js";
67
68
  import { SqliteLinkStore } from "../link/sqlite_store.js";
69
+ import { CANONICAL_MODELS } from "../models/canonical.js";
68
70
  import { secretBoxFromEnv } from "./secret_box.js";
69
71
  import { SubscriptionStore } from "./subscriptions/index.js";
70
72
 
@@ -93,7 +95,7 @@ export type StubUpstreamCall = {
93
95
  };
94
96
 
95
97
  export type StubGatewayOptions = {
96
- // One connected plan per entry, in order. Default: two Claude Code plans.
98
+ // One connected plan per entry, in order. Default: one ChatGPT plan.
97
99
  plans?: Array<"anthropic_claude_code" | "openai_codex">;
98
100
  // An API key of the plans' user for each of these providers. Default: none.
99
101
  keys?: Array<"anthropic" | "openai" | "openrouter">;
@@ -101,12 +103,13 @@ export type StubGatewayOptions = {
101
103
  // which serve only the grants that user approves. `"gateway"` connects them
102
104
  // as the gateway owner's instead, which serve the gateway key.
103
105
  owner?: "link_user" | "gateway";
104
- // The default router's models. Default: Claude Sonnet and GPT-5.5.
106
+ // The default router's models, as canonical `provider/model` ids (a
107
+ // `dari/model/` prefix is dropped). Default: Claude Sonnet and GPT-5.5.
105
108
  models?: string[];
106
109
  upstream?: (call: StubUpstreamCall) => Response;
107
110
  // The gateway key. Default: `k`.
108
111
  gatewayKey?: string;
109
- // The gateway's port. Default: a free one.
112
+ // The gateway's port. Default (or 0): a free one.
110
113
  port?: number;
111
114
  // Hosts the gateway allows http redirect URIs on (`link.allowHttpRedirectHosts`).
112
115
  allowHttpRedirectHosts?: string[];
@@ -132,7 +135,8 @@ export type StubConnectOptions = {
132
135
  export type StubLinkMessage = { message: Record<string, string>; targetOrigin: string };
133
136
 
134
137
  export type StubState = {
135
- // Every provider call is a usage-limit refusal.
138
+ // Every plan is held at its usage limit for an hour, and every provider
139
+ // call is a usage-limit refusal. Unset clears it.
136
140
  limited?: boolean;
137
141
  // Plan usage each default reply reports, 0 to 1.
138
142
  five_hour?: number;
@@ -172,14 +176,32 @@ export type StubGateway = {
172
176
  const STUB_USER = "stub-user";
173
177
 
174
178
  export async function startStubGateway(options: StubGatewayOptions = {}): Promise<StubGateway> {
175
- const kinds = options.plans ?? ["anthropic_claude_code", "anthropic_claude_code"];
176
- const models = options.models ?? ["anthropic/claude-sonnet-5-5", "openai/gpt-5.5"];
179
+ // A plain stub serves any app: a Claude Code plan serves only Claude Code.
180
+ const kinds = options.plans ?? ["openai_codex"];
181
+ const models = (options.models ?? ["anthropic/claude-sonnet-5-5", "openai/gpt-6.2-astra"]).map((model) => model.replace(/^dari\/model\//, ""));
182
+ const unknown = models.filter((model) => !CANONICAL_MODELS.some((entry) => entry.id === model));
183
+ if (unknown.length > 0) {
184
+ throw new Error(
185
+ `startStubGateway models must be canonical "provider/model" ids, such as "openai/gpt-6.1-sol"; unknown: ${unknown.join(", ")}.`,
186
+ );
187
+ }
177
188
  const gatewayKey = options.gatewayKey ?? "k";
178
189
  const upstream = options.upstream;
179
190
  const served: string[] = [];
180
191
  const calls: StubUpstreamCall[] = [];
181
192
  const messages: StubLinkMessage[] = [];
182
193
  let state: StubState = {};
194
+ // While `limited`: when the forced limit resets.
195
+ let limitedUntil: Date | null = null;
196
+ // Set once the plans are stored.
197
+ let holdPlans: (until: Date | null) => void = () => {};
198
+ // A forced limit holds the plans at once, as a refusal would, until it
199
+ // resets or `limited: false` clears it.
200
+ const setState = (next: StubState) => {
201
+ state = next;
202
+ limitedUntil = next.limited ? new Date(Date.now() + 3_600_000) : null;
203
+ holdPlans(limitedUntil);
204
+ };
183
205
  let approve: StubGateway["approve"] = async () => {
184
206
  throw new Error("The gateway is not up yet.");
185
207
  };
@@ -194,7 +216,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
194
216
  if (pathname === "/served" && request.method === "GET") return Response.json({ calls });
195
217
  if (pathname === "/messages" && request.method === "GET") return Response.json({ messages });
196
218
  if (pathname === "/state" && request.method === "POST") {
197
- state = (await request.json()) as StubState;
219
+ setState((await request.json()) as StubState);
198
220
  return Response.json({ state });
199
221
  }
200
222
  if (pathname === "/connect" && request.method === "POST") {
@@ -218,7 +240,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
218
240
  });
219
241
  return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
220
242
  } catch (error) {
221
- return Response.json({ error: error instanceof LinkError ? error.code : String(error) }, { status: 400 });
243
+ return Response.json({ error: error instanceof LinkError ? error.code : errorMessage(error) }, { status: 400 });
222
244
  }
223
245
  }
224
246
  if (pathname === "/approve" && request.method === "POST") {
@@ -230,9 +252,11 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
230
252
  });
231
253
  return Response.json({ message: result.message, target_origin: result.targetOrigin });
232
254
  } catch (error) {
233
- return Response.json({ error: String(error) }, { status: 400 });
255
+ return Response.json({ error: errorMessage(error) }, { status: 400 });
234
256
  }
235
257
  }
258
+ // A provider key check (list models): the operator's stand-in keys are good.
259
+ if (pathname.endsWith("/models") && request.method === "GET") return Response.json({ data: [] });
236
260
  // The Codex usage report: a fresh plan, nothing used.
237
261
  if (pathname.endsWith("/wham/usage")) {
238
262
  return Response.json({ rate_limit: { primary_window: { used_percent: 0, reset_at: null } } });
@@ -281,7 +305,7 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
281
305
  if (upstream !== undefined) return upstream(call);
282
306
  if (chat) return chatReply(call.model);
283
307
  const plan: SubscriptionKind = kind === "openai_codex" ? kind : "anthropic_claude_code";
284
- if (state.limited) return limitRefusal(plan);
308
+ if (limitedUntil !== null) return limitRefusal(plan, limitedUntil);
285
309
  return stubReply(plan, call.model, usageHeaders(plan, state));
286
310
  },
287
311
  });
@@ -303,6 +327,12 @@ export async function startStubGateway(options: StubGatewayOptions = {}): Promis
303
327
  accountEmail: `${letter}@example.com`,
304
328
  }, null, new Date(), options.owner === "gateway" ? null : STUB_USER)!.id;
305
329
  });
330
+ holdPlans = (until) => {
331
+ for (const id of planIds) {
332
+ if (until === null) store.markAvailable(store.get(id)!.name, new Date(), options.owner === "gateway" ? null : STUB_USER);
333
+ else store.markUnavailable(id, until, "The stub gateway's forced usage limit.");
334
+ }
335
+ };
306
336
  const keys = options.keys ?? [];
307
337
  const links = new SqliteLinkStore(new Database(dbPath), secrets);
308
338
  const keyIds = keys.map((key) => links.addKey(STUB_USER, key, `stub-key-${key}`).id);
@@ -317,14 +347,22 @@ providers:
317
347
  baseUrl: ${stubUrl}
318
348
  api: anthropic-messages
319
349
  apiKeyEnv: STUB_ANTHROPIC_API_KEY
350
+ openai:
351
+ baseUrl: ${stubUrl}/openai
352
+ apiKeyEnv: STUB_OPENAI_API_KEY
320
353
  openai-codex:
321
354
  baseUrl: ${stubUrl}/backend-api
322
- ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl: ${stubUrl}/${key}\n apiKeyEnv: STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY\n`).join("")}${options.allowHttpRedirectHosts?.length ? `link:\n allowHttpRedirectHosts: [${options.allowHttpRedirectHosts.map((host) => JSON.stringify(host)).join(", ")}]\n` : ""}`);
323
- const port = options.port ?? await freePort();
355
+ ${keys.filter((key) => key === "openrouter").map((key) => ` ${key}:\n baseUrl: ${stubUrl}/${key}\n apiKeyEnv: STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY\n`).join("")}${options.allowHttpRedirectHosts?.length ? `link:\n allowHttpRedirectHosts: [${options.allowHttpRedirectHosts.map((host) => JSON.stringify(host)).join(", ")}]\n` : ""}`);
356
+ // 0, like none, is a free one.
357
+ const port = options.port || await freePort();
324
358
  const sessionSecret = randomBytes(32).toString("base64url");
325
359
  // The gateway's own entrypoint, beside this file as source or as built.
326
360
  const entrypoint = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./main.ts" : "./main.js", import.meta.url));
327
- const gateway = Bun.spawn([process.execPath, entrypoint], {
361
+ // The gateway exits once its stdin closes: when this process dies, however
362
+ // it dies, the gateway goes with it.
363
+ const child = `process.stdin.on("end", () => process.exit(0)).resume(); `
364
+ + `await (await import(${JSON.stringify(entrypoint)})).runSelfHostedGateway();`;
365
+ const gateway = Bun.spawn([process.execPath, "-e", child], {
328
366
  env: {
329
367
  PATH: process.env.PATH ?? "",
330
368
  DARI_GATEWAY_KEYS: gatewayKey,
@@ -333,13 +371,23 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
333
371
  DARI_LINK_SESSION_SECRET: sessionSecret,
334
372
  DARI_GATEWAY_ENCRYPTION_KEY: encryptionKey,
335
373
  // The operator's own keys for the stand-in providers.
336
- ...Object.fromEntries(["anthropic", ...keys].map((key) => [`STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY`, "stub-operator-key"])),
374
+ ...Object.fromEntries(["anthropic", "openai", ...keys].map((key) => [`STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY`, "stub-operator-key"])),
337
375
  PORT: String(port),
338
376
  },
377
+ stdin: "pipe",
339
378
  stdout: "pipe",
340
- stderr: "inherit",
379
+ stderr: "pipe",
341
380
  });
342
- await waitForLine(gateway.stdout as ReadableStream<Uint8Array>, "dari-gateway listening");
381
+ const killGateway = () => gateway.kill();
382
+ process.on("exit", killGateway);
383
+ const stderr = echo(gateway.stderr as ReadableStream<Uint8Array>);
384
+ try {
385
+ await waitForLine(gateway.stdout as ReadableStream<Uint8Array>, "dari-gateway listening");
386
+ } catch {
387
+ await gateway.exited;
388
+ await provider.stop(true);
389
+ throw new Error(`The stub gateway did not start:\n${(await stderr).trim()}`);
390
+ }
343
391
  const baseUrl = `http://127.0.0.1:${port}`;
344
392
  const userCookie = linkUserCookie(sessionSecret, STUB_USER);
345
393
  approve = async (authorizeUrl, approveOptions = {}) => {
@@ -387,10 +435,9 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
387
435
  approve: (url, approveOptions) => approve(url, approveOptions),
388
436
  app,
389
437
  connect: (connectOptions) => connect(connectOptions),
390
- setState: (next) => {
391
- state = next;
392
- },
438
+ setState,
393
439
  stop: async () => {
440
+ process.off("exit", killGateway);
394
441
  gateway.kill();
395
442
  await gateway.exited;
396
443
  await provider.stop(true);
@@ -411,7 +458,12 @@ async function driveApproval(
411
458
  const params = [...url.searchParams];
412
459
  const choose = await (await fetch(page, { headers: { cookie } })).text();
413
460
  const csrf = /name="csrf" value="([^"]+)"/.exec(choose)?.[1];
414
- if (csrf === undefined) throw new Error(`No approval form:\n${choose}`);
461
+ if (csrf === undefined) {
462
+ throw new Error(
463
+ "The approval page offers this app nothing to approve: none of the stub user's plans or keys serves it. "
464
+ + 'A Claude Code plan serves only an app that asks for clients: ["claude_code"].',
465
+ );
466
+ }
415
467
  const usable = [...choose.matchAll(/name="credential_id" value="([^"]+)"/g)].map((match) => match[1]!);
416
468
  const decided = await fetch(`${baseUrl}${url.pathname}`, {
417
469
  method: "POST",
@@ -436,9 +488,9 @@ async function driveApproval(
436
488
  return { message, targetOrigin };
437
489
  }
438
490
 
439
- // A usage-limit refusal in the plan's provider protocol, resetting in an hour.
440
- function limitRefusal(kind: SubscriptionKind): Response {
441
- const reset = String(Math.floor(Date.now() / 1000) + 3600);
491
+ // A usage-limit refusal in the plan's provider protocol, resetting at `until`.
492
+ function limitRefusal(kind: SubscriptionKind, until: Date): Response {
493
+ const reset = String(Math.floor(until.getTime() / 1000));
442
494
  if (kind === "openai_codex") {
443
495
  return Response.json(
444
496
  { error: { type: "usage_limit_reached", code: "usage_limit_reached", message: "The usage limit has been reached", resets_at: Number(reset) } },
@@ -557,6 +609,21 @@ async function freePort(): Promise<number> {
557
609
  return port!;
558
610
  }
559
611
 
612
+ function errorMessage(error: unknown): string {
613
+ return error instanceof Error ? error.message : String(error);
614
+ }
615
+
616
+ // Copy the gateway's stderr to this process's, and resolve with all of it once it closes.
617
+ async function echo(stream: ReadableStream<Uint8Array>): Promise<string> {
618
+ const decoder = new TextDecoder();
619
+ let output = "";
620
+ for await (const chunk of stream) {
621
+ process.stderr.write(chunk);
622
+ output += decoder.decode(chunk, { stream: true });
623
+ }
624
+ return output;
625
+ }
626
+
560
627
  async function waitForLine(stream: ReadableStream<Uint8Array>, marker: string): Promise<void> {
561
628
  const reader = stream.getReader();
562
629
  const decoder = new TextDecoder();
@@ -22,7 +22,7 @@
22
22
  * Options: `--plans` (comma-separated
23
23
  * `openai_codex` and `anthropic_claude_code`), `--keys` (comma-separated
24
24
  * `anthropic`, `openai`, and `openrouter`: an API key of the plans' user for each), `--models` (the default
25
- * router's models), `--key` (the gateway key), `--port` (the gateway's port),
25
+ * router's models), `--key` (the gateway key), `--port` (the gateway's port; 0 or none picks a free one),
26
26
  * `--redirect-uri` (the redirect URI `app` is registered with),
27
27
  * and `--allow-http-redirect-host` (repeatable: a host apps may register http
28
28
  * redirect URIs on, such as `*.example.ts.net`).
@@ -539,9 +539,9 @@ export class SubscriptionStore {
539
539
  return true;
540
540
  }
541
541
 
542
- /** Clear a subscription's usage-limit holds. Null when it is not connected. */
543
- markAvailable(name: string, now = new Date()): SubscriptionCredential | null {
544
- const credential = this.getByName(name);
542
+ /** Clear a subscription's usage-limit holds (a Dari Link user's with `owner`). Null when it is not connected. */
543
+ markAvailable(name: string, now = new Date(), owner: string | null = null): SubscriptionCredential | null {
544
+ const credential = this.getByName(name, owner);
545
545
  if (credential === null) return null;
546
546
  this.db.run(
547
547
  `UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,