@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,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.expandBlueprintDefaults = expandBlueprintDefaults;
4
+ const access_1 = require("../access");
5
+ const field_type_1 = require("./field-type");
6
+ const DEFAULT_GRANTS = [
7
+ {
8
+ roles: ['authenticated'],
9
+ privileges: [
10
+ ['select', '*'],
11
+ ['insert', '*'],
12
+ ['update', '*'],
13
+ ['delete', '*'],
14
+ ],
15
+ },
16
+ ];
17
+ const ALL_PRIVILEGES = ['select', 'insert', 'update', 'delete'];
18
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ const typeOf = (node) => (typeof node === 'string' ? node : node.$type);
20
+ const listOf = (value) => (Array.isArray(value) ? value : []);
21
+ /** A rule with the role, the privileges and the kind the backend takes when it gives none. */
22
+ function expandPolicy(policy) {
23
+ if (!isRecord(policy))
24
+ return policy;
25
+ return { ...policy, privileges: policy.privileges ?? ALL_PRIVILEGES, policy_role: policy.policy_role ?? 'authenticated', permissive: policy.permissive ?? true };
26
+ }
27
+ /** A field with its type and default in the backend's form: a type name becomes a FieldType, SQL text or a constant a FieldDefault. */
28
+ function expandField(field) {
29
+ if (!isRecord(field))
30
+ return field;
31
+ const { default: given, ...rest } = field;
32
+ const type = typeof field.type === 'string' ? (0, field_type_1.toFieldType)(field.type) : field.type;
33
+ const value = typeof given === 'string' || typeof given === 'number' || typeof given === 'boolean' || given === null ? (0, field_type_1.toFieldDefault)(given) : given;
34
+ return { ...rest, type, ...(value === undefined ? {} : { default: value }) };
35
+ }
36
+ // A new table: DataId first, its own nodes, the Data nodes its rules need, DataTimestamps last; its fields as given (the
37
+ // backend creates them before the nodes, and a node keeps a column that exists); row security on and the default
38
+ // grants unless it gives its own.
39
+ function expandTable(table) {
40
+ if (!isRecord(table) || typeof table.table_name !== 'string')
41
+ return table;
42
+ const policies = listOf(table.policies).map(expandPolicy);
43
+ const rules = policies.filter(isRecord).flatMap((policy) => {
44
+ const rule = { type: String(policy.$type), data: isRecord(policy.data) ? policy.data : {} };
45
+ const check = policy.with_check;
46
+ return isRecord(check) && typeof check.$type === 'string'
47
+ ? [rule, { type: check.$type, data: isRecord(check.data) ? check.data : {} }]
48
+ : [rule];
49
+ });
50
+ const declared = listOf(table.fields).flatMap((field) => (isRecord(field) && typeof field.name === 'string' ? [field.name] : []));
51
+ const needed = (0, access_1.dataNodesForPolicies)(rules, new Set(declared)).nodes;
52
+ const given = listOf(table.nodes).filter((node) => typeof node === 'string' || (isRecord(node) && typeof node.$type === 'string'));
53
+ const present = new Set(given.map(typeOf));
54
+ const body = given.filter((node) => typeOf(node) !== 'DataId' && typeOf(node) !== 'DataTimestamps');
55
+ const stamps = present.has('DataTimestamps') ? given.filter((node) => typeOf(node) === 'DataTimestamps') : ['DataTimestamps'];
56
+ const nodes = ['DataId', ...body, ...needed.filter((node) => !present.has(node.$type)), ...stamps];
57
+ const fields = Array.isArray(table.fields) ? table.fields.map(expandField) : table.fields;
58
+ return {
59
+ ...table,
60
+ use_rls: table.use_rls ?? true,
61
+ grants: table.grants ?? DEFAULT_GRANTS,
62
+ nodes,
63
+ ...(Array.isArray(table.policies) ? { policies } : {}),
64
+ ...(fields === undefined ? {} : { fields }),
65
+ };
66
+ }
67
+ /**
68
+ * The blueprint the backend receives, with every key the caller gave. A new table (one with a table_name) gets DataId,
69
+ * its own nodes, the Data nodes its rules need (node-type-registry's `dataNodesForPolicies`) and DataTimestamps; row
70
+ * security and the default grants when it gives none; each rule's role, privileges and kind when it gives none; and its
71
+ * fields, each field's type and default in the backend's form. An entry that attaches to
72
+ * a module's table, and every other key of the definition, goes as given. Nothing here checks the blueprint: the
73
+ * registry's JSON Schema and the backend do.
74
+ */
75
+ function expandBlueprintDefaults(definition) {
76
+ return { ...definition, ...(Array.isArray(definition.tables) ? { tables: definition.tables.map(expandTable) } : {}) };
77
+ }
@@ -0,0 +1,68 @@
1
+ import { type BlueprintDefinition, type BlueprintField, type BlueprintTable, type FieldDefault, type FieldType } from 'node-type-registry';
2
+ import { z } from 'zod';
3
+ import { type RuleProblem } from '../access/policies';
4
+ /** The policy types a rule takes: the registry's Authz nodes that are policies. */
5
+ export declare const AuthzTypeZod: z.ZodEnum<{
6
+ [x: string]: string;
7
+ }>;
8
+ /** What a rule object says about a key of another rule shape, or one the tools do not support. */
9
+ export declare const RULE_KEY_HINTS: Record<string, string>;
10
+ /**
11
+ * One access rule, in the registry's blueprint shape (`BlueprintPolicy`). The tool checks it against that shape
12
+ * (`ruleShapeProblems`) and its data against its policy type.
13
+ */
14
+ export declare const AccessPolicyZod: z.ZodObject<{
15
+ $type: z.ZodString;
16
+ privileges: z.ZodOptional<z.ZodArray<z.ZodString>>;
17
+ permissive: z.ZodOptional<z.ZodBoolean>;
18
+ policy_role: z.ZodOptional<z.ZodString>;
19
+ policy_name: z.ZodOptional<z.ZodString>;
20
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
21
+ }, z.core.$loose>;
22
+ export type AccessPolicy = z.infer<typeof AccessPolicyZod>;
23
+ /**
24
+ * What is wrong with one rule's shape, by the registry's `BlueprintPolicy`: its keys, its policy type and its
25
+ * privileges, which a rule here always gives (its data is its policy type's to check). `with_check` is refused unless
26
+ * `withCheck` allows it.
27
+ */
28
+ export declare function ruleShapeProblems(rule: unknown, { withCheck }?: {
29
+ withCheck?: boolean;
30
+ }): RuleProblem[];
31
+ export declare const BlueprintZod: z.ZodObject<{
32
+ name: z.ZodString;
33
+ description: z.ZodString;
34
+ definition: z.ZodObject<{
35
+ tables: z.ZodArray<z.ZodObject<{
36
+ table_name: z.ZodOptional<z.ZodString>;
37
+ fields: z.ZodOptional<z.ZodArray<z.ZodObject<{
38
+ name: z.ZodString;
39
+ }, z.core.$loose>>>;
40
+ }, z.core.$loose>>;
41
+ }, z.core.$loose>;
42
+ categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
43
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
44
+ }, z.core.$strict>;
45
+ /** A field as a caller writes it: its type as a name ("text", "text[]") or a type object, its default as SQL text, a constant, or a default object. */
46
+ export type FieldBlueprint = Omit<BlueprintField, 'type' | 'default'> & {
47
+ type: string | FieldType;
48
+ default?: string | number | boolean | null | FieldDefault;
49
+ };
50
+ /** A table as a caller writes it. */
51
+ export type TableBlueprint = Omit<BlueprintTable, 'fields'> & {
52
+ fields?: FieldBlueprint[];
53
+ };
54
+ /** The input of provision_blueprint, with the definition as a caller writes it. */
55
+ export type Blueprint = {
56
+ name: string;
57
+ description: string;
58
+ definition: Omit<BlueprintDefinition, 'tables'> & {
59
+ tables: TableBlueprint[];
60
+ };
61
+ categories?: string[];
62
+ tags?: string[];
63
+ };
64
+ /**
65
+ * What is wrong with a blueprint the backend would receive, by the registry's blueprint JSON Schema: one sentence per
66
+ * place, none when it fits. The backend checks it again with its own rules.
67
+ */
68
+ export declare function blueprintProblems(definition: unknown): string[];
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ // The blueprint as provision_blueprint takes it, and the one rule shape every access tool takes. The parameter schemas
3
+ // stay small: they name the keys, and the registry's blueprint JSON Schema checks a whole definition and each rule
4
+ // inside the tool, the way the backend reads them.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BlueprintZod = exports.AccessPolicyZod = exports.RULE_KEY_HINTS = exports.AuthzTypeZod = void 0;
7
+ exports.ruleShapeProblems = ruleShapeProblems;
8
+ exports.blueprintProblems = blueprintProblems;
9
+ const harness_1 = require("@agentic-kit/harness");
10
+ const node_type_registry_1 = require("node-type-registry");
11
+ const zod_1 = require("zod");
12
+ const policies_1 = require("../access/policies");
13
+ const rule_check_1 = require("../access/rule-check");
14
+ const POLICY_TYPES = node_type_registry_1.policyNodeTypes.map((node) => node.name);
15
+ /** The policy types a rule takes: the registry's Authz nodes that are policies. */
16
+ exports.AuthzTypeZod = zod_1.z
17
+ .enum(POLICY_TYPES)
18
+ .describe('A policy type: an Authz node of the registry (node-type-registry); its data takes the parameters of that node');
19
+ /** What a rule object says about a key of another rule shape, or one the tools do not support. */
20
+ exports.RULE_KEY_HINTS = {
21
+ role: 'is not a key of a rule: the role is "policy_role".',
22
+ restrictive: 'is not a key of a rule: a restrictive rule has "permissive": false.',
23
+ policy_type: 'is not a key of a rule: the type is "$type".',
24
+ operations: 'is not a key of a rule: give "privileges" (select, insert, update, delete).',
25
+ with_check: 'is not supported in a rule you write: the tools cannot give an update rule its own check of the changed row.',
26
+ };
27
+ /**
28
+ * One access rule, in the registry's blueprint shape (`BlueprintPolicy`). The tool checks it against that shape
29
+ * (`ruleShapeProblems`) and its data against its policy type.
30
+ */
31
+ exports.AccessPolicyZod = (0, harness_1.looseObject)({
32
+ $type: zod_1.z.string().describe('The policy type: an Authz node, for example "AuthzEntityMembership"'),
33
+ privileges: zod_1.z.array(zod_1.z.string()).optional().describe('The privileges the rule covers: select, insert, update or delete'),
34
+ permissive: zod_1.z.boolean().optional().describe('False for a restrictive rule, a limit every row must also pass. Default true.'),
35
+ policy_role: (0, harness_1.textParam)().optional().describe('Default "authenticated"'),
36
+ policy_name: (0, harness_1.textParam)().optional().describe('The name of the rule, when two rules of one policy type, role and privilege are on one table'),
37
+ data: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional().describe("The node's parameters, as its parameter schema names them"),
38
+ }).describe('One rule: {$type, privileges, permissive, policy_role, policy_name, data}');
39
+ // A branch of a oneOf or anyOf fails on its own whenever the whole fails; the whole is reported instead. `if` repeats the
40
+ // errors of its `then`.
41
+ const reported = (error) => !/\/(oneOf|anyOf)\/\d+\//.test(error.schemaPath) && error.keyword !== 'if';
42
+ const RULE_KEYS = ['$type', 'privileges', 'permissive', 'policy_role', 'policy_name', 'data'];
43
+ /**
44
+ * What is wrong with one rule's shape, by the registry's `BlueprintPolicy`: its keys, its policy type and its
45
+ * privileges, which a rule here always gives (its data is its policy type's to check). `with_check` is refused unless
46
+ * `withCheck` allows it.
47
+ */
48
+ function ruleShapeProblems(rule, { withCheck = false } = {}) {
49
+ if (typeof rule !== 'object' || rule === null || Array.isArray(rule))
50
+ return [{ path: '', code: 'type', message: 'A rule must be an object.' }];
51
+ const without = (value, key) => Object.fromEntries(Object.entries(value).filter(([name]) => name !== key));
52
+ const envelope = without(rule, 'data');
53
+ const unchecked = without(envelope, 'with_check');
54
+ const problems = [];
55
+ if (envelope.privileges === undefined)
56
+ problems.push({ path: 'privileges', code: 'privileges', message: '"privileges" is missing: give the privileges the rule covers, from select, insert, update and delete.' });
57
+ if (!withCheck && envelope.with_check !== undefined)
58
+ problems.push({ path: 'with_check', code: 'not-supported', message: `"with_check" ${exports.RULE_KEY_HINTS.with_check}` });
59
+ const validate = (0, rule_check_1.blueprintValidator)('BlueprintPolicy');
60
+ if (!validate((0, rule_check_1.jsonCopy)(withCheck ? envelope : unchecked))) {
61
+ for (const error of validate.errors.filter(reported)) {
62
+ const path = error.instancePath.split('/').slice(1).join('.');
63
+ if (error.keyword === 'additionalProperties') {
64
+ const key = String(error.params.additionalProperty);
65
+ const meant = (0, harness_1.nearestName)(key, RULE_KEYS);
66
+ problems.push({
67
+ path: key,
68
+ code: 'unknown-key',
69
+ message: `"${key}" ${Object.hasOwn(exports.RULE_KEY_HINTS, key) ? exports.RULE_KEY_HINTS[key] : meant ? `is not a key of a rule: use "${meant}".` : `is not a key of a rule: its keys are ${(0, harness_1.listed)((0, policies_1.quoted)(RULE_KEYS))}.`}`,
70
+ ...(meant ? { meant } : {}),
71
+ });
72
+ }
73
+ else if (path === '$type' || (error.keyword === 'required' && error.params.missingProperty === '$type')) {
74
+ const meant = typeof envelope.$type === 'string' ? (0, harness_1.nearestName)(envelope.$type, POLICY_TYPES) : undefined;
75
+ problems.push({
76
+ path: '$type',
77
+ code: meant ? 'mistyped-node' : 'not-a-node',
78
+ message: `"$type" ${envelope.$type === undefined ? 'is missing' : `is ${JSON.stringify(envelope.$type)}, which is not a policy type`}${meant ? `; did you mean "${meant}"?` : '.'} Give the policy type of the rule.`,
79
+ ...(meant ? { meant } : {}),
80
+ });
81
+ }
82
+ else if (path.startsWith('privileges')) {
83
+ problems.push({ path, code: 'privileges', message: `"privileges" must list one or more of select, insert, update and delete.` });
84
+ }
85
+ else {
86
+ problems.push({ path, code: error.keyword, message: `"${path}" ${error.message}.` });
87
+ }
88
+ }
89
+ }
90
+ return problems.filter((problem, i) => problems.findIndex((other) => other.path === problem.path) === i);
91
+ }
92
+ const DefinitionZod = zod_1.z
93
+ .looseObject({
94
+ tables: zod_1.z
95
+ // The names a plan shows are plain text; the rest of a table is the schema's to check.
96
+ .array(zod_1.z.looseObject({ table_name: (0, harness_1.identifierParam)().optional(), fields: zod_1.z.array(zod_1.z.looseObject({ name: (0, harness_1.identifierParam)() })).optional() }))
97
+ .describe('The tables to create. A table takes table_name, and optionally schema_name, fields, nodes, policies, grants, use_rls, indexes, ' +
98
+ 'unique_constraints, check_constraints and full_text_searches. A field is {name, type, is_required, default}: its type a name ' +
99
+ '("text", "text[]") or a type object, its default SQL text ("now()"), a number, true or false, or a default object. A rule is ' +
100
+ '{$type, privileges, permissive, policy_role, data}. Every table gets id, created_at and updated_at, and the columns its rules need.'),
101
+ })
102
+ .describe('The blueprint: tables, and optionally relations ({$type: "RelationBelongsTo", source_table, target_table, field_name, ...; ' +
103
+ 'source_schema and target_schema name the schema of each end}), indexes, unique_constraints, check_constraints, full_text_searches, ' +
104
+ 'entity_types and the other keys of a blueprint. The whole blueprint is checked against the blueprint JSON Schema of node-type-registry ' +
105
+ 'before anything changes.');
106
+ exports.BlueprintZod = (0, harness_1.strictObject)('the input', {
107
+ name: (0, harness_1.textParam)().describe('Blueprint name in snake_case'),
108
+ description: zod_1.z.string().describe('Brief description of what this schema is for'),
109
+ definition: DefinitionZod,
110
+ categories: zod_1.z.array((0, harness_1.textParam)()).optional().describe('Template categories if saved as template, e.g. ["e-commerce", "healthcare"]'),
111
+ tags: zod_1.z.array((0, harness_1.textParam)()).optional().describe('Freeform search tags if saved as template, e.g. ["products", "orders"]'),
112
+ });
113
+ const at = (instancePath) => ['definition', ...instancePath.split('/').slice(1)].join('.');
114
+ /**
115
+ * What is wrong with a blueprint the backend would receive, by the registry's blueprint JSON Schema: one sentence per
116
+ * place, none when it fits. The backend checks it again with its own rules.
117
+ */
118
+ function blueprintProblems(definition) {
119
+ const validate = (0, rule_check_1.blueprintValidator)('BlueprintDefinition');
120
+ if (validate((0, rule_check_1.jsonCopy)(definition)))
121
+ return [];
122
+ const sentences = validate.errors.filter(reported).map((error) => {
123
+ const place = at(error.instancePath);
124
+ switch (error.keyword) {
125
+ case 'required':
126
+ return `${place} needs "${error.params.missingProperty}".`;
127
+ case 'additionalProperties':
128
+ return `${place} has no key "${error.params.additionalProperty}".`;
129
+ case 'enum':
130
+ return `${place} must be one of ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(', ')}.`;
131
+ case 'anyOf':
132
+ case 'oneOf':
133
+ return `${place} is not in a shape it takes.`;
134
+ default:
135
+ return `${place} ${error.message}.`;
136
+ }
137
+ });
138
+ return [...new Set(sentences)];
139
+ }
@@ -0,0 +1,4 @@
1
+ import type { FieldDefault, FieldType } from 'node-type-registry';
2
+ export declare function fieldTypeToTypeName(t: unknown): string;
3
+ export declare function toFieldType(typeName: string): FieldType;
4
+ export declare function toFieldDefault(def?: string | number | boolean | null): FieldDefault | undefined;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fieldTypeToTypeName = fieldTypeToTypeName;
4
+ exports.toFieldType = toFieldType;
5
+ exports.toFieldDefault = toFieldDefault;
6
+ const SQL_KEYWORDS = new Set([
7
+ 'CURRENT_TIMESTAMP',
8
+ 'CURRENT_DATE',
9
+ 'CURRENT_TIME',
10
+ 'LOCALTIME',
11
+ 'LOCALTIMESTAMP',
12
+ 'CURRENT_ROLE',
13
+ 'CURRENT_USER',
14
+ 'SESSION_USER',
15
+ 'USER',
16
+ 'CURRENT_CATALOG',
17
+ 'CURRENT_SCHEMA',
18
+ ]);
19
+ function fieldTypeToTypeName(t) {
20
+ if (t == null)
21
+ return '';
22
+ if (typeof t === 'string')
23
+ return t;
24
+ if (typeof t === 'object') {
25
+ const obj = t;
26
+ if (typeof obj.name === 'string') {
27
+ const dims = typeof obj.array_dimensions === 'number' && obj.array_dimensions > 0
28
+ ? obj.array_dimensions
29
+ : 0;
30
+ return obj.name + '[]'.repeat(dims);
31
+ }
32
+ }
33
+ return '';
34
+ }
35
+ function toFieldType(typeName) {
36
+ const raw = (typeName ?? '').trim();
37
+ let base = raw;
38
+ let dims = 0;
39
+ while (base.endsWith('[]')) {
40
+ base = base.slice(0, -2);
41
+ dims += 1;
42
+ }
43
+ base = base.trim();
44
+ const result = { name: base };
45
+ if (dims > 0)
46
+ result.array_dimensions = dims;
47
+ return result;
48
+ }
49
+ function parseScalarLiteral(token) {
50
+ const t = token.trim();
51
+ if (t === '')
52
+ return '';
53
+ if (t === 'true')
54
+ return true;
55
+ if (t === 'false')
56
+ return false;
57
+ if (t.toLowerCase() === 'null')
58
+ return null;
59
+ if (/^-?\d+(\.\d+)?$/.test(t))
60
+ return Number(t);
61
+ if ((t.startsWith("'") && t.endsWith("'")) || (t.startsWith('"') && t.endsWith('"'))) {
62
+ return t.slice(1, -1);
63
+ }
64
+ return t;
65
+ }
66
+ function toFieldDefault(def) {
67
+ if (def === undefined || def === null)
68
+ return undefined;
69
+ // A number or a boolean is a constant, sent as the value it is.
70
+ if (typeof def === 'number' || typeof def === 'boolean')
71
+ return { value: def };
72
+ const raw = String(def).trim();
73
+ if (raw === '')
74
+ return undefined;
75
+ if (SQL_KEYWORDS.has(raw.toUpperCase())) {
76
+ return { sql_keyword: raw.toUpperCase() };
77
+ }
78
+ const fnMatch = raw.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([\s\S]*)\)$/);
79
+ if (fnMatch) {
80
+ const fnName = fnMatch[1];
81
+ const argsRaw = fnMatch[2].trim();
82
+ const result = { function: fnName };
83
+ if (argsRaw !== '') {
84
+ const args = argsRaw.split(',').map((a) => parseScalarLiteral(a));
85
+ if (args.length > 0)
86
+ result.args = args;
87
+ }
88
+ return result;
89
+ }
90
+ if (raw === 'true')
91
+ return { value: true };
92
+ if (raw === 'false')
93
+ return { value: false };
94
+ if (/^-?\d+(\.\d+)?$/.test(raw))
95
+ return { value: Number(raw) };
96
+ if ((raw.startsWith("'") && raw.endsWith("'")) || (raw.startsWith('"') && raw.endsWith('"'))) {
97
+ return { value: raw.slice(1, -1) };
98
+ }
99
+ return { value: raw };
100
+ }
@@ -0,0 +1 @@
1
+ export declare function isInternalPolicy(policyType: string | null | undefined): boolean;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isInternalPolicy = isInternalPolicy;
4
+ // Policies the platform can attach by itself, such as the read-only block a team
5
+ // table gets. Every report of a table's policies shows them; only the
6
+ // classification of a table's access mode leaves them out.
7
+ const INTERNAL_POLICY_TYPES = new Set(['AuthzNotReadOnly']);
8
+ function isInternalPolicy(policyType) {
9
+ return !policyType || INTERNAL_POLICY_TYPES.has(policyType);
10
+ }
@@ -24,16 +24,16 @@ export type WaitForConstructionOptions = {
24
24
  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
25
25
  };
26
26
  /**
27
- * Why a construction failed, from its `error` column. That column came with
28
- * the queued build, and the modules SDK predates it, so it is read on its own
29
- * after a failure: the status reads stay valid on a backend without it. The
30
- * SDK's select type doesn't list `error`, but the ORM writes each select key
31
- * as the field name.
27
+ * Why a construction failed, in one sentence with its id, from its `error`
28
+ * column. That column came with the queued build, and the modules SDK predates
29
+ * it, so it is read on its own after a failure: the status reads stay valid on
30
+ * a backend without it. The SDK's select type doesn't list `error`, but the
31
+ * ORM writes each select key as the field name.
32
32
  */
33
33
  export declare function readConstructionFailure(modules: ModulesClient, constructionId: string): Promise<string>;
34
34
  /**
35
35
  * Wait for a construction to finish. Resolves with its table map once it is
36
- * constructed, and throws with the backend's coded error once it failed, or
36
+ * constructed, and throws with the words of its error once it failed, or
37
37
  * when the deadline passes, the signal aborts, or its status can't be read.
38
38
  */
39
39
  export declare function waitForConstruction(modules: ModulesClient, constructionId: string, options?: WaitForConstructionOptions): Promise<ConstructionTableMap>;
@@ -42,6 +42,10 @@ export declare function waitForConstruction(modules: ModulesClient, construction
42
42
  * on. The construction carries on without the caller, so constructing again
43
43
  * would queue the same tables a second time.
44
44
  */
45
+ /** constructBlueprint answered without an error but without the construction it queued. */
46
+ export declare class BuildNotQueuedError extends Error {
47
+ constructor();
48
+ }
45
49
  export declare class BlueprintBuildError extends Error {
46
50
  readonly constructionId: string;
47
51
  constructor(message: string, constructionId: string);
@@ -1,16 +1,17 @@
1
1
  "use strict";
2
2
  // Building a blueprint: constructBlueprint enqueues a `blueprint:construct`
3
- // job and returns the construction id at once (constructive-db#4156). A worker
3
+ // job and returns the construction id at once. A worker
4
4
  // builds one blueprint at a time, each under a 120 s statement timeout, and
5
5
  // moves the construction row pending → constructing → constructed | failed,
6
6
  // with a failed build's coded error in `error`. A backend from before that
7
7
  // builds inside the mutation and raises the build's error from it, so the
8
8
  // first read already says constructed, and the same wait serves both.
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.BlueprintBuildError = exports.MAX_CONSECUTIVE_READ_FAILURES = exports.CONSTRUCTION_POLL_MS = exports.CONSTRUCTION_DEADLINE_MS = void 0;
10
+ exports.BlueprintBuildError = exports.BuildNotQueuedError = exports.MAX_CONSECUTIVE_READ_FAILURES = exports.CONSTRUCTION_POLL_MS = exports.CONSTRUCTION_DEADLINE_MS = void 0;
11
11
  exports.readConstructionFailure = readConstructionFailure;
12
12
  exports.waitForConstruction = waitForConstruction;
13
13
  exports.buildBlueprint = buildBlueprint;
14
+ const graphql_http_1 = require("./graphql-http");
14
15
  const request_database_1 = require("./provision-database/request-database");
15
16
  /**
16
17
  * How long a tool waits for its build: the build's own 120 s statement
@@ -28,7 +29,6 @@ exports.CONSTRUCTION_POLL_MS = 2_000;
28
29
  */
29
30
  exports.MAX_CONSECUTIVE_READ_FAILURES = 3;
30
31
  const MAY_STILL_FINISH = 'The build may still finish on the backend: read the schema before you call again.';
31
- const errorText = (err) => (err instanceof Error ? err.message : String(err));
32
32
  function stopped() {
33
33
  return new Error(`Stopped waiting for the blueprint build. ${MAY_STILL_FINISH}`);
34
34
  }
@@ -53,24 +53,26 @@ function tableMapOf(raw) {
53
53
  return Object.fromEntries(Object.entries(raw).filter((entry) => typeof entry[1] === 'string'));
54
54
  }
55
55
  /**
56
- * A failed construction's coded error on one line: `CODE: message` for a
57
- * database error, `CODE {context}` for one raised through errors.raise_error.
56
+ * A failed construction's error in words. The backend stores the `{ code, context, class }` an errors.raise_error
57
+ * carried, or a database error's own code and text. Only a code it marked public is for the person, with its context;
58
+ * anything else is named by the construction id alone, which the backend operator can look up.
58
59
  */
59
- function describeConstructionError(error) {
60
+ function constructionFailureWords(error, constructionId) {
61
+ const id = `Construction id: ${constructionId}.`;
60
62
  if (!error || typeof error !== 'object')
61
- return null;
62
- const { code, message, context } = error;
63
- const head = [code, message].filter((part) => typeof part === 'string' && part).join(': ');
63
+ return `The blueprint build failed, and the backend gave no reason. ${id}`;
64
+ const { code, context, class: kind } = error;
65
+ if (kind !== 'public' || typeof code !== 'string' || !code)
66
+ return `The blueprint build failed with an error the backend does not show. ${id}`;
64
67
  const hasContext = Boolean(context && typeof context === 'object' && Object.keys(context).length);
65
- const tail = hasContext ? JSON.stringify(context) : '';
66
- return [head, tail].filter(Boolean).join(' ') || null;
68
+ return `The blueprint build failed with the code ${code}${hasContext ? ` ${JSON.stringify(context)}` : ''}. ${id}`;
67
69
  }
68
70
  /**
69
- * Why a construction failed, from its `error` column. That column came with
70
- * the queued build, and the modules SDK predates it, so it is read on its own
71
- * after a failure: the status reads stay valid on a backend without it. The
72
- * SDK's select type doesn't list `error`, but the ORM writes each select key
73
- * as the field name.
71
+ * Why a construction failed, in one sentence with its id, from its `error`
72
+ * column. That column came with the queued build, and the modules SDK predates
73
+ * it, so it is read on its own after a failure: the status reads stay valid on
74
+ * a backend without it. The SDK's select type doesn't list `error`, but the
75
+ * ORM writes each select key as the field name.
74
76
  */
75
77
  async function readConstructionFailure(modules, constructionId) {
76
78
  try {
@@ -78,15 +80,15 @@ async function readConstructionFailure(modules, constructionId) {
78
80
  .findOne({ id: constructionId, select: { error: true } })
79
81
  .unwrap();
80
82
  const row = result.blueprintConstruction;
81
- return describeConstructionError(row?.error) ?? 'the backend gave no reason';
83
+ return constructionFailureWords(row?.error, constructionId);
82
84
  }
83
85
  catch (err) {
84
- return `the backend gave no reason (reading it failed: ${errorText(err)})`;
86
+ return `The blueprint build failed, and its reason could not be read (${(0, graphql_http_1.thrownText)(err)}). Construction id: ${constructionId}.`;
85
87
  }
86
88
  }
87
89
  /**
88
90
  * Wait for a construction to finish. Resolves with its table map once it is
89
- * constructed, and throws with the backend's coded error once it failed, or
91
+ * constructed, and throws with the words of its error once it failed, or
90
92
  * when the deadline passes, the signal aborts, or its status can't be read.
91
93
  */
92
94
  async function waitForConstruction(modules, constructionId, options = {}) {
@@ -108,16 +110,15 @@ async function waitForConstruction(modules, constructionId, options = {}) {
108
110
  catch (err) {
109
111
  // A GraphQL error is the backend's answer and won't change on a reread.
110
112
  if (!(0, request_database_1.isTransientProvisionError)(err) || ++readFailures >= exports.MAX_CONSECUTIVE_READ_FAILURES) {
111
- throw new Error(`Could not read the blueprint build's status: ${errorText(err)}. ${MAY_STILL_FINISH}`);
113
+ throw new Error(`Could not read the blueprint build's status: ${(0, graphql_http_1.thrownText)(err)}. ${MAY_STILL_FINISH}`);
112
114
  }
113
115
  }
114
116
  if (row === null)
115
117
  throw new Error(`The backend has no blueprint construction ${constructionId}.`);
116
118
  if (row?.status === 'constructed')
117
119
  return tableMapOf(row.tableMap);
118
- if (row?.status === 'failed') {
119
- throw new Error(`The blueprint build failed: ${await readConstructionFailure(modules, constructionId)}`);
120
- }
120
+ if (row?.status === 'failed')
121
+ throw new Error(await readConstructionFailure(modules, constructionId));
121
122
  status = row?.status ?? status;
122
123
  if (now() >= deadline) {
123
124
  const where = status === 'pending' ? "waiting in the backend's build queue" : 'building';
@@ -131,6 +132,14 @@ async function waitForConstruction(modules, constructionId, options = {}) {
131
132
  * on. The construction carries on without the caller, so constructing again
132
133
  * would queue the same tables a second time.
133
134
  */
135
+ /** constructBlueprint answered without an error but without the construction it queued. */
136
+ class BuildNotQueuedError extends Error {
137
+ constructor() {
138
+ super('constructBlueprint answered with no construction id');
139
+ this.name = 'BuildNotQueuedError';
140
+ }
141
+ }
142
+ exports.BuildNotQueuedError = BuildNotQueuedError;
134
143
  class BlueprintBuildError extends Error {
135
144
  constructionId;
136
145
  constructor(message, constructionId) {
@@ -151,11 +160,11 @@ async function buildBlueprint(modules, input, options = {}) {
151
160
  .unwrap();
152
161
  const constructionId = result.constructBlueprint?.result;
153
162
  if (!constructionId)
154
- throw new Error('constructBlueprint returned no construction id');
163
+ throw new BuildNotQueuedError();
155
164
  try {
156
165
  return { constructionId, tables: await waitForConstruction(modules, constructionId, options) };
157
166
  }
158
167
  catch (err) {
159
- throw new BlueprintBuildError(errorText(err), constructionId);
168
+ throw new BlueprintBuildError((0, graphql_http_1.thrownText)(err), constructionId);
160
169
  }
161
170
  }
package/context.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { PlanAgent, ToolFailure } from '@agentic-kit/harness';
1
2
  import { api, modules } from '@constructive-io/sdk';
2
3
  import { type UnreachableCause } from './db-probe';
3
4
  export type ApiClient = ReturnType<typeof api.createClient>;
@@ -8,6 +9,12 @@ export type ProjectContext = {
8
9
  databaseId: string;
9
10
  schemaId: string;
10
11
  ownerId: string | undefined;
12
+ /** The signed-in account every control-plane request is made as, and its email when the host gives it. */
13
+ accountUserId: string;
14
+ accountEmail?: string;
15
+ accountAgent?: PlanAgent;
16
+ /** The host's api endpoint: every control-plane request goes there, whatever .env pins. */
17
+ controlApiEndpoint: string;
11
18
  apiEndpoint: string;
12
19
  modulesEndpoint: string;
13
20
  databaseName: string;
@@ -22,6 +29,12 @@ export type ResolveResult = {
22
29
  code?: ProjectContextFailureCode;
23
30
  /** Why the backend couldn't answer, with code 'backend-unreachable'. */
24
31
  cause?: UnreachableCause;
32
+ /**
33
+ * Why there is no context, for a tool to report as is; present exactly when
34
+ * `context` is null. `reason` is its text. Its code is `signed-out` where
35
+ * `code` says a missing or rejected account credential less directly.
36
+ */
37
+ failure?: ToolFailure;
25
38
  };
26
39
  export declare const CONTEXT_ENV_KEYS: readonly ["ACCESS_TOKEN", "DATABASE_ID", "API_ENDPOINT", "MODULES_ENDPOINT", "DATABASE_NAME", "OWNER_ID"];
27
40
  export type ContextEnvKey = (typeof CONTEXT_ENV_KEYS)[number];
@@ -55,10 +68,12 @@ export type ResolveOptions = {
55
68
  * Job, an explicit record for anything else.
56
69
  */
57
70
  export declare function resolveProjectContext(input: string | ContextSource, options?: ResolveOptions): Promise<ResolveResult>;
71
+ /** A token, or the `reason` and `failure` that say why there is none. */
58
72
  export type DataTokenResult = {
59
73
  token?: string;
60
74
  userId?: string;
61
75
  reason?: string;
76
+ failure?: ToolFailure;
62
77
  };
63
78
  export declare function resolveDataToken(context: ProjectContext): Promise<DataTokenResult>;
64
79
  export declare function deriveSubdomainEndpoint(baseEndpoint: string, firstLabel: string): string;