@north-light/api 0.3.763 → 0.3.765

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.
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.81";
2
+ export declare const CONTRACT_LEVEL = "1.82";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.81';
15
+ export const CONTRACT_LEVEL = '1.82';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -93,7 +93,8 @@ export declare function hasRunningRemoteExecution(nodeId: string): Promise<boole
93
93
  export declare function hasLaunchingExecution(nodeId: string, epoch: string): Promise<boolean>;
94
94
  /** Node ids with a live process-runner execution begun by this daemon epoch. */
95
95
  export declare function liveProcessExecutionNodeIds(epoch: string): Promise<Set<string>>;
96
- /** Every node with a live (not exited) execution row, whichever process or runner holds it. */
96
+ /** Every node with a live (not exited) process-runner execution row, whichever daemon process holds it. A Blaxel sandbox or a
97
+ * machine's broker uses no capacity on this host, so the broker cap does not count it. */
97
98
  export declare function liveExecutionNodeIds(): Promise<Set<string>>;
98
99
  export declare const PROFILE_PAUSE_STOP_REASON = "profile_pause";
99
100
  /** Marks the node's live execution as stopped by a profile pause, so the exit it causes is not read as a crash. */
@@ -72,7 +72,7 @@ export async function beginExecution(nodeId, input) {
72
72
  throw new Error(`cannot begin execution: missing node ${nodeId}`);
73
73
  if (input.cap !== undefined) {
74
74
  await db.prepare(`SELECT pg_advisory_xact_lock(${EXECUTION_CAP_LOCK_KEY})`).get();
75
- const live = Number((await db.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(nodeId)).n);
75
+ const live = Number((await db.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND runner = 'process' AND node_id != ?").get(nodeId)).n);
76
76
  if (live >= input.cap)
77
77
  throw new ExecutionCapReached(input.cap, live);
78
78
  }
@@ -216,9 +216,10 @@ export async function liveProcessExecutionNodeIds(epoch) {
216
216
  const rows = await (await openDb()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(epoch);
217
217
  return new Set(rows.map((row) => row.node_id));
218
218
  }
219
- /** Every node with a live (not exited) execution row, whichever process or runner holds it. */
219
+ /** Every node with a live (not exited) process-runner execution row, whichever daemon process holds it. A Blaxel sandbox or a
220
+ * machine's broker uses no capacity on this host, so the broker cap does not count it. */
220
221
  export async function liveExecutionNodeIds() {
221
- const rows = await (await openDb()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();
222
+ const rows = await (await openDb()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process'").all();
222
223
  return new Set(rows.map((row) => row.node_id));
223
224
  }
224
225
  export const PROFILE_PAUSE_STOP_REASON = 'profile_pause';
@@ -70,7 +70,9 @@ async function compare(stored) {
70
70
  // The directory may still send the older `'user'`/`'app'` payer; the mirror stores it as a principal.
71
71
  const liveSide = { ...live, payer: principalPayer(live['payer'], stored.sub, stored.grantee) };
72
72
  const storedSide = { ...stored, resolved_scopes: compactLike(stored.resolved_scopes, live['resolved_scopes']) };
73
- const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(storedSide[key] ?? null));
73
+ const fields = COMPARED.filter((key) => key === 'resolved_scopes'
74
+ ? scopeSet(liveSide[key]) !== scopeSet(storedSide[key])
75
+ : canonicalJson(liveSide[key] ?? null) !== canonicalJson(storedSide[key] ?? null));
74
76
  if (fields.length === 0) {
75
77
  shadowCounts.agree++;
76
78
  return;
@@ -78,8 +80,16 @@ async function compare(stored) {
78
80
  shadowCounts.disagree++;
79
81
  warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, rev: stored.rev, fields })}`);
80
82
  }
83
+ // A resolved set is a set: the expanded and compact forms list scopes in different orders, so they compare as sorted `scope|mode` lists.
84
+ function scopeSet(value) {
85
+ if (!Array.isArray(value))
86
+ return canonicalJson(value ?? null);
87
+ return JSON.stringify([...new Set(value.map((entry) => `${entry.scope}|${entry.mode}`))].sort());
88
+ }
81
89
  // The live answer may hold `<provider>:*` where the stored column still lists each group (phase 4). Fold the stored groups of each such
82
- // provider into its wildcard, keeping the first group's mode and position, so the two forms compare equal when they name the same providers. A group the live answer still names (an `own` group) stays.
90
+ // provider into its wildcard so the two forms compare equal when they name the same providers. A group the live answer still names
91
+ // (an `own` group, or the app's own scopes) stays, and still counts as that provider's group: when every stored group of a provider is
92
+ // also named exactly, the expanded form deduplicated the held groups into those names, and the wildcard stands for them.
83
93
  function compactLike(stored, live) {
84
94
  if (!Array.isArray(live))
85
95
  return stored;
@@ -91,15 +101,15 @@ function compactLike(stored, live) {
91
101
  if (wild.size === 0)
92
102
  return stored;
93
103
  const seen = new Set();
94
- return stored.flatMap((entry) => {
104
+ const folded = stored.flatMap((entry) => {
95
105
  const provider = entry.scope.slice(0, entry.scope.indexOf(':'));
96
- if (provider === 'crtr' || !wild.has(provider) || named.has(entry.scope))
106
+ if (provider === 'crtr' || !wild.has(provider))
97
107
  return [entry];
98
- if (seen.has(provider))
99
- return [];
108
+ const wildcard = seen.has(provider) ? [] : [{ ...entry, scope: `${provider}:*` }];
100
109
  seen.add(provider);
101
- return [{ ...entry, scope: `${provider}:*` }];
110
+ return named.has(entry.scope) ? [entry, ...wildcard] : wildcard;
102
111
  });
112
+ return folded;
103
113
  }
104
114
  let summaryTimer;
105
115
  let reported = { agree: 0, disagree: 0, lagging: 0, error: 0 };
@@ -167,10 +167,13 @@ async function ownerView(db, src, reposFn) {
167
167
  const owner = src.owner == null ? null : await getById(db, src.owner);
168
168
  if (src.deleted_at || src.home_machine !== null || !owner || owner.deleted_at)
169
169
  return null;
170
- return owner.type === 'node'
171
- ? await readerForNode(db, owner.id, reposFn ?? (async () => []), liveLookups(db), true)
172
- : await readerForObject(db, src, reposFn).catch((error) => { if (error instanceof NoOwningAppError)
173
- return null; throw error; });
170
+ if (owner.type === 'node')
171
+ return await readerForNode(db, owner.id, reposFn ?? (async () => []), liveLookups(db), true);
172
+ // A person's document resolves as that person: an object reader under a person owner holds no scopes, so it would see none of the person's documents.
173
+ if (owner.type === 'person')
174
+ return { class: 'person', person: owner };
175
+ return await readerForObject(db, src, reposFn).catch((error) => { if (error instanceof NoOwningAppError)
176
+ return null; throw error; });
174
177
  }
175
178
  /** `target` has just come into existence or gained a name. Every live document whose current revision holds an
176
179
  * unresolved link that could name it re-resolves that link in its OWNER's view (not the caller's); the link gains its
@@ -240,6 +240,9 @@ async function decideReviveAsCaller(nodeId, opts, wakeParked) {
240
240
  // owns the node while launch is in flight; a second contender must not cross
241
241
  // that awaited gap and start a second broker on the same session file.
242
242
  const fleet = boundFleet();
243
+ // A node that runs in a Blaxel sandbox or on a remote machine uses no capacity on this host: it takes no broker slot and no
244
+ // memory admission. Read here, before the guard below; `beginExecution` refuses a second live execution for the node.
245
+ const remote = await blaxelEnvironmentOf(meta.profile_id ?? null) !== null || await remoteMachineEnvironmentOf(meta.profile_id ?? null) !== null;
243
246
  // A terminal node's token is minted from the terminal grant, and a joined runtime holds none until its first directory snapshot
244
247
  // commits. Read here, before the guard below, because nothing may await between that guard and the slot reservation.
245
248
  const awaitingGrants = meta.grantee === 'app:terminal' && await grantSnapshotMissing();
@@ -286,9 +289,9 @@ async function decideReviveAsCaller(nodeId, opts, wakeParked) {
286
289
  const drained = await isDrained();
287
290
  if (drained && opts.capacity === 'refuse')
288
291
  throw new Error(`the daemon is drained for an import; ${nodeId} cannot start until it ends`);
289
- const slot = !drained && await fleet.reserveSlot(nodeId);
292
+ const slot = !drained && (remote || await fleet.reserveSlot(nodeId));
290
293
  let memory = null;
291
- if (slot) {
294
+ if (slot && !remote) {
292
295
  try {
293
296
  memory = await admitBrokerMemory(nodeId);
294
297
  }
@@ -471,7 +474,7 @@ async function launchRevive(nodeId, meta, opts) {
471
474
  const runner = blaxelEnvironment !== null ? runnerForEnvironment('blaxel') : remoteMachine ? runnerForEnvironment('machine') : processRunner;
472
475
  let executionId;
473
476
  try {
474
- executionId = await beginExecution(nodeId, { daemonEpoch: boundFleet().epoch(), cap: automaticReviveCap,
477
+ executionId = await beginExecution(nodeId, { daemonEpoch: boundFleet().epoch(), ...(remote ? {} : { cap: automaticReviveCap }),
475
478
  ...(blaxelEnvironment !== null ? { runner: 'blaxel', release: acceptedRelease() } : remoteMachine ? { runner: 'machine', release: acceptedRelease() } : {}) });
476
479
  }
477
480
  catch (error) {
@@ -146,6 +146,11 @@ async function crashAndTearDown(nodeId, error) {
146
146
  * and does NOT resolve a uuid, so a bare id must be resolved here or the fork
147
147
  * throws at boot. Session files are `<sessions>/<project>/<ts>_<id>.jsonl`. */
148
148
  async function resolveSessionUuid(uuid) {
149
+ // A full id is one header read. The prefix scan below reads the header of every conversation the store holds, which on a
150
+ // cloud role is every person's, and outlasts the proxy's request timeout.
151
+ const exactPath = await conversationStore().header(uuid).then((h) => h.path, () => null);
152
+ if (exactPath !== null)
153
+ return exactPath;
149
154
  const matches = (await conversationStore().list()).map(({ conversation_id, path }) => ({ id: conversation_id, path }));
150
155
  const exact = matches.filter((m) => m.id === uuid);
151
156
  const hit = exact.length > 0 ? exact : matches.filter((m) => m.id.startsWith(uuid));
@@ -287,22 +292,20 @@ async function recordStartCallTimings(callId, answer) {
287
292
  * transaction renders the start data, mints the token and queues the `start` call; the call is awaited after that commit. The bundle's network work
288
293
  * (GitHub token, blob store) runs before that transaction opens. 'failed': nothing started, the caller freezes the node for the lifecycle tick to wake.
289
294
  * 'uncertain': the call was sent and its answer lost, so the Mac may have a broker: the execution stays launching and the node stays active, and the
290
- * tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained or at its broker cap, so nothing was begun. */
295
+ * tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained, so nothing was begun. A machine run takes no broker slot on this host. */
291
296
  async function startOnMachine(meta, environmentId, inv) {
292
297
  const setupStart = performance.now();
293
298
  // Loaded here: the handlers import the runtime that imports this module.
294
299
  const { buildStartBundle } = await import('../../daemon/api/handlers/execution-start.js');
295
300
  const { renderCarriedStart } = await import('../../daemon/api/handlers/broker-ops.js');
296
- // The checks reviveNode makes before it begins an execution: a drained daemon starts nothing, and the execution cap is enforced by the insert.
301
+ // The check reviveNode makes before it begins an execution: a drained daemon starts nothing.
297
302
  if (await isDrained())
298
303
  return 'full';
299
304
  let executionId;
300
305
  try {
301
- executionId = await beginExecution(meta.node_id, { daemonEpoch: boundFleet().epoch(), cap: brokerThresholdsForDaemon().automaticReviveCap, runner: 'machine', release: acceptedRelease() });
306
+ executionId = await beginExecution(meta.node_id, { daemonEpoch: boundFleet().epoch(), runner: 'machine', release: acceptedRelease() });
302
307
  }
303
308
  catch (error) {
304
- if (error instanceof ExecutionCapReached)
305
- return 'full';
306
309
  emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
307
310
  return 'failed';
308
311
  }
@@ -594,9 +597,7 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
594
597
  // launch, so the release below is a no-op then and a give-back on any path
595
598
  // that never registered a handle.
596
599
  const fleet = boundFleet();
597
- // A node whose profile points at a Blaxel environment, or on a cloud role at a remote machine, is never launched here: it is born
598
- // dormant with its goal kept, and the node-lifecycle lane wakes it through `reviveNode`, the one launch path that chooses the
599
- // Blaxel or machine runner and runs the bill check.
600
+ // A node whose profile points at a Blaxel environment, or on a cloud role at a remote machine, is never launched on this host.
600
601
  if (await remoteEnvironmentOf(meta.profile_id ?? null) !== null) {
601
602
  const frozenAt = new Date().toISOString();
602
603
  // A create that asked to start, for a node on a machine this control plane reaches over a link: the start call carries everything the
@@ -609,9 +610,26 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
609
610
  if (started === 'started' || started === 'uncertain')
610
611
  return { node: meta, frozen: false, window: null, session: null };
611
612
  }
613
+ // Any other remote birth launches now through `reviveNode`, the one launch path that chooses the Blaxel or machine runner and
614
+ // runs the bill check; it takes no broker slot on this host. A launch that cannot start now (a pending image, a drained
615
+ // daemon, an offline machine) leaves the node frozen with its goal kept, and the node-lifecycle tick wakes it.
616
+ let launched = false;
617
+ if (machine === null)
618
+ try {
619
+ const { reviveNode } = await import('./revive.js');
620
+ launched = (await reviveNode(meta.node_id, { resume: true, capacity: 'freeze', recovery: true })).outcome !== 'frozen';
621
+ }
622
+ catch (error) {
623
+ emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
624
+ }
625
+ const current = await getNode(meta.node_id);
626
+ if (launched)
627
+ return { node: current, frozen: false, window: null, session: null };
628
+ if (current.frozen_at != null || (current.status !== 'active' && current.status !== 'idle'))
629
+ return { node: current, frozen: current.frozen_at != null, window: null, session: null };
612
630
  await setFrozen(meta.node_id, frozenAt);
613
631
  emitEvent({ level: 'info', event: 'broker.frozen', node_id: meta.node_id, fields: { reason: 'remote_environment' } });
614
- return { node: { ...meta, frozen_at: frozenAt }, frozen: true, window: null, session: null };
632
+ return { node: { ...current, frozen_at: frozenAt }, frozen: true, window: null, session: null };
615
633
  }
616
634
  // Here the broker would start on this host. On a cloud role that is the control plane's own pod, never a person's machine: a profile
617
635
  // with no environment and a directory this host does not have names a path from the person's computer, so fail with that reason.
@@ -195,10 +195,10 @@ export const OPERATIONS = [
195
195
  { name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
196
196
  { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
197
  { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
198
- { name: 'environment.create', method: 'POST', path: '/v1/environments', classes: ['app'], resource: 'profile' },
199
- { name: 'environment.list', method: 'GET', path: '/v1/environments', classes: ['app', 'person'], resource: 'profile' },
200
- { name: 'environment.patch', method: 'PATCH', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
201
- { name: 'environment.delete', method: 'DELETE', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
198
+ { name: 'environment.create', method: 'POST', path: '/v1/environments', classes: ['app'], resource: 'profile', stage: 'objects' },
199
+ { name: 'environment.list', method: 'GET', path: '/v1/environments', classes: ['app', 'person'], resource: 'profile', stage: 'objects' },
200
+ { name: 'environment.patch', method: 'PATCH', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile', stage: 'objects' },
201
+ { name: 'environment.delete', method: 'DELETE', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile', stage: 'objects' },
202
202
  { name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
203
203
  { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker', 'cron'], resource: 'profile', stage: 'chat' },
204
204
  { name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.763",
3
+ "version": "0.3.765",
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",