@north-light/api 0.3.759 → 0.3.761

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 (39) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/error-codes.d.ts +5 -0
  4. package/dist/api/error-codes.js +2 -0
  5. package/dist/clients/attach/config.js +2 -1
  6. package/dist/commands/api-client.d.ts +0 -5
  7. package/dist/commands/api-client.js +1 -12
  8. package/dist/commands/sys/import/move.d.ts +1 -34
  9. package/dist/commands/sys/import/move.js +5 -205
  10. package/dist/commands/sys/import/start.d.ts +0 -3
  11. package/dist/commands/sys/import/start.js +15 -51
  12. package/dist/commands/sys/signin.js +13 -54
  13. package/dist/core/command-plugins/caller-header.d.ts +3 -1
  14. package/dist/core/command-plugins/caller-header.js +2 -2
  15. package/dist/core/command.d.ts +1 -1
  16. package/dist/core/grants/owner.d.ts +2 -0
  17. package/dist/core/grants/owner.js +6 -0
  18. package/dist/core/graph/reader.d.ts +5 -0
  19. package/dist/core/graph/reader.js +15 -1
  20. package/dist/core/graph/types.d.ts +2 -0
  21. package/dist/core/permissions/evaluator.js +2 -0
  22. package/dist/core/providers/call.js +11 -5
  23. package/dist/core/providers/errors.js +1 -0
  24. package/dist/core/providers/mint.d.ts +19 -0
  25. package/dist/core/providers/mint.js +58 -29
  26. package/dist/core/worktree-mutation-async.js +11 -3
  27. package/dist/core/worktree-scripts.d.ts +13 -0
  28. package/dist/core/worktree-scripts.js +72 -0
  29. package/dist/core/worktree-sweep.js +10 -1
  30. package/dist/daemon/api/reader.d.ts +1 -1
  31. package/dist/daemon/api/reader.js +10 -2
  32. package/dist/daemon/machine-link/config.d.ts +0 -24
  33. package/dist/daemon/machine-link/config.js +1 -27
  34. package/dist/daemon/manage.d.ts +1 -1
  35. package/package.json +1 -1
  36. package/dist/commands/sys/import/retry.d.ts +0 -1
  37. package/dist/commands/sys/import/retry.js +0 -38
  38. package/dist/daemon/machine-link/move-notify.d.ts +0 -4
  39. package/dist/daemon/machine-link/move-notify.js +0 -15
@@ -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.80";
2
+ export declare const CONTRACT_LEVEL = "1.81";
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.80';
15
+ export const CONTRACT_LEVEL = '1.81';
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`. */
@@ -39,6 +39,11 @@ export declare const errorCodes: {
39
39
  readonly status: 403;
40
40
  readonly retryable: false;
41
41
  };
42
+ readonly not_granted: {
43
+ readonly type: "permission_error";
44
+ readonly status: 403;
45
+ readonly retryable: false;
46
+ };
42
47
  readonly owner_only: {
43
48
  readonly type: "permission_error";
44
49
  readonly status: 403;
@@ -13,6 +13,8 @@ export const errorCodes = {
13
13
  refresh_token_expired: { type: 'authentication_error', status: 401, retryable: false },
14
14
  refresh_token_reused: { type: 'authentication_error', status: 401, retryable: false },
15
15
  scope_missing: { type: 'permission_error', status: 403, retryable: false },
16
+ // `--as` named an owner who has granted the caller nothing.
17
+ not_granted: { type: 'permission_error', status: 403, retryable: false },
16
18
  owner_only: { type: 'permission_error', status: 403, retryable: false },
17
19
  other_app_run: { type: 'permission_error', status: 403, retryable: false },
18
20
  payer_not_app: { type: 'permission_error', status: 403, retryable: false },
@@ -95,7 +95,8 @@ export function loadUserKeybindings(agentDir = defaultAgentDir()) {
95
95
  const ATTACH_KEYBINDING_OVERRIDES = {
96
96
  'tui.input.newLine': { defaultKeys: ['shift+enter', 'alt+enter'], description: 'Insert new line' },
97
97
  // Ctrl+K/U/D/J/G scroll the transcript (crtr.attach.scroll.*), so the editor gives them up.
98
- 'tui.editor.deleteToLineStart': { defaultKeys: [], description: 'Delete to line start' },
98
+ // Cmd+Delete arrives as super+backspace (CSI 127;9u) when the terminal or tmux sends it distinctly.
99
+ 'tui.editor.deleteToLineStart': { defaultKeys: ['super+backspace'], description: 'Delete to line start' },
99
100
  'tui.editor.deleteToLineEnd': { defaultKeys: [], description: 'Delete to line end' },
100
101
  'tui.editor.deleteCharForward': { defaultKeys: ['delete'], description: 'Delete character forward' },
101
102
  };
@@ -1,5 +1,4 @@
1
1
  import { CrtrClient } from '../api/index.js';
2
- import { CrtrError } from '../core/errors.js';
3
2
  import type { CanvasSource } from '../core/canvas/source.js';
4
3
  import type { NodeStatus, SubscriptionRef } from '../core/canvas/types.js';
5
4
  import type { Scope } from '../types.js';
@@ -46,10 +45,6 @@ export declare function remoteTarget(): {
46
45
  * a node on a Mac moved into Northlight (`machine.json`; its machine daemon serves no `/v1`) or a fleet node (`CRTR_API_URL` names the control plane).
47
46
  * `remoteTarget()` reports undefined for it because the transport is a local socket. */
48
47
  export declare function relayReachesControlPlane(): boolean;
49
- /** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
50
- * and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
51
- * is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
52
- export declare function moveUnfinished(): CrtrError | undefined;
53
48
  /** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
54
49
  * default: on a cold socket the injected `onColdSocket` hook fires
55
50
  * `ensureDaemon()` (spawns crtrd detached via the branded host), then the
@@ -20,7 +20,7 @@ import { gunzipSync } from 'node:zlib';
20
20
  import { CrtrClient, ApiError } from '../api/index.js';
21
21
  import { localClient } from '../api/node-transport.js';
22
22
  import { northlightFetch, notSignedIn, readPersonCredential } from '../core/directory/person-credential.js';
23
- import { isMoveCommitted, moveUnfinishedError, readMachineConfig } from '../daemon/machine-link/config.js';
23
+ import { readMachineConfig } from '../daemon/machine-link/config.js';
24
24
  import { northlightUnreachable } from '../core/directory/reach.js';
25
25
  import { apiErrorToCliError } from '../core/io.js';
26
26
  import { autostartDisabled, daemonAutostartStartupFailure, ensureDaemon } from '../daemon/manage.js';
@@ -169,12 +169,6 @@ function asApiError(error) {
169
169
  const next = typeof error.details?.['next'] === 'string' ? error.details['next'] : undefined;
170
170
  return new ApiError(error.exitCode === ExitCode.NETWORK ? 503 : 401, error.code, error.message, { error: error.code, message: error.message, ...(next === undefined ? {} : { next }) });
171
171
  }
172
- /** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
173
- * and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
174
- * is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
175
- export function moveUnfinished() {
176
- return isMoveCommitted() ? moveUnfinishedError() : undefined;
177
- }
178
172
  /** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
179
173
  * default: on a cold socket the injected `onColdSocket` hook fires
180
174
  * `ensureDaemon()` (spawns crtrd detached via the branded host), then the
@@ -190,11 +184,6 @@ export function moveUnfinished() {
190
184
  * Both callers use the shared startup policy so a valid on-disk migration
191
185
  * cannot outlast the initiating CLI command. */
192
186
  export function cliClient(opts) {
193
- if (opts?.local !== true) {
194
- const unfinished = moveUnfinished();
195
- if (unfinished !== undefined)
196
- throw unfinished;
197
- }
198
187
  if (opts?.local === true && relayReachesControlPlane()) {
199
188
  throw new CrtrError('no_local_daemon', 'this node reaches Northlight\'s shared control plane, not a daemon on this computer', ExitCode.USAGE, {
200
189
  next: 'Ask the person to run this in their own terminal on this computer.',
@@ -1,6 +1,4 @@
1
1
  import { ImportCloud } from '../../../core/import/export/cloud.js';
2
- import { type MoveRecord } from '../../../daemon/machine-link/config.js';
3
- import { type SignInPrompt } from '../../../core/directory/person-credential.js';
4
2
  /** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
5
3
  export declare function defaultDirectoryUrl(): string;
6
4
  /** End the daemon's drain and confirm the daemon answers `drained: false`, retrying a lost answer: the daemon persists its drain before it waits for
@@ -26,37 +24,6 @@ export interface ExportStep {
26
24
  }
27
25
  /** One export: open the run (or use hosting's), upload blobs, drain, dump, upload rows and stores, load, wait for `done`. `step.name` is the step in
28
26
  * progress, so a failure can name it. The drain ends here when the run did not reach `done`, and stays on when it did. */
29
- export declare function exportRun(kind: 'machine' | 'hosted', cloud: ImportCloud, existingRun: string | undefined, step: ExportStep, onStarted?: (runId: string) => void, onFailed?: () => void): Promise<string>;
30
- /** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
31
- * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
32
- * crtrd in machine role, and the move record's deletion. Safe to repeat. */
33
- export declare function finishMove(move: MoveRecord): Promise<void>;
27
+ export declare function exportRun(kind: 'hosted', cloud: ImportCloud, existingRun: string | undefined, step: ExportStep, onStarted?: (runId: string) => void, onFailed?: () => void): Promise<string>;
34
28
  /** 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. */
35
29
  export declare function registerThisMac(directoryUrl: string): Promise<void>;
36
- /** 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
37
- * 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
38
- * `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`. */
39
- export declare function runMove(opts: {
40
- directoryUrl: string;
41
- apiUrl?: string;
42
- notify: string | null;
43
- }): Promise<{
44
- runId: string;
45
- account: string;
46
- timings: string;
47
- }>;
48
- /** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
49
- * refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
50
- * `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
51
- * loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
52
- * the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
53
- * `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
54
- * Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
55
- export declare function settleEarlierMove(show?: (prompt: SignInPrompt & {
56
- complete: string;
57
- }) => void): Promise<MoveRecord | undefined>;
58
- /** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
59
- * a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
60
- * Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
61
- * for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
62
- export declare function settleMoveAtDaemonStart(stopped: () => boolean, onRetry: (error: unknown) => void): Promise<void>;
@@ -1,26 +1,21 @@
1
- // The exporter's run (design-import "Exporter") and the move of a person's computer into their Northlight account (design-crtr-northlight-signin
2
- // component 4): `exportRun` uploads, drains, dumps and loads one run; `runMove` wraps it for a computer with the move record, the two commit
3
- // boundaries (the cloud run reaching `done`; activation) and the messages to the node that asked; `finishMove` is activation, shared with
4
- // `crtr sys signin` finishing an unfinished switch-over.
1
+ // The hosted exporter's run (design-import "Exporter"): `exportRun` uploads, drains, dumps and loads one run. `registerThisMac` is `crtr sys signin`'s directory registration.
5
2
  import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
6
3
  import { tmpdir } from 'node:os';
7
4
  import { join } from 'node:path';
8
5
  import { CrtrError, general } from '../../../core/errors.js';
9
6
  import { ExitCode } from '../../../types.js';
10
7
  import { cliClient } from '../../api-client.js';
11
- import { ImportCloud, STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
8
+ import { STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
12
9
  import { Uploader, localObjects, reviewSourceObject } from '../../../core/import/export/files.js';
13
10
  import { BODIES_TABLE, bundleKeys } from '../../../core/import/bundle/layout.js';
14
11
  import { crtrVersion } from '../../../shared/crtr-version.js';
15
12
  import { nodeArchive } from '../../../core/import/export/archive.js';
16
13
  import { buildSourceJson } from '../../../core/import/export/source.js';
17
- import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId, spawnDaemon, stopAllDaemons } from '../../../daemon/manage.js';
18
- import { deleteMoveRecord, moveUnfinishedError, readMachineConfig, readMoveRecord, writeMachineConfig, writeMachineCredential, writeMoveRecord } from '../../../daemon/machine-link/config.js';
19
- import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
14
+ import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId } from '../../../daemon/manage.js';
15
+ import { readMachineConfig } from '../../../daemon/machine-link/config.js';
20
16
  import { registerSignedInMac } from '../../../core/directory/join.js';
21
- import { controlPlaneUrl, forgetSignIn, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../../core/directory/person-credential.js';
17
+ import { personBearer, readPersonCredential } from '../../../core/directory/person-credential.js';
22
18
  import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
23
- import { isPidAlive } from '../../../core/canvas/pid.js';
24
19
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
20
  /** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
26
21
  export function defaultDirectoryUrl() {
@@ -198,29 +193,6 @@ export async function exportRun(kind, cloud, existingRun, step, onStarted = () =
198
193
  }
199
194
  }
200
195
  }
201
- /** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
202
- * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
203
- * crtrd in machine role, and the move record's deletion. Safe to repeat. */
204
- export async function finishMove(move) {
205
- await notifyMoveFinished(move);
206
- const cloud = new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl));
207
- let credential;
208
- try {
209
- credential = await cloud.machineCredential(move.runId);
210
- }
211
- catch (error) {
212
- if (!(error instanceof CrtrError) || error.details?.['code'] !== 'credential_exists')
213
- throw error;
214
- credential = await cloud.machineCredential(move.runId, true);
215
- }
216
- writeMachineCredential(credential.credential);
217
- writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
218
- await registerThisMac(move.directoryUrl);
219
- await stopAllDaemons();
220
- await spawnDaemon();
221
- // Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
222
- deleteMoveRecord();
223
- }
224
196
  /** 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
197
  export async function registerThisMac(directoryUrl) {
226
198
  try {
@@ -231,175 +203,3 @@ export async function registerThisMac(directoryUrl) {
231
203
  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
204
  }
233
205
  }
234
- const ACTIVATION_ATTEMPTS = 3;
235
- const ACTIVATION_GAP_MS = 30_000;
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
237
- * 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
238
- * `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`. */
239
- export async function runMove(opts) {
240
- const step = { name: 'sign-in', timings: [] };
241
- let move;
242
- let runId = '';
243
- let base;
244
- try {
245
- const account = await personAccount(opts.directoryUrl);
246
- const apiUrl = opts.apiUrl ?? await controlPlaneUrl(opts.directoryUrl);
247
- const cloud = new ImportCloud(apiUrl, () => personBearer(opts.directoryUrl));
248
- base = { apiUrl, directoryUrl: opts.directoryUrl, account, notify: opts.notify, notified: false, pid: process.pid };
249
- await exportRun('machine', cloud, undefined, step, (id) => { runId = id; writeMoveRecord({ ...base, runId: id, state: 'running' }); }, deleteMoveRecord);
250
- }
251
- catch (error) {
252
- // Once `load` was sent and its outcome is unknown, the record and the drain stay: the next starter (`crtr sys signin`, the local daemon's start)
253
- // asks the control plane and settles the move.
254
- if (error instanceof CrtrError && error.code === 'move_outcome_unknown')
255
- throw error;
256
- throw await undoMove(step.name, error, opts.notify);
257
- }
258
- // The run is `done`: from here nothing may undo the move, so a failed record write is reported as it is and the `running` record settles to `committed` later.
259
- move = { ...base, runId, state: 'committed' };
260
- writeMoveRecord(move);
261
- let last;
262
- const activating = Date.now();
263
- for (let attempt = 1; attempt <= ACTIVATION_ATTEMPTS; attempt++) {
264
- try {
265
- await finishMove(move);
266
- step.timings.push(`restart=${((Date.now() - activating) / 1000).toFixed(1)}s`);
267
- process.stderr.write(`restart ${((Date.now() - activating) / 1000).toFixed(1)}s\n`);
268
- return { runId: move.runId, account: move.account.display, timings: step.timings.join(' ') };
269
- }
270
- catch (error) {
271
- last = error;
272
- process.stderr.write(`switch-over attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}\n`);
273
- if (attempt < ACTIVATION_ATTEMPTS)
274
- await sleep(ACTIVATION_GAP_MS);
275
- move = readMoveRecord() ?? move;
276
- }
277
- }
278
- throw moveUnfinishedError(last instanceof Error ? last.message : String(last));
279
- }
280
- /** Undo a move that never reached `done` (the drain is already confirmed ended), tell the asking node, and return the error to throw. */
281
- async function undoMove(step, error, notify) {
282
- const reason = error instanceof Error ? error.message : String(error);
283
- const still = error instanceof CrtrError && error.code === 'drain_not_ended' ? 'crtr is still local, but its pause could not be ended: run `crtr sys import resume`' : 'crtr is still local and working as before';
284
- const failed = `The move to Northlight failed at ${step}: ${reason}. ${still}.`;
285
- const revokeFailure = await dropMove(failed, notify);
286
- const code = error instanceof CrtrError && error.code !== 'error' ? error.code : (error instanceof CrtrError && typeof error.details?.['code'] === 'string' ? error.details['code'] : 'move_failed');
287
- return new CrtrError(code, `the move to Northlight failed at ${step}: ${reason}. ${still}, and ${signedOutText(revokeFailure)}`, ExitCode.GENERAL);
288
- }
289
- /** What the person is told about the sign-in a failed move removes: revoked at Northlight, or removed here only. */
290
- const signedOutText = (revokeFailure) => revokeFailure === undefined ? 'this computer is signed out.' : `this computer's sign-in was removed here but could not be revoked at Northlight (${revokeFailure}); revoke it on your Northlight account page.`;
291
- /** The shared end of a failed move: delete the record, sign this computer out, and tell the node that asked (a failed revoke is added to its
292
- * message). Returns why the sign-in could not be revoked at Northlight, or undefined when it was revoked or already ended: the secret is deleted here either way,
293
- * so a failed revoke leaves one that is still valid there. */
294
- async function dropMove(message, notify) {
295
- deleteMoveRecord();
296
- let revokeFailure;
297
- try {
298
- await signOut();
299
- }
300
- catch (error) {
301
- forgetSignIn();
302
- revokeFailure = error instanceof Error ? error.message : String(error);
303
- process.stderr.write(`could not revoke the sign-in at Northlight: ${revokeFailure}\n`);
304
- }
305
- if (notify === null)
306
- return revokeFailure;
307
- try {
308
- await cliClient({ local: true }).sendMessage(notify, { from: null, body: `${message} Tell the person the move failed.${revokeFailure === undefined ? '' : ` ${signedOutText(revokeFailure)}`}` });
309
- }
310
- catch (sendError) {
311
- process.stderr.write(`could not message ${notify}: ${sendError instanceof Error ? sendError.message : String(sendError)}\n`);
312
- }
313
- return revokeFailure;
314
- }
315
- /** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
316
- * refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
317
- * `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
318
- * loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
319
- * the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
320
- * `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
321
- * Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
322
- export async function settleEarlierMove(show) {
323
- const move = readMoveRecord();
324
- if (move === undefined || move.state === 'activated')
325
- return undefined;
326
- const signBackIn = async () => {
327
- await signIn(move.directoryUrl, show, { accept: async (approved) => approved.account.id === move.account.id ? undefined
328
- : new CrtrError('signin_other_account', `This computer's move belongs to the Northlight account ${move.account.display}. Sign in to that account.`, ExitCode.USAGE) });
329
- };
330
- if (move.state === 'committed') {
331
- if (show !== undefined) {
332
- try {
333
- await personAccount(move.directoryUrl);
334
- }
335
- catch (error) {
336
- if (!(error instanceof CrtrError && error.code === 'not_signed_in'))
337
- throw error;
338
- await signBackIn();
339
- }
340
- }
341
- return move;
342
- }
343
- if (move.pid > 0 && isPidAlive(move.pid)) {
344
- throw new CrtrError('move_running', `a move to Northlight is already running (process ${move.pid}).`, ExitCode.USAGE, { next: 'Wait for it to finish; the node that asked is messaged when it does.' });
345
- }
346
- const ask = () => new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl)).get(move.runId);
347
- let run;
348
- try {
349
- run = await ask();
350
- }
351
- catch (error) {
352
- if (!(error instanceof CrtrError && error.code === 'not_signed_in') || show === undefined)
353
- throw error;
354
- await signBackIn();
355
- run = await ask();
356
- }
357
- if (run.state === 'done') {
358
- const committed = { ...move, state: 'committed' };
359
- writeMoveRecord(committed);
360
- return committed;
361
- }
362
- if (run.state === 'loading' || run.state === 'committed') {
363
- throw new CrtrError('move_running', 'Northlight is still loading this computer\'s records from an earlier move.', ExitCode.USAGE, { next: 'Retry in a minute.' });
364
- }
365
- if (run.state !== 'failed' && run.state !== 'rolled_back' && run.state !== 'uploading') {
366
- throw new CrtrError('move_outcome_unknown', 'Northlight did not report a settled outcome for this move.', ExitCode.GENERAL, { next: 'Run `crtr sys signin` to settle the move.' });
367
- }
368
- const step = run.failure?.step ?? 'an earlier step';
369
- const reason = run.failure == null ? 'the process that was moving this computer stopped before Northlight had the records' : run.failure.message;
370
- deleteMoveRecord();
371
- try {
372
- await endDrainConfirmed(cliClient({ local: true }));
373
- }
374
- catch (error) {
375
- throw await undoMove(step, new CrtrError('drain_not_ended', `${reason} (and ${error instanceof Error ? error.message : String(error)})`, ExitCode.GENERAL), move.notify);
376
- }
377
- await dropMove(`The move to Northlight failed at ${step}: ${reason}. crtr is still local and working as before.`, move.notify);
378
- return undefined;
379
- }
380
- const DAEMON_SETTLE_GAP_MS = 60_000;
381
- /** The daemon answers its own socket only once startup is done, which is a moment after the settle is scheduled. */
382
- const DAEMON_SETTLE_FIRST_MS = 5_000;
383
- /** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
384
- * a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
385
- * Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
386
- * for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
387
- export async function settleMoveAtDaemonStart(stopped, onRetry) {
388
- await sleep(DAEMON_SETTLE_FIRST_MS);
389
- while (!stopped()) {
390
- const move = readMoveRecord();
391
- if (move === undefined || move.state !== 'running' || (move.pid > 0 && isPidAlive(move.pid)))
392
- return;
393
- try {
394
- await settleEarlierMove();
395
- return;
396
- }
397
- catch (error) {
398
- onRetry(error);
399
- // No working sign-in: only the person signing back in (`crtr sys signin`) can settle it, so asking again every minute cannot help.
400
- if (error instanceof CrtrError && error.code === 'not_signed_in')
401
- return;
402
- }
403
- await sleep(DAEMON_SETTLE_GAP_MS);
404
- }
405
- }
@@ -1,4 +1 @@
1
- /** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
2
- * so it is never in a broker's process tree. */
3
- export declare const WAIT_FOR_PID_ENV = "CRTR_IMPORT_WAIT_PID";
4
1
  export declare const sysImportBranch: import("../../../core/command.js").BranchDef;
@@ -1,36 +1,25 @@
1
1
  // `crtr sys import start`: the source side of an import (design-import, "Exporter"). Uploads blobs, drains the daemon, dumps the rows and file
2
- // stores, uploads them, asks the control plane to load, and on a computer switches this install to the machine role (`./move.ts`).
2
+ // stores, uploads them, asks the control plane to load, and (`./move.ts`).
3
3
  import { defineBranch, defineLeaf } from '../../../core/command.js';
4
4
  import { general, usage } from '../../../core/errors.js';
5
5
  import { ImportCloud } from '../../../core/import/export/cloud.js';
6
6
  import { ensureSignedIn } from '../../../core/directory/person-credential.js';
7
- import { isPidAlive } from '../../../core/canvas/pid.js';
8
7
  import { showSignIn } from '../signin.js';
9
8
  import { insideBroker } from '../join.js';
10
- import { defaultDirectoryUrl, exportRun, settleEarlierMove, finishMove, runMove } from './move.js';
9
+ import { defaultDirectoryUrl, exportRun } from './move.js';
11
10
  import { resume } from './resume.js';
12
- import { retry } from './retry.js';
13
- /** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
14
- * so it is never in a broker's process tree. */
15
- export const WAIT_FOR_PID_ENV = 'CRTR_IMPORT_WAIT_PID';
16
- async function waitForExit(pid) {
17
- while (isPidAlive(pid))
18
- await new Promise((resolve) => setTimeout(resolve, 200));
19
- }
20
11
  const start = defineLeaf({
21
12
  name: 'start',
22
- description: 'export this runtime into the person\'s Northlight account',
23
- whenToUse: 'moving this computer or hosted runtime\'s canvas into Northlight: run it from a plain terminal, not from inside a node',
13
+ description: 'export this hosted runtime into the person\'s Northlight account',
14
+ whenToUse: 'hosting runs it inside a hosted runtime to move that runtime\'s canvas into Northlight: from a plain terminal, not from inside a node',
24
15
  help: {
25
16
  name: 'sys import start',
26
17
  summary: 'upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them',
27
- guide: 'Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before; a computer\'s move also signs it out. On `done` the daemon stays drained: a hosted runtime until hosting quiesces it (`crtr sys import resume` ends it), a computer until it has switched over — machine credential, `runtime/machine.json`, daemon restarted in machine role — which is retried three times over a minute and otherwise finished by `crtr sys signin`. A machine import signs the person in first when this computer has no stored sign-in. `crtr sys signin` normally starts a computer\'s move itself. With `--run`, hosting has already opened the run: the exporter uses it and reads that run\'s import token from the environment variable `CRTR_IMPORT_TOKEN`.',
18
+ guide: 'Order: open the run (hosting already did, with `--run`), upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, archive running nodes\' files, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before. On `done` the daemon stays drained until hosting quiesces it (`crtr sys import resume` ends it). The run\'s import token is read from the environment variable `CRTR_IMPORT_TOKEN`.',
28
19
  params: [
29
- { kind: 'flag', name: 'kind', type: 'enum', choices: ['machine', 'hosted'], required: true, constraint: '`machine` for a person\'s computer, `hosted` for a hosted runtime (also archives running nodes\' files).' },
30
- { kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL (http or https). Required with `--kind hosted`; with `--kind machine` the default is the control plane the person\'s sign-in is for.' },
31
- { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`.' },
32
- { kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
33
- { kind: 'flag', name: 'notify', type: 'string', required: false, constraint: 'With `--kind machine`: a node id told by message when the move fails or finishes.' },
20
+ { kind: 'flag', name: 'kind', type: 'enum', choices: ['hosted'], required: true, constraint: '`hosted`, the only kind: a hosted runtime (also archives running nodes\' files).' },
21
+ { kind: 'flag', name: 'api-url', type: 'string', required: true, constraint: 'Control plane base URL (http or https) hosting opened the run on.' },
22
+ { kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime; its import token is read from `CRTR_IMPORT_TOKEN`.' },
34
23
  ],
35
24
  output: [
36
25
  { name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
@@ -40,41 +29,16 @@ const start = defineLeaf({
40
29
  outputKind: 'object',
41
30
  effects: [
42
31
  'Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.',
43
- 'Machine: writes `runtime/import/move.json` (0600) from the run\'s start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.',
44
- 'Machine with `--notify`: sends that node one message when the move fails or finishes.',
45
32
  'Opens a temporary directory holding the opened file stores (0600), removed before the command ends.',
46
33
  ],
47
34
  },
48
35
  run: async (input) => {
49
- const kind = input['kind'];
50
36
  const existingRun = input['run'] === undefined ? undefined : String(input['run']);
51
- const apiUrl = input.apiUrl === undefined ? undefined : String(input.apiUrl);
52
- const notify = input['notify'] === undefined ? null : String(input['notify']);
53
- if (kind === 'hosted') {
54
- if (apiUrl === undefined)
55
- throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
56
- if (notify !== null)
57
- throw usage('--notify names the node that asked for a computer\'s move: use it only with --kind machine');
58
- }
59
- else if (existingRun !== undefined) {
60
- throw usage('--run takes an existing run, which only a hosted import has: use --kind hosted');
61
- }
62
- const waitFor = Number(process.env[WAIT_FOR_PID_ENV] ?? '');
63
- if (Number.isInteger(waitFor) && waitFor > 0)
64
- await waitForExit(waitFor);
37
+ const apiUrl = String(input.apiUrl ?? '');
38
+ if (apiUrl === '')
39
+ throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
65
40
  if (insideBroker())
66
41
  throw general('import_inside_node: run this from a plain terminal; a node\'s broker ends with the daemon restart', { code: 'import_inside_node' });
67
- if (kind === 'machine') {
68
- const earlier = await settleEarlierMove(showSignIn);
69
- if (earlier !== undefined) {
70
- await finishMove(earlier);
71
- return { run_id: earlier.runId, state: 'done', timings: '' };
72
- }
73
- const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
74
- await ensureSignedIn(directoryUrl, showSignIn);
75
- const moved = await runMove({ directoryUrl, ...(apiUrl === undefined ? {} : { apiUrl }), notify });
76
- return { run_id: moved.runId, state: 'done', timings: moved.timings };
77
- }
78
42
  const token = (existingRun === undefined ? await ensureSignedIn(defaultDirectoryUrl(), showSignIn) : process.env['CRTR_IMPORT_TOKEN'] ?? '').trim();
79
43
  if (token === '')
80
44
  throw usage('set CRTR_IMPORT_TOKEN to the run\'s import token');
@@ -86,8 +50,8 @@ const start = defineLeaf({
86
50
  });
87
51
  export const sysImportBranch = defineBranch({
88
52
  name: 'import',
89
- description: 'move this runtime into the person\'s Northlight account',
90
- whenToUse: 'importing this computer or hosted runtime into Northlight',
91
- help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role.' },
92
- children: [start, resume, retry],
53
+ description: 'move this hosted runtime into the person\'s Northlight account',
54
+ whenToUse: 'importing a hosted runtime into Northlight',
55
+ help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database.' },
56
+ children: [start, resume],
93
57
  });