@north-light/api 0.3.737 → 0.3.739

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.
@@ -12,6 +12,7 @@ import { pathExists, listDirs, removePath } from '../../core/fs-utils.js';
12
12
  import { lsRemote } from '../../core/git.js';
13
13
  import { cliClient } from '../api-client.js';
14
14
  import { detectNerdFont, nerdFontInstallCommand, NERD_FONT_SELECT_HINT } from '../../core/runtime/nerd-font.js';
15
+ import { oldPackageInstalled } from './old-package.js';
15
16
  import { detectPackageManager } from './setup-core.js';
16
17
  import { validateEffectiveCommandPlugins } from '../../core/command-plugins/discovery.js';
17
18
  import { adaptPluginContributions } from '../../core/command-plugins/compose.js';
@@ -386,6 +387,13 @@ function runNerdFontCheck() {
386
387
  ...(plan.command ? { command: plan.command } : {}),
387
388
  });
388
389
  }
390
+ /** `@crouton-kit/crouter` installed beside this package fights it for the `crtr` bin, and npm refuses to install over it; only uninstalling it first works. */
391
+ function oldPackageCheck() {
392
+ const old = oldPackageInstalled();
393
+ if (old === undefined)
394
+ return pass('canvas', 'package:old-crouter', 'the old @crouton-kit/crouter package is not installed');
395
+ return failCheck('canvas', 'package:old-crouter', old.message, { kind: 'human_action', description: 'Remove the old package, then reinstall this one', command: `${old.uninstall} && npm i -g @north-light/cli@latest` });
396
+ }
389
397
  /** Where the generation was installed from (`<id>.source.json` beside it, written by install-runtime). */
390
398
  function installSourceCheck(label, generation) {
391
399
  const name = `runtime:${label}:source`;
@@ -630,6 +638,7 @@ export const sysDoctorLeaf = defineLeaf({
630
638
  allResults.push(...runBinContributionChecks(scopes));
631
639
  allResults.push(...runHumanActionChecks(scopes));
632
640
  allResults.push(...await runRequiresChecks(scopes));
641
+ allResults.push(oldPackageCheck());
633
642
  allResults.push(...await runFaultChecks());
634
643
  const processLocation = processGeneration();
635
644
  allResults.push(...await generationChecks('selected', selectedGeneration(), processLocation === null));
@@ -0,0 +1,9 @@
1
+ export declare const OLD_PACKAGE = "@crouton-kit/crouter";
2
+ export declare const OLD_PACKAGE_UNINSTALL = "npm uninstall -g @crouton-kit/crouter";
3
+ /** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
4
+ export declare function oldPackageDir(packageRoot: string): string | undefined;
5
+ /** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
6
+ export declare function oldPackageInstalled(packageRoot?: string): {
7
+ uninstall: string;
8
+ message: string;
9
+ } | undefined;
@@ -0,0 +1,20 @@
1
+ // The old `@crouton-kit/crouter` package declares the same `crtr` bin as `@north-light/cli`. npm checks bin ownership before any install script runs,
2
+ // so `npm i -g @north-light/cli` over it fails with EEXIST and no script of ours can prevent that; the old package has to be uninstalled first.
3
+ import { existsSync } from 'node:fs';
4
+ import { dirname, join, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ export const OLD_PACKAGE = '@crouton-kit/crouter';
7
+ export const OLD_PACKAGE_UNINSTALL = `npm uninstall -g ${OLD_PACKAGE}`;
8
+ /** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
9
+ export function oldPackageDir(packageRoot) {
10
+ const marker = `${sep}node_modules${sep}@north-light${sep}cli`;
11
+ const at = packageRoot.lastIndexOf(marker);
12
+ return at < 0 ? undefined : join(packageRoot.slice(0, at), 'node_modules', OLD_PACKAGE);
13
+ }
14
+ /** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
15
+ export function oldPackageInstalled(packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')) {
16
+ const dir = oldPackageDir(packageRoot);
17
+ if (dir === undefined || !existsSync(join(dir, 'package.json')))
18
+ return undefined;
19
+ return { uninstall: OLD_PACKAGE_UNINSTALL, message: `The old ${OLD_PACKAGE} package is still installed at ${dir} and owns the \`crtr\` command. Run \`${OLD_PACKAGE_UNINSTALL}\`, then \`npm i -g @north-light/cli@latest\`.` };
20
+ }
@@ -5,7 +5,7 @@ import { piAgentDir } from '../../core/runtime/package-health.js';
5
5
  import { basename, dirname, join, relative, resolve } from 'node:path';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { BINDING_CATALOG, normalizeGesture, splitGestureExpression, inboxShortcut, resolveKeybindings, } from '../../core/keybindings/index.js';
8
- import { runtimeManifest } from './shared.js';
8
+ import { builtinPiPackageDir } from '../../core/scope.js';
9
9
  import { atomicWriteJson, readJsonIfExists, readJsonOrNull } from '../../core/fs-utils.js';
10
10
  import { resolveBundledPiCliPath } from '../../core/runtime/pi-cli.js';
11
11
  import { crtrVersion } from '../../shared/crtr-version.js';
@@ -272,7 +272,7 @@ const LOCAL_PACKAGE_NAME_ALIASES = {
272
272
  'dev-plugin': [],
273
273
  };
274
274
  function selectedPiPackageDir(name) {
275
- return join(runtimeManifest.runtimeHome(), 'selected', 'dist', 'builtin-pi-packages', name);
275
+ return builtinPiPackageDir(name);
276
276
  }
277
277
  export function buildSetupManifest(resolveBuiltinPackageDir = selectedPiPackageDir) {
278
278
  // Order matters at execution: the marketplace source registers before the
@@ -13,6 +13,7 @@ import { envNodeId } from '../../shared/env.js';
13
13
  import { ExitCode } from '../../types.js';
14
14
  import { insideBroker } from './join.js';
15
15
  import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
16
+ import { oldPackageInstalled } from './old-package.js';
16
17
  import { WAIT_FOR_PID_ENV } from './import/start.js';
17
18
  /** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
18
19
  function openBrowser(url) {
@@ -114,6 +115,7 @@ export const sysSigninLeaf = defineLeaf({
114
115
  outputKind: 'object',
115
116
  effects: [
116
117
  '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.',
118
+ 'Starts the local daemon first when it is not running, and waits until it serves.',
117
119
  '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
120
  '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.',
119
121
  'On a moved computer: restarts the daemon so it reconnects to Northlight.',
@@ -121,6 +123,12 @@ export const sysSigninLeaf = defineLeaf({
121
123
  ],
122
124
  },
123
125
  run: async (input) => {
126
+ // A computer with local records needs its daemon (the move reads the canvas through it) and a machine's daemon is the machine role; a fresh computer starts none until it is registered.
127
+ if (readMachineConfig() !== undefined || hasLocalCanvas())
128
+ await spawnDaemon();
129
+ const oldPackage = oldPackageInstalled();
130
+ if (oldPackage !== undefined)
131
+ process.stderr.write(`${oldPackage.message}\n`);
124
132
  const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
125
133
  const unfinished = await settleEarlierMove(showSignIn);
126
134
  if (unfinished !== undefined) {
@@ -1,7 +1,10 @@
1
+ import { CrtrError } from '../../errors.js';
1
2
  import type { ImportRunDTO, ImportStartRequest, ImportStartedDTO, ImportStoreNameDTO, ImportUploadUrlsDTO } from '../../../api/dto/imports.js';
2
3
  /** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
3
4
  export declare const STORE_FILE = "stores.json";
4
5
  export declare const STORE_ORDER: readonly ImportStoreNameDTO[];
6
+ /** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
7
+ export declare function releaseMismatch(accepted: string, status: number): CrtrError;
5
8
  export declare class ImportCloud {
6
9
  private readonly apiUrl;
7
10
  private readonly token;
@@ -1,6 +1,8 @@
1
1
  // The exporter's HTTP side: `/v1/imports` on the control plane with the person's (or the operator's) bearer token, and signed R2 PUTs.
2
2
  // Imports Node built-ins only, so a CLI leaf can use it.
3
3
  import { CrtrError, general } from '../../errors.js';
4
+ import { ExitCode } from '../../../types.js';
5
+ import { crtrVersion } from '../../../shared/crtr-version.js';
4
6
  import { NORTHLIGHT_UNREACHABLE } from '../../directory/reach.js';
5
7
  /** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
6
8
  export const STORE_FILE = 'stores.json';
@@ -17,6 +19,11 @@ function failureText(error) {
17
19
  const cause = error.cause;
18
20
  return `failed: ${error instanceof Error ? error.message : String(error)}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`;
19
21
  }
22
+ /** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
23
+ export function releaseMismatch(accepted, status) {
24
+ const command = `npm i -g @north-light/cli@${accepted}`;
25
+ return new CrtrError('release_mismatch', `Northlight accepts only crtr ${accepted} for this step, and this computer runs ${crtrVersion()}. Install it with \`${command}\`, then run \`crtr sys signin\` again.`, ExitCode.GENERAL, { status, code: 'release_mismatch', accepted, next: `Run \`${command}\`, then \`crtr sys signin\`.` });
26
+ }
20
27
  export class ImportCloud {
21
28
  apiUrl;
22
29
  token;
@@ -83,6 +90,9 @@ export class ImportCloud {
83
90
  catch {
84
91
  code = undefined;
85
92
  }
93
+ const accepted = code === 'release_mismatch' ? /control plane accepts (\S+)/.exec(text)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/, '') : undefined;
94
+ if (accepted !== undefined)
95
+ throw releaseMismatch(accepted, response.status);
86
96
  throw general(`${method} ${path} answered ${response.status}: ${text.slice(0, 500)}`, { status: response.status, ...(typeof code === 'string' ? { code } : {}) });
87
97
  }
88
98
  return (text === '' ? undefined : JSON.parse(text));
@@ -237,9 +237,12 @@ export async function ensureRootProfile() {
237
237
  }
238
238
  return await createProfile(ROOT_PROFILE_NAME, [], { grantee: 'app:terminal' });
239
239
  }
240
- const existing = getStoredProfile(ROOT_PROFILE_ID);
240
+ // A computer signed in to an account that already has a root profile (made on another computer, so with another id) uses that one.
241
+ const existing = getStoredProfile(ROOT_PROFILE_ID)
242
+ ?? listProfiles().find((p) => p.manifest.name === ROOT_PROFILE_NAME && profileApp(p.manifest) === 'app:terminal')
243
+ ?? null;
241
244
  if (existing !== null) {
242
- scaffoldProfile(ROOT_PROFILE_ID, existing.manifest);
245
+ scaffoldProfile(existing.profileId, existing.manifest);
243
246
  return existing;
244
247
  }
245
248
  const next = {
@@ -48,3 +48,5 @@ export declare const installIdPath: () => string;
48
48
  export declare function readOrCreateInstallId(): string;
49
49
  /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
50
50
  export declare const hasLocalCanvas: () => boolean;
51
+ /** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
52
+ export declare const computerIsUnset: () => boolean;
@@ -7,6 +7,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync }
7
7
  import { randomBytes } from 'node:crypto';
8
8
  import { dirname, join } from 'node:path';
9
9
  import { runtimeRoot, secretsDir } from '../../core/layout.js';
10
+ import { joinedIssuer } from '../../core/directory/join.js';
10
11
  import { CrtrError } from '../../core/errors.js';
11
12
  import { atomicWriteJson } from '../../core/fs-utils.js';
12
13
  import { ExitCode } from '../../types.js';
@@ -75,3 +76,5 @@ export function readOrCreateInstallId() {
75
76
  }
76
77
  /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
77
78
  export const hasLocalCanvas = () => ['pg', 'canvas.db', 'canvas.db.imported'].some((name) => existsSync(join(runtimeRoot(), name)));
79
+ /** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
80
+ export const computerIsUnset = () => readMachineConfig() === undefined && !hasLocalCanvas() && joinedIssuer() === null;
@@ -16,7 +16,7 @@ import { hostExecPath } from '../core/runtime/branded-host.js';
16
16
  // reaches openDb) so the CLI daemon front door stays canvas.db-free (plan B-0).
17
17
  import { isDaemonRunning, readPidfile, isPidAlive } from './pidfile.js';
18
18
  import { DAEMON_STARTUP_WINDOW_MS } from './startup-policy.js';
19
- import { readMachineConfig } from './machine-link/config.js';
19
+ import { computerIsUnset, readMachineConfig } from './machine-link/config.js';
20
20
  import { exclusiveLockOwnerPid } from '../core/exclusive-lock.js';
21
21
  import { onDiskMigrationLockPath } from '../core/canvas/paths.js';
22
22
  import { envNoDaemonAutostart } from '../shared/env.js';
@@ -694,6 +694,9 @@ export function ensureDaemon(deps = {}) {
694
694
  const now = deps.now ?? Date.now;
695
695
  if (autostartDisabled())
696
696
  return;
697
+ // A computer with no `machine.json` and no local records is not set up: no command starts a local control plane there (`crtr sys signin` comes first).
698
+ if (!deps.spawnDaemon && computerIsUnset())
699
+ return;
697
700
  if (autostartInFlight)
698
701
  return;
699
702
  if (now() < autostartNextAttemptAt)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.737",
3
+ "version": "0.3.739",
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",