@agentic-kit/pi 0.2.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.
- package/LICENSE +23 -0
- package/README.md +126 -0
- package/app-workspace.d.ts +16 -0
- package/app-workspace.js +145 -0
- package/confirm-gate.d.ts +13 -0
- package/confirm-gate.js +51 -0
- package/context.d.ts +39 -0
- package/context.js +251 -0
- package/db-probe.d.ts +29 -0
- package/db-probe.js +50 -0
- package/esm/app-workspace.d.ts +16 -0
- package/esm/app-workspace.js +134 -0
- package/esm/confirm-gate.d.ts +13 -0
- package/esm/confirm-gate.js +48 -0
- package/esm/context.d.ts +39 -0
- package/esm/context.js +242 -0
- package/esm/db-probe.d.ts +29 -0
- package/esm/db-probe.js +47 -0
- package/esm/host.d.ts +55 -0
- package/esm/host.js +20 -0
- package/esm/index.d.ts +11 -0
- package/esm/index.js +48 -0
- package/esm/policy/add-policies-to-table.d.ts +26 -0
- package/esm/policy/add-policies-to-table.js +66 -0
- package/esm/policy/provision-helpers.d.ts +38 -0
- package/esm/policy/provision-helpers.js +50 -0
- package/esm/provision-database/create-database-provision.d.ts +11 -0
- package/esm/provision-database/create-database-provision.js +48 -0
- package/esm/provision-database/credential.d.ts +14 -0
- package/esm/provision-database/credential.js +19 -0
- package/esm/provision-database/env-file.d.ts +37 -0
- package/esm/provision-database/env-file.js +85 -0
- package/esm/provision-database/modules.d.ts +2 -0
- package/esm/provision-database/modules.js +40 -0
- package/esm/provision-database/pg-fixups.d.ts +16 -0
- package/esm/provision-database/pg-fixups.js +132 -0
- package/esm/records/meta.d.ts +41 -0
- package/esm/records/meta.js +170 -0
- package/esm/run-codegen/barrels.d.ts +3 -0
- package/esm/run-codegen/barrels.js +48 -0
- package/esm/run-codegen/endpoints.d.ts +8 -0
- package/esm/run-codegen/endpoints.js +46 -0
- package/esm/schema-resolve.d.ts +23 -0
- package/esm/schema-resolve.js +69 -0
- package/esm/tool-schema.d.ts +3 -0
- package/esm/tool-schema.js +10 -0
- package/esm/tools/add-policies.d.ts +8 -0
- package/esm/tools/add-policies.js +96 -0
- package/esm/tools/add-records.d.ts +14 -0
- package/esm/tools/add-records.js +124 -0
- package/esm/tools/add-relation-schema.d.ts +30 -0
- package/esm/tools/add-relation-schema.js +58 -0
- package/esm/tools/add-relation.d.ts +10 -0
- package/esm/tools/add-relation.js +91 -0
- package/esm/tools/describe-schema.d.ts +18 -0
- package/esm/tools/describe-schema.js +132 -0
- package/esm/tools/mutations.d.ts +14 -0
- package/esm/tools/mutations.js +235 -0
- package/esm/tools/provision-blueprint.d.ts +22 -0
- package/esm/tools/provision-blueprint.js +111 -0
- package/esm/tools/provision-database.d.ts +14 -0
- package/esm/tools/provision-database.js +251 -0
- package/esm/tools/run-codegen.d.ts +11 -0
- package/esm/tools/run-codegen.js +139 -0
- package/esm/tools/templates.d.ts +49 -0
- package/esm/tools/templates.js +337 -0
- package/host.d.ts +55 -0
- package/host.js +25 -0
- package/index.d.ts +11 -0
- package/index.js +60 -0
- package/package.json +51 -0
- package/policy/add-policies-to-table.d.ts +26 -0
- package/policy/add-policies-to-table.js +71 -0
- package/policy/provision-helpers.d.ts +38 -0
- package/policy/provision-helpers.js +58 -0
- package/provision-database/create-database-provision.d.ts +11 -0
- package/provision-database/create-database-provision.js +51 -0
- package/provision-database/credential.d.ts +14 -0
- package/provision-database/credential.js +22 -0
- package/provision-database/env-file.d.ts +37 -0
- package/provision-database/env-file.js +91 -0
- package/provision-database/modules.d.ts +2 -0
- package/provision-database/modules.js +43 -0
- package/provision-database/pg-fixups.d.ts +16 -0
- package/provision-database/pg-fixups.js +170 -0
- package/records/meta.d.ts +41 -0
- package/records/meta.js +175 -0
- package/run-codegen/barrels.d.ts +3 -0
- package/run-codegen/barrels.js +54 -0
- package/run-codegen/endpoints.d.ts +8 -0
- package/run-codegen/endpoints.js +51 -0
- package/schema-resolve.d.ts +23 -0
- package/schema-resolve.js +75 -0
- package/tool-schema.d.ts +3 -0
- package/tool-schema.js +13 -0
- package/tools/add-policies.d.ts +8 -0
- package/tools/add-policies.js +99 -0
- package/tools/add-records.d.ts +14 -0
- package/tools/add-records.js +127 -0
- package/tools/add-relation-schema.d.ts +30 -0
- package/tools/add-relation-schema.js +62 -0
- package/tools/add-relation.d.ts +10 -0
- package/tools/add-relation.js +94 -0
- package/tools/describe-schema.d.ts +18 -0
- package/tools/describe-schema.js +135 -0
- package/tools/mutations.d.ts +14 -0
- package/tools/mutations.js +238 -0
- package/tools/provision-blueprint.d.ts +22 -0
- package/tools/provision-blueprint.js +114 -0
- package/tools/provision-database.d.ts +14 -0
- package/tools/provision-database.js +257 -0
- package/tools/run-codegen.d.ts +11 -0
- package/tools/run-codegen.js +143 -0
- package/tools/templates.d.ts +49 -0
- package/tools/templates.js +341 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { filterInternalPolicies } from '@agentic-kit/harness';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { resolveProjectContext } from '../context';
|
|
4
|
+
import { toolSchema } from '../tool-schema';
|
|
5
|
+
// A stored blueprint field's `type` is an expanded object (`{ name: 'text' }`),
|
|
6
|
+
// not the bare string the agent passes to provision_blueprint. Flatten it to the
|
|
7
|
+
// type name so the renderer gets a string, never an object (which React can't
|
|
8
|
+
// render as a child).
|
|
9
|
+
function fieldTypeName(raw) {
|
|
10
|
+
if (typeof raw === 'string')
|
|
11
|
+
return raw;
|
|
12
|
+
if (raw && typeof raw === 'object' && typeof raw.name === 'string') {
|
|
13
|
+
return raw.name;
|
|
14
|
+
}
|
|
15
|
+
return '';
|
|
16
|
+
}
|
|
17
|
+
// A template's definition is a stored blueprint (see BlueprintDefinitionSchema):
|
|
18
|
+
// { tables: [{ table_name, fields, policies }], relations: [{ source_table, … }] }.
|
|
19
|
+
// Parse it into the same table shape provision_blueprint surfaces so the renderer
|
|
20
|
+
// can reuse TableCard. Defensive throughout — it's untyped JSON from the catalog.
|
|
21
|
+
function parseTemplateTables(definition) {
|
|
22
|
+
if (!definition || typeof definition !== 'object')
|
|
23
|
+
return [];
|
|
24
|
+
const def = definition;
|
|
25
|
+
const tables = Array.isArray(def.tables) ? def.tables : [];
|
|
26
|
+
const relations = Array.isArray(def.relations) ? def.relations : [];
|
|
27
|
+
return tables.map((raw) => {
|
|
28
|
+
const table = raw;
|
|
29
|
+
const fields = Array.isArray(table.fields) ? table.fields : [];
|
|
30
|
+
const policies = Array.isArray(table.policies) ? table.policies : [];
|
|
31
|
+
return {
|
|
32
|
+
name: table.table_name ?? '',
|
|
33
|
+
fields: fields.map((rawField) => {
|
|
34
|
+
const field = rawField;
|
|
35
|
+
return {
|
|
36
|
+
name: field.name ?? '',
|
|
37
|
+
type: fieldTypeName(field.type),
|
|
38
|
+
isRequired: field.is_required ?? false,
|
|
39
|
+
defaultValue: typeof field.default === 'string' ? field.default : null,
|
|
40
|
+
};
|
|
41
|
+
}),
|
|
42
|
+
policies: filterInternalPolicies(policies.map((policy) => policy.$type ?? '').filter(Boolean)),
|
|
43
|
+
relationCount: relations.filter((relation) => relation.source_table === table.table_name).length,
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function formatTemplatesText(templates) {
|
|
48
|
+
if (templates.length === 0)
|
|
49
|
+
return 'No blueprint templates available.';
|
|
50
|
+
const lines = [`Available blueprint templates (${templates.length}):`];
|
|
51
|
+
for (const template of templates) {
|
|
52
|
+
const cats = template.categories.length ? ` [${template.categories.join(', ')}]` : '';
|
|
53
|
+
lines.push(` ${template.displayName} — ${template.tables.length} tables${cats}`);
|
|
54
|
+
for (const table of template.tables) {
|
|
55
|
+
lines.push(` - ${table.name} (${table.fields.length} field${table.fields.length === 1 ? '' : 's'})`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return lines.join('\n');
|
|
59
|
+
}
|
|
60
|
+
// The latest project blueprint (or a named one) — the definition source for
|
|
61
|
+
// create_template, and for the confirm preview of the tables it will template.
|
|
62
|
+
// A blueprintName is a best-effort hint: if it matches nothing (the agent often
|
|
63
|
+
// guesses casing/wording), fall back to the most recent blueprint so the confirm
|
|
64
|
+
// still previews real tables and execute templates the same one it previewed.
|
|
65
|
+
async function fetchLatestBlueprint(context, blueprintName) {
|
|
66
|
+
const found = await context.modules.blueprint
|
|
67
|
+
.findMany({
|
|
68
|
+
select: { displayName: true, definition: true },
|
|
69
|
+
where: {
|
|
70
|
+
databaseId: { equalTo: context.databaseId },
|
|
71
|
+
...(blueprintName ? { displayName: { equalTo: blueprintName } } : {}),
|
|
72
|
+
},
|
|
73
|
+
orderBy: ['CREATED_AT_DESC'],
|
|
74
|
+
first: 1,
|
|
75
|
+
})
|
|
76
|
+
.unwrap();
|
|
77
|
+
return found.blueprints?.nodes?.[0];
|
|
78
|
+
}
|
|
79
|
+
async function findProjectBlueprint(context, blueprintName) {
|
|
80
|
+
let node = await fetchLatestBlueprint(context, blueprintName);
|
|
81
|
+
if (!node && blueprintName)
|
|
82
|
+
node = await fetchLatestBlueprint(context, undefined);
|
|
83
|
+
return node?.definition ? { displayName: node.displayName ?? '', definition: node.definition } : null;
|
|
84
|
+
}
|
|
85
|
+
// The create_template confirm preview — the source blueprint's name and its
|
|
86
|
+
// tables, parsed into the shape the renderer's TableCard reuses. Best-effort: any
|
|
87
|
+
// failure yields no tables rather than blocking the confirm.
|
|
88
|
+
export async function createTemplatePreviewTables(context, blueprintName) {
|
|
89
|
+
try {
|
|
90
|
+
const blueprint = await findProjectBlueprint(context, blueprintName);
|
|
91
|
+
if (!blueprint)
|
|
92
|
+
return { blueprintName: '', tables: [] };
|
|
93
|
+
return {
|
|
94
|
+
blueprintName: blueprint.displayName,
|
|
95
|
+
tables: parseTemplateTables(blueprint.definition),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
console.warn('[db-tools] create_template preview lookup failed:', err);
|
|
100
|
+
return { blueprintName: '', tables: [] };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function resolveTemplateId(client, displayName) {
|
|
104
|
+
const result = await client.blueprintTemplate
|
|
105
|
+
.findMany({
|
|
106
|
+
select: { id: true, displayName: true },
|
|
107
|
+
where: { displayName: { equalTo: displayName } },
|
|
108
|
+
first: 1,
|
|
109
|
+
})
|
|
110
|
+
.unwrap();
|
|
111
|
+
const template = result.blueprintTemplates?.nodes?.[0];
|
|
112
|
+
if (!template?.id)
|
|
113
|
+
throw new Error(`Template "${displayName}" not found`);
|
|
114
|
+
return template.id;
|
|
115
|
+
}
|
|
116
|
+
function done(success, message) {
|
|
117
|
+
return { content: [{ type: 'text', text: message }], details: { success, message } };
|
|
118
|
+
}
|
|
119
|
+
// ── list_templates ────────────────────────────────────────────────────────
|
|
120
|
+
const ListTemplatesZod = z.object({});
|
|
121
|
+
const ListTemplatesSchema = toolSchema(ListTemplatesZod);
|
|
122
|
+
export const listTemplatesTool = {
|
|
123
|
+
name: 'list_templates',
|
|
124
|
+
label: 'List templates',
|
|
125
|
+
description: 'List the blueprint templates available to provision into the project database (display name, description, categories, table count). Read-only — these are a global catalog, not the project schema.',
|
|
126
|
+
promptSnippet: 'list_templates: list the available blueprint templates to apply. Read-only — call before apply_template.',
|
|
127
|
+
parameters: ListTemplatesSchema,
|
|
128
|
+
async execute(_id, _params, _signal, _onUpdate, ctx) {
|
|
129
|
+
const resolved = await resolveProjectContext(ctx.cwd);
|
|
130
|
+
if (!resolved.context) {
|
|
131
|
+
return { content: [{ type: 'text', text: resolved.reason }], details: { templates: [] } };
|
|
132
|
+
}
|
|
133
|
+
const result = await resolved.context.modules.blueprintTemplate
|
|
134
|
+
.findMany({
|
|
135
|
+
select: {
|
|
136
|
+
displayName: true,
|
|
137
|
+
description: true,
|
|
138
|
+
categories: true,
|
|
139
|
+
definition: true,
|
|
140
|
+
},
|
|
141
|
+
orderBy: ['NAME_ASC'],
|
|
142
|
+
})
|
|
143
|
+
.execute();
|
|
144
|
+
if (!result.ok) {
|
|
145
|
+
const message = result.errors.map((e) => e.message).join('; ');
|
|
146
|
+
return {
|
|
147
|
+
content: [{ type: 'text', text: `Failed to read templates: ${message}` }],
|
|
148
|
+
details: { templates: [] },
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const templates = (result.data.blueprintTemplates?.nodes ?? []).map((template) => ({
|
|
152
|
+
displayName: template.displayName ?? '',
|
|
153
|
+
description: template.description ?? null,
|
|
154
|
+
categories: Array.isArray(template.categories) ? template.categories : [],
|
|
155
|
+
tables: parseTemplateTables(template.definition),
|
|
156
|
+
}));
|
|
157
|
+
return {
|
|
158
|
+
content: [{ type: 'text', text: formatTemplatesText(templates) }],
|
|
159
|
+
details: { templates },
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
// ── create_template ───────────────────────────────────────────────────────
|
|
164
|
+
const CreateTemplateZod = z.object({
|
|
165
|
+
displayName: z.string().describe('Display name for the new blueprint template'),
|
|
166
|
+
blueprintName: z
|
|
167
|
+
.string()
|
|
168
|
+
.describe('Display name of an existing project blueprint to save as the template. Defaults to the most recently provisioned blueprint.')
|
|
169
|
+
.optional(),
|
|
170
|
+
description: z.string().describe('Description shown in the template catalog').optional(),
|
|
171
|
+
categories: z
|
|
172
|
+
.array(z.string())
|
|
173
|
+
.describe('Categories for catalog grouping and discovery')
|
|
174
|
+
.optional(),
|
|
175
|
+
});
|
|
176
|
+
const CreateTemplateSchema = toolSchema(CreateTemplateZod);
|
|
177
|
+
export const createTemplateTool = {
|
|
178
|
+
name: 'create_template',
|
|
179
|
+
label: 'Create template',
|
|
180
|
+
description: 'Save an existing project blueprint into the global template catalog as a reusable blueprint template. Defaults to the most recently provisioned blueprint; pass blueprintName to pick a specific one by display name. Gated.',
|
|
181
|
+
promptSnippet: 'create_template: save a project blueprint to the reusable template catalog. Gated.',
|
|
182
|
+
parameters: CreateTemplateSchema,
|
|
183
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
184
|
+
const resolved = await resolveProjectContext(ctx.cwd);
|
|
185
|
+
if (!resolved.context)
|
|
186
|
+
return done(false, resolved.reason);
|
|
187
|
+
const { modules, ownerId } = resolved.context;
|
|
188
|
+
if (!ownerId)
|
|
189
|
+
return done(false, 'Not authenticated (missing OWNER_ID in .env).');
|
|
190
|
+
try {
|
|
191
|
+
const blueprint = await findProjectBlueprint(resolved.context, params.blueprintName);
|
|
192
|
+
if (!blueprint) {
|
|
193
|
+
const which = params.blueprintName ? `"${params.blueprintName}"` : 'any blueprint';
|
|
194
|
+
return done(false, `No project blueprint found (${which}). Provision a blueprint first.`);
|
|
195
|
+
}
|
|
196
|
+
const base = params.displayName.toLowerCase().replace(/\s+/g, '_');
|
|
197
|
+
await modules.blueprintTemplate
|
|
198
|
+
.create({
|
|
199
|
+
data: {
|
|
200
|
+
ownerId,
|
|
201
|
+
name: `${base}_${Date.now()}`,
|
|
202
|
+
displayName: params.displayName,
|
|
203
|
+
description: params.description,
|
|
204
|
+
categories: params.categories,
|
|
205
|
+
definition: blueprint.definition,
|
|
206
|
+
},
|
|
207
|
+
select: { id: true, displayName: true },
|
|
208
|
+
})
|
|
209
|
+
.unwrap();
|
|
210
|
+
const message = `Created template "${params.displayName}"`;
|
|
211
|
+
return {
|
|
212
|
+
content: [{ type: 'text', text: message }],
|
|
213
|
+
details: {
|
|
214
|
+
success: true,
|
|
215
|
+
message,
|
|
216
|
+
displayName: params.displayName,
|
|
217
|
+
blueprintName: blueprint.displayName,
|
|
218
|
+
tables: parseTemplateTables(blueprint.definition),
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
return done(false, err instanceof Error ? err.message : 'Failed to create template');
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
// ── apply_template ────────────────────────────────────────────────────────
|
|
228
|
+
const ApplyTemplateZod = z.object({
|
|
229
|
+
templateName: z.string().describe('The display name of the blueprint template to apply'),
|
|
230
|
+
nameOverride: z
|
|
231
|
+
.string()
|
|
232
|
+
.describe('Optional name override for the created blueprint (snake_case). Defaults to template name.')
|
|
233
|
+
.optional(),
|
|
234
|
+
});
|
|
235
|
+
const ApplyTemplateSchema = toolSchema(ApplyTemplateZod);
|
|
236
|
+
export const applyTemplateTool = {
|
|
237
|
+
name: 'apply_template',
|
|
238
|
+
label: 'Apply template',
|
|
239
|
+
description: 'Apply an existing blueprint template to the project database, creating its tables. Use the template display name (from list_templates).',
|
|
240
|
+
promptSnippet: 'apply_template: provision a saved blueprint template by display name. Gated.',
|
|
241
|
+
parameters: ApplyTemplateSchema,
|
|
242
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
243
|
+
const resolved = await resolveProjectContext(ctx.cwd);
|
|
244
|
+
if (!resolved.context)
|
|
245
|
+
return done(false, resolved.reason);
|
|
246
|
+
const { modules, databaseId, schemaId, ownerId } = resolved.context;
|
|
247
|
+
if (!ownerId)
|
|
248
|
+
return done(false, 'Not authenticated (missing OWNER_ID in .env).');
|
|
249
|
+
try {
|
|
250
|
+
const templateId = await resolveTemplateId(modules, params.templateName);
|
|
251
|
+
const base = params.nameOverride ?? params.templateName.toLowerCase().replace(/\s+/g, '_');
|
|
252
|
+
const nameOverride = `${base}_${Date.now()}`;
|
|
253
|
+
const copyResult = await modules.mutation
|
|
254
|
+
.copyTemplateToBlueprint({ input: { templateId, databaseId, ownerId, nameOverride } }, { select: { result: true } })
|
|
255
|
+
.unwrap();
|
|
256
|
+
const blueprintId = copyResult.copyTemplateToBlueprint?.result;
|
|
257
|
+
if (!blueprintId)
|
|
258
|
+
throw new Error('Failed to copy template');
|
|
259
|
+
const constructResult = await modules.mutation
|
|
260
|
+
.constructBlueprint({ input: { blueprintId, schemaId } }, { select: { result: true } })
|
|
261
|
+
.unwrap();
|
|
262
|
+
const refMap = constructResult.constructBlueprint?.result;
|
|
263
|
+
if (!refMap)
|
|
264
|
+
return done(false, `Construction failed for template "${params.templateName}"`);
|
|
265
|
+
const createdCount = Object.keys(refMap).length;
|
|
266
|
+
return done(true, `Applied template "${params.templateName}" — created ${createdCount} table${createdCount === 1 ? '' : 's'}`);
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
return done(false, err instanceof Error ? err.message : 'Failed to apply template');
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
// ── update_template ───────────────────────────────────────────────────────
|
|
274
|
+
const UpdateTemplateZod = z.object({
|
|
275
|
+
templateName: z.string().describe('The display name of the blueprint template to update'),
|
|
276
|
+
patch: z.object({
|
|
277
|
+
displayName: z.string().describe('New display name').optional(),
|
|
278
|
+
description: z.string().describe('New description').optional(),
|
|
279
|
+
categories: z.array(z.string()).describe('New categories').optional(),
|
|
280
|
+
tags: z.array(z.string()).describe('New tags').optional(),
|
|
281
|
+
visibility: z.enum(['private', 'public']).describe('New visibility').optional(),
|
|
282
|
+
}),
|
|
283
|
+
});
|
|
284
|
+
const UpdateTemplateSchema = toolSchema(UpdateTemplateZod);
|
|
285
|
+
export const updateTemplateTool = {
|
|
286
|
+
name: 'update_template',
|
|
287
|
+
label: 'Update template',
|
|
288
|
+
description: 'Update a blueprint template’s metadata (display name, description, categories, tags, visibility).',
|
|
289
|
+
promptSnippet: 'update_template: edit a saved template’s metadata by display name. Gated.',
|
|
290
|
+
parameters: UpdateTemplateSchema,
|
|
291
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
292
|
+
const resolved = await resolveProjectContext(ctx.cwd);
|
|
293
|
+
if (!resolved.context)
|
|
294
|
+
return done(false, resolved.reason);
|
|
295
|
+
try {
|
|
296
|
+
const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
|
|
297
|
+
await resolved.context.modules.blueprintTemplate
|
|
298
|
+
.update({
|
|
299
|
+
where: { id: templateId },
|
|
300
|
+
data: params.patch,
|
|
301
|
+
select: { id: true, displayName: true },
|
|
302
|
+
})
|
|
303
|
+
.unwrap();
|
|
304
|
+
return done(true, `Updated template "${params.templateName}"`);
|
|
305
|
+
}
|
|
306
|
+
catch (err) {
|
|
307
|
+
return done(false, err instanceof Error ? err.message : 'Failed to update template');
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
// ── delete_template ───────────────────────────────────────────────────────
|
|
312
|
+
const DeleteTemplateZod = z.object({
|
|
313
|
+
templateName: z.string().describe('The display name of the blueprint template to delete'),
|
|
314
|
+
});
|
|
315
|
+
const DeleteTemplateSchema = toolSchema(DeleteTemplateZod);
|
|
316
|
+
export const deleteTemplateTool = {
|
|
317
|
+
name: 'delete_template',
|
|
318
|
+
label: 'Delete template',
|
|
319
|
+
description: 'Permanently delete a blueprint template by its display name.',
|
|
320
|
+
promptSnippet: 'delete_template: remove a saved template by display name. Destructive — gated.',
|
|
321
|
+
parameters: DeleteTemplateSchema,
|
|
322
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
323
|
+
const resolved = await resolveProjectContext(ctx.cwd);
|
|
324
|
+
if (!resolved.context)
|
|
325
|
+
return done(false, resolved.reason);
|
|
326
|
+
try {
|
|
327
|
+
const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
|
|
328
|
+
await resolved.context.modules.blueprintTemplate
|
|
329
|
+
.delete({ where: { id: templateId }, select: { id: true } })
|
|
330
|
+
.unwrap();
|
|
331
|
+
return done(true, `Deleted template "${params.templateName}"`);
|
|
332
|
+
}
|
|
333
|
+
catch (err) {
|
|
334
|
+
return done(false, err instanceof Error ? err.message : 'Failed to delete template');
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
};
|
package/host.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host contract for the pi-hosted Constructive tools.
|
|
3
|
+
*
|
|
4
|
+
* The typed db tools were extracted from Constructive Desktop, where they read
|
|
5
|
+
* an Electron-side `runtime` singleton (account store, backend config, data-auth
|
|
6
|
+
* broker, preview token). Hosts now inject the same surface here once at
|
|
7
|
+
* startup (`configureHost`); the tool modules stay module-level `ToolDefinition`
|
|
8
|
+
* consts and read it lazily via `getHost()`.
|
|
9
|
+
*/
|
|
10
|
+
export type HostAccount = {
|
|
11
|
+
userId: string;
|
|
12
|
+
accessToken: string;
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
};
|
|
15
|
+
export type HostBackendConfig = {
|
|
16
|
+
apiEndpoint?: string;
|
|
17
|
+
modulesEndpoint?: string;
|
|
18
|
+
};
|
|
19
|
+
export type ActiveDataToken = {
|
|
20
|
+
token: string;
|
|
21
|
+
userId?: string;
|
|
22
|
+
expiresAt: number;
|
|
23
|
+
origin?: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Optional data-plane token broker: remembers per-database end-user tokens
|
|
27
|
+
* across tool calls and invalidates declined/expired ones. Hosts without a
|
|
28
|
+
* broker fall back to the preview-token harvest on every call.
|
|
29
|
+
*/
|
|
30
|
+
export interface DataAuthBroker {
|
|
31
|
+
getActiveToken(databaseId: string): ActiveDataToken | undefined | null;
|
|
32
|
+
isInvalidToken(databaseId: string, token: string): boolean;
|
|
33
|
+
adoptToken(databaseId: string, token: ActiveDataToken): void;
|
|
34
|
+
}
|
|
35
|
+
/** Token harvested from the host's app preview (end-user sign-in). */
|
|
36
|
+
export type PreviewToken = {
|
|
37
|
+
accessToken: string;
|
|
38
|
+
accessTokenExpiresAt?: string;
|
|
39
|
+
userId?: string;
|
|
40
|
+
};
|
|
41
|
+
export interface PiToolsHost {
|
|
42
|
+
/** Signed-in platform account, or null/undefined when signed out. */
|
|
43
|
+
account(): HostAccount | null | undefined;
|
|
44
|
+
/** Host-configured backend endpoints (env-aware). */
|
|
45
|
+
backendConfig(): HostBackendConfig | null | undefined;
|
|
46
|
+
/** Optional data-plane token broker (see DataAuthBroker). */
|
|
47
|
+
dataAuthBroker?: DataAuthBroker;
|
|
48
|
+
/** Harvest an end-user token from the host's app preview, if it has one. */
|
|
49
|
+
previewToken?(): Promise<PreviewToken | null>;
|
|
50
|
+
/** Treat tokens expiring within this window as already expired. Default 30s. */
|
|
51
|
+
dataTokenSkewMs?: number;
|
|
52
|
+
}
|
|
53
|
+
export declare const DEFAULT_DATA_TOKEN_SKEW_MS = 30000;
|
|
54
|
+
export declare function configureHost(host: PiToolsHost): void;
|
|
55
|
+
export declare function getHost(): PiToolsHost;
|
package/host.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Host contract for the pi-hosted Constructive tools.
|
|
4
|
+
*
|
|
5
|
+
* The typed db tools were extracted from Constructive Desktop, where they read
|
|
6
|
+
* an Electron-side `runtime` singleton (account store, backend config, data-auth
|
|
7
|
+
* broker, preview token). Hosts now inject the same surface here once at
|
|
8
|
+
* startup (`configureHost`); the tool modules stay module-level `ToolDefinition`
|
|
9
|
+
* consts and read it lazily via `getHost()`.
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DEFAULT_DATA_TOKEN_SKEW_MS = void 0;
|
|
13
|
+
exports.configureHost = configureHost;
|
|
14
|
+
exports.getHost = getHost;
|
|
15
|
+
exports.DEFAULT_DATA_TOKEN_SKEW_MS = 30_000;
|
|
16
|
+
let currentHost = null;
|
|
17
|
+
function configureHost(host) {
|
|
18
|
+
currentHost = host;
|
|
19
|
+
}
|
|
20
|
+
function getHost() {
|
|
21
|
+
if (!currentHost) {
|
|
22
|
+
throw new Error('@agentic-kit/pi host not configured. Call configureHost() (or createDbTools(host)) before using the db tools.');
|
|
23
|
+
}
|
|
24
|
+
return currentHost;
|
|
25
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { ExtensionFactory } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { type PiToolsHost } from './host';
|
|
3
|
+
export declare const dbTools: ExtensionFactory;
|
|
4
|
+
/** Configure the host and get the extension in one call. */
|
|
5
|
+
export declare function createDbTools(host: PiToolsHost): ExtensionFactory;
|
|
6
|
+
export { type ConfirmGate, type ConfirmGateDeps, createConfirmGate } from './confirm-gate';
|
|
7
|
+
export { type ModulesClient, type ProjectContext, resolveDataToken, resolveProjectContext, } from './context';
|
|
8
|
+
export { type ActiveDataToken, configureHost, type DataAuthBroker, getHost, type HostAccount, type HostBackendConfig, type PiToolsHost, type PreviewToken, } from './host';
|
|
9
|
+
export { toolSchema } from './tool-schema';
|
|
10
|
+
export { createTemplatePreviewTables } from './tools/templates';
|
|
11
|
+
export default dbTools;
|
package/index.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createTemplatePreviewTables = exports.toolSchema = exports.getHost = exports.configureHost = exports.resolveProjectContext = exports.resolveDataToken = exports.createConfirmGate = exports.dbTools = void 0;
|
|
4
|
+
exports.createDbTools = createDbTools;
|
|
5
|
+
const confirm_gate_1 = require("./confirm-gate");
|
|
6
|
+
const context_1 = require("./context");
|
|
7
|
+
const host_1 = require("./host");
|
|
8
|
+
const add_policies_1 = require("./tools/add-policies");
|
|
9
|
+
const add_records_1 = require("./tools/add-records");
|
|
10
|
+
const add_relation_1 = require("./tools/add-relation");
|
|
11
|
+
const describe_schema_1 = require("./tools/describe-schema");
|
|
12
|
+
const mutations_1 = require("./tools/mutations");
|
|
13
|
+
const provision_blueprint_1 = require("./tools/provision-blueprint");
|
|
14
|
+
const provision_database_1 = require("./tools/provision-database");
|
|
15
|
+
const run_codegen_1 = require("./tools/run-codegen");
|
|
16
|
+
const templates_1 = require("./tools/templates");
|
|
17
|
+
const dbTools = (pi) => {
|
|
18
|
+
pi.registerTool(provision_database_1.provisionDatabaseTool);
|
|
19
|
+
pi.registerTool(describe_schema_1.describeSchemaTool);
|
|
20
|
+
pi.registerTool(templates_1.listTemplatesTool);
|
|
21
|
+
pi.registerTool(provision_blueprint_1.provisionBlueprintTool);
|
|
22
|
+
pi.registerTool(add_relation_1.addRelationTool);
|
|
23
|
+
pi.registerTool(mutations_1.deleteTableTool);
|
|
24
|
+
pi.registerTool(mutations_1.createFieldTool);
|
|
25
|
+
pi.registerTool(mutations_1.updateFieldTool);
|
|
26
|
+
pi.registerTool(mutations_1.deleteFieldTool);
|
|
27
|
+
pi.registerTool(add_policies_1.addPoliciesTool);
|
|
28
|
+
pi.registerTool(templates_1.applyTemplateTool);
|
|
29
|
+
pi.registerTool(templates_1.createTemplateTool);
|
|
30
|
+
pi.registerTool(templates_1.updateTemplateTool);
|
|
31
|
+
pi.registerTool(templates_1.deleteTemplateTool);
|
|
32
|
+
pi.registerTool(add_records_1.addRecordsTool);
|
|
33
|
+
pi.registerTool(run_codegen_1.runCodegenTool);
|
|
34
|
+
const gate = (0, confirm_gate_1.createConfirmGate)({
|
|
35
|
+
resolveProjectContext: context_1.resolveProjectContext,
|
|
36
|
+
resolveDataToken: context_1.resolveDataToken,
|
|
37
|
+
createTemplatePreviewTables: templates_1.createTemplatePreviewTables,
|
|
38
|
+
});
|
|
39
|
+
pi.on('agent_start', gate.onAgentStart);
|
|
40
|
+
pi.on('tool_call', gate.onToolCall);
|
|
41
|
+
};
|
|
42
|
+
exports.dbTools = dbTools;
|
|
43
|
+
/** Configure the host and get the extension in one call. */
|
|
44
|
+
function createDbTools(host) {
|
|
45
|
+
(0, host_1.configureHost)(host);
|
|
46
|
+
return exports.dbTools;
|
|
47
|
+
}
|
|
48
|
+
var confirm_gate_2 = require("./confirm-gate");
|
|
49
|
+
Object.defineProperty(exports, "createConfirmGate", { enumerable: true, get: function () { return confirm_gate_2.createConfirmGate; } });
|
|
50
|
+
var context_2 = require("./context");
|
|
51
|
+
Object.defineProperty(exports, "resolveDataToken", { enumerable: true, get: function () { return context_2.resolveDataToken; } });
|
|
52
|
+
Object.defineProperty(exports, "resolveProjectContext", { enumerable: true, get: function () { return context_2.resolveProjectContext; } });
|
|
53
|
+
var host_2 = require("./host");
|
|
54
|
+
Object.defineProperty(exports, "configureHost", { enumerable: true, get: function () { return host_2.configureHost; } });
|
|
55
|
+
Object.defineProperty(exports, "getHost", { enumerable: true, get: function () { return host_2.getHost; } });
|
|
56
|
+
var tool_schema_1 = require("./tool-schema");
|
|
57
|
+
Object.defineProperty(exports, "toolSchema", { enumerable: true, get: function () { return tool_schema_1.toolSchema; } });
|
|
58
|
+
var templates_2 = require("./tools/templates");
|
|
59
|
+
Object.defineProperty(exports, "createTemplatePreviewTables", { enumerable: true, get: function () { return templates_2.createTemplatePreviewTables; } });
|
|
60
|
+
exports.default = exports.dbTools;
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentic-kit/pi",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"author": "Dan Lynch <pyramation@gmail.com>",
|
|
5
|
+
"description": "Pi adapter for agentic-kit — the Constructive typed db tools (provision, blueprint, codegen, records, policies, templates) and confirm gate as a pi coding-agent extension",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/constructive",
|
|
10
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/constructive"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/constructive/issues"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"clean": "makage clean",
|
|
24
|
+
"prepack": "npm run build",
|
|
25
|
+
"build": "makage build",
|
|
26
|
+
"build:dev": "makage build --dev",
|
|
27
|
+
"lint": "eslint . --fix",
|
|
28
|
+
"test": "jest",
|
|
29
|
+
"test:watch": "jest --watch"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@agentic-kit/harness": "^0.3.0",
|
|
33
|
+
"@constructive-io/graphql-query": "^4.5.4",
|
|
34
|
+
"@constructive-io/sdk": "^1.5.4",
|
|
35
|
+
"zod": "^4.4.3"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@earendil-works/pi-coding-agent": ">=0.79.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@earendil-works/pi-coding-agent": "0.79.6",
|
|
42
|
+
"typebox": "^1.0.0"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"agentic-kit",
|
|
46
|
+
"pi",
|
|
47
|
+
"coding-agent",
|
|
48
|
+
"constructive"
|
|
49
|
+
],
|
|
50
|
+
"gitHead": "31f7cd3d3cc28cf069056eae5b2a0d4198d154a1"
|
|
51
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type PolicyProvisioningCategory } from '@agentic-kit/harness';
|
|
2
|
+
import type { ModulesClient } from '../context';
|
|
3
|
+
import { type CrudOperation, type CrudPolicyConfigs } from './provision-helpers';
|
|
4
|
+
export interface AddPoliciesToTablePolicyEntry {
|
|
5
|
+
policyType: string;
|
|
6
|
+
dataNodeType?: string;
|
|
7
|
+
nodeData?: Record<string, unknown>;
|
|
8
|
+
sharedPolicyData: Record<string, unknown>;
|
|
9
|
+
operations: CrudPolicyConfigs;
|
|
10
|
+
enabledOperations?: CrudOperation[];
|
|
11
|
+
}
|
|
12
|
+
export interface AddPoliciesToTableInput {
|
|
13
|
+
client: ModulesClient;
|
|
14
|
+
databaseId: string;
|
|
15
|
+
schemaId: string;
|
|
16
|
+
tableId: string;
|
|
17
|
+
policies: AddPoliciesToTablePolicyEntry[];
|
|
18
|
+
}
|
|
19
|
+
export declare class UnsupportedPolicyCategoryError extends Error {
|
|
20
|
+
readonly policyType: string;
|
|
21
|
+
readonly category: PolicyProvisioningCategory;
|
|
22
|
+
constructor(policyType: string, category: PolicyProvisioningCategory);
|
|
23
|
+
}
|
|
24
|
+
export declare function addPoliciesToExistingTable(input: AddPoliciesToTableInput): Promise<{
|
|
25
|
+
success: true;
|
|
26
|
+
}>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UnsupportedPolicyCategoryError = void 0;
|
|
4
|
+
exports.addPoliciesToExistingTable = addPoliciesToExistingTable;
|
|
5
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
6
|
+
const provision_helpers_1 = require("./provision-helpers");
|
|
7
|
+
const SUPPORTED_CATEGORIES = new Set([
|
|
8
|
+
'has-module',
|
|
9
|
+
'no-fields',
|
|
10
|
+
'needs-table',
|
|
11
|
+
]);
|
|
12
|
+
class UnsupportedPolicyCategoryError extends Error {
|
|
13
|
+
policyType;
|
|
14
|
+
category;
|
|
15
|
+
constructor(policyType, category) {
|
|
16
|
+
super(`Policy type "${policyType}" has category "${category}" which requires column creation or composite handling — use the policies UI instead.`);
|
|
17
|
+
this.policyType = policyType;
|
|
18
|
+
this.category = category;
|
|
19
|
+
this.name = 'UnsupportedPolicyCategoryError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.UnsupportedPolicyCategoryError = UnsupportedPolicyCategoryError;
|
|
23
|
+
async function addPoliciesToExistingTable(input) {
|
|
24
|
+
const { client } = input;
|
|
25
|
+
for (const entry of input.policies) {
|
|
26
|
+
const category = (0, harness_1.getPolicyCategory)(entry.policyType);
|
|
27
|
+
if (!SUPPORTED_CATEGORIES.has(category)) {
|
|
28
|
+
throw new UnsupportedPolicyCategoryError(entry.policyType, category);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const policiesArray = [];
|
|
32
|
+
const nodesByType = new Map();
|
|
33
|
+
for (const entry of input.policies) {
|
|
34
|
+
const groups = (0, provision_helpers_1.groupOperationsByConfig)(entry.enabledOperations ?? provision_helpers_1.CRUD_OPERATIONS, entry.operations);
|
|
35
|
+
for (const group of groups) {
|
|
36
|
+
const ops = group.privileges.join('_');
|
|
37
|
+
const rand = Math.random().toString(36).slice(2, 8);
|
|
38
|
+
policiesArray.push((0, provision_helpers_1.buildPolicyEntry)(entry.policyType, {
|
|
39
|
+
privileges: group.privileges,
|
|
40
|
+
policy_role: group.roleName,
|
|
41
|
+
permissive: group.isPermissive,
|
|
42
|
+
data: entry.sharedPolicyData,
|
|
43
|
+
policy_name: `${ops}_${rand}`,
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
if (entry.dataNodeType && !nodesByType.has(entry.dataNodeType)) {
|
|
47
|
+
const nodeData = entry.nodeData ?? {};
|
|
48
|
+
nodesByType.set(entry.dataNodeType, {
|
|
49
|
+
$type: entry.dataNodeType,
|
|
50
|
+
...(Object.keys(nodeData).length > 0 ? { data: nodeData } : {}),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const provisionInput = {
|
|
55
|
+
databaseId: input.databaseId,
|
|
56
|
+
schemaId: input.schemaId,
|
|
57
|
+
tableId: input.tableId,
|
|
58
|
+
grants: (0, provision_helpers_1.buildGrants)(),
|
|
59
|
+
policies: policiesArray,
|
|
60
|
+
};
|
|
61
|
+
if (nodesByType.size > 0) {
|
|
62
|
+
provisionInput.nodes = [...nodesByType.values()];
|
|
63
|
+
}
|
|
64
|
+
await client.secureTableProvision
|
|
65
|
+
.create({
|
|
66
|
+
data: provisionInput,
|
|
67
|
+
select: { id: true, tableId: true, tableName: true },
|
|
68
|
+
})
|
|
69
|
+
.unwrap();
|
|
70
|
+
return { success: true };
|
|
71
|
+
}
|