@north-light/api 0.3.735 → 0.3.737

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.73";
2
+ export declare const CONTRACT_LEVEL = "1.74";
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.73';
15
+ export const CONTRACT_LEVEL = '1.74';
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`. */
@@ -3,5 +3,10 @@ import { type SignInPrompt } from '../../core/directory/person-credential.js';
3
3
  export declare function showSignIn(prompt: SignInPrompt & {
4
4
  complete: string;
5
5
  }): void;
6
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
7
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
8
+ export declare function registerFreshComputer(directoryUrl: string): Promise<{
9
+ account: string;
10
+ }>;
6
11
  export declare const sysSigninLeaf: import("../../core/command.js").LeafDef;
7
12
  export declare const sysSignoutLeaf: import("../../core/command.js").LeafDef;
@@ -4,14 +4,14 @@ import { mkdirSync, openSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { defineLeaf } from '../../core/command.js';
6
6
  import { CrtrError } from '../../core/errors.js';
7
- import { signIn, signOut } from '../../core/directory/person-credential.js';
8
- import { moveRecordPath, readMachineConfig } from '../../daemon/machine-link/config.js';
9
- import { sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
7
+ import { controlPlaneUrl, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../core/directory/person-credential.js';
8
+ import { hasLocalCanvas, moveRecordPath, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
9
+ import { probeDaemonHealth, sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
10
+ import { hostname } from 'node:os';
10
11
  import { northlightUnreachable } from '../../core/directory/reach.js';
11
12
  import { envNodeId } from '../../shared/env.js';
12
13
  import { ExitCode } from '../../types.js';
13
14
  import { insideBroker } from './join.js';
14
- import { cliClient } from '../api-client.js';
15
15
  import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
16
16
  import { WAIT_FOR_PID_ENV } from './import/start.js';
17
17
  /** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
@@ -31,6 +31,10 @@ export function showSignIn(prompt) {
31
31
  * to the run's own person (404 `import_not_found` to anyone else). */
32
32
  function sameAccountOnly(machine) {
33
33
  return async (approved) => {
34
+ if (machine.runId === undefined) {
35
+ return machine.account === undefined || machine.account.id === approved.account.id ? undefined
36
+ : new CrtrError('signin_other_account', `This computer belongs to the Northlight account ${machine.account.display}. Sign in to that account.`, ExitCode.USAGE);
37
+ }
34
38
  let response;
35
39
  try {
36
40
  response = await fetch(new URL(`/v1/imports/${machine.runId}`, machine.apiUrl), { headers: { authorization: `Bearer ${approved.bearer}` }, signal: AbortSignal.timeout(30_000) });
@@ -59,6 +63,37 @@ function startDetachedMove(notify) {
59
63
  const args = [...process.execArgv, process.argv[1], 'sys', 'import', 'start', '--kind', 'machine', ...(notify === undefined ? [] : ['--notify', notify])];
60
64
  spawn(process.execPath, args, { detached: true, stdio: ['ignore', fd, fd], env }).unref();
61
65
  }
66
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
67
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
68
+ export async function registerFreshComputer(directoryUrl) {
69
+ const account = readPersonCredential() === undefined ? (await signIn(directoryUrl, showSignIn), await personAccount(directoryUrl)) : await personAccount(directoryUrl);
70
+ const apiUrl = await controlPlaneUrl(directoryUrl);
71
+ const bearer = await personBearer(directoryUrl);
72
+ const post = async (rotate) => {
73
+ try {
74
+ return await fetch(new URL(`/v1/machines${rotate ? '?rotate=1' : ''}`, apiUrl), { method: 'POST', headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json' },
75
+ body: JSON.stringify({ install_id: readOrCreateInstallId(), name: hostname().slice(0, 64) }), signal: AbortSignal.timeout(30_000) });
76
+ }
77
+ catch (error) {
78
+ throw northlightUnreachable(error, apiUrl);
79
+ }
80
+ };
81
+ let response = await post(false);
82
+ if (response.status === 409 && (await response.clone().text()).includes('credential_exists'))
83
+ response = await post(true);
84
+ const text = await response.text();
85
+ if (!response.ok)
86
+ throw new CrtrError('machine_registration_failed', `Northlight refused to register this computer (HTTP ${response.status}): ${text.slice(0, 300)}`, ExitCode.GENERAL, { next: 'Run `crtr sys signin` again.' });
87
+ const body = JSON.parse(text);
88
+ if (typeof body.credential !== 'string' || typeof body.environment_id !== 'string')
89
+ throw new CrtrError('machine_registration_failed', 'Northlight answered without a credential', ExitCode.GENERAL);
90
+ writeMachineCredential(body.credential);
91
+ writeMachineConfig({ apiUrl, environmentId: body.environment_id, directoryUrl, account });
92
+ await registerThisMac(directoryUrl);
93
+ await stopAllDaemons();
94
+ await spawnDaemon();
95
+ return { account: account.display };
96
+ }
62
97
  const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
63
98
  export const sysSigninLeaf = defineLeaf({
64
99
  name: 'signin',
@@ -80,6 +115,7 @@ export const sysSigninLeaf = defineLeaf({
80
115
  effects: [
81
116
  'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
82
117
  'On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account\'s result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.',
118
+ 'On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
83
119
  'On a moved computer: restarts the daemon so it reconnects to Northlight.',
84
120
  'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
85
121
  ],
@@ -103,6 +139,8 @@ export const sysSigninLeaf = defineLeaf({
103
139
  await spawnDaemon();
104
140
  return { account };
105
141
  }
142
+ if (!hasLocalCanvas())
143
+ return await registerFreshComputer(directoryUrl);
106
144
  const { account } = await signIn(directoryUrl, showSignIn);
107
145
  if (insideBroker()) {
108
146
  startDetachedMove(envNodeId());
@@ -120,8 +158,22 @@ export const sysSigninLeaf = defineLeaf({
120
158
  async function stopMovedComputer() {
121
159
  await stopAllDaemons();
122
160
  await spawnDaemon();
123
- const health = await cliClient({ local: true }).healthz();
124
- return health.signed_in === false;
161
+ return (await probeDaemonHealth()).signed_in === false;
162
+ }
163
+ /** End this computer's machine credential at the control plane with the stored sign-in, so signing out works with no daemon running. Skipped when there is no sign-in to authenticate with. */
164
+ async function revokeMachine(machine) {
165
+ if (readPersonCredential() === undefined)
166
+ return;
167
+ const bearer = await personBearer(machine.directoryUrl);
168
+ let response;
169
+ try {
170
+ response = await fetch(new URL(`/v1/machines/${machine.environmentId}`, machine.apiUrl), { method: 'DELETE', headers: { authorization: `Bearer ${bearer}` }, signal: AbortSignal.timeout(30_000) });
171
+ }
172
+ catch (error) {
173
+ throw northlightUnreachable(error, machine.apiUrl);
174
+ }
175
+ if (!response.ok && response.status !== 404)
176
+ throw new CrtrError('machine_revoke_failed', `Northlight refused to revoke this computer's machine credential (HTTP ${response.status}): ${(await response.text()).slice(0, 300)}`, ExitCode.GENERAL, { next: 'Run `crtr sys signout` again.' });
125
177
  }
126
178
  export const sysSignoutLeaf = defineLeaf({
127
179
  name: 'signout',
@@ -138,13 +190,16 @@ export const sysSignoutLeaf = defineLeaf({
138
190
  ],
139
191
  outputKind: 'object',
140
192
  effects: [
141
- 'Calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.',
193
+ 'On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.',
142
194
  'On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`.',
143
195
  ],
144
196
  },
145
197
  run: async () => {
198
+ const machine = readMachineConfig();
199
+ if (machine !== undefined)
200
+ await revokeMachine(machine);
146
201
  const { signedOut, revoked } = await signOut();
147
- const stopped = readMachineConfig() === undefined ? false : await stopMovedComputer();
202
+ const stopped = machine === undefined ? false : await stopMovedComputer();
148
203
  return { signed_out: signedOut, revoked, stopped };
149
204
  },
150
205
  render: (r) => `<signout signed_out="${r['signed_out']}" revoked="${r['revoked']}" stopped="${r['stopped']}"/>`,
@@ -111,6 +111,8 @@ export declare function grantsOfPerson(person: string): Promise<Array<Pick<Grant
111
111
  export declare function grantExpired(grant: Pick<GrantRecord, 'expires_at'>): boolean;
112
112
  /** The active form of a grant record read earlier, or null when it is not active, is past `expires_at`, or is unparsable. */
113
113
  export declare function activeRecord(grant: GrantRecord): ActiveGrant | null;
114
+ /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
115
+ export declare function canonicalJson(value: unknown): string;
114
116
  /** `grant.get`'s `version`: an opaque string that changes exactly when what an app
115
117
  * reads from its grant changes — `rev`, `resolved_scopes` (order kept), `spend_cap`,
116
118
  * `payer`, `inference_endpoint`, `dependencies`. `synced_at` and the token's claims are left out, so a
@@ -4,6 +4,7 @@ import { openDb, withCanvasWrite } from '../canvas/db.js';
4
4
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
5
5
  import { replaceWrittenBy, userSubject } from '../permissions/facts.js';
6
6
  import { GROUP_TYPE } from '../permissions/builtin.js';
7
+ import { shadowCheck } from './shadow.js';
7
8
  const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
8
9
  const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
9
10
  /** The fleet's runtime principal (`CRTR_RUNTIME`): a cloud role reads only its own runtime's grants, so a person's VM or laptop grants are never used. A Mac sets none. */
@@ -104,7 +105,10 @@ function active(row) {
104
105
  if (!row || row.status !== 'active')
105
106
  return null;
106
107
  try {
107
- return activeRecord(record(row));
108
+ const grant = activeRecord(record(row));
109
+ if (grant !== null)
110
+ shadowCheck(grant);
111
+ return grant;
108
112
  }
109
113
  catch (error) {
110
114
  if (error instanceof TypeError || error instanceof SyntaxError)
@@ -278,7 +282,7 @@ export function activeRecord(grant) {
278
282
  }
279
283
  }
280
284
  /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
281
- function canonicalJson(value) {
285
+ export function canonicalJson(value) {
282
286
  if (Array.isArray(value))
283
287
  return `[${value.map(canonicalJson).join(',')}]`;
284
288
  if (value && typeof value === 'object') {
@@ -0,0 +1,15 @@
1
+ import { type GrantRecord } from './mirror.js';
2
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
3
+ export declare function setShadowTtl(ms: number): void;
4
+ /** Test hook: forget every cached answer. */
5
+ export declare function resetShadowCache(): void;
6
+ /** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
7
+ export declare const shadowCounts: {
8
+ agree: number;
9
+ disagree: number;
10
+ lagging: number;
11
+ error: number;
12
+ };
13
+ export declare function shadowIdle(): Promise<void>;
14
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
15
+ export declare function shadowCheck(stored: GrantRecord): void;
@@ -0,0 +1,102 @@
1
+ // Grant-evaluation phase 3 (shadow). On the fleet, each stored-column grant read is compared with the directory's live answer for that account.
2
+ // The stored column still decides; this only counts and logs disagreements. Every failure here is swallowed into a log line, never into the decision.
3
+ import { directoryIssuer } from '../directory/issuer.js';
4
+ import { outboundFetch } from '../events/outbound.js';
5
+ import { warn } from '../output.js';
6
+ import { canonicalJson } from './mirror.js';
7
+ let ttlMs = 5_000;
8
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
9
+ export function setShadowTtl(ms) { ttlMs = ms; }
10
+ const MAX_SUBS = 512;
11
+ const COMPARED = ['status', 'scopes', 'resolved_scopes', 'spend_cap', 'payer', 'dependencies', 'run_notice_url', 'inference_endpoint'];
12
+ // Insertion-ordered Map used as an LRU: a read re-inserts the key.
13
+ /** Test hook: forget every cached answer. */
14
+ export function resetShadowCache() { cache.clear(); }
15
+ const cache = new Map();
16
+ const inflight = new Map();
17
+ /** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
18
+ export const shadowCounts = { agree: 0, disagree: 0, lagging: 0, error: 0 };
19
+ async function fetchAnswer(base, sub, held) {
20
+ // Imported here, not at the top: sync.js reaches the whole canvas, and a static edge made mirror.js -> shadow.js -> sync.js close an import cycle that broke module load order.
21
+ const { mintDirectoryToken } = await import('./sync.js');
22
+ const token = await mintDirectoryToken(base);
23
+ const epochs = held ? `&epochs=${held.epochs.global},${held.epochs.sub}` : '';
24
+ const url = `${base}/v1/runtime/grant-answers?sub=${encodeURIComponent(sub)}${epochs}`;
25
+ const response = await outboundFetch('grant_shadow', url, { headers: { Authorization: `Bearer ${token.access_token}` }, signal: AbortSignal.timeout(10_000) });
26
+ if (!response.ok)
27
+ throw new Error(`grant-answers ${response.status}`);
28
+ const body = await response.json();
29
+ if (body.unchanged) {
30
+ if (!held)
31
+ throw new Error('grant-answers said unchanged to a caller holding nothing');
32
+ return { ...held, epochs: body.epochs, checkedAt: Date.now() };
33
+ }
34
+ return { epochs: body.epochs, grants: new Map((body.grants ?? []).map((grant) => [String(grant['id']), grant])), checkedAt: Date.now() };
35
+ }
36
+ async function answerFor(base, sub) {
37
+ const held = cache.get(sub);
38
+ if (held && Date.now() - held.checkedAt < ttlMs)
39
+ return held;
40
+ const pending = inflight.get(sub);
41
+ if (pending)
42
+ return pending;
43
+ const run = fetchAnswer(base, sub, held).then((answer) => {
44
+ cache.delete(sub);
45
+ cache.set(sub, answer);
46
+ if (cache.size > MAX_SUBS)
47
+ cache.delete(cache.keys().next().value);
48
+ return answer;
49
+ }).finally(() => inflight.delete(sub));
50
+ inflight.set(sub, run);
51
+ return run;
52
+ }
53
+ /** Resolves once every comparison started so far has finished. Test hook. */
54
+ const running = new Set();
55
+ export async function shadowIdle() { await Promise.all([...running]); }
56
+ async function compare(stored) {
57
+ const base = directoryIssuer();
58
+ if (base === null)
59
+ return;
60
+ const live = (await answerFor(base, stored.sub)).grants.get(stored.id);
61
+ if (!live) {
62
+ shadowCounts.disagree++;
63
+ warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, fields: ['missing'] })}`);
64
+ return;
65
+ }
66
+ if (live['rev'] !== stored.rev) {
67
+ shadowCounts.lagging++;
68
+ return;
69
+ }
70
+ const fields = COMPARED.filter((key) => canonicalJson(live[key] ?? null) !== canonicalJson(stored[key] ?? null));
71
+ if (fields.length === 0) {
72
+ shadowCounts.agree++;
73
+ return;
74
+ }
75
+ shadowCounts.disagree++;
76
+ warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, rev: stored.rev, fields })}`);
77
+ }
78
+ let summaryTimer;
79
+ let reported = { agree: 0, disagree: 0, lagging: 0, error: 0 };
80
+ // One greppable line a minute while checks are happening: `grep grant_shadow_summary`; sum `disagree` across pods over 7 days.
81
+ function startSummary() {
82
+ if (summaryTimer)
83
+ return;
84
+ summaryTimer = setInterval(() => {
85
+ const delta = { agree: shadowCounts.agree - reported.agree, disagree: shadowCounts.disagree - reported.disagree, lagging: shadowCounts.lagging - reported.lagging, error: shadowCounts.error - reported.error };
86
+ reported = { ...shadowCounts };
87
+ if (delta.agree + delta.disagree + delta.lagging + delta.error > 0)
88
+ warn(`grant_shadow_summary ${JSON.stringify({ window_s: 60, ...delta })}`);
89
+ }, 60_000);
90
+ summaryTimer.unref();
91
+ }
92
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
93
+ export function shadowCheck(stored) {
94
+ if (!process.env['CRTR_RUNTIME'])
95
+ return;
96
+ startSummary();
97
+ const task = compare(stored).catch((error) => {
98
+ shadowCounts.error++;
99
+ warn(`grant_shadow error ${JSON.stringify({ grant: stored.id, message: error instanceof Error ? error.message : String(error) })}`);
100
+ }).finally(() => running.delete(task));
101
+ running.add(task);
102
+ }
@@ -205,6 +205,7 @@ export const OPERATIONS = [
205
205
  { name: 'import.get', method: 'GET', path: '/v1/imports/:run_id', classes: ['person', 'import'], resource: 'none' },
206
206
  { name: 'import.rollback', method: 'POST', path: '/v1/imports/:run_id/rollback', classes: ['person'], resource: 'none' },
207
207
  { name: 'machine.register', method: 'POST', path: '/v1/machines', classes: ['person'], resource: 'none' },
208
+ { name: 'machine.revoke', method: 'DELETE', path: '/v1/machines/:environment_id', classes: ['person'], resource: 'none' },
208
209
  { name: 'import.machine-credential', method: 'POST', path: '/v1/imports/:run_id/machine-credential', classes: ['person'], resource: 'none' },
209
210
  { name: 'execution.import-unpacked', method: 'POST', path: '/v1/executions/:execution_id/import-unpacked', classes: ['broker'], resource: 'none' },
210
211
  { name: 'execution.start', method: 'GET', path: '/v1/executions/:execution_id/start', classes: ['broker'], resource: 'none' },
@@ -5,11 +5,11 @@ export interface NorthlightAccount {
5
5
  display: string;
6
6
  }
7
7
  /** `directoryUrl` is the directory the person signs in against (`crtr sys signin`).
8
- * `account` is the account the records moved into, kept only to name it when another account signs in; a Mac moved before it existed has none. */
8
+ * `runId` is present only on a computer whose records were moved by an import. `account` is the account this computer belongs to (always written now; a Mac moved before it existed has none). */
9
9
  export interface MachineConfig {
10
10
  apiUrl: string;
11
11
  environmentId: string;
12
- runId: string;
12
+ runId?: string;
13
13
  directoryUrl: string;
14
14
  account?: NorthlightAccount;
15
15
  }
@@ -43,3 +43,8 @@ export declare function deleteMoveRecord(): void;
43
43
  export declare const isMoveCommitted: () => boolean;
44
44
  /** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
45
45
  export declare const moveUnfinishedError: (reason?: string) => CrtrError;
46
+ /** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
47
+ export declare const installIdPath: () => string;
48
+ export declare function readOrCreateInstallId(): string;
49
+ /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
50
+ export declare const hasLocalCanvas: () => boolean;
@@ -4,6 +4,7 @@
4
4
  // Also the move record `runtime/import/move.json` (0600): where a move to Northlight that `crtr sys signin` started stands, from before the drain until the
5
5
  // computer has switched over (design-crtr-northlight-signin component 4).
6
6
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { randomBytes } from 'node:crypto';
7
8
  import { dirname, join } from 'node:path';
8
9
  import { runtimeRoot, secretsDir } from '../../core/layout.js';
9
10
  import { CrtrError } from '../../core/errors.js';
@@ -17,10 +18,10 @@ export function readMachineConfig() {
17
18
  if (!existsSync(path))
18
19
  return undefined;
19
20
  const raw = JSON.parse(readFileSync(path, 'utf8'));
20
- if (typeof raw.apiUrl !== 'string' || typeof raw.environmentId !== 'string' || typeof raw.runId !== 'string' || typeof raw.directoryUrl !== 'string')
21
- throw new Error(`${path} must hold {apiUrl, environmentId, runId, directoryUrl}`);
21
+ if (typeof raw.apiUrl !== 'string' || typeof raw.environmentId !== 'string' || (raw.runId !== undefined && typeof raw.runId !== 'string') || typeof raw.directoryUrl !== 'string')
22
+ throw new Error(`${path} must hold {apiUrl, environmentId, directoryUrl}`);
22
23
  const account = raw.account !== undefined && typeof raw.account?.id === 'string' && typeof raw.account.display === 'string' ? { id: raw.account.id, display: raw.account.display } : undefined;
23
- return { apiUrl: raw.apiUrl, environmentId: raw.environmentId, runId: raw.runId, directoryUrl: raw.directoryUrl, ...(account === undefined ? {} : { account }) };
24
+ return { apiUrl: raw.apiUrl, environmentId: raw.environmentId, ...(raw.runId === undefined ? {} : { runId: raw.runId }), directoryUrl: raw.directoryUrl, ...(account === undefined ? {} : { account }) };
24
25
  }
25
26
  export function writeMachineConfig(config) {
26
27
  mkdirSync(dirname(machineConfigPath()), { recursive: true });
@@ -61,3 +62,16 @@ export function deleteMoveRecord() {
61
62
  export const isMoveCommitted = () => readMoveRecord()?.state === 'committed';
62
63
  /** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
63
64
  export const moveUnfinishedError = (reason) => new CrtrError('move_unfinished', `crtr's records are already in your Northlight account, but this computer has not switched over${reason === undefined ? '.' : `: ${reason}`}`, ExitCode.USAGE, { next: 'Run `crtr sys signin` to finish.' });
65
+ /** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
66
+ export const installIdPath = () => join(runtimeRoot(), 'install-id');
67
+ export function readOrCreateInstallId() {
68
+ const path = installIdPath();
69
+ if (existsSync(path))
70
+ return readFileSync(path, 'utf8').trim();
71
+ const id = Array.from(randomBytes(8), (b) => 'abcdefghijklmnopqrstuvwxyz0123456789'[b % 36]).join('');
72
+ mkdirSync(dirname(path), { recursive: true });
73
+ writeFileSync(path, `${id}\n`);
74
+ return id;
75
+ }
76
+ /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
77
+ export const hasLocalCanvas = () => ['pg', 'canvas.db', 'canvas.db.imported'].some((name) => existsSync(join(runtimeRoot(), name)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.735",
3
+ "version": "0.3.737",
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",