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