@north-light/cli 0.3.730 → 0.3.732

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 (68) hide show
  1. package/dist/api/client.d.ts +3 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/errors.d.ts +5 -0
  6. package/dist/api/errors.js +1 -1
  7. package/dist/builtin-memory/northlight-apps/get-started.md +4 -4
  8. package/dist/clients/attach/overlays/graph.d.ts +2 -0
  9. package/dist/clients/attach/overlays/graph.js +1 -1
  10. package/dist/clients/attach/viewer.js +500 -500
  11. package/dist/commands/sys/daemon.js +1 -1
  12. package/dist/commands/sys/import/move.d.ts +2 -0
  13. package/dist/commands/sys/import/move.js +9 -7
  14. package/dist/commands/sys/join.js +1 -1
  15. package/dist/commands/sys/signin.js +2 -2
  16. package/dist/core/canvas/canvas.d.ts +1 -1
  17. package/dist/core/canvas/canvas.js +16 -16
  18. package/dist/core/canvas/history.d.ts +1 -1
  19. package/dist/core/canvas/history.js +8 -8
  20. package/dist/core/canvas/tree.d.ts +4 -0
  21. package/dist/core/canvas/tree.js +6 -6
  22. package/dist/core/conversation-store/row-store.js +13 -13
  23. package/dist/core/directory/join.d.ts +6 -26
  24. package/dist/core/directory/join.js +1 -1
  25. package/dist/core/environment-starter-script.d.ts +1 -1
  26. package/dist/core/environment-starter-script.js +4 -1
  27. package/dist/core/grants/sync.js +1 -1
  28. package/dist/core/model-auth/activations.js +1 -1
  29. package/dist/core/providers/call.js +1 -1
  30. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  31. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  32. package/dist/core/storage/client.js +2 -2
  33. package/dist/daemon/api/bridge.js +2 -2
  34. package/dist/daemon/api/handlers/canvas.js +5 -5
  35. package/dist/daemon/api/handlers/shares.js +1 -1
  36. package/dist/daemon/crtrd.js +8 -8
  37. package/dist/daemon/manage.d.ts +2 -7
  38. package/dist/daemon/manage.js +3 -3
  39. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  40. package/docs/apps/get-started.md +4 -4
  41. package/docs/cli/join-northlight.md +16 -22
  42. package/package.json +3 -3
  43. package/packages/crouter-api/dist/api/client.js +4 -3
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/errors.js +11 -0
  46. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +18 -1
  47. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -3
  48. package/packages/crouter-api/dist/commands/sys/import/move.js +12 -0
  49. package/packages/crouter-api/dist/commands/sys/join.js +5 -37
  50. package/packages/crouter-api/dist/commands/sys/signin.js +6 -4
  51. package/packages/crouter-api/dist/core/canvas/canvas.js +7 -3
  52. package/packages/crouter-api/dist/core/canvas/history.js +3 -3
  53. package/packages/crouter-api/dist/core/canvas/tree.js +20 -0
  54. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -2
  55. package/packages/crouter-api/dist/core/directory/join.js +35 -86
  56. package/packages/crouter-api/dist/core/environment-starter-script.js +4 -1
  57. package/packages/crouter-api/dist/core/grants/sync.js +1 -1
  58. package/packages/crouter-api/dist/core/providers/call.js +1 -1
  59. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +4 -1
  60. package/packages/crouter-api/dist/core/storage/client.js +1 -1
  61. package/packages/crouter-api/dist/daemon/manage.js +2 -16
  62. package/packages/crouter-api/package.json +1 -1
  63. package/packages/crouter-identity/package.json +1 -1
  64. package/packages/crouter-plugin/package.json +3 -3
  65. package/runtime.lock.json +14 -14
  66. package/dist/core/directory/join-lock.d.ts +0 -13
  67. package/dist/core/directory/join-lock.js +0 -1
  68. package/packages/crouter-api/dist/core/directory/join-lock.js +0 -61
@@ -265,8 +265,13 @@ export function createRowStore() {
265
265
  lines.shift();
266
266
  return { header, entries: entriesOf(lines.join('\n')), path };
267
267
  }
268
- if (!window || size <= window.head + window.tail)
269
- return { header, entries: entriesOf((await bytesOf(snap, 0, size)).toString('utf8')), path };
268
+ // Line by line: a conversation over V8's string limit (~512 MB) cannot be decoded as one string.
269
+ if (!window || size <= window.head + window.tail) {
270
+ const entries = [];
271
+ for await (const line of linesOf(snap))
272
+ entries.push(...entriesOf(line));
273
+ return { header, entries, path };
274
+ }
270
275
  const front = (await bytesOf(snap, 0, Math.max(0, window.head))).toString('utf8').split('\n');
271
276
  front.pop();
272
277
  // One byte before the tail window says whether it begins on a line boundary.
@@ -1,6 +1,6 @@
1
- // Runtime join: exchange a directory enrollment token for a registration of a
2
- // new runtime client key, then record the returned identity in the runtime-client file. Runs
3
- // offline, before the daemon starts, as the daemon's OS user; it writes no settings (the daemon applies them at its start).
1
+ // Runtime registration: send the directory a new public ES256 key under a credential (a hosted runtime's single-use enrollment token at first
2
+ // boot, or a signed-in person's bearer from `crtr sys signin`), then record the returned identity and the private key in the runtime-client file.
3
+ // It writes no settings (the daemon applies them at its start); the private key never leaves this computer.
4
4
  import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
6
6
  import { hostname } from 'node:os';
@@ -14,7 +14,6 @@ import { atomicWriteJson, readJsonIfExists } from '../fs-utils.js';
14
14
  import { launcherPresent } from '../grants/sandboxes.js';
15
15
  import { crtrVersion } from '../../shared/crtr-version.js';
16
16
  import { pluginsDir } from '../scope.js';
17
- import { withJoinLock } from './join-lock.js';
18
17
  function clientPath() {
19
18
  return join(secretsDir(), 'runtime-client.json');
20
19
  }
@@ -55,7 +54,7 @@ export function installedPluginIds() {
55
54
  return [];
56
55
  }
57
56
  }
58
- async function register(directory, token, publicJwk, name) {
57
+ async function register(directory, token, publicJwk, name, retry) {
59
58
  const endpoint = `${directory.replace(/\/$/, '')}/v1/runtimes/registration`;
60
59
  let response;
61
60
  try {
@@ -77,7 +76,7 @@ async function register(directory, token, publicJwk, name) {
77
76
  throw new InputError({
78
77
  error: 'join_refused',
79
78
  message: `directory refused the registration: ${response.status} ${text.slice(0, 500)}`,
80
- next: `Create a new join token at ${directory.replace(/\/$/, '')}/account/machines (tokens are single-use and expire after 10 minutes), and run \`crtr sys join\` again.`,
79
+ next: retry,
81
80
  });
82
81
  }
83
82
  try {
@@ -113,12 +112,12 @@ export function joinedClient() {
113
112
  function daemonRunningError(socket) {
114
113
  return new InputError({
115
114
  error: 'daemon_running',
116
- message: `cannot join while a daemon answers on ${socket}`,
117
- next: 'This daemon is managed outside crtr, so join cannot restart it: stop the daemon that owns this volume, then run `crtr sys join` again.',
115
+ message: `cannot register while a daemon answers on ${socket}`,
116
+ next: 'Stop the daemon that owns this volume, then run `crtr sys join` again.',
118
117
  });
119
118
  }
120
119
  /** Register (or reuse the stored registration) without touching local state beyond the pending key. */
121
- async function obtainRegistration(directory, token, name, tokenHash) {
120
+ async function obtainRegistration(directory, token, name, tokenHash, retry) {
122
121
  const stored = readJsonIfExists(clientPath());
123
122
  if (stored?.token_sha256 === tokenHash)
124
123
  return { joined: registration(stored), registered: false };
@@ -133,86 +132,36 @@ async function obtainRegistration(directory, token, name, tokenHash) {
133
132
  atomicWriteJson(pendingPath(), pending, { mode: 0o600 });
134
133
  }
135
134
  const { jwk, public_jwk: publicJwk } = pending;
136
- const joined = await register(directory, token, publicJwk, name);
135
+ const joined = await register(directory, token, publicJwk, name, retry);
137
136
  return { joined, registered: true, client: { jwk, kid: jwk.kid, alg: 'ES256', ...joined, token_sha256: tokenHash } };
138
137
  }
139
- /** Join this runtime to a directory.
140
- *
141
- * With `daemon` control, a running daemon is no obstacle: the join holds the
142
- * join lock (so no viewer's redial can autostart a daemon while it is down),
143
- * registers with the directory while the daemon still serves, stops the
144
- * daemon, writes the identity, and starts the daemon again so its start
145
- * applies the person change to canvas.db. Without it, a running daemon refuses. */
146
- export async function joinDirectory(directory, token, name = hostname(), daemon) {
138
+ function requireDirectory(directory) {
147
139
  if (!isUrl(directory))
148
140
  throw new InputError({ error: 'invalid_directory', message: 'directory must be an http or https URL', received: directory, field: 'directory', next: 'Pass the directory base URL, for example https://directory.example.' });
149
- if (token === '')
150
- throw new InputError({ error: 'invalid_token', message: 'token is empty', field: 'token', next: 'Pass the enrollment token provisioning supplied.' });
151
- const socket = apiSocketPath();
152
- const tokenHash = createHash('sha256').update(token).digest('hex');
153
- if (daemon === undefined) {
154
- if (await daemonAnswers(socket))
155
- throw daemonRunningError(socket);
156
- const { joined, registered, client } = await obtainRegistration(directory, token, name, tokenHash);
157
- if (client) {
158
- atomicWriteJson(clientPath(), client, { mode: 0o600 });
159
- rmSync(pendingPath(), { force: true });
160
- }
161
- return { ...joined, registered, daemon: 'not_running' };
141
+ }
142
+ /** Register this runtime under `credential` and record the identity. A second call with the same credential finishes without calling the directory. */
143
+ async function registerAndStore(directory, credential, name, retry) {
144
+ requireDirectory(directory);
145
+ if (credential === '')
146
+ throw new InputError({ error: 'invalid_token', message: 'credential is empty', field: 'token', next: 'Pass the enrollment token provisioning supplied.' });
147
+ const { joined, registered, client } = await obtainRegistration(directory, credential, name, createHash('sha256').update(credential).digest('hex'), retry);
148
+ if (client) {
149
+ atomicWriteJson(clientPath(), client, { mode: 0o600 });
150
+ rmSync(pendingPath(), { force: true });
162
151
  }
163
- return withJoinLock(async () => {
164
- const refuseInsideNode = () => new InputError({
165
- error: 'join_inside_node',
166
- message: 'a daemon is running and this command is inside a node: stopping the daemon would kill this node\'s broker and this command with it',
167
- next: 'Run `crtr sys join` from a plain terminal outside any crtr node. It stops the daemon, joins, and starts it again for you.',
168
- });
169
- if (await daemon.running() && daemon.insideNode())
170
- throw refuseInsideNode();
171
- const { joined, registered, client } = await obtainRegistration(directory, token, name, tokenHash);
172
- let stopped = false;
173
- let failure;
174
- try {
175
- if (await daemon.running()) {
176
- // The daemon may have started during the registration call: decide again, here, where the stop happens.
177
- if (daemon.insideNode())
178
- throw refuseInsideNode();
179
- stopped = true;
180
- await daemon.stop();
181
- if (await daemon.running())
182
- throw daemonRunningError(socket);
183
- }
184
- if (client) {
185
- atomicWriteJson(clientPath(), client, { mode: 0o600 });
186
- rmSync(pendingPath(), { force: true });
187
- }
188
- // Nothing may start a daemon now (the lock is held), so one seen here began before the lock and read the old settings.
189
- if (await daemon.running()) {
190
- if (daemon.insideNode())
191
- throw refuseInsideNode();
192
- stopped = true;
193
- await daemon.stop();
194
- }
195
- }
196
- catch (error) {
197
- failure = error;
198
- }
199
- // Bring the daemon back whether or not the join finished: it was running when we began. The lock is held until it serves, so no redial races it.
200
- // With none running, start one anyway: grant sync is what installs `cloud`, and a bare `crtr cloud …` is an unknown
201
- // command (it never reaches the daemon, so never autostarts one) until some daemon has synced.
202
- let restart = { daemon: 'not_running' };
203
- if (failure === undefined || stopped) {
204
- try {
205
- await daemon.start();
206
- restart = { daemon: stopped ? 'restarted' : 'started' };
207
- }
208
- catch (error) {
209
- restart = { daemon: 'restart_failed', daemon_error: error instanceof Error ? error.message : String(error) };
210
- }
211
- }
212
- if (failure !== undefined)
213
- throw failure;
214
- if (restart.daemon === 'started')
215
- await daemon.firstSync?.();
216
- return { ...joined, registered, ...restart };
217
- });
152
+ return { ...joined, registered };
153
+ }
154
+ /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
155
+ export async function joinDirectory(directory, token, name = hostname()) {
156
+ const socket = apiSocketPath();
157
+ if (await daemonAnswers(socket))
158
+ throw daemonRunningError(socket);
159
+ return registerAndStore(directory, token, name, 'Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.');
160
+ }
161
+ /** `crtr sys signin`'s registration: the signed-in person's bearer registers this computer as one of the person's runtimes, once. A computer that
162
+ * already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
163
+ export async function registerSignedInMac(directory, bearer) {
164
+ if (readJoined() !== null)
165
+ return null;
166
+ return registerAndStore(directory, bearer, hostname(), 'Run `crtr sys signin` again.');
218
167
  }
@@ -7,7 +7,10 @@ export const STARTER_SETUP_SCRIPT = `#!/usr/bin/env bash
7
7
  # How it runs
8
8
  # - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
9
9
  # - Your repositories are already checked out at /work/<repo name> before this runs.
10
- # - The sandbox user is "crtr" (home /home/crtr). Files you create for it must be chowned to it.
10
+ # - The sandbox user is "crtr". Files you create for it must be chowned to it. A node runs with HOME set to its app's home
11
+ # (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.
12
+ # - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,
13
+ # with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.
11
14
  # - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
12
15
  # or install at build time below.
13
16
  # - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
@@ -37,7 +37,7 @@ export function runtimeId(client = runtimeClient()) {
37
37
  }
38
38
  /** The text a person sees when the directory no longer recognises this machine. */
39
39
  export function machineRevokedMessage(issuer) {
40
- return `This machine was removed from your Northlight account. To use it again, create a join token at ${issuer.replace(/\/$/, '')}/account/machines, and run \`crtr sys join\` from a plain terminal.`;
40
+ return `This machine was removed from your Northlight account. To use it again, run \`crtr sys signin\`.`;
41
41
  }
42
42
  /** The directory answered `invalid_client` to this runtime's key: the machine was revoked. */
43
43
  export class MachineRevokedError extends Error {
@@ -92,7 +92,7 @@ export async function identity(caller) {
92
92
  if (caller.class === 'person') {
93
93
  const sub = (await callerTerminalGrant())?.sub;
94
94
  if (!sub)
95
- throw new ProviderError('grant_revoked', 'This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.');
95
+ throw new ProviderError('grant_revoked', 'This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.');
96
96
  return { sub, grantee: sub };
97
97
  }
98
98
  if (!caller.sub || !caller.grantee)
@@ -30,6 +30,9 @@ export const RUN_USER_NPMRC = [
30
30
  '//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}',
31
31
  `store-dir=/home/${RUN_USER}/.local/share/pnpm/store`,
32
32
  ];
33
+ /** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
34
+ * this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
35
+ export const RUN_USER_NPMRC_ENV = `ENV NPM_CONFIG_USERCONFIG=/home/${RUN_USER}/.npmrc`;
33
36
  const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
34
37
  export const REPOS_DIR = 'repos';
35
38
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
@@ -93,7 +96,7 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
93
96
  // A setup script may have written a resolved token into an npmrc; the run user's npmrc is rewritten to the token-free lines.
94
97
  if (packagesToken)
95
98
  out.push('RUN rm -f /work/.npmrc', `RUN ${writeRunUserNpmrc()} && chown ${RUN_USER}:${RUN_USER} /home/${RUN_USER}/.npmrc`);
96
- out.push(`USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
99
+ out.push(RUN_USER_NPMRC_ENV, `USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
97
100
  return out.join('\n');
98
101
  }
99
102
  const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
@@ -52,7 +52,7 @@ export function storageClient() {
52
52
  const config = storageConfig();
53
53
  const issuer = directoryIssuer();
54
54
  if (!config || !issuer) {
55
- throw new RunError(503, 'storage_unavailable', 'file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a computer joined with `crtr sys join` cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.', undefined, undefined, undefined, false);
55
+ throw new RunError(503, 'storage_unavailable', 'file storage is not configured on this runtime: it has no `runtime.storage` setting (service_url, base_url) or no joined directory. Only a hosted runtime has file storage (its provisioner sets CRTR_BOOT_STORAGE_URL), and the directory issues storage tokens only to a sandboxed runtime, so a registered computer cannot send or receive files yet. Retrying does not help: run this command from your hosted runtime.', undefined, undefined, undefined, false);
56
56
  }
57
57
  const key = `${issuer}\n${config.service_url}\n${config.base_url}`;
58
58
  if (cached?.key !== key)
@@ -20,7 +20,6 @@ import { 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';
23
- import { awaitJoinLockRelease, joinInProgress, joinInProgressError, joinLockHolder } from '../core/directory/join-lock.js';
24
23
  import { waitForDaemonAvailability } from '../api/index.js';
25
24
  import { localClient } from '../api/node-transport.js';
26
25
  // Daemon env sanitization
@@ -230,8 +229,6 @@ export function runDaemonBodiesDump(out) {
230
229
  export function runDaemonInstallId() {
231
230
  return runDaemonEntry(['import-dump', '', 'install-id']);
232
231
  }
233
- /** How long a handover successor waits for a running join: a registration call (30 s) plus the join's own stop and start. */
234
- const JOIN_WAIT_WINDOW_MS = 3 * 60_000;
235
232
  // Shutdown stays short even though startup may include corpus migration.
236
233
  const DAEMON_SHUTDOWN_WINDOW_MS = 20_000;
237
234
  const DAEMON_VERIFY_POLL_MS = 10;
@@ -464,7 +461,7 @@ export async function stopDaemonProcess(pid, timeoutMs = DAEMON_SHUTDOWN_WINDOW_
464
461
  throw new Error(`daemon ${pid} survived both SIGTERM and SIGKILL`);
465
462
  }
466
463
  /** Stop the recorded daemon and sweep every stray crtrd of this canvas home.
467
- * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys join`. */
464
+ * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys signin`. */
468
465
  export async function stopAllDaemons() {
469
466
  const pid = readPidfile();
470
467
  const recorded = pid !== null && isPidAlive(pid);
@@ -557,13 +554,6 @@ export async function spawnDaemon(opts = {}) {
557
554
  const launchArgs = await resolveDaemonLaunch().catch((error) => {
558
555
  throw new DaemonLaunchError(error);
559
556
  });
560
- // The one spawn point every start reaches (autostart, `sys daemon start`, a handover successor): an
561
- // autostart begun before a join took its lock lands here after it, and must not start a daemon.
562
- if (opts.waitForJoinLock === true)
563
- await awaitJoinLockRelease(JOIN_WAIT_WINDOW_MS);
564
- const joiner = joinLockHolder();
565
- if (joiner !== null && joiner !== process.pid && opts.ignoreJoinLock !== true)
566
- throw joinInProgressError(joiner);
567
557
  // Route stdout+stderr to an append-mode file instead of discarding them
568
558
  // (stdio:'ignore'). This fd is RAW RESIDUE only — third-party/runtime
569
559
  // output the daemon doesn't control, plus the narrow set of authorized raw
@@ -693,8 +683,7 @@ export function daemonAutostartStartupFailure() {
693
683
  return autostartStartupFailure;
694
684
  }
695
685
  /** Start the daemon if it is not already running. No-op if already up, if
696
- * autostart is suppressed for this invocation, while `crtr sys join` holds
697
- * the join lock (see core/directory/join-lock.ts), while an attempt is in flight,
686
+ * autostart is suppressed for this invocation, while an attempt is in flight,
698
687
  * or while backing off from a recent failure.
699
688
  * Does not throw: a spawn error is recorded, and a launch or early-exit failure
700
689
  * is reported through `daemonAutostartStartupFailure()` so a waiting client
@@ -705,9 +694,6 @@ export function ensureDaemon(deps = {}) {
705
694
  const now = deps.now ?? Date.now;
706
695
  if (autostartDisabled())
707
696
  return;
708
- // `crtr sys join` holds the daemon down on purpose; a viewer's redial must not bring it back.
709
- if (joinInProgress())
710
- return;
711
697
  if (autostartInFlight)
712
698
  return;
713
699
  if (now() < autostartNextAttemptAt)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.730",
3
+ "version": "0.3.732",
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.730",
3
+ "version": "0.3.732",
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.730",
3
+ "version": "0.3.732",
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.730",
31
- "@north-light/identity": "0.3.730"
30
+ "@north-light/api": "0.3.732",
31
+ "@north-light/identity": "0.3.732"
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.730",
3
+ "version": "0.3.732",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.730",
9
+ "version": "0.3.732",
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.730",
32
- "@north-light/plugin": "0.3.730",
31
+ "@north-light/identity": "0.3.732",
32
+ "@north-light/plugin": "0.3.732",
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.730",
11905
+ "version": "0.3.732",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.730",
11910
+ "version": "0.3.732",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.730",
11915
+ "version": "0.3.732",
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.730",
11923
+ "version": "0.3.732",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.730",
11927
- "@north-light/identity": "0.3.730"
11926
+ "@north-light/api": "0.3.732",
11927
+ "@north-light/identity": "0.3.732"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.730",
11932
+ "version": "0.3.732",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.730",
11936
- "@north-light/identity": "0.3.730",
11937
- "@north-light/plugin": "0.3.730",
11935
+ "@north-light/api": "0.3.732",
11936
+ "@north-light/identity": "0.3.732",
11937
+ "@north-light/plugin": "0.3.732",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -1,13 +0,0 @@
1
- import { InputError } from '../io.js';
2
- export declare function joinLockPath(): string;
3
- /** The live process holding the lock, or null when no join is running (no lock, or a holder that died). */
4
- export declare function joinLockHolder(): number | null;
5
- /** Whether a join is in progress. The joiner starts its own daemon through `spawnDaemon`, never through the implicit paths that ask this. */
6
- export declare function joinInProgress(): boolean;
7
- export declare function joinInProgressError(pid: number | null): InputError;
8
- /** Resolve once no other live process holds the join lock, or after `timeoutMs`. For a start that must happen
9
- * but must read the settings a join is about to commit (a daemon handover's successor): it waits the join out
10
- * instead of bypassing the lock, so nothing but the join starts a daemon while the lock is held. */
11
- export declare function awaitJoinLockRelease(timeoutMs: number, pollMs?: number): Promise<void>;
12
- /** Run `operation` holding the join lock. Throws `join_in_progress` when a live process holds it. */
13
- export declare function withJoinLock<T>(operation: () => Promise<T>): Promise<T>;
@@ -1 +0,0 @@
1
- var a=Object.defineProperty;var n=(o,r)=>a(o,"name",{value:r,configurable:!0});import{mkdirSync as l}from"node:fs";import{join as m}from"node:path";import{crtrHome as e}from"../canvas/paths.js";import{isPidAlive as f}from"../canvas/pid.js";import{exclusiveLockOwnerPid as d,withExclusiveDirectoryLockAsync as p}from"../exclusive-lock.js";import{InputError as h}from"../io.js";const w=1e3;function s(){return m(e(),"join.lock")}n(s,"joinLockPath");function t(){const o=d(s());return o!==null&&f(o)?o:null}n(t,"joinLockHolder");function E(){return t()!==null}n(E,"joinInProgress");function j(o){return new h({error:"join_in_progress",message:o===null?"`crtr sys join` is running and holds the daemon down until it finishes":`\`crtr sys join\` (pid ${o}) is running and holds the daemon down until it finishes`,next:"Wait for the join to finish; it starts the daemon again itself. If it is stuck, `crtr sys daemon start --force`."})}n(j,"joinInProgressError");async function _(o,r=100){const c=Date.now()+o;for(;;){const i=t();if(i===null||i===process.pid||Date.now()>=c)return;await new Promise(u=>setTimeout(u,r))}}n(_,"awaitJoinLockRelease");async function v(o){return l(e(),{recursive:!0}),p(s(),o,{timeoutMs:w,timeoutError:n(()=>j(t()),"timeoutError")})}n(v,"withJoinLock");export{_ as awaitJoinLockRelease,E as joinInProgress,j as joinInProgressError,t as joinLockHolder,s as joinLockPath,v as withJoinLock};
@@ -1,61 +0,0 @@
1
- // The "join in progress" lock. `crtr sys join` stops the daemon, rewrites local
2
- // identity, and starts the daemon again. Stopping the daemon kills every broker,
3
- // so every open viewer sees a cold socket and its client would autostart a new
4
- // daemon within seconds, which makes the join refuse (`daemon_running`). While
5
- // this lock is held by a live process, `ensureDaemon` and `spawnDaemon` (so also
6
- // `sys daemon start` and a handover successor) decline to start a daemon.
7
- //
8
- // It is the shared token-checked directory lock (`core/exclusive-lock.ts`): the
9
- // holder's pid is in its marker's name, a dead holder is reclaimed by exactly the
10
- // marker it observed (so a lagging reclaimer can never strip a live successor),
11
- // and only the holder's own marker releases it. PURITY: Node built-ins, path
12
- // builders and the pid probe only, so `daemon/manage.ts` can import it.
13
- import { mkdirSync } from 'node:fs';
14
- import { join } from 'node:path';
15
- import { crtrHome } from '../canvas/paths.js';
16
- import { isPidAlive } from '../canvas/pid.js';
17
- import { exclusiveLockOwnerPid, withExclusiveDirectoryLockAsync } from '../exclusive-lock.js';
18
- import { InputError } from '../io.js';
19
- /** How long a second joiner waits for the first before it refuses. Long enough to reclaim a dead holder's lock. */
20
- const ACQUIRE_WAIT_MS = 1_000;
21
- export function joinLockPath() {
22
- return join(crtrHome(), 'join.lock');
23
- }
24
- /** The live process holding the lock, or null when no join is running (no lock, or a holder that died). */
25
- export function joinLockHolder() {
26
- const pid = exclusiveLockOwnerPid(joinLockPath());
27
- return pid !== null && isPidAlive(pid) ? pid : null;
28
- }
29
- /** Whether a join is in progress. The joiner starts its own daemon through `spawnDaemon`, never through the implicit paths that ask this. */
30
- export function joinInProgress() {
31
- return joinLockHolder() !== null;
32
- }
33
- export function joinInProgressError(pid) {
34
- return new InputError({
35
- error: 'join_in_progress',
36
- message: pid === null
37
- ? '`crtr sys join` is running and holds the daemon down until it finishes'
38
- : `\`crtr sys join\` (pid ${pid}) is running and holds the daemon down until it finishes`,
39
- next: 'Wait for the join to finish; it starts the daemon again itself. If it is stuck, `crtr sys daemon start --force`.',
40
- });
41
- }
42
- /** Resolve once no other live process holds the join lock, or after `timeoutMs`. For a start that must happen
43
- * but must read the settings a join is about to commit (a daemon handover's successor): it waits the join out
44
- * instead of bypassing the lock, so nothing but the join starts a daemon while the lock is held. */
45
- export async function awaitJoinLockRelease(timeoutMs, pollMs = 100) {
46
- const deadline = Date.now() + timeoutMs;
47
- for (;;) {
48
- const holder = joinLockHolder();
49
- if (holder === null || holder === process.pid || Date.now() >= deadline)
50
- return;
51
- await new Promise((resolve) => setTimeout(resolve, pollMs));
52
- }
53
- }
54
- /** Run `operation` holding the join lock. Throws `join_in_progress` when a live process holds it. */
55
- export async function withJoinLock(operation) {
56
- mkdirSync(crtrHome(), { recursive: true });
57
- return withExclusiveDirectoryLockAsync(joinLockPath(), operation, {
58
- timeoutMs: ACQUIRE_WAIT_MS,
59
- timeoutError: () => joinInProgressError(joinLockHolder()),
60
- });
61
- }