@north-light/cli 0.3.721 → 0.3.723
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/dto/recovery.d.ts +2 -0
- package/dist/builtin-memory/internal/plugins.md +3 -3
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/node/inspect.js +7 -7
- package/dist/commands/pkg/browse/model.d.ts +1 -1
- package/dist/commands/profile/environment.js +2 -2
- package/dist/commands/sys/setup-core.d.ts +1 -1
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup.js +1 -1
- package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/environment-starter-script.d.ts +1 -0
- package/dist/core/environment-starter-script.js +58 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/managed-providers.d.ts +9 -1
- package/dist/core/preview-registry.js +3 -3
- package/dist/core/provider-failure.d.ts +2 -0
- package/dist/core/provider-failure.js +1 -1
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/revive.d.ts +2 -0
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/subscription-state.d.ts +4 -4
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/messages.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
- package/packages/crouter-api/dist/commands/pkg/browse/model.js +1 -1
- package/packages/crouter-api/dist/commands/profile/environment.js +23 -5
- package/packages/crouter-api/dist/commands/sys/setup-core.js +2 -10
- package/packages/crouter-api/dist/commands/sys/setup.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/environment-starter-script.js +61 -0
- package/packages/crouter-api/dist/core/llm/run.js +13 -2
- package/packages/crouter-api/dist/core/preview-registry.js +1 -5
- package/packages/crouter-api/dist/core/provider-failure.js +9 -0
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
- package/packages/crouter-api/dist/core/subscription-state.js +26 -10
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -9,6 +9,7 @@ import { nodeSnapshotLeaf } from '../node-snapshot.js';
|
|
|
9
9
|
import { nodeTranscriptLeaf } from '../node-transcript.js';
|
|
10
10
|
import { nodeContextLeaf } from '../node-context.js';
|
|
11
11
|
import { ApiError } from '../../api/index.js';
|
|
12
|
+
import { describeVendorLimit } from '../../core/provider-failure.js';
|
|
12
13
|
import { cliClient, cliCanvasSource, rethrowAsCliError } from '../api-client.js';
|
|
13
14
|
import { RemoteCanvasSource } from '../../core/canvas/remote-canvas-source.js';
|
|
14
15
|
import { kindsStateBlock, profilesStateBlock, resolveProfileViaDaemon } from '../profile/daemon-profiles.js';
|
|
@@ -203,7 +204,7 @@ const nodeShow = defineLeaf({
|
|
|
203
204
|
const meta = [
|
|
204
205
|
`- kind/mode/lifecycle: ${node['kind']} / ${node['mode']} / ${node['lifecycle']}`,
|
|
205
206
|
`- status: ${node['status']}${intent}`,
|
|
206
|
-
...(fault === null || fault === undefined ? [] : [`- fault: ${String(fault['kind'])} / ${String(fault['retry']?.disposition)} since ${String(fault['since'])}`]),
|
|
207
|
+
...(fault === null || fault === undefined ? [] : [`- fault: ${String(fault['kind'])} / ${String(fault['retry']?.disposition)} since ${String(fault['since'])}${fault.retry?.nextAt === undefined ? '' : `. Next router probe: ${fault.retry.nextAt}.`}${describeVendorLimit(fault.providerError)}`]),
|
|
207
208
|
`- broker pid: ${pid ?? '(none)'} — ${alive}`,
|
|
208
209
|
`- cwd: ${node['cwd']}`,
|
|
209
210
|
`- host: ${node['host_kind']}` + (node['profile_id'] ? ` · profile ${node['profile_id']}` : ''),
|
|
@@ -10,7 +10,7 @@ export const INSTALLED_SOURCE_ID = "installed";
|
|
|
10
10
|
export function marketplaceSourceId(name, scope) {
|
|
11
11
|
return `market:${scope}:${name}`;
|
|
12
12
|
}
|
|
13
|
-
/** `crtr
|
|
13
|
+
/** `crtr capture shot` — how a user types the command a node names. The one place
|
|
14
14
|
* a command path becomes a label, so no corner of the page invents its own. */
|
|
15
15
|
export function commandLabel(node) {
|
|
16
16
|
return `crtr ${node.path.join(" ")}`;
|
|
@@ -5,6 +5,7 @@ import { resolve } from 'node:path';
|
|
|
5
5
|
import { defineLeaf, defineBranch } from '../../core/command.js';
|
|
6
6
|
import { usage } from '../../core/errors.js';
|
|
7
7
|
import { cliClient } from '../api-client.js';
|
|
8
|
+
import { STARTER_SETUP_SCRIPT } from '../../core/environment-starter-script.js';
|
|
8
9
|
import { resolveProfileViaDaemon } from './daemon-profiles.js';
|
|
9
10
|
const PROFILE_FLAG = { kind: 'flag', name: 'profile', type: 'string', required: true, constraint: 'Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr.' };
|
|
10
11
|
const ENVIRONMENT_OUTPUT = [
|
|
@@ -39,24 +40,41 @@ const showLeaf = defineLeaf({
|
|
|
39
40
|
return output(await cliClient().getProfileEnvironment(id));
|
|
40
41
|
},
|
|
41
42
|
});
|
|
43
|
+
const starterLeaf = defineLeaf({
|
|
44
|
+
name: 'starter',
|
|
45
|
+
description: 'print a commented starter setup script to copy and fill in',
|
|
46
|
+
whenToUse: 'writing the first setup script for a cloud profile, or looking up what the image build already does and where secrets go.',
|
|
47
|
+
help: {
|
|
48
|
+
name: 'profile environment starter',
|
|
49
|
+
summary: 'print a commented starter setup script with example sections',
|
|
50
|
+
params: [],
|
|
51
|
+
output: [],
|
|
52
|
+
outputKind: 'object',
|
|
53
|
+
effects: ['Prints the script as-is to stdout: redirect it to a file (`> setup.sh`), edit it, pass it to `profile environment set --setup-script-file`. Read-only; changes no profile and builds no image.'],
|
|
54
|
+
},
|
|
55
|
+
run: async () => { process.stdout.write(STARTER_SETUP_SCRIPT); },
|
|
56
|
+
});
|
|
42
57
|
const setLeaf = defineLeaf({
|
|
43
58
|
name: 'set',
|
|
44
59
|
description: "change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",
|
|
45
|
-
whenToUse: 'a dev profile needs other repositories, a setup script for its image
|
|
60
|
+
whenToUse: 'a dev profile needs other repositories, a setup script for its image, pi packages, or more memory. A flag left out keeps its value. For a first setup script, start from `crtr profile environment starter`.',
|
|
46
61
|
help: {
|
|
47
62
|
name: 'profile environment set',
|
|
48
63
|
summary: "change a cloud profile's environment recipe or memory",
|
|
49
64
|
params: [
|
|
50
65
|
PROFILE_FLAG,
|
|
51
66
|
{ 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
|
-
{ kind: 'flag', name: 'setup-script-file', type: 'path', required: false, constraint: 'File holding the setup script
|
|
67
|
+
{ kind: 'flag', name: 'setup-script-file', type: 'path', required: false, constraint: 'File holding the setup script. The image build runs it once as root in `/work` on Alpine (apk), after checking out the repositories into `/work/<name>` and downloading every pnpm-lock.yaml repository\'s packages into a shared pnpm store; output lands in `/work/.crtr/setup.log`, and a non-zero exit stops sandboxes from starting. `crtr profile environment starter` prints a commented template.' },
|
|
53
68
|
{ kind: 'flag', name: 'pi-package', type: 'string', required: false, repeatable: true, constraint: 'pi package source (repeat per package); replaces the whole list.' },
|
|
54
69
|
{ 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
70
|
{ 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
71
|
],
|
|
57
72
|
output: [...ENVIRONMENT_OUTPUT],
|
|
58
73
|
outputKind: 'object',
|
|
59
|
-
effects: [
|
|
74
|
+
effects: [
|
|
75
|
+
'A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing.',
|
|
76
|
+
'Secrets never go in the setup script, because it is baked into the image: store them with `crtr profile env set <profile> --name <NAME>` and every sandbox gets them as environment variables.',
|
|
77
|
+
],
|
|
60
78
|
},
|
|
61
79
|
run: async (input) => {
|
|
62
80
|
const { id } = await resolveProfileViaDaemon(input['profile']);
|
|
@@ -86,7 +104,7 @@ export const environmentBranch = defineBranch({
|
|
|
86
104
|
help: {
|
|
87
105
|
name: 'profile environment',
|
|
88
106
|
summary: "a cloud profile's environment recipe and memory",
|
|
89
|
-
model: 'A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from
|
|
107
|
+
model: 'A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from: repositories, a setup script and pi packages. Changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only. The build always checks out the repositories into `/work/<name>`, installs git, gh, Node and pnpm, and downloads each pnpm repository\'s packages into a shared store; the setup script adds the rest (`starter` prints a template). API keys and other secrets live in `crtr profile env`, never in the recipe.',
|
|
90
108
|
},
|
|
91
|
-
children: [showLeaf, setLeaf],
|
|
109
|
+
children: [showLeaf, starterLeaf, setLeaf],
|
|
92
110
|
});
|
|
@@ -250,11 +250,6 @@ const PACKAGE_COPY = {
|
|
|
250
250
|
shortDescription: 'crtr plugin mounting `crtr capture` — browser automation and UI measurement over CDP.',
|
|
251
251
|
longDescription: 'Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser — the command then costs nothing in their root prompt.',
|
|
252
252
|
},
|
|
253
|
-
'exa-search-plugin': {
|
|
254
|
-
name: 'exa-search',
|
|
255
|
-
shortDescription: 'crtr plugin mounting `crtr exa-search` — public-web discovery, grounded answers, and content extraction.',
|
|
256
|
-
longDescription: 'Installs the `exa-search` plugin from the official crtr marketplace. It mounts `crtr exa-search` and calls Exa directly with EXA_API_KEY, collected during install or set through `crtr sys env set --name EXA_API_KEY` in the app env store. Uncheck it on a machine whose agents get web search from somewhere else, such as a Northlight home where the platform serves `crtr search` from its own plugin.',
|
|
257
|
-
},
|
|
258
253
|
'dev-plugin': {
|
|
259
254
|
name: 'dev',
|
|
260
255
|
shortDescription: 'crtr plugin mounting the development workflow — repository setup, worktrees, pull requests, and a dev track in the tutorial.',
|
|
@@ -266,7 +261,6 @@ const PACKAGE_SOURCES = {
|
|
|
266
261
|
'crtr-extensions': { kind: 'local-path', source: selectedPiPackageDir('pi-crtr-extensions') },
|
|
267
262
|
'oauth-adapter': { kind: 'npm', source: 'npm:pi-claude-oauth-adapter@0.2.2' },
|
|
268
263
|
'capture-plugin': { kind: 'marketplace-plugin', source: 'crouter-official-marketplace/capture' },
|
|
269
|
-
'exa-search-plugin': { kind: 'marketplace-plugin', source: 'crouter-official-marketplace/exa-search' },
|
|
270
264
|
'dev-plugin': { kind: 'marketplace-plugin', source: 'crouter-official-marketplace/dev' },
|
|
271
265
|
};
|
|
272
266
|
const CRTR_EXTENSION_GLOBS = ['extensions/*.ts', 'extensions/*/index.ts', '!extensions/**/*.d.ts'];
|
|
@@ -275,7 +269,6 @@ const LOCAL_PACKAGE_NAME_ALIASES = {
|
|
|
275
269
|
'crtr-extensions': ['pi-crtr-extensions'],
|
|
276
270
|
'oauth-adapter': [],
|
|
277
271
|
'capture-plugin': [],
|
|
278
|
-
'exa-search-plugin': [],
|
|
279
272
|
'dev-plugin': [],
|
|
280
273
|
};
|
|
281
274
|
function selectedPiPackageDir(name) {
|
|
@@ -289,7 +282,6 @@ export function buildSetupManifest(resolveBuiltinPackageDir = selectedPiPackageD
|
|
|
289
282
|
'crtr-extensions',
|
|
290
283
|
'oauth-adapter',
|
|
291
284
|
'capture-plugin',
|
|
292
|
-
'exa-search-plugin',
|
|
293
285
|
'dev-plugin',
|
|
294
286
|
].map((id) => {
|
|
295
287
|
const copy = PACKAGE_COPY[id];
|
|
@@ -738,8 +730,8 @@ export async function reconcileFirstRun(onFailure, commandExists = detectCommand
|
|
|
738
730
|
installedPackageIds.add(id);
|
|
739
731
|
const byId = new Map(manifest.map((entry) => [entry.id, entry]));
|
|
740
732
|
const packageIds = process.stdin.isTTY && process.stdout.isTTY
|
|
741
|
-
? ['crtr-extensions', 'official-marketplace', 'oauth-adapter', 'capture-plugin'
|
|
742
|
-
: ['crtr-extensions', 'official-marketplace', 'capture-plugin'
|
|
733
|
+
? ['crtr-extensions', 'official-marketplace', 'oauth-adapter', 'capture-plugin']
|
|
734
|
+
: ['crtr-extensions', 'official-marketplace', 'capture-plugin'];
|
|
743
735
|
let gitMissing;
|
|
744
736
|
let gitReported = false;
|
|
745
737
|
for (const id of packageIds) {
|
|
@@ -24,7 +24,7 @@ export const sysSetupLeaf = defineLeaf({
|
|
|
24
24
|
'The remaining steps collect companion package installs and system dependency installs, then confirm them all at once.',
|
|
25
25
|
'On macOS, a final step detects the terminal and explains how to make Option act as Alt (crouter\'s menu is Alt+C). Where the setting is safely scriptable (Ghostty, stock VS Code) it can write the one line for you, but only if you tick it and after showing exactly what will be written.',
|
|
26
26
|
'Runs the bundled pi CLI to install the selected companion packages and prints a summary.',
|
|
27
|
-
'The companion-package list includes the official crtr marketplace and the plugins installed from it (currently `capture`
|
|
27
|
+
'The companion-package list includes the official crtr marketplace and the plugins installed from it (currently `capture`), all checked by default and registered or installed into the user scope when left checked. Nothing else registers a marketplace, so an install that never runs setup fetches no catalog. An unreachable marketplace is reported as skipped rather than failing setup. Vendor credentials belong to the plugin that needs them, never to setup.',
|
|
28
28
|
'In a terminal, records setup as done (the same record the first bare `crtr` writes), so the next bare `crtr` boots a conversation instead of reopening the installer, and offers the tutorial if no conversation has started since setup first ran.',
|
|
29
29
|
'On every invocation (best-effort, idempotent), refreshes crouter-owned tmux bindings and registers known nodes\' interaction roots so resolved tickets can call back into the asking node. The inbox popup toggle is a crouter-owned keybinding, editable on the keybindings tab.',
|
|
30
30
|
],
|
|
@@ -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 =
|
|
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. */
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The starter setup script `crtr profile environment starter` prints: a commented template a developer copies, fills in and passes to
|
|
2
|
+
// `crtr profile environment set --setup-script-file`. It is printed, never stored: a stored script, even one of comments only, gives the
|
|
3
|
+
// environment a recipe and costs an image build before anyone has asked for one.
|
|
4
|
+
export const STARTER_SETUP_SCRIPT = `#!/usr/bin/env bash
|
|
5
|
+
# Setup script for a crtr cloud environment.
|
|
6
|
+
#
|
|
7
|
+
# How it runs
|
|
8
|
+
# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
|
|
9
|
+
# - Your repositories are already checked out at /work/<repo name> before this runs.
|
|
10
|
+
# - The sandbox user is "crtr" (home /home/crtr). Files you create for it must be chowned to it.
|
|
11
|
+
# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. For every repository with a pnpm-lock.yaml, its packages are already
|
|
12
|
+
# downloaded into a shared pnpm store, so \`pnpm install\` in a sandbox links instead of downloading.
|
|
13
|
+
# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
|
|
14
|
+
# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.
|
|
15
|
+
#
|
|
16
|
+
# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile
|
|
17
|
+
# instead and every sandbox gets them as environment variables:
|
|
18
|
+
# printf '%s' "<value>" | crtr profile env set <profile> --name OPENAI_API_KEY
|
|
19
|
+
#
|
|
20
|
+
# Apply this file with:
|
|
21
|
+
# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh
|
|
22
|
+
# then watch the build with \`crtr profile environment show --profile <profile>\` (ready when image_revision equals recipe_revision).
|
|
23
|
+
#
|
|
24
|
+
# Uncomment the sections you need. Delete the rest.
|
|
25
|
+
|
|
26
|
+
set -euo pipefail
|
|
27
|
+
|
|
28
|
+
# ── 1. System packages ───────────────────────────────────────────────────────────────────────────────
|
|
29
|
+
# Alpine package names: https://pkgs.alpinelinux.org/packages
|
|
30
|
+
# apk add --no-cache build-base python3 # native npm modules (node-gyp)
|
|
31
|
+
# apk add --no-cache jq sqlite # command-line tools your agents use
|
|
32
|
+
# apk add --no-cache chromium # headless browser tests
|
|
33
|
+
|
|
34
|
+
# ── 2. A local Postgres ──────────────────────────────────────────────────────────────────────────────
|
|
35
|
+
# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.
|
|
36
|
+
# apk add --no-cache postgresql postgresql-contrib
|
|
37
|
+
# mkdir -p /run/postgresql && chown crtr /run/postgresql
|
|
38
|
+
# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'
|
|
39
|
+
|
|
40
|
+
# ── 3. App dependencies ──────────────────────────────────────────────────────────────────────────────
|
|
41
|
+
# pnpm repositories are already prepared (see above). For npm or yarn, or to install fully at build time:
|
|
42
|
+
# (cd /work/<repo name> && npm ci)
|
|
43
|
+
# (cd /work/<repo name> && pnpm install --frozen-lockfile)
|
|
44
|
+
# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.
|
|
45
|
+
|
|
46
|
+
# ── 4. Global CLIs ───────────────────────────────────────────────────────────────────────────────────
|
|
47
|
+
# npm install -g typescript tsx
|
|
48
|
+
# curl -fsSL https://example.com/install.sh | sh
|
|
49
|
+
|
|
50
|
+
# ── 5. Start services on the agent's first command ───────────────────────────────────────────────────
|
|
51
|
+
# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then
|
|
52
|
+
# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV
|
|
53
|
+
# cat > /home/crtr/.services-up.sh <<'UP'
|
|
54
|
+
# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o "-k /tmp -h localhost" -l /tmp/pg.log -w start >/dev/null 2>&1 || true
|
|
55
|
+
# UP
|
|
56
|
+
# chown crtr /home/crtr/.services-up.sh
|
|
57
|
+
|
|
58
|
+
# ── 6. Seed files and config ─────────────────────────────────────────────────────────────────────────
|
|
59
|
+
# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from \`crtr profile env\`
|
|
60
|
+
# chown -R crtr /work/<repo name>
|
|
61
|
+
`;
|
|
@@ -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) {
|
|
@@ -59,7 +59,7 @@ export const TOOL_ICON = {
|
|
|
59
59
|
/** One glyph per root family (`crtr <family> ...`) — the fallback for any
|
|
60
60
|
* leaf not listed in LEAF_ICON_CP below. Codepoints are Nerd Font
|
|
61
61
|
* private-use-area icons chosen per family concept (see command-icons.md).
|
|
62
|
-
* Families a plugin mounts (capture, device
|
|
62
|
+
* Families a plugin mounts (capture, device) are listed here too: this
|
|
63
63
|
* registry is keyed by command path, not by who owns the command. */
|
|
64
64
|
const FAMILY_ICON_CP = {
|
|
65
65
|
canvas: 0xf0e8,
|
|
@@ -71,7 +71,6 @@ const FAMILY_ICON_CP = {
|
|
|
71
71
|
pkg: 0xf1b2,
|
|
72
72
|
profile: 0xf2bd,
|
|
73
73
|
push: 0xf0ee,
|
|
74
|
-
'exa-search': 0xf002,
|
|
75
74
|
surface: 0xf108,
|
|
76
75
|
sys: 0xf013,
|
|
77
76
|
};
|
|
@@ -143,9 +142,6 @@ export const LEAF_ICON_CP = {
|
|
|
143
142
|
'pkg market browse': 0xf14e,
|
|
144
143
|
'push update': 0xf093,
|
|
145
144
|
'push final': 0xf11e,
|
|
146
|
-
'exa-search web': 0xf0ac,
|
|
147
|
-
'exa-search answer': 0xf075,
|
|
148
|
-
'exa-search contents': 0xf0f6,
|
|
149
145
|
'surface attach to': 0xf1e6,
|
|
150
146
|
'sys config get': 0xf019,
|
|
151
147
|
'sys config set': 0xf040,
|
|
@@ -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
|
-
|
|
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(
|
|
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
|
|
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(
|
|
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);
|
|
@@ -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
|
-
(
|
|
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.
|
|
3
|
+
"version": "0.3.723",
|
|
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/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.723",
|
|
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.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.723",
|
|
31
|
+
"@north-light/identity": "0.3.723"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|