@north-light/api 0.3.754 → 0.3.756
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/dist/api/client.d.ts +1 -2
- package/dist/api/client.js +0 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/health.d.ts +0 -54
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +0 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +0 -9
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -2
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -17
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +0 -16
- package/dist/core/directory/join.js +18 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +0 -7
- package/dist/core/grants/sync.js +2 -2
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +0 -5
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -19
- package/dist/core/runs/operations.js +6 -0
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +0 -16
- package/dist/daemon/api/operations.js +0 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/manage.js +1 -1
- package/package.json +1 -1
- package/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -79
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -523
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -118
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -424
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -543
- package/dist/core/locked-file.d.ts +0 -27
- package/dist/core/locked-file.js +0 -121
- package/dist/core/scoped-state/db.d.ts +0 -17
- package/dist/core/scoped-state/db.js +0 -271
- package/dist/core/scoped-state/legacy-profiles.d.ts +0 -11
- package/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -332
- package/dist/core/scoped-state/schema.d.ts +0 -14
- package/dist/core/scoped-state/schema.js +0 -52
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -89
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -46
package/dist/core/locked-file.js
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
// locked-file.ts — crouter's cross-process locked read/modify/write primitive for the
|
|
2
|
-
// small JSON state files the runtime co-owns with pi: pi's own `auth.json` (api keys and
|
|
3
|
-
// non-managed OAuth credentials) and crouter's per-provider subscription pool files, which
|
|
4
|
-
// hold every managed account's own credential.
|
|
5
|
-
//
|
|
6
|
-
// The lock is `proper-lockfile` on the target path, so a crouter process and a pi process
|
|
7
|
-
// contending for `auth.json` still exclude each other: same library, same lock path, and
|
|
8
|
-
// same `realpath: false` option. Every callback runs asynchronously and returns
|
|
9
|
-
// `{ result, next }`; `next === undefined` means "no write". Every write lands by atomic
|
|
10
|
-
// tmp+rename (pool callers do their own, inside the callback), so a whole snapshot is the
|
|
11
|
-
// only thing on disk and READS need no lock at all -- `readUnlocked` serves them. That
|
|
12
|
-
// matters: pi asks its CredentialStore for every registered provider (~75) whenever it
|
|
13
|
-
// builds a model runtime, and routing those through the lock made each boot serialize
|
|
14
|
-
// behind seconds of lock acquisition backoff.
|
|
15
|
-
import { chmodSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, closeSync } from 'node:fs';
|
|
16
|
-
import { dirname } from 'node:path';
|
|
17
|
-
import lockfile from 'proper-lockfile';
|
|
18
|
-
import { publishFileExclusive } from './fs-utils.js';
|
|
19
|
-
const WRITE_OPTIONS = { encoding: 'utf-8', mode: 0o600 };
|
|
20
|
-
// proper-lockfile decides a held lock is abandoned when its lockdir mtime is older than
|
|
21
|
-
// the acquirer's `stale`, and refreshes the mtime on the holder's `update` timer. The holder
|
|
22
|
-
// refreshes well inside the staleness threshold so long-running callbacks remain protected.
|
|
23
|
-
const LOCK_STALE_MS = 30_000;
|
|
24
|
-
const LOCK_UPDATE_MS = 5_000;
|
|
25
|
-
/** A 0600 JSON file guarded by a cross-process `proper-lockfile` lock on its own path. */
|
|
26
|
-
export class LockedJsonFile {
|
|
27
|
-
path;
|
|
28
|
-
durable;
|
|
29
|
-
initialContent;
|
|
30
|
-
constructor(path, durable = false, initialContent = '{}') {
|
|
31
|
-
this.path = path;
|
|
32
|
-
this.durable = durable;
|
|
33
|
-
this.initialContent = initialContent;
|
|
34
|
-
}
|
|
35
|
-
readUnlocked() {
|
|
36
|
-
return existsSync(this.path) ? readFileSync(this.path, 'utf-8') : undefined;
|
|
37
|
-
}
|
|
38
|
-
ensureFile() {
|
|
39
|
-
const dir = dirname(this.path);
|
|
40
|
-
if (!existsSync(dir))
|
|
41
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
42
|
-
if (!existsSync(this.path)) {
|
|
43
|
-
// Published whole and exclusively: another process may be creating it too, and a
|
|
44
|
-
// reader (or a lost write) must never see the empty file a plain create leaves.
|
|
45
|
-
publishFileExclusive(this.path, this.initialContent, 0o600);
|
|
46
|
-
chmodSync(this.path, 0o600);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
/** Acquire the lock without blocking the event loop, keeping every read-modify-write
|
|
50
|
-
* callback on the same asynchronous path. */
|
|
51
|
-
async withLockAsync(fn) {
|
|
52
|
-
this.ensureFile();
|
|
53
|
-
let release;
|
|
54
|
-
let compromised;
|
|
55
|
-
const throwIfCompromised = () => {
|
|
56
|
-
if (compromised)
|
|
57
|
-
throw compromised;
|
|
58
|
-
};
|
|
59
|
-
try {
|
|
60
|
-
release = await lockfile.lock(this.path, {
|
|
61
|
-
// A different realpath setting would derive a DIFFERENT lock path for a symlinked
|
|
62
|
-
// auth.json and silently stop excluding other writers.
|
|
63
|
-
realpath: false,
|
|
64
|
-
retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10_000, randomize: true },
|
|
65
|
-
stale: LOCK_STALE_MS,
|
|
66
|
-
// Refresh the lockdir mtime well inside `stale` so long-running callbacks remain protected.
|
|
67
|
-
update: LOCK_UPDATE_MS,
|
|
68
|
-
onCompromised: (err) => {
|
|
69
|
-
compromised = err;
|
|
70
|
-
},
|
|
71
|
-
});
|
|
72
|
-
throwIfCompromised();
|
|
73
|
-
const current = existsSync(this.path) ? readFileSync(this.path, 'utf-8') : undefined;
|
|
74
|
-
let published = false;
|
|
75
|
-
const publish = (next) => {
|
|
76
|
-
if (published)
|
|
77
|
-
throw new Error(`locked file was published twice: ${this.path}`);
|
|
78
|
-
throwIfCompromised();
|
|
79
|
-
const tmp = `${this.path}.${process.pid}.${Date.now()}.tmp`;
|
|
80
|
-
writeFileSync(tmp, next, WRITE_OPTIONS);
|
|
81
|
-
chmodSync(tmp, 0o600);
|
|
82
|
-
if (this.durable) {
|
|
83
|
-
const fd = openSync(tmp, 'r');
|
|
84
|
-
try {
|
|
85
|
-
fsyncSync(fd);
|
|
86
|
-
}
|
|
87
|
-
finally {
|
|
88
|
-
closeSync(fd);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
renameSync(tmp, this.path);
|
|
92
|
-
if (this.durable) {
|
|
93
|
-
const fd = openSync(dirname(this.path), 'r');
|
|
94
|
-
try {
|
|
95
|
-
fsyncSync(fd);
|
|
96
|
-
}
|
|
97
|
-
finally {
|
|
98
|
-
closeSync(fd);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
published = true;
|
|
102
|
-
};
|
|
103
|
-
const { result, next } = await fn(current, throwIfCompromised, publish);
|
|
104
|
-
throwIfCompromised();
|
|
105
|
-
if (next !== undefined)
|
|
106
|
-
publish(next);
|
|
107
|
-
throwIfCompromised();
|
|
108
|
-
return result;
|
|
109
|
-
}
|
|
110
|
-
finally {
|
|
111
|
-
if (release) {
|
|
112
|
-
try {
|
|
113
|
-
await release();
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
// A compromised lock's release throws; the compromise itself already surfaced.
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
import { type ScopedStore } from './paths.js';
|
|
3
|
-
export declare const PROFILE_ID_SHAPE: RegExp;
|
|
4
|
-
export declare function writeOwnerRoot(db: DatabaseSync, key: string, root: string): void;
|
|
5
|
-
export declare function assertScopedStoreReady(store: ScopedStore): void;
|
|
6
|
-
export declare function discardIncompleteScopedStore(store: ScopedStore): void;
|
|
7
|
-
export declare function withProjectStateLock<T>(root: string, run: () => T): T;
|
|
8
|
-
export declare function scopedStoreExists(store: ScopedStore): boolean;
|
|
9
|
-
export declare function legacyScopedStorePaths(store: ScopedStore): string[];
|
|
10
|
-
export declare function initializeFreshScopedStore(input: {
|
|
11
|
-
kind: 'user' | 'project' | 'provider';
|
|
12
|
-
root: string;
|
|
13
|
-
}): void;
|
|
14
|
-
export declare function openScopedStore(store: ScopedStore): DatabaseSync;
|
|
15
|
-
export declare function createScopedStore(store: ScopedStore, create: (db: DatabaseSync) => void): void;
|
|
16
|
-
export declare function withScopedWrite<T>(store: ScopedStore, run: (db: DatabaseSync) => T): T;
|
|
17
|
-
export declare function closeScopedStores(): void;
|
|
@@ -1,271 +0,0 @@
|
|
|
1
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
import { forgetPrepared } from '../sqlite-statements.js';
|
|
3
|
-
import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import lockfile from 'proper-lockfile';
|
|
6
|
-
import { CONFIG_FILE, PROFILE_DIR, STATE_FILE } from '../../types.js';
|
|
7
|
-
import { withExclusiveDirectoryLock } from '../exclusive-lock.js';
|
|
8
|
-
import { syncDirectory, syncFile } from '../fs-utils.js';
|
|
9
|
-
import { layoutNeedsMigration } from '../layout.js';
|
|
10
|
-
import { providerStore, projectStore, userStore } from './paths.js';
|
|
11
|
-
import { createScopedSchema, ensureProviderModelCooldowns, PROFILE_ENVIRONMENT_COLUMN, PROFILE_PROJECT_REPO_COLUMN, PROVIDER_SCHEMA_VERSION, SCOPED_SCHEMA_VERSION } from './schema.js';
|
|
12
|
-
const handles = new Map();
|
|
13
|
-
export const PROFILE_ID_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;
|
|
14
|
-
export function writeOwnerRoot(db, key, root) {
|
|
15
|
-
db.prepare('UPDATE scope_owners SET root=? WHERE owner_key=?').run(root, key);
|
|
16
|
-
}
|
|
17
|
-
function version(db) {
|
|
18
|
-
return Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
19
|
-
}
|
|
20
|
-
function assertVersion(db, store) {
|
|
21
|
-
const found = version(db);
|
|
22
|
-
if (found === 0)
|
|
23
|
-
throw new Error(`scoped SQL store is uninitialized: ${store.path}; crtr was updated and \`crtr sys daemon restart\` converts local state`);
|
|
24
|
-
const expected = store.kind === 'provider' ? PROVIDER_SCHEMA_VERSION : SCOPED_SCHEMA_VERSION;
|
|
25
|
-
if (found > expected)
|
|
26
|
-
throw new Error(`scoped SQL store ${store.path} uses unsupported schema version ${found}`);
|
|
27
|
-
if (found !== expected)
|
|
28
|
-
throw new Error(`scoped SQL store ${store.path} requires an explicit conversion`);
|
|
29
|
-
}
|
|
30
|
-
function profilesHaveEnvironmentColumn(db) {
|
|
31
|
-
return db.prepare('PRAGMA table_info(profiles)').all().some(({ name }) => name === PROFILE_ENVIRONMENT_COLUMN);
|
|
32
|
-
}
|
|
33
|
-
function hasColumn(db, table, column) {
|
|
34
|
-
return db.prepare(`PRAGMA table_info(${table})`).all().some(({ name }) => name === column);
|
|
35
|
-
}
|
|
36
|
-
function addProfileProjectRepos(db) {
|
|
37
|
-
if (!hasColumn(db, 'profile_projects', PROFILE_PROJECT_REPO_COLUMN))
|
|
38
|
-
db.exec(`ALTER TABLE profile_projects ADD COLUMN ${PROFILE_PROJECT_REPO_COLUMN} TEXT`);
|
|
39
|
-
db.exec('CREATE TABLE IF NOT EXISTS profile_project_repos (profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, repo TEXT NOT NULL, position INTEGER NOT NULL, PRIMARY KEY(profile_id,repo))');
|
|
40
|
-
}
|
|
41
|
-
function upgradeScopedStore(db, store) {
|
|
42
|
-
if (store.kind === 'provider') {
|
|
43
|
-
if (version(db) === PROVIDER_SCHEMA_VERSION) {
|
|
44
|
-
db.exec('PRAGMA busy_timeout = 5000');
|
|
45
|
-
ensureProviderModelCooldowns(db);
|
|
46
|
-
}
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
if (version(db) > SCOPED_SCHEMA_VERSION)
|
|
50
|
-
return;
|
|
51
|
-
db.exec('PRAGMA busy_timeout = 5000');
|
|
52
|
-
if (version(db) === SCOPED_SCHEMA_VERSION && profilesHaveEnvironmentColumn(db) && hasColumn(db, 'profile_projects', PROFILE_PROJECT_REPO_COLUMN))
|
|
53
|
-
return;
|
|
54
|
-
db.exec('BEGIN IMMEDIATE');
|
|
55
|
-
try {
|
|
56
|
-
if (version(db) === 1) {
|
|
57
|
-
const columns = db.prepare('PRAGMA table_info(profiles)').all();
|
|
58
|
-
if (!columns.some(({ name }) => name === 'grantee'))
|
|
59
|
-
db.exec('ALTER TABLE profiles ADD COLUMN grantee TEXT');
|
|
60
|
-
db.exec('PRAGMA user_version = 2');
|
|
61
|
-
}
|
|
62
|
-
if (version(db) === 2) {
|
|
63
|
-
const columns = db.prepare('PRAGMA table_info(profiles)').all();
|
|
64
|
-
if (columns.some(({ name }) => name === 'home'))
|
|
65
|
-
db.exec('ALTER TABLE profiles DROP COLUMN home');
|
|
66
|
-
db.exec('PRAGMA user_version = 3');
|
|
67
|
-
}
|
|
68
|
-
if (version(db) === 3) {
|
|
69
|
-
db.exec("ALTER TABLE profiles ADD COLUMN delivery_limits_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(delivery_limits_json))");
|
|
70
|
-
db.exec('PRAGMA user_version = 4');
|
|
71
|
-
}
|
|
72
|
-
if (version(db) === 4) {
|
|
73
|
-
db.exec(`CREATE TABLE IF NOT EXISTS legacy_project_caps (profile_id TEXT NOT NULL, path TEXT NOT NULL, memory TEXT NOT NULL CHECK(memory IN ('none','name','preview')), PRIMARY KEY(profile_id,path))`);
|
|
74
|
-
const columns = db.prepare('PRAGMA table_info(profile_projects)').all();
|
|
75
|
-
if (columns.some(({ name }) => name === 'memory')) {
|
|
76
|
-
db.exec(`INSERT INTO legacy_project_caps SELECT profile_id, path, memory FROM profile_projects WHERE memory != 'content';
|
|
77
|
-
ALTER TABLE profile_projects DROP COLUMN memory;`);
|
|
78
|
-
}
|
|
79
|
-
db.exec(`PRAGMA user_version = ${SCOPED_SCHEMA_VERSION}`);
|
|
80
|
-
}
|
|
81
|
-
if (version(db) === SCOPED_SCHEMA_VERSION && !profilesHaveEnvironmentColumn(db))
|
|
82
|
-
db.exec(`ALTER TABLE profiles ADD COLUMN ${PROFILE_ENVIRONMENT_COLUMN} TEXT`);
|
|
83
|
-
if (version(db) === SCOPED_SCHEMA_VERSION)
|
|
84
|
-
addProfileProjectRepos(db);
|
|
85
|
-
db.exec('COMMIT');
|
|
86
|
-
}
|
|
87
|
-
catch (error) {
|
|
88
|
-
db.exec('ROLLBACK');
|
|
89
|
-
throw error;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
export function assertScopedStoreReady(store) {
|
|
93
|
-
const db = new DatabaseSync(store.path);
|
|
94
|
-
try {
|
|
95
|
-
upgradeScopedStore(db, store);
|
|
96
|
-
assertVersion(db, store);
|
|
97
|
-
}
|
|
98
|
-
finally {
|
|
99
|
-
db.close();
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
export function discardIncompleteScopedStore(store) {
|
|
103
|
-
if (!scopedStoreExists(store))
|
|
104
|
-
return;
|
|
105
|
-
const db = new DatabaseSync(store.path, { readOnly: true });
|
|
106
|
-
let found;
|
|
107
|
-
try {
|
|
108
|
-
found = version(db);
|
|
109
|
-
}
|
|
110
|
-
finally {
|
|
111
|
-
db.close();
|
|
112
|
-
}
|
|
113
|
-
if (found === 0)
|
|
114
|
-
for (const path of [store.path, `${store.path}-wal`, `${store.path}-shm`])
|
|
115
|
-
rmSync(path, { force: true });
|
|
116
|
-
}
|
|
117
|
-
export function withProjectStateLock(root, run) {
|
|
118
|
-
return withExclusiveDirectoryLock(join(root, '.init.lock'), () => {
|
|
119
|
-
const path = join(root, STATE_FILE);
|
|
120
|
-
const deadline = Date.now() + 5_000;
|
|
121
|
-
let pollMs = 10;
|
|
122
|
-
for (;;) {
|
|
123
|
-
let release;
|
|
124
|
-
try {
|
|
125
|
-
release = lockfile.lockSync(path, { realpath: false, retries: 0, stale: 30_000, update: 10_000 });
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
if (error.code !== 'ELOCKED')
|
|
129
|
-
throw error;
|
|
130
|
-
const remaining = deadline - Date.now();
|
|
131
|
-
if (remaining <= 0)
|
|
132
|
-
throw new Error(`timed out waiting for project state conversion lock: ${path}`, { cause: error });
|
|
133
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(pollMs, remaining));
|
|
134
|
-
pollMs = Math.min(pollMs * 2, 250);
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
try {
|
|
138
|
-
return run();
|
|
139
|
-
}
|
|
140
|
-
finally {
|
|
141
|
-
release();
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
function secure(path) {
|
|
147
|
-
if (existsSync(path))
|
|
148
|
-
chmodSync(path, 0o600);
|
|
149
|
-
for (const suffix of ['-wal', '-shm'])
|
|
150
|
-
if (existsSync(`${path}${suffix}`))
|
|
151
|
-
chmodSync(`${path}${suffix}`, 0o600);
|
|
152
|
-
}
|
|
153
|
-
export function scopedStoreExists(store) {
|
|
154
|
-
return existsSync(store.path);
|
|
155
|
-
}
|
|
156
|
-
export function legacyScopedStorePaths(store) {
|
|
157
|
-
if (store.kind === 'project')
|
|
158
|
-
return [join(store.root, STATE_FILE)];
|
|
159
|
-
if (store.kind === 'provider')
|
|
160
|
-
return [join(store.root, 'anthropic-subscriptions.json'), join(store.root, 'openai-codex-subscriptions.json'), join(store.root, 'provider-rotation.json')];
|
|
161
|
-
const paths = [join(store.root, CONFIG_FILE), join(store.root, STATE_FILE), join(store.root, 'profile-defaults.json')];
|
|
162
|
-
const profiles = join(store.root, PROFILE_DIR);
|
|
163
|
-
if (existsSync(profiles))
|
|
164
|
-
for (const entry of readdirSync(profiles, { withFileTypes: true }))
|
|
165
|
-
if (entry.isDirectory() && PROFILE_ID_SHAPE.test(entry.name))
|
|
166
|
-
paths.push(join(profiles, entry.name, 'profile.json'), join(profiles, entry.name, CONFIG_FILE), join(profiles, entry.name, STATE_FILE));
|
|
167
|
-
return paths;
|
|
168
|
-
}
|
|
169
|
-
export function initializeFreshScopedStore(input) {
|
|
170
|
-
const store = input.kind === 'user' ? userStore(input.root) : input.kind === 'project' ? projectStore(input.root) : providerStore(input.root);
|
|
171
|
-
if (store.kind !== 'project')
|
|
172
|
-
mkdirSync(store.root, { recursive: true, mode: 0o700 });
|
|
173
|
-
const initialize = () => {
|
|
174
|
-
if (store.kind === 'project')
|
|
175
|
-
discardIncompleteScopedStore(store);
|
|
176
|
-
if (scopedStoreExists(store))
|
|
177
|
-
return;
|
|
178
|
-
const legacyPath = legacyScopedStorePaths(store).find(existsSync);
|
|
179
|
-
if (legacyPath !== undefined)
|
|
180
|
-
throw new Error(`legacy scoped state exists at ${legacyPath}; crtr was updated and \`crtr sys daemon restart\` converts local state`);
|
|
181
|
-
createScopedStore(store, (db) => {
|
|
182
|
-
createScopedSchema(db, store.kind);
|
|
183
|
-
if (store.kind !== 'provider')
|
|
184
|
-
writeOwnerRoot(db, store.kind, store.root);
|
|
185
|
-
});
|
|
186
|
-
};
|
|
187
|
-
if (store.kind === 'project')
|
|
188
|
-
withProjectStateLock(store.root, initialize);
|
|
189
|
-
else
|
|
190
|
-
withExclusiveDirectoryLock(join(store.root, '.init.lock'), initialize);
|
|
191
|
-
}
|
|
192
|
-
export function openScopedStore(store) {
|
|
193
|
-
if (layoutNeedsMigration())
|
|
194
|
-
throw new Error('layout_migration_required');
|
|
195
|
-
const cached = handles.get(store.path);
|
|
196
|
-
if (cached !== undefined)
|
|
197
|
-
return cached;
|
|
198
|
-
initializeFreshScopedStore(store);
|
|
199
|
-
const db = new DatabaseSync(store.path);
|
|
200
|
-
try {
|
|
201
|
-
db.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
|
|
202
|
-
upgradeScopedStore(db, store);
|
|
203
|
-
assertVersion(db, store);
|
|
204
|
-
secure(store.path);
|
|
205
|
-
handles.set(store.path, db);
|
|
206
|
-
return db;
|
|
207
|
-
}
|
|
208
|
-
catch (error) {
|
|
209
|
-
db.close();
|
|
210
|
-
throw error;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
export function createScopedStore(store, create) {
|
|
214
|
-
if (existsSync(store.path))
|
|
215
|
-
throw new Error(`scoped SQL store already exists: ${store.path}`);
|
|
216
|
-
if (store.kind !== 'project')
|
|
217
|
-
mkdirSync(store.root, { recursive: true, mode: 0o700 });
|
|
218
|
-
if (!statSync(store.root).isDirectory())
|
|
219
|
-
throw new Error(`scoped SQL root is not a directory: ${store.root}`);
|
|
220
|
-
if (store.kind !== 'project' || process.platform !== 'linux')
|
|
221
|
-
chmodSync(store.root, 0o700);
|
|
222
|
-
writeFileSync(store.path, '', { mode: 0o600 });
|
|
223
|
-
const db = new DatabaseSync(store.path);
|
|
224
|
-
try {
|
|
225
|
-
db.exec('PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; BEGIN IMMEDIATE;');
|
|
226
|
-
create(db);
|
|
227
|
-
db.exec('COMMIT');
|
|
228
|
-
}
|
|
229
|
-
catch (error) {
|
|
230
|
-
try {
|
|
231
|
-
db.exec('ROLLBACK');
|
|
232
|
-
}
|
|
233
|
-
catch { }
|
|
234
|
-
throw error;
|
|
235
|
-
}
|
|
236
|
-
finally {
|
|
237
|
-
secure(store.path);
|
|
238
|
-
db.close();
|
|
239
|
-
}
|
|
240
|
-
// Closing checkpoints the WAL into the database file. Force the finished file and its
|
|
241
|
-
// directory entry to stable storage so a volume handed off right after first boot never
|
|
242
|
-
// comes back with the empty, schema-less file that `scoped SQL store is uninitialized` names.
|
|
243
|
-
syncFile(store.path);
|
|
244
|
-
syncDirectory(store.root);
|
|
245
|
-
}
|
|
246
|
-
export function withScopedWrite(store, run) {
|
|
247
|
-
const db = openScopedStore(store);
|
|
248
|
-
if (db.isTransaction)
|
|
249
|
-
return run(db);
|
|
250
|
-
db.exec('BEGIN IMMEDIATE');
|
|
251
|
-
try {
|
|
252
|
-
const value = run(db);
|
|
253
|
-
db.exec('COMMIT');
|
|
254
|
-
secure(store.path);
|
|
255
|
-
return value;
|
|
256
|
-
}
|
|
257
|
-
catch (error) {
|
|
258
|
-
try {
|
|
259
|
-
db.exec('ROLLBACK');
|
|
260
|
-
}
|
|
261
|
-
catch { }
|
|
262
|
-
throw error;
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
export function closeScopedStores() {
|
|
266
|
-
for (const db of handles.values()) {
|
|
267
|
-
forgetPrepared(db);
|
|
268
|
-
db.close();
|
|
269
|
-
}
|
|
270
|
-
handles.clear();
|
|
271
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import type { PersonSnapshot } from './person-store.js';
|
|
2
|
-
/** The old user store's contents in the shape of a person's snapshot, or null when this install never had a store. */
|
|
3
|
-
export declare function readLegacyUserSnapshot(root: string): PersonSnapshot | null;
|
|
4
|
-
/** Pre-canvas per-project memory caps (`none|name|preview`) the canvas import has not converted yet. */
|
|
5
|
-
export declare function listLegacyProjectCaps(root: string): Array<{
|
|
6
|
-
profileId: string;
|
|
7
|
-
path: string;
|
|
8
|
-
memory: string;
|
|
9
|
-
}>;
|
|
10
|
-
/** Delete every legacy cap row once the canvas import has stored the converted limits on the profile rows. */
|
|
11
|
-
export declare function deleteLegacyProjectCaps(root: string): void;
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
// legacy-profiles.ts — the old per-install SQLite user store (`operations.db`), read-only. It survives only as the source of the
|
|
2
|
-
// one-time boot copy into Postgres rows (migrate.ts) and of the pre-canvas per-project memory caps the canvas import (migration
|
|
3
|
-
// 004) converts. Nothing writes profiles, settings or bookkeeping here any more: those are rows (person-store.ts).
|
|
4
|
-
import { prepared as cachedStatement } from '../sqlite-statements.js';
|
|
5
|
-
import { userStore } from './paths.js';
|
|
6
|
-
import { openScopedStore, scopedStoreExists, withScopedWrite } from './db.js';
|
|
7
|
-
/** The old user store's contents in the shape of a person's snapshot, or null when this install never had a store. */
|
|
8
|
-
export function readLegacyUserSnapshot(root) {
|
|
9
|
-
const store = userStore(root);
|
|
10
|
-
if (!scopedStoreExists(store))
|
|
11
|
-
return null;
|
|
12
|
-
const db = openScopedStore(store);
|
|
13
|
-
const hasRepos = db.prepare('PRAGMA table_info(profile_projects)').all().some(({ name }) => name === 'repo');
|
|
14
|
-
const projects = (hasRepos
|
|
15
|
-
? db.prepare(`SELECT profile_id, path, repo, position FROM (SELECT profile_id, path, repo, position FROM profile_projects
|
|
16
|
-
UNION ALL SELECT profile_id, NULL, repo, position FROM profile_project_repos) ORDER BY profile_id, position`).all()
|
|
17
|
-
: db.prepare('SELECT profile_id, path, NULL AS repo, position FROM profile_projects ORDER BY profile_id, position').all());
|
|
18
|
-
const profiles = cachedStatement(db, 'SELECT id, name, created_at, last_used_at, paused_at, default_kind, grantee, metadata_json, delivery_limits_json, environment_id FROM profiles ORDER BY rowid').all().map((r) => {
|
|
19
|
-
const metadata = JSON.parse(r.metadata_json);
|
|
20
|
-
const limits = JSON.parse(r.delivery_limits_json);
|
|
21
|
-
return {
|
|
22
|
-
profileId: r.id,
|
|
23
|
-
manifest: {
|
|
24
|
-
schema_version: 1, name: r.name, projects: projects.filter((x) => x.profile_id === r.id).map((x) => ({ ...(x.repo === null ? {} : { repo: x.repo }), ...(x.path === null ? {} : { path: x.path }) })), paused_at: r.paused_at,
|
|
25
|
-
...(r.default_kind === null ? {} : { default_kind: r.default_kind }), ...(r.grantee === null ? {} : { grantee: r.grantee }),
|
|
26
|
-
...(r.environment_id === null ? {} : { environment_id: r.environment_id }),
|
|
27
|
-
...(Object.keys(limits).length === 0 ? {} : { delivery_limits: limits }), ...(Object.keys(metadata).length === 0 ? {} : { metadata }),
|
|
28
|
-
created_at: r.created_at, last_used_at: r.last_used_at,
|
|
29
|
-
},
|
|
30
|
-
};
|
|
31
|
-
});
|
|
32
|
-
const defaults = Object.fromEntries(cachedStatement(db, 'SELECT directory, profile_id FROM profile_defaults').all().map((r) => [r.directory, r.profile_id]));
|
|
33
|
-
const settings = {};
|
|
34
|
-
for (const r of cachedStatement(db, "SELECT owner_key, raw_json FROM scope_settings WHERE owner_key != 'project'").all())
|
|
35
|
-
settings[r.owner_key] = JSON.parse(r.raw_json);
|
|
36
|
-
const state = {};
|
|
37
|
-
const stateOf = (owner) => (state[owner] ??= { marketplaces: {}, plugins: {}, activeCanvas: null });
|
|
38
|
-
for (const r of cachedStatement(db, "SELECT owner_key, last_self_check, active_canvas FROM scope_bookkeeping WHERE owner_key != 'project'").all()) {
|
|
39
|
-
const st = stateOf(r.owner_key);
|
|
40
|
-
if (r.last_self_check !== null)
|
|
41
|
-
st.last_self_check = r.last_self_check;
|
|
42
|
-
st.activeCanvas = r.active_canvas;
|
|
43
|
-
}
|
|
44
|
-
for (const r of cachedStatement(db, "SELECT owner_key, name, last_updated FROM scope_marketplaces WHERE owner_key != 'project'").all())
|
|
45
|
-
stateOf(r.owner_key).marketplaces[r.name] = r.last_updated === null ? {} : { last_updated: r.last_updated };
|
|
46
|
-
for (const r of cachedStatement(db, "SELECT owner_key, name, last_updated, etag, checked_at FROM scope_plugins WHERE owner_key != 'project'").all()) {
|
|
47
|
-
stateOf(r.owner_key).plugins[r.name] = { ...(r.last_updated === null ? {} : { last_updated: r.last_updated }), ...(r.etag === null ? {} : { etag: r.etag }), ...(r.checked_at === null ? {} : { checked_at: r.checked_at }) };
|
|
48
|
-
}
|
|
49
|
-
return { profiles, defaults, settings, state, apps: {} };
|
|
50
|
-
}
|
|
51
|
-
/** Pre-canvas per-project memory caps (`none|name|preview`) the canvas import has not converted yet. */
|
|
52
|
-
export function listLegacyProjectCaps(root) {
|
|
53
|
-
const store = userStore(root);
|
|
54
|
-
if (!scopedStoreExists(store))
|
|
55
|
-
return [];
|
|
56
|
-
return cachedStatement(openScopedStore(store), 'SELECT profile_id, path, memory FROM legacy_project_caps ORDER BY profile_id, path').all()
|
|
57
|
-
.map((r) => ({ profileId: r.profile_id, path: r.path, memory: r.memory }));
|
|
58
|
-
}
|
|
59
|
-
/** Delete every legacy cap row once the canvas import has stored the converted limits on the profile rows. */
|
|
60
|
-
export function deleteLegacyProjectCaps(root) {
|
|
61
|
-
const store = userStore(root);
|
|
62
|
-
if (!scopedStoreExists(store))
|
|
63
|
-
return;
|
|
64
|
-
withScopedWrite(store, (db) => { cachedStatement(db, 'DELETE FROM legacy_project_caps').run(); });
|
|
65
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { type PersonSnapshot } from './person-store.js';
|
|
2
|
-
/** Conversion is intentionally explicit. Deployment coordination must prove all legacy writers at these shared roots are stopped before calling it. */
|
|
3
|
-
export declare function convertLegacyScopedStore(input: {
|
|
4
|
-
kind: 'user' | 'project' | 'provider';
|
|
5
|
-
root: string;
|
|
6
|
-
}): void;
|
|
7
|
-
/** Converts legacy provider pools only after the activation owner has stopped every writer sharing this agent directory. */
|
|
8
|
-
export declare function convertLegacyProviderStore(agentDir: string): Promise<void>;
|
|
9
|
-
export declare function personStoresCopied(): Promise<boolean>;
|
|
10
|
-
/** Copy this install's files into the person's rows, once: profiles, scope settings and bookkeeping, the plugin and marketplace
|
|
11
|
-
* lists, managed model accounts with their cooldowns, rotation settings, the OpenAI device id, `auth.json` API keys and the profile, app and deployment env files (sealed into `env_vars`). One
|
|
12
|
-
* transaction, skipping any key a row already holds, ending with `canvas_meta.person_stores_copied`. The files stay, unread. */
|
|
13
|
-
export declare function copyPersonStoresToRows(person: string, legacyUserSnapshot: PersonSnapshot | null, agentDir: string): Promise<void>;
|
|
14
|
-
/** The install's person just became known: copy the old local files into their rows once, then load their snapshot. */
|
|
15
|
-
export declare function adoptInstallPerson(person: string): Promise<void>;
|