@agentic-kit/db-tools 0.11.5 → 0.12.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 (82) hide show
  1. package/README.md +40 -1
  2. package/app-workspace.d.ts +29 -2
  3. package/app-workspace.js +99 -8
  4. package/blueprint-construction.d.ts +60 -0
  5. package/blueprint-construction.js +161 -0
  6. package/context.d.ts +5 -1
  7. package/context.js +30 -5
  8. package/db-probe.d.ts +25 -17
  9. package/db-probe.js +97 -37
  10. package/esm/app-workspace.d.ts +29 -2
  11. package/esm/app-workspace.js +96 -8
  12. package/esm/blueprint-construction.d.ts +60 -0
  13. package/esm/blueprint-construction.js +154 -0
  14. package/esm/context.d.ts +5 -1
  15. package/esm/context.js +31 -6
  16. package/esm/db-probe.d.ts +25 -17
  17. package/esm/db-probe.js +96 -37
  18. package/esm/graphql-http.d.ts +35 -0
  19. package/esm/graphql-http.js +134 -0
  20. package/esm/host.d.ts +46 -0
  21. package/esm/host.js +9 -0
  22. package/esm/index.d.ts +11 -2
  23. package/esm/index.js +6 -0
  24. package/esm/provision-database/env-file.d.ts +23 -2
  25. package/esm/provision-database/env-file.js +86 -27
  26. package/esm/provision-database/pending-ticket.d.ts +33 -0
  27. package/esm/provision-database/pending-ticket.js +63 -0
  28. package/esm/provision-database/provision.d.ts +71 -0
  29. package/esm/provision-database/provision.js +557 -0
  30. package/esm/provision-database/request-database.d.ts +55 -3
  31. package/esm/provision-database/request-database.js +118 -17
  32. package/esm/schema-model/normalize.d.ts +21 -0
  33. package/esm/schema-model/normalize.js +244 -0
  34. package/esm/schema-model.d.ts +110 -0
  35. package/esm/schema-model.js +303 -0
  36. package/esm/tools/add-policies.d.ts +1 -1
  37. package/esm/tools/add-records.d.ts +1 -0
  38. package/esm/tools/add-records.js +18 -6
  39. package/esm/tools/add-relation.js +2 -3
  40. package/esm/tools/create-api-key.d.ts +2 -0
  41. package/esm/tools/create-api-key.js +27 -12
  42. package/esm/tools/manage-entity-types.d.ts +1 -1
  43. package/esm/tools/provision-blueprint.d.ts +6 -0
  44. package/esm/tools/provision-blueprint.js +11 -4
  45. package/esm/tools/provision-database.d.ts +8 -11
  46. package/esm/tools/provision-database.js +23 -243
  47. package/esm/tools/run-codegen.d.ts +19 -2
  48. package/esm/tools/run-codegen.js +184 -97
  49. package/esm/tools/templates.js +3 -15
  50. package/graphql-http.d.ts +35 -0
  51. package/graphql-http.js +140 -0
  52. package/host.d.ts +46 -0
  53. package/host.js +10 -0
  54. package/index.d.ts +11 -2
  55. package/index.js +26 -1
  56. package/package.json +4 -4
  57. package/provision-database/env-file.d.ts +23 -2
  58. package/provision-database/env-file.js +89 -28
  59. package/provision-database/pending-ticket.d.ts +33 -0
  60. package/provision-database/pending-ticket.js +72 -0
  61. package/provision-database/provision.d.ts +71 -0
  62. package/provision-database/provision.js +565 -0
  63. package/provision-database/request-database.d.ts +55 -3
  64. package/provision-database/request-database.js +124 -18
  65. package/schema-model/normalize.d.ts +21 -0
  66. package/schema-model/normalize.js +250 -0
  67. package/schema-model.d.ts +110 -0
  68. package/schema-model.js +309 -0
  69. package/tools/add-policies.d.ts +1 -1
  70. package/tools/add-records.d.ts +1 -0
  71. package/tools/add-records.js +18 -6
  72. package/tools/add-relation.js +2 -3
  73. package/tools/create-api-key.d.ts +2 -0
  74. package/tools/create-api-key.js +27 -12
  75. package/tools/manage-entity-types.d.ts +1 -1
  76. package/tools/provision-blueprint.d.ts +6 -0
  77. package/tools/provision-blueprint.js +11 -4
  78. package/tools/provision-database.d.ts +8 -11
  79. package/tools/provision-database.js +23 -245
  80. package/tools/run-codegen.d.ts +19 -2
  81. package/tools/run-codegen.js +184 -96
  82. package/tools/templates.js +3 -15
@@ -1,41 +1,10 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.provisionDatabaseTool = void 0;
7
- const promises_1 = require("node:fs/promises");
8
- const promises_2 = require("node:fs/promises");
9
- const node_path_1 = __importDefault(require("node:path"));
4
+ exports.createProvisionDatabaseTool = createProvisionDatabaseTool;
10
5
  const zod_1 = require("zod");
11
6
  const app_workspace_1 = require("../app-workspace");
12
- const db_probe_1 = require("../db-probe");
13
- const host_1 = require("../host");
14
- const credential_1 = require("../provision-database/credential");
15
- const env_file_1 = require("../provision-database/env-file");
16
- const manifest_1 = require("../provision-database/manifest");
17
- const preset_match_1 = require("../provision-database/preset-match");
18
- const request_database_1 = require("../provision-database/request-database");
19
- const resolve_1 = require("../provision-database/resolve");
20
- const DEFAULT_API_ENDPOINT = 'http://api.localhost:3000/graphql';
21
- const DEFAULT_MODULES_ENDPOINT = 'http://modules.localhost:3000/graphql';
22
- // The per-DB endpoints are subdomain.<domain>; the provisioning domain is the api
23
- // endpoint's host minus its first label (api.localhost -> localhost,
24
- // api.launchql.dev -> launchql.dev), so dev and devnet both provision correctly.
25
- function provisionDomain(apiEndpoint) {
26
- try {
27
- const { hostname } = new URL(apiEndpoint);
28
- // A bare IP host has no domain hierarchy to strip: dropping its first label
29
- // ('192.168.1.10' -> '168.1.10') would yield a garbage domain. Use it verbatim.
30
- if (hostname.includes(':') || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname))
31
- return hostname;
32
- const parts = hostname.split('.');
33
- return parts.length > 1 ? parts.slice(1).join('.') : parts.join('.');
34
- }
35
- catch {
36
- return 'localhost';
37
- }
38
- }
7
+ const provision_1 = require("../provision-database/provision");
39
8
  const ProvisionDatabaseZod = zod_1.z.object({
40
9
  database_name: zod_1.z
41
10
  .string()
@@ -45,216 +14,25 @@ const ProvisionDatabaseZod = zod_1.z.object({
45
14
  .describe('Mint a fresh database even though the project already carries a binding — use when the bound database no longer exists on this backend (refreshed backend, deleted database), when it belongs to a different account than the one signed in, or when the user asks for a clean rebuild. The old .env keys are archived as comments and the old database is never deleted server-side. The schema must be rebuilt afterwards (provision_blueprint + run_codegen); records do not carry over.')
46
15
  .optional(),
47
16
  });
48
- function fail(message) {
49
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
50
- }
51
- // Minimal .env reader for the idempotency check (full parsing lives in context.ts).
52
- function parseEnvKeys(source) {
53
- const env = {};
54
- for (const rawLine of source.split('\n')) {
55
- const line = rawLine.trim();
56
- if (!line || line.startsWith('#'))
57
- continue;
58
- const eq = line.indexOf('=');
59
- if (eq === -1)
60
- continue;
61
- env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
62
- }
63
- return env;
17
+ // `exec` runs the prewarm's child processes (clone, install); tests inject it.
18
+ function createProvisionDatabaseTool(exec = app_workspace_1.run) {
19
+ return {
20
+ name: 'provision_database',
21
+ label: 'Provision database',
22
+ description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set and write credentials (DATABASE_ID, ACCESS_TOKEN, etc.) to the project .env. Run this ONCE before any schema/record tools. If the project is already bound to a live database under the signed-in account it skips; if the bound database no longer exists on this backend (refreshed/deleted) or belongs to a different account, pass reprovision: true to mint a fresh one (old keys archived in .env, old database kept; rebuild the schema afterwards). If a call returns while the database is still provisioning, call it again with the same database_name to keep waiting; a different name starts a second database.',
23
+ promptSnippet: 'provision_database: one-time bootstrap of the project database (owner + modules + .env). Run before describe_schema/provision_blueprint. Skips when the existing binding is live under the signed-in account; reprovision: true replaces a dead or foreign-account binding (archives old keys, never deletes the old db). Gated.',
24
+ parameters: ProvisionDatabaseZod,
25
+ async execute(params, ctx) {
26
+ // reprovision: true replaces the binding the project has right now; one
27
+ // that changes while this call waits for the project lock is not replaced.
28
+ const replace = params.reprovision === true;
29
+ const details = await (0, provision_1.provisionFromTool)({
30
+ databaseName: params.database_name,
31
+ mode: replace ? 'replace' : 'ensure',
32
+ replaces: replace ? ((await (0, provision_1.boundDatabaseId)(ctx.cwd)) ?? null) : undefined,
33
+ }, ctx, exec);
34
+ return { content: [{ type: 'text', text: details.message }], details };
35
+ },
36
+ };
64
37
  }
65
- exports.provisionDatabaseTool = {
66
- name: 'provision_database',
67
- label: 'Provision database',
68
- description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set and write credentials (DATABASE_ID, ACCESS_TOKEN, etc.) to the project .env. Run this ONCE before any schema/record tools. If the project is already bound to a live database under the signed-in account it skips; if the bound database no longer exists on this backend (refreshed/deleted) or belongs to a different account, pass reprovision: true to mint a fresh one (old keys archived in .env, old database kept; rebuild the schema afterwards).',
69
- promptSnippet: 'provision_database: one-time bootstrap of the project database (owner + modules + .env). Run before describe_schema/provision_blueprint. Skips when the existing binding is live under the signed-in account; reprovision: true replaces a dead or foreign-account binding (archives old keys, never deletes the old db). Gated.',
70
- parameters: ProvisionDatabaseZod,
71
- async execute(params, ctx) {
72
- const databaseName = params.database_name.trim();
73
- if (!databaseName)
74
- return fail('database_name is required.');
75
- const envPath = node_path_1.default.join(ctx.cwd, '.env');
76
- let existing = '';
77
- try {
78
- existing = await (0, promises_2.readFile)(envPath, 'utf8');
79
- }
80
- catch {
81
- /* no existing .env — fine */
82
- }
83
- // Unify endpoints onto the app's backend-config store (environment-aware:
84
- // *.localhost:3000 in dev, *.launchql.dev packaged). A process.env override
85
- // still wins for ad-hoc dev; the hardcoded default is a last resort if the
86
- // store isn't ready.
87
- const host = (0, host_1.getHost)();
88
- const backend = host.backendConfig();
89
- const apiEndpoint = process.env.API_ENDPOINT || backend?.apiEndpoint || DEFAULT_API_ENDPOINT;
90
- const modulesEndpoint = process.env.MODULES_ENDPOINT || backend?.modulesEndpoint || DEFAULT_MODULES_ENDPOINT;
91
- // Every new project provisions UNDER the account (requestDatabase owns the
92
- // database to the JWT user), so it is account-owned and enumerable. The
93
- // account bearer is the single credential: it authenticates the provision
94
- // mutation, the idempotency
95
- // probe below, and is the ACCESS_TOKEN written to .env for project-local
96
- // scripts. It expires with the login session — a relogin plus any provision
97
- // run (including the skip path) refreshes the .env copy. A signed-in session
98
- // with no usable bearer errors out here rather than silently minting a
99
- // throwaway owner. Gate BEFORE prewarm so an error return doesn't leak a
100
- // detached background scaffold/install.
101
- const credential = (0, credential_1.selectProvisionCredential)(host.account(), host.signInHint);
102
- if (credential.mode === 'error') {
103
- return fail(`Cannot provision a database: ${credential.reason}`);
104
- }
105
- const ownerId = credential.ownerId;
106
- // Idempotency keyed on binding liveness AND ownership: a binding is done only
107
- // when its database still answers and belongs to the signed-in account
108
- // (schemas are account-scoped). A dead binding (backend refreshed, database
109
- // deleted, key revoked) or a live one under another account points at the
110
- // reprovision path; an unreachable backend is a retry, never a reprovision.
111
- const existingEnv = parseEnvKeys(existing);
112
- const hasBinding = Boolean(existingEnv.DATABASE_ID && existingEnv.ACCESS_TOKEN);
113
- if (hasBinding && !params.reprovision) {
114
- // The probe carries the account bearer, so it only ever targets the
115
- // app-configured backend — never a .env-pinned endpoint, which an
116
- // untrusted cloned project controls.
117
- const probe = await (0, db_probe_1.probeDatabase)({
118
- endpoint: apiEndpoint,
119
- bearer: credential.bearer,
120
- databaseId: existingEnv.DATABASE_ID,
121
- signInHint: host.signInHint,
122
- });
123
- if (probe.outcome === 'unreachable') {
124
- return fail(`Cannot verify the existing database binding: backend unreachable (${probe.detail}). Check the Constructive backend is running, then retry — do not reprovision on an unreachable backend.`);
125
- }
126
- if (probe.outcome === 'missing') {
127
- return fail(`Project carries a binding (DATABASE_ID=${existingEnv.DATABASE_ID}) but that database no longer exists on this backend. Re-run with reprovision: true to mint a fresh database (old keys archived in .env, old database untouched), then rebuild the schema (provision_blueprint + run_codegen); records do not carry over.`);
128
- }
129
- const sessionUserId = host.account()?.userId;
130
- if (probe.ownerId && sessionUserId && probe.ownerId !== sessionUserId) {
131
- return fail(`Project carries a binding (DATABASE_ID=${existingEnv.DATABASE_ID}) but that database was provisioned under a different account than the one signed in. Re-run with reprovision: true to mint a fresh database under this account (old keys archived in .env, old database untouched), then rebuild the schema (provision_blueprint + run_codegen); records do not carry over.`);
132
- }
133
- // Heal .env on the skip path: a stale token (relogin) or missing/stale
134
- // endpoint pins (project provisioned before pins existed, or backend
135
- // config changed) refresh to the current session + backend.
136
- const refresh = {};
137
- if (existingEnv.ACCESS_TOKEN !== credential.bearer)
138
- refresh.ACCESS_TOKEN = credential.bearer;
139
- if (existingEnv.API_ENDPOINT !== apiEndpoint)
140
- refresh.API_ENDPOINT = apiEndpoint;
141
- if (existingEnv.MODULES_ENDPOINT !== modulesEndpoint) {
142
- refresh.MODULES_ENDPOINT = modulesEndpoint;
143
- }
144
- let tokenNote = '';
145
- if (Object.keys(refresh).length > 0) {
146
- const keys = Object.keys(refresh).join(', ');
147
- try {
148
- await (0, promises_1.writeFile)(envPath, (0, env_file_1.mergeEnv)(existing, refresh));
149
- tokenNote = ` Refreshed in .env from the signed-in session: ${keys}.`;
150
- }
151
- catch (err) {
152
- tokenNote = ` Could not refresh ${keys} in .env: ${err instanceof Error ? err.message : String(err)}.`;
153
- }
154
- }
155
- const message = `Project already provisioned (DATABASE_ID=${existingEnv.DATABASE_ID}) and the database is live under this account. Skipping — pass reprovision: true only for an explicit clean rebuild.${tokenNote}`;
156
- return {
157
- content: [{ type: 'text', text: message }],
158
- details: {
159
- success: true,
160
- message,
161
- databaseId: existingEnv.DATABASE_ID,
162
- databaseName: existingEnv.DATABASE_NAME,
163
- ownerId: existingEnv.OWNER_ID,
164
- skipped: true,
165
- },
166
- };
167
- }
168
- if (hasBinding && params.reprovision) {
169
- existing = (0, env_file_1.archiveBindingKeys)(existing, env_file_1.ARCHIVED_BINDING_KEYS, new Date().toISOString().slice(0, 10));
170
- }
171
- // The packages/app scaffold + pnpm install are database-INDEPENDENT, so kick
172
- // them off now to run concurrently with the provisioning request below
173
- // (near-instant on a warm-pool hit, up to minutes on the cold path).
174
- // This keeps clone + install off run_codegen's critical path. Best-effort:
175
- // run_codegen re-runs the same idempotent steps, so a prewarm failure is
176
- // harmless. Never let it reject (we await it before returning).
177
- const prewarm = (0, app_workspace_1.prewarmAppWorkspace)(ctx.cwd).catch((err) => ({
178
- ok: false,
179
- out: err instanceof Error ? err.message : String(err),
180
- }));
181
- // Resolve the module set: pinned base preset from node-type-registry, then
182
- // ordered overlays (host default < project-local provision.json). No list is
183
- // hand-copied here; overlays are pure data. A bad preset/manifest fails the
184
- // run rather than provisioning a wrong module set.
185
- let modules;
186
- try {
187
- const layers = [];
188
- const hostOverlay = await host.provisionOverlay?.();
189
- if (hostOverlay)
190
- layers.push(hostOverlay);
191
- const projectOverlay = await (0, manifest_1.loadProvisionManifest)(ctx.cwd);
192
- if (projectOverlay)
193
- layers.push(projectOverlay);
194
- modules = (0, resolve_1.resolveProvisionModules)(layers);
195
- }
196
- catch (err) {
197
- return fail(`Cannot resolve provision modules: ${err instanceof Error ? err.message : String(err)}`);
198
- }
199
- // Provision on the API endpoint: requestDatabase claims a warm-pool
200
- // database when the resolved module set matches a cataloged preset
201
- // (near-instant) and cold-provisions asynchronously otherwise; the ticket
202
- // is polled on the modules endpoint until the database AND its deferred
203
- // owner bootstrap complete. No retry wrapper: a pending ticket is the
204
- // normal first response, and transient poll failures are absorbed inside
205
- // the poll loop. The domain still derives from the api endpoint's host
206
- // (per-DB endpoints live under it), and an explicit subdomain
207
- // (= databaseName) keeps them deterministic (SUBDOMAIN-001).
208
- let databaseId;
209
- try {
210
- ({ databaseId } = await (0, request_database_1.requestDatabaseProvision)({
211
- apiEndpoint,
212
- modulesEndpoint,
213
- bearer: credential.bearer,
214
- databaseName,
215
- domain: provisionDomain(apiEndpoint),
216
- request: (0, preset_match_1.selectProvisionRequest)(modules),
217
- }));
218
- }
219
- catch (err) {
220
- const detail = err instanceof Error ? err.message : String(err);
221
- const nameTakenHint = /already exists|already taken|already in use|duplicate/i.test(detail)
222
- ? ' The database name is already taken on the backend — re-run with a different database_name.'
223
- : '';
224
- return fail(`Database provisioning failed: ${detail}.${nameTakenHint}`);
225
- }
226
- // Persist the binding to the project .env (upsert, preserving other keys).
227
- const merged = (0, env_file_1.mergeEnv)(existing, (0, env_file_1.provisionEnvVars)({
228
- databaseId,
229
- databaseName,
230
- ownerId,
231
- accessToken: credential.bearer,
232
- apiEndpoint,
233
- modulesEndpoint,
234
- }));
235
- try {
236
- await (0, promises_1.writeFile)(envPath, merged);
237
- }
238
- catch (err) {
239
- return fail(`Database provisioned (ID: ${databaseId}) but writing .env failed: ${err instanceof Error ? err.message : String(err)}`);
240
- }
241
- // Settle the concurrent prewarm so the scaffold + install are in place before
242
- // run_codegen runs. A failure here is non-fatal — run_codegen redoes the work.
243
- const prewarmResult = await prewarm;
244
- const prewarmNote = prewarmResult.ok ? ' packages/app prewarmed.' : '';
245
- const reprovisionNote = hasBinding && params.reprovision
246
- ? ' Previous binding archived in .env (old database kept); rebuild the schema with provision_blueprint + run_codegen.'
247
- : '';
248
- const message = `Provisioned database "${databaseName}" (ID: ${databaseId}). Credentials written to .env.${prewarmNote}${reprovisionNote}`;
249
- return {
250
- content: [{ type: 'text', text: message }],
251
- details: {
252
- success: true,
253
- message,
254
- databaseId,
255
- databaseName,
256
- ownerId,
257
- },
258
- };
259
- },
260
- };
38
+ exports.provisionDatabaseTool = createProvisionDatabaseTool();
@@ -1,12 +1,29 @@
1
1
  import type { HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
- import { prewarmAppWorkspace } from '../app-workspace';
3
+ import { prewarmAppWorkspace, type RunCommand } from '../app-workspace';
4
4
  declare const RunCodegenZod: z.ZodObject<{}, z.core.$strip>;
5
+ /** Wall-clock milliseconds per step; a step that didn't run reports 0. */
6
+ export type RunCodegenTimings = {
7
+ scaffoldMs: number;
8
+ installMs: number;
9
+ codegenMs: number;
10
+ barrelsMs: number;
11
+ totalMs: number;
12
+ };
5
13
  export type RunCodegenDetails = {
6
14
  success: boolean;
7
15
  message: string;
8
16
  barrelsRewritten?: number;
9
17
  generatedSubmodules?: string[];
18
+ /** `composed` when packages/app carries .constructive/compose.json. */
19
+ appKind?: 'composed' | 'template';
20
+ /** False when a composed app's node_modules was already there. */
21
+ installed?: boolean;
22
+ codegenAttempts?: number;
23
+ timings?: RunCodegenTimings;
24
+ /** The app API answered ACCESS_SUSPENDED: the database is deleted or suspended. */
25
+ code?: 'database-unavailable';
10
26
  };
11
- export declare const runCodegenTool: HarnessTool<typeof RunCodegenZod, RunCodegenDetails>;
27
+ export declare function createRunCodegenTool(exec?: RunCommand): HarnessTool<typeof RunCodegenZod, RunCodegenDetails>;
28
+ export declare const runCodegenTool: HarnessTool<z.ZodObject<{}, z.core.$strip>, RunCodegenDetails>;
12
29
  export { prewarmAppWorkspace };