@agentic-kit/db-tools 0.12.47 → 0.13.1

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