@north-light/cli 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.
Files changed (60) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/recovery.d.ts +2 -0
  4. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  5. package/dist/cli.js +8 -8
  6. package/dist/clients/attach/viewer.js +314 -314
  7. package/dist/commands/api-client.d.ts +2 -0
  8. package/dist/commands/api-client.js +2 -2
  9. package/dist/commands/node/inspect.js +7 -7
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/core/canvas/schema-pg/031-environment-pull-request-write-default.sql +2 -0
  12. package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/environments.js +1 -1
  16. package/dist/core/graph/reader.js +1 -1
  17. package/dist/core/import/load/open-grants.d.ts +1 -0
  18. package/dist/core/import/load/open-grants.js +1 -0
  19. package/dist/core/import/load/run.d.ts +3 -1
  20. package/dist/core/import/load/run.js +2 -2
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/managed-providers.d.ts +9 -1
  23. package/dist/core/provider-failure.d.ts +2 -0
  24. package/dist/core/provider-failure.js +1 -1
  25. package/dist/core/runtime/broker/model-adapter.js +3 -3
  26. package/dist/core/runtime/revive.d.ts +2 -0
  27. package/dist/core/runtime/revive.js +2 -2
  28. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  29. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  30. package/dist/core/subscription-state.d.ts +4 -4
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/messages.js +2 -2
  33. package/dist/daemon/api/handlers/nodes.js +1 -1
  34. package/dist/daemon/api/handlers/profiles.js +1 -1
  35. package/dist/daemon/api/operations.js +1 -1
  36. package/dist/daemon/api/router.d.ts +4 -0
  37. package/dist/daemon/api/router.js +1 -1
  38. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  39. package/docs/sdk/release-notes.md +6 -0
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/api/contract.js +1 -1
  42. package/packages/crouter-api/dist/commands/api-client.js +3 -1
  43. package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
  44. package/packages/crouter-api/dist/commands/profile/environment.js +2 -2
  45. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  46. package/packages/crouter-api/dist/core/environments.js +1 -1
  47. package/packages/crouter-api/dist/core/graph/reader.js +3 -3
  48. package/packages/crouter-api/dist/core/llm/run.js +13 -2
  49. package/packages/crouter-api/dist/core/provider-failure.js +9 -0
  50. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
  51. package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
  52. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
  53. package/packages/crouter-api/dist/core/subscription-state.js +26 -10
  54. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  55. package/packages/crouter-api/dist/daemon/api/router.js +1 -1
  56. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
  57. package/packages/crouter-api/package.json +1 -1
  58. package/packages/crouter-identity/package.json +1 -1
  59. package/packages/crouter-plugin/package.json +3 -3
  60. package/runtime.lock.json +14 -14
@@ -13,7 +13,7 @@ const ENVIRONMENT_OUTPUT = [
13
13
  { name: 'setup_script', type: 'string', required: false, constraint: 'The script the image build runs; null when none.' },
14
14
  { name: 'pi_packages', type: 'string', required: false, constraint: 'pi package sources, one per line; null when none.' },
15
15
  { name: 'memory_mb', type: 'number', required: true, constraint: 'Memory of new sandboxes: 2048, 4096 or 8192.' },
16
- { name: 'allow_pull_request_write', type: 'boolean', required: true, constraint: 'Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write.' },
16
+ { name: 'allow_pull_request_write', type: 'boolean', required: true, constraint: 'Whether sandboxes may open and merge pull requests: their GitHub credential carries pull_requests write besides contents write. On by default.' },
17
17
  { name: 'recipe_revision', type: 'number', required: true, constraint: 'Raised by one each time the recipe changes.' },
18
18
  { name: 'image_revision', type: 'number', required: false, constraint: 'The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build.' },
19
19
  { name: 'image_error', type: 'string', required: false, constraint: 'Why the last image build failed; null when it did not.' },
@@ -51,7 +51,7 @@ const setLeaf = defineLeaf({
51
51
  { kind: 'flag', name: 'repo', type: 'string', required: false, repeatable: true, constraint: 'GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each.' },
52
52
  { kind: 'flag', name: 'setup-script-file', type: 'path', required: false, constraint: 'File holding the setup script the image build runs as root.' },
53
53
  { kind: 'flag', name: 'pi-package', type: 'string', required: false, repeatable: true, constraint: 'pi package source (repeat per package); replaces the whole list.' },
54
- { kind: 'flag', name: 'allow-pull-request-write', type: 'bool', required: false, constraint: 'Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image.' },
54
+ { kind: 'flag', name: 'allow-pull-request-write', type: 'bool', required: false, constraint: 'On by default: sandboxes may open and merge pull requests (their GitHub credential carries pull_requests write). `--no-allow-pull-request-write` drops to contents write only, so sandboxes can push branches but not open pull requests. Takes effect on the next credential a sandbox fetches; builds no image.' },
55
55
  { kind: 'flag', name: 'memory', type: 'int', required: false, constraint: 'Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory.' },
56
56
  ],
57
57
  output: [...ENVIRONMENT_OUTPUT],
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 30;
9
+ export const CANVAS_SCHEMA_VERSION = 32;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -38,7 +38,7 @@ export async function createProfileBlaxelEnvironment(db, spec) {
38
38
  const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
39
39
  const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
40
40
  await writeActsFor(db, object.id, spec.person);
41
- await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, last_seen_at) VALUES (?, 'blaxel', NULL, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, new Date().toISOString());
41
+ await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)`).run(object.id, spec.memoryMb ?? 2048, new Date().toISOString());
42
42
  if (spec.recipe !== undefined)
43
43
  await writeEnvironmentRecipe(db, object.id, spec.recipe);
44
44
  return object.id;
@@ -197,10 +197,10 @@ export async function readerForObject(db, watcher, reposFn = async () => [], loo
197
197
  const scope = runtimeScope();
198
198
  const grants = await db.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${scope.sql}`).all(grantee, ...scope.args);
199
199
  const always = (grant) => JSON.parse(grant.resolved_scopes_json).filter((s) => s.mode === 'always').map((s) => parseScope(s.scope));
200
- // Several people may have granted the same app. An app-owned object then reads as the person it is kept for (its `acts_for` fact), under that person's grant.
201
- const keptFor = grants.length > 1 && owner.type === 'app'
200
+ // Several people granted the app: read as the person `acts_for` names (an app-owned object's own, a repository document's repository's), under that grant.
201
+ const keptFor = grants.length > 1 && (owner.type === 'app' || owner.type === 'repo')
202
202
  ? new Set((await db.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'")
203
- .all(OBJECT_TYPE, watcher.id)).map((r) => r.subject_id))
203
+ .all(OBJECT_TYPE, owner.type === 'repo' ? owner.id : watcher.id)).map((r) => r.subject_id))
204
204
  : null;
205
205
  const sub = keptFor === null ? undefined : grants.find((g) => keptFor.has(g.sub.replace(/^user:/, '')))?.sub;
206
206
  const kept = sub === undefined ? null : await lookups.grantFor(grantee, sub);
@@ -5,7 +5,7 @@ import { KEY_CREDENTIAL_SOURCE, parseModelSpec } from '../model-routes.js';
5
5
  import { openModelRegistry } from '../runtime/model-registry.js';
6
6
  import { getProviderLabel, isInvalidRefreshTokenError } from '../managed-providers.js';
7
7
  import { MAX_RATE_LIMIT_COOLDOWN_MS, coolingUntilFor, isManagedProvider, markSubscriptionRateLimited, markSubscriptionSuccess, readSubscriptionPool, retryAfterMsFromHeaders, retryAfterMsFromError, refreshSubscriptionCredential, subscriptionNeedsSuccessWrite, vendorRateLimit, RefreshBusyError, RefreshTimeoutError } from '../subscription-state.js';
8
- import { describeRateLimitScope, rateLimitHeaders } from '../rate-limit-scope.js';
8
+ import { describeRateLimitScope, modelCooldownFamily, rateLimitHeaders } from '../rate-limit-scope.js';
9
9
  import { RunError } from '../runs/operations.js';
10
10
  import { recognizeProviderError } from '../provider-error-recognition.js';
11
11
  import { isSafetyRefusal } from './refusal.js';
@@ -282,6 +282,17 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
282
282
  earliestCooling = frees;
283
283
  coolingRoute = `${model.provider}/${model.id}`;
284
284
  }
285
+ // Each cooling account's stored vendor 429 still speaks for it: its named reset joins the earliest-reset aggregate, and with no fresh 429 this call its observation is the refusal's rate-limit block.
286
+ const family = modelCooldownFamily(model.id);
287
+ for (const row of pool) {
288
+ // Only the observation of a cooldown still in force: an expired row's facts belong to an earlier window.
289
+ const stored = family !== undefined && (row.modelCooldowns?.[family] ?? 0) > Date.now() ? row.vendorLimits?.[family] : row.rateLimitedUntil > Date.now() ? row.vendorLimits?.['account'] : undefined;
290
+ if (stored === undefined)
291
+ continue;
292
+ if (stored.vendorReset !== undefined && stored.vendorReset > Date.now())
293
+ earliestVendorReset = Math.min(earliestVendorReset, stored.vendorReset);
294
+ lastLimit ??= { provider, model: stored.model, account: row.label, observation: stored.observation };
295
+ }
285
296
  continue;
286
297
  }
287
298
  // An app-paid or hosted candidate gets a second attempt only to re-mint after a 401.
@@ -491,7 +502,7 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
491
502
  lastLimit = { provider, model: model.id, ...(account ? { account: account.label } : {}), observation };
492
503
  console.error(`[llm] 429 from ${served}${account ? ` account "${account.label}"` : ''}: scope=${describeRateLimitScope(observation.scope)} retry_after_ms=${retryMs} headers=${JSON.stringify(observation.headers)}`);
493
504
  if (account && isManagedProvider(provider))
494
- await markSubscriptionRateLimited(provider, account.label, retryMs, at, Date.now(), observation.scope);
505
+ await markSubscriptionRateLimited(provider, account.label, retryMs, at, Date.now(), observation.scope, { model: model.id, ...(vendorReset !== undefined ? { vendorReset } : {}), observation });
495
506
  if (vendorReset !== undefined)
496
507
  earliestVendorReset = Math.min(earliestVendorReset, vendorReset);
497
508
  if (Date.now() + Math.min(retryMs, MAX_RATE_LIMIT_COOLDOWN_MS) < earliestCooling) {
@@ -79,6 +79,15 @@ function jsonDetails(details) {
79
79
  const RATELIMIT_HEADER_LIMIT = 48;
80
80
  const RATELIMIT_VALUE_LIMIT = 256;
81
81
  const PAYMENT_REASONS = new Set(PAYMENT_REFUSAL_REASONS);
82
+ /** Plain text for a fault's vendor facts: the earliest known vendor reset (across the pool), then the last 429's window with its own account and model. Never pairs the aggregate reset with that window. */
83
+ export function describeVendorLimit(details) {
84
+ const reset = details?.payment?.reset_at ? ` Earliest known vendor reset: ${details.payment.reset_at}.` : '';
85
+ const limit = details?.ratelimit;
86
+ if (limit === undefined)
87
+ return reset;
88
+ const window = limit.headers['anthropic-ratelimit-unified-reset'];
89
+ return `${reset} Rate limit: ${limit.scope ?? 'account'}${limit.claim === undefined ? '' : ` (${limit.claim})`}${limit.account === undefined ? '' : ` on account ${limit.account}`}${limit.model === undefined ? '' : ` for ${limit.model}`}${window === undefined || !Number(window) ? '' : `, that window resets ${new Date(Number(window) * 1000).toISOString()}`}.`;
90
+ }
82
91
  /** Strictly parse a recorded payment refusal: a known reason and a message, nothing else trusted. */
83
92
  export function parseProviderPayment(value) {
84
93
  const raw = record(value);
@@ -320,7 +320,9 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
320
320
  const remaining = LLM_BROKER_RETRY_WINDOW_S - waited;
321
321
  if (seconds > remaining) {
322
322
  const retryAt = Date.now() + seconds * 1000;
323
- throw new LlmRefusalError(`${error.message} (retry after ${seconds}s, at ${new Date(retryAt).toISOString()})`, retryAt, refusalRateLimit(error), error.code, response.status, refusalPayment(error));
323
+ // The router's next probe and the vendor's own reset are different times: name both, never one as the other.
324
+ const vendorReset = refusalPayment(error)?.reset_at;
325
+ throw new LlmRefusalError(`${error.message} (retry after ${seconds}s, at ${new Date(retryAt).toISOString()}: the router's next probe${vendorReset ? `; earliest known vendor reset ${vendorReset}` : ''})`, retryAt, refusalRateLimit(error), error.code, response.status, refusalPayment(error));
324
326
  }
325
327
  await sleep(seconds * 1000, undefined, { signal: options.signal });
326
328
  waited += seconds;
@@ -368,6 +368,17 @@ export async function assertRecordedCwdExists(nodeId, meta) {
368
368
  }
369
369
  return { blaxelEnvironment, remoteMachine };
370
370
  }
371
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
372
+ export function assertCheckoutNotRemoved(nodeId, meta) {
373
+ const worktree = meta.managed_worktree;
374
+ if (worktree?.state !== 'closed' || worktree.cleanup !== 'complete' || meta.cwd !== worktree.path)
375
+ return;
376
+ throw new InputError({
377
+ error: 'checkout_removed',
378
+ message: `${nodeId} cannot be revived — cleanup removed its checkout ${worktree.path} and branch ${worktree.branch}`,
379
+ next: `Start a new node in ${worktree.repo_root}.`,
380
+ });
381
+ }
371
382
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
372
383
  export async function runNodeStartHooks(nodeId, meta, isBirth) {
373
384
  const lifecycleHooks = discoverLifecycleHookRegistry(meta.cwd, meta.profile_id).plans.get('node:start') ?? [];
@@ -23,6 +23,14 @@ export const BLAXEL_TOML_FILE = 'blaxel.toml';
23
23
  export const BLAXEL_TOML = '[build]\nslim = false\n';
24
24
  const PI_VERSION = '1.1.0';
25
25
  export const SETUP_SCRIPT_FILE = 'recipe-setup.sh';
26
+ /** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
27
+ * variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
28
+ export const RUN_USER_NPMRC = [
29
+ '@northlight-systems:registry=https://npm.pkg.github.com',
30
+ '//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}',
31
+ `store-dir=/home/${RUN_USER}/.local/share/pnpm/store`,
32
+ ];
33
+ const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
26
34
  export const REPOS_DIR = 'repos';
27
35
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
28
36
  export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
@@ -63,6 +71,12 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
63
71
  if (hasScript)
64
72
  out.push(`COPY ${SETUP_SCRIPT_FILE} /tmp/${SETUP_SCRIPT_FILE}`);
65
73
  out.push('WORKDIR /work');
74
+ out.push(`RUN ${writeRunUserNpmrc()}`);
75
+ // Warm the image's pnpm store from each repository's lockfile, so `pnpm install` in the sandbox links instead of downloading. A failed fetch only costs that
76
+ // warmth, so it is logged and never refuses the sandbox start.
77
+ for (const repo of recipe.repositories) {
78
+ out.push(`RUN if [ -f /work/${repo.name}/pnpm-lock.yaml ]; then cd /work/${repo.name} && HOME=/home/${RUN_USER} pnpm fetch >> ${SETUP_LOG_FILE} 2>&1 || echo 'pnpm fetch ${repo.name} failed' >> ${SETUP_LOG_FILE}; fi`);
79
+ }
66
80
  for (const source of packages)
67
81
  out.push(guarded(`pi install ${source}`, `HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${RECIPE_PI_AGENT_DIR} pi install ${shellQuote(source)}`));
68
82
  // Blaxel never reports a failed Docker step: the image stays BUILDING until the timeout, and its build log is not readable. So a failing script must not fail
@@ -79,8 +93,9 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
79
93
  out.push('COPY --from=build /var/lib/postgresql /var/lib/postgresql');
80
94
  // The copied /etc/passwd now names the postgres user (when the setup script installed postgres); its data directory must belong to it or the server refuses to start.
81
95
  out.push('RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi');
96
+ // A setup script may have written a resolved token into an npmrc; the run user's npmrc is rewritten to the token-free lines.
82
97
  if (packagesToken)
83
- out.push(`RUN rm -f /work/.npmrc /home/${RUN_USER}/.npmrc`);
98
+ out.push('RUN rm -f /work/.npmrc', `RUN ${writeRunUserNpmrc()} && chown ${RUN_USER}:${RUN_USER} /home/${RUN_USER}/.npmrc`);
84
99
  out.push(`USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
85
100
  return out.join('\n');
86
101
  }
@@ -40,7 +40,7 @@ export class RefreshBusyError extends Error {
40
40
  export class RefreshTimeoutError extends Error {
41
41
  constructor(provider) { super(`${getProviderLabel(provider)} ${REFRESH_TIMEOUT_PHRASE} ${REFRESH_EXCHANGE_TIMEOUT_MS} ms`); this.name = 'RefreshTimeoutError'; }
42
42
  }
43
- const COLUMNS = 'id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id';
43
+ const COLUMNS = 'id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id,vendor_limit_json';
44
44
  export const aadOf = (person, provider, id, part) => `model_accounts|${person}|${provider}|${id}|${part}`;
45
45
  function stored(entry) { return { refresh: entry.refresh, access: entry.access, expires: entry.expires, ...(entry.accountId ? { accountId: entry.accountId } : {}), ...(entry.clientId ? { clientId: entry.clientId } : {}) }; }
46
46
  function rowOf(provider, r) { return { providerId: provider, id: r.id, label: r.label, labelKey: r.label_key, position: r.position, lastAttemptAt: r.last_attempt_at, lastRateLimitedAt: r.last_rate_limited_at, rateLimitedUntil: r.rate_limited_until, ...(r.auth_failure ? { authFailure: r.auth_failure } : {}) }; }
@@ -51,20 +51,28 @@ function toPublic(person, provider, r, cooldowns = []) {
51
51
  const refresh = open(r.refresh_sealed, r.key_id, secrets, aadOf(person, provider, r.id, 'refresh'));
52
52
  const access = open(r.access_sealed, r.key_id, secrets, aadOf(person, provider, r.id, 'access'));
53
53
  const row = rowOf(provider, r);
54
- const entry = { label: row.label, refresh, access, expires: r.expires, rateLimitedUntil: row.authFailure || !row.lastRateLimitedAt ? row.rateLimitedUntil : Math.min(row.rateLimitedUntil, row.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS), lastAttemptAt: row.lastAttemptAt, lastRateLimitedAt: row.lastRateLimitedAt, ...(row.authFailure ? { authFailure: row.authFailure } : {}), ...(r.vendor_account_id ? { accountId: r.vendor_account_id } : {}), ...(r.client_id ? { clientId: r.client_id } : {}), ...(cooldowns.length ? { modelCooldowns: Object.fromEntries(cooldowns.map((cooldown) => [cooldown.family, cooldown.lastRateLimitedAt ? Math.min(cooldown.rateLimitedUntil, cooldown.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS) : cooldown.rateLimitedUntil])) } : {}) };
54
+ const vendorLimits = Object.fromEntries([...(vendorLimitOf(r.vendor_limit_json) ? [['account', vendorLimitOf(r.vendor_limit_json)]] : []), ...cooldowns.flatMap((cooldown) => cooldown.vendorLimit ? [[cooldown.family, cooldown.vendorLimit]] : [])]);
55
+ const entry = { label: row.label, refresh, access, expires: r.expires, rateLimitedUntil: row.authFailure || !row.lastRateLimitedAt ? row.rateLimitedUntil : Math.min(row.rateLimitedUntil, row.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS), lastAttemptAt: row.lastAttemptAt, lastRateLimitedAt: row.lastRateLimitedAt, ...(row.authFailure ? { authFailure: row.authFailure } : {}), ...(r.vendor_account_id ? { accountId: r.vendor_account_id } : {}), ...(r.client_id ? { clientId: r.client_id } : {}), ...(cooldowns.length ? { modelCooldowns: Object.fromEntries(cooldowns.map((cooldown) => [cooldown.family, cooldown.lastRateLimitedAt ? Math.min(cooldown.rateLimitedUntil, cooldown.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS) : cooldown.rateLimitedUntil])) } : {}), ...(Object.keys(vendorLimits).length ? { vendorLimits } : {}) };
55
56
  return { row, entry };
56
57
  }
58
+ /** A stored vendor observation; an unreadable value is no observation, never a failed pool read. */
59
+ function vendorLimitOf(json) { try {
60
+ return json ? JSON.parse(json) : undefined;
61
+ }
62
+ catch {
63
+ return undefined;
64
+ } }
57
65
  function groupCooldowns(rows) {
58
66
  const out = new Map();
59
67
  for (const r of rows) {
60
68
  const list = out.get(r.account_id) ?? [];
61
- list.push({ family: r.family, rateLimitedUntil: r.rate_limited_until, lastRateLimitedAt: r.last_rate_limited_at });
69
+ list.push({ family: r.family, rateLimitedUntil: r.rate_limited_until, lastRateLimitedAt: r.last_rate_limited_at, ...(vendorLimitOf(r.vendor_limit_json) ? { vendorLimit: vendorLimitOf(r.vendor_limit_json) } : {}) });
62
70
  out.set(r.account_id, list);
63
71
  }
64
72
  return out;
65
73
  }
66
74
  async function loadCooldowns(db, person, provider) {
67
- return groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family').all(person, provider));
75
+ return groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family').all(person, provider));
68
76
  }
69
77
  /** The person's accounts at one provider in pool order, tokens opened. `forUpdate` row-locks them. */
70
78
  async function loadPool(db, person, provider, forUpdate = false) {
@@ -77,7 +85,7 @@ export async function readAllSubscriptionPools() {
77
85
  const person = await personIdAsync();
78
86
  const db = await openDb();
79
87
  const rows = await db.prepare(`SELECT provider_id,${COLUMNS} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(person);
80
- const cooldowns = groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? ORDER BY family').all(person));
88
+ const cooldowns = groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json FROM model_account_cooldowns WHERE person=? ORDER BY family').all(person));
81
89
  const pools = new Map();
82
90
  for (const r of rows) {
83
91
  const list = pools.get(r.provider_id) ?? [];
@@ -121,7 +129,8 @@ async function setCredential(db, person, provider, id, entry, spent) {
121
129
  return (await db.prepare(`UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=?,refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?${spent ? ' AND refresh_sealed=?' : ''}`).run(refresh.sealed, access.sealed, entry.expires, entry.accountId ?? null, entry.clientId ?? null, refresh.keyId, person, provider, id, ...(spent ? [spent] : []))).changes === 1;
122
130
  }
123
131
  async function updateHealth(db, person, row) { await db.prepare('UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?').run(row.label, row.labelKey, row.position, row.lastAttemptAt, row.lastRateLimitedAt, row.rateLimitedUntil, row.authFailure ?? null, person, row.providerId, row.id); }
124
- export async function upsertModelCooldown(db, person, provider, accountId, family, until, rateLimitedAt) { await db.prepare('INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at').run(person, provider, accountId, family, until, rateLimitedAt); }
132
+ export async function upsertModelCooldown(db, person, provider, accountId, family, until, rateLimitedAt, vendorLimit) { await db.prepare('INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json) VALUES(?,?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at,vendor_limit_json=excluded.vendor_limit_json').run(person, provider, accountId, family, until, rateLimitedAt, vendorLimit ? JSON.stringify(vendorLimit) : null); }
133
+ async function setAccountVendorLimit(db, person, row, vendorLimit) { await db.prepare('UPDATE model_accounts SET vendor_limit_json=? WHERE person=? AND provider_id=? AND id=?').run(vendorLimit ? JSON.stringify(vendorLimit) : null, person, row.providerId, row.id); }
125
134
  async function deleteModelCooldowns(db, person, provider, accountId) { if (accountId === undefined)
126
135
  await db.prepare('DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?').run(person, provider);
127
136
  else
@@ -183,6 +192,8 @@ export async function upsertSubscriptionWithUniqueAccount(provider, entry) {
183
192
  const cooldownIncoming = checked.lastRateLimitedAt >= row.lastRateLimitedAt;
184
193
  await setCredential(db, person, provider, row.id, stored(checked));
185
194
  await updateHealth(db, person, { ...row, authFailure: undefined, label: checked.label, labelKey: key(checked.label), lastAttemptAt: Math.max(row.lastAttemptAt, checked.lastAttemptAt), lastRateLimitedAt: cooldownIncoming ? checked.lastRateLimitedAt : row.lastRateLimitedAt, rateLimitedUntil: cooldownIncoming ? checked.rateLimitedUntil : row.rateLimitedUntil });
195
+ if (cooldownIncoming || differentAccount(existing.entry, checked))
196
+ await setAccountVendorLimit(db, person, row, undefined);
186
197
  if (differentAccount(existing.entry, checked))
187
198
  await deleteModelCooldowns(db, person, provider, row.id);
188
199
  return publicPool(pool, provider);
@@ -255,29 +266,32 @@ async function healthWrite(provider, ref, write) {
255
266
  return readSubscriptionPool(provider);
256
267
  }
257
268
  export async function markSubscriptionAttempt(provider, ref, attemptAt = Date.now()) { return healthWrite(provider, ref, (db, person, row) => updateHealth(db, person, { ...row, lastAttemptAt: Math.max(row.lastAttemptAt, attemptAt) })); }
258
- /** Record a 429 on an account. `scope` defaults to the whole account; a model scope cools only that family on this account, and a 429 older than the newest one already recorded for the same scope is ignored. */
259
- export async function markSubscriptionRateLimited(provider, ref, retryAfterMs, attemptAt = Date.now(), rateLimitedAt = Date.now(), scope = { kind: 'account' }) {
269
+ /** Record a 429 on an account. `scope` defaults to the whole account; a model scope cools only that family on this account, and a 429 older than the newest one already recorded for the same scope is ignored. `vendorLimit` replaces that cooldown's stored vendor observation. */
270
+ export async function markSubscriptionRateLimited(provider, ref, retryAfterMs, attemptAt = Date.now(), rateLimitedAt = Date.now(), scope = { kind: 'account' }, vendorLimit) {
260
271
  retryAfterMs = Math.min(Math.max(0, retryAfterMs), MAX_RATE_LIMIT_COOLDOWN_MS);
261
272
  return healthWrite(provider, ref, async (db, person, row) => {
262
273
  if (scope.kind === 'account') {
263
274
  if (rateLimitedAt < row.lastRateLimitedAt)
264
275
  return;
265
276
  await updateHealth(db, person, { ...row, lastAttemptAt: Math.max(row.lastAttemptAt, attemptAt), lastRateLimitedAt: rateLimitedAt, rateLimitedUntil: rateLimitedAt + retryAfterMs });
277
+ await setAccountVendorLimit(db, person, row, vendorLimit);
266
278
  return;
267
279
  }
268
280
  await updateHealth(db, person, { ...row, lastAttemptAt: Math.max(row.lastAttemptAt, attemptAt) });
269
281
  const current = (await loadCooldowns(db, person, provider)).get(row.id)?.find((cooldown) => cooldown.family === scope.family);
270
282
  if (current && rateLimitedAt < current.lastRateLimitedAt)
271
283
  return;
272
- await upsertModelCooldown(db, person, provider, row.id, scope.family, rateLimitedAt + retryAfterMs, rateLimitedAt);
284
+ await upsertModelCooldown(db, person, provider, row.id, scope.family, rateLimitedAt + retryAfterMs, rateLimitedAt, vendorLimit);
273
285
  });
274
286
  }
275
287
  /** A call on `modelId` succeeded: clear the account-wide cooldown and auth failure, and that model family's cooldown, unless a newer 429 for the same scope landed after `attemptAt` began. */
276
288
  export async function markSubscriptionSuccess(provider, ref, attemptAt = Date.now(), modelId) {
277
289
  const family = modelCooldownFamily(modelId);
278
290
  return healthWrite(provider, ref, async (db, person, row) => {
279
- if (attemptAt >= row.lastRateLimitedAt)
291
+ if (attemptAt >= row.lastRateLimitedAt) {
280
292
  await updateHealth(db, person, { ...row, authFailure: undefined, lastAttemptAt: Math.max(row.lastAttemptAt, attemptAt), rateLimitedUntil: 0 });
293
+ await setAccountVendorLimit(db, person, row, undefined);
294
+ }
281
295
  if (family === undefined)
282
296
  return;
283
297
  const current = (await loadCooldowns(db, person, provider)).get(row.id)?.find((cooldown) => cooldown.family === family);
@@ -412,6 +426,8 @@ export async function commitManagedLogin(provider, label, value) {
412
426
  const clear = entry.lastRateLimitedAt >= row.lastRateLimitedAt;
413
427
  await setCredential(db, person, provider, row.id, stored(entry));
414
428
  await updateHealth(db, person, { ...row, authFailure: undefined, lastAttemptAt: Math.max(row.lastAttemptAt, entry.lastAttemptAt), lastRateLimitedAt: clear ? entry.lastRateLimitedAt : row.lastRateLimitedAt, rateLimitedUntil: clear ? 0 : row.rateLimitedUntil });
429
+ if (clear || differentAccount(matching.entry, entry))
430
+ await setAccountVendorLimit(db, person, row, undefined);
415
431
  if (differentAccount(matching.entry, entry))
416
432
  await deleteModelCooldowns(db, person, provider, row.id);
417
433
  return publicPool(pool, provider);
@@ -196,7 +196,7 @@ export const OPERATIONS = [
196
196
  { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
197
  { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
198
198
  { name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
199
- { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker'], resource: 'profile', stage: 'chat' },
199
+ { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker', 'cron'], resource: 'profile', stage: 'chat' },
200
200
  { name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
201
201
  { name: 'import.start', method: 'POST', path: '/v1/imports', classes: ['person', 'import'], resource: 'none' },
202
202
  { name: 'import.upload-urls', method: 'POST', path: '/v1/imports/:run_id/upload-urls', classes: ['person', 'import'], resource: 'none' },
@@ -220,7 +220,7 @@ export const OPERATIONS = [
220
220
  { name: 'canvas.get.127', method: 'GET', path: '/v1/canvas/history/read', classes: ['person', 'broker', 'forwarded'], resource: 'canvas-read' },
221
221
  { name: 'canvas.post.128', method: 'POST', path: '/v1/canvas/history/stats', classes: ['person', 'broker', 'forwarded'], resource: 'canvas-read' },
222
222
  { name: 'canvas.get.129', method: 'GET', path: '/v1/canvas/snapshot', classes: ['person', 'broker', 'forwarded'], resource: 'canvas-read' },
223
- { name: 'canvas.get.130', method: 'GET', path: '/v1/canvas/roster', classes: ['person', 'broker'], resource: 'canvas-read' },
223
+ { name: 'canvas.get.130', method: 'GET', path: '/v1/canvas/roster', classes: ['person', 'broker', 'cron'], resource: 'canvas-read' },
224
224
  { name: 'canvas.get.view', method: 'GET', path: '/v1/canvas/view/:id', classes: ['person', 'broker'], resource: 'canvas-read' },
225
225
  { name: 'canvas.get.live-roots', method: 'GET', path: '/v1/canvas/live-roots', classes: ['person'], resource: 'canvas-read' },
226
226
  { name: 'canvas.get.browse', method: 'GET', path: '/v1/canvas/browse', classes: ['person', 'broker'], resource: 'canvas-read' },
@@ -55,7 +55,7 @@ async function authorizeHumanBody(operation, principal, params, query, body) {
55
55
  throw new ApiError(404, 'not_found', 'comment not found');
56
56
  }
57
57
  /** Classes whose stored scope list is a second ceiling and whose reach is confined to a run place. */
58
- function boundedByStoredScopes(principal) {
58
+ export function boundedByStoredScopes(principal) {
59
59
  return principal.class === 'broker' || principal.class === 'cron';
60
60
  }
61
61
  /** The app a non-person caller acts as: a forwarded app actor's app, a forwarded person's terminal, null for the anonymous, a machine and the person. */
@@ -10,6 +10,7 @@ import { recordedPidLiveness } from '../../core/canvas/pid.js';
10
10
  import { transition } from '../../core/runtime/lifecycle.js';
11
11
  import { hasAdmittedTurn, listUnnotifiedFatalFaultNodes, markFaultNotified, readFault, readLiveTurn, recordFault } from '../../core/canvas/recovery.js';
12
12
  import { errorClassFromFault } from '../../core/fault-classifier.js';
13
+ import { describeVendorLimit } from '../../core/provider-failure.js';
13
14
  import { nextFaultRetry } from '../../core/runtime/fault-recovery.js';
14
15
  import { publishNotice } from '../../core/runtime/close.js';
15
16
  import { openDb, withCanvasWrite } from '../../core/canvas/db.js';
@@ -671,7 +672,8 @@ export class BrokerSupervisionReconciler {
671
672
  (providerError.errno === undefined ? '' : ` Errno: ${providerError.errno}.`) +
672
673
  (providerError.code === undefined ? '' : ` Code: ${providerError.code}.`) +
673
674
  (providerError.body === undefined ? '' : ` Body: ${providerError.body.slice(0, 200)}.`) +
674
- (providerError.ratelimit === undefined ? '' : ` Rate limit: ${providerError.ratelimit.scope ?? 'account'}${providerError.ratelimit.claim === undefined ? '' : ` (${providerError.ratelimit.claim})`}${providerError.ratelimit.model === undefined ? '' : ` on ${providerError.ratelimit.model}`}.`);
675
+ (fault.retry.nextAt === undefined ? '' : ` Next router probe: ${fault.retry.nextAt}.`) +
676
+ describeVendorLimit(providerError);
675
677
  const terminalOverflow = fault.kind === 'context-overflow';
676
678
  const terminalProviderFault = settlesOnFatalProviderFault(meta, typeof providerError?.code === 'string' ? providerError.code : undefined);
677
679
  const terminalFault = terminalOverflow || terminalProviderFault;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.720",
3
+ "version": "0.3.722",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.720",
3
+ "version": "0.3.722",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.720",
3
+ "version": "0.3.722",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.720",
31
- "@north-light/identity": "0.3.720"
30
+ "@north-light/api": "0.3.722",
31
+ "@north-light/identity": "0.3.722"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.720",
3
+ "version": "0.3.722",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.720",
9
+ "version": "0.3.722",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.720",
32
- "@north-light/plugin": "0.3.720",
31
+ "@north-light/identity": "0.3.722",
32
+ "@north-light/plugin": "0.3.722",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.720",
11905
+ "version": "0.3.722",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.720",
11910
+ "version": "0.3.722",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.720",
11915
+ "version": "0.3.722",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.720",
11923
+ "version": "0.3.722",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.720",
11927
- "@north-light/identity": "0.3.720"
11926
+ "@north-light/api": "0.3.722",
11927
+ "@north-light/identity": "0.3.722"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.720",
11932
+ "version": "0.3.722",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.720",
11936
- "@north-light/identity": "0.3.720",
11937
- "@north-light/plugin": "0.3.720",
11935
+ "@north-light/api": "0.3.722",
11936
+ "@north-light/identity": "0.3.722",
11937
+ "@north-light/plugin": "0.3.722",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {