@north-light/cli 0.3.713 → 0.3.714

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/clients/attach/input/controller.d.ts +2 -0
  2. package/dist/clients/attach/input/controller.js +1 -1
  3. package/dist/clients/attach/input/local-files.d.ts +3 -1
  4. package/dist/clients/attach/input/local-files.js +8 -3
  5. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  8. package/dist/clients/attach/session/input-wiring.js +1 -1
  9. package/dist/clients/attach/viewer.js +526 -521
  10. package/dist/commands/node/inspect.js +5 -5
  11. package/dist/core/broker-client/client.js +1 -1
  12. package/dist/core/canvas/canvas.js +1 -1
  13. package/dist/core/canvas/deliveries.js +10 -10
  14. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  15. package/dist/core/canvas/schema-version.d.ts +1 -1
  16. package/dist/core/canvas/schema-version.js +1 -1
  17. package/dist/core/canvas/types.d.ts +1 -0
  18. package/dist/core/checkout-identities.js +1 -1
  19. package/dist/core/import/load/bind.d.ts +8 -0
  20. package/dist/core/import/load/bind.js +15 -15
  21. package/dist/core/import/load/prepare.d.ts +8 -1
  22. package/dist/core/import/load/prepare.js +9 -7
  23. package/dist/core/import/load/run.js +2 -2
  24. package/dist/core/llm/run.d.ts +1 -1
  25. package/dist/core/pool-credential-store.d.ts +5 -5
  26. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  27. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  28. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  29. package/dist/core/runtime/broker-wedge.js +2 -2
  30. package/dist/core/subscription-state.d.ts +3 -3
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  33. package/dist/daemon/fleet.d.ts +1 -12
  34. package/dist/daemon/fleet.js +2 -2
  35. package/dist/daemon/machine-daemon.js +1 -1
  36. package/dist/daemon/machine-link/holder.js +1 -1
  37. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  38. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  39. package/package.json +3 -3
  40. package/packages/crouter-api/dist/clients/attach/input/controller.js +1 -1
  41. package/packages/crouter-api/dist/clients/attach/input/local-files.js +18 -2
  42. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  43. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  44. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  45. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  46. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  47. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  48. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  49. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  50. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  51. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  52. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  53. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  54. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  55. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  56. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +10 -11
  57. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  58. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  59. package/packages/crouter-api/package.json +1 -1
  60. package/packages/crouter-identity/package.json +1 -1
  61. package/packages/crouter-plugin/package.json +3 -3
  62. package/runtime.lock.json +14 -14
  63. package/scripts/install-runtime.mjs +3 -2
  64. package/scripts/self-update.mjs +5 -1
@@ -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 hold the account's row lock. */
29
+ /** Longest a refresh exchange may take. */
29
30
  export const REFRESH_EXCHANGE_TIMEOUT_MS = 10_000;
30
- /** Longest a statement waits for another process's row or provider lock before the call gives up. */
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
- const LOCK_NOT_AVAILABLE = '55P03';
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('UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?').run(refresh.sealed, access.sealed, entry.expires, entry.accountId ?? null, entry.clientId ?? null, refresh.keyId, person, provider, id);
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
- const lockWaitExpired = (error) => error?.code === LOCK_NOT_AVAILABLE;
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. Both refresh paths (pi's `modify` and the daemon's /v1/llm) record it here, in the transaction that holds the row lock, so a process waiting on the lock finds the flag and does not spend the token again. */
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's tokens under its row lock. A process that waited on the lock finds the tokens already fresh (or the account already flagged) and does not call the vendor again. */
301
- export async function refreshSubscriptionCredential(provider, label, exchange) {
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
- let outcome;
304
- try {
305
- outcome = await withCanvasWrite(async (db) => {
306
- await setLockTimeout(db);
307
- const current = await lockedAccount(db, person, provider, label);
308
- if (!current)
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
- next = await withExchangeTimeout(provider, exchange(current.entry.refresh, current.entry.clientId));
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
- const next = await withExchangeTimeout(provider, apply(current.entry));
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 (!isInvalidRefreshTokenError(error))
363
- throw error;
364
- lastError = error;
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
- return lastError ? { refused: lastError } : {};
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
- catch (error) {
372
- if (lockWaitExpired(error))
373
- throw new RefreshBusyError(provider, elect([])?.label ?? provider);
374
- throw error;
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.intent === 'refresh' || node.pi_session_id == null;
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, unless that cycle is already recorded and starting; any other exits and is relaunched. */
386
- function refreshDirective(request, node) {
387
- return request.inPlaceCycle !== true ? { action: 'shutdown' } : node.cycle_pending === true ? { action: 'stay_dormant' } : { action: 'new_cycle' };
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, node), closePane: false };
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, node), closePane: false };
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, run the node:start hooks, and clear the yield intent so no stall check mistakes this for a hung broker.
486
- // The yield intent stays until the rebuilt session's session_start confirms the cycle (handleSessionBound clears it), so a
487
- // failed rebuild ends in the relaunch path with the yield note and kickoff mail intact. The counter and cycle_pending are written
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 updateNode(nodeId, { cycles: meta.cycles, cycle_pending: true });
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)
@@ -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, row.intent, false, now - stalledSince) !== 'kill')
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, row.intent, false, now - state.since) !== 'kill')
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.713",
3
+ "version": "0.3.714",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.713",
3
+ "version": "0.3.714",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.713",
3
+ "version": "0.3.714",
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.713",
31
- "@north-light/identity": "0.3.713"
30
+ "@north-light/api": "0.3.714",
31
+ "@north-light/identity": "0.3.714"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.713",
3
+ "version": "0.3.714",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.713",
9
+ "version": "0.3.714",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.713",
32
- "@north-light/plugin": "0.3.713",
31
+ "@north-light/identity": "0.3.714",
32
+ "@north-light/plugin": "0.3.714",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.713",
11905
+ "version": "0.3.714",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.713",
11910
+ "version": "0.3.714",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.713",
11915
+ "version": "0.3.714",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.713",
11923
+ "version": "0.3.714",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.713",
11927
- "@north-light/identity": "0.3.713"
11926
+ "@north-light/api": "0.3.714",
11927
+ "@north-light/identity": "0.3.714"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.713",
11932
+ "version": "0.3.714",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.713",
11936
- "@north-light/identity": "0.3.713",
11937
- "@north-light/plugin": "0.3.713",
11935
+ "@north-light/api": "0.3.714",
11936
+ "@north-light/identity": "0.3.714",
11937
+ "@north-light/plugin": "0.3.714",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -409,7 +409,7 @@ async function acquireLock() {
409
409
  if (error?.code !== 'EEXIST') throw error;
410
410
  const owner = await readLockOwner(LOCK);
411
411
  if (owner && (await ownerIsAlive(owner))) {
412
- throw new Error(`runtime installer lock is held by a live process: pid=${owner.pid} started=${owner.startTime || 'unknown'} host=${owner.hostname || 'unknown'}; refusing to install concurrently`);
412
+ throw Object.assign(new Error(`runtime installer lock is held by a live process: pid=${owner.pid} started=${owner.startTime || 'unknown'} host=${owner.hostname || 'unknown'}; refusing to install concurrently`), { lockHeld: true });
413
413
  }
414
414
  if (!owner) {
415
415
  let stat;
@@ -666,5 +666,6 @@ async function install() {
666
666
 
667
667
  install().catch((error) => {
668
668
  process.stderr.write(`runtime installation failed: ${error.stack || error.message}\n`);
669
- process.exitCode = 1;
669
+ // 75 (EX_TEMPFAIL): another install holds the lock and nothing else is wrong, so the caller may retry soon (the machine daemon's self-update does).
670
+ process.exitCode = error?.lockHeld ? 75 : 1;
670
671
  });
@@ -22,7 +22,7 @@ if (target.migrating) process.stderr.write(`crtr: moving from ${own.name} to ${t
22
22
  function run(command, args, options) {
23
23
  const result = spawnSync(command, args, options);
24
24
  if (result.error) throw new Error(`${command} ${args.join(' ')}: ${result.error.message}`);
25
- if (result.status !== 0) throw new Error(`${command} ${args.join(' ')} failed (${result.status ?? result.signal ?? 'unknown'})`);
25
+ if (result.status !== 0) throw Object.assign(new Error(`${command} ${args.join(' ')} failed (${result.status ?? result.signal ?? 'unknown'})`), { status: result.status });
26
26
  return result;
27
27
  }
28
28
 
@@ -44,6 +44,10 @@ try {
44
44
  mkdirSync(release);
45
45
  run('tar', ['-xzf', archive, '--strip-components=1', '-C', release]);
46
46
  run(process.execPath, [join(release, 'scripts', 'install-runtime.mjs'), release], { stdio: 'inherit' });
47
+ } catch (error) {
48
+ // The installer's 75 (its lock is held by another install) is passed on as this script's exit status; every other failure exits 1.
49
+ process.stderr.write(`${error.stack || error.message}\n`);
50
+ process.exitCode = error?.status === 75 ? 75 : 1;
47
51
  } finally {
48
52
  rmSync(temporary, { recursive: true, force: true });
49
53
  }