@north-light/api 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 (34) hide show
  1. package/dist/api/client.d.ts +3 -2
  2. package/dist/api/client.js +4 -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 +11 -0
  7. package/dist/clients/attach/overlays/graph.d.ts +2 -0
  8. package/dist/clients/attach/overlays/graph.js +18 -1
  9. package/dist/commands/sys/daemon.js +1 -3
  10. package/dist/commands/sys/import/move.d.ts +2 -0
  11. package/dist/commands/sys/import/move.js +12 -0
  12. package/dist/commands/sys/join.js +5 -37
  13. package/dist/commands/sys/signin.js +6 -4
  14. package/dist/core/canvas/canvas.d.ts +1 -1
  15. package/dist/core/canvas/canvas.js +7 -3
  16. package/dist/core/canvas/history.d.ts +1 -1
  17. package/dist/core/canvas/history.js +3 -3
  18. package/dist/core/canvas/tree.d.ts +4 -0
  19. package/dist/core/canvas/tree.js +20 -0
  20. package/dist/core/conversation-store/row-store.js +7 -2
  21. package/dist/core/directory/join.d.ts +6 -26
  22. package/dist/core/directory/join.js +35 -86
  23. package/dist/core/environment-starter-script.d.ts +1 -1
  24. package/dist/core/environment-starter-script.js +4 -1
  25. package/dist/core/grants/sync.js +1 -1
  26. package/dist/core/providers/call.js +1 -1
  27. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  28. package/dist/core/runtime/runner/blaxel/image-build.js +4 -1
  29. package/dist/core/storage/client.js +1 -1
  30. package/dist/daemon/manage.d.ts +2 -7
  31. package/dist/daemon/manage.js +2 -16
  32. package/package.json +1 -1
  33. package/dist/core/directory/join-lock.d.ts +0 -13
  34. package/dist/core/directory/join-lock.js +0 -61
@@ -528,8 +528,9 @@ export declare class CrtrClient {
528
528
  * decompresses it because socketFetch does not interpret content-encoding. */
529
529
  canvasBrowseCompressed(): Promise<Uint8Array>;
530
530
  /** The lean attach-graph projection: display rows, topology, and focus state
531
- * in one daemon-owned read rather than the full node-summary list. */
532
- canvasGraph(): Promise<GraphDTO>;
531
+ * in one daemon-owned read rather than the full node-summary list. With
532
+ * `root`, only the tree that contains that node. */
533
+ canvasGraph(root?: string): Promise<GraphDTO>;
533
534
  prune(req: PruneRequest): Promise<PruneResultDTO>;
534
535
  /** Raw request for routes not yet method-wrapped. Applies the same
535
536
  * autostart + retry + error-mapping semantics. */
@@ -985,9 +985,10 @@ export class CrtrClient {
985
985
  return new Uint8Array(await response.arrayBuffer());
986
986
  }
987
987
  /** The lean attach-graph projection: display rows, topology, and focus state
988
- * in one daemon-owned read rather than the full node-summary list. */
989
- canvasGraph() {
990
- return this.request('GET', routes.canvasGraph());
988
+ * in one daemon-owned read rather than the full node-summary list. With
989
+ * `root`, only the tree that contains that node. */
990
+ canvasGraph(root) {
991
+ return this.request('GET', root === undefined ? routes.canvasGraph() : `${routes.canvasGraph()}?root=${encodeURIComponent(root)}`);
991
992
  }
992
993
  prune(req) {
993
994
  return this.request('POST', routes.canvasPrune(), req);
@@ -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.71";
2
+ export declare const CONTRACT_LEVEL = "1.72";
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.71';
15
+ export const CONTRACT_LEVEL = '1.72';
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`. */
@@ -43,6 +43,11 @@ export { APIError as ApiError };
43
43
  /** A local API transport failure has stable status/code identity, independent
44
44
  * of message prose. */
45
45
  export declare function isDaemonTransportApiError(error: unknown): error is APIError;
46
+ /** A daemon answer that says nothing about the caller's data: the daemon was unreachable, starting, draining for a
47
+ * restart (503 `startup_blocked`), overloaded, or failed server-side. Retrying the same request later can succeed, so a
48
+ * long-lived caller (a broker's inbox poll) retries it rather than treating it as corrupt state. A 4xx other than
49
+ * 408/429 is about the request itself and is not transient. */
50
+ export declare function isTransientDaemonApiError(error: unknown): error is APIError;
46
51
  /** The daemon refused the caller's node token. A teardown revokes the broker's token before its process stops, so a broker
47
52
  * that sees this on a poll is being shut down, not hitting a corrupt state. */
48
53
  export declare function isTokenRevokedApiError(error: unknown): error is APIError;
@@ -55,6 +55,17 @@ export function isDaemonTransportApiError(error) {
55
55
  || error.code === 'northlight_unreachable')) || (error.status === 504 && (error.code === 'request_timeout' || error.code === 'deadline_exceeded'))
56
56
  || (error.status >= 500 && error.code === 'daemon_health_unavailable');
57
57
  }
58
+ /** A daemon answer that says nothing about the caller's data: the daemon was unreachable, starting, draining for a
59
+ * restart (503 `startup_blocked`), overloaded, or failed server-side. Retrying the same request later can succeed, so a
60
+ * long-lived caller (a broker's inbox poll) retries it rather than treating it as corrupt state. A 4xx other than
61
+ * 408/429 is about the request itself and is not transient. */
62
+ export function isTransientDaemonApiError(error) {
63
+ if (!(error instanceof APIError))
64
+ return false;
65
+ const { status, code, retryable } = error;
66
+ return isDaemonTransportApiError(error) || retryable === true || code === 'startup_blocked'
67
+ || status === 408 || status === 429 || status >= 500;
68
+ }
58
69
  /** The daemon refused the caller's node token. A teardown revokes the broker's token before its process stops, so a broker
59
70
  * that sees this on a poll is being shut down, not hitting a corrupt state. */
60
71
  export function isTokenRevokedApiError(error) {
@@ -27,6 +27,8 @@ export declare class GraphOverlay implements Component {
27
27
  private pendingConfirm;
28
28
  private snapshot;
29
29
  private snapshotSeq;
30
+ private loading;
31
+ private reloadQueued;
30
32
  /** True when `source` is a `RemoteCanvasSource` — gates every local disk/
31
33
  * SQLite adornment (tokens, activity, fault, attach, focus) to a safe
32
34
  * default and makes Enter/r/m/x no-op instead of shelling local lifecycle
@@ -124,6 +124,8 @@ export class GraphOverlay {
124
124
  pendingConfirm;
125
125
  snapshot;
126
126
  snapshotSeq = 0;
127
+ loading = false;
128
+ reloadQueued = false;
127
129
  /** True when `source` is a `RemoteCanvasSource` — gates every local disk/
128
130
  * SQLite adornment (tokens, activity, fault, attach, focus) to a safe
129
131
  * default and makes Enter/r/m/x no-op instead of shelling local lifecycle
@@ -202,6 +204,15 @@ export class GraphOverlay {
202
204
  refresh() {
203
205
  if (this.handle === undefined)
204
206
  return;
207
+ // One read at a time. The 5 s chrome poll calls this; when a read takes
208
+ // longer than the poll, superseding the in-flight read discarded every
209
+ // result and the overlay never left "loading". Instead, let the read finish
210
+ // and run one more afterwards.
211
+ if (this.loading) {
212
+ this.reloadQueued = true;
213
+ return;
214
+ }
215
+ this.loading = true;
205
216
  const seq = ++this.snapshotSeq;
206
217
  void this.buildSnapshot().then((snapshot) => {
207
218
  if (seq !== this.snapshotSeq)
@@ -214,6 +225,12 @@ export class GraphOverlay {
214
225
  // writing raw stderr bytes into the frame.
215
226
  this.onRefreshFailure(err);
216
227
  this.tui.requestRender();
228
+ }).finally(() => {
229
+ this.loading = false;
230
+ if (this.reloadQueued) {
231
+ this.reloadQueued = false;
232
+ this.refresh();
233
+ }
217
234
  });
218
235
  }
219
236
  invalidate() {
@@ -234,7 +251,7 @@ export class GraphOverlay {
234
251
  focused: new Set(),
235
252
  };
236
253
  }
237
- const graph = await cliClient().canvasGraph();
254
+ const graph = await cliClient().canvasGraph(this.self);
238
255
  const subscriptions = new Map();
239
256
  const subscribers = new Map();
240
257
  // Edges arrive in `created` order — the same order the per-node reads
@@ -26,7 +26,6 @@ const daemonStart = defineLeaf({
26
26
  summary: 'start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)',
27
27
  params: [
28
28
  { kind: 'flag', name: 'prepare', type: 'bool', required: false, constraint: 'Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup.' },
29
- { kind: 'flag', name: 'force', type: 'bool', required: false, default: false, constraint: 'Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck.' },
30
29
  ],
31
30
  output: [
32
31
  { name: 'started', type: 'boolean', required: true, constraint: 'True when a new daemon process was spawned; false when one was already running.' },
@@ -39,14 +38,13 @@ const daemonStart = defineLeaf({
39
38
  ],
40
39
  outputKind: 'object',
41
40
  effects: [
42
- 'Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.',
43
41
  'Spawns dist/daemon/crtrd-cli.js detached + unref\'d; it outlives this process.',
44
42
  'Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid.'
45
43
  ],
46
44
  },
47
45
  run: async (input) => {
48
46
  try {
49
- const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready', ignoreJoinLock: input.force === true });
47
+ const result = await spawnDaemon({ targetPhase: input.prepare === true ? 'prepared' : 'ready' });
50
48
  return result;
51
49
  }
52
50
  catch (error) {
@@ -26,6 +26,8 @@ export declare function exportRun(kind: 'machine' | 'hosted', cloud: ImportCloud
26
26
  * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
27
27
  * crtrd in machine role, and the move record's deletion. Safe to repeat. */
28
28
  export declare function finishMove(move: MoveRecord): Promise<void>;
29
+ /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
30
+ export declare function registerThisMac(directoryUrl: string): Promise<void>;
29
31
  /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
30
32
  * sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
31
33
  * `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
@@ -17,6 +17,7 @@ import { buildSourceJson } from '../../../core/import/export/source.js';
17
17
  import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
18
18
  import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
19
19
  import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
20
+ import { registerSignedInMac } from '../../../core/directory/join.js';
20
21
  import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
21
22
  import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
22
23
  import { isPidAlive } from '../../../core/canvas/pid.js';
@@ -214,11 +215,22 @@ export async function finishMove(move) {
214
215
  }
215
216
  writeMachineCredential(credential.credential);
216
217
  writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
218
+ await registerThisMac(move.directoryUrl);
217
219
  await stopAllDaemons();
218
220
  await spawnDaemon();
219
221
  // Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
220
222
  deleteMoveRecord();
221
223
  }
224
+ /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
225
+ export async function registerThisMac(directoryUrl) {
226
+ try {
227
+ await registerSignedInMac(directoryUrl, await personBearer(directoryUrl));
228
+ }
229
+ catch (error) {
230
+ // A directory that predates person-credential registration refuses it; the move is done either way, and `crtr sys signin` again registers once the directory accepts.
231
+ process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
232
+ }
233
+ }
222
234
  const ACTIVATION_ATTEMPTS = 3;
223
235
  const ACTIVATION_GAP_MS = 30_000;
224
236
  /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
@@ -1,15 +1,8 @@
1
1
  // `crtr sys join` registers this runtime with its directory before the daemon starts.
2
2
  import { defineLeaf } from '../../core/command.js';
3
- import { existsSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { pluginsDir } from '../../core/scope.js';
6
3
  import { joinDirectory } from '../../core/directory/join.js';
7
- import { apiSocketPath } from '../../core/canvas/paths.js';
8
4
  import { listProcessTable } from '../../core/canvas/pid.js';
9
- import { daemonAnswers } from '../../core/layout-migrate/index.js';
10
5
  import { envNodeId } from '../../shared/env.js';
11
- import { isDaemonRunning } from '../../daemon/pidfile.js';
12
- import { findDaemonPids, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
13
6
  /** Whether a broker (a node's engine) is an ancestor of this process, or cannot be ruled out. Stopping the daemon kills every broker, so a join run from one would die mid-way. */
14
7
  export function insideBroker() {
15
8
  const table = listProcessTable();
@@ -27,33 +20,14 @@ export function insideBroker() {
27
20
  }
28
21
  return false;
29
22
  }
30
- /** Daemon control for a person's computer. A container whose daemon is the launcher's PID 1 keeps the offline contract. */
31
- function daemonControl() {
32
- if (process.platform === 'linux' && (process.env['CRTR_LAUNCHER_SOCKET'] || existsSync('/run/crtr/launcher.sock')))
33
- return undefined;
34
- return {
35
- // The process table too: a successor spawned just before the join took its lock has no pidfile or socket yet, but boots on the settings the join is about to replace.
36
- running: async () => isDaemonRunning() || findDaemonPids().length > 0 || await daemonAnswers(apiSocketPath()),
37
- stop: async () => { await stopAllDaemons(); },
38
- start: async () => { await spawnDaemon(); },
39
- // A bare `crtr cloud …` is an unknown command until a daemon's grant sync has installed the `cloud` plugin.
40
- firstSync: async () => {
41
- const dir = pluginsDir('user');
42
- const deadline = Date.now() + 20_000;
43
- while (dir && Date.now() < deadline && !existsSync(join(dir, 'cloud', 'commands.json')))
44
- await new Promise((resolve) => setTimeout(resolve, 250));
45
- },
46
- insideNode: insideBroker,
47
- };
48
- }
49
23
  export const sysJoinLeaf = defineLeaf({
50
24
  name: 'join',
51
- description: 'register this runtime with its directory using an enrollment token, offline',
52
- whenToUse: 'on your own computer, with a token from `<issuer>/account/machines`: run it from a plain terminal, with any viewers open. It stops the daemon, joins, and starts it again. Also at a hosted runtime\'s first boot, before the daemon starts, with the enrollment token provisioning passed in.',
25
+ description: 'register a hosted runtime with its directory using the provisioning enrollment token, before its daemon starts',
26
+ whenToUse: 'only at a hosted runtime\'s first boot, before the daemon starts, with the enrollment token provisioning passed in. A person\'s own computer registers through `crtr sys signin`.',
53
27
  help: {
54
28
  name: 'sys join',
55
29
  summary: 'exchange a directory enrollment token for a new runtime client key and record the returned identity',
56
- guide: 'Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon\'s next start replaces this install\'s person with the owner everywhere in canvas.db, sets the user settings `runtime.issuer` and `runtime.audience` from the key file, and rewrites the legacy local person\'s profile grantees to `app:terminal`, all before it serves anything. On your own computer a running daemon is no obstacle: join takes a `join.lock` in the runtime directory (so no open viewer\'s redial can autostart a daemon while it works), registers with the directory while the daemon still serves, stops the daemon, writes the identity, and starts the daemon again, whose start applies the change. Run it from a plain terminal, not from inside a node: a node\'s broker dies with the daemon, so join refuses `join_inside_node` instead. Where the launcher owns the daemon (a hosted container) join keeps the offline contract and refuses `daemon_running`. Presenting the token of the stored successful registration again finishes those local writes without calling the directory. Any other token generates a new key and registers again.',
30
+ guide: 'Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon\'s next start replaces this install\'s person with the owner everywhere in canvas.db and sets `runtime.issuer` and `runtime.audience` from the key file. It never touches a daemon: while one answers it refuses `daemon_running`. Presenting the token of the stored successful registration again finishes without calling the directory. Any other token generates a new key and registers again.',
57
31
  params: [
58
32
  { kind: 'flag', name: 'directory', type: 'string', required: true, constraint: 'Directory base URL (http or https) that minted the token.' },
59
33
  { kind: 'flag', name: 'token', type: 'string', required: true, sensitive: true, constraint: 'Single-use enrollment token. Sensitive: never echoed in output or errors.' },
@@ -67,19 +41,13 @@ export const sysJoinLeaf = defineLeaf({
67
41
  { name: 'canvas_rewrite', type: 'string', required: true, constraint: 'Always `next daemon start`: when canvas.db identity fields are rewritten.' },
68
42
  { name: 'url', type: 'string', required: true, constraint: 'Runtime URL, written to `runtime.audience`.' },
69
43
  { name: 'registered', type: 'boolean', required: true, constraint: 'False when the token matched the stored registration and the directory was not called.' },
70
- { name: 'daemon', type: 'string', required: true, constraint: '`restarted` (a daemon was stopped and started on the joined settings), `started` (none was running; join started one and waited, up to 20s, for its first grant sync to install the account\'s provider plugins, so `crtr cloud …` resolves), `not_running` (none was started: a hosted container\'s launcher owns its daemon), or `restart_failed` (joined, but the new daemon did not start: see `daemon_error`, then run `crtr sys daemon start`).' },
71
- { name: 'daemon_error', type: 'string', required: false, constraint: 'Why the new daemon did not start, with `daemon: restart_failed`.' },
72
44
  ],
73
45
  outputKind: 'object',
74
46
  effects: [
75
- 'Holds `<runtime>/join.lock` (its pid) from the start until the daemon is back; `ensureDaemon` and `sys daemon start` (without `--force`) decline to start a daemon while a live process holds it (including a start already in flight when the join began). A lock whose holder died is reclaimed.',
76
- 'A running daemon is stopped (SIGTERM, then SIGKILL, plus strays) after the directory accepts the registration and before the local writes, then started again. Every broker dies with it and is revived by the new daemon. If the join fails after the stop, the daemon is started again anyway. With no daemon running join starts one anyway, because a bare `crtr cloud …` is an unknown command (it never autostarts a daemon) until a daemon\'s grant sync has installed the provider plugins. Refuses `join_inside_node` when run from inside a node and a daemon is running; refuses `daemon_running` where a container launcher owns the daemon.',
77
47
  'On a new token: calls the directory once; on success writes `<runtime>/secrets/runtime-client.json` (mode 0600) with the private key, registration and the token\'s SHA-256, replacing any earlier key file. A refused or failed call writes nothing.',
78
48
  'Sends name, platform, crtr version, installed plugin ids and sandbox state with the public key. Before the request it writes `runtime-client.pending.json` (mode 0600); a rerun with the same token and directory reuses that key, so a lost reply is retried safely. The file is deleted on success or a refusal.',
79
- 'Sets `runtime.issuer` and `runtime.audience` in user settings. When the directory says this machine is not the account\'s default (`is_default: false`) it replaces the whole `runtime` setting with `{issuer, audience, unsandboxed: true}`: no app listener, and only `app:terminal` nodes run.',
80
- 'Rewrites the legacy local person\'s profile grantees to `app:terminal`.',
81
- 'At the next daemon start, before any listener, the person this install minted (or still the legacy local person) is replaced by the owner in every canvas.db column that holds a person: node, token, grant, cron, audit and usage subjects and grantees, the person\'s identity, and queued cron births. References to the install\'s local terminal grant are cleared and that local grant mirror is deleted so grant sync installs the directory\'s. Free text is unchanged. The start after that changes nothing.',
49
+ 'At the next daemon start, before any listener, the person this install minted is replaced by the owner in every canvas.db column that holds a person, and the legacy local person\'s profile grantees become `app:terminal`.',
82
50
  ],
83
51
  },
84
- run: async (input) => ({ ...(await joinDirectory(input['directory'], input['token'], input['name'] || undefined, daemonControl())), canvas_rewrite: 'next daemon start' }),
52
+ run: async (input) => ({ ...(await joinDirectory(input['directory'], input['token'], input['name'] || undefined)), canvas_rewrite: 'next daemon start' }),
85
53
  });
@@ -12,7 +12,7 @@ import { envNodeId } from '../../shared/env.js';
12
12
  import { ExitCode } from '../../types.js';
13
13
  import { insideBroker } from './join.js';
14
14
  import { cliClient } from '../api-client.js';
15
- import { defaultDirectoryUrl, finishMove, runMove, settleEarlierMove } from './import/move.js';
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. */
18
18
  function openBrowser(url) {
@@ -62,12 +62,12 @@ function startDetachedMove(notify) {
62
62
  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
63
  export const sysSigninLeaf = defineLeaf({
64
64
  name: 'signin',
65
- description: 'sign this computer\'s crtr in to the person\'s Northlight account',
65
+ description: 'sign this computer\'s crtr in to the person\'s Northlight account and register it as one of their machines',
66
66
  whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`',
67
67
  help: {
68
68
  name: 'sys signin',
69
- summary: 'pair this computer with the person\'s Northlight account in the browser, then move this computer\'s records into it',
70
- guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
69
+ summary: 'pair this computer with the person\'s Northlight account in the browser, move this computer\'s records into it, and register it with the directory',
70
+ guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account\'s move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account\'s machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
71
71
  params: [
72
72
  { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
73
73
  ],
@@ -81,6 +81,7 @@ export const sysSigninLeaf = defineLeaf({
81
81
  '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
82
  '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`.',
83
83
  'On a moved computer: restarts the daemon so it reconnects to Northlight.',
84
+ '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.',
84
85
  ],
85
86
  },
86
87
  run: async (input) => {
@@ -97,6 +98,7 @@ export const sysSigninLeaf = defineLeaf({
97
98
  const machine = readMachineConfig();
98
99
  if (machine !== undefined) {
99
100
  const { account } = await signIn(directoryUrl, showSignIn, { accept: sameAccountOnly(machine) });
101
+ await registerThisMac(directoryUrl);
100
102
  await stopAllDaemons();
101
103
  await spawnDaemon();
102
104
  return { account };
@@ -155,7 +155,7 @@ export interface GraphNodeRow {
155
155
  /** Stored fields the attach graph displays, plus the two live execution cues it
156
156
  * needs. This keeps the interactive graph off the full node-summary projection
157
157
  * and its unused runtime, outcome, and placement fields. */
158
- export declare function graphNodes(): Promise<GraphNodeRow[]>;
158
+ export declare function graphNodes(ids?: readonly string[]): Promise<GraphNodeRow[]>;
159
159
  export interface ListNodesFilter {
160
160
  status?: NodeStatus | NodeStatus[];
161
161
  withRecordedPid?: boolean;
@@ -582,8 +582,9 @@ export async function updateNodeTelemetry(nodeId, telemetry) {
582
582
  /** Stored fields the attach graph displays, plus the two live execution cues it
583
583
  * needs. This keeps the interactive graph off the full node-summary projection
584
584
  * and its unused runtime, outcome, and placement fields. */
585
- export async function graphNodes() {
586
- const rows = await (await openDb()).prepare(`SELECT
585
+ export async function graphNodes(ids) {
586
+ const db = await openDb();
587
+ const sql = `SELECT
587
588
  node_id, name, description, cycles, kind, status, frozen_at,
588
589
  telemetry_context_tokens, telemetry_last_activity,
589
590
  pi_pid, turn_open_at, turn_closed_at,
@@ -591,7 +592,10 @@ export async function graphNodes() {
591
592
  fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
592
593
  fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
593
594
  fault_provider_error_json
594
- FROM node_rows WHERE ${NOT_A_SPARE} ORDER BY created`).all();
595
+ FROM node_rows WHERE ${NOT_A_SPARE}${ids === undefined ? '' : ' AND node_id = ANY(?::text[])'} ORDER BY created`;
596
+ const rows = (ids === undefined
597
+ ? await db.prepare(sql).all()
598
+ : await db.prepareUncached(sql).all([...ids]));
595
599
  return rows.map((row) => {
596
600
  const pid = row['pi_pid'] ?? null;
597
601
  const pidAlive = isPidPresent(pid);
@@ -95,7 +95,7 @@ export interface ResolvedRef {
95
95
  /** Rendered body. */
96
96
  body: string;
97
97
  /** The verbatim record (session bytes or jsonl line); null for an inbox entry. */
98
- raw: string | null;
98
+ raw: (() => Promise<string | null>) | null;
99
99
  path: string | null;
100
100
  }
101
101
  /** Resolve a `<node-id>:inbox/<n>`, `<node-id>:session` or
@@ -454,10 +454,10 @@ export async function resolveRef(ref) {
454
454
  ts: messages[messages.length - 1]?.ts ?? node.created,
455
455
  nodeName: node.name,
456
456
  body: rendered,
457
- raw: await (async () => {
457
+ raw: async () => {
458
458
  const { header, entries } = await conversationStore().read(conversationIdFromPath(file));
459
459
  return [header, ...entries].map((entry) => `${JSON.stringify(entry)}\n`).join('');
460
- })(),
460
+ },
461
461
  path: file,
462
462
  };
463
463
  }
@@ -472,7 +472,7 @@ export async function resolveRef(ref) {
472
472
  ts: msg.ts,
473
473
  nodeName: node.name,
474
474
  body: msg.text,
475
- raw: await rawSessionLine(file, index),
475
+ raw: () => rawSessionLine(file, index),
476
476
  path: file,
477
477
  };
478
478
  }
@@ -18,6 +18,10 @@ export declare function unsubscribe(subscriber: string, publisher: string): Prom
18
18
  /** Rewrite the listening configuration of the pair's tree subscriptions: NULL (the watcher's
19
19
  * default) for active, `{"3":"next-turn"}` for passive. */
20
20
  export declare function setSubscriptionActive(subscriber: string, publisher: string, active: boolean): Promise<void>;
21
+ /** `node` and every node in the tree that contains it: climb first managers (oldest subscriber) to the top, then take that
22
+ * top node's whole subtree. The attach graph climbs the same way, so the tree it draws is exactly this set. Empty when `node`
23
+ * is not a node. */
24
+ export declare function treeContaining(node: string): Promise<string[]>;
21
25
  /** Who watches `publisher` in the tree — the targets a push fans out to. */
22
26
  export declare function subscribersOf(publisher: string): Promise<SubscriptionRef[]>;
23
27
  /** The nodes `subscriber` watches in the tree — its reports. */
@@ -84,6 +84,26 @@ export async function setSubscriptionActive(subscriber, publisher, active) {
84
84
  AND watch IN (SELECT watch_id FROM watches WHERE watcher = ? AND object = ?)`).run(active ? null : configToJson(PASSIVE), (await nodeObject(db, subscriber)).id, (await nodeObject(db, publisher)).id);
85
85
  });
86
86
  }
87
+ /** `node` and every node in the tree that contains it: climb first managers (oldest subscriber) to the top, then take that
88
+ * top node's whole subtree. The attach graph climbs the same way, so the tree it draws is exactly this set. Empty when `node`
89
+ * is not a node. */
90
+ export async function treeContaining(node) {
91
+ const db = await openDb();
92
+ const self = await getById(db, node);
93
+ if (self?.type !== 'node')
94
+ return [];
95
+ let top = self.id;
96
+ const seen = new Set([top]);
97
+ for (;;) {
98
+ const manager = (await treeEdges(db, 'AND oo.id = ?', top))[0]?.from_id;
99
+ if (manager === undefined || seen.has(manager))
100
+ break;
101
+ seen.add(manager);
102
+ top = manager;
103
+ }
104
+ const below = (await db.prepareUncached(SUBTREE_ALL_IDS_SQL).all(top, top)).map((r) => r.id);
105
+ return [top, ...below];
106
+ }
87
107
  /** Who watches `publisher` in the tree — the targets a push fans out to. */
88
108
  export async function subscribersOf(publisher) {
89
109
  return (await treeEdges(await openDb(), 'AND oo.id = ?', publisher)).map((e) => ({ node_id: e.from_id, active: e.active, created: e.created }));
@@ -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.
@@ -18,25 +18,8 @@ interface JoinedClient {
18
18
  }
19
19
  type Registration = Pick<JoinedClient, 'runtime' | 'client_id' | 'issuer' | 'owner' | 'url' | 'machine_id' | 'is_default'>;
20
20
  export interface JoinResult extends Registration {
21
- /** False when the token matched the stored successful registration and no directory call was made. */
21
+ /** False when the credential matched the stored successful registration and no directory call was made. */
22
22
  registered: boolean;
23
- /** `restarted`: a daemon was running, join stopped it and started a new one on the joined config. `started`: none was running and join started one, whose first grant sync installs the account's provider plugins (`crtr cloud …`). `not_running`: none was started (a hosted container's launcher owns its daemon). `restart_failed`: the join is committed but the new daemon did not start (see `daemon_error`). */
24
- daemon: 'restarted' | 'started' | 'not_running' | 'restart_failed';
25
- daemon_error?: string;
26
- }
27
- /** How join takes a running daemon down and brings it back. Absent, join keeps
28
- * the offline contract and refuses `daemon_running` while a daemon answers. */
29
- export interface JoinDaemonControl {
30
- /** Whether a daemon is running or answering on this runtime's socket. */
31
- running(): Promise<boolean>;
32
- /** Stop the daemon and every stray; resolves once none remains. */
33
- stop(): Promise<void>;
34
- /** Start a daemon on the settings now on disk and wait until it serves. */
35
- start(): Promise<void>;
36
- /** Waits, bounded, for a daemon that join started with none running to finish its first grant sync, which installs the account's provider plugins. Best effort: the join is committed either way. */
37
- firstSync?(): Promise<void>;
38
- /** Whether this process runs inside a node, whose broker the stop kills. */
39
- insideNode(): boolean;
40
23
  }
41
24
  /** Provider plugin ids installed on this machine (reported for display only). */
42
25
  export declare function installedPluginIds(): string[];
@@ -46,12 +29,9 @@ export declare function joinedOwner(): string | null;
46
29
  export declare function joinedIssuer(): string | null;
47
30
  /** The whole registration a successful join recorded, or null; a damaged file throws. */
48
31
  export declare function joinedClient(): Registration | null;
49
- /** Join this runtime to a directory.
50
- *
51
- * With `daemon` control, a running daemon is no obstacle: the join holds the
52
- * join lock (so no viewer's redial can autostart a daemon while it is down),
53
- * registers with the directory while the daemon still serves, stops the
54
- * daemon, writes the identity, and starts the daemon again so its start
55
- * applies the person change to canvas.db. Without it, a running daemon refuses. */
56
- export declare function joinDirectory(directory: string, token: string, name?: string, daemon?: JoinDaemonControl): Promise<JoinResult>;
32
+ /** A hosted runtime's first boot: register with the provisioning enrollment token before any daemon exists. Refuses `daemon_running` when one answers. */
33
+ export declare function joinDirectory(directory: string, token: string, name?: string): Promise<JoinResult>;
34
+ /** `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
35
+ * already holds a registration for this directory's owner (a join, or an earlier signin) is left as it is. */
36
+ export declare function registerSignedInMac(directory: string, bearer: string): Promise<JoinResult | null>;
57
37
  export {};
@@ -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
  }
@@ -1 +1 @@
1
- export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\" (home /home/crtr). Files you create for it must be chowned to it.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - 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.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
1
+ export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - 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\n# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.\n# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,\n# 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.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - 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.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
@@ -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)
@@ -25,6 +25,9 @@ export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
25
25
  /** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
26
26
  * variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
27
27
  export declare const RUN_USER_NPMRC: string[];
28
+ /** 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;
29
+ * 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). */
30
+ export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
28
31
  export declare const REPOS_DIR = "repos";
29
32
  /** 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`). */
30
33
  export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
@@ -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)
@@ -69,10 +69,6 @@ export declare function runDaemonInstallId(): Promise<{
69
69
  export interface SpawnDaemonOptions {
70
70
  /** The phase that proves a daemon launched by this call is available. */
71
71
  targetPhase?: 'ready' | 'prepared';
72
- /** Start even while another process's `crtr sys join` holds the daemon down. */
73
- ignoreJoinLock?: boolean;
74
- /** While another process's `crtr sys join` holds the daemon down, wait for it to finish, then start. For a handover successor. */
75
- waitForJoinLock?: boolean;
76
72
  }
77
73
  export interface SpawnDaemonResult {
78
74
  /** True when a new daemon process was spawned. */
@@ -172,7 +168,7 @@ export declare function waitForDaemonExit(pid: number, timeoutMs?: number, deps?
172
168
  * Returns how the daemon went down, for a truthful report. */
173
169
  export declare function stopDaemonProcess(pid: number, timeoutMs?: number, deps?: DaemonWaitDeps): Promise<'terminated' | 'killed'>;
174
170
  /** Stop the recorded daemon and sweep every stray crtrd of this canvas home.
175
- * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys join`. */
171
+ * Resolves once none remains. Shared by `crtr sys daemon stop` and `crtr sys signin`. */
176
172
  export declare function stopAllDaemons(): Promise<{
177
173
  stopped: boolean;
178
174
  pid?: number;
@@ -213,8 +209,7 @@ export interface EnsureDaemonDeps {
213
209
  * rather than at the end of the startup window. */
214
210
  export declare function daemonAutostartStartupFailure(): string | undefined;
215
211
  /** Start the daemon if it is not already running. No-op if already up, if
216
- * autostart is suppressed for this invocation, while `crtr sys join` holds
217
- * the join lock (see core/directory/join-lock.ts), while an attempt is in flight,
212
+ * autostart is suppressed for this invocation, while an attempt is in flight,
218
213
  * or while backing off from a recent failure.
219
214
  * Does not throw: a spawn error is recorded, and a launch or early-exit failure
220
215
  * is reported through `daemonAutostartStartupFailure()` so a waiting client
@@ -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)
package/package.json CHANGED
@@ -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,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,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
- }