@north-light/api 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 +1 -1
- package/dist/commands/sys/provider-login.js +2 -2
- package/dist/commands/sys.js +1 -3
- package/dist/core/canvas/paths.d.ts +1 -1
- package/dist/core/canvas/paths.js +1 -1
- package/dist/core/canvas/person-state.d.ts +3 -0
- package/dist/core/canvas/person-state.js +4 -0
- package/dist/core/canvas/person.d.ts +2 -3
- package/dist/core/canvas/person.js +2 -14
- package/dist/core/canvas/tree.js +3 -1
- package/dist/core/environments.d.ts +0 -10
- package/dist/core/environments.js +2 -38
- package/dist/core/model-auth/daemon-login.js +2 -2
- package/dist/core/runtime/blaxel-environment.js +3 -3
- package/dist/core/secrets.d.ts +2 -4
- package/dist/core/secrets.js +1 -11
- 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 +7 -4
- package/dist/daemon/api/router.d.ts +1 -1
- package/dist/daemon/manage.d.ts +0 -8
- package/dist/daemon/manage.js +0 -4
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/package.json +1 -1
- package/dist/commands/sys/connect.d.ts +0 -1
- package/dist/commands/sys/connect.js +0 -185
- package/dist/commands/sys/db.d.ts +0 -1
- package/dist/commands/sys/db.js +0 -69
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ The package is ESM-only. Import it from an ES module, or use dynamic `import()`
|
|
|
22
22
|
|
|
23
23
|
## Connect to a daemon
|
|
24
24
|
|
|
25
|
-
`CrtrClient` is the typed HTTP client. Give it a TCP base URL and any required bearer header.
|
|
25
|
+
`CrtrClient` is the typed HTTP client. Give it a TCP base URL and any required bearer header.
|
|
26
26
|
|
|
27
27
|
```ts
|
|
28
28
|
import { CrtrClient } from '@north-light/api';
|
|
@@ -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: `
|
package/dist/commands/sys.js
CHANGED
|
@@ -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
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Runtime-owned records; never a bind source for an app sandbox. */
|
|
2
2
|
export declare function crtrHome(): string;
|
|
3
|
-
/** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres
|
|
3
|
+
/** The pre-Postgres SQLite canvas file. Read only by the one-time import into Postgres. */
|
|
4
4
|
export declare function canvasDbPath(): string;
|
|
5
5
|
export declare function onDiskMigrationLockPath(): string;
|
|
6
6
|
export declare function onDiskMigrationMarkerPath(): string;
|
|
@@ -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
|
}
|
|
@@ -15,6 +15,9 @@ export declare function setPersonId(id: string): void;
|
|
|
15
15
|
export declare function markCloudRole(): void;
|
|
16
16
|
/** Whether this process is a cloud role (`markCloudRole` ran at boot). */
|
|
17
17
|
export declare function isCloudRole(): boolean;
|
|
18
|
+
/** `crtrd --role all` (tests and crouter development) runs every node's engine on its own host: no Blaxel sandbox, no remote machine. */
|
|
19
|
+
export declare function markEnginesInProcess(): void;
|
|
20
|
+
export declare function areEnginesInProcess(): boolean;
|
|
18
21
|
/** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
|
|
19
22
|
export declare function runAsPerson<T>(person: string, fn: () => T): T;
|
|
20
23
|
/** The request's person; else, on a Mac, the boot-set person. Throws `PersonOutsideRequestError` on a cloud role outside a request and
|
|
@@ -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
|
|
@@ -2,13 +2,12 @@ import { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markClou
|
|
|
2
2
|
import { type CanvasDb } from './db.js';
|
|
3
3
|
import { LEGACY_LOCAL_PERSON } from './legacy-person.js';
|
|
4
4
|
export { LEGACY_LOCAL_PERSON };
|
|
5
|
-
export type PersonSource = 'stored' | 'joined' | 'grants'
|
|
5
|
+
export type PersonSource = 'stored' | 'joined' | 'grants';
|
|
6
6
|
export { PersonUnresolvedError, PersonOutsideRequestError, setPersonId, markCloudRole, isCloudRole, runAsPerson, personId };
|
|
7
7
|
/** As `personId()`, but a process that is not the daemon gets a lazy get-or-create keyed by the active canvas database. */
|
|
8
8
|
export declare function personIdAsync(): Promise<string>;
|
|
9
9
|
/** Get-or-create the person and say where it came from. Order: stored, the join file's owner, the single `sub` of the
|
|
10
|
-
* mirrored grants (a runtime with an issuer and no join file), else
|
|
11
|
-
* Null when an issuer runtime has no mirrored grants yet; nothing is stored then. */
|
|
10
|
+
* mirrored grants (a runtime with an issuer and no join file), else null (nothing is stored): no person is ever minted. */
|
|
12
11
|
export declare function resolvePerson(): Promise<{
|
|
13
12
|
id: string;
|
|
14
13
|
source: PersonSource;
|
|
@@ -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() {
|
package/dist/core/canvas/tree.js
CHANGED
|
@@ -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,11 +1,5 @@
|
|
|
1
1
|
import type { CanvasDb } from './canvas/db.js';
|
|
2
2
|
import { type EnvironmentRecipeInput } from './environment-recipe.js';
|
|
3
|
-
/** Find the `environments` row for `installId`, or create its object and row; either way set `last_seen_at`, and cache
|
|
4
|
-
* the environment id and install id for {@link machineEnvironmentId} and {@link touchMachineEnvironment}. */
|
|
5
|
-
export declare function registerMachineEnvironment(installId: string): Promise<{
|
|
6
|
-
environmentId: string;
|
|
7
|
-
created: boolean;
|
|
8
|
-
}>;
|
|
9
3
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
10
4
|
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
11
5
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
@@ -18,7 +12,3 @@ export declare function createProfileBlaxelEnvironment(db: CanvasDb, spec: {
|
|
|
18
12
|
memoryMb?: number;
|
|
19
13
|
recipe?: EnvironmentRecipeInput;
|
|
20
14
|
}): Promise<string>;
|
|
21
|
-
/** Stamp `last_seen_at` on the machine environment: one statement, no read. A no-op before {@link registerMachineEnvironment}. */
|
|
22
|
-
export declare function touchMachineEnvironment(now: string): Promise<void>;
|
|
23
|
-
/** The machine environment's object id; throws before {@link registerMachineEnvironment} has run. */
|
|
24
|
-
export declare function machineEnvironmentId(): string;
|
|
@@ -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
|
}
|
package/dist/core/secrets.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export interface SecretsStore {
|
|
|
11
11
|
apiToken?: string;
|
|
12
12
|
scopedApiTokens?: ScopedApiToken[];
|
|
13
13
|
}
|
|
14
|
-
/** A bearer token minted
|
|
14
|
+
/** A bearer token minted for an app whose `scopes` list is
|
|
15
15
|
* the ceiling for every scope-gated daemon operation the holder performs. The
|
|
16
16
|
* owner token (`apiToken`) has no ceiling. */
|
|
17
17
|
export interface ScopedApiToken {
|
|
@@ -29,15 +29,13 @@ export declare function getRelayToken(ref: string, scope: Scope): string | undef
|
|
|
29
29
|
export declare function setRelayToken(ref: string, token: string, scope: Scope): void;
|
|
30
30
|
export declare function deleteRelayToken(ref: string, scope: Scope): void;
|
|
31
31
|
export declare function getApiToken(scope: Scope): string | undefined;
|
|
32
|
-
export declare function setApiToken(token: string, scope: Scope): void;
|
|
33
32
|
export declare function listScopedApiTokens(scope: Scope): ScopedApiToken[];
|
|
34
|
-
export declare function addScopedApiToken(entry: ScopedApiToken, scope: Scope): void;
|
|
35
33
|
/** The `crtr_app_` token minted for an installed plugin, if it holds one. */
|
|
36
34
|
export declare function pluginAppToken(plugin: string): ScopedApiToken | undefined;
|
|
37
35
|
/** Mint the plugin's `crtr_app_` token when absent; rewrite its `scopes` in place (same token) when they
|
|
38
36
|
* differ; otherwise write nothing. */
|
|
39
37
|
export declare function ensurePluginAppToken(plugin: string, scopes: readonly string[]): ScopedApiToken;
|
|
40
|
-
/** Remove the plugin's `crtr_app_` tokens.
|
|
38
|
+
/** Remove the plugin's `crtr_app_` tokens. Other entries are never touched. */
|
|
41
39
|
export declare function revokePluginAppTokens(plugin: string): boolean;
|
|
42
40
|
/** Look a raw scoped bearer up in the user store. Cached; the cache is dropped by every in-process
|
|
43
41
|
* `writeSecrets` and re-read when the file's (inode, size, mtime) changes, so a revocation by any
|
package/dist/core/secrets.js
CHANGED
|
@@ -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,5 +1,5 @@
|
|
|
1
1
|
import type { StartBundleRecipeDTO } from '../../api/index.js';
|
|
2
|
-
/** The environment object id a node runs in: its profile's `environment_id
|
|
2
|
+
/** 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. */
|
|
3
3
|
export declare function environmentOfNode(profileId: string | null): Promise<string>;
|
|
4
4
|
/** SQL predicate over `environments`: the recipe has content (a repository, a setup script or pi packages). A recipe cleared back to nothing
|
|
5
5
|
* has none, whatever its `recipe_revision` counter says: the counter only orders edits, it does not say whether a recipe exists. */
|
|
@@ -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
|
}
|
|
@@ -3,7 +3,7 @@ import { ApiError } from '../../api/errors.js';
|
|
|
3
3
|
import type { AppPrincipal } from './principal.js';
|
|
4
4
|
import { type Operation } from './operations.js';
|
|
5
5
|
/** What the caller's bearer token may reach: `null` is the owner (every scope,
|
|
6
|
-
* every route); a list is the ceiling minted by
|
|
6
|
+
* every route); a list is the ceiling minted by an app token. */
|
|
7
7
|
export type Ceiling = readonly string[] | null;
|
|
8
8
|
export type RequestPrincipal = {
|
|
9
9
|
class: 'anonymous';
|
package/dist/daemon/manage.d.ts
CHANGED
|
@@ -47,14 +47,6 @@ export interface DaemonExportSqliteResult {
|
|
|
47
47
|
ms: number;
|
|
48
48
|
userVersion: number;
|
|
49
49
|
}
|
|
50
|
-
export interface DaemonExportSqliteResult {
|
|
51
|
-
path: string;
|
|
52
|
-
rows: number;
|
|
53
|
-
ms: number;
|
|
54
|
-
userVersion: number;
|
|
55
|
-
}
|
|
56
|
-
/** Run the selected generation's `crtrd-cli export-sqlite` and wait for it. */
|
|
57
|
-
export declare function runDaemonExportSqlite(): Promise<DaemonExportSqliteResult>;
|
|
58
50
|
/** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
|
|
59
51
|
export declare function runDaemonImportDump(out: string, kind: 'machine' | 'hosted'): Promise<DumpResult>;
|
|
60
52
|
/** Run `crtrd-cli import-dump <out> bodies`: every `bodies` row into `out`/rows/bodies (the pre-pause dump; the later `runDaemonImportDump` adds the rows written since). */
|
package/dist/daemon/manage.js
CHANGED
|
@@ -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
|
}
|
package/package.json
CHANGED
|
@@ -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 +0,0 @@
|
|
|
1
|
-
export declare const sysConnectLeaf: import("../../core/command.js").LeafDef;
|
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { defineLeaf } from '../../core/command.js';
|
|
4
|
-
import { readConfig, updateConfig } from '../../core/config.js';
|
|
5
|
-
import { emit, InputError, isJsonOutput } from '../../core/io.js';
|
|
6
|
-
import { renderResult } from '../../core/render.js';
|
|
7
|
-
import { addScopedApiToken, getApiToken, setApiToken } from '../../core/secrets.js';
|
|
8
|
-
import { ENFORCED } from '@north-light/identity';
|
|
9
|
-
import { envCrtrdTcp, envCrtrdToken, envNodeId } from '../../shared/env.js';
|
|
10
|
-
import { shellQuote } from '../../shared/shell-quote.js';
|
|
11
|
-
import { cliClient } from '../api-client.js';
|
|
12
|
-
const DEFAULT_TCP = '127.0.0.1:8787';
|
|
13
|
-
const LISTENER_WAIT_MS = 30_000;
|
|
14
|
-
const LISTENER_POLL_MS = 100;
|
|
15
|
-
function token() {
|
|
16
|
-
return randomBytes(32).toString('hex');
|
|
17
|
-
}
|
|
18
|
-
/** Parse `--scopes` into a non-empty validated list, or undefined when the
|
|
19
|
-
* flag was omitted (the owner token). */
|
|
20
|
-
function parseScopes(raw) {
|
|
21
|
-
if (raw === undefined)
|
|
22
|
-
return undefined;
|
|
23
|
-
const scopes = String(raw).split(',').map((scope) => scope.trim()).filter((scope) => scope !== '');
|
|
24
|
-
if (scopes.length === 0) {
|
|
25
|
-
throw new InputError({
|
|
26
|
-
error: 'empty_scopes',
|
|
27
|
-
message: '--scopes names no scope',
|
|
28
|
-
received: raw,
|
|
29
|
-
field: 'scopes',
|
|
30
|
-
next: `Pass a comma-separated list from ${[...ENFORCED].join(', ')}; omit the flag for the owner token.`,
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
for (const scope of scopes)
|
|
34
|
-
if (!ENFORCED.has(scope))
|
|
35
|
-
throw new InputError({ error: 'invalid_scope', message: `invalid scope: ${scope}`, field: 'scopes', received: scope, next: `Use one of ${[...ENFORCED].join(', ')}.` });
|
|
36
|
-
return scopes;
|
|
37
|
-
}
|
|
38
|
-
function printCredentials(result) {
|
|
39
|
-
if (isJsonOutput())
|
|
40
|
-
emit(result);
|
|
41
|
-
else
|
|
42
|
-
process.stdout.write(renderResult(result, sysConnectLeaf.help) + '\n');
|
|
43
|
-
}
|
|
44
|
-
function fixedTcpPort(tcp) {
|
|
45
|
-
const separator = tcp.lastIndexOf(':');
|
|
46
|
-
if (separator === -1 || Number(tcp.slice(separator + 1)) !== 0)
|
|
47
|
-
return tcp;
|
|
48
|
-
return `${tcp.slice(0, separator + 1)}8787`;
|
|
49
|
-
}
|
|
50
|
-
async function awaitTcpListener() {
|
|
51
|
-
const client = cliClient();
|
|
52
|
-
const deadline = Date.now() + LISTENER_WAIT_MS;
|
|
53
|
-
let lastError;
|
|
54
|
-
while (Date.now() < deadline) {
|
|
55
|
-
try {
|
|
56
|
-
const status = await client.status();
|
|
57
|
-
if (status.listeners.tcp !== null)
|
|
58
|
-
return status;
|
|
59
|
-
}
|
|
60
|
-
catch (error) {
|
|
61
|
-
lastError = error;
|
|
62
|
-
}
|
|
63
|
-
await new Promise((resolve) => setTimeout(resolve, LISTENER_POLL_MS));
|
|
64
|
-
}
|
|
65
|
-
throw new InputError({
|
|
66
|
-
error: 'listener_unavailable',
|
|
67
|
-
message: `the successor did not expose a TCP listener within ${LISTENER_WAIT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ''}`,
|
|
68
|
-
next: 'Run `crtr sys daemon status` to inspect the daemon, then retry `crtr sys connect`.',
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
async function ensureProviderCredential(client, selectors) {
|
|
72
|
-
const readiness = await client.getModelAuthReadiness(selectors);
|
|
73
|
-
if (readiness.credential === 'ready')
|
|
74
|
-
return;
|
|
75
|
-
process.stderr.write(`Logging in to ${readiness.provider} for ${readiness.model}.\n`);
|
|
76
|
-
const { loginProvider, openProviderLoginRuntime, terminalAuthInteraction } = await import('./provider-login.js');
|
|
77
|
-
await loginProvider(await openProviderLoginRuntime(), readiness.provider, terminalAuthInteraction());
|
|
78
|
-
const confirmed = await client.getModelAuthReadiness(selectors);
|
|
79
|
-
if (confirmed.credential !== 'ready') {
|
|
80
|
-
throw new InputError({
|
|
81
|
-
error: 'provider_login_incomplete',
|
|
82
|
-
message: `provider ${confirmed.provider} credential is ${confirmed.credential} after login`,
|
|
83
|
-
next: `Run \`${connectCommand(selectors)}\` again and complete the provider login.`,
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function connectCommand(selectors) {
|
|
88
|
-
return [
|
|
89
|
-
'crtr sys connect',
|
|
90
|
-
selectors.profile === undefined ? undefined : `--profile ${shellQuote(selectors.profile)}`,
|
|
91
|
-
selectors.cwd === undefined ? undefined : `--cwd ${shellQuote(selectors.cwd)}`,
|
|
92
|
-
selectors.kind === undefined ? undefined : `--kind ${shellQuote(selectors.kind)}`,
|
|
93
|
-
selectors.model === undefined ? undefined : `--model ${shellQuote(selectors.model)}`,
|
|
94
|
-
].filter((part) => part !== undefined).join(' ');
|
|
95
|
-
}
|
|
96
|
-
export const sysConnectLeaf = defineLeaf({
|
|
97
|
-
name: 'connect',
|
|
98
|
-
description: 'enable browser access to this daemon',
|
|
99
|
-
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.',
|
|
100
|
-
help: {
|
|
101
|
-
name: 'sys connect',
|
|
102
|
-
summary: 'enable authenticated browser access and log in to the selected model provider when needed; a handover reports browser credentials before it begins',
|
|
103
|
-
params: [
|
|
104
|
-
{ kind: 'flag', name: 'app', type: 'string', required: false, constraint: 'App id for the new scoped token (without the app: prefix). Required with --scopes; omit both for the owner token.' },
|
|
105
|
-
{ kind: 'flag', name: 'scopes', type: 'string', required: false, constraint: `Comma-separated list from ${[...ENFORCED].join(', ')}. Requires --app; mints a NEW app bearer with this resolved scope set. Omit both flags for the owner token.` },
|
|
106
|
-
{ kind: 'flag', name: 'profile', type: 'string', required: false, constraint: 'Profile setting selecting the provider a root launch with these settings would use.' },
|
|
107
|
-
{ kind: 'flag', name: 'cwd', type: 'string', required: false, constraint: 'Directory setting selecting the provider a root launch with these settings would use. Default: this directory.' },
|
|
108
|
-
{ kind: 'flag', name: 'kind', type: 'string', required: false, constraint: 'Node kind setting selecting the provider a root launch with these settings would use.' },
|
|
109
|
-
{ kind: 'flag', name: 'model', type: 'string', required: false, constraint: 'Model setting selecting the provider a root launch with these settings would use.' },
|
|
110
|
-
],
|
|
111
|
-
output: [
|
|
112
|
-
{ name: 'base_url', type: 'string', required: true, constraint: 'The HTTP URL configured for the TCP listener.' },
|
|
113
|
-
{ name: 'token', type: 'string', required: true, 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.' },
|
|
114
|
-
],
|
|
115
|
-
outputKind: 'object',
|
|
116
|
-
effects: [
|
|
117
|
-
'Stores a missing listener address in user settings and a missing owner bearer token in the 0600 user secrets store.',
|
|
118
|
-
'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.',
|
|
119
|
-
'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.',
|
|
120
|
-
'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.',
|
|
121
|
-
],
|
|
122
|
-
},
|
|
123
|
-
run: async (input) => {
|
|
124
|
-
const selectors = {
|
|
125
|
-
profile: input['profile'],
|
|
126
|
-
cwd: path.resolve(input['cwd'] ?? process.cwd()),
|
|
127
|
-
kind: input['kind'],
|
|
128
|
-
model: input['model'],
|
|
129
|
-
};
|
|
130
|
-
const scopes = parseScopes(input['scopes']);
|
|
131
|
-
const app = input['app'];
|
|
132
|
-
if ((scopes === undefined) !== (app === undefined) || (app !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(String(app)))) {
|
|
133
|
-
throw new InputError({ error: 'invalid_app', message: '--app must name an app id and is required exactly when --scopes is set', field: 'app', received: app, next: 'Pass --app with an app id and --scopes together, or omit both for the owner token.' });
|
|
134
|
-
}
|
|
135
|
-
const callerNodeId = envNodeId();
|
|
136
|
-
const config = readConfig('user');
|
|
137
|
-
const storedTcp = config.api.tcp;
|
|
138
|
-
const storedToken = getApiToken('user');
|
|
139
|
-
const client = cliClient();
|
|
140
|
-
const status = await client.status();
|
|
141
|
-
if (storedTcp === '')
|
|
142
|
-
await updateConfig('user', (next) => { next.api.tcp = DEFAULT_TCP; });
|
|
143
|
-
else if (Number(storedTcp.slice(storedTcp.lastIndexOf(':') + 1)) === 0) {
|
|
144
|
-
await updateConfig('user', (next) => { next.api.tcp = fixedTcpPort(storedTcp); });
|
|
145
|
-
}
|
|
146
|
-
const tcp = envCrtrdTcp() ?? readConfig('user').api.tcp;
|
|
147
|
-
if (Number(tcp.slice(tcp.lastIndexOf(':') + 1)) === 0) {
|
|
148
|
-
throw new InputError({
|
|
149
|
-
error: 'dynamic_tcp_port',
|
|
150
|
-
message: 'CRTRD_TCP must use a fixed port for `crtr sys connect`',
|
|
151
|
-
next: 'Set CRTRD_TCP to a host and fixed port, then run `crtr sys connect` again.',
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
if (scopes === undefined && storedTcp !== '' && storedToken !== undefined && status.listeners.tcp !== null) {
|
|
155
|
-
await ensureProviderCredential(client, selectors);
|
|
156
|
-
return {
|
|
157
|
-
base_url: `http://${status.listeners.tcp}`,
|
|
158
|
-
token: envCrtrdToken() ?? storedToken,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
if (storedToken === undefined)
|
|
162
|
-
setApiToken(token(), 'user');
|
|
163
|
-
const ownerToken = envCrtrdToken() ?? getApiToken('user');
|
|
164
|
-
if (ownerToken === undefined) {
|
|
165
|
-
throw new Error('TCP listener cannot start without a bearer token');
|
|
166
|
-
}
|
|
167
|
-
let issued = ownerToken;
|
|
168
|
-
if (scopes !== undefined) {
|
|
169
|
-
issued = token();
|
|
170
|
-
addScopedApiToken({ token: issued, grantee: `app:${String(app)}`, scopes, created: new Date().toISOString() }, 'user');
|
|
171
|
-
}
|
|
172
|
-
// Handover can replace the caller's broker before it receives a returned result.
|
|
173
|
-
printCredentials({ base_url: `http://${tcp}`, token: issued });
|
|
174
|
-
await client.restartDaemon();
|
|
175
|
-
await awaitTcpListener();
|
|
176
|
-
await ensureProviderCredential(client, selectors);
|
|
177
|
-
if (callerNodeId !== undefined) {
|
|
178
|
-
await client.sendMessage(callerNodeId, {
|
|
179
|
-
body: 'Browser access is ready.',
|
|
180
|
-
tier: 'urgent',
|
|
181
|
-
from: callerNodeId,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
},
|
|
185
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const sysDbBranch: import("../../core/command.js").BranchDef;
|
package/dist/commands/sys/db.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// `crtr sys db`: offline operations on the canvas database. Today one leaf: the rollback export to SQLite.
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
3
|
-
import { defineBranch, defineLeaf } from '../../core/command.js';
|
|
4
|
-
import { general } from '../../core/errors.js';
|
|
5
|
-
import { canvasDbPath } from '../../core/canvas/paths.js';
|
|
6
|
-
import { isDaemonRunning } from '../../daemon/pidfile.js';
|
|
7
|
-
import { runDaemonExportSqlite } from '../../daemon/manage.js';
|
|
8
|
-
const sysDbExportSqliteLeaf = defineLeaf({
|
|
9
|
-
name: 'export-sqlite',
|
|
10
|
-
description: 'write the Postgres canvas database back into a SQLite canvas.db, for rolling back to a generation that predates Postgres',
|
|
11
|
-
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.',
|
|
12
|
-
help: {
|
|
13
|
-
name: 'sys db export-sqlite',
|
|
14
|
-
summary: 'copy the Postgres canvas database into a new runtime/canvas.db at the SQLite schema version the previous generation expects',
|
|
15
|
-
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.',
|
|
16
|
-
params: [],
|
|
17
|
-
output: [
|
|
18
|
-
{ name: 'path', type: 'string', required: true, constraint: 'The canvas.db that was written.' },
|
|
19
|
-
{ name: 'rows', type: 'number', required: true, constraint: 'Rows copied across all tables.' },
|
|
20
|
-
{ name: 'user_version', type: 'number', required: true, constraint: 'The SQLite schema version of the written file.' },
|
|
21
|
-
{ name: 'ms', type: 'number', required: true, constraint: 'Wall time of the copy.' },
|
|
22
|
-
],
|
|
23
|
-
outputKind: 'object',
|
|
24
|
-
effects: [
|
|
25
|
-
'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.',
|
|
26
|
-
'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.',
|
|
27
|
-
'Refuses while a daemon is running, and when runtime/canvas.db already exists.',
|
|
28
|
-
],
|
|
29
|
-
},
|
|
30
|
-
run: async () => {
|
|
31
|
-
if (isDaemonRunning()) {
|
|
32
|
-
throw general('a daemon is running; an export taken under it would miss writes made after the copy', {
|
|
33
|
-
next: 'Run `crtr sys daemon stop`, then `crtr sys db export-sqlite`.',
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
const target = canvasDbPath();
|
|
37
|
-
if (existsSync(target)) {
|
|
38
|
-
throw general(`${target} already exists`, {
|
|
39
|
-
next: `Move it aside (or delete it if it is a leftover) before exporting; ${target}.imported is the pre-Postgres database kept by the import.`,
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
try {
|
|
43
|
-
const result = await runDaemonExportSqlite();
|
|
44
|
-
return { path: result.path, rows: result.rows, user_version: result.userVersion, ms: result.ms };
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
const message = `export failed: ${error.message}`;
|
|
48
|
-
if (existsSync(target)) {
|
|
49
|
-
throw general(`${message}; ${target} was published before the failure`, {
|
|
50
|
-
next: `${target} may be complete: inspect it before using it, or move it aside and rerun the export.`,
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
throw general(message, {
|
|
54
|
-
next: `Nothing was written to ${target}. To start the previous generation from the pre-Postgres database instead, rename ${target}.imported to ${target}; every write made since the Postgres import is lost.`,
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
},
|
|
58
|
-
});
|
|
59
|
-
export const sysDbBranch = defineBranch({
|
|
60
|
-
name: 'db',
|
|
61
|
-
description: 'offline operations on the canvas database',
|
|
62
|
-
whenToUse: 'rolling the canvas database back to SQLite after a Postgres soak fails',
|
|
63
|
-
help: {
|
|
64
|
-
name: 'sys db',
|
|
65
|
-
summary: 'offline canvas database operations',
|
|
66
|
-
model: 'The canvas lives in a supervised Postgres. These commands run with the daemon stopped and are for migration and rollback only.',
|
|
67
|
-
},
|
|
68
|
-
children: [sysDbExportSqliteLeaf],
|
|
69
|
-
});
|