@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
package/failure.js ADDED
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROWS_REFUSED_HINT = exports.explainAccessCall = exports.MISSING_OWNER = exports.NO_NEW_ROW = exports.NEW_DATABASE = exports.DESCRIBE_SCHEMA = exports.suggest = exports.ToolFailureError = exports.failureText = void 0;
4
+ exports.failedResult = failedResult;
5
+ exports.noBackendFailure = noBackendFailure;
6
+ exports.noRowsChanged = noRowsChanged;
7
+ exports.noRowCreated = noRowCreated;
8
+ exports.invalidBinding = invalidBinding;
9
+ exports.failureFromErrors = failureFromErrors;
10
+ exports.failureFromError = failureFromError;
11
+ const harness_1 = require("@agentic-kit/harness");
12
+ Object.defineProperty(exports, "failureText", { enumerable: true, get: function () { return harness_1.failureText; } });
13
+ const blueprint_construction_1 = require("./blueprint-construction");
14
+ const graphql_http_1 = require("./graphql-http");
15
+ /** A failure a helper raises for the tool that called it to report as is. */
16
+ class ToolFailureError extends Error {
17
+ failure;
18
+ constructor(failure) {
19
+ super(failure.message);
20
+ this.name = 'ToolFailureError';
21
+ this.failure = failure;
22
+ }
23
+ }
24
+ exports.ToolFailureError = ToolFailureError;
25
+ /** A failed call, with the tool's own `details`. */
26
+ function failedResult(failure, details) {
27
+ return { content: [{ type: 'text', text: (0, harness_1.failureText)(failure) }], details, failure };
28
+ }
29
+ function noBackendFailure(hint) {
30
+ return {
31
+ code: 'no-backend',
32
+ message: 'No Constructive backend is configured.',
33
+ hint: hint ?? 'Choose a backend in the app, then retry.',
34
+ };
35
+ }
36
+ /** A call to suggest; `choose` names the inputs the caller must still choose, which `why` explains. */
37
+ const suggest = (tool, input, why, choose) => ({
38
+ tool,
39
+ input,
40
+ why,
41
+ ...(choose?.length ? { choose } : {}),
42
+ });
43
+ exports.suggest = suggest;
44
+ exports.DESCRIBE_SCHEMA = (0, exports.suggest)('describe_schema', {}, 'See the tables and fields that exist');
45
+ /** No database is bound yet: the call that makes one, with its name left to choose. */
46
+ exports.NEW_DATABASE = (0, exports.suggest)('provision_database', {}, 'Create a database for this directory and bind it', ['database_name']);
47
+ /**
48
+ * An update or delete the backend answered without an error but with no row in
49
+ * its payload: on the latest server that is how row-level security answers for
50
+ * a row this account cannot see, and how any server answers for a row that is
51
+ * gone. `check` is the call that lists what exists.
52
+ */
53
+ function noRowsChanged(action, check) {
54
+ return {
55
+ code: 'no-rows-changed',
56
+ message: `${action}: no row was changed, because it does not exist or this account may not change it.`,
57
+ hint: 'Check that it still exists; if it does, this account may not change it.',
58
+ calls: [check],
59
+ };
60
+ }
61
+ /** What a row the backend answered without is, in a row's own record (add_records' failedRows). */
62
+ exports.NO_NEW_ROW = 'The backend answered without the new row, so it may not exist, or this account may not read it.';
63
+ /**
64
+ * A create the backend answered without an error but without the new row:
65
+ * the row may not exist, or a policy lets this account create it but not
66
+ * read it back. `check` is the call that shows whether it exists, when a tool
67
+ * has one.
68
+ */
69
+ function noRowCreated(action, check) {
70
+ return {
71
+ code: 'no-rows-changed',
72
+ message: `${action}: ${exports.NO_NEW_ROW.charAt(0).toLowerCase()}${exports.NO_NEW_ROW.slice(1)}`,
73
+ ...(check ? { hint: 'Check whether it exists before you call again.', calls: [check] } : {}),
74
+ };
75
+ }
76
+ /**
77
+ * A project binding with values that are not of their form (`keys`, in `where`): none of them is used, sent or shown,
78
+ * so the project acts as bound to no database until the person fixes them.
79
+ */
80
+ function invalidBinding(keys, where = '.env') {
81
+ return {
82
+ code: 'missing-credentials',
83
+ message: `The project's database entry is not valid: ${(0, harness_1.listed)(keys.map((key) => `${key} in ${where}`))} ${keys.length === 1 ? 'does' : 'do'} not hold a value ` +
84
+ 'of the form it takes, so the value is not used or shown.',
85
+ hint: 'Fix or remove those lines, then bind the directory to a database again.',
86
+ };
87
+ }
88
+ // provision_database fills a missing OWNER_ID when it keeps a live binding.
89
+ exports.MISSING_OWNER = {
90
+ code: 'missing-credentials',
91
+ message: 'The project binding has no owner: OWNER_ID is missing from .env and the backend reported none.',
92
+ hint: "Bind the directory again under the project's database name to refresh the binding, then retry.",
93
+ calls: [(0, exports.suggest)('provision_database', {}, "Refresh the binding: give the project's database name", ['database_name'])],
94
+ };
95
+ /** The read of a table's rules, for a refusal on its rows. */
96
+ const explainAccessCall = (table) => (0, exports.suggest)('explain_access', { table_name: table }, 'See the rules of the table');
97
+ exports.explainAccessCall = explainAccessCall;
98
+ /** The next step of a refusal on the rows of an app table, in words. */
99
+ exports.ROWS_REFUSED_HINT = "The table's rules or grants refuse this person: read the rules of the table to see who they let in.";
100
+ const FOREIGN_KEY = { code: 'conflict', hint: 'A row it refers to is missing, or other rows still refer to it.' };
101
+ // A change in a read-only request: no rule of the table decides it, so no call that writes helps.
102
+ const READ_ONLY = {
103
+ code: 'read-only',
104
+ message: 'the request was read-only, so nothing changed; a read-only credential is the usual cause.',
105
+ hint: 'Use a credential that may write (for an agent, ask the person to grant one). If this credential may write, the backend answered from a read-only copy: tell the backend operator.',
106
+ retryable: false,
107
+ };
108
+ const UNIQUE_CONFLICT_HINT = 'A value that must be unique is already in another row: change it, or leave that row out.';
109
+ function duplicate(meaning) {
110
+ if (!meaning.taken)
111
+ return { code: 'conflict', hint: UNIQUE_CONFLICT_HINT };
112
+ const { check } = meaning;
113
+ return {
114
+ code: 'name-taken',
115
+ message: meaning.taken,
116
+ hint: check ? 'Choose another name; check the names that exist.' : 'Choose another name.',
117
+ ...(check ? { calls: [check] } : {}),
118
+ };
119
+ }
120
+ // The sentence of each code the backend sends when it cannot build a policy from a rule's data; the message it sends
121
+ // beside the code is the bare code.
122
+ const POLICY_CODES = {
123
+ MEMBERSHIP_TYPE_MUST_BE_INT: "a rule's membership_type must be a whole number: 2 for organizations, 3 and up for other kinds of team; to name a kind by its name, use entity_type.",
124
+ MEMBERSHIP_TYPE_SCOPE_NOT_FOUND: "a rule's membership_type names a kind of membership this database does not have.",
125
+ CAPABILITY_NOT_FOUND: 'a rule names a capability this database does not have.',
126
+ BAD_RLS_EXPRESSION: 'the backend could not build a rule from its data: a parameter is missing, is not one its type takes, or has a wrong value.',
127
+ BAD_EXPRESSION: "a rule's data is not in the shape its type takes.",
128
+ MISSING_REQUIRED_FIELD: 'a rule leaves out a parameter its policy type requires.',
129
+ UNKNOWN_POLICY_TYPE: 'a rule names a policy type the backend does not have.',
130
+ SECURITY: 'a rule names a table of another database.',
131
+ BAD_PRIVILEGE_FOR_POLICY: 'a rule names a privilege a policy cannot take: use select, insert, update or delete.',
132
+ WITH_CHECK_NOT_ALLOWED: 'a rule checks new rows for a privilege that makes none (select or delete).',
133
+ };
134
+ // The one value the backend sends beside a policy code, labelled for the message.
135
+ function backendDetail(context) {
136
+ const field = typeof context?.field === 'string' ? `${context.field}${typeof context.node_type === 'string' ? ` of ${context.node_type}` : ''}` : undefined;
137
+ const value = context?.detail ?? context?.names ?? context?.policy_type ?? context?.privilege ?? field;
138
+ const text = Array.isArray(value) ? value.join(', ') : typeof value === 'string' ? value : '';
139
+ return text ? ` Backend detail: ${text}.` : '';
140
+ }
141
+ // One call that describes each policy type the call sends, or one that lists them all.
142
+ const describePolicyCalls = (types) => types?.length
143
+ ? [...new Set(types)].map((type) => (0, exports.suggest)('describe_policy_type', { type }, `See the parameters ${type} takes`))
144
+ : [(0, exports.suggest)('describe_policy_type', {}, 'See the policy types and what each one needs')];
145
+ function policyRefusal(code, meaning, context) {
146
+ const sentence = POLICY_CODES[code];
147
+ if (!sentence)
148
+ return undefined;
149
+ return { code: 'invalid-input', message: `${sentence}${backendDetail(context)}`, hint: 'Check the rule against the parameters its type takes.', calls: describePolicyCalls(meaning.policyTypes) };
150
+ }
151
+ // The public codes the backend's blueprint check raises, each with the place and the problem in its detail.
152
+ const BLUEPRINT_CODES = new Set([
153
+ 'VALIDATE_BLUEPRINT_DEPENDENCY_NOT_MET',
154
+ 'VALIDATE_BLUEPRINT_EMPTY_NOT_ALLOWED',
155
+ 'VALIDATE_BLUEPRINT_EXPECTED_ARRAY',
156
+ 'VALIDATE_BLUEPRINT_EXPECTED_BOOLEAN',
157
+ 'VALIDATE_BLUEPRINT_EXPECTED_NUMBER',
158
+ 'VALIDATE_BLUEPRINT_EXPECTED_OBJECT',
159
+ 'VALIDATE_BLUEPRINT_EXPECTED_STRING',
160
+ 'VALIDATE_BLUEPRINT_EXPECTED_STRING_OR_OBJECT',
161
+ 'VALIDATE_BLUEPRINT_INVALID',
162
+ 'VALIDATE_BLUEPRINT_INVALID_ENUM',
163
+ 'VALIDATE_BLUEPRINT_INVALID_FORMAT',
164
+ 'VALIDATE_BLUEPRINT_MISSING_REQUIRED_KEY',
165
+ 'VALIDATE_BLUEPRINT_RESERVED_VALUE',
166
+ 'VALIDATE_BLUEPRINT_VALUE_TOO_LONG',
167
+ ]);
168
+ function blueprintRefusal(context) {
169
+ const detail = typeof context?.detail === 'string' ? context.detail : undefined;
170
+ return {
171
+ code: 'invalid-input',
172
+ message: `the backend refused the blueprint${detail ? `: ${detail.replace(/\.?$/, '.')}` : '.'}`,
173
+ hint: 'Fix the part of the blueprint the message names, then send it again; nothing was created.',
174
+ };
175
+ }
176
+ // An internal error while the backend builds the rules: its text is not for the person, and can hold the whole rule tree.
177
+ function policyInternal(meaning, errorId) {
178
+ return {
179
+ code: 'failed',
180
+ message: `the backend failed with an internal error while it built the rules from their data.${errorId ? ` Error id: ${errorId}.` : ''}`,
181
+ hint: 'Most often the data of a rule does not fit its type or the table: check it against the parameters its type takes. If the data is right, give the error id to the backend operator.',
182
+ calls: describePolicyCalls(meaning.policyTypes),
183
+ };
184
+ }
185
+ // The numbers of a request-protection error, as its context names them: " (cost 1010100, limit 1000000)".
186
+ function measured(context, keys) {
187
+ const parts = keys.filter((key) => typeof context?.[key] === 'number').map((key) => `${key} ${context[key]}`);
188
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
189
+ }
190
+ /** The meaning of a public code from the server's registry (packages/errors/src/registry.ts). */
191
+ function byCode(code, meaning, context) {
192
+ if ((0, graphql_http_1.isSignedOutCode)(code))
193
+ return { code: 'signed-out', hint: 'Sign in again, then retry.' };
194
+ switch (code) {
195
+ case 'NETWORK':
196
+ return { code: 'backend-unreachable', hint: 'Check the backend is running, then retry.', retryable: true };
197
+ case 'ACCESS_SUSPENDED':
198
+ return { code: 'database-unavailable' };
199
+ case 'FORBIDDEN':
200
+ return { code: 'permission-denied', ...(meaning.rows ? { hint: exports.ROWS_REFUSED_HINT } : {}) };
201
+ case 'READ_ONLY_TRANSACTION':
202
+ return READ_ONLY;
203
+ case 'RATE_LIMITED':
204
+ case 'CONCURRENCY_LIMIT_REACHED':
205
+ return rateLimited(undefined);
206
+ case 'NONEXISTENT_TYPE':
207
+ return unknownType(context);
208
+ case 'STEP_UP_REQUIRED':
209
+ return { code: 'step-up-required', message: 'this change needs a recent sign-in.', hint: 'Sign in again, then retry.' };
210
+ case 'UNIQUE_VIOLATION':
211
+ return duplicate(meaning);
212
+ case 'EXCLUSION_VIOLATION':
213
+ return { code: 'conflict' };
214
+ case 'FOREIGN_KEY_VIOLATION':
215
+ return FOREIGN_KEY;
216
+ case 'NOT_NULL_VIOLATION':
217
+ return meaning.notNull ? { code: 'conflict', ...meaning.notNull } : { code: 'invalid-input', hint: 'Give a value for every required column.' };
218
+ case 'CHECK_VIOLATION':
219
+ case 'BAD_USER_INPUT':
220
+ case 'VALIDATION_FAILED':
221
+ return { code: 'invalid-input' };
222
+ case 'NOT_FOUND':
223
+ return { code: 'not-found' };
224
+ case 'BILLING_PLAN_REQUIRED':
225
+ return { code: 'plan-required', hint: 'Choose a plan for this account under Billing → Plans in the Constructive dashboard, then retry.' };
226
+ case 'LIMIT_REACHED':
227
+ case 'BILLING_QUOTA_EXCEEDED':
228
+ return { code: 'limit-reached', hint: 'Remove what this account no longer needs, or choose a larger plan under Billing → Plans in the Constructive dashboard, then retry.' };
229
+ // Request protection: the limits the backend resolved for this API.
230
+ case 'QUERY_TOO_COSTLY':
231
+ return {
232
+ code: 'query-too-large',
233
+ message: `the query asks for more rows than this backend allows${measured(context, ['cost', 'limit'])}.`,
234
+ hint: 'Add `first:` to each connection in the query, and ask for fewer nested lists.',
235
+ };
236
+ case 'QUERY_TOO_DEEP':
237
+ return {
238
+ code: 'query-too-large',
239
+ message: `the query nests more levels than this backend allows${measured(context, ['depth', 'limit'])}.`,
240
+ hint: 'Ask for fewer nested levels.',
241
+ };
242
+ case 'PAGE_SIZE_TOO_LARGE':
243
+ return {
244
+ code: 'query-too-large',
245
+ message: `the query asks for more rows in one page than this backend allows${measured(context, ['requested', 'limit'])}.`,
246
+ hint: 'Set `first:` on each connection to the limit or less.',
247
+ };
248
+ case 'REQUEST_TOO_LARGE':
249
+ return {
250
+ code: 'query-too-large',
251
+ message: `the request body is larger than this backend allows${measured(context, ['bytes', 'limit'])}.`,
252
+ hint: 'Send less in one request, for example fewer rows in each call.',
253
+ };
254
+ default:
255
+ return BLUEPRINT_CODES.has(code) ? blueprintRefusal(context) : policyRefusal(code, meaning, context);
256
+ }
257
+ }
258
+ // A request the backend limited: the step is to wait, as long as it asked when it said.
259
+ function rateLimited(seconds) {
260
+ return {
261
+ code: 'rate-limited',
262
+ message: `the backend is limiting how many requests it takes${seconds === undefined ? '' : `, and asks to wait ${seconds} seconds`}.`,
263
+ hint: seconds === undefined ? 'Wait a moment, then call again.' : `Wait ${seconds} seconds, then call again.`,
264
+ retryable: true,
265
+ };
266
+ }
267
+ // The types a field most often takes, and the words people write for them, for the hint of an unknown type.
268
+ const TYPE_WORDS = {
269
+ text: 'text', string: 'text', varchar: 'text', citext: 'citext', integer: 'integer', int: 'integer', bigint: 'bigint', smallint: 'smallint',
270
+ numeric: 'numeric', decimal: 'numeric', float: 'numeric', number: 'numeric', boolean: 'boolean', bool: 'boolean', date: 'date', time: 'time',
271
+ timestamp: 'timestamp', timestamptz: 'timestamptz', datetime: 'timestamptz', uuid: 'uuid', json: 'json', jsonb: 'jsonb', inet: 'inet',
272
+ email: 'email', url: 'url', image: 'image', upload: 'upload',
273
+ };
274
+ function unknownType(context) {
275
+ const given = context?.type;
276
+ const name = typeof given === 'string' ? given : typeof given?.name === 'string' ? given.name : undefined;
277
+ const nearest = name === undefined ? undefined : (0, harness_1.nearestName)(name.toLowerCase(), Object.keys(TYPE_WORDS));
278
+ return {
279
+ code: 'invalid-input',
280
+ message: `the backend has no type${name === undefined ? ' of that name' : ` "${name}"`}: a field takes a PostgreSQL type, a type this platform adds (email, url, image, upload), or an enum of this database.`,
281
+ hint: nearest ? `Did you mean "${TYPE_WORDS[nearest]}"?` : 'Give one of those, for example text, integer, boolean, timestamptz or uuid.',
282
+ };
283
+ }
284
+ function byStatus(status, meaning) {
285
+ if (status === 429)
286
+ return rateLimited(undefined);
287
+ if (status >= 500) {
288
+ return { code: 'backend-unreachable', hint: 'Check the backend is running, then retry.', retryable: true };
289
+ }
290
+ if (status === 401)
291
+ return { code: 'signed-out', hint: 'Sign in again, then retry.' };
292
+ if (status === 403)
293
+ return { code: 'permission-denied', ...(meaning.rows ? { hint: exports.ROWS_REFUSED_HINT } : {}) };
294
+ return undefined;
295
+ }
296
+ const codeOf = (error) => {
297
+ const code = error?.extensions?.code;
298
+ return typeof code === 'string' ? code : undefined;
299
+ };
300
+ const errorIdOf = (error) => {
301
+ const id = error?.extensions?.errorId;
302
+ return typeof id === 'string' ? id : undefined;
303
+ };
304
+ // An internal error: the server logs it under an error id, and its code and text are not for the person, so neither
305
+ // decides nor is shown.
306
+ const isInternal = (error) => error?.extensions?.class === 'internal' || errorIdOf(error) !== undefined;
307
+ const contextOf = (error) => {
308
+ const context = error?.extensions?.context;
309
+ return context && typeof context === 'object' && !Array.isArray(context) ? context : undefined;
310
+ };
311
+ // A public code decides, with the context the server sent beside it.
312
+ function byPublicCode(error, meaning) {
313
+ if (isInternal(error))
314
+ return undefined;
315
+ const context = contextOf(error);
316
+ const why = byCode(codeOf(error) ?? '', meaning, context);
317
+ return why && context ? { ...why, context } : why;
318
+ }
319
+ function classify(list, meaning) {
320
+ const why = decide(list, meaning, list.find(isInternal));
321
+ // A limited request says how long to wait when the backend sent Retry-After.
322
+ return why?.code === 'rate-limited' ? { ...why, ...rateLimited((0, graphql_http_1.retryAfterOf)(list)) } : why;
323
+ }
324
+ function decide(list, meaning, internal) {
325
+ return (list.map((error) => byPublicCode(error, meaning)).find(Boolean) ??
326
+ (internal && meaning.policyTypes ? policyInternal(meaning, errorIdOf(internal)) : undefined) ??
327
+ list.map((error) => byStatus((0, graphql_http_1.statusOf)(error) ?? 0, meaning)).find(Boolean) ??
328
+ (internal
329
+ ? {
330
+ code: 'failed',
331
+ message: `the backend failed with an internal error.${errorIdOf(internal) ? ` Error id: ${errorIdOf(internal)}.` : ''}`,
332
+ hint: 'Give the error id to the backend operator: it names the logged error.',
333
+ }
334
+ : undefined));
335
+ }
336
+ /**
337
+ * A failed backend answer as a failure. `action` says what was attempted
338
+ * ("Failed to delete table \"posts\""); the meaning of the code follows it, or,
339
+ * for a code with no sentence here, the code itself. The public code decides
340
+ * first (packages/errors/src/registry.ts), then the HTTP status (the one the
341
+ * server put inside the error first), then a masked internal error with its
342
+ * id. A message's text never decides and is never shown.
343
+ */
344
+ function failureFromErrors(errors, action, meaning = {}) {
345
+ const list = errors ?? [];
346
+ const { message, ...why } = classify(list, meaning) ?? { code: 'failed' };
347
+ const errorId = list.map(errorIdOf).find(Boolean);
348
+ // A refusal on rows suggests the read of the table's rules, as data beside the hint.
349
+ const calls = meaning.rows && (why.code === 'permission-denied' || why.code === 'no-rows-changed') ? { calls: [(0, exports.explainAccessCall)(meaning.rows.table)] } : {};
350
+ return { ...why, message: `${action}: ${message ?? `${(0, graphql_http_1.answerText)(list)}.`}`, ...(errorId ? { errorId } : {}), ...calls };
351
+ }
352
+ /**
353
+ * A thrown error as a failure: a `ToolFailureError` keeps its own, an SDK
354
+ * error is classified by its GraphQL errors, anything else is `failed`.
355
+ */
356
+ function failureFromError(err, action, meaning = {}) {
357
+ if (err instanceof ToolFailureError)
358
+ return err.failure;
359
+ if (err instanceof blueprint_construction_1.BuildNotQueuedError)
360
+ return noRowCreated(action, exports.DESCRIBE_SCHEMA);
361
+ const errors = err?.errors;
362
+ if (Array.isArray(errors) && errors.length > 0)
363
+ return failureFromErrors(errors, action, meaning);
364
+ const detail = (0, graphql_http_1.thrownText)(err);
365
+ if (err instanceof blueprint_construction_1.BlueprintBuildError) {
366
+ return {
367
+ code: 'failed',
368
+ message: `${action}: ${detail}`,
369
+ hint: 'The backend queued the build, so check the tables that exist before you call again: another call queues the same tables a second time. ' +
370
+ 'If the message gives no reason, give the construction id to the backend operator.',
371
+ calls: [exports.DESCRIBE_SCHEMA],
372
+ };
373
+ }
374
+ return { code: 'failed', message: `${action}: ${detail}` };
375
+ }
package/gate.d.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  import type { ConstructiveGateDeps } from '@agentic-kit/harness';
2
- import { resolveDataToken as defaultResolveDataToken, resolveProjectContext as defaultResolveProjectContext } from './context';
2
+ import { resolveProjectContext as defaultResolveProjectContext } from './context';
3
3
  import { createTemplatePreviewTables as defaultCreateTemplatePreviewTables } from './tools/templates';
4
- /** The resolvers the deps are built from, so a test can substitute fakes. */
4
+ /** What the deps are built from, so a test can substitute fakes. */
5
5
  export type ConstructiveGateResolvers = {
6
+ /** Default: the check the tool itself runs first (`toolPreconditions`). */
7
+ precondition: ConstructiveGateDeps['precondition'];
6
8
  resolveProjectContext: typeof defaultResolveProjectContext;
7
- resolveDataToken: typeof defaultResolveDataToken;
8
9
  createTemplatePreviewTables: typeof defaultCreateTemplatePreviewTables;
9
10
  };
10
11
  /**
11
12
  * The Constructive gate's host capabilities, answered by this package's own
12
- * project/token/template resolvers.
13
+ * tools: their effects say what is gated, and their first checks say whether
14
+ * a gated call can run at all.
13
15
  *
14
16
  * Every adapter gates the same tools against the same project state, so the
15
17
  * mapping lives here rather than once per harness — an adapter's job is only
package/gate.js CHANGED
@@ -2,10 +2,45 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.constructiveGateDeps = constructiveGateDeps;
4
4
  const context_1 = require("./context");
5
+ const graphql_http_1 = require("./graphql-http");
6
+ const tools_1 = require("./tools");
5
7
  const templates_1 = require("./tools/templates");
8
+ const tools = new Map(tools_1.constructiveDbTools.map((tool) => [tool.name, tool]));
9
+ function invalidInput(error) {
10
+ const issues = error.issues.map((issue) => `${issue.path.join('.') || 'the input'}: ${issue.message.replace(/\.$/, '')}`);
11
+ return { code: 'invalid-input', message: `The input is not valid: ${issues.join('; ')}.` };
12
+ }
13
+ const blocked = (failure) => ({ kind: 'blocked', failure });
14
+ /** The tool's own first check, on the params it would parse, and the target it resolved. */
15
+ async function toolPrecondition(toolName, input, cwd) {
16
+ const tool = tools.get(toolName);
17
+ const check = tools_1.toolPreconditions.get(toolName);
18
+ if (!tool || !check) {
19
+ // Every db tool has a check (tool-contract.test.ts), so this is a tool of another set.
20
+ return blocked({
21
+ code: 'unsupported',
22
+ message: `The Constructive gate does not know the tool "${toolName}", so it cannot say what the call acts on.`,
23
+ });
24
+ }
25
+ const parsed = tool.parameters.safeParse(input);
26
+ if (!parsed.success)
27
+ return blocked(invalidInput(parsed.error));
28
+ try {
29
+ const ready = await check(parsed.data, cwd);
30
+ return ready.kind === 'ok' ? { kind: 'ready', ...ready.value } : blocked(ready.failure);
31
+ }
32
+ catch (err) {
33
+ // A check that cannot finish blocks the call rather than let it through.
34
+ return blocked({
35
+ code: 'failed',
36
+ message: `Could not check whether the call can run: ${(0, graphql_http_1.thrownText)(err)}`,
37
+ });
38
+ }
39
+ }
6
40
  /**
7
41
  * The Constructive gate's host capabilities, answered by this package's own
8
- * project/token/template resolvers.
42
+ * tools: their effects say what is gated, and their first checks say whether
43
+ * a gated call can run at all.
9
44
  *
10
45
  * Every adapter gates the same tools against the same project state, so the
11
46
  * mapping lives here rather than once per harness — an adapter's job is only
@@ -13,22 +48,15 @@ const templates_1 = require("./tools/templates");
13
48
  */
14
49
  function constructiveGateDeps(resolvers = {}) {
15
50
  const resolveProjectContext = resolvers.resolveProjectContext ?? context_1.resolveProjectContext;
16
- const resolveDataToken = resolvers.resolveDataToken ?? context_1.resolveDataToken;
17
51
  const createTemplatePreviewTables = resolvers.createTemplatePreviewTables ?? templates_1.createTemplatePreviewTables;
18
- const context = async (cwd) => (await resolveProjectContext(cwd)).context;
19
52
  return {
20
- isProjectRunnable: async (cwd) => (await context(cwd)) !== null,
21
- hasDataToken: async (cwd) => {
22
- const resolved = await context(cwd);
23
- if (!resolved)
24
- return false;
25
- return Boolean((await resolveDataToken(resolved)).token);
26
- },
53
+ effectOf: (toolName) => tools.get(toolName)?.effect,
54
+ precondition: resolvers.precondition ?? toolPrecondition,
27
55
  resolveTemplatePreview: async (cwd, blueprintName, displayName) => {
28
- const resolved = await context(cwd);
29
- if (!resolved)
56
+ const { context } = await resolveProjectContext(cwd);
57
+ if (!context)
30
58
  return undefined;
31
- const result = await createTemplatePreviewTables(resolved, blueprintName);
59
+ const result = await createTemplatePreviewTables(context, blueprintName);
32
60
  if (result.tables.length === 0)
33
61
  return undefined;
34
62
  return {
package/graphql-http.d.ts CHANGED
@@ -16,6 +16,8 @@ export type PostGraphQLArgs = {
16
16
  headers?: Record<string, string>;
17
17
  query: string;
18
18
  variables?: Record<string, unknown>;
19
+ /** The operation to run, when the document holds more than one. */
20
+ operationName?: string;
19
21
  fetchFn?: typeof fetch;
20
22
  };
21
23
  export declare function postGraphQL<T>(args: PostGraphQLArgs): Promise<HttpGraphQLResponse<T>>;
@@ -24,12 +26,31 @@ export declare function postGraphQL<T>(args: PostGraphQLArgs): Promise<HttpGraph
24
26
  * FetchAdapter, and their failures then carry the status and code.
25
27
  */
26
28
  export declare function statusAdapter(endpoint: string, headers?: Record<string, string>, fetchFn?: typeof fetch): GraphQLAdapter;
27
- export type BackendErrorKind = 'suspended' | 'auth' | 'forbidden' | 'server' | 'network' | 'graphql';
29
+ export type BackendErrorKind = 'suspended' | 'auth' | 'forbidden' | 'rate-limited' | 'server' | 'network' | 'graphql';
30
+ /** Whether the backend limited the request (a 429, or its code): the step is to wait. */
31
+ export declare const isRateLimited: (error: GraphQLError) => boolean;
32
+ /** The seconds the backend asked to wait (its Retry-After), when it said. */
33
+ export declare function retryAfterOf(errors: readonly GraphQLError[]): number | undefined;
28
34
  /**
29
- * What a failed backend answer says, first match wins: the database is
30
- * suspended or gone (`ACCESS_SUSPENDED`), no response, the backend failing
31
- * (5xx, 429), a rejected credential (401), a refusal (403), or anything else.
35
+ * The HTTP status of one error: the one the server put inside it
36
+ * (`extensions.http`, since it answers every GraphQL request with HTTP 200),
37
+ * else the response's own (`extensions.httpStatus`, added by `postGraphQL`),
38
+ * else the one in the SDK FetchAdapter's "HTTP 503: …" message, which drops
39
+ * the body.
32
40
  */
41
+ export declare function statusOf(error: GraphQLError): number | undefined;
42
+ /** Whether a public code says the request's sign-in has ended or is missing (packages/errors registry). */
43
+ export declare const isSignedOutCode: (code: string | undefined) => boolean;
44
+ /** Whether an error says the backend did not accept the request's credential: one of those codes, or a 401. */
45
+ export declare const isSignedOut: (error: GraphQLError) => boolean;
46
+ /** Whether a thrown SDK error carries an answer that says so. */
47
+ export declare const answersSignedOut: (err: unknown) => boolean;
33
48
  export declare function classifyBackendErrors(errors: readonly GraphQLError[]): BackendErrorKind;
34
- /** The messages of a failed answer, joined for a reason string. */
35
- export declare function errorsText(errors: readonly GraphQLError[]): string;
49
+ /**
50
+ * What a failed answer was, in fixed words: each error's public code, HTTP status or error id. The text a server writes
51
+ * is never in them, since a server can pass the database's own text through, with internal table names and error
52
+ * codes. Only a request that got no answer keeps its text, which postGraphQL made from the local fetch failure.
53
+ */
54
+ export declare function answerText(errors: readonly GraphQLError[]): string;
55
+ /** A thrown error in words that hold no server text: an SDK error by its GraphQL errors, any other by its own message. */
56
+ export declare function thrownText(err: unknown): string;