@agentic-kit/pi 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +5 -7
  2. package/confirm-gate.d.ts +1 -2
  3. package/esm/confirm-gate.d.ts +1 -2
  4. package/esm/host.d.ts +5 -110
  5. package/esm/host.js +5 -18
  6. package/esm/index.d.ts +17 -9
  7. package/esm/index.js +20 -38
  8. package/esm/pi-tool.d.ts +16 -0
  9. package/esm/pi-tool.js +32 -0
  10. package/host.d.ts +5 -110
  11. package/host.js +10 -22
  12. package/index.d.ts +17 -9
  13. package/index.js +47 -62
  14. package/package.json +6 -10
  15. package/pi-tool.d.ts +16 -0
  16. package/pi-tool.js +36 -0
  17. package/app-workspace.d.ts +0 -16
  18. package/app-workspace.js +0 -145
  19. package/context.d.ts +0 -62
  20. package/context.js +0 -282
  21. package/db-probe.d.ts +0 -30
  22. package/db-probe.js +0 -50
  23. package/esm/app-workspace.d.ts +0 -16
  24. package/esm/app-workspace.js +0 -134
  25. package/esm/context.d.ts +0 -62
  26. package/esm/context.js +0 -270
  27. package/esm/db-probe.d.ts +0 -30
  28. package/esm/db-probe.js +0 -47
  29. package/esm/policy/add-policies-to-table.d.ts +0 -26
  30. package/esm/policy/add-policies-to-table.js +0 -66
  31. package/esm/policy/provision-helpers.d.ts +0 -38
  32. package/esm/policy/provision-helpers.js +0 -50
  33. package/esm/provision-database/credential.d.ts +0 -14
  34. package/esm/provision-database/credential.js +0 -19
  35. package/esm/provision-database/env-file.d.ts +0 -37
  36. package/esm/provision-database/env-file.js +0 -85
  37. package/esm/provision-database/manifest.d.ts +0 -10
  38. package/esm/provision-database/manifest.js +0 -48
  39. package/esm/provision-database/pg-fixups.d.ts +0 -16
  40. package/esm/provision-database/pg-fixups.js +0 -132
  41. package/esm/provision-database/preset-match.d.ts +0 -13
  42. package/esm/provision-database/preset-match.js +0 -66
  43. package/esm/provision-database/presets.d.ts +0 -4
  44. package/esm/provision-database/presets.js +0 -13
  45. package/esm/provision-database/request-database.d.ts +0 -61
  46. package/esm/provision-database/request-database.js +0 -130
  47. package/esm/provision-database/resolve.d.ts +0 -27
  48. package/esm/provision-database/resolve.js +0 -49
  49. package/esm/records/meta.d.ts +0 -41
  50. package/esm/records/meta.js +0 -167
  51. package/esm/run-codegen/barrels.d.ts +0 -3
  52. package/esm/run-codegen/barrels.js +0 -48
  53. package/esm/run-codegen/endpoints.d.ts +0 -8
  54. package/esm/run-codegen/endpoints.js +0 -46
  55. package/esm/schema-resolve.d.ts +0 -23
  56. package/esm/schema-resolve.js +0 -69
  57. package/esm/tool-schema.d.ts +0 -3
  58. package/esm/tool-schema.js +0 -10
  59. package/esm/tools/add-policies.d.ts +0 -8
  60. package/esm/tools/add-policies.js +0 -96
  61. package/esm/tools/add-records.d.ts +0 -14
  62. package/esm/tools/add-records.js +0 -124
  63. package/esm/tools/add-relation-schema.d.ts +0 -30
  64. package/esm/tools/add-relation-schema.js +0 -58
  65. package/esm/tools/add-relation.d.ts +0 -10
  66. package/esm/tools/add-relation.js +0 -91
  67. package/esm/tools/create-api-key.d.ts +0 -18
  68. package/esm/tools/create-api-key.js +0 -216
  69. package/esm/tools/describe-schema.d.ts +0 -18
  70. package/esm/tools/describe-schema.js +0 -132
  71. package/esm/tools/manage-entity-types.d.ts +0 -41
  72. package/esm/tools/manage-entity-types.js +0 -203
  73. package/esm/tools/mutations.d.ts +0 -14
  74. package/esm/tools/mutations.js +0 -235
  75. package/esm/tools/provision-blueprint.d.ts +0 -22
  76. package/esm/tools/provision-blueprint.js +0 -111
  77. package/esm/tools/provision-database.d.ts +0 -14
  78. package/esm/tools/provision-database.js +0 -262
  79. package/esm/tools/run-codegen.d.ts +0 -11
  80. package/esm/tools/run-codegen.js +0 -139
  81. package/esm/tools/templates.d.ts +0 -49
  82. package/esm/tools/templates.js +0 -337
  83. package/policy/add-policies-to-table.d.ts +0 -26
  84. package/policy/add-policies-to-table.js +0 -71
  85. package/policy/provision-helpers.d.ts +0 -38
  86. package/policy/provision-helpers.js +0 -58
  87. package/provision-database/credential.d.ts +0 -14
  88. package/provision-database/credential.js +0 -22
  89. package/provision-database/env-file.d.ts +0 -37
  90. package/provision-database/env-file.js +0 -91
  91. package/provision-database/manifest.d.ts +0 -10
  92. package/provision-database/manifest.js +0 -56
  93. package/provision-database/pg-fixups.d.ts +0 -16
  94. package/provision-database/pg-fixups.js +0 -170
  95. package/provision-database/preset-match.d.ts +0 -13
  96. package/provision-database/preset-match.js +0 -70
  97. package/provision-database/presets.d.ts +0 -4
  98. package/provision-database/presets.js +0 -17
  99. package/provision-database/request-database.d.ts +0 -61
  100. package/provision-database/request-database.js +0 -134
  101. package/provision-database/resolve.d.ts +0 -27
  102. package/provision-database/resolve.js +0 -53
  103. package/records/meta.d.ts +0 -41
  104. package/records/meta.js +0 -172
  105. package/run-codegen/barrels.d.ts +0 -3
  106. package/run-codegen/barrels.js +0 -54
  107. package/run-codegen/endpoints.d.ts +0 -8
  108. package/run-codegen/endpoints.js +0 -51
  109. package/schema-resolve.d.ts +0 -23
  110. package/schema-resolve.js +0 -75
  111. package/tool-schema.d.ts +0 -3
  112. package/tool-schema.js +0 -13
  113. package/tools/add-policies.d.ts +0 -8
  114. package/tools/add-policies.js +0 -99
  115. package/tools/add-records.d.ts +0 -14
  116. package/tools/add-records.js +0 -127
  117. package/tools/add-relation-schema.d.ts +0 -30
  118. package/tools/add-relation-schema.js +0 -62
  119. package/tools/add-relation.d.ts +0 -10
  120. package/tools/add-relation.js +0 -94
  121. package/tools/create-api-key.d.ts +0 -18
  122. package/tools/create-api-key.js +0 -222
  123. package/tools/describe-schema.d.ts +0 -18
  124. package/tools/describe-schema.js +0 -135
  125. package/tools/manage-entity-types.d.ts +0 -41
  126. package/tools/manage-entity-types.js +0 -208
  127. package/tools/mutations.d.ts +0 -14
  128. package/tools/mutations.js +0 -238
  129. package/tools/provision-blueprint.d.ts +0 -22
  130. package/tools/provision-blueprint.js +0 -114
  131. package/tools/provision-database.d.ts +0 -14
  132. package/tools/provision-database.js +0 -268
  133. package/tools/run-codegen.d.ts +0 -11
  134. package/tools/run-codegen.js +0 -143
  135. package/tools/templates.d.ts +0 -49
  136. package/tools/templates.js +0 -341
@@ -1,85 +0,0 @@
1
- // Pure .env merge — used by provision_database to persist provisioning
2
- // credentials without clobbering existing keys: replace a key in place if
3
- // present, else append.
4
- // Kept side-effect-free so it is unit-testable (the tool does the fs write).
5
- /**
6
- * Upsert `vars` into the existing `.env` `content`. Existing keys are replaced
7
- * in place (preserving surrounding lines/comments); new keys are appended.
8
- * Returns the new file body, trailing-newline-terminated.
9
- */
10
- export function mergeEnv(content, vars) {
11
- let out = content;
12
- for (const [key, val] of Object.entries(vars)) {
13
- // Escape the key for the regex, and use a replacement function so `$`
14
- // sequences in the value are never treated as replacement specials.
15
- const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
16
- const regex = new RegExp(`^${escapedKey}=.*`, 'm');
17
- if (regex.test(out))
18
- out = out.replace(regex, () => `${key}=${val}`);
19
- else
20
- out += `\n${key}=${val}`;
21
- }
22
- return out.trim() + '\n';
23
- }
24
- /** The credential keys provision_database owns in a project's .env. */
25
- export const PROVISION_ENV_KEYS = [
26
- 'DATABASE_ID',
27
- 'DATABASE_NAME',
28
- 'OWNER_ID',
29
- 'ACCESS_TOKEN',
30
- 'PGDATABASE',
31
- 'API_ENDPOINT',
32
- 'MODULES_ENDPOINT',
33
- ];
34
- /**
35
- * Keys archived as comments on reprovision — the binding identity: which
36
- * database, under whom, on which backend. ACCESS_TOKEN is the account login
37
- * token, identical across bindings, so it is overwritten in place rather than
38
- * archived.
39
- */
40
- export const ARCHIVED_BINDING_KEYS = [
41
- 'DATABASE_ID',
42
- 'DATABASE_NAME',
43
- 'OWNER_ID',
44
- 'PGDATABASE',
45
- 'API_ENDPOINT',
46
- 'MODULES_ENDPOINT',
47
- ];
48
- /**
49
- * Build the provisioning credential block written to a project's .env. The
50
- * endpoint pins record which backend owns this binding — outside-app consumers
51
- * (verify-feature.sh, skill scripts, dev-server shells) resolve them instead of
52
- * falling back to localhost defaults when the app targets a hosted backend.
53
- */
54
- export function provisionEnvVars(args) {
55
- return {
56
- DATABASE_ID: args.databaseId,
57
- DATABASE_NAME: args.databaseName,
58
- OWNER_ID: args.ownerId,
59
- ACCESS_TOKEN: args.accessToken,
60
- PGDATABASE: args.databaseName,
61
- API_ENDPOINT: args.apiEndpoint,
62
- MODULES_ENDPOINT: args.modulesEndpoint,
63
- };
64
- }
65
- /**
66
- * Comment out the given keys in place (`# archived <date>: KEY=value`) so a
67
- * reprovision keeps the previous binding readable in the file instead of
68
- * silently overwriting it. Every other line — including existing comments and
69
- * already-archived entries — passes through untouched.
70
- */
71
- export function archiveBindingKeys(content, keys, archivedOn) {
72
- const keySet = new Set(keys);
73
- return content
74
- .split('\n')
75
- .map((line) => {
76
- if (line.trimStart().startsWith('#'))
77
- return line;
78
- const eq = line.indexOf('=');
79
- if (eq === -1)
80
- return line;
81
- const key = line.slice(0, eq).trim();
82
- return keySet.has(key) ? `# archived ${archivedOn}: ${line.trim()}` : line;
83
- })
84
- .join('\n');
85
- }
@@ -1,10 +0,0 @@
1
- import type { ProvisionOverlay } from './resolve';
2
- export declare const PROVISION_MANIFEST_FILE = "provision.json";
3
- export type ProvisionManifest = ProvisionOverlay;
4
- /** Validate an untrusted value as a provision manifest, throwing on bad shape. */
5
- export declare function parseProvisionManifest(value: unknown): ProvisionManifest;
6
- /**
7
- * Load `<dir>/provision.json` as an overlay, or `null` when absent. A malformed
8
- * file throws so a broken overlay is surfaced rather than silently ignored.
9
- */
10
- export declare function loadProvisionManifest(dir: string): Promise<ProvisionManifest | null>;
@@ -1,48 +0,0 @@
1
- // `provision.json` overlay manifest.
2
- //
3
- // A pure-data overlay, distributed the same way skills are: written into a
4
- // config/app directory (locally, or materialized there from appstash / a pinned
5
- // git ref) and read at provision time. It NEVER installs or executes a package
6
- // — the base preset is a pinned build-time dependency; this file only selects a
7
- // preset and layers add/remove on top.
8
- import { readFile } from 'node:fs/promises';
9
- import path from 'node:path';
10
- import { z } from 'zod';
11
- export const PROVISION_MANIFEST_FILE = 'provision.json';
12
- const ModuleSchema = z.union([
13
- z.string(),
14
- z.tuple([z.string(), z.record(z.string(), z.unknown())]),
15
- ]);
16
- const ProvisionManifestSchema = z
17
- .object({
18
- preset: z.string().optional(),
19
- add: z.array(ModuleSchema).optional(),
20
- remove: z.array(z.string()).optional(),
21
- })
22
- .strict();
23
- /** Validate an untrusted value as a provision manifest, throwing on bad shape. */
24
- export function parseProvisionManifest(value) {
25
- return ProvisionManifestSchema.parse(value);
26
- }
27
- /**
28
- * Load `<dir>/provision.json` as an overlay, or `null` when absent. A malformed
29
- * file throws so a broken overlay is surfaced rather than silently ignored.
30
- */
31
- export async function loadProvisionManifest(dir) {
32
- const file = path.join(dir, PROVISION_MANIFEST_FILE);
33
- let raw;
34
- try {
35
- raw = await readFile(file, 'utf8');
36
- }
37
- catch {
38
- return null;
39
- }
40
- let parsed;
41
- try {
42
- parsed = JSON.parse(raw);
43
- }
44
- catch (err) {
45
- throw new Error(`Invalid ${PROVISION_MANIFEST_FILE} at ${file}: ${err instanceof Error ? err.message : String(err)}`);
46
- }
47
- return parseProvisionManifest(parsed);
48
- }
@@ -1,16 +0,0 @@
1
- export type FixupResult = {
2
- applied: boolean;
3
- note: string;
4
- };
5
- export type PgEnv = {
6
- host?: string;
7
- port?: string;
8
- user?: string;
9
- password?: string;
10
- };
11
- export declare function parsePgpmEnv(stdout: string): PgEnv;
12
- export declare function resolvePgEnv(): Promise<PgEnv | null>;
13
- export declare function applySqlFixups(args: {
14
- databaseName: string;
15
- physicalDb: string;
16
- }): Promise<FixupResult>;
@@ -1,132 +0,0 @@
1
- // Post-provision SQL fixups for a freshly provisioned database.
2
- //
3
- // Two things must happen at the Postgres level that the provisioning GraphQL API
4
- // does not do for us:
5
- //
6
- // 1. Naming settings — `constructive.simple_schema_names` and
7
- // `schema_use_underscores` make later `provision_blueprint` calls create an
8
- // `app_public` schema (which resolveSchemaId looks for) instead of a
9
- // hyphenated `<db>-<hex>-app-public` one. These ALTER DATABASE settings
10
- // PERSIST, so we set them once here, before any blueprint construction.
11
- //
12
- // 2. Membership defaults — new sign-ups otherwise land with
13
- // is_approved=false/is_verified=false, the AuthzEntityMembership policy then
14
- // denies every insert/select, and CRUD rows silently never persist
15
- // (BLUEPRINT-PENDING-001). We flip the defaults (future sign-ups) AND any
16
- // memberships already created during provisioning.
17
- //
18
- // All SQL targets the PHYSICAL control-plane database (`constructive`), NOT the
19
- // app's database name — that name is only a schema prefix (MEMBERSHIP-DB-001).
20
- //
21
- // Connection creds come from the ambient PG* env vars, falling back to sourcing
22
- // `pgpm env` (the same mechanism the old `eval "$(pgpm env)"` shell step used).
23
- // If neither yields a connection, provisioning still succeeded — we return a
24
- // note so the tool can warn the user that sign-in/CRUD may need a manual fixup.
25
- import { execFile } from 'node:child_process';
26
- import { promisify } from 'node:util';
27
- const execFileAsync = promisify(execFile);
28
- // Parse `pgpm env` output. It prints shell assignments (optionally `export`-
29
- // prefixed), one per line: `export PGHOST=localhost`. Quotes are stripped.
30
- export function parsePgpmEnv(stdout) {
31
- const env = {};
32
- for (const rawLine of stdout.split('\n')) {
33
- const line = rawLine.trim().replace(/^export\s+/, '');
34
- const eq = line.indexOf('=');
35
- if (eq === -1)
36
- continue;
37
- const key = line.slice(0, eq).trim();
38
- let value = line.slice(eq + 1).trim();
39
- if ((value.startsWith('"') && value.endsWith('"')) ||
40
- (value.startsWith("'") && value.endsWith("'"))) {
41
- value = value.slice(1, -1);
42
- }
43
- env[key] = value;
44
- }
45
- return {
46
- host: env.PGHOST,
47
- port: env.PGPORT,
48
- user: env.PGUSER,
49
- password: env.PGPASSWORD,
50
- };
51
- }
52
- export async function resolvePgEnv() {
53
- if (process.env.PGHOST) {
54
- return {
55
- host: process.env.PGHOST,
56
- port: process.env.PGPORT,
57
- user: process.env.PGUSER,
58
- password: process.env.PGPASSWORD,
59
- };
60
- }
61
- try {
62
- const { stdout } = await execFileAsync('pgpm', ['env'], { timeout: 15_000 });
63
- const parsed = parsePgpmEnv(stdout);
64
- return parsed.host ? parsed : null;
65
- }
66
- catch {
67
- return null;
68
- }
69
- }
70
- // Find the memberships schema for this app. Schema names use hyphens locally
71
- // (`<db>-<hex>-memberships-public`) but may use underscores when the naming
72
- // settings are active — match both, scoped to this app's name prefix.
73
- const MEMBERSHIPS_SCHEMA_QUERY = `
74
- SELECT schema_name FROM information_schema.schemata
75
- WHERE (schema_name LIKE '%memberships-public' OR schema_name LIKE '%memberships_public')
76
- AND (schema_name LIKE $1 OR schema_name LIKE $2)
77
- ORDER BY schema_name DESC LIMIT 1`;
78
- export async function applySqlFixups(args) {
79
- const pgEnv = await resolvePgEnv();
80
- if (!pgEnv) {
81
- return {
82
- applied: false,
83
- note: 'Could not reach Postgres (no PGHOST and `pgpm env` unavailable). Database provisioned, but membership defaults were not enabled — sign-in/CRUD may fail until the constructive DB is fixed up manually.',
84
- };
85
- }
86
- // pg is dynamically imported so the main bundle never loads it unless a
87
- // provision actually runs with Postgres access. The import lives inside the
88
- // try: fixups are best-effort, so even a broken pg module must degrade to a
89
- // note instead of failing the tool after the database is already provisioned.
90
- let pool;
91
- try {
92
- const { Pool } = await import('pg');
93
- pool = new Pool({
94
- host: pgEnv.host,
95
- port: pgEnv.port ? Number(pgEnv.port) : undefined,
96
- user: pgEnv.user,
97
- password: pgEnv.password,
98
- database: args.physicalDb,
99
- });
100
- const db = args.physicalDb;
101
- // Persistent naming settings — so future provision_blueprint calls land an
102
- // `app_public` schema resolveSchemaId can find.
103
- await pool.query(`ALTER DATABASE "${db}" SET constructive.simple_schema_names = 'true'`);
104
- await pool.query(`ALTER DATABASE "${db}" SET constructive.schema_use_underscores = 'true'`);
105
- const schemaResult = await pool.query(MEMBERSHIPS_SCHEMA_QUERY, [
106
- `${args.databaseName}-%`,
107
- `${args.databaseName}\\_%`,
108
- ]);
109
- if (schemaResult.rows.length === 0) {
110
- return {
111
- applied: true,
112
- note: `Naming settings applied, but no memberships schema was found for "${args.databaseName}" — sign-in may need a manual membership fixup.`,
113
- };
114
- }
115
- const membershipsSchema = schemaResult.rows[0].schema_name;
116
- await pool.query(`UPDATE "${membershipsSchema}".app_membership_defaults SET is_approved = TRUE, is_verified = TRUE`);
117
- await pool.query(`UPDATE "${membershipsSchema}".app_memberships
118
- SET is_approved = TRUE, is_verified = TRUE
119
- WHERE is_approved = FALSE OR is_verified = FALSE`);
120
- return { applied: true, note: `Membership defaults enabled (schema: ${membershipsSchema}).` };
121
- }
122
- catch (err) {
123
- const message = err instanceof Error ? err.message : String(err);
124
- return {
125
- applied: false,
126
- note: `Database provisioned, but SQL fixups failed (${message}). Sign-in/CRUD may fail until membership defaults are enabled manually.`,
127
- };
128
- }
129
- finally {
130
- await pool?.end().catch(() => { });
131
- }
132
- }
@@ -1,13 +0,0 @@
1
- import { type ProvisionModule } from './presets';
2
- import type { ProvisionRequest } from './request-database';
3
- /**
4
- * The slug of the registry preset whose module set equals `resolved` under
5
- * the backend's hash semantics, or undefined when no preset matches.
6
- */
7
- export declare function matchPresetSlug(resolved: ProvisionModule[]): string | undefined;
8
- /**
9
- * Build the requestDatabase input branch: presetSlug when the resolved set
10
- * equals a registry preset (warm-pool eligible), else the explicit modules
11
- * array — never both.
12
- */
13
- export declare function selectProvisionRequest(resolved: ProvisionModule[]): ProvisionRequest;
@@ -1,66 +0,0 @@
1
- // Client-side mirror of the backend's modules_hash normalization
2
- // (constructive-db: metaschema_private.modules_hash), used to decide whether a
3
- // resolved module set can be requested by preset slug — the warm-pool-eligible
4
- // path — or must be sent as an explicit modules array:
5
- // 1. A bare module name normalizes to [name, {}]; a missing/null options
6
- // slot normalizes to {}.
7
- // 2. Options are compared verbatim after canonicalization (object keys
8
- // sorted at every level) — no default-value normalization.
9
- // 3. Entries are sorted so the caller's ordering never affects the match.
10
- // 4. Duplicate normalized entries never match (the backend rejects them).
11
- // Only equality within this process matters, so string sort order does not
12
- // need to replicate PostgreSQL collation.
13
- //
14
- // The registry presets are the canonical definitions; the backend's
15
- // db_presets catalog is synced from them. A slug match assumes that sync —
16
- // preset drift would provision the backend's version of the set.
17
- import { allModulePresets } from './presets';
18
- function canonicalize(value) {
19
- if (Array.isArray(value))
20
- return value.map(canonicalize);
21
- if (value && typeof value === 'object') {
22
- const sorted = {};
23
- for (const key of Object.keys(value).sort()) {
24
- sorted[key] = canonicalize(value[key]);
25
- }
26
- return sorted;
27
- }
28
- return value;
29
- }
30
- function normalizedEntries(list) {
31
- const entries = list.map((m) => {
32
- const name = Array.isArray(m) ? m[0] : m;
33
- const options = Array.isArray(m) ? (m[1] ?? {}) : {};
34
- return JSON.stringify([name, canonicalize(options)]);
35
- });
36
- entries.sort();
37
- for (let i = 1; i < entries.length; i++) {
38
- if (entries[i] === entries[i - 1])
39
- return null;
40
- }
41
- return entries;
42
- }
43
- /**
44
- * The slug of the registry preset whose module set equals `resolved` under
45
- * the backend's hash semantics, or undefined when no preset matches.
46
- */
47
- export function matchPresetSlug(resolved) {
48
- const target = normalizedEntries(resolved)?.join('\n');
49
- if (!target)
50
- return undefined;
51
- for (const preset of allModulePresets) {
52
- if (normalizedEntries(preset.modules)?.join('\n') === target) {
53
- return preset.name;
54
- }
55
- }
56
- return undefined;
57
- }
58
- /**
59
- * Build the requestDatabase input branch: presetSlug when the resolved set
60
- * equals a registry preset (warm-pool eligible), else the explicit modules
61
- * array — never both.
62
- */
63
- export function selectProvisionRequest(resolved) {
64
- const presetSlug = matchPresetSlug(resolved);
65
- return presetSlug ? { presetSlug } : { modules: resolved };
66
- }
@@ -1,4 +0,0 @@
1
- import { allModulePresets, getModulePreset, type ModulePreset } from 'node-type-registry';
2
- export type ProvisionModule = string | [string, Record<string, unknown>];
3
- export declare const DEFAULT_PROVISION_PRESET: string;
4
- export { allModulePresets, getModulePreset, type ModulePreset };
@@ -1,13 +0,0 @@
1
- // Provision module presets — the canonical source of truth.
2
- //
3
- // The module list is NEVER hand-copied here. It is imported from the pinned
4
- // `node-type-registry` package (the same presets the backend and dashboard use),
5
- // so bumping that dependency is how the base module set moves. Hosts customize
6
- // on top with an ordered overlay (see `resolve.ts`) rather than editing a list.
7
- import { allModulePresets, getModulePreset, PresetB2bStorage, } from 'node-type-registry';
8
- // Default base preset. `b2b:storage` = the full multi-tenant B2B shape plus file
9
- // storage, matching Constructive's app shape. It carries the app-scoped secret,
10
- // identity-provider, and storage modules the backend's provisioning requires —
11
- // the drift the old hand-copied list caused (a dropped, then bare/unscoped, set).
12
- export const DEFAULT_PROVISION_PRESET = PresetB2bStorage.name;
13
- export { allModulePresets, getModulePreset };
@@ -1,61 +0,0 @@
1
- import type { ProvisionModule } from './presets';
2
- /**
3
- * Exactly one of presetSlug or modules — requestDatabase rejects both/neither
4
- * (REQUEST_DATABASE_INVALID_INPUT). `selectProvisionRequest` (preset-match.ts)
5
- * builds this from the resolved module set.
6
- */
7
- export type ProvisionRequest = {
8
- presetSlug: string;
9
- } | {
10
- modules: ProvisionModule[];
11
- };
12
- export type ProvisionTicket = {
13
- id?: string | null;
14
- status?: string | null;
15
- bootstrapStatus?: string | null;
16
- databaseId?: string | null;
17
- errorMessage?: string | null;
18
- bootstrapError?: string | null;
19
- };
20
- /**
21
- * Request + poll seam, injectable for tests (pattern: db-probe's
22
- * ProbeExecutor). The default executor drives the SDK clients.
23
- */
24
- export type ProvisionRequestExecutor = {
25
- request(input: {
26
- databaseName: string;
27
- subdomain: string;
28
- domain: string;
29
- request: ProvisionRequest;
30
- }): Promise<ProvisionTicket>;
31
- poll(ticketId: string): Promise<ProvisionTicket | null>;
32
- };
33
- export declare const POLL_INTERVAL_MS = 2000;
34
- /** Stays under airpage's 5-minute per-tool timeout. */
35
- export declare const POLL_DEADLINE_MS = 240000;
36
- /**
37
- * Consecutive unreadable polls tolerated before giving up. Provisioning keeps
38
- * running server-side, so a dropped request or a momentary 502 must not abort
39
- * a creation that is about to succeed.
40
- */
41
- export declare const MAX_CONSECUTIVE_POLL_FAILURES = 3;
42
- /**
43
- * Request a database and resolve only when it is fully usable: ticket
44
- * `status` AND `bootstrapStatus` both 'completed'. The ticket the mutation
45
- * returns is checked before the first sleep, so a warm claim with bootstrap
46
- * already done never waits. `status: 'failed'` surfaces `errorMessage`;
47
- * `bootstrapStatus: 'failed'` surfaces `bootstrapError`.
48
- */
49
- export declare function requestDatabaseProvision(args: {
50
- apiEndpoint: string;
51
- modulesEndpoint: string;
52
- bearer: string;
53
- databaseName: string;
54
- domain: string;
55
- request: ProvisionRequest;
56
- executor?: ProvisionRequestExecutor;
57
- pollIntervalMs?: number;
58
- pollDeadlineMs?: number;
59
- }): Promise<{
60
- databaseId: string;
61
- }>;
@@ -1,130 +0,0 @@
1
- // Provision a database through the api endpoint's requestDatabase mutation —
2
- // the pool-aware entry point. The mutation returns a ticket (a
3
- // database_provision_module row) immediately: a warm-pool claim arrives
4
- // 'completed' with the deferred owner bootstrap still pending; a cold request
5
- // arrives 'pending' and is fulfilled asynchronously by the backend's jobs
6
- // worker. The ticket is polled on the MODULES endpoint (the api endpoint has
7
- // no ticket query) until BOTH status and bootstrapStatus are 'completed': pi
8
- // hands credentials to the agent as soon as this resolves, and until owner
9
- // bootstrap completes the new database has zero users, so its per-DB API
10
- // would reject the owner token under RLS. requestDatabase owns the database
11
- // to the JWT user — there is no owner input. The generated ORM's default
12
- // adapter is plain fetch, so the SDK's FetchAdapter is injected to keep
13
- // *.localhost DNS/Host routing working in Node.
14
- import { api, modules } from '@constructive-io/sdk';
15
- export const POLL_INTERVAL_MS = 2_000;
16
- /** Stays under airpage's 5-minute per-tool timeout. */
17
- export const POLL_DEADLINE_MS = 240_000;
18
- /**
19
- * Consecutive unreadable polls tolerated before giving up. Provisioning keeps
20
- * running server-side, so a dropped request or a momentary 502 must not abort
21
- * a creation that is about to succeed.
22
- */
23
- export const MAX_CONSECUTIVE_POLL_FAILURES = 3;
24
- const TICKET_SELECT = {
25
- id: true,
26
- status: true,
27
- bootstrapStatus: true,
28
- databaseId: true,
29
- errorMessage: true,
30
- bootstrapError: true,
31
- };
32
- function createSdkExecutor(args) {
33
- const headers = { Authorization: `Bearer ${args.bearer}` };
34
- const apiClient = api.createClient({ adapter: new api.FetchAdapter(args.apiEndpoint, headers) });
35
- const modulesClient = modules.createClient({
36
- adapter: new api.FetchAdapter(args.modulesEndpoint, headers),
37
- });
38
- return {
39
- async request(input) {
40
- const requestInput = {
41
- databaseName: input.databaseName,
42
- subdomain: input.subdomain,
43
- domain: input.domain,
44
- ...('presetSlug' in input.request
45
- ? { presetSlug: input.request.presetSlug }
46
- : { modules: input.request.modules }),
47
- };
48
- const result = await apiClient.mutation
49
- .requestDatabase({ input: requestInput }, { select: { result: { select: TICKET_SELECT } } })
50
- .unwrap();
51
- const ticket = result.requestDatabase?.result;
52
- if (!ticket)
53
- throw new Error('requestDatabase returned no provision ticket.');
54
- return ticket;
55
- },
56
- async poll(ticketId) {
57
- const result = await modulesClient.databaseProvisionModule
58
- .findOne({ id: ticketId, select: TICKET_SELECT })
59
- .unwrap();
60
- return result.databaseProvisionModule ?? null;
61
- },
62
- };
63
- }
64
- function sleep(ms) {
65
- return new Promise((resolve) => setTimeout(resolve, ms));
66
- }
67
- /**
68
- * Request a database and resolve only when it is fully usable: ticket
69
- * `status` AND `bootstrapStatus` both 'completed'. The ticket the mutation
70
- * returns is checked before the first sleep, so a warm claim with bootstrap
71
- * already done never waits. `status: 'failed'` surfaces `errorMessage`;
72
- * `bootstrapStatus: 'failed'` surfaces `bootstrapError`.
73
- */
74
- export async function requestDatabaseProvision(args) {
75
- const executor = args.executor ??
76
- createSdkExecutor({
77
- apiEndpoint: args.apiEndpoint,
78
- modulesEndpoint: args.modulesEndpoint,
79
- bearer: args.bearer,
80
- });
81
- const intervalMs = args.pollIntervalMs ?? POLL_INTERVAL_MS;
82
- const deadlineMs = args.pollDeadlineMs ?? POLL_DEADLINE_MS;
83
- let ticket = await executor.request({
84
- databaseName: args.databaseName,
85
- subdomain: args.databaseName,
86
- domain: args.domain,
87
- request: args.request,
88
- });
89
- const ticketId = ticket.id;
90
- if (!ticketId)
91
- throw new Error('requestDatabase returned a provision ticket without an id.');
92
- const deadline = Date.now() + deadlineMs;
93
- let failures = 0;
94
- for (;;) {
95
- if (ticket.status === 'failed') {
96
- throw new Error(ticket.errorMessage ?? 'provisioning failed');
97
- }
98
- if (ticket.bootstrapStatus === 'failed') {
99
- throw new Error(ticket.bootstrapError ?? 'owner bootstrap failed');
100
- }
101
- if (ticket.status === 'completed' && ticket.bootstrapStatus === 'completed') {
102
- if (!ticket.databaseId)
103
- throw new Error('provisioning completed but returned no databaseId.');
104
- return { databaseId: ticket.databaseId };
105
- }
106
- if (Date.now() >= deadline) {
107
- throw new Error(`provisioning timed out after ${Math.round(deadlineMs / 1000)}s (status: ${ticket.status ?? 'unknown'}, bootstrapStatus: ${ticket.bootstrapStatus ?? 'unknown'})`);
108
- }
109
- await sleep(intervalMs);
110
- // A poll that throws (network blip, 502) or comes back empty is retried a
111
- // few times rather than failing a provision that is still running.
112
- let polled;
113
- try {
114
- polled = await executor.poll(ticketId);
115
- }
116
- catch (err) {
117
- if (++failures > MAX_CONSECUTIVE_POLL_FAILURES)
118
- throw err;
119
- continue;
120
- }
121
- if (!polled) {
122
- if (++failures > MAX_CONSECUTIVE_POLL_FAILURES) {
123
- throw new Error(`provision ticket ${ticketId} could not be read back.`);
124
- }
125
- continue;
126
- }
127
- failures = 0;
128
- ticket = polled;
129
- }
130
- }
@@ -1,27 +0,0 @@
1
- import { type ProvisionModule } from './presets';
2
- export interface ProvisionOverlay {
3
- /**
4
- * Base preset name to resolve from (e.g. 'b2b:storage', 'full'). The last
5
- * layer that sets `preset` wins; if none set it, `DEFAULT_PROVISION_PRESET`
6
- * is used.
7
- */
8
- preset?: string;
9
- /**
10
- * Modules to add. An entry whose key matches an existing module OVERRIDES it
11
- * (e.g. re-declaring `storage_module` with app-specific options); a new key
12
- * is appended.
13
- */
14
- add?: ProvisionModule[];
15
- /**
16
- * Module names or `name:scope` keys to drop from the base. A bare name
17
- * removes every scope of that module; `name:scope` removes just that one.
18
- */
19
- remove?: string[];
20
- }
21
- /** Stable identity for a module entry: `name` or `name:scope` when scoped. */
22
- export declare function moduleKey(m: ProvisionModule): string;
23
- /**
24
- * Resolve the effective module list from a pinned preset plus ordered overlays.
25
- * Pure: no I/O, no host access. Later overlays win (last-write-wins by key).
26
- */
27
- export declare function resolveProvisionModules(layers?: ProvisionOverlay[]): ProvisionModule[];
@@ -1,49 +0,0 @@
1
- // Ordered-overlay resolution for provision modules.
2
- //
3
- // Mirrors the skills overlay model (`@agentic-kit/harness` skills manifest): a
4
- // pinned base (a named preset from `node-type-registry`) is layered under zero
5
- // or more overlays, later layers winning by module key. An empty overlay list
6
- // resolves to the base preset unchanged.
7
- import { allModulePresets, DEFAULT_PROVISION_PRESET, getModulePreset, } from './presets';
8
- function moduleName(m) {
9
- return Array.isArray(m) ? m[0] : m;
10
- }
11
- function moduleScope(m) {
12
- if (!Array.isArray(m))
13
- return undefined;
14
- const scope = m[1]?.scope;
15
- return typeof scope === 'string' ? scope : undefined;
16
- }
17
- /** Stable identity for a module entry: `name` or `name:scope` when scoped. */
18
- export function moduleKey(m) {
19
- const scope = moduleScope(m);
20
- return scope ? `${moduleName(m)}:${scope}` : moduleName(m);
21
- }
22
- /**
23
- * Resolve the effective module list from a pinned preset plus ordered overlays.
24
- * Pure: no I/O, no host access. Later overlays win (last-write-wins by key).
25
- */
26
- export function resolveProvisionModules(layers = []) {
27
- const presetName = [...layers].reverse().find((l) => l.preset)?.preset ?? DEFAULT_PROVISION_PRESET;
28
- const preset = getModulePreset(presetName);
29
- if (!preset) {
30
- const known = allModulePresets.map((p) => p.name).join(', ');
31
- throw new Error(`Unknown provision preset "${presetName}". Known presets: ${known}.`);
32
- }
33
- // Ordered map keyed by module identity preserves position while allowing
34
- // overrides (same key) and appends (new key).
35
- const resolved = new Map();
36
- for (const m of preset.modules)
37
- resolved.set(moduleKey(m), m);
38
- for (const layer of layers) {
39
- for (const target of layer.remove ?? []) {
40
- for (const key of [...resolved.keys()]) {
41
- if (key === target || key.split(':')[0] === target)
42
- resolved.delete(key);
43
- }
44
- }
45
- for (const m of layer.add ?? [])
46
- resolved.set(moduleKey(m), m);
47
- }
48
- return [...resolved.values()];
49
- }