@north-light/cli 0.3.743 → 0.3.745
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.
- package/README.md +2 -2
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
- package/dist/builtin-memory/crouter-sdk/README.md +1 -1
- package/dist/builtin-memory/crouter-sdk/client.md +1 -1
- package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/sys/provider-login.js +2 -2
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/daemon-owner.d.ts +1 -1
- package/dist/core/canvas/paths.d.ts +1 -1
- package/dist/core/canvas/person-state.d.ts +3 -0
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +2 -3
- package/dist/core/canvas/person.js +7 -7
- package/dist/core/canvas/tree.js +4 -4
- package/dist/core/environments.d.ts +0 -10
- package/dist/core/environments.js +1 -1
- package/dist/core/runtime/blaxel-environment.js +1 -1
- package/dist/core/secrets.d.ts +2 -4
- package/dist/core/secrets.js +1 -1
- package/dist/core/spaces/space.js +2 -2
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/environment-of.d.ts +1 -1
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/router.d.ts +1 -1
- package/dist/daemon/crtrd-cli.js +1 -1
- package/dist/daemon/crtrd.d.ts +4 -2
- package/dist/daemon/crtrd.js +20 -20
- package/dist/daemon/manage.d.ts +0 -8
- package/dist/daemon/manage.js +3 -3
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/docs/concepts/scopes-and-trust.md +2 -2
- package/docs/public-api.md +1 -7
- package/docs/sdk/README.md +1 -1
- package/docs/sdk/client.md +1 -1
- package/docs/sdk/getting-started.md +3 -38
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
- package/packages/crouter-api/dist/commands/sys.js +1 -3
- package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
- package/packages/crouter-api/dist/core/canvas/person.js +2 -14
- package/packages/crouter-api/dist/core/canvas/tree.js +3 -1
- package/packages/crouter-api/dist/core/environments.js +2 -38
- package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
- package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
- package/packages/crouter-api/dist/core/secrets.js +1 -11
- package/packages/crouter-api/dist/core/spaces/space.js +2 -2
- package/packages/crouter-api/dist/core/user-settings.js +1 -1
- package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
- package/packages/crouter-api/dist/daemon/manage.js +0 -4
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/connect.d.ts +0 -1
- package/dist/commands/sys/connect.js +0 -3
- package/dist/commands/sys/db.d.ts +0 -1
- package/dist/commands/sys/db.js +0 -1
- package/dist/core/canvas/export-sqlite.d.ts +0 -14
- package/dist/core/canvas/export-sqlite.js +0 -3
- package/dist/daemon/api/document-listener.d.ts +0 -7
- package/dist/daemon/api/document-listener.js +0 -1
- package/dist/daemon/api/document-secret.d.ts +0 -2
- package/dist/daemon/api/document-secret.js +0 -1
- package/dist/daemon/export-sqlite-run.d.ts +0 -1
- package/dist/daemon/export-sqlite-run.js +0 -4
- package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
- package/packages/crouter-api/dist/commands/sys/db.js +0 -69
|
@@ -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
|
|
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
|
|
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,
|
|
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
|
|
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
|
|
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
|
-
|
|
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() {
|
|
@@ -52,7 +52,9 @@ export async function rosterEdges(visible = null) {
|
|
|
52
52
|
const ids = visible === null ? null : [...visible];
|
|
53
53
|
const rows = ids === null
|
|
54
54
|
? await treeEdges(await openDb(), '')
|
|
55
|
-
|
|
55
|
+
// `IN (SELECT unnest(...))`, not `= ANY(...)`: the planner hashes the set instead of scanning the array per joined row
|
|
56
|
+
// (thousands of ids made `ANY` a linear filter: 5.6 s against 0.3 s on the fleet database).
|
|
57
|
+
: await treeEdges(await openDb(), 'AND wo.id IN (SELECT unnest(?::text[])) AND oo.id IN (SELECT unnest(?::text[]))', ids, ids);
|
|
56
58
|
return rows.map(({ from_id, to_id, active, created }) => ({ from_id, to_id, active, created }));
|
|
57
59
|
}
|
|
58
60
|
/** `subscriber` asks to watch `publisher` (an `ask` watch, in the tree). Re-running sets the
|
|
@@ -1,33 +1,9 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
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)); }));
|
|
@@ -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
|
-
//
|
|
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.
|
|
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: '
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
3
|
+
"version": "0.3.745",
|
|
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/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.745",
|
|
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.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.745",
|
|
31
|
+
"@north-light/identity": "0.3.745"
|
|
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.
|
|
3
|
+
"version": "0.3.745",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.745",
|
|
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.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.745",
|
|
32
|
+
"@north-light/plugin": "0.3.745",
|
|
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.
|
|
11905
|
+
"version": "0.3.745",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.745",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.745",
|
|
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.
|
|
11923
|
+
"version": "0.3.745",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.745",
|
|
11927
|
+
"@north-light/identity": "0.3.745"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.745",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.745",
|
|
11936
|
+
"@north-light/identity": "0.3.745",
|
|
11937
|
+
"@north-light/plugin": "0.3.745",
|
|
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;
|
package/dist/commands/sys/db.js
DELETED
|
@@ -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};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/** Why this daemon has no document listener, or undefined while one is bound. `/v1/documents/browser-access` refuses the secret while this is set, so a viewer never sends it to whatever process holds the port. */
|
|
2
|
-
export declare function documentListenerUnavailable(): string | undefined;
|
|
3
|
-
/** Dedicated localhost-only browser listener, independent of /v1 and its TCP bearer configuration. Every route except `/assets/` needs the per-install `secret`, carried by a cookie that `/r/<ref>?t=<secret>` sets. */
|
|
4
|
-
export declare function createDocumentListener(port: number, secret: string): {
|
|
5
|
-
ready: Promise<void>;
|
|
6
|
-
close: () => Promise<void>;
|
|
7
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var f=Object.defineProperty;var c=(n,r)=>f(n,"name",{value:r,configurable:!0});import{createHash as p,timingSafeEqual as v}from"node:crypto";import{createServer as g}from"node:http";import{cookieValue as S,documentNotFound as $,documentShell as y,error as d,messagePage as w,resolveDocument as P,serveDocumentApi as k,setPageHeaders as _}from"./document-page.js";function m(n,r){const l=c(s=>p("sha256").update(s).digest(),"digest");return v(l(n),l(r))}c(m,"sameSecret");const b=c(n=>n(),"inProcess");let h="the document listener has not started";function T(){return h}c(T,"documentListenerUnavailable");function W(n,r){const l=`crtr_doc_${n}`,s=g((t,e)=>{(async()=>{_(e);const a=[`127.0.0.1:${n}`,`localhost:${n}`];if(typeof t.headers.host!="string"||!a.includes(t.headers.host))return d(e,403,"forbidden","invalid Host");if(t.method==="POST"){if(!a.some(i=>t.headers.origin===`http://${i}`))return d(e,403,"forbidden","invalid Origin");if(t.headers["content-type"]!=="application/json")return d(e,415,"unsupported_media_type","Content-Type must be application/json")}const o=new URL(t.url??"/",`http://127.0.0.1:${n}`);if(!o.pathname.startsWith("/assets/")){const i=t.method==="GET"&&o.pathname.startsWith("/r/")?o.searchParams.get("t"):null;if(i!==null&&m(i,r))return o.searchParams.delete("t"),e.writeHead(303,{Location:`${o.pathname}${o.search}`,"Set-Cookie":`${l}=${r}; HttpOnly; SameSite=Strict; Path=/`,"Cache-Control":"no-store"}),e.end();const u=S(t.headers.cookie,l);if(i!==null||u===void 0||!m(u,r))return o.pathname.startsWith("/r/")?w(e,401,"Not authorized","Open this document from its link in the attach viewer."):d(e,401,"unauthorized","open the document link from the attach viewer")}if(t.method==="GET"&&o.pathname.startsWith("/r/")){let i;try{i=decodeURIComponent(o.pathname.slice(3))}catch{return d(e,400,"invalid_request","ref is not valid percent-encoding")}const u=await P(i);return u?y(e,i,u):$(e,i)}if(!await k(t,e,o,b))return d(e,404,"not_found","route not found")})().catch(a=>{e.headersSent?e.destroy():d(e,500,"server_failure",a instanceof Error?a.message:String(a))})});return{ready:new Promise((t,e)=>{s.once("error",a=>{h=`the document listener could not bind 127.0.0.1:${n}: ${a.message}`,e(a)}),s.listen(n,"127.0.0.1",()=>{s.removeAllListeners("error"),h=void 0,t()})}),close:c(()=>new Promise(t=>{h="the document listener is closed",s.closeAllConnections(),s.close(()=>t())}),"close")}}c(W,"createDocumentListener");export{W as createDocumentListener,T as documentListenerUnavailable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var n=Object.defineProperty;var o=(t,r)=>n(t,"name",{value:r,configurable:!0});import{randomBytes as c}from"node:crypto";import{readFileSync as m,writeFileSync as i}from"node:fs";import{join as d}from"node:path";import{crtrHome as a}from"../../core/canvas/paths.js";const s=/^[A-Za-z0-9_-]{43,}$/;function S(){const t=d(a(),"document-secret");try{i(t,c(32).toString("base64url"),{mode:384,flag:"wx"})}catch(e){if(e.code!=="EEXIST")throw e}const r=m(t,"utf8").trim();if(!s.test(r))throw new Error(`${t} does not hold a document secret; delete it and restart crtrd to mint a new one`);return r}o(S,"documentSecret");export{S as documentSecret};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function runExportSqlite(): Promise<number>;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var a=Object.defineProperty;var s=(e,r)=>a(e,"name",{value:r,configurable:!0});import{daemonOwnershipClaimed as i}from"../core/canvas/daemon-owner.js";import{closeAllDbs as n}from"../core/canvas/db.js";import{exportPostgresToSqlite as c}from"../core/canvas/export-sqlite.js";import{ensurePostgres as l,stopPostgres as p}from"./postgres/index.js";async function g(){let e=!1,r=0;try{const t=await l();e=t.started;const o=await c(t.url);process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
-
`)}catch(t){process.stderr.write(`${t.message}
|
|
3
|
-
`),r=1}if(e)try{await p({claimed:s(async()=>{try{return await i()}finally{await n()}},"claimed")})}catch(t){process.stderr.write(`the export started Postgres and could not stop it: ${t.message}
|
|
4
|
-
`),r=1}return r}s(g,"runExportSqlite");export{g as runExportSqlite};
|