@agentic-kit/pi 0.17.1 → 0.18.1

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,114 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.provisionBlueprintTool = void 0;
4
- const harness_1 = require("@agentic-kit/harness");
5
- const context_1 = require("../context");
6
- const tool_schema_1 = require("../tool-schema");
7
- const BlueprintSchema = (0, tool_schema_1.toolSchema)(harness_1.BlueprintZod);
8
- function formatText(name, details) {
9
- if (details.error)
10
- return `Failed to provision "${name}": ${details.error}`;
11
- const lines = [`Created ${details.created} table${details.created === 1 ? '' : 's'} from "${name}":`];
12
- for (const table of details.tables) {
13
- const parts = [`${table.fields.length} field${table.fields.length === 1 ? '' : 's'}`];
14
- if (table.relationCount > 0) {
15
- parts.push(`${table.relationCount} relation${table.relationCount === 1 ? '' : 's'}`);
16
- }
17
- if (table.policies.length > 0) {
18
- parts.push(`policies: ${table.policies.map((policy) => policy.replace(/^Authz/, '')).join(', ')}`);
19
- }
20
- lines.push(` - ${table.name} (${parts.join(', ')})`);
21
- }
22
- return lines.join('\n');
23
- }
24
- exports.provisionBlueprintTool = {
25
- name: 'provision_blueprint',
26
- label: 'Provision blueprint',
27
- description: 'Create one or more related tables (with fields, RLS policies, and relations) in the project database from a blueprint definition. Always put related tables in a SINGLE call so relations are created together.',
28
- promptSnippet: 'provision_blueprint: create new tables from scratch in a single call (fields + policies + relations). Call describe_schema first.',
29
- parameters: BlueprintSchema,
30
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
31
- const empty = { created: 0, total: 0, tables: [], error: null };
32
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
33
- if (!resolved.context) {
34
- return { content: [{ type: 'text', text: resolved.reason }], details: empty };
35
- }
36
- const { modules, databaseId, schemaId, ownerId } = resolved.context;
37
- if (!ownerId) {
38
- return {
39
- content: [{ type: 'text', text: 'Not authenticated (missing OWNER_ID in .env).' }],
40
- details: empty,
41
- };
42
- }
43
- const definition = (0, harness_1.expandBlueprintDefaults)(params.definition);
44
- const uniqueName = `${params.name}_${Date.now()}`;
45
- try {
46
- const createResult = await modules.blueprint
47
- .create({
48
- data: {
49
- ownerId,
50
- databaseId,
51
- name: uniqueName,
52
- displayName: params.name,
53
- description: params.description,
54
- definition,
55
- },
56
- select: { id: true, name: true },
57
- })
58
- .unwrap();
59
- const blueprintId = createResult.createBlueprint?.blueprint?.id;
60
- if (!blueprintId)
61
- throw new Error('Failed to create blueprint');
62
- const constructResult = await modules.mutation
63
- .constructBlueprint({ input: { blueprintId, schemaId } }, { select: { result: true } })
64
- .unwrap();
65
- const result = constructResult.constructBlueprint?.result;
66
- if (!result) {
67
- const constructions = await modules.blueprintConstruction
68
- .findMany({
69
- where: { blueprintId: { equalTo: blueprintId } },
70
- orderBy: ['ID_DESC'],
71
- first: 1,
72
- select: { status: true, errorDetails: true },
73
- })
74
- .unwrap();
75
- const error = constructions?.blueprintConstructions?.nodes?.[0]?.errorDetails ?? 'Unknown error';
76
- const details = {
77
- created: 0,
78
- total: params.definition.tables.length,
79
- tables: [],
80
- error: typeof error === 'string' ? error : JSON.stringify(error),
81
- };
82
- return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
83
- }
84
- const relations = params.definition.relations ?? [];
85
- const details = {
86
- created: params.definition.tables.length,
87
- total: params.definition.tables.length,
88
- tables: params.definition.tables.map((t) => ({
89
- name: t.table_name,
90
- fields: (t.fields ?? []).map((f) => ({
91
- name: f.name,
92
- type: f.type,
93
- isRequired: f.is_required ?? false,
94
- defaultValue: f.default ?? null,
95
- })),
96
- policies: (0, harness_1.filterInternalPolicies)(t.policies.map((p) => p.$type)),
97
- relationCount: relations.filter((r) => r.source_table === t.table_name).length,
98
- })),
99
- error: null,
100
- };
101
- return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
102
- }
103
- catch (err) {
104
- const message = err instanceof Error ? err.message : 'Failed to provision blueprint';
105
- const details = {
106
- created: 0,
107
- total: params.definition.tables.length,
108
- tables: [],
109
- error: message,
110
- };
111
- return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
112
- }
113
- },
114
- };
@@ -1,14 +0,0 @@
1
- import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
2
- declare const ProvisionDatabaseSchema: import("typebox/type").TSchema;
3
- export type ProvisionDatabaseDetails = {
4
- success: boolean;
5
- message: string;
6
- databaseId?: string;
7
- databaseName?: string;
8
- ownerId?: string;
9
- fixupNote?: string;
10
- /** True when an existing live binding was kept — nothing changed. */
11
- skipped?: boolean;
12
- };
13
- export declare const provisionDatabaseTool: ToolDefinition<typeof ProvisionDatabaseSchema, ProvisionDatabaseDetails>;
14
- export {};
@@ -1,268 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- 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"));
10
- const zod_1 = require("zod");
11
- 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 pg_fixups_1 = require("../provision-database/pg-fixups");
18
- const preset_match_1 = require("../provision-database/preset-match");
19
- const request_database_1 = require("../provision-database/request-database");
20
- const resolve_1 = require("../provision-database/resolve");
21
- const tool_schema_1 = require("../tool-schema");
22
- const DEFAULT_API_ENDPOINT = 'http://api.localhost:3000/graphql';
23
- const DEFAULT_MODULES_ENDPOINT = 'http://modules.localhost:3000/graphql';
24
- // The per-DB endpoints are subdomain.<domain>; the provisioning domain is the api
25
- // endpoint's host minus its first label (api.localhost -> localhost,
26
- // api.launchql.dev -> launchql.dev), so dev and devnet both provision correctly.
27
- function provisionDomain(apiEndpoint) {
28
- try {
29
- const { hostname } = new URL(apiEndpoint);
30
- // A bare IP host has no domain hierarchy to strip: dropping its first label
31
- // ('192.168.1.10' -> '168.1.10') would yield a garbage domain. Use it verbatim.
32
- if (hostname.includes(':') || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname))
33
- return hostname;
34
- const parts = hostname.split('.');
35
- return parts.length > 1 ? parts.slice(1).join('.') : parts.join('.');
36
- }
37
- catch {
38
- return 'localhost';
39
- }
40
- }
41
- const ProvisionDatabaseZod = zod_1.z.object({
42
- database_name: zod_1.z
43
- .string()
44
- .describe('Name for the app database (lowercase, alphanumeric + underscores). Doubles as the deterministic provisioning subdomain (api-<name>/auth-<name>/app-<name>.localhost), so keep it short and URL-safe.'),
45
- reprovision: zod_1.z
46
- .boolean()
47
- .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.')
48
- .optional(),
49
- });
50
- const ProvisionDatabaseSchema = (0, tool_schema_1.toolSchema)(ProvisionDatabaseZod);
51
- function fail(message) {
52
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
53
- }
54
- // Minimal .env reader for the idempotency check (full parsing lives in context.ts).
55
- function parseEnvKeys(source) {
56
- const env = {};
57
- for (const rawLine of source.split('\n')) {
58
- const line = rawLine.trim();
59
- if (!line || line.startsWith('#'))
60
- continue;
61
- const eq = line.indexOf('=');
62
- if (eq === -1)
63
- continue;
64
- env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
65
- }
66
- return env;
67
- }
68
- exports.provisionDatabaseTool = {
69
- name: 'provision_database',
70
- label: 'Provision database',
71
- description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set, enable membership defaults, 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).',
72
- 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.',
73
- parameters: ProvisionDatabaseSchema,
74
- async execute(_id, params, _signal, _onUpdate, ctx) {
75
- const databaseName = params.database_name.trim();
76
- if (!databaseName)
77
- return fail('database_name is required.');
78
- const envPath = node_path_1.default.join(ctx.cwd, '.env');
79
- let existing = '';
80
- try {
81
- existing = await (0, promises_2.readFile)(envPath, 'utf8');
82
- }
83
- catch {
84
- /* no existing .env — fine */
85
- }
86
- // Unify endpoints onto the app's backend-config store (environment-aware:
87
- // *.localhost:3000 in dev, *.launchql.dev packaged). A process.env override
88
- // still wins for ad-hoc dev; the hardcoded default is a last resort if the
89
- // store isn't ready.
90
- const host = (0, host_1.getHost)();
91
- const backend = host.backendConfig();
92
- const apiEndpoint = process.env.API_ENDPOINT || backend?.apiEndpoint || DEFAULT_API_ENDPOINT;
93
- const modulesEndpoint = process.env.MODULES_ENDPOINT || backend?.modulesEndpoint || DEFAULT_MODULES_ENDPOINT;
94
- // Every new project provisions UNDER the account (requestDatabase owns the
95
- // database to the JWT user), so it is account-owned and enumerable. The
96
- // account bearer is the single credential: it authenticates the provision
97
- // mutation, the idempotency
98
- // probe below, and is the ACCESS_TOKEN written to .env for project-local
99
- // scripts. It expires with the login session — a relogin plus any provision
100
- // run (including the skip path) refreshes the .env copy. A signed-in session
101
- // with no usable bearer errors out here rather than silently minting a
102
- // throwaway owner. Gate BEFORE prewarm so an error return doesn't leak a
103
- // detached background scaffold/install.
104
- const credential = (0, credential_1.selectProvisionCredential)(host.account(), host.signInHint);
105
- if (credential.mode === 'error') {
106
- return fail(`Cannot provision a database: ${credential.reason}`);
107
- }
108
- const ownerId = credential.ownerId;
109
- // Idempotency keyed on binding liveness AND ownership: a binding is done only
110
- // when its database still answers and belongs to the signed-in account
111
- // (schemas are account-scoped). A dead binding (backend refreshed, database
112
- // deleted, key revoked) or a live one under another account points at the
113
- // reprovision path; an unreachable backend is a retry, never a reprovision.
114
- const existingEnv = parseEnvKeys(existing);
115
- const hasBinding = Boolean(existingEnv.DATABASE_ID && existingEnv.ACCESS_TOKEN);
116
- if (hasBinding && !params.reprovision) {
117
- // The probe carries the account bearer, so it only ever targets the
118
- // app-configured backend — never a .env-pinned endpoint, which an
119
- // untrusted cloned project controls.
120
- const probe = await (0, db_probe_1.probeDatabase)({
121
- endpoint: apiEndpoint,
122
- bearer: credential.bearer,
123
- databaseId: existingEnv.DATABASE_ID,
124
- signInHint: host.signInHint,
125
- });
126
- if (probe.outcome === 'unreachable') {
127
- 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.`);
128
- }
129
- if (probe.outcome === 'missing') {
130
- 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.`);
131
- }
132
- const sessionUserId = host.account()?.userId;
133
- if (probe.ownerId && sessionUserId && probe.ownerId !== sessionUserId) {
134
- 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.`);
135
- }
136
- // Heal .env on the skip path: a stale token (relogin) or missing/stale
137
- // endpoint pins (project provisioned before pins existed, or backend
138
- // config changed) refresh to the current session + backend.
139
- const refresh = {};
140
- if (existingEnv.ACCESS_TOKEN !== credential.bearer)
141
- refresh.ACCESS_TOKEN = credential.bearer;
142
- if (existingEnv.API_ENDPOINT !== apiEndpoint)
143
- refresh.API_ENDPOINT = apiEndpoint;
144
- if (existingEnv.MODULES_ENDPOINT !== modulesEndpoint) {
145
- refresh.MODULES_ENDPOINT = modulesEndpoint;
146
- }
147
- let tokenNote = '';
148
- if (Object.keys(refresh).length > 0) {
149
- const keys = Object.keys(refresh).join(', ');
150
- try {
151
- await (0, promises_1.writeFile)(envPath, (0, env_file_1.mergeEnv)(existing, refresh));
152
- tokenNote = ` Refreshed in .env from the signed-in session: ${keys}.`;
153
- }
154
- catch (err) {
155
- tokenNote = ` Could not refresh ${keys} in .env: ${err instanceof Error ? err.message : String(err)}.`;
156
- }
157
- }
158
- 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}`;
159
- return {
160
- content: [{ type: 'text', text: message }],
161
- details: {
162
- success: true,
163
- message,
164
- databaseId: existingEnv.DATABASE_ID,
165
- databaseName: existingEnv.DATABASE_NAME,
166
- ownerId: existingEnv.OWNER_ID,
167
- skipped: true,
168
- },
169
- };
170
- }
171
- if (hasBinding && params.reprovision) {
172
- existing = (0, env_file_1.archiveBindingKeys)(existing, env_file_1.ARCHIVED_BINDING_KEYS, new Date().toISOString().slice(0, 10));
173
- }
174
- // The packages/app scaffold + pnpm install are database-INDEPENDENT, so kick
175
- // them off now to run concurrently with the provisioning request below
176
- // (near-instant on a warm-pool hit, up to minutes on the cold path).
177
- // This keeps clone + install off run_codegen's critical path. Best-effort:
178
- // run_codegen re-runs the same idempotent steps, so a prewarm failure is
179
- // harmless. Never let it reject (we await it before returning).
180
- const prewarm = (0, app_workspace_1.prewarmAppWorkspace)(ctx.cwd).catch((err) => ({
181
- ok: false,
182
- out: err instanceof Error ? err.message : String(err),
183
- }));
184
- // Resolve the module set: pinned base preset from node-type-registry, then
185
- // ordered overlays (host default < project-local provision.json). No list is
186
- // hand-copied here; overlays are pure data. A bad preset/manifest fails the
187
- // run rather than provisioning a wrong module set.
188
- let modules;
189
- try {
190
- const layers = [];
191
- const hostOverlay = await host.provisionOverlay?.();
192
- if (hostOverlay)
193
- layers.push(hostOverlay);
194
- const projectOverlay = await (0, manifest_1.loadProvisionManifest)(ctx.cwd);
195
- if (projectOverlay)
196
- layers.push(projectOverlay);
197
- modules = (0, resolve_1.resolveProvisionModules)(layers);
198
- }
199
- catch (err) {
200
- return fail(`Cannot resolve provision modules: ${err instanceof Error ? err.message : String(err)}`);
201
- }
202
- const physicalDb = process.env.CONSTRUCTIVE_DB || 'constructive';
203
- // Provision on the API endpoint: requestDatabase claims a warm-pool
204
- // database when the resolved module set matches a cataloged preset
205
- // (near-instant) and cold-provisions asynchronously otherwise; the ticket
206
- // is polled on the modules endpoint until the database AND its deferred
207
- // owner bootstrap complete. No retry wrapper: a pending ticket is the
208
- // normal first response, and transient poll failures are absorbed inside
209
- // the poll loop. The domain still derives from the api endpoint's host
210
- // (per-DB endpoints live under it), and an explicit subdomain
211
- // (= databaseName) keeps them deterministic (SUBDOMAIN-001).
212
- let databaseId;
213
- try {
214
- ({ databaseId } = await (0, request_database_1.requestDatabaseProvision)({
215
- apiEndpoint,
216
- modulesEndpoint,
217
- bearer: credential.bearer,
218
- databaseName,
219
- domain: provisionDomain(apiEndpoint),
220
- request: (0, preset_match_1.selectProvisionRequest)(modules),
221
- }));
222
- }
223
- catch (err) {
224
- const detail = err instanceof Error ? err.message : String(err);
225
- const nameTakenHint = /already exists|already taken|already in use|duplicate/i.test(detail)
226
- ? ' The database name is already taken on the backend — re-run with a different database_name.'
227
- : '';
228
- return fail(`Database provisioning failed: ${detail}.${nameTakenHint}`);
229
- }
230
- // Enable membership defaults + naming settings at the SQL level. Best-effort:
231
- // provisioning already succeeded, so a fixup failure is a warning, not an error.
232
- const fixup = await (0, pg_fixups_1.applySqlFixups)({ databaseName, physicalDb });
233
- // Persist the binding to the project .env (upsert, preserving other keys).
234
- const merged = (0, env_file_1.mergeEnv)(existing, (0, env_file_1.provisionEnvVars)({
235
- databaseId,
236
- databaseName,
237
- ownerId,
238
- accessToken: credential.bearer,
239
- apiEndpoint,
240
- modulesEndpoint,
241
- }));
242
- try {
243
- await (0, promises_1.writeFile)(envPath, merged);
244
- }
245
- catch (err) {
246
- return fail(`Database provisioned (ID: ${databaseId}) but writing .env failed: ${err instanceof Error ? err.message : String(err)}`);
247
- }
248
- // Settle the concurrent prewarm so the scaffold + install are in place before
249
- // run_codegen runs. A failure here is non-fatal — run_codegen redoes the work.
250
- const prewarmResult = await prewarm;
251
- const prewarmNote = prewarmResult.ok ? ' packages/app prewarmed.' : '';
252
- const reprovisionNote = hasBinding && params.reprovision
253
- ? ' Previous binding archived in .env (old database kept); rebuild the schema with provision_blueprint + run_codegen.'
254
- : '';
255
- const message = `Provisioned database "${databaseName}" (ID: ${databaseId}). Credentials written to .env. ${fixup.note}${prewarmNote}${reprovisionNote}`;
256
- return {
257
- content: [{ type: 'text', text: message }],
258
- details: {
259
- success: true,
260
- message,
261
- databaseId,
262
- databaseName,
263
- ownerId,
264
- fixupNote: fixup.note,
265
- },
266
- };
267
- },
268
- };
@@ -1,11 +0,0 @@
1
- import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
2
- import { prewarmAppWorkspace } from '../app-workspace';
3
- declare const RunCodegenSchema: import("typebox/type").TSchema;
4
- export type RunCodegenDetails = {
5
- success: boolean;
6
- message: string;
7
- barrelsRewritten?: number;
8
- generatedSubmodules?: string[];
9
- };
10
- export declare const runCodegenTool: ToolDefinition<typeof RunCodegenSchema, RunCodegenDetails>;
11
- export { prewarmAppWorkspace };
@@ -1,143 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.prewarmAppWorkspace = exports.runCodegenTool = void 0;
7
- const node_fs_1 = require("node:fs");
8
- const promises_1 = require("node:fs/promises");
9
- const node_path_1 = __importDefault(require("node:path"));
10
- const zod_1 = require("zod");
11
- const app_workspace_1 = require("../app-workspace");
12
- Object.defineProperty(exports, "prewarmAppWorkspace", { enumerable: true, get: function () { return app_workspace_1.prewarmAppWorkspace; } });
13
- const host_1 = require("../host");
14
- const barrels_1 = require("../run-codegen/barrels");
15
- const endpoints_1 = require("../run-codegen/endpoints");
16
- const tool_schema_1 = require("../tool-schema");
17
- const DEFAULT_API_ENDPOINT = 'http://api.localhost:3000/graphql';
18
- const RunCodegenZod = zod_1.z.object({});
19
- const RunCodegenSchema = (0, tool_schema_1.toolSchema)(RunCodegenZod);
20
- function fail(message) {
21
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
22
- }
23
- const FETCH_RESET_RE = /Failed to fetch schema|Connection reset|ECONNRESET|socket hang up/i;
24
- // Read the binding provision_database wrote to the project .env. The
25
- // API_ENDPOINT pin identifies which backend owns the binding — it wins over
26
- // the app's current backend config, matching context.ts data-plane precedence.
27
- async function readProjectEnv(cwd) {
28
- try {
29
- const env = await (0, promises_1.readFile)(node_path_1.default.join(cwd, '.env'), 'utf8');
30
- const read = (key) => env.match(new RegExp(`^${key}=(.+)$`, 'm'))?.[1]?.trim();
31
- return { databaseName: read('DATABASE_NAME'), apiEndpoint: read('API_ENDPOINT') };
32
- }
33
- catch {
34
- return {};
35
- }
36
- }
37
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
38
- // The codegen CLI introspects three live vhosts (admin/auth/app). Under load the
39
- // Constructive backend intermittently resets a connection mid-introspection
40
- // ("Failed to fetch schema: Connection reset"), which is transient — a retry
41
- // almost always clears it. Re-run the whole generate (it rebuilds all targets)
42
- // up to `attempts` times, only on a fetch/reset failure; any other failure is
43
- // real and returned immediately (CODEGEN-RETRY-001).
44
- async function runCodegenWithRetry(appDir, env, attempts = 4) {
45
- const sdk = node_path_1.default.join(appDir, 'src', 'graphql', 'sdk');
46
- let last = { ok: false, out: 'codegen never ran' };
47
- for (let i = 1; i <= attempts; i++) {
48
- for (const sub of ['admin', 'auth', 'app']) {
49
- await (0, promises_1.rm)(node_path_1.default.join(sdk, sub), { recursive: true, force: true });
50
- }
51
- last = await (0, app_workspace_1.run)('npx', ['@constructive-io/graphql-codegen', 'generate', '--config', './graphql-codegen.config.ts'], appDir, env);
52
- if (last.ok)
53
- return last;
54
- if (!FETCH_RESET_RE.test(last.out))
55
- return last;
56
- if (i < attempts)
57
- await sleep(2000 * i);
58
- }
59
- return last;
60
- }
61
- exports.runCodegenTool = {
62
- name: 'run_codegen',
63
- label: 'Run codegen',
64
- description: "Generate the typed GraphQL SDK for the project's Next.js app (packages/app). Runs the exact deterministic sequence — scaffold packages/app from the constructive-app template if it doesn't exist yet, hoist the graphql override to the root workspace so a single grafast resolves, pin codegen to latest, do one clean install, run codegen (retrying transient backend connection resets), and normalize SDK barrels for Turbopack. Run AFTER provisioning the database and creating schema; it scaffolds packages/app itself, so no separate `pgpm init` step is needed. The scaffold + install are usually prewarmed during provision_database, so this is fast.",
65
- promptSnippet: 'run_codegen: scaffold packages/app (if missing) + regenerate the typed SDK (workspace-config + clean install + codegen-with-retry + barrel-normalize). Run after schema changes. Gated.',
66
- parameters: RunCodegenSchema,
67
- async execute(_id, _params, _signal, _onUpdate, ctx) {
68
- const cwd = ctx.cwd;
69
- const appDir = node_path_1.default.join(cwd, 'packages', 'app');
70
- // Materialize packages/app deterministically if it isn't there yet — this
71
- // replaces the flaky `pgpm init` scaffold step (PGPM-001). When
72
- // provision_database prewarmed it, this no-ops.
73
- const scaffold = await (0, app_workspace_1.ensureAppScaffold)(cwd);
74
- if (!scaffold.ok) {
75
- return fail(scaffold.out);
76
- }
77
- const { databaseName: dbName, apiEndpoint: envApiEndpoint } = await readProjectEnv(cwd);
78
- if (!dbName) {
79
- return fail('DATABASE_NAME missing from .env — provision the database first, then re-run.');
80
- }
81
- const backend = (0, host_1.getHost)().backendConfig();
82
- const apiEndpoint = envApiEndpoint || backend?.apiEndpoint || DEFAULT_API_ENDPOINT;
83
- const planes = (0, endpoints_1.derivePlaneEndpoints)(apiEndpoint, dbName);
84
- // The dev server reads .env.local (NEXT_PUBLIC_DB_NAME + per-DB endpoint
85
- // overrides so it doesn't fall back to localhost vhosts on a remote
86
- // backend); the codegen config reads process.env (passed directly below).
87
- try {
88
- await (0, promises_1.writeFile)(node_path_1.default.join(appDir, '.env.local'), (0, endpoints_1.envLocalContent)(dbName, planes));
89
- }
90
- catch (err) {
91
- return fail(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`);
92
- }
93
- // Hoist the graphql override to the root workspace (PNPM-GRAPHQL-OVERRIDE-001)
94
- // and pin codegen to latest (TS-001) before the single clean install. When
95
- // prewarmed by provision_database these are idempotent and the install is a
96
- // fast no-op; otherwise this is the first install (PNPM-BUILDS-001).
97
- await (0, app_workspace_1.ensureWorkspaceConfig)(cwd);
98
- await (0, app_workspace_1.pinCodegenLatest)(appDir);
99
- const install = await (0, app_workspace_1.run)('pnpm', ['install', '--no-frozen-lockfile'], cwd);
100
- if (!install.ok && !app_workspace_1.IGNORED_BUILDS_RE.test(install.out)) {
101
- return fail(`pnpm install failed:\n${install.out}`);
102
- }
103
- const codegen = await runCodegenWithRetry(appDir, {
104
- NEXT_PUBLIC_DB_NAME: dbName,
105
- ...(planes ? (0, endpoints_1.codegenEndpointEnv)(planes) : {}),
106
- });
107
- if (!codegen.ok) {
108
- // A reset that survives every internal retry is a backend OUTAGE, not a code
109
- // or install problem — re-running run_codegen cannot fix it. Say so explicitly
110
- // so the agent marks sdk-codegen `blocked` instead of looping the tool to the
111
- // time cap (CODEGEN-OUTAGE-001 / THRASH-001).
112
- if (FETCH_RESET_RE.test(codegen.out)) {
113
- return fail('codegen failed: BACKEND OUTAGE — the Constructive backend reset the connection ' +
114
- 'during schema introspection, and it stayed down across every internal retry. ' +
115
- 'This is an EXTERNAL outage, not a code or install problem; re-running run_codegen ' +
116
- 'will NOT fix it. Call run_preflight once — if the backend is down, mark ' +
117
- 'sdk-codegen `blocked` (SERVER-001, BLOCKED-PROCEED-001) and hand back to ' +
118
- 'build-orchestrator. Do NOT loop on run_codegen (THRASH-001).\n\n' +
119
- codegen.out);
120
- }
121
- return fail(`codegen failed:\n${codegen.out}`);
122
- }
123
- // Normalize directory barrels so Turbopack can resolve them (TURBOPACK-BARREL-001).
124
- const sdkRoot = node_path_1.default.join(appDir, 'src', 'graphql', 'sdk');
125
- const barrelsRewritten = (0, barrels_1.normalizeSdkBarrels)(sdkRoot);
126
- // Report which app submodules actually generated — a bare scaffold with only
127
- // index.ts means codegen had no schema to generate against.
128
- const appSdk = node_path_1.default.join(sdkRoot, 'app');
129
- const generatedSubmodules = ['hooks', 'orm', 'types'].filter((sub) => (0, node_fs_1.existsSync)(node_path_1.default.join(appSdk, sub)));
130
- const message = generatedSubmodules.length > 0
131
- ? `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`
132
- : `Codegen ran, but no app submodules (hooks/orm/types) were generated — the database may have no entity tables yet. Normalized ${barrelsRewritten} barrel file(s).`;
133
- return {
134
- content: [{ type: 'text', text: message }],
135
- details: {
136
- success: generatedSubmodules.length > 0,
137
- message,
138
- barrelsRewritten,
139
- generatedSubmodules,
140
- },
141
- };
142
- },
143
- };
@@ -1,49 +0,0 @@
1
- import { type ConfirmPreviewTable } from '@agentic-kit/harness';
2
- import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
3
- import type { ProjectContext } from '../context';
4
- export type TemplateDetails = {
5
- success: boolean;
6
- message: string;
7
- };
8
- export type CreateTemplateDetails = TemplateDetails & {
9
- displayName?: string;
10
- blueprintName?: string;
11
- tables?: ConfirmPreviewTable[];
12
- };
13
- type TemplateField = {
14
- name: string;
15
- type: string;
16
- isRequired: boolean;
17
- defaultValue: string | null;
18
- };
19
- type TemplateTable = {
20
- name: string;
21
- fields: TemplateField[];
22
- policies: string[];
23
- relationCount: number;
24
- };
25
- type TemplateInfo = {
26
- displayName: string;
27
- description: string | null;
28
- categories: string[];
29
- tables: TemplateTable[];
30
- };
31
- export type ListTemplatesDetails = {
32
- templates: TemplateInfo[];
33
- };
34
- export type CreateTemplatePreview = {
35
- blueprintName: string;
36
- tables: ConfirmPreviewTable[];
37
- };
38
- export declare function createTemplatePreviewTables(context: ProjectContext, blueprintName: string | undefined): Promise<CreateTemplatePreview>;
39
- declare const ListTemplatesSchema: import("typebox/type").TSchema;
40
- export declare const listTemplatesTool: ToolDefinition<typeof ListTemplatesSchema, ListTemplatesDetails>;
41
- declare const CreateTemplateSchema: import("typebox/type").TSchema;
42
- export declare const createTemplateTool: ToolDefinition<typeof CreateTemplateSchema, CreateTemplateDetails>;
43
- declare const ApplyTemplateSchema: import("typebox/type").TSchema;
44
- export declare const applyTemplateTool: ToolDefinition<typeof ApplyTemplateSchema, TemplateDetails>;
45
- declare const UpdateTemplateSchema: import("typebox/type").TSchema;
46
- export declare const updateTemplateTool: ToolDefinition<typeof UpdateTemplateSchema, TemplateDetails>;
47
- declare const DeleteTemplateSchema: import("typebox/type").TSchema;
48
- export declare const deleteTemplateTool: ToolDefinition<typeof DeleteTemplateSchema, TemplateDetails>;
49
- export {};