@north-light/cli 0.3.744 → 0.3.746

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 (75) hide show
  1. package/README.md +2 -2
  2. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
  3. package/dist/builtin-memory/crouter-sdk/README.md +1 -1
  4. package/dist/builtin-memory/crouter-sdk/client.md +1 -1
  5. package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
  6. package/dist/clients/attach/viewer.js +1 -1
  7. package/dist/commands/sys/provider-login.js +2 -2
  8. package/dist/commands/sys.js +1 -1
  9. package/dist/core/canvas/daemon-owner.d.ts +1 -1
  10. package/dist/core/canvas/paths.d.ts +1 -1
  11. package/dist/core/canvas/person-state.d.ts +3 -0
  12. package/dist/core/canvas/person-state.js +1 -1
  13. package/dist/core/canvas/person.d.ts +2 -3
  14. package/dist/core/canvas/person.js +7 -7
  15. package/dist/core/environments.d.ts +0 -10
  16. package/dist/core/environments.js +1 -1
  17. package/dist/core/import/load/prepare.d.ts +3 -0
  18. package/dist/core/import/load/prepare.js +14 -14
  19. package/dist/core/import/load/run.js +2 -2
  20. package/dist/core/runtime/blaxel-environment.js +1 -1
  21. package/dist/core/secrets.d.ts +2 -4
  22. package/dist/core/secrets.js +1 -1
  23. package/dist/core/spaces/space.js +2 -2
  24. package/dist/core/user-settings.js +1 -1
  25. package/dist/daemon/api/environment-of.d.ts +1 -1
  26. package/dist/daemon/api/environment-of.js +3 -3
  27. package/dist/daemon/api/handlers/document-access.js +1 -1
  28. package/dist/daemon/api/router.d.ts +1 -1
  29. package/dist/daemon/crtrd-cli.js +1 -1
  30. package/dist/daemon/crtrd.d.ts +4 -2
  31. package/dist/daemon/crtrd.js +20 -20
  32. package/dist/daemon/manage.d.ts +0 -8
  33. package/dist/daemon/manage.js +3 -3
  34. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  35. package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
  36. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  37. package/docs/concepts/scopes-and-trust.md +2 -2
  38. package/docs/public-api.md +1 -7
  39. package/docs/sdk/README.md +1 -1
  40. package/docs/sdk/client.md +1 -1
  41. package/docs/sdk/getting-started.md +3 -38
  42. package/package.json +3 -3
  43. package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
  44. package/packages/crouter-api/dist/commands/sys.js +1 -3
  45. package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
  46. package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
  47. package/packages/crouter-api/dist/core/canvas/person.js +2 -14
  48. package/packages/crouter-api/dist/core/environments.js +2 -38
  49. package/packages/crouter-api/dist/core/import/load/prepare.js +7 -0
  50. package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
  51. package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
  52. package/packages/crouter-api/dist/core/secrets.js +1 -11
  53. package/packages/crouter-api/dist/core/spaces/space.js +2 -2
  54. package/packages/crouter-api/dist/core/user-settings.js +1 -1
  55. package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
  56. package/packages/crouter-api/dist/daemon/manage.js +0 -4
  57. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  58. package/packages/crouter-api/package.json +1 -1
  59. package/packages/crouter-identity/package.json +1 -1
  60. package/packages/crouter-plugin/package.json +3 -3
  61. package/runtime.lock.json +14 -14
  62. package/dist/commands/sys/connect.d.ts +0 -1
  63. package/dist/commands/sys/connect.js +0 -3
  64. package/dist/commands/sys/db.d.ts +0 -1
  65. package/dist/commands/sys/db.js +0 -1
  66. package/dist/core/canvas/export-sqlite.d.ts +0 -14
  67. package/dist/core/canvas/export-sqlite.js +0 -3
  68. package/dist/daemon/api/document-listener.d.ts +0 -7
  69. package/dist/daemon/api/document-listener.js +0 -1
  70. package/dist/daemon/api/document-secret.d.ts +0 -2
  71. package/dist/daemon/api/document-secret.js +0 -1
  72. package/dist/daemon/export-sqlite-run.d.ts +0 -1
  73. package/dist/daemon/export-sqlite-run.js +0 -4
  74. package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
  75. package/packages/crouter-api/dist/commands/sys/db.js +0 -69
@@ -40,50 +40,15 @@ The SDK covers the app routes (`runs`, `uploads`, `docs`, `memory`, …). To cre
40
40
 
41
41
  ## 4. A browser or a remote application
42
42
 
43
- A process that is not on the daemon's machine — or a page in a browser, which has no unix sockets at all — reaches the daemon over TCP with a bearer token. There are two kinds. The **owner token** is the owner credential: whoever holds it can drive the whole surface. A **scoped token** (`crtr sys connect --app <id> --scopes …`) carries a list of scopes that caps what its holder and every run it creates may do.
44
-
45
- ### Turn the listener on, once
46
-
47
- On the machine running the daemon:
48
-
49
- ```bash
50
- crtr sys connect
51
- ```
52
-
53
- This stores a listener address and generates a token if either is missing, then prints the base URL and token before handing the daemon over to a successor that boots with the listener on. It then logs in to the selected model provider when that provider has no usable credential. Run it again and, when the listener is up and that provider is ready, it prints the credentials and changes nothing.
54
-
55
- The command returns `base_url` and `token`. Use JSON output when a program or a setup UI needs those exact fields:
56
-
57
- ```text
58
- $ crtr --json sys connect
59
- {"base_url":"http://127.0.0.1:8787","token":"<64-character bearer token>"}
60
- ```
61
-
62
- ### A token that holds less than the owner
63
-
64
- ```bash
65
- crtr sys connect --app my-app --scopes crtr:llm,crtr:act,crtr:memory:read:user
66
- ```
67
-
68
- `--scopes` requires `--app` (the app id, without the `app:` prefix) and accepts only `crtr:llm`, `crtr:act`, `crtr:schedule`, `crtr:memory:read:user`, `crtr:memory:read:app`, `crtr:memory:rw:app`, `crtr:files:read:user:.` and `crtr:files:rw:user:.`. This mints a new token for that app whose scope list is a ceiling, appends it to the same secrets store, prints it in place of the owner token, and always hands the daemon over (it reads tokens once, at boot). The ceiling is checked on every request that carries the token:
69
-
70
- - A scope-gated operation the ceiling lacks answers `403 scope_denied`. Starting or messaging a run, and creating, reviving, forking, messaging, or yielding a node, needs `crtr:act`, as do `bash`, `files`, and creating a human request or review (there is no separate scope for human requests); arming or running a cron needs `crtr:schedule`; `/v1/llm` needs `crtr:llm`. `client.memory` has no scope of its own: it reads the person's documents filtered by privacy, and a grant holding `crtr:memory:read_private:user` also sees `private` documents, and one holding `crtr:memory:manage:user` sees every level.
71
- - A run started with `scopes` outside the ceiling answers `403 scope_denied`; `details.scopes` lists the offending scopes. Omit `scopes` and the run gets the ceiling.
72
- - Owner-only operations — daemon restart, the attach viewer, broker internals, canvas prune, profile pause/resume/delete, model credential install — answer `403 owner_only` to any scoped token.
73
-
74
- What a scope does **not** do on a developer's machine: there is no OS sandbox. Scopes gate the daemon and the CLI; a run's own bash tool is ungated, and the daemon identifies a calling node by a field the caller declares, so a scope check bounds a well-behaved agent, not a hostile one. A scope the daemon does not check at any route is recorded on the run but not enforced; `sys connect` mints only the scopes listed above. There is no list or revoke verb yet; to retire a scoped token, remove it from the 0600 user secrets store and restart the daemon.
75
-
76
- ### Connect with the saved values
77
-
78
- Construct the client from the base URL and token the user pasted from `crtr sys connect`:
43
+ A process that is not on the daemon's machine — or a page in a browser, which has no unix sockets at all — reaches a daemon over TCP with a bearer token. A computer signed in with `crtr sys signin` is a fleet machine: its crtr commands go to the Northlight control plane with the person's bearer, and no local listener or owner token is created. Run a daemon with `--tcp <host:port>` and `CRTRD_TOKEN` only for your own control plane under development (`crtrd --role all` with `CRTR_DATABASE_URL` and `CRTR_DIRECTORY_URL`).
79
44
 
80
45
  ```ts
81
46
  import Crouter from '@north-light/sdk';
82
47
 
83
- const client = new Crouter({ baseURL: saved.baseURL, token: saved.token });
48
+ const client = new Crouter({ baseURL: process.env.CRTR_BASE_URL, token: process.env.CRTRD_TOKEN });
84
49
  ```
85
50
 
86
- A rejected token raises `AuthenticationError` and an unreachable listener raises `APIConnectionError`; in both cases ask the user to run `crtr sys connect` again and paste what it prints.
51
+ A rejected token raises `AuthenticationError` and an unreachable listener raises `APIConnectionError`.
87
52
 
88
53
  The root entry of the SDK is browser-safe: it imports nothing from `node:*`. The unix-socket code is reached only through a dynamic import taken when `socketPath` is set, so a browser bundle never resolves it.
89
54
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.744",
3
+ "version": "0.3.746",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.744",
162
- "@north-light/plugin": "0.3.744",
161
+ "@north-light/identity": "0.3.746",
162
+ "@north-light/plugin": "0.3.746",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -29,7 +29,7 @@ export async function loginProvider(runtime, providerId, interaction, options =
29
29
  throw new InputError({
30
30
  error: 'provider_login_unavailable',
31
31
  message: `provider ${providerId} has no OAuth login flow`,
32
- next: 'Configure an API key through `crtr sys setup`, then run `crtr sys connect` again.',
32
+ next: 'Configure an API key through `crtr sys setup`, then try again.',
33
33
  });
34
34
  const credential = await oauth.login(interaction);
35
35
  if (options.beforeInstall?.() === false)
@@ -70,7 +70,7 @@ async function promptTerminal(prompt) {
70
70
  throw new InputError({
71
71
  error: 'interactive_login_required',
72
72
  message: 'provider login requires an interactive terminal',
73
- next: 'Run `crtr sys connect` from an interactive terminal, or configure the provider credential through `crtr sys setup` first.',
73
+ next: 'Run this from an interactive terminal, or configure the provider credential through `crtr sys setup` first.',
74
74
  });
75
75
  const question = prompt.type === 'select'
76
76
  ? `${prompt.message}\n${prompt.options.map((option, index) => `${index + 1}. ${option.label}`).join('\n')}\nSelect: `
@@ -12,7 +12,6 @@ import { sysSpacesLeaf } from './sys/spaces.js';
12
12
  import { sysLimitsBranch } from './sys/limits.js';
13
13
  import { sysSpendBranch } from './sys/spend.js';
14
14
  import { sysSettingsLeaf } from './sys/settings.js';
15
- import { sysConnectLeaf } from './sys/connect.js';
16
15
  import { sysSetupLeaf } from './sys/setup.js';
17
16
  import { tutorialBranch } from './sys/tutorial/branch.js';
18
17
  import { supportBranch } from './sys/support.js';
@@ -20,12 +19,11 @@ import { contextBranch } from './sys/context.js';
20
19
  import { sysSyncBranch } from './sys/sync.js';
21
20
  import { sysMigrateLeaf } from './sys/migrate.js';
22
21
  import { sysJoinLeaf } from './sys/join.js';
23
- import { sysDbBranch } from './sys/db.js';
24
22
  import { sysImportBranch } from './sys/import/start.js';
25
23
  import { sysMachineBranch } from './sys/machine/rotate.js';
26
24
  import { sysDesktopBranch } from './sys/desktop.js';
27
25
  import { sysSigninLeaf, sysSignoutLeaf } from './sys/signin.js';
28
26
  import { sysUpdateLeaf, sysVersionLeaf } from './sys/update.js';
29
27
  export function registerSys() {
30
- return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysConnectLeaf, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysMigrateLeaf, sysJoinLeaf, sysSyncBranch, sysDbBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
28
+ return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysMigrateLeaf, sysJoinLeaf, sysSyncBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
31
29
  }
@@ -5,7 +5,7 @@ import { envGrantee, envNodeId } from '../../shared/env.js';
5
5
  import { withDirBeneath } from '../spaces/open-beneath.js';
6
6
  /** Runtime-owned records; never a bind source for an app sandbox. */
7
7
  export function crtrHome() { return runtimeRoot(); }
8
- /** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres and by `crtr sys db export-sqlite`. */
8
+ /** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres. */
9
9
  export function canvasDbPath() {
10
10
  return join(crtrHome(), 'canvas.db');
11
11
  }
@@ -21,6 +21,10 @@ export function setPersonId(id) { daemonPersonId = id; }
21
21
  export function markCloudRole() { cloudRole = true; }
22
22
  /** Whether this process is a cloud role (`markCloudRole` ran at boot). */
23
23
  export function isCloudRole() { return cloudRole; }
24
+ let enginesInProcess = false;
25
+ /** `crtrd --role all` (tests and crouter development) runs every node's engine on its own host: no Blaxel sandbox, no remote machine. */
26
+ export function markEnginesInProcess() { enginesInProcess = true; }
27
+ export function areEnginesInProcess() { return enginesInProcess; }
24
28
  /** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
25
29
  export function runAsPerson(person, fn) { return requestPersons.run(person, fn); }
26
30
  /** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
@@ -1,6 +1,5 @@
1
1
  // person.ts — the install's person (`user:<id>`), the one routine that replaces one person with another in every
2
2
  // known column, and the boot step that retires the legacy local person. Design: cycle 2 local identity.
3
- import { randomBytes } from 'node:crypto';
4
3
  import { CrtrError } from '../errors.js';
5
4
  import { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId, bootPersonId, requestPersonId } from './person-state.js';
6
5
  import { readConfig } from '../config.js';
@@ -15,7 +14,6 @@ export { LEGACY_LOCAL_PERSON };
15
14
  const PERSON_KEY = 'person_id';
16
15
  const RETIRED_KEY = 'local_person_retired';
17
16
  const PERSON_SHAPE = /^user:[A-Za-z0-9._-]+$/;
18
- const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
19
17
  export { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId };
20
18
  const lazyPersonByHome = new Map();
21
19
  /** As `personId()`, but a process that is not the daemon gets a lazy get-or-create keyed by the active canvas database. */
@@ -38,13 +36,6 @@ export async function personIdAsync() {
38
36
  lazyPersonByHome.set(home, resolved);
39
37
  return resolved;
40
38
  }
41
- function mintPersonId() {
42
- const bytes = randomBytes(12);
43
- let out = 'user:';
44
- for (let i = 0; i < 12; i++)
45
- out += ALPHABET[bytes[i] % ALPHABET.length];
46
- return out;
47
- }
48
39
  async function readMeta(db, key) {
49
40
  const row = await db.prepare('SELECT value FROM canvas_meta WHERE key = ?').get(key);
50
41
  return row?.value ?? null;
@@ -53,8 +44,7 @@ async function writeMeta(db, key, value) {
53
44
  await db.prepare('INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value);
54
45
  }
55
46
  /** Get-or-create the person and say where it came from. Order: stored, the join file's owner, the single `sub` of the
56
- * mirrored grants (a runtime with an issuer and no join file), else a minted id on a runtime without an issuer.
57
- * Null when an issuer runtime has no mirrored grants yet; nothing is stored then. */
47
+ * mirrored grants (a runtime with an issuer and no join file), else null (nothing is stored): no person is ever minted. */
58
48
  export async function resolvePerson() {
59
49
  return await withCanvasWrite(async (db) => {
60
50
  const stored = await readMeta(db, PERSON_KEY);
@@ -72,9 +62,7 @@ export async function resolvePerson() {
72
62
  await writeMeta(db, PERSON_KEY, subs[0].sub);
73
63
  return { id: subs[0].sub, source: 'grants' };
74
64
  }
75
- const minted = mintPersonId();
76
- await writeMeta(db, PERSON_KEY, minted);
77
- return { id: minted, source: 'minted' };
65
+ return null;
78
66
  });
79
67
  }
80
68
  export async function resolvePersonId() {
@@ -1,33 +1,9 @@
1
- /** The machine environment: an `environment` object (kind `machine`, owned by the terminal app) with an `environments`
2
- * sidecar row naming the install id, registered at every daemon boot and kept fresh by the storage-maintenance tick. */
3
- import { openDb, withCanvasWrite } from './canvas/db.js';
1
+ /** Environment rows: a cloud profile's own `blaxel` environment. */
2
+ import { withCanvasWrite } from './canvas/db.js';
4
3
  import { createObject, ensureOwner, ownerForGrantee } from './graph/objects.js';
5
4
  import { writeActsFor } from './permissions/facts.js';
6
- import { isCloudRole, personIdAsync } from './canvas/person.js';
7
5
  import { writeEnvironmentRecipe } from './environment-recipe.js';
8
6
  import { setCloudProfileWriter } from './profiles/manifest.js';
9
- let registered = null;
10
- /** Find the `environments` row for `installId`, or create its object and row; either way set `last_seen_at`, and cache
11
- * the environment id and install id for {@link machineEnvironmentId} and {@link touchMachineEnvironment}. */
12
- export async function registerMachineEnvironment(installId) {
13
- const now = new Date().toISOString();
14
- const result = await withCanvasWrite(async (db) => {
15
- const existing = await db.prepare('SELECT object FROM environments WHERE machine_id = ?').get(installId);
16
- if (existing !== undefined) {
17
- await db.prepare('UPDATE environments SET last_seen_at = ? WHERE machine_id = ?').run(now, installId);
18
- return { environmentId: existing.object, created: false };
19
- }
20
- const owner = await ownerForGrantee(db, 'app:terminal');
21
- const object = await createObject(db, { type: 'environment', kind: 'machine', owner: owner.id, privacy: 'public', name: installId, preview: 'machine' });
22
- // A cloud-role machine belongs to no person, so it acts for nobody.
23
- if (!isCloudRole())
24
- await writeActsFor(db, object.id, await personIdAsync());
25
- await db.prepare(`INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)`).run(object.id, installId, now);
26
- return { environmentId: object.id, created: true };
27
- });
28
- registered = { environmentId: result.environmentId, machineId: installId };
29
- return result;
30
- }
31
7
  /** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
32
8
  * its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
33
9
  * caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
@@ -43,17 +19,5 @@ export async function createProfileBlaxelEnvironment(db, spec) {
43
19
  await writeEnvironmentRecipe(db, object.id, spec.recipe);
44
20
  return object.id;
45
21
  }
46
- /** Stamp `last_seen_at` on the machine environment: one statement, no read. A no-op before {@link registerMachineEnvironment}. */
47
- export async function touchMachineEnvironment(now) {
48
- if (registered === null)
49
- return;
50
- await (await openDb()).prepare('UPDATE environments SET last_seen_at = ? WHERE machine_id = ?').run(now, registered.machineId);
51
- }
52
- /** The machine environment's object id; throws before {@link registerMachineEnvironment} has run. */
53
- export function machineEnvironmentId() {
54
- if (registered === null)
55
- throw new Error('the machine environment is not registered yet');
56
- return registered.environmentId;
57
- }
58
22
  // The daemon loads this file, which is what makes a cloud role's profile creation write the environment with the profile (D105).
59
23
  setCloudProfileWriter((spec, insert) => withCanvasWrite(async (db) => { await insert(await createProfileBlaxelEnvironment(db, spec)); }));
@@ -2,6 +2,7 @@
2
2
  // repo-synced documents, and the pre-check (design-import, "Import lane"). All SQL names the staging schema explicitly.
3
3
  import { createProfileBlaxelEnvironment } from '../../environments.js';
4
4
  import { KEY_MAPPED_TABLES, mapPath } from '../bundle/layout.js';
5
+ import { IDEMPOTENCY_WINDOW_MS } from '../../runs/operations.js';
5
6
  import { ImportLaneError } from './stage.js';
6
7
  import { withHeaderCwd } from '../../conversation-store/row-store.js';
7
8
  import { runBlobKey } from '../bundle/blob-keys.js';
@@ -126,6 +127,12 @@ export async function dropExistingIdempotencyKeys(db, schema, target) {
126
127
  const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} s WHERE EXISTS (SELECT 1 FROM ${sq(target, 'idempotency_keys')} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();
127
128
  return Number(done.changes);
128
129
  }
130
+ /** A staged idempotency key at least `IDEMPOTENCY_WINDOW_MS` old is already expired (`findIdempotent` ignores it and the daemon's sweep deletes it within a minute), so it is dropped before
131
+ * the copy: otherwise the sweep removes it between copy and verify and verify reports a difference. Returns the dropped rows. Runs before the pre-check. */
132
+ export async function dropExpiredIdempotencyKeys(db, schema) {
133
+ const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} WHERE created_at <= ?`).run(new Date(Date.now() - IDEMPOTENCY_WINDOW_MS).toISOString());
134
+ return Number(done.changes);
135
+ }
129
136
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
130
137
  * absent). Runs in the copy transaction: it writes target objects. */
131
138
  export async function fillEnvironments(tx, schema, target, source, person) {
@@ -1,6 +1,6 @@
1
1
  // Client side of daemon-run vendor sign-in (runtime spec §7, RT-LLM-24/41/45).
2
- // The attach viewer's /login, `crtr sys setup`'s Providers panel, the front door,
3
- // and `crtr sys connect` drive a managed provider's sign-in through
2
+ // The attach viewer's /login, `crtr sys setup`'s Providers panel, the front door
3
+ // drive a managed provider's sign-in through
4
4
  // `model_auth.start`/`complete` and never run vendor OAuth in their own process.
5
5
  // The caller's `ProviderAuthInteraction` (a LoginDialogComponent adapter or the
6
6
  // terminal one) only shows the URL/code and collects Anthropic's pasted code.
@@ -1,9 +1,9 @@
1
1
  import { openDb } from '../canvas/db.js';
2
- import { isCloudRole } from '../canvas/person-state.js';
2
+ import { areEnginesInProcess, isCloudRole } from '../canvas/person-state.js';
3
3
  import { machineEnvironmentOfProfile } from './runner/machine/environment.js';
4
4
  /** The Blaxel environment the node's profile points at, or null when it runs on a machine. Reads rows only, so it is safe before any environment is registered. A leaf module: the launch and run-start paths import it without pulling in the ledger. */
5
5
  export async function blaxelEnvironmentOf(profileId) {
6
- if (profileId === null)
6
+ if (profileId === null || areEnginesInProcess())
7
7
  return null;
8
8
  const row = await (await openDb()).prepare("SELECT e.object AS object FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ? AND e.kind = 'blaxel'").get(profileId);
9
9
  return row?.object ?? null;
@@ -13,5 +13,5 @@ export async function blaxelEnvironmentOf(profileId) {
13
13
  export async function remoteEnvironmentOf(profileId) {
14
14
  if (profileId === null)
15
15
  return null;
16
- return await blaxelEnvironmentOf(profileId) ?? (isCloudRole() ? await machineEnvironmentOfProfile(profileId) : null);
16
+ return await blaxelEnvironmentOf(profileId) ?? (isCloudRole() && !areEnginesInProcess() ? await machineEnvironmentOfProfile(profileId) : null);
17
17
  }
@@ -56,19 +56,9 @@ export function deleteRelayToken(ref, scope) {
56
56
  export function getApiToken(scope) {
57
57
  return readSecrets(scope).apiToken;
58
58
  }
59
- export function setApiToken(token, scope) {
60
- const s = readSecrets(scope);
61
- s.apiToken = token;
62
- writeSecrets(scope, s);
63
- }
64
59
  export function listScopedApiTokens(scope) {
65
60
  return readSecrets(scope).scopedApiTokens ?? [];
66
61
  }
67
- export function addScopedApiToken(entry, scope) {
68
- const s = readSecrets(scope);
69
- s.scopedApiTokens = [...(s.scopedApiTokens ?? []), entry];
70
- writeSecrets(scope, s);
71
- }
72
62
  const GRANTEE = /^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
73
63
  const APP_TOKEN_PREFIX = 'crtr_app_';
74
64
  function appGrantee(plugin) {
@@ -100,7 +90,7 @@ export function ensurePluginAppToken(plugin, scopes) {
100
90
  writeSecrets('user', store);
101
91
  return next;
102
92
  }
103
- /** Remove the plugin's `crtr_app_` tokens. Entries minted by `crtr sys connect` are never touched. */
93
+ /** Remove the plugin's `crtr_app_` tokens. Other entries are never touched. */
104
94
  export function revokePluginAppTokens(plugin) {
105
95
  const grantee = appGrantee(plugin);
106
96
  const store = readSecrets('user');
@@ -3,7 +3,7 @@ import { appSpace, appsRoot, userFilesRoot } from '../layout.js';
3
3
  import { launcherRequest } from '../../launcher/client.js';
4
4
  import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
5
5
  import { allocateAppUser, uidForApp } from './users.js';
6
- import { isCloudRole } from '../canvas/person-state.js';
6
+ import { areEnginesInProcess, isCloudRole } from '../canvas/person-state.js';
7
7
  function dataGroup() {
8
8
  const group = readFileSync('/etc/group', 'utf8').split('\n').find(line => line.startsWith('crtr-data:'));
9
9
  if (!group)
@@ -34,7 +34,7 @@ export function ensureUserFiles() {
34
34
  * or directory to prepare: a node's files live in its sandbox and in rows, so it answers the process's own ids and touches nothing. */
35
35
  export async function ensureAppSpace(app) {
36
36
  const space = appSpace(app);
37
- if (isCloudRole())
37
+ if (isCloudRole() && !areEnginesInProcess())
38
38
  return { uid: process.getuid(), gid: process.getgid(), root: space.root };
39
39
  const launcher = process.platform === 'linux' && existsSync(LAUNCHER_SOCKET);
40
40
  if (!launcher) {
@@ -403,7 +403,7 @@ export const CONFIG_SETTINGS_COVERAGE = {
403
403
  kinds: { surface: 'specialized', owner: 'Models tab and kind registry' },
404
404
  page_components: { surface: 'specialized', owner: 'Page component catalog: product-registered page component kinds' },
405
405
  remoteCanvas: { surface: 'specialized', owner: 'canvas config commands' },
406
- api: { surface: 'specialized', owner: 'sys connect' },
406
+ api: { surface: 'specialized', owner: 'daemon API listener' },
407
407
  paths: { surface: 'specialized', owner: 'runtime layout' },
408
408
  store: { surface: 'specialized', owner: 'daemon conversation store' },
409
409
  runtime: { surface: 'specialized', owner: 'app-facing listener' },
@@ -1,13 +1,14 @@
1
1
  // Which environment a node runs in, and that environment's recipe.
2
2
  import { ApiError } from '../../api/errors.js';
3
3
  import { openDb } from '../../core/canvas/db.js';
4
- import { machineEnvironmentId } from '../../core/environments.js';
5
- /** The environment object id a node runs in: its profile's `environment_id`, or the machine environment when it has none. */
4
+ /** The environment object id a node runs in: its profile's `environment_id`. A node whose profile names none is a defect: the environment is set when the profile is made. */
6
5
  export async function environmentOfNode(profileId) {
7
6
  if (profileId === null)
8
- return machineEnvironmentId();
7
+ throw new Error('a node with no profile has no environment');
9
8
  const row = await (await openDb()).prepare('SELECT environment_id FROM profiles WHERE id = ?').get(profileId);
10
- return row?.environment_id ?? machineEnvironmentId();
9
+ if (row?.environment_id == null)
10
+ throw new Error(`profile ${profileId} has no environment`);
11
+ return row.environment_id;
11
12
  }
12
13
  /** SQL predicate over `environments`: the recipe has content (a repository, a setup script or pi packages). A recipe cleared back to nothing
13
14
  * has none, whatever its `recipe_revision` counter says: the counter only orders edits, it does not say whether a recipe exists. */
@@ -36,6 +37,8 @@ export async function recipeOf(environmentId) {
36
37
  }
37
38
  /** True when the node runs in a Blaxel environment, where its sandbox is its worktree (D102). */
38
39
  export async function runsOnBlaxel(profileId) {
40
+ if (profileId === null)
41
+ return false;
39
42
  const row = await (await openDb()).prepare('SELECT kind FROM environments WHERE object = ?').get(await environmentOfNode(profileId));
40
43
  return row?.kind === 'blaxel';
41
44
  }
@@ -224,10 +224,6 @@ async function runDaemonEntry(args) {
224
224
  const line = stdout.trim().split('\n').at(-1) ?? '';
225
225
  return JSON.parse(line);
226
226
  }
227
- /** Run the selected generation's `crtrd-cli export-sqlite` and wait for it. */
228
- export function runDaemonExportSqlite() {
229
- return runDaemonEntry(['export-sqlite']);
230
- }
231
227
  /** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
232
228
  export function runDaemonImportDump(out, kind) {
233
229
  return runDaemonEntry(['import-dump', out, kind]);
@@ -3,7 +3,7 @@
3
3
  // recovery of a `launching` execution whose starter is gone. A node in a `machine` environment never reaches any of it.
4
4
  import { liveExecutionForNode, endExecution, recordExecutionAwake, endLaunchingExecution, requestExecutionStop } from '../../../core/canvas/executions.js';
5
5
  import { openDb } from '../../../core/canvas/db.js';
6
- import { isCloudRole } from '../../../core/canvas/person-state.js';
6
+ import { areEnginesInProcess, isCloudRole } from '../../../core/canvas/person-state.js';
7
7
  import { getRow, recordRespawnAttempt } from '../../../core/canvas/index.js';
8
8
  import { fullName } from '../../../core/canvas/labels.js';
9
9
  import { publishNotice } from '../../../core/runtime/close.js';
@@ -27,7 +27,7 @@ export const acceptedRelease = () => crtrVersion();
27
27
  /** The machine environment the node's profile points at when this process is a cloud role (the machine is another host, reached
28
28
  * through the remote machine runner), else null: a Mac's own crtrd runs its machine environment's nodes as processes. */
29
29
  export async function remoteMachineEnvironmentOf(profileId) {
30
- if (profileId === null || !isCloudRole())
30
+ if (profileId === null || !isCloudRole() || areEnginesInProcess())
31
31
  return null;
32
32
  return await machineEnvironmentOfProfile(profileId);
33
33
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.744",
3
+ "version": "0.3.746",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.744",
3
+ "version": "0.3.746",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.744",
3
+ "version": "0.3.746",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.744",
31
- "@north-light/identity": "0.3.744"
30
+ "@north-light/api": "0.3.746",
31
+ "@north-light/identity": "0.3.746"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.744",
3
+ "version": "0.3.746",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.744",
9
+ "version": "0.3.746",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.744",
32
- "@north-light/plugin": "0.3.744",
31
+ "@north-light/identity": "0.3.746",
32
+ "@north-light/plugin": "0.3.746",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.744",
11905
+ "version": "0.3.746",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.744",
11910
+ "version": "0.3.746",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.744",
11915
+ "version": "0.3.746",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.744",
11923
+ "version": "0.3.746",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.744",
11927
- "@north-light/identity": "0.3.744"
11926
+ "@north-light/api": "0.3.746",
11927
+ "@north-light/identity": "0.3.746"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.744",
11932
+ "version": "0.3.746",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.744",
11936
- "@north-light/identity": "0.3.744",
11937
- "@north-light/plugin": "0.3.744",
11935
+ "@north-light/api": "0.3.746",
11936
+ "@north-light/identity": "0.3.746",
11937
+ "@north-light/plugin": "0.3.746",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -1 +0,0 @@
1
- export declare const sysConnectLeaf: import("../../core/command.js").LeafDef;
@@ -1,3 +0,0 @@
1
- var x=Object.defineProperty;var i=(e,n)=>x(e,"name",{value:n,configurable:!0});import{randomBytes as P}from"node:crypto";import R from"node:path";import{defineLeaf as A}from"../../core/command.js";import{readConfig as k,updateConfig as y}from"../../core/config.js";import{emit as S,InputError as s,isJsonOutput as E}from"../../core/io.js";import{renderResult as L}from"../../core/render.js";import{addScopedApiToken as q,getApiToken as b,setApiToken as I}from"../../core/secrets.js";import{ENFORCED as c}from"@north-light/identity";import{envCrtrdTcp as D,envCrtrdToken as v,envNodeId as N}from"../../shared/env.js";import{shellQuote as p}from"../../shared/shell-quote.js";import{cliClient as T}from"../api-client.js";const O="127.0.0.1:8787",$=3e4,M=100;function C(){return P(32).toString("hex")}i(C,"token");function j(e){if(e===void 0)return;const n=String(e).split(",").map(t=>t.trim()).filter(t=>t!=="");if(n.length===0)throw new s({error:"empty_scopes",message:"--scopes names no scope",received:e,field:"scopes",next:`Pass a comma-separated list from ${[...c].join(", ")}; omit the flag for the owner token.`});for(const t of n)if(!c.has(t))throw new s({error:"invalid_scope",message:`invalid scope: ${t}`,field:"scopes",received:t,next:`Use one of ${[...c].join(", ")}.`});return n}i(j,"parseScopes");function U(e){E()?S(e):process.stdout.write(L(e,F.help)+`
2
- `)}i(U,"printCredentials");function W(e){const n=e.lastIndexOf(":");return n===-1||Number(e.slice(n+1))!==0?e:`${e.slice(0,n+1)}8787`}i(W,"fixedTcpPort");async function z(){const e=T(),n=Date.now()+$;let t;for(;Date.now()<n;){try{const r=await e.status();if(r.listeners.tcp!==null)return r}catch(r){t=r}await new Promise(r=>setTimeout(r,M))}throw new s({error:"listener_unavailable",message:`the successor did not expose a TCP listener within ${$}ms${t instanceof Error?`: ${t.message}`:""}`,next:"Run `crtr sys daemon status` to inspect the daemon, then retry `crtr sys connect`."})}i(z,"awaitTcpListener");async function _(e,n){const t=await e.getModelAuthReadiness(n);if(t.credential==="ready")return;process.stderr.write(`Logging in to ${t.provider} for ${t.model}.
3
- `);const{loginProvider:r,openProviderLoginRuntime:a,terminalAuthInteraction:m}=await import("./provider-login.js");await r(await a(),t.provider,m());const o=await e.getModelAuthReadiness(n);if(o.credential!=="ready")throw new s({error:"provider_login_incomplete",message:`provider ${o.provider} credential is ${o.credential} after login`,next:`Run \`${B(n)}\` again and complete the provider login.`})}i(_,"ensureProviderCredential");function B(e){return["crtr sys connect",e.profile===void 0?void 0:`--profile ${p(e.profile)}`,e.cwd===void 0?void 0:`--cwd ${p(e.cwd)}`,e.kind===void 0?void 0:`--kind ${p(e.kind)}`,e.model===void 0?void 0:`--model ${p(e.model)}`].filter(n=>n!==void 0).join(" ")}i(B,"connectCommand");const F=A({name:"connect",description:"enable browser access to this daemon",whenToUse:"an application needs a browser-reachable daemon URL and bearer token; this enables the local TCP listener and reports the credentials to paste into that application. Add --app and --scopes to mint an app token instead of the owner token.",help:{name:"sys connect",summary:"enable authenticated browser access and log in to the selected model provider when needed; a handover reports browser credentials before it begins",params:[{kind:"flag",name:"app",type:"string",required:!1,constraint:"App id for the new scoped token (without the app: prefix). Required with --scopes; omit both for the owner token."},{kind:"flag",name:"scopes",type:"string",required:!1,constraint:`Comma-separated list from ${[...c].join(", ")}. Requires --app; mints a NEW app bearer with this resolved scope set. Omit both flags for the owner token.`},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Profile setting selecting the provider a root launch with these settings would use."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Directory setting selecting the provider a root launch with these settings would use. Default: this directory."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Node kind setting selecting the provider a root launch with these settings would use."},{kind:"flag",name:"model",type:"string",required:!1,constraint:"Model setting selecting the provider a root launch with these settings would use."}],output:[{name:"base_url",type:"string",required:!0,constraint:"The HTTP URL configured for the TCP listener."},{name:"token",type:"string",required:!0,constraint:"The bearer token accepted by that listener: the owner token, or with --scopes the newly minted scoped token. Paste it only into the application that needs daemon access."}],outputKind:"object",effects:["Stores a missing listener address in user settings and a missing owner bearer token in the 0600 user secrets store.","With --scopes, appends a new scoped token to that secrets store; there is no revoke verb yet, so removing one means editing the store by hand.","When the listener is not already up with both settings present, or a scoped token was minted (the daemon reads tokens only at boot), asks the daemon to hand over to a successor.","After the listener is available, resolves the provider selected by these params (default: this directory) and runs its existing OAuth login flow when that provider has no usable credential."]},run:i(async e=>{const n={profile:e.profile,cwd:R.resolve(e.cwd??process.cwd()),kind:e.kind,model:e.model},t=j(e.scopes),r=e.app;if(t===void 0!=(r===void 0)||r!==void 0&&!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(String(r)))throw new s({error:"invalid_app",message:"--app must name an app id and is required exactly when --scopes is set",field:"app",received:r,next:"Pass --app with an app id and --scopes together, or omit both for the owner token."});const a=N(),o=k("user").api.tcp,l=b("user"),d=T(),w=await d.status();o===""?await y("user",h=>{h.api.tcp=O}):Number(o.slice(o.lastIndexOf(":")+1))===0&&await y("user",h=>{h.api.tcp=W(o)});const f=D()??k("user").api.tcp;if(Number(f.slice(f.lastIndexOf(":")+1))===0)throw new s({error:"dynamic_tcp_port",message:"CRTRD_TCP must use a fixed port for `crtr sys connect`",next:"Set CRTRD_TCP to a host and fixed port, then run `crtr sys connect` again."});if(t===void 0&&o!==""&&l!==void 0&&w.listeners.tcp!==null)return await _(d,n),{base_url:`http://${w.listeners.tcp}`,token:v()??l};l===void 0&&I(C(),"user");const g=v()??b("user");if(g===void 0)throw new Error("TCP listener cannot start without a bearer token");let u=g;t!==void 0&&(u=C(),q({token:u,grantee:`app:${String(r)}`,scopes:t,created:new Date().toISOString()},"user")),U({base_url:`http://${f}`,token:u}),await d.restartDaemon(),await z(),await _(d,n),a!==void 0&&await d.sendMessage(a,{body:"Browser access is ready.",tier:"urgent",from:a})},"run")});export{F as sysConnectLeaf};
@@ -1 +0,0 @@
1
- export declare const sysDbBranch: import("../../core/command.js").BranchDef;
@@ -1 +0,0 @@
1
- var n=Object.defineProperty;var a=(e,t)=>n(e,"name",{value:t,configurable:!0});import{existsSync as o}from"node:fs";import{defineBranch as i,defineLeaf as d}from"../../core/command.js";import{general as s}from"../../core/errors.js";import{canvasDbPath as m}from"../../core/canvas/paths.js";import{isDaemonRunning as c}from"../../daemon/pidfile.js";import{runDaemonExportSqlite as p}from"../../daemon/manage.js";const h=d({name:"export-sqlite",description:"write the Postgres canvas database back into a SQLite canvas.db, for rolling back to a generation that predates Postgres",whenToUse:"rolling back to a runtime generation that still uses SQLite, after `crtr sys daemon stop`. Not part of normal operation; the Postgres generation never needs it.",help:{name:"sys db export-sqlite",summary:"copy the Postgres canvas database into a new runtime/canvas.db at the SQLite schema version the previous generation expects",guide:"Rollback sequence: `crtr sys daemon stop` (drains the daemon, releases its claim, stops the supervised Postgres), `crtr sys db export-sqlite` (this command starts the supervised Postgres by itself, copies every table with object ids mapped back to rowids, verifies row counts, and renames the result into place as runtime/canvas.db), select the previous runtime generation, `crtr sys daemon start`. If the export fails before publishing, canvas.db is not created and the Postgres data is untouched (only the export mark may be left, which keeps a later Postgres boot from importing a restored canvas.db over newer data): rename `runtime/canvas.db.imported` back to `runtime/canvas.db` to start the previous generation from the database as it was before the first Postgres boot, which loses every write made since. This command does not do that rename for you.",params:[],output:[{name:"path",type:"string",required:!0,constraint:"The canvas.db that was written."},{name:"rows",type:"number",required:!0,constraint:"Rows copied across all tables."},{name:"user_version",type:"number",required:!0,constraint:"The SQLite schema version of the written file."},{name:"ms",type:"number",required:!0,constraint:"Wall time of the copy."}],outputKind:"object",effects:["Starts the supervised Postgres if it is not running (or uses CRTR_DATABASE_URL), reads it in one read-only transaction, and writes runtime/canvas.db.exporting-<pid>, then renames it to runtime/canvas.db. Stops the Postgres again afterwards if this command started it.","Records an exported_to_sqlite mark in the Postgres canvas_meta before publishing runtime/canvas.db, so a later boot of the Postgres generation refuses to import this canvas.db over newer Postgres data.","Refuses while a daemon is running, and when runtime/canvas.db already exists."]},run:a(async()=>{if(c())throw s("a daemon is running; an export taken under it would miss writes made after the copy",{next:"Run `crtr sys daemon stop`, then `crtr sys db export-sqlite`."});const e=m();if(o(e))throw s(`${e} already exists`,{next:`Move it aside (or delete it if it is a leftover) before exporting; ${e}.imported is the pre-Postgres database kept by the import.`});try{const t=await p();return{path:t.path,rows:t.rows,user_version:t.userVersion,ms:t.ms}}catch(t){const r=`export failed: ${t.message}`;throw o(e)?s(`${r}; ${e} was published before the failure`,{next:`${e} may be complete: inspect it before using it, or move it aside and rerun the export.`}):s(r,{next:`Nothing was written to ${e}. To start the previous generation from the pre-Postgres database instead, rename ${e}.imported to ${e}; every write made since the Postgres import is lost.`})}},"run")}),y=i({name:"db",description:"offline operations on the canvas database",whenToUse:"rolling the canvas database back to SQLite after a Postgres soak fails",help:{name:"sys db",summary:"offline canvas database operations",model:"The canvas lives in a supervised Postgres. These commands run with the daemon stopped and are for migration and rollback only."},children:[h]});export{y as sysDbBranch};
@@ -1,14 +0,0 @@
1
- export interface ExportResult {
2
- path: string;
3
- rows: number;
4
- ms: number;
5
- userVersion: number;
6
- }
7
- type Log = (message: string) => void;
8
- /**
9
- * Copy the Postgres database at `url` into a new canvas.db next to the runtime records and rename it into place.
10
- * Refuses when a canvas.db already exists. On any failure the temp file is removed; the only thing that can remain is the
11
- * export mark in Postgres, which is written just before the rename.
12
- */
13
- export declare function exportPostgresToSqlite(url: string, log?: Log): Promise<ExportResult>;
14
- export {};
@@ -1,3 +0,0 @@
1
- var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_project_repos","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","files","group_invites","checkout_identities","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let k=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),M=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${M===void 0?"":` ORDER BY ${M}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),k+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:k,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
2
- ${s.join(`
3
- `)}`)}d(pe,"verify");export{Re as exportPostgresToSqlite};