@agentic-kit/db-tools 0.12.46 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
@@ -0,0 +1,54 @@
1
+ import { type HarnessTool, type ToolCallSuggestion } from '@agentic-kit/harness';
2
+ import { z } from 'zod';
3
+ import type { ProjectContext } from '../context';
4
+ import { type Result } from '../failure';
5
+ export type EntityTypeSummary = {
6
+ id: string;
7
+ name: string | null;
8
+ description: string | null;
9
+ prefix: string | null;
10
+ parentEntity: string | null;
11
+ isVisible: boolean | null;
12
+ entityTableName: string | null;
13
+ installedModules: string[] | null;
14
+ };
15
+ export type EntityTypesDetails = {
16
+ success: boolean;
17
+ message: string;
18
+ entityTypes?: EntityTypeSummary[];
19
+ };
20
+ export declare function defaultPrefix(name: string): string;
21
+ export declare const LIST_ENTITY_TYPES: ToolCallSuggestion;
22
+ export type EntityTypeRow = {
23
+ id: string;
24
+ prefix?: string | null;
25
+ outMembershipType?: number | null;
26
+ };
27
+ /** The entity types of the project database: each one's prefix is a team kind, and its out_membership_type the number rules store. */
28
+ export declare function readEntityTypes(context: ProjectContext): Promise<Result<EntityTypeRow[]>>;
29
+ declare const ListEntityTypesZod: z.ZodObject<{}, z.core.$strict>;
30
+ export declare const listEntityTypesTool: HarnessTool<typeof ListEntityTypesZod, EntityTypesDetails>;
31
+ declare const CreateEntityTypeZod: z.ZodObject<{
32
+ name: z.ZodString;
33
+ description: z.ZodOptional<z.ZodString>;
34
+ prefix: z.ZodOptional<z.ZodString>;
35
+ parent_entity: z.ZodOptional<z.ZodString>;
36
+ is_visible: z.ZodOptional<z.ZodBoolean>;
37
+ has_invites: z.ZodOptional<z.ZodBoolean>;
38
+ has_profiles: z.ZodOptional<z.ZodBoolean>;
39
+ has_limits: z.ZodOptional<z.ZodBoolean>;
40
+ has_levels: z.ZodOptional<z.ZodBoolean>;
41
+ has_storage: z.ZodOptional<z.ZodBoolean>;
42
+ }, z.core.$strict>;
43
+ type CreateParams = z.infer<typeof CreateEntityTypeZod>;
44
+ /** What create_entity_type checks before it changes anything: a name, the project, and a prefix no entity type has. */
45
+ export declare function createEntityTypeReady(params: CreateParams, cwd: string): Promise<Result<ProjectContext>>;
46
+ export declare const createEntityTypeTool: HarnessTool<typeof CreateEntityTypeZod, EntityTypesDetails>;
47
+ declare const DeleteEntityTypeZod: z.ZodObject<{
48
+ entity_type_id: z.ZodGUID;
49
+ }, z.core.$strict>;
50
+ type DeleteParams = z.infer<typeof DeleteEntityTypeZod>;
51
+ /** What delete_entity_type checks before it changes anything: the project, and an entity type of that id. */
52
+ export declare function deleteEntityTypeReady(params: DeleteParams, cwd: string): Promise<Result<ProjectContext>>;
53
+ export declare const deleteEntityTypeTool: HarnessTool<typeof DeleteEntityTypeZod, EntityTypesDetails>;
54
+ export {};
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteEntityTypeTool = exports.createEntityTypeTool = exports.listEntityTypesTool = exports.LIST_ENTITY_TYPES = void 0;
4
+ exports.defaultPrefix = defaultPrefix;
5
+ exports.readEntityTypes = readEntityTypes;
6
+ exports.createEntityTypeReady = createEntityTypeReady;
7
+ exports.deleteEntityTypeReady = deleteEntityTypeReady;
8
+ const harness_1 = require("@agentic-kit/harness");
9
+ const zod_1 = require("zod");
10
+ const failure_1 = require("../failure");
11
+ const ready_1 = require("../ready");
12
+ const SUMMARY_SELECT = {
13
+ id: true,
14
+ name: true,
15
+ description: true,
16
+ prefix: true,
17
+ parentEntity: true,
18
+ isVisible: true,
19
+ outEntityTableName: true,
20
+ outInstalledModules: true,
21
+ };
22
+ function toSummary(row) {
23
+ return {
24
+ id: row.id,
25
+ name: row.name,
26
+ description: row.description,
27
+ prefix: row.prefix,
28
+ parentEntity: row.parentEntity,
29
+ isVisible: row.isVisible,
30
+ entityTableName: row.outEntityTableName,
31
+ installedModules: row.outInstalledModules,
32
+ };
33
+ }
34
+ function formatSummary(s) {
35
+ const parts = [
36
+ `- ${s.name ?? '?'} (id: ${s.id})`,
37
+ ` table: ${s.entityTableName ?? '?'}, prefix: ${s.prefix ?? '?'}`,
38
+ ];
39
+ if (s.parentEntity)
40
+ parts.push(` parent: ${s.parentEntity}`);
41
+ if (s.description)
42
+ parts.push(` description: ${s.description}`);
43
+ if (s.installedModules?.length)
44
+ parts.push(` modules: ${s.installedModules.join(', ')}`);
45
+ return parts.join('\n');
46
+ }
47
+ function defaultPrefix(name) {
48
+ return name
49
+ .trim()
50
+ .toLowerCase()
51
+ .replace(/[^a-z0-9]+/g, '_')
52
+ .replace(/^_+|_+$/g, '');
53
+ }
54
+ exports.LIST_ENTITY_TYPES = (0, failure_1.suggest)('list_entity_types', {}, 'See the entity types that exist');
55
+ /** The entity types of the project database: each one's prefix is a team kind, and its out_membership_type the number rules store. */
56
+ async function readEntityTypes(context) {
57
+ try {
58
+ const result = await context.modules.entityTypeProvision
59
+ .findMany({ where: { databaseId: { equalTo: context.databaseId } }, select: { id: true, prefix: true, outMembershipType: true } })
60
+ .unwrap();
61
+ return { kind: 'ok', value: result.entityTypeProvisions.nodes };
62
+ }
63
+ catch (err) {
64
+ return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to read the entity types of the project database') };
65
+ }
66
+ }
67
+ function fail(failure) {
68
+ return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure) });
69
+ }
70
+ const done = (message, entityTypes, calls) => ({
71
+ content: [{ type: 'text', text: message }],
72
+ details: { success: true, message, ...(entityTypes ? { entityTypes } : {}) },
73
+ ...(calls ? { calls } : {}),
74
+ });
75
+ // ── list_entity_types ────────────────────────────────────────────────────
76
+ const ListEntityTypesZod = (0, harness_1.strictObject)('the input', {});
77
+ exports.listEntityTypesTool = {
78
+ name: 'list_entity_types',
79
+ label: 'List entity types',
80
+ description: 'List the entity types of the project database (organizations, teams, projects, …): each one with its id, prefix, entity table and modules. An entity type is the unit API keys can be scoped to. Read-only.',
81
+ promptSnippet: 'list_entity_types: the entity types (orgs, teams, …) of the project database. Read-only.',
82
+ parameters: ListEntityTypesZod,
83
+ effect: 'read',
84
+ async execute(_params, ctx) {
85
+ const ready = await (0, ready_1.projectReady)(ctx.cwd);
86
+ if (ready.kind === 'failed')
87
+ return fail(ready.failure);
88
+ const { modules, databaseId } = ready.value;
89
+ try {
90
+ const result = await modules.entityTypeProvision.findMany({ where: { databaseId: { equalTo: databaseId } }, select: SUMMARY_SELECT }).unwrap();
91
+ const entityTypes = result.entityTypeProvisions.nodes.map((row) => toSummary(row));
92
+ const message = entityTypes.length === 0
93
+ ? 'No entity types yet.'
94
+ : `${entityTypes.length} entity type${entityTypes.length === 1 ? '' : 's'}:\n${entityTypes.map(formatSummary).join('\n')}`;
95
+ return done(message, entityTypes);
96
+ }
97
+ catch (err) {
98
+ return fail((0, failure_1.failureFromError)(err, 'Failed to list entity types'));
99
+ }
100
+ },
101
+ };
102
+ // ── create_entity_type ───────────────────────────────────────────────────
103
+ const CreateEntityTypeZod = (0, harness_1.strictObject)('the input', {
104
+ name: (0, harness_1.textParam)().describe('Entity type name'),
105
+ description: zod_1.z.string().describe('Human-readable description of the entity type').optional(),
106
+ prefix: (0, harness_1.identifierParam)()
107
+ .describe('Table-name prefix for the provisioned tables (e.g. "org" → org table, org_memberships); defaults to the snake_case of name.')
108
+ .optional(),
109
+ parent_entity: (0, harness_1.identifierParam)()
110
+ .describe('Parent entity table name, for hierarchical types (e.g. a "team" under an "org"); the backend defaults it to the root entity (org).')
111
+ .optional(),
112
+ is_visible: zod_1.z.boolean().describe('Whether the type shows up in end-user entity listings').optional(),
113
+ has_invites: zod_1.z.boolean().describe('Provision an invites module ({prefix}_invites + claimed invites)').optional(),
114
+ has_profiles: zod_1.z.boolean().describe('Provision a profiles table for members of this type').optional(),
115
+ has_limits: zod_1.z.boolean().describe('Provision usage-limits tracking for this type').optional(),
116
+ has_levels: zod_1.z.boolean().describe('Provision levels/achievements support for this type').optional(),
117
+ has_storage: zod_1.z.boolean().describe('Provision a storage module (files + buckets tables) for this type').optional(),
118
+ });
119
+ const prefixOf = (params) => params.prefix?.trim() || defaultPrefix(params.name);
120
+ /** What create_entity_type checks before it changes anything: a name, the project, and a prefix no entity type has. */
121
+ async function createEntityTypeReady(params, cwd) {
122
+ if (!params.name.trim())
123
+ return { kind: 'failed', failure: { code: 'invalid-input', message: 'The entity type needs a name that is not blank.' } };
124
+ const ready = await (0, ready_1.projectReady)(cwd);
125
+ if (ready.kind === 'failed')
126
+ return ready;
127
+ const read = await readEntityTypes(ready.value);
128
+ if (read.kind === 'failed')
129
+ return read;
130
+ const prefix = prefixOf(params);
131
+ if (read.value.some((type) => type.prefix === prefix)) {
132
+ return {
133
+ kind: 'failed',
134
+ failure: {
135
+ code: 'name-taken',
136
+ message: `Failed to create entity type "${params.name}": an entity type with the prefix "${prefix}" already exists in this database.`,
137
+ hint: 'Choose another name or prefix; check the entity types that exist.',
138
+ calls: [exports.LIST_ENTITY_TYPES],
139
+ },
140
+ };
141
+ }
142
+ return ready;
143
+ }
144
+ exports.createEntityTypeTool = {
145
+ name: 'create_entity_type',
146
+ label: 'Create entity type',
147
+ description: 'Create an entity type in the project database (an organization, a team, a project): it provisions its own entity table and the tables that record who belongs to each one. A type cannot be changed once provisioned; to change one, delete it and create a new one.',
148
+ promptSnippet: 'create_entity_type: add an entity type (org, team, …) with its table and memberships. Gated.',
149
+ parameters: CreateEntityTypeZod,
150
+ effect: 'write',
151
+ async execute(params, ctx) {
152
+ const ready = await createEntityTypeReady(params, ctx.cwd);
153
+ if (ready.kind === 'failed')
154
+ return fail(ready.failure);
155
+ const { modules, databaseId } = ready.value;
156
+ const name = params.name.trim();
157
+ const action = `Failed to create entity type "${name}"`;
158
+ try {
159
+ const result = await modules.entityTypeProvision
160
+ .create({
161
+ data: {
162
+ databaseId,
163
+ name,
164
+ prefix: prefixOf(params),
165
+ ...(params.description !== undefined && { description: params.description }),
166
+ ...(params.parent_entity !== undefined && { parentEntity: params.parent_entity }),
167
+ ...(params.is_visible !== undefined && { isVisible: params.is_visible }),
168
+ ...(params.has_invites !== undefined && { hasInvites: params.has_invites }),
169
+ ...(params.has_profiles !== undefined && { hasProfiles: params.has_profiles }),
170
+ ...(params.has_limits !== undefined && { hasLimits: params.has_limits }),
171
+ ...(params.has_levels !== undefined && { hasLevels: params.has_levels }),
172
+ ...(params.has_storage && { storage: [{}] }),
173
+ },
174
+ select: SUMMARY_SELECT,
175
+ })
176
+ .unwrap();
177
+ const row = result.createEntityTypeProvision?.entityTypeProvision;
178
+ if (!row)
179
+ return fail((0, failure_1.noRowCreated)(action, exports.LIST_ENTITY_TYPES));
180
+ const summary = toSummary(row);
181
+ const modulesText = summary.installedModules?.length ? `, modules: ${summary.installedModules.join(', ')}` : '';
182
+ return done(`Created entity type "${summary.name}" (id: ${summary.id}) — entity table "${summary.entityTableName}"${modulesText}. Generate the typed SDK again to use it in the app.`, [summary], [(0, failure_1.suggest)('run_codegen', {}, 'Generate the typed SDK with the new entity type')]);
183
+ }
184
+ catch (err) {
185
+ return fail((0, failure_1.failureFromError)(err, action, { taken: `an entity type with the prefix "${prefixOf(params)}" already exists in this database.`, check: exports.LIST_ENTITY_TYPES }));
186
+ }
187
+ },
188
+ };
189
+ // ── delete_entity_type ───────────────────────────────────────────────────
190
+ const DeleteEntityTypeZod = (0, harness_1.strictObject)('the input', {
191
+ entity_type_id: (0, harness_1.idParam)().describe('The id of the entity type, as the list of entity types gives it'),
192
+ });
193
+ /** What delete_entity_type checks before it changes anything: the project, and an entity type of that id. */
194
+ async function deleteEntityTypeReady(params, cwd) {
195
+ const ready = await (0, ready_1.projectReady)(cwd);
196
+ if (ready.kind === 'failed')
197
+ return ready;
198
+ const read = await readEntityTypes(ready.value);
199
+ if (read.kind === 'failed')
200
+ return read;
201
+ if (!read.value.some((type) => type.id === params.entity_type_id)) {
202
+ return {
203
+ kind: 'failed',
204
+ failure: {
205
+ code: 'not-found',
206
+ message: `No entity type has the id ${params.entity_type_id} in the project database.`,
207
+ hint: 'Check the ids of the entity types that exist, then retry.',
208
+ calls: [exports.LIST_ENTITY_TYPES],
209
+ },
210
+ };
211
+ }
212
+ return ready;
213
+ }
214
+ exports.deleteEntityTypeTool = {
215
+ name: 'delete_entity_type',
216
+ label: 'Delete entity type',
217
+ description: 'Delete the registration of an entity type. Its entity table and the rows in it stay in the database and its API. Destructive.',
218
+ promptSnippet: 'delete_entity_type: remove the registration of an entity type; its table stays. Destructive — gated.',
219
+ parameters: DeleteEntityTypeZod,
220
+ effect: 'destructive',
221
+ async execute(params, ctx) {
222
+ const ready = await deleteEntityTypeReady(params, ctx.cwd);
223
+ if (ready.kind === 'failed')
224
+ return fail(ready.failure);
225
+ const action = `Failed to delete entity type ${params.entity_type_id}`;
226
+ try {
227
+ const result = await ready.value.modules.entityTypeProvision
228
+ .delete({ where: { id: params.entity_type_id }, select: { id: true, name: true, outEntityTableName: true } })
229
+ .unwrap();
230
+ const row = result.deleteEntityTypeProvision?.entityTypeProvision;
231
+ if (!row)
232
+ return fail((0, failure_1.noRowsChanged)(action, exports.LIST_ENTITY_TYPES));
233
+ const table = row.outEntityTableName ? ` "${row.outEntityTableName}"` : '';
234
+ return done(`Deleted entity type registration "${row.name ?? params.entity_type_id}". Note: the provisioned entity table${table} remains in the API schema with its data.`);
235
+ }
236
+ catch (err) {
237
+ return fail((0, failure_1.failureFromError)(err, action));
238
+ }
239
+ },
240
+ };
@@ -0,0 +1,26 @@
1
+ import type { AnyHarnessTool, PlanTableAccess, PlanTarget } from '@agentic-kit/harness';
2
+ import type { Result } from '../failure';
3
+ /**
4
+ * The Constructive database tools, in registration order.
5
+ *
6
+ * Plain `HarnessTool`s: a harness gets them by mapping them into its own tool
7
+ * shape, which is the adapter's job, so this package stays free of any harness
8
+ * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
9
+ */
10
+ export declare const constructiveDbTools: readonly AnyHarnessTool[];
11
+ /** What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, and what it must say that the input does not. */
12
+ export type Resolved = {
13
+ target: PlanTarget;
14
+ access?: PlanTableAccess[];
15
+ notes?: string[];
16
+ };
17
+ type Precondition = (params: any, cwd: string) => Promise<Result<Resolved>>;
18
+ /**
19
+ * The check each db tool runs first, before it changes anything, by tool name,
20
+ * for the gate to run on the same parsed params; its target is what the plan
21
+ * names. The template catalog belongs to the account, so the template tools
22
+ * name the account, and provision_database the backend and account it
23
+ * provisions under.
24
+ */
25
+ export declare const toolPreconditions: ReadonlyMap<string, Precondition>;
26
+ export {};
package/tools/index.js ADDED
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toolPreconditions = exports.constructiveDbTools = void 0;
4
+ const access_1 = require("../access");
5
+ const field_type_1 = require("../blueprint/field-type");
6
+ const provision_1 = require("../provision-database/provision");
7
+ const ready_1 = require("../ready");
8
+ const schema_resolve_1 = require("../schema-resolve");
9
+ const table_access_1 = require("../table-access");
10
+ const access_2 = require("./access");
11
+ const add_policies_1 = require("./add-policies");
12
+ const add_records_1 = require("./add-records");
13
+ const add_relation_1 = require("./add-relation");
14
+ const create_api_key_1 = require("./create-api-key");
15
+ const describe_schema_1 = require("./describe-schema");
16
+ const entity_types_1 = require("./entity-types");
17
+ const mutations_1 = require("./mutations");
18
+ const provision_blueprint_1 = require("./provision-blueprint");
19
+ const provision_database_1 = require("./provision-database");
20
+ const run_codegen_1 = require("./run-codegen");
21
+ const templates_1 = require("./templates");
22
+ /**
23
+ * The Constructive database tools, in registration order.
24
+ *
25
+ * Plain `HarnessTool`s: a harness gets them by mapping them into its own tool
26
+ * shape, which is the adapter's job, so this package stays free of any harness
27
+ * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
28
+ */
29
+ exports.constructiveDbTools = [
30
+ provision_database_1.provisionDatabaseTool,
31
+ provision_database_1.replaceDatabaseTool,
32
+ describe_schema_1.describeSchemaTool,
33
+ templates_1.listTemplatesTool,
34
+ provision_blueprint_1.provisionBlueprintTool,
35
+ add_relation_1.addRelationTool,
36
+ mutations_1.deleteTableTool,
37
+ mutations_1.createFieldTool,
38
+ mutations_1.updateFieldTool,
39
+ mutations_1.retypeFieldTool,
40
+ mutations_1.deleteFieldTool,
41
+ add_policies_1.addPoliciesTool,
42
+ templates_1.applyTemplateTool,
43
+ templates_1.createTemplateTool,
44
+ templates_1.updateTemplateTool,
45
+ templates_1.deleteTemplateTool,
46
+ add_records_1.addRecordsTool,
47
+ entity_types_1.listEntityTypesTool,
48
+ entity_types_1.createEntityTypeTool,
49
+ entity_types_1.deleteEntityTypeTool,
50
+ create_api_key_1.createApiKeyTool,
51
+ run_codegen_1.runCodegenTool,
52
+ access_2.explainAccessTool,
53
+ access_2.setAccessTool,
54
+ access_2.describePolicyTypeTool,
55
+ ];
56
+ /** A tool's first check, with what it resolved turned into what its plan names. */
57
+ function targeting(check, target, access, notes) {
58
+ return async (params, cwd) => {
59
+ const ready = await check(params, cwd);
60
+ if (ready.kind === 'failed')
61
+ return ready;
62
+ const said = (notes?.(params) ?? []).filter((note) => note !== undefined);
63
+ return {
64
+ kind: 'ok',
65
+ value: {
66
+ target: target(ready.value),
67
+ ...(access ? { access: access(ready.value) } : {}),
68
+ ...(said.length ? { notes: said } : {}),
69
+ },
70
+ };
71
+ };
72
+ }
73
+ // A new field's or table's name, as the backend will store it.
74
+ const newFieldNote = (params) => [params.field_name ? (0, schema_resolve_1.renameNote)('field', params.field_name) : undefined];
75
+ const newRelationNotes = (params) => [
76
+ ...newFieldNote(params),
77
+ params.junction_table_name ? (0, schema_resolve_1.renameNote)('table', params.junction_table_name) : undefined,
78
+ ];
79
+ // The access of each table a blueprint creates: its rules and grants as the backend receives them, with the read-only
80
+ // limit the backend adds beside a team rule, its own fields and the columns its nodes add (a new table has no rows),
81
+ // and the names the backend stores differently.
82
+ const blueprintAccess = ({ definition, related }) => definition.tables.flatMap((table) => {
83
+ if (typeof table.table_name !== 'string')
84
+ return [];
85
+ const policies = (table.policies ?? []);
86
+ const grants = table.grants;
87
+ const rules = policies.map(access_1.tablePolicyFromBlueprint);
88
+ // The blueprint was refused before this when a rule reads a column the table will not have.
89
+ const change = (0, table_access_1.columnChange)(table.table_name, (table.fields ?? []).map(({ name }) => ({ name })), table.nodes ?? [], rules);
90
+ const columns = change.kind === 'ok' ? change.value : { added: [], reused: [], failsIfRows: [], fields: [], notes: [] };
91
+ const own = (table.fields ?? []).map((field) => ({
92
+ name: field.name,
93
+ required: field.is_required === true,
94
+ default: typeof field.default === 'object' ? field.default : (0, field_type_1.toFieldDefault)(field.default) ?? null,
95
+ type: (0, field_type_1.fieldTypeToTypeName)(field.type),
96
+ }));
97
+ const access = (0, table_access_1.planTableAccess)(table.table_name, undefined, {
98
+ policies: [...rules, ...(0, access_2.addedByBackend)(policies, grants)],
99
+ grants,
100
+ rls_enabled: table.use_rls !== false,
101
+ fields: [...own, ...columns.fields],
102
+ ...(related ? { related } : {}),
103
+ });
104
+ const names = [(0, schema_resolve_1.renameNote)('table', table.table_name), ...(table.fields ?? []).map((field) => (0, schema_resolve_1.renameNote)('field', field.name))];
105
+ const notes = [...names.filter((note) => note !== undefined), ...(0, access_2.readOnlyNotes)(policies, grants), ...columns.notes];
106
+ return [{ ...access, ...(table.schema_name ? { schema: table.schema_name } : {}), ...(0, table_access_1.columnPlan)(columns, false), ...(notes.length ? { notes } : {}) }];
107
+ });
108
+ const project = (_params, cwd) => (0, ready_1.projectReady)(cwd);
109
+ const onDatabase = (check) => targeting(check, (context) => (0, ready_1.databaseTarget)(context));
110
+ /**
111
+ * The check each db tool runs first, before it changes anything, by tool name,
112
+ * for the gate to run on the same parsed params; its target is what the plan
113
+ * names. The template catalog belongs to the account, so the template tools
114
+ * name the account, and provision_database the backend and account it
115
+ * provisions under.
116
+ */
117
+ exports.toolPreconditions = new Map([
118
+ [provision_database_1.provisionDatabaseTool.name, targeting((_params, cwd) => (0, provision_1.provisionDatabaseReady)(false, cwd), (target) => target)],
119
+ [provision_database_1.replaceDatabaseTool.name, targeting((_params, cwd) => (0, provision_1.provisionDatabaseReady)(true, cwd), (target) => target)],
120
+ [describe_schema_1.describeSchemaTool.name, onDatabase(project)],
121
+ [templates_1.listTemplatesTool.name, targeting(project, ready_1.accountTarget)],
122
+ [provision_blueprint_1.provisionBlueprintTool.name, targeting(provision_blueprint_1.provisionBlueprintReady, (context) => (0, ready_1.databaseTarget)(context), blueprintAccess)],
123
+ [add_relation_1.addRelationTool.name, targeting(add_relation_1.addRelationReady, (context) => (0, ready_1.databaseTarget)(context), undefined, newRelationNotes)],
124
+ [mutations_1.deleteTableTool.name, targeting(mutations_1.deleteTableReady, ({ context, table }) => ({
125
+ ...(0, ready_1.databaseTarget)(context),
126
+ table: { id: table.id, schemaId: context.schemaId },
127
+ }))],
128
+ [mutations_1.createFieldTool.name, targeting(mutations_1.createFieldReady, ({ context }) => (0, ready_1.databaseTarget)(context), undefined, newFieldNote)],
129
+ [mutations_1.updateFieldTool.name, targeting(mutations_1.updateFieldReady, ({ context }) => (0, ready_1.databaseTarget)(context))],
130
+ [mutations_1.retypeFieldTool.name, targeting(mutations_1.retypeFieldReady, ({ context }) => (0, ready_1.databaseTarget)(context))],
131
+ [mutations_1.deleteFieldTool.name, targeting(mutations_1.deleteFieldReady, ({ context }) => (0, ready_1.databaseTarget)(context))],
132
+ [add_policies_1.addPoliciesTool.name, targeting(add_policies_1.addPoliciesReady, ({ context }) => (0, ready_1.databaseTarget)(context), add_policies_1.addPoliciesPlan)],
133
+ [templates_1.applyTemplateTool.name, targeting(templates_1.applyTemplateReady, ({ context }) => (0, ready_1.databaseTarget)(context), blueprintAccess)],
134
+ [templates_1.createTemplateTool.name, targeting((_params, cwd) => (0, ready_1.ownedProjectReady)(cwd), ready_1.accountTarget)],
135
+ [templates_1.updateTemplateTool.name, targeting(templates_1.templateReady, ({ context }) => (0, ready_1.accountTarget)(context))],
136
+ [templates_1.deleteTemplateTool.name, targeting(templates_1.templateReady, ({ context }) => (0, ready_1.accountTarget)(context))],
137
+ [add_records_1.addRecordsTool.name, targeting(add_records_1.addRecordsReady, ({ context, userId }) => (0, ready_1.databaseTarget)(context, userId))],
138
+ [entity_types_1.listEntityTypesTool.name, onDatabase(project)],
139
+ [entity_types_1.createEntityTypeTool.name, onDatabase(entity_types_1.createEntityTypeReady)],
140
+ [entity_types_1.deleteEntityTypeTool.name, onDatabase(entity_types_1.deleteEntityTypeReady)],
141
+ [create_api_key_1.createApiKeyTool.name, targeting(create_api_key_1.createApiKeyReady, ({ context }) => (0, ready_1.databaseTarget)(context))],
142
+ [
143
+ run_codegen_1.runCodegenTool.name,
144
+ async (_params, cwd) => {
145
+ const ready = await (0, run_codegen_1.runCodegenReady)(cwd);
146
+ if (ready.kind === 'failed')
147
+ return ready;
148
+ const { context, notes } = ready.value;
149
+ return { kind: 'ok', value: { target: (0, ready_1.databaseTarget)(context), notes } };
150
+ },
151
+ ],
152
+ [access_2.explainAccessTool.name, onDatabase(project)],
153
+ [access_2.setAccessTool.name, targeting(access_2.setAccessReady, ({ context }) => (0, ready_1.databaseTarget)(context), access_2.setAccessPlan)],
154
+ ]);
@@ -1,35 +1,64 @@
1
1
  import { type HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
+ import type { ProjectContext } from '../context';
4
+ import { type Result } from '../failure';
5
+ import { type ResolvedField, type ResolvedTable } from '../schema-resolve';
3
6
  export type MutationDetails = {
4
7
  success: boolean;
5
8
  message: string;
9
+ /** With a partial result: what the backend said about the part that did not happen. */
10
+ errors?: string[];
11
+ };
12
+ /** The project, and the table (and field) a change names, read before any plan. */
13
+ type Named = {
14
+ context: ProjectContext;
15
+ table: ResolvedTable;
16
+ field?: ResolvedField;
6
17
  };
7
18
  declare const DeleteTableZod: z.ZodObject<{
8
19
  table_name: z.ZodString;
9
- }, z.core.$strip>;
20
+ }, z.core.$strict>;
21
+ /** What delete_table checks before it changes anything: the project, and the table. */
22
+ export declare const deleteTableReady: (params: z.infer<typeof DeleteTableZod>, cwd: string) => Promise<Result<Named>>;
10
23
  export declare const deleteTableTool: HarnessTool<typeof DeleteTableZod, MutationDetails>;
11
24
  declare const CreateFieldZod: z.ZodObject<{
12
25
  table_name: z.ZodString;
13
26
  field_name: z.ZodString;
14
27
  type: z.ZodString;
15
28
  is_required: z.ZodOptional<z.ZodBoolean>;
16
- default_value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNull]>>;
29
+ default_value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>;
17
30
  is_unique: z.ZodOptional<z.ZodBoolean>;
18
- }, z.core.$strip>;
31
+ }, z.core.$strict>;
32
+ /** What create_field checks before it changes anything: the project, the table, and that the field's stored name is free. */
33
+ export declare function createFieldReady(params: z.infer<typeof CreateFieldZod>, cwd: string): Promise<Result<Named>>;
19
34
  export declare const createFieldTool: HarnessTool<typeof CreateFieldZod, MutationDetails>;
20
35
  declare const UpdateFieldZod: z.ZodObject<{
21
36
  table_name: z.ZodString;
22
37
  field_name: z.ZodString;
23
38
  new_name: z.ZodOptional<z.ZodString>;
24
- new_type: z.ZodOptional<z.ZodString>;
25
39
  is_required: z.ZodOptional<z.ZodBoolean>;
26
- default_value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNull]>>;
40
+ default_value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>;
27
41
  is_unique: z.ZodOptional<z.ZodBoolean>;
28
- }, z.core.$strip>;
42
+ }, z.core.$strict>;
43
+ type UpdateFieldParams = z.infer<typeof UpdateFieldZod>;
44
+ /** What update_field checks before it changes anything: a change to make, and the project. */
45
+ export declare function updateFieldReady(params: UpdateFieldParams, cwd: string): Promise<Result<Named & {
46
+ field: ResolvedField;
47
+ }>>;
29
48
  export declare const updateFieldTool: HarnessTool<typeof UpdateFieldZod, MutationDetails>;
49
+ declare const RetypeFieldZod: z.ZodObject<{
50
+ table_name: z.ZodString;
51
+ field_name: z.ZodString;
52
+ type: z.ZodString;
53
+ }, z.core.$strict>;
54
+ /** What retype_field checks before it changes anything: the project, the table and the field. */
55
+ export declare const retypeFieldReady: (params: z.infer<typeof RetypeFieldZod>, cwd: string) => Promise<Result<Named>>;
56
+ export declare const retypeFieldTool: HarnessTool<typeof RetypeFieldZod, MutationDetails>;
30
57
  declare const DeleteFieldZod: z.ZodObject<{
31
58
  table_name: z.ZodString;
32
59
  field_name: z.ZodString;
33
- }, z.core.$strip>;
60
+ }, z.core.$strict>;
61
+ /** What delete_field checks before it changes anything: the project, the table and the field. */
62
+ export declare const deleteFieldReady: (params: z.infer<typeof DeleteFieldZod>, cwd: string) => Promise<Result<Named>>;
34
63
  export declare const deleteFieldTool: HarnessTool<typeof DeleteFieldZod, MutationDetails>;
35
64
  export {};