@north-light/cli 0.3.713 → 0.3.715
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/client.d.ts +3 -1
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/environments.d.ts +4 -0
- package/dist/api/dto/execution-start.d.ts +9 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +2 -0
- package/dist/clients/attach/input/controller.js +1 -1
- package/dist/clients/attach/input/local-files.d.ts +3 -1
- package/dist/clients/attach/input/local-files.js +8 -3
- package/dist/clients/attach/render/chat-view.d.ts +1 -1
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/viewer.js +526 -521
- package/dist/commands/node/inspect.js +5 -5
- package/dist/commands/profile/environment.js +2 -2
- package/dist/commands/sys/feedback.js +5 -5
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/canvas.js +1 -1
- package/dist/core/canvas/deliveries.js +10 -10
- package/dist/core/canvas/executions.d.ts +0 -2
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
- package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/types.d.ts +1 -0
- package/dist/core/checkout-identities.js +1 -1
- package/dist/core/environment-recipe.d.ts +1 -0
- package/dist/core/environment-recipe.js +1 -1
- package/dist/core/import/load/bind.d.ts +8 -0
- package/dist/core/import/load/bind.js +15 -15
- package/dist/core/import/load/prepare.d.ts +8 -1
- package/dist/core/import/load/prepare.js +9 -7
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/ledger/rates.d.ts +0 -2
- package/dist/core/ledger/rates.js +1 -1
- package/dist/core/llm/run.d.ts +1 -1
- package/dist/core/pool-credential-store.d.ts +5 -5
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker-wedge.d.ts +1 -2
- package/dist/core/runtime/broker-wedge.js +2 -2
- 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/runtime/runner/types.d.ts +0 -2
- package/dist/core/runtime/spawn.js +1 -1
- package/dist/core/subscription-state.d.ts +3 -3
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/feedback.d.ts +2 -0
- package/dist/daemon/api/handlers/feedback.js +9 -0
- package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
- package/dist/daemon/api/handlers/git-credential.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -12
- package/dist/daemon/fleet.js +2 -2
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/holder.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +3 -3
- package/dist/daemon/reconcilers/ledger-storage.js +2 -4
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
- package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
- package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
- package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
- package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
- package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
- package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
- package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
- package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
- package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
- package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
- package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/core/subscription-state.js +70 -81
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
- package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
- 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
- package/scripts/install-runtime.mjs +3 -2
- package/scripts/sandbox-start.mjs +1 -1
- package/scripts/self-update.mjs +5 -1
|
@@ -81,20 +81,37 @@ function rewriteJsonPaths(text, map) {
|
|
|
81
81
|
return mapPath(map, text);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
-
/** A profile whose name
|
|
84
|
+
/** A profile whose name another profile already holds is renamed `<name>-<install id>` (staging only; runs before the pre-check), in its `profiles` row and in its `profile`
|
|
85
|
+
* object's handle. The name clashes when the person already uses it for another profile, or when the object's handle is held by any other live profile object: `objects_handle`
|
|
86
|
+
* is unique per type across the whole fleet, so another person's profile counts. Only a handle that is the profile's name moves (a cloud role's handle is the profile id).
|
|
87
|
+
* The new name is a function of the install, so a second load of the bundle derives the same one. Runs after `mapProfileIds`, which leaves the staged identity at the profile's id. */
|
|
85
88
|
export async function renameClashingProfiles(db, schema, target, installId, person) {
|
|
86
89
|
const S = (t) => sq(schema, t);
|
|
87
90
|
const profiles = await db.prepareUncached(`SELECT id, name FROM ${S('profiles')} ORDER BY id`).all();
|
|
88
91
|
let renamed = 0;
|
|
89
92
|
for (const profile of profiles) {
|
|
90
|
-
const
|
|
91
|
-
|
|
93
|
+
const object = await db.prepareUncached(`SELECT o.id FROM ${S('objects')} o JOIN ${S('identities')} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
94
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(profile.id, profile.name);
|
|
95
|
+
const sameName = await db.prepareUncached(`SELECT 1 AS found FROM ${sq(target, 'profiles')} WHERE person = ? AND name = ? AND id <> ?`).get(person, profile.name, profile.id);
|
|
96
|
+
const handleHeld = object === undefined ? undefined : await db.prepareUncached(`SELECT 1 AS found FROM ${sq(target, 'objects')} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(profile.name, object.id);
|
|
97
|
+
if (sameName === undefined && handleHeld === undefined)
|
|
92
98
|
continue;
|
|
93
|
-
|
|
99
|
+
const next = `${profile.name}-${installId}`;
|
|
100
|
+
await db.prepareUncached(`UPDATE ${S('profiles')} SET name = ? WHERE id = ?`).run(next, profile.id);
|
|
101
|
+
if (object !== undefined)
|
|
102
|
+
await db.prepareUncached(`UPDATE ${S('objects')} SET name = ? WHERE id = ?`).run(next, object.id);
|
|
94
103
|
renamed += 1;
|
|
95
104
|
}
|
|
96
105
|
return renamed;
|
|
97
106
|
}
|
|
107
|
+
/** A migrated usage charge (`legacy:` id, `importLegacyUsage`) has no install id, so two Macs of one person with usage in the same month and model produce one id with
|
|
108
|
+
* different amounts. A staged one whose id the target holds with a different payer, units or usd is renamed `<id>:install-<install id>`; one the target holds unchanged keeps its
|
|
109
|
+
* id and is skipped by the copy. A second load of the same bundle derives the same id. Runs before the pre-check. */
|
|
110
|
+
export async function renameClashingLegacyCharges(db, schema, target, installId) {
|
|
111
|
+
const done = await db.prepareUncached(`UPDATE ${sq(schema, 'charges')} s SET id = s.id || ':install-' || ?::text FROM ${sq(target, 'charges')} t
|
|
112
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(installId);
|
|
113
|
+
return Number(done.changes);
|
|
114
|
+
}
|
|
98
115
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
99
116
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
100
117
|
export async function fillEnvironments(tx, schema, target, source, person) {
|
|
@@ -7,7 +7,6 @@ export const LEDGER_ENV = {
|
|
|
7
7
|
sandboxUsdPerGbHour: 'CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR',
|
|
8
8
|
sandboxStandbyS: 'CRTR_LEDGER_SANDBOX_STANDBY_S',
|
|
9
9
|
storageUsdPerGbMonth: 'CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH',
|
|
10
|
-
sandboxDiskUsdPerGbMonth: 'CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH',
|
|
11
10
|
infraFreeUsdPerMonth: 'CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH',
|
|
12
11
|
takePct: 'CRTR_LEDGER_TAKE_PCT',
|
|
13
12
|
r2Move: 'CRTR_LEDGER_R2_MOVE',
|
|
@@ -37,7 +36,6 @@ function flag(name) {
|
|
|
37
36
|
export const sandboxUsdPerGbHour = () => number(LEDGER_ENV.sandboxUsdPerGbHour);
|
|
38
37
|
export const sandboxStandbyS = () => number(LEDGER_ENV.sandboxStandbyS) ?? DEFAULT_STANDBY_S;
|
|
39
38
|
export const storageUsdPerGbMonth = () => number(LEDGER_ENV.storageUsdPerGbMonth);
|
|
40
|
-
export const sandboxDiskUsdPerGbMonth = () => number(LEDGER_ENV.sandboxDiskUsdPerGbMonth);
|
|
41
39
|
export const infraFreeUsdPerMonth = () => number(LEDGER_ENV.infraFreeUsdPerMonth) ?? DEFAULT_INFRA_FREE_USD;
|
|
42
40
|
/** Northlight's take on each priced model or tool charge, in percent; 0 (the default) writes no take rows. */
|
|
43
41
|
export const takePercent = () => number(LEDGER_ENV.takePct, 100) ?? 0;
|
|
@@ -48,7 +46,6 @@ export function assertLedgerEnv() {
|
|
|
48
46
|
sandboxUsdPerGbHour();
|
|
49
47
|
sandboxStandbyS();
|
|
50
48
|
storageUsdPerGbMonth();
|
|
51
|
-
sandboxDiskUsdPerGbMonth();
|
|
52
49
|
infraFreeUsdPerMonth();
|
|
53
50
|
takePercent();
|
|
54
51
|
r2MoveEnabled();
|
|
@@ -44,7 +44,7 @@ function refreshFailure(error, served) {
|
|
|
44
44
|
return error;
|
|
45
45
|
return new RunError(503, 'upstream_model_unavailable', message.slice(0, 500), undefined, { served_model: served });
|
|
46
46
|
}
|
|
47
|
-
/** The account's access token, refreshed under the
|
|
47
|
+
/** The account's access token, refreshed under the account's refresh claim (no connection held during the vendor call) when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
|
|
48
48
|
export async function freshSubscriptionAccess(registry, provider, account, served, signal) {
|
|
49
49
|
if (account.expires > Date.now())
|
|
50
50
|
return account.access;
|
|
@@ -69,11 +69,11 @@ export class PoolCredentialStore {
|
|
|
69
69
|
return listedCredentials(stored, (providerId) => sizes.get(providerId) ?? 0);
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
|
-
* pi's
|
|
73
|
-
*
|
|
74
|
-
* expired account
|
|
75
|
-
* `invalid_grant`.
|
|
76
|
-
* back on exactly the account whose token was spent.
|
|
72
|
+
* pi's read-modify-write, chiefly its OAuth refresh. Running pi's `fn` and committing the result
|
|
73
|
+
* happen under the account's refresh claim, because a refresh token is single-use: two brokers
|
|
74
|
+
* refreshing the same expired account without it would both spend it and the loser would get a
|
|
75
|
+
* genuine `invalid_grant`. The commit is conditional on the spent token, so the refreshed token
|
|
76
|
+
* lands back on exactly the account whose token was spent.
|
|
77
77
|
*
|
|
78
78
|
* A managed provider with no pool account is NOT created here — pi must not be able to mint a
|
|
79
79
|
* managed account behind crouter's login surfaces, which own the account-identity gate.
|
|
@@ -7,11 +7,9 @@ export const YIELD_STALL_GRACE_MS = 3 * 60_000;
|
|
|
7
7
|
export const KILL_ESCALATE_MS = 20_000;
|
|
8
8
|
export const WEDGE_QUIET_MS = 20 * 60_000;
|
|
9
9
|
export const WEDGE_CPU_MAX_PERCENT = 2;
|
|
10
|
-
export function yieldStallVerdict(piPidAlive,
|
|
10
|
+
export function yieldStallVerdict(piPidAlive, busy, stalledFor) {
|
|
11
11
|
if (piPidAlive !== true)
|
|
12
12
|
return 'leave';
|
|
13
|
-
if (intent !== 'refresh')
|
|
14
|
-
return 'leave';
|
|
15
13
|
if (busy)
|
|
16
14
|
return 'leave';
|
|
17
15
|
if (stalledFor === null || stalledFor < YIELD_STALL_GRACE_MS)
|
|
@@ -651,7 +651,7 @@ async function launchRevive(nodeId, meta, opts) {
|
|
|
651
651
|
let launched;
|
|
652
652
|
try {
|
|
653
653
|
const row = await liveExecutionForNode(nodeId);
|
|
654
|
-
const started = await runner.start({ executionId, nodeId, attempt: row?.attempt ?? 1,
|
|
654
|
+
const started = await runner.start({ executionId, nodeId, attempt: row?.attempt ?? 1,
|
|
655
655
|
release: row?.release ?? '', launchJson, cwd: meta.cwd, resuming });
|
|
656
656
|
launched = started;
|
|
657
657
|
if (!remote && launched.pid === null) {
|
|
@@ -27,6 +27,15 @@ export const REPOS_DIR = 'repos';
|
|
|
27
27
|
/** 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
28
|
export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
|
|
29
29
|
export const SETUP_FAILED_FILE = '/work/.crtr/setup-failed';
|
|
30
|
+
/** `gh` for a sandbox: /usr/local/bin comes before /usr/bin, so this wrapper runs first. It asks git's credential helper (set at sandbox start, so it reaches the control plane's
|
|
31
|
+
* git-credential route) for a fresh installation token, exports it as GH_TOKEN for this one call and runs the real gh. No token is stored on disk. */
|
|
32
|
+
export const GH_WRAPPER_PATH = '/usr/local/bin/gh';
|
|
33
|
+
const GH_WRAPPER_LINES = [
|
|
34
|
+
'#!/bin/sh',
|
|
35
|
+
'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")',
|
|
36
|
+
'[ -n "$token" ] && export GH_TOKEN="$token"',
|
|
37
|
+
'exec /usr/bin/gh "$@"',
|
|
38
|
+
];
|
|
30
39
|
const shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
31
40
|
const lines = (text) => (text ?? '').split('\n').map((l) => l.trim()).filter((l) => l !== '');
|
|
32
41
|
/** A RUN step that cannot fail the build (Blaxel hangs on a failed step and its build log is unreadable): its output goes to `SETUP_LOG_FILE` and a
|
|
@@ -40,7 +49,8 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
40
49
|
const hasScript = recipe.setup_script !== null && recipe.setup_script.trim() !== '';
|
|
41
50
|
const base = [
|
|
42
51
|
`FROM ${NODE_BASE_IMAGE}`,
|
|
43
|
-
'RUN apk add --no-cache bash git curl ripgrep',
|
|
52
|
+
'RUN apk add --no-cache bash git curl ripgrep github-cli',
|
|
53
|
+
`RUN printf '%s\\n' ${GH_WRAPPER_LINES.map(shellQuote).join(' ')} > ${GH_WRAPPER_PATH} && chmod 755 ${GH_WRAPPER_PATH}`,
|
|
44
54
|
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
45
55
|
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /work/.crtr ${RECIPE_PI_AGENT_DIR} && chown -R ${RUN_USER} /work /var/lib/crtr`,
|
|
46
56
|
];
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
//
|
|
8
8
|
// Boundaries: the runner does not decide when to wake (the node-lifecycle lane
|
|
9
9
|
// does), holds no mail, and writes the `executions` row only through its runner
|
|
10
|
-
// columns (`pid`, `process_identity`, `
|
|
10
|
+
// columns (`pid`, `process_identity`, `heartbeat_at`). Every
|
|
11
11
|
// method is safe to call twice: a reconciler whose lease was taken may repeat a
|
|
12
12
|
// call, so a repeat must be harmless (design D76).
|
|
13
13
|
//
|
|
@@ -333,7 +333,7 @@ async function startOnMachine(meta, environmentId, inv) {
|
|
|
333
333
|
const start = await renderCarriedStart(meta.node_id);
|
|
334
334
|
const nodeToken = await mintNodeToken(db, execId, meta.node_id, new Date().toISOString());
|
|
335
335
|
return await enqueueMachineCall(environmentId, 'start', {
|
|
336
|
-
executionId: execId, nodeId: meta.node_id, attempt: 1,
|
|
336
|
+
executionId: execId, nodeId: meta.node_id, attempt: 1, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
|
|
337
337
|
nodeToken, bundle, start,
|
|
338
338
|
});
|
|
339
339
|
}, { timingName: 'render_tx' }));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
3
|
import { brokerConfigSnapshot } from './config.js';
|
|
3
4
|
import { openDb, withCanvasWrite } from './canvas/db.js';
|
|
4
5
|
import { personIdAsync } from './canvas/person.js';
|
|
@@ -25,12 +26,13 @@ function identity(entry) { return entry.accountId?.trim() || (entry.refresh.trim
|
|
|
25
26
|
function withClientId(tokens, clientId) { const id = optionalString(clientId); return id ? { ...tokens, clientId: id } : tokens; }
|
|
26
27
|
function assertTokens(provider, label, value) { const refresh = value.refresh?.trim() ?? ''; const access = value.access?.trim() ?? ''; const expires = Number(value.expires); if (!refresh || !access || !Number.isFinite(expires))
|
|
27
28
|
throw new Error(`${getProviderLabel(provider)} subscription "${label}" returned an incomplete credential; the stored credential was left unchanged.`); return { refresh, access, expires }; }
|
|
28
|
-
/** Longest a refresh exchange may
|
|
29
|
+
/** Longest a refresh exchange may take. */
|
|
29
30
|
export const REFRESH_EXCHANGE_TIMEOUT_MS = 10_000;
|
|
30
|
-
/**
|
|
31
|
+
/** How long a refresh claim lasts, and how long another caller waits for the claimer's tokens. */
|
|
32
|
+
const REFRESH_CLAIM_MS = 15_000;
|
|
33
|
+
/** Longest a pool mutation or health write waits for another process's row or provider lock. */
|
|
31
34
|
const LOCK_TIMEOUT = '15s';
|
|
32
|
-
|
|
33
|
-
/** Another process held this account's row lock for the whole lock timeout (a slow refresh exchange): the account is cooling for this call, not failed. */
|
|
35
|
+
/** Another process claimed this account's refresh and wrote no fresh tokens within `REFRESH_CLAIM_MS`: the account is cooling for this call, not failed. */
|
|
34
36
|
export class RefreshBusyError extends Error {
|
|
35
37
|
constructor(provider, label) { super(`${getProviderLabel(provider)} subscription "${label}" ${REFRESH_BUSY_PHRASE}; treating it as cooling for this call`); this.name = 'RefreshBusyError'; }
|
|
36
38
|
}
|
|
@@ -84,6 +86,7 @@ export async function readAllSubscriptionPools() {
|
|
|
84
86
|
}
|
|
85
87
|
return pools;
|
|
86
88
|
}
|
|
89
|
+
async function setLockTimeout(db) { await db.exec(`SET LOCAL lock_timeout = '${LOCK_TIMEOUT}'`); }
|
|
87
90
|
/** One account by 1-based position or label, row-locked. */
|
|
88
91
|
async function lockedAccount(db, person, provider, ref) {
|
|
89
92
|
const needle = ref.trim().toLowerCase();
|
|
@@ -94,7 +97,6 @@ async function lockedAccount(db, person, provider, ref) {
|
|
|
94
97
|
return undefined;
|
|
95
98
|
return toPublic(person, provider, r, (await loadCooldowns(db, person, provider)).get(r.id));
|
|
96
99
|
}
|
|
97
|
-
async function setLockTimeout(db) { await db.exec(`SET LOCAL lock_timeout = '${LOCK_TIMEOUT}'`); }
|
|
98
100
|
/** Run one pool mutation in a transaction holding the provider's advisory lock and a row lock on every account, so no two processes mutate one pool at once. */
|
|
99
101
|
async function locked(provider, run) {
|
|
100
102
|
const person = await personIdAsync();
|
|
@@ -111,12 +113,12 @@ export async function insertAccount(db, person, provider, row, entry) {
|
|
|
111
113
|
await db.prepare('INSERT INTO model_accounts(person,provider_id,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) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
|
|
112
114
|
.run(person, provider, row.id, row.label, row.labelKey, row.position, row.lastAttemptAt, row.lastRateLimitedAt, row.rateLimitedUntil, row.authFailure ?? null, refresh.sealed, access.sealed, entry.expires, entry.accountId ?? null, entry.clientId ?? null, refresh.keyId);
|
|
113
115
|
}
|
|
114
|
-
/** Replace the account's whole token record (account id and client id included). */
|
|
115
|
-
async function setCredential(db, person, provider, id, entry) {
|
|
116
|
+
/** Replace the account's whole token record (account id and client id included) and clear any refresh claim. With `spent`, only while the stored refresh token is still that one; the answer says whether the row was written. */
|
|
117
|
+
async function setCredential(db, person, provider, id, entry, spent) {
|
|
116
118
|
const secrets = loadSecretsKey();
|
|
117
119
|
const refresh = seal(entry.refresh, secrets, aadOf(person, provider, id, 'refresh'));
|
|
118
120
|
const access = seal(entry.access, secrets, aadOf(person, provider, id, 'access'));
|
|
119
|
-
await db.prepare(
|
|
121
|
+
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;
|
|
120
122
|
}
|
|
121
123
|
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); }
|
|
122
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); }
|
|
@@ -125,8 +127,7 @@ async function deleteModelCooldowns(db, person, provider, accountId) { if (accou
|
|
|
125
127
|
else
|
|
126
128
|
await db.prepare('DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?').run(person, provider, accountId); }
|
|
127
129
|
const publicPool = async ({ db, person }, provider) => (await loadPool(db, person, provider)).map(({ entry }) => entry);
|
|
128
|
-
|
|
129
|
-
/** Stop waiting on a network exchange made while holding a row lock. */
|
|
130
|
+
/** Stop waiting on a refresh exchange after `REFRESH_EXCHANGE_TIMEOUT_MS`. */
|
|
130
131
|
function withExchangeTimeout(provider, run) { let timer; return Promise.race([run, new Promise((_, reject) => { timer = setTimeout(() => reject(new RefreshTimeoutError(provider)), REFRESH_EXCHANGE_TIMEOUT_MS); })]).finally(() => clearTimeout(timer)); }
|
|
131
132
|
export async function readSubscriptionPool(provider) { return (await readSubscriptionPoolRows(provider)).map(({ entry }) => entry); }
|
|
132
133
|
/** The pool with each account's row id: the stable handle a caller outside the process removes an account by. */
|
|
@@ -284,7 +285,7 @@ export async function markSubscriptionSuccess(provider, ref, attemptAt = Date.no
|
|
|
284
285
|
await db.prepare('DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?').run(person, provider, row.id, family);
|
|
285
286
|
});
|
|
286
287
|
}
|
|
287
|
-
/** The vendor refused this account's refresh token: flag the row so every pool reader skips it until a sign-in replaces it.
|
|
288
|
+
/** The vendor refused this account's refresh token: flag the row so every pool reader skips it until a sign-in replaces it. A 401 records it here; a refused refresh records it in `refreshAccount`, so a process waiting on that refresh finds the flag and does not spend the token again. */
|
|
288
289
|
async function recordInvalidGrant(db, person, row) { const at = Date.now(); await updateHealth(db, person, { ...row, authFailure: 'invalid_grant', lastAttemptAt: Math.max(row.lastAttemptAt, at), rateLimitedUntil: Math.max(row.rateLimitedUntil, at + INVALID_REFRESH_TOKEN_BACKOFF_MS) }); }
|
|
289
290
|
/** What a vendor 429 asks of the account that received it, parsed once from its headers. The wait is `current` when the caller already holds one, else the vendor's Retry-After, else `defaultMs`; with no Retry-After, a rejected window's reset lengthens it to the window. `vendorReset` is the reset the vendor itself named (Retry-After or the window), never a default. */
|
|
290
291
|
export function vendorRateLimit(headers, modelId, current, defaultMs = 15_000, now = Date.now()) {
|
|
@@ -297,85 +298,73 @@ export function vendorRateLimit(headers, modelId, current, defaultMs = 15_000, n
|
|
|
297
298
|
}
|
|
298
299
|
/** The vendor refused this account's access token on a request (401): flag the row as a refused refresh does, so every pool reader skips it until a sign-in replaces it. */
|
|
299
300
|
export async function markSubscriptionAuthFailure(provider, ref) { return healthWrite(provider, ref, (db, person, row) => recordInvalidGrant(db, person, row)); }
|
|
300
|
-
/** Refresh one account
|
|
301
|
-
|
|
301
|
+
/** Refresh one account (by label) with no connection held across the vendor call. One statement claims the expired, unflagged, unclaimed row; the claimer calls `exchange` and writes the new tokens only while the stored refresh token is still the one it spent. A caller that did not get the claim re-reads every 500 ms until the tokens are fresh, the account is flagged, or `REFRESH_CLAIM_MS` passes, then throws `RefreshBusyError`. With `onlyExpired` false the row is claimed whatever its expiry and `exchange` (pi's `fn`) decides; such a caller waits only for the claim. `exchange` returning undefined leaves the tokens unchanged. */
|
|
302
|
+
async function refreshAccount(provider, label, onlyExpired, exchange) {
|
|
302
303
|
const person = await personIdAsync();
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
throw new Error(`${getProviderLabel(provider)} subscription "${label}" no longer exists`);
|
|
310
|
-
if (current.entry.expires > Date.now())
|
|
311
|
-
return { entry: current.entry };
|
|
312
|
-
if (current.row.authFailure)
|
|
313
|
-
throw new Error(`${getProviderLabel(provider)} subscription "${current.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);
|
|
314
|
-
let next;
|
|
304
|
+
const db = await openDb();
|
|
305
|
+
const deadline = Date.now() + REFRESH_CLAIM_MS;
|
|
306
|
+
for (;;) {
|
|
307
|
+
const now = Date.now();
|
|
308
|
+
const claimed = await db.prepare(`UPDATE model_accounts SET refresh_claimed_until=? WHERE person=? AND provider_id=? AND label_key=? AND expires<=? AND auth_failure IS NULL AND refresh_claimed_until<=? RETURNING ${COLUMNS}`).get(now + REFRESH_CLAIM_MS, person, provider, key(label), onlyExpired ? now : Number.MAX_SAFE_INTEGER, now);
|
|
309
|
+
if (claimed) {
|
|
315
310
|
try {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
catch (error) {
|
|
319
|
-
if (!isInvalidRefreshTokenError(error))
|
|
320
|
-
throw error;
|
|
321
|
-
await recordInvalidGrant(db, person, current.row);
|
|
322
|
-
return { refused: error };
|
|
323
|
-
}
|
|
324
|
-
const tokens = withClientId(assertTokens(provider, current.entry.label, next), next.clientId ?? current.entry.clientId);
|
|
325
|
-
await setCredential(db, person, provider, current.row.id, stored({ ...current.entry, ...tokens }));
|
|
326
|
-
return { entry: { ...current.entry, ...tokens } };
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
catch (error) {
|
|
330
|
-
if (lockWaitExpired(error))
|
|
331
|
-
throw new RefreshBusyError(provider, label);
|
|
332
|
-
throw error;
|
|
333
|
-
}
|
|
334
|
-
if ('refused' in outcome)
|
|
335
|
-
throw outcome.refused;
|
|
336
|
-
return outcome.entry;
|
|
337
|
-
}
|
|
338
|
-
export async function modifyElectedSubscription(provider, elect, apply) {
|
|
339
|
-
const person = await personIdAsync();
|
|
340
|
-
let outcome;
|
|
341
|
-
try {
|
|
342
|
-
outcome = await withCanvasWrite(async (db) => {
|
|
343
|
-
await setLockTimeout(db);
|
|
344
|
-
const rows = await loadPool(db, person, provider, true);
|
|
345
|
-
const attempted = new Set();
|
|
346
|
-
let lastError;
|
|
347
|
-
while (attempted.size < rows.length) {
|
|
348
|
-
const chosen = elect(rows.filter(({ entry }) => !attempted.has(entry.label)).map(({ entry }) => entry));
|
|
349
|
-
if (!chosen)
|
|
350
|
-
break;
|
|
351
|
-
const current = rows.find(({ entry }) => entry.label === chosen.label);
|
|
352
|
-
attempted.add(current.entry.label);
|
|
311
|
+
const current = toPublic(person, provider, claimed);
|
|
312
|
+
let next;
|
|
353
313
|
try {
|
|
354
|
-
|
|
355
|
-
if (!next)
|
|
356
|
-
return { entry: current.entry };
|
|
357
|
-
const tokens = withClientId(assertTokens(provider, current.entry.label, next), next.clientId ?? current.entry.clientId);
|
|
358
|
-
await setCredential(db, person, provider, current.row.id, stored({ ...current.entry, ...tokens }));
|
|
359
|
-
return { entry: { ...current.entry, ...tokens } };
|
|
314
|
+
next = await withExchangeTimeout(provider, exchange(current.entry));
|
|
360
315
|
}
|
|
361
316
|
catch (error) {
|
|
362
|
-
if (
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
await recordInvalidGrant(db, person, current.row);
|
|
317
|
+
if (isInvalidRefreshTokenError(error))
|
|
318
|
+
await db.prepare('UPDATE model_accounts SET auth_failure=?,last_attempt_at=GREATEST(last_attempt_at,?),rate_limited_until=GREATEST(rate_limited_until,?) WHERE person=? AND provider_id=? AND id=? AND refresh_sealed=?').run('invalid_grant', Date.now(), Date.now() + INVALID_REFRESH_TOKEN_BACKOFF_MS, person, provider, claimed.id, claimed.refresh_sealed);
|
|
319
|
+
throw error;
|
|
366
320
|
}
|
|
321
|
+
if (!next)
|
|
322
|
+
return current.entry;
|
|
323
|
+
const tokens = withClientId(assertTokens(provider, current.entry.label, next), next.clientId ?? current.entry.clientId);
|
|
324
|
+
if (await setCredential(db, person, provider, claimed.id, stored({ ...current.entry, ...tokens }), claimed.refresh_sealed))
|
|
325
|
+
return { ...current.entry, ...tokens };
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
await db.prepare('UPDATE model_accounts SET refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?').run(person, provider, claimed.id).catch(() => undefined);
|
|
367
330
|
}
|
|
368
|
-
|
|
369
|
-
});
|
|
331
|
+
}
|
|
332
|
+
const current = (await loadPool(db, person, provider)).find(({ entry }) => key(entry.label) === key(label));
|
|
333
|
+
if (!current)
|
|
334
|
+
throw new Error(`${getProviderLabel(provider)} subscription "${label}" no longer exists`);
|
|
335
|
+
if (current.row.authFailure)
|
|
336
|
+
throw new Error(`${getProviderLabel(provider)} subscription "${current.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);
|
|
337
|
+
if (onlyExpired && current.entry.expires > now)
|
|
338
|
+
return current.entry;
|
|
339
|
+
if (Date.now() >= deadline)
|
|
340
|
+
throw new RefreshBusyError(provider, current.entry.label);
|
|
341
|
+
await sleep(500);
|
|
370
342
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
343
|
+
}
|
|
344
|
+
export async function refreshSubscriptionCredential(provider, label, exchange) {
|
|
345
|
+
return refreshAccount(provider, label, true, (current) => exchange(current.refresh, current.clientId));
|
|
346
|
+
}
|
|
347
|
+
/** Elect an account and refresh it with `apply`; an account whose refresh token the vendor refuses is flagged and the next elected account is tried. */
|
|
348
|
+
export async function modifyElectedSubscription(provider, elect, apply) {
|
|
349
|
+
const attempted = new Set();
|
|
350
|
+
let lastError;
|
|
351
|
+
for (;;) {
|
|
352
|
+
const chosen = elect((await readSubscriptionPool(provider)).filter(({ label }) => !attempted.has(label)));
|
|
353
|
+
if (!chosen) {
|
|
354
|
+
if (lastError)
|
|
355
|
+
throw lastError;
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
attempted.add(chosen.label);
|
|
359
|
+
try {
|
|
360
|
+
return await refreshAccount(provider, chosen.label, false, apply);
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (!isInvalidRefreshTokenError(error))
|
|
364
|
+
throw error;
|
|
365
|
+
lastError = error;
|
|
366
|
+
}
|
|
375
367
|
}
|
|
376
|
-
if ('refused' in outcome)
|
|
377
|
-
throw outcome.refused;
|
|
378
|
-
return outcome.entry;
|
|
379
368
|
}
|
|
380
369
|
export async function enrichManagedLoginIdentity(provider, value) { const supplied = value.accountId?.trim(); const suppliedEmail = value.email?.trim(); if (provider !== ANTHROPIC_PROVIDER_ID)
|
|
381
370
|
return { ...(supplied ? { accountId: supplied } : {}), ...(suppliedEmail ? { email: suppliedEmail } : {}) }; try {
|
|
@@ -351,7 +351,7 @@ async function handleCycleStart(ctx) {
|
|
|
351
351
|
// A node that has never recorded a session is provisional the same way: binding now would make a boot that dies before
|
|
352
352
|
// session_start look like a resumable session (retried, then a crash loop) instead of the boot failure it is.
|
|
353
353
|
const markerPending = reviewId !== undefined && !request.reviewBoundaryIds.includes(reviewId);
|
|
354
|
-
const bindPending = markerPending || node.cycle_pending === true || node.
|
|
354
|
+
const bindPending = markerPending || node.cycle_pending === true || node.pi_session_id == null;
|
|
355
355
|
if (bindPending) {
|
|
356
356
|
await requireCurrentExecution(nodeId, request.executionId);
|
|
357
357
|
}
|
|
@@ -382,9 +382,9 @@ async function residentBlaxelCanIdle(nodeId, viewer) {
|
|
|
382
382
|
&& !await isHeldAwake(nodeId, viewer)
|
|
383
383
|
&& (await runningJobs(await openDb(), nodeId)).length === 0;
|
|
384
384
|
}
|
|
385
|
-
/** A yield's settle: a broker that can start the next cycle itself is told to ask for it
|
|
386
|
-
function refreshDirective(request
|
|
387
|
-
return request.inPlaceCycle
|
|
385
|
+
/** A yield's settle: a broker that can start the next cycle itself is told to ask for it; any other exits and is relaunched. */
|
|
386
|
+
function refreshDirective(request) {
|
|
387
|
+
return request.inPlaceCycle === true ? { action: 'new_cycle' } : { action: 'shutdown' };
|
|
388
388
|
}
|
|
389
389
|
async function settleBroker(nodeId, request, viewer) {
|
|
390
390
|
const node = await getNode(nodeId);
|
|
@@ -418,7 +418,7 @@ async function settleBroker(nodeId, request, viewer) {
|
|
|
418
418
|
if (request.stopReason !== 'stop' && request.stopReason !== 'length') {
|
|
419
419
|
await clearFault(nodeId, { link: 'daemon→node' });
|
|
420
420
|
if (node.intent === 'refresh')
|
|
421
|
-
return { directive: refreshDirective(request
|
|
421
|
+
return { directive: refreshDirective(request), closePane: false };
|
|
422
422
|
// The broker reports a recorded fatal provider fault with no retry or fallback armed: nothing is left to run, so a resident
|
|
423
423
|
// Blaxel broker goes idle like any settled one, instead of holding its awake sandbox until the unattended park clock tears it
|
|
424
424
|
// down. A pending structured-output request keeps it awake as before.
|
|
@@ -437,7 +437,7 @@ async function settleBroker(nodeId, request, viewer) {
|
|
|
437
437
|
}
|
|
438
438
|
if (node.intent === 'refresh') {
|
|
439
439
|
await clearFault(nodeId);
|
|
440
|
-
return { directive: refreshDirective(request
|
|
440
|
+
return { directive: refreshDirective(request), closePane: false };
|
|
441
441
|
}
|
|
442
442
|
const decision = await evaluateStop(nodeId, signals);
|
|
443
443
|
await clearFault(nodeId);
|
|
@@ -482,10 +482,9 @@ async function handleCycle(ctx) {
|
|
|
482
482
|
}
|
|
483
483
|
async function startCycleRecord(nodeId, meta, executionId, nextEnv) {
|
|
484
484
|
// What a cycling relaunch does (revive.ts launchRevive), minus the process: count the cycle, drain the bearings into the kickoff,
|
|
485
|
-
// reset the ledger
|
|
486
|
-
//
|
|
487
|
-
//
|
|
488
|
-
// last: a failure before then leaves nothing for the relaunch to double count.
|
|
485
|
+
// reset the ledger and run the node:start hooks. The last write counts the cycle, sets cycle_pending and ends the yield intent, so a
|
|
486
|
+
// second settle cannot start another cycle; until session_start confirms it, cycle_pending alone makes a failed rebuild relaunch
|
|
487
|
+
// as a cycle with the yield note and kickoff mail intact. A failure before that write leaves nothing for the relaunch to double count.
|
|
489
488
|
meta.cycles = (meta.cycles ?? 0) + 1;
|
|
490
489
|
// Mail the old session claimed but pi never dequeued was never seen by the model: free it so the kickoff carries it, and the old
|
|
491
490
|
// watcher's shutdown receipts (fenced by the claim's attempt count) cannot acknowledge it.
|
|
@@ -497,7 +496,7 @@ async function startCycleRecord(nodeId, meta, executionId, nextEnv) {
|
|
|
497
496
|
await consumeDeadlineOnWake(nodeId);
|
|
498
497
|
await clearFault(nodeId, { preserveEpisode: true });
|
|
499
498
|
await recordLaunch(nodeId, new Date().toISOString());
|
|
500
|
-
await
|
|
499
|
+
await (await openDb()).prepare('UPDATE nodes SET cycles = ?, cycle_pending = 1, intent = NULL WHERE node_id = ?').run(meta.cycles, nodeId);
|
|
501
500
|
const env = {};
|
|
502
501
|
for (const name of CYCLE_APPLIED_ENV)
|
|
503
502
|
if (nextEnv[name] !== undefined)
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// `POST /v1/environments/:environment_id/git-credential` — a GitHub token limited to the environment's recipe repositories.
|
|
2
2
|
// The control plane asks the GitHub app's internal route with its service credential; GitHub enforces the restriction.
|
|
3
3
|
import { ApiError } from '../../../api/errors.js';
|
|
4
|
+
import { openDb } from '../../../core/canvas/db.js';
|
|
4
5
|
import { getNode } from '../../../core/canvas/canvas.js';
|
|
5
6
|
import { environmentOfNode, recipeOf } from '../environment-of.js';
|
|
6
7
|
import { invalidRequest, objectBody, optionalString, requiredString } from './validate.js';
|
|
7
|
-
function requiredEnv(name) {
|
|
8
|
+
export function requiredEnv(name) {
|
|
8
9
|
const value = process.env[name];
|
|
9
10
|
if (value === undefined || value === '')
|
|
10
11
|
throw new ApiError(500, 'github_service_unconfigured', `${name} is not set on this control plane`);
|
|
@@ -31,15 +32,16 @@ async function handleGitCredential(ctx) {
|
|
|
31
32
|
const repositories = (await recipeOf(environmentId))?.repositories.map((r) => r.github_full_name) ?? [];
|
|
32
33
|
if (repositories.length === 0)
|
|
33
34
|
throw new ApiError(409, 'no_recipe_repositories', `environment ${environmentId} has no recipe repositories`);
|
|
34
|
-
const
|
|
35
|
+
const allow = await (await openDb()).prepare('SELECT allow_pull_request_write FROM environments WHERE object = ?').get(environmentId);
|
|
36
|
+
const minted = await mintInstallationToken(principal.sub, repositories, allow?.allow_pull_request_write === true);
|
|
35
37
|
return { status: 200, body: { username: 'x-access-token', password: minted.token, expiry: minted.expires_at } };
|
|
36
38
|
}
|
|
37
|
-
/** The GitHub app's internal route: a token limited to `repositories` for the person, and the commit author for their GitHub link (null when unlinked). */
|
|
38
|
-
export async function mintInstallationToken(sub, repositories) {
|
|
39
|
+
/** The GitHub app's internal route: a token limited to `repositories` for the person (with pull_requests write too when `allowPullRequestWrite`), and the commit author for their GitHub link (null when unlinked). */
|
|
40
|
+
export async function mintInstallationToken(sub, repositories, allowPullRequestWrite = false) {
|
|
39
41
|
const response = await fetch(`${requiredEnv('GITHUB_SERVICE_URL').replace(/\/$/, '')}/internal/installation-token`, {
|
|
40
42
|
method: 'POST',
|
|
41
43
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${requiredEnv('CROUTER_SERVICE_TOKEN')}` },
|
|
42
|
-
body: JSON.stringify({ sub, repositories }),
|
|
44
|
+
body: JSON.stringify({ sub, repositories, allow_pull_request_write: allowPullRequestWrite }),
|
|
43
45
|
});
|
|
44
46
|
const text = await response.text();
|
|
45
47
|
const parsed = text === '' ? {} : JSON.parse(text);
|
|
@@ -208,6 +208,7 @@ export const OPERATIONS = [
|
|
|
208
208
|
{ name: 'execution.import-unpacked', method: 'POST', path: '/v1/executions/:execution_id/import-unpacked', classes: ['broker'], resource: 'none' },
|
|
209
209
|
{ name: 'execution.start', method: 'GET', path: '/v1/executions/:execution_id/start', classes: ['broker'], resource: 'none' },
|
|
210
210
|
{ name: 'environment.git-credential', method: 'POST', path: '/v1/environments/:environment_id/git-credential', classes: ['broker'], resource: 'none' },
|
|
211
|
+
{ name: 'feedback.file', method: 'POST', path: '/v1/feedback', classes: ['broker'], resource: 'none' },
|
|
211
212
|
{ name: 'node-outcomes.get.119', method: 'GET', path: '/v1/nodes/:id/outcome', classes: ['person', 'broker', 'cron'], resource: 'node-read' },
|
|
212
213
|
{ name: 'node-outcomes.put.120', method: 'PUT', path: '/v1/nodes/:id/outcome-delivery', classes: ['person', 'broker'], resource: 'node-write' },
|
|
213
214
|
{ name: 'node-outcomes.get.121', method: 'GET', path: '/v1/nodes/:id/outcome-delivery', classes: ['person', 'broker', 'cron'], resource: 'node-read' },
|
|
@@ -236,7 +236,7 @@ export class HeldLink extends EventEmitter {
|
|
|
236
236
|
const turn = await readLiveTurn(node);
|
|
237
237
|
const since = turn?.busy === true && turn.progressAt !== null ? Date.parse(turn.progressAt) : Number.NaN;
|
|
238
238
|
const launched = Date.parse(row.launched_at ?? '');
|
|
239
|
-
turns[execution] = { since: Number.isFinite(since) && Number.isFinite(launched) && since >= launched ? since : null, refresh: row.intent === 'refresh', jobs: (await runningJobs(await openDb(), node)).length > 0 };
|
|
239
|
+
turns[execution] = { since: Number.isFinite(since) && Number.isFinite(launched) && since >= launched ? since : null, refresh: row.intent === 'refresh' || row.cycle_pending === true, jobs: (await runningJobs(await openDb(), node)).length > 0 };
|
|
240
240
|
}
|
|
241
241
|
return turns;
|
|
242
242
|
}
|
|
@@ -475,7 +475,7 @@ export class BrokerSupervisionReconciler {
|
|
|
475
475
|
/** A refresh that never reached its replacement: the same stall clock as a local broker, enacted through the runner. */
|
|
476
476
|
async handleRemoteYieldStall(row, execution, now) {
|
|
477
477
|
const id = row.node_id;
|
|
478
|
-
if (row.intent !== 'refresh' || await busySinceForIncarnation(row) !== null) {
|
|
478
|
+
if ((row.intent !== 'refresh' && row.cycle_pending !== true) || await busySinceForIncarnation(row) !== null) {
|
|
479
479
|
await clearSupervisionMark(id, 'stall_noticed_at');
|
|
480
480
|
return;
|
|
481
481
|
}
|
|
@@ -484,7 +484,7 @@ export class BrokerSupervisionReconciler {
|
|
|
484
484
|
await writeSupervisionMark(id, 'stall_noticed_at', now);
|
|
485
485
|
return;
|
|
486
486
|
}
|
|
487
|
-
if (yieldStallVerdict(true,
|
|
487
|
+
if (yieldStallVerdict(true, false, now - stalledSince) !== 'kill')
|
|
488
488
|
return;
|
|
489
489
|
if ((await liveExecutionForNode(id))?.executionId !== execution.executionId)
|
|
490
490
|
return;
|
|
@@ -524,7 +524,7 @@ export class BrokerSupervisionReconciler {
|
|
|
524
524
|
async handleYieldStall(row, entry, fleet, now) {
|
|
525
525
|
const id = row.node_id;
|
|
526
526
|
const incarnation = incarnationOf(entry.pid, row.pi_pid_identity);
|
|
527
|
-
if (row.intent !== 'refresh' || await busySinceForIncarnation(row) !== null || incarnation === null) {
|
|
527
|
+
if ((row.intent !== 'refresh' && row.cycle_pending !== true) || await busySinceForIncarnation(row) !== null || incarnation === null) {
|
|
528
528
|
await clearSupervisionMark(id, 'stall_noticed_at');
|
|
529
529
|
if (incarnation !== null)
|
|
530
530
|
this.yieldTermedAt.delete(incarnation);
|
|
@@ -536,7 +536,7 @@ export class BrokerSupervisionReconciler {
|
|
|
536
536
|
return;
|
|
537
537
|
}
|
|
538
538
|
const state = { since: stalledSince, termedAt: this.yieldTermedAt.get(incarnation) };
|
|
539
|
-
if (yieldStallVerdict(true,
|
|
539
|
+
if (yieldStallVerdict(true, false, now - state.since) !== 'kill')
|
|
540
540
|
return;
|
|
541
541
|
const current = await getNode(id);
|
|
542
542
|
if (fleet.get(id) !== entry || current?.pi_pid !== entry.pid || current.pi_pid_identity !== row.pi_pid_identity || recordedPidLiveness(entry.pid, row.pi_pid_identity) !== 'alive')
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.715",
|
|
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.715",
|
|
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.715",
|
|
31
|
+
"@north-light/identity": "0.3.715"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|