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